lang
stringclasses
2 values
license
stringclasses
13 values
stderr
stringlengths
0
343
commit
stringlengths
40
40
returncode
int64
0
128
repos
stringlengths
6
87.7k
new_contents
stringlengths
0
6.23M
new_file
stringlengths
3
311
old_contents
stringlengths
0
6.23M
message
stringlengths
6
9.1k
old_file
stringlengths
3
311
subject
stringlengths
0
4k
git_diff
stringlengths
0
6.31M
Java
agpl-3.0
158b0f23fc85e69dc0be2bff62780cd70c87ffed
0
duaneking/rockstar_test,duaneking/rockstar_test,duaneking/rockstar_test,duaneking/rockstar_test,duaneking/rockstar_test,duaneking/rockstar_test,duaneking/rockstar_test,duaneking/rockstar_test,duaneking/rockstar_test,duaneking/rockstar_test
d8cc4b5c-2e61-11e5-9284-b827eb9e62be
hello.java
d8c6e946-2e61-11e5-9284-b827eb9e62be
d8cc4b5c-2e61-11e5-9284-b827eb9e62be
hello.java
d8cc4b5c-2e61-11e5-9284-b827eb9e62be
<ide><path>ello.java <del>d8c6e946-2e61-11e5-9284-b827eb9e62be <add>d8cc4b5c-2e61-11e5-9284-b827eb9e62be
Java
apache-2.0
4e037e61e7ec3d1fff33455f64bb2da07b5cddda
0
udayinfy/vaadin,oalles/vaadin,bmitc/vaadin,shahrzadmn/vaadin,cbmeeks/vaadin,udayinfy/vaadin,Flamenco/vaadin,asashour/framework,kironapublic/vaadin,synes/vaadin,magi42/vaadin,magi42/vaadin,peterl1084/framework,Darsstar/framework,sitexa/vaadin,bmitc/vaadin,asashour/framework,mstahv/framework,Legioth/vaadin,shahrzadmn/vaadin,mittop/vaadin,udayinfy/vaadin,Darsstar/framework,kironapublic/vaadin,Darsstar/framework,kironapublic/vaadin,Scarlethue/vaadin,jdahlstrom/vaadin.react,oalles/vaadin,mittop/vaadin,asashour/framework,mittop/vaadin,Peppe/vaadin,mittop/vaadin,udayinfy/vaadin,peterl1084/framework,Peppe/vaadin,bmitc/vaadin,mstahv/framework,Peppe/vaadin,synes/vaadin,Legioth/vaadin,cbmeeks/vaadin,fireflyc/vaadin,sitexa/vaadin,travisfw/vaadin,carrchang/vaadin,Legioth/vaadin,bmitc/vaadin,Flamenco/vaadin,carrchang/vaadin,magi42/vaadin,Legioth/vaadin,peterl1084/framework,jdahlstrom/vaadin.react,magi42/vaadin,Scarlethue/vaadin,travisfw/vaadin,shahrzadmn/vaadin,oalles/vaadin,cbmeeks/vaadin,fireflyc/vaadin,Flamenco/vaadin,oalles/vaadin,shahrzadmn/vaadin,jdahlstrom/vaadin.react,cbmeeks/vaadin,peterl1084/framework,kironapublic/vaadin,Peppe/vaadin,udayinfy/vaadin,travisfw/vaadin,jdahlstrom/vaadin.react,Scarlethue/vaadin,mstahv/framework,fireflyc/vaadin,jdahlstrom/vaadin.react,fireflyc/vaadin,mstahv/framework,magi42/vaadin,Darsstar/framework,mstahv/framework,peterl1084/framework,oalles/vaadin,Scarlethue/vaadin,shahrzadmn/vaadin,synes/vaadin,asashour/framework,asashour/framework,fireflyc/vaadin,Peppe/vaadin,carrchang/vaadin,travisfw/vaadin,Flamenco/vaadin,Scarlethue/vaadin,carrchang/vaadin,sitexa/vaadin,synes/vaadin,synes/vaadin,sitexa/vaadin,sitexa/vaadin,Darsstar/framework,Legioth/vaadin,kironapublic/vaadin,travisfw/vaadin
package com.vaadin.tests.components.checkbox; import java.util.Date; import com.vaadin.terminal.Resource; import com.vaadin.terminal.ThemeResource; import com.vaadin.tests.components.ComponentTestCase; import com.vaadin.ui.CheckBox; public class CheckBoxes extends ComponentTestCase<CheckBox> { private ThemeResource SMALL_ICON = new ThemeResource( "../runo/icons/16/ok.png"); private ThemeResource LARGE_ICON = new ThemeResource( "../runo/icons/64/document.png"); private ThemeResource LARGE_ICON_NOCACHE = new ThemeResource( "../runo/icons/64/document.png?" + new Date().getTime()); @Override protected Class<CheckBox> getTestClass() { return CheckBox.class; } @Override protected void initializeComponents() { setTheme("tests-tickets"); CheckBox cb; cb = createCheckBox("CheckBox with normal text"); addTestComponent(cb); cb = createCheckBox("CheckBox with large text"); cb.setStyleName("large"); addTestComponent(cb); cb = createCheckBox("CheckBox with normal text and small icon", SMALL_ICON); addTestComponent(cb); cb = createCheckBox("CheckBox with large text and small icon", SMALL_ICON); cb.setStyleName("large"); addTestComponent(cb); cb = createCheckBox("CheckBox with normal text and large icon", LARGE_ICON); addTestComponent(cb); cb = createCheckBox("CheckBox with large text and large icon", LARGE_ICON_NOCACHE); cb.setStyleName("large"); addTestComponent(cb); } private CheckBox createCheckBox(String caption, Resource icon) { CheckBox cb = createCheckBox(caption); cb.setIcon(icon); return cb; } private CheckBox createCheckBox(String caption) { return new CheckBox(caption); } @Override protected String getDescription() { return "A generic test for CheckBoxes in different configurations"; } @Override protected Integer getTicketNumber() { return null; } }
tests/src/com/vaadin/tests/components/checkbox/CheckBoxes.java
package com.vaadin.tests.components.checkbox; import com.vaadin.terminal.Resource; import com.vaadin.terminal.ThemeResource; import com.vaadin.tests.components.ComponentTestCase; import com.vaadin.ui.CheckBox; public class CheckBoxes extends ComponentTestCase<CheckBox> { private ThemeResource SMALL_ICON = new ThemeResource( "../runo/icons/16/ok.png"); private ThemeResource LARGE_ICON = new ThemeResource( "../runo/icons/64/document.png"); @Override protected Class<CheckBox> getTestClass() { return CheckBox.class; } @Override protected void initializeComponents() { setTheme("tests-tickets"); CheckBox cb; cb = createCheckBox("CheckBox with normal text"); addTestComponent(cb); cb = createCheckBox("CheckBox with large text"); cb.setStyleName("large"); addTestComponent(cb); cb = createCheckBox("CheckBox with normal text and small icon", SMALL_ICON); addTestComponent(cb); cb = createCheckBox("CheckBox with large text and small icon", SMALL_ICON); cb.setStyleName("large"); addTestComponent(cb); cb = createCheckBox("CheckBox with normal text and large icon", LARGE_ICON); addTestComponent(cb); cb = createCheckBox("CheckBox with large text and large icon", LARGE_ICON); cb.setStyleName("large"); addTestComponent(cb); } private CheckBox createCheckBox(String caption, Resource icon) { CheckBox cb = createCheckBox(caption); cb.setIcon(icon); return cb; } private CheckBox createCheckBox(String caption) { return new CheckBox(caption); } @Override protected String getDescription() { return "A generic test for CheckBoxes in different configurations"; } @Override protected Integer getTicketNumber() { return null; } }
Do not cache the second image ensure onload is working properly svn changeset:16236/svn branch:6.5
tests/src/com/vaadin/tests/components/checkbox/CheckBoxes.java
Do not cache the second image ensure onload is working properly
<ide><path>ests/src/com/vaadin/tests/components/checkbox/CheckBoxes.java <ide> package com.vaadin.tests.components.checkbox; <add> <add>import java.util.Date; <ide> <ide> import com.vaadin.terminal.Resource; <ide> import com.vaadin.terminal.ThemeResource; <ide> "../runo/icons/16/ok.png"); <ide> private ThemeResource LARGE_ICON = new ThemeResource( <ide> "../runo/icons/64/document.png"); <add> private ThemeResource LARGE_ICON_NOCACHE = new ThemeResource( <add> "../runo/icons/64/document.png?" + new Date().getTime()); <ide> <ide> @Override <ide> protected Class<CheckBox> getTestClass() { <ide> LARGE_ICON); <ide> addTestComponent(cb); <ide> cb = createCheckBox("CheckBox with large text and large icon", <del> LARGE_ICON); <add> LARGE_ICON_NOCACHE); <ide> cb.setStyleName("large"); <ide> addTestComponent(cb); <ide>
JavaScript
mit
c4b6d0afe99f7a6ae347a5ea9cc98d7e92cafaf5
0
algonauti/ember-g-recaptcha,algonauti/ember-g-recaptcha
/* jshint node: true */ 'use strict'; module.exports = { name: 'ember-g-recaptcha', contentFor: function(type, config) { var content = ''; if (type === 'head') { var src = 'https://www.google.com/recaptcha/api.js?render=explicit'; content = '<script type="text/javascript" src="'+src+'"></script>'; } return content; } };
index.js
/* jshint node: true */ 'use strict'; module.exports = { name: 'ember-g-recaptcha', contentFor: function(type, config) { var content = ''; if (type === 'head') { var src = 'https://www.google.com/recaptcha/api.js?render=explicit'; content = `<script type="text/javascript" src="${src}"></script>`; } return content; } };
avoid ES6 strings when using strict mode
index.js
avoid ES6 strings when using strict mode
<ide><path>ndex.js <ide> var content = ''; <ide> if (type === 'head') { <ide> var src = 'https://www.google.com/recaptcha/api.js?render=explicit'; <del> content = `<script type="text/javascript" src="${src}"></script>`; <add> content = '<script type="text/javascript" src="'+src+'"></script>'; <ide> } <ide> return content; <ide> }
Java
mit
error: pathspec 'src/pp/arithmetic/leetcode/_20_isValid.java' did not match any file(s) known to git
0924adee9a8cc0c041d711766aac2afb31f57fa4
1
pphdsny/ArithmeticTest
package pp.arithmetic.leetcode; import java.util.Stack; /** * Created by wangpeng on 2019-04-12. * 20. 有效的括号 * <p> * 给定一个只包括 '(',')','{','}','[',']' 的字符串,判断字符串是否有效。 * <p> * 有效字符串需满足: * <p> * 左括号必须用相同类型的右括号闭合。 * 左括号必须以正确的顺序闭合。 * 注意空字符串可被认为是有效字符串。 * <p> * 示例 1: * <p> * 输入: "()" * 输出: true * 示例 2: * <p> * 输入: "()[]{}" * 输出: true * 示例 3: * <p> * 输入: "(]" * 输出: false * 示例 4: * <p> * 输入: "([)]" * 输出: false * 示例 5: * <p> * 输入: "{[]}" * 输出: true * * @see <a href="https://leetcode-cn.com/problems/valid-parentheses/">valid-parentheses</a> */ public class _20_isValid { public static void main(String[] args) { _20_isValid valid = new _20_isValid(); System.out.println(valid.isValid("()")); System.out.println(valid.isValid("()[]{}")); System.out.println(valid.isValid("(]")); System.out.println(valid.isValid("([)]")); System.out.println(valid.isValid("{[]}")); } /** * 解题思路: * 需要知道是否有效,也就是左右得成对出现,利用栈去做存储 * 1、左括号时,则入栈 * 2、有括号时,则判断栈顶是否是配套左括号,如是则将其出栈,否则无效 * 3、遍历完成后,如栈空则有效,反则无效 * * @param s * @return */ public boolean isValid(String s) { Stack<Character> stack = new Stack<>(); for (int i = 0; i < s.length(); i++) { char c = s.charAt(i); if (c == '(' || c == '{' || c == '[') { stack.push(c); } else { if (stack.isEmpty()){ return false; } Character pop = stack.pop(); switch (c) { case ')': if (pop != '(') { return false; } break; case '}': if (pop != '{') { return false; } break; case ']': if (pop != '[') { return false; } break; } } } return stack.isEmpty(); } }
src/pp/arithmetic/leetcode/_20_isValid.java
feat(EASY): _20_isValid
src/pp/arithmetic/leetcode/_20_isValid.java
feat(EASY): _20_isValid
<ide><path>rc/pp/arithmetic/leetcode/_20_isValid.java <add>package pp.arithmetic.leetcode; <add> <add>import java.util.Stack; <add> <add>/** <add> * Created by wangpeng on 2019-04-12. <add> * 20. 有效的括号 <add> * <p> <add> * 给定一个只包括 '(',')','{','}','[',']' 的字符串,判断字符串是否有效。 <add> * <p> <add> * 有效字符串需满足: <add> * <p> <add> * 左括号必须用相同类型的右括号闭合。 <add> * 左括号必须以正确的顺序闭合。 <add> * 注意空字符串可被认为是有效字符串。 <add> * <p> <add> * 示例 1: <add> * <p> <add> * 输入: "()" <add> * 输出: true <add> * 示例 2: <add> * <p> <add> * 输入: "()[]{}" <add> * 输出: true <add> * 示例 3: <add> * <p> <add> * 输入: "(]" <add> * 输出: false <add> * 示例 4: <add> * <p> <add> * 输入: "([)]" <add> * 输出: false <add> * 示例 5: <add> * <p> <add> * 输入: "{[]}" <add> * 输出: true <add> * <add> * @see <a href="https://leetcode-cn.com/problems/valid-parentheses/">valid-parentheses</a> <add> */ <add>public class _20_isValid { <add> public static void main(String[] args) { <add> _20_isValid valid = new _20_isValid(); <add> System.out.println(valid.isValid("()")); <add> System.out.println(valid.isValid("()[]{}")); <add> System.out.println(valid.isValid("(]")); <add> System.out.println(valid.isValid("([)]")); <add> System.out.println(valid.isValid("{[]}")); <add> } <add> <add> /** <add> * 解题思路: <add> * 需要知道是否有效,也就是左右得成对出现,利用栈去做存储 <add> * 1、左括号时,则入栈 <add> * 2、有括号时,则判断栈顶是否是配套左括号,如是则将其出栈,否则无效 <add> * 3、遍历完成后,如栈空则有效,反则无效 <add> * <add> * @param s <add> * @return <add> */ <add> public boolean isValid(String s) { <add> Stack<Character> stack = new Stack<>(); <add> for (int i = 0; i < s.length(); i++) { <add> char c = s.charAt(i); <add> if (c == '(' || c == '{' || c == '[') { <add> stack.push(c); <add> } else { <add> if (stack.isEmpty()){ <add> return false; <add> } <add> Character pop = stack.pop(); <add> switch (c) { <add> case ')': <add> if (pop != '(') { <add> return false; <add> } <add> break; <add> case '}': <add> if (pop != '{') { <add> return false; <add> } <add> break; <add> case ']': <add> if (pop != '[') { <add> return false; <add> } <add> break; <add> } <add> } <add> } <add> <add> return stack.isEmpty(); <add> } <add>}
Java
apache-2.0
972e065a4a352511e5a6f5fd0ccbecf4f2445b4d
0
fritaly/dual-commander
/* * 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. */ package com.github.fritaly.dualcommander; import java.awt.Color; import java.awt.Component; import java.awt.Font; import java.awt.event.FocusEvent; import java.awt.event.FocusListener; import java.awt.event.KeyEvent; import java.awt.event.KeyListener; import java.awt.event.MouseEvent; import java.awt.event.MouseListener; import java.io.File; import java.io.IOException; import java.text.DecimalFormat; import java.text.DecimalFormatSymbols; import java.text.SimpleDateFormat; import java.util.Date; import java.util.List; import java.util.Locale; import javax.swing.BorderFactory; import javax.swing.DefaultListCellRenderer; import javax.swing.JButton; import javax.swing.JLabel; import javax.swing.JList; import javax.swing.JPanel; import javax.swing.JScrollPane; import javax.swing.JTable; import javax.swing.ListSelectionModel; import javax.swing.SwingConstants; import javax.swing.border.BevelBorder; import javax.swing.event.ChangeEvent; import javax.swing.event.ChangeListener; import javax.swing.event.ListSelectionEvent; import javax.swing.event.ListSelectionListener; import javax.swing.table.DefaultTableCellRenderer; import javax.swing.table.TableCellRenderer; import javax.swing.table.TableColumn; import net.miginfocom.swing.MigLayout; import org.apache.commons.lang.Validate; import org.apache.log4j.Logger; import com.github.fritaly.dualcommander.event.ChangeEventSource; import com.github.fritaly.dualcommander.event.ChangeEventSupport; import com.github.fritaly.dualcommander.event.ColumnEvent; import com.github.fritaly.dualcommander.event.ColumnEventHelper; import com.github.fritaly.dualcommander.event.ColumnEventListener; public class DirectoryBrowser extends JPanel implements ListSelectionListener, ChangeEventSource, KeyListener, MouseListener, HasParentDirectory, FocusListener, ColumnEventListener { private static final Color EVEN_ROW = Color.WHITE; private static final Color ODD_ROW = Color.decode("#DDDDFF"); private final class FileTableCellRenderer extends DefaultTableCellRenderer { private static final long serialVersionUID = -896199602148007012L; @Override public Component getTableCellRendererComponent(JTable table, Object value, boolean isSelected, boolean hasFocus, int row, int column) { final JLabel component = (JLabel) super.getTableCellRendererComponent(table, value, isSelected, hasFocus, row, column); final File file = (File) value; if (file.isDirectory()) { // Render the directories with a bold font final Font font = component.getFont(); component.setFont(new Font(font.getName(), Font.BOLD, component.getFont().getSize())); if (file.equals(getParentDirectory())) { // Render the parent directory entry as ".." component.setText("[..]"); } else { component.setText(String.format("[%s]", file.getName())); } } else { component.setText(file.getName()); } if (isSelected) { setBackground((row % 2 == 0) ? Color.decode("#FFC57A") : Color.decode("#F5AC4C")); } else { setBackground((row % 2 == 0) ? EVEN_ROW : ODD_ROW); } setForeground(file.isDirectory() ? Color.BLACK : Color.decode("#555555")); setBorder(BorderFactory.createEmptyBorder(2, 2, 2, 2)); return component; } } private final class FileSizeTableCellRenderer extends DefaultTableCellRenderer { private static final long serialVersionUID = -5094024636812268688L; private final DecimalFormat decimalFormat; public FileSizeTableCellRenderer() { final DecimalFormatSymbols symbols = new DecimalFormatSymbols(Locale.US); symbols.setGroupingSeparator(' '); this.decimalFormat = new DecimalFormat(); this.decimalFormat.setDecimalFormatSymbols(symbols); } @Override public Component getTableCellRendererComponent(JTable table, Object value, boolean isSelected, boolean hasFocus, int row, int column) { final JLabel component = (JLabel) super.getTableCellRendererComponent(table, value, isSelected, hasFocus, row, column); final File file = (File) value; if (file.isFile()) { // Render the file sizes with ' ' as grouping separator component.setText(decimalFormat.format(file.length())); component.setHorizontalAlignment(JLabel.RIGHT); } else { component.setText(""); } if (isSelected) { setBackground((row % 2 == 0) ? Color.decode("#FFC57A") : Color.decode("#F5AC4C")); } else { setBackground((row % 2 == 0) ? EVEN_ROW : ODD_ROW); } setForeground(Color.decode("#555555")); setBorder(BorderFactory.createEmptyBorder(2, 2, 2, 2)); return component; } } private final class LastUpdateTableCellRenderer extends DefaultTableCellRenderer { private static final long serialVersionUID = -1888924791239159846L; @Override public Component getTableCellRendererComponent(JTable table, Object value, boolean isSelected, boolean hasFocus, int row, int column) { final JLabel component = (JLabel) super.getTableCellRendererComponent(table, value, isSelected, hasFocus, row, column); final Long lastUpdate = (Long) value; component.setText(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date(lastUpdate))); if (isSelected) { setBackground((row % 2 == 0) ? Color.decode("#FFC57A") : Color.decode("#F5AC4C")); } else { setBackground((row % 2 == 0) ? EVEN_ROW : ODD_ROW); } setForeground(Color.decode("#555555")); setBorder(BorderFactory.createEmptyBorder(2, 2, 2, 2)); return component; } } private final class FileListCellRenderer extends DefaultListCellRenderer { private static final long serialVersionUID = -8630518399718717693L; @Override public Component getListCellRendererComponent(JList<?> list, Object value, int index, boolean isSelected, boolean cellHasFocus) { final JLabel component = (JLabel) super.getListCellRendererComponent(list, value, index, isSelected, cellHasFocus); final File file = (File) value; if (file.isDirectory()) { // Render the directories with a bold font final Font font = component.getFont(); component.setFont(new Font(font.getName(), Font.BOLD, component.getFont().getSize())); if (file.equals(getParentDirectory())) { // Render the parent directory entry as ".." component.setText("[..]"); } else { component.setText(String.format("[%s]", file.getName())); } } else { component.setText(file.getName()); } if (isSelected) { setBackground((index % 2 == 0) ? Color.decode("#FFC57A") : Color.decode("#F5AC4C")); } else { setBackground((index % 2 == 0) ? EVEN_ROW : ODD_ROW); } setForeground(file.isDirectory() ? Color.BLACK : Color.decode("#555555")); setBorder(BorderFactory.createEmptyBorder(2, 2, 2, 2)); return component; } } private static class TableHeaderRenderer extends JLabel implements TableCellRenderer { private static final long serialVersionUID = 596061491019164527L; @Override public Component getTableCellRendererComponent(JTable table, Object value, boolean isSelected, boolean hasFocus, int row, int column) { setText(value.toString()); setBorder(BorderFactory.createBevelBorder(BevelBorder.RAISED)); return this; } } private static String getCanonicalPath(File file) { try { return file.getCanonicalPath(); } catch (IOException e) { throw new RuntimeException(e); } } private static File getCanonicalFile(File file) { try { return file.getCanonicalFile(); } catch (IOException e) { throw new RuntimeException(e); } } private static final long serialVersionUID = 411590029543053088L; private final Logger logger = Logger.getLogger(this.getClass()); private File directory; private final FileTableModel tableModel; private final JTable table; private final JButton directoryButton = new JButton(Icons.FOLDER_ICON); private final ChangeEventSupport eventSupport = new ChangeEventSupport(); private final UserPreferences preferences; public DirectoryBrowser(UserPreferences preferences, File directory) { Validate.notNull(preferences, "The given user preferences are null"); Validate.notNull(directory, "The given directory is null"); Validate.isTrue(directory.exists(), String.format("The given directory '%s' doesn't exist", directory.getAbsolutePath())); Validate.isTrue(directory.isDirectory(), String.format("The given path '%s' doesn't denote a directory", directory.getAbsolutePath())); this.preferences = preferences; // Layout, columns & rows setLayout(new MigLayout("insets 0px", "[grow]", "[][grow]")); this.tableModel = new FileTableModel(this); this.table = new JTable(tableModel); this.table.setBackground(Utils.getDefaultBackgroundColor()); this.table.addKeyListener(this); this.table.addMouseListener(this); this.table.addFocusListener(this); this.table.setSelectionMode(ListSelectionModel.MULTIPLE_INTERVAL_SELECTION); this.table.getSelectionModel().addListSelectionListener(this); // Listen to column event resize events final ColumnEventHelper eventHelper = new ColumnEventHelper(this); this.table.getColumnModel().addColumnModelListener(eventHelper); this.table.getTableHeader().addMouseListener(eventHelper); // Render the table headers with a bold font this.table.getTableHeader().setFont(Utils.getBoldFont(this.table.getTableHeader().getFont())); this.table.getTableHeader().setBackground(Color.decode("#CCCCCC")); this.table.getTableHeader().setDefaultRenderer(new TableHeaderRenderer()); this.table.getTableHeader().addMouseListener(this); final TableColumn fileColumn = this.table.getColumn(FileTableModel.COLUMN_NAME); fileColumn.setCellRenderer(new FileTableCellRenderer()); fileColumn.setResizable(true); final TableColumn sizeColumn = this.table.getColumn(FileTableModel.COLUMN_SIZE); sizeColumn.setCellRenderer(new FileSizeTableCellRenderer()); sizeColumn.setResizable(true); final TableColumn lastUpdateColumn = this.table.getColumn(FileTableModel.COLUMN_LAST_UPDATE); lastUpdateColumn.setCellRenderer(new LastUpdateTableCellRenderer()); lastUpdateColumn.setResizable(true); this.directoryButton.setFocusable(false); this.directoryButton.setHorizontalAlignment(SwingConstants.LEFT); add(directoryButton, "grow, span"); add(new JScrollPane(table), "grow"); // Set the directory (this will populate the table) setDirectory(directory); } public File getDirectory() { return getCanonicalFile(directory); } @Override public File getParentDirectory() { final File parentDir = getCanonicalFile(directory).getParentFile(); return (parentDir != null) && parentDir.exists() ? parentDir : null; } public void refresh() { setDirectory(getDirectory()); } public void setDirectory(File directory) { Validate.notNull(directory, "The given directory is null"); Validate.isTrue(directory.exists(), String.format("The given directory '%s' doesn't exist", directory.getAbsolutePath())); Validate.isTrue(directory.isDirectory(), String.format("The given path '%s' doesn't denote a directory", directory.getAbsolutePath())); final File oldDir = this.directory; this.directory = directory; // Refresh the UI // Display the (normalized) canonical path directoryButton.setText(getCanonicalPath(directory)); this.tableModel.clear(); // Populate the list with the directory's entries for (File file : directory.listFiles()) { if (!file.isHidden() || preferences.isShowHidden()) { tableModel.add(file); } } // If there's a parent directory, add an entry rendered as ".." final File parentDir = getCanonicalFile(directory).getParentFile(); if ((parentDir != null) && parentDir.exists()) { tableModel.add(parentDir); } // Sort the entries tableModel.sort(); // Notify the listeners that all the entries changed tableModel.fireTableDataChanged(); if ((oldDir != null) && tableModel.contains(oldDir)) { // Auto-select the directory we just left final int index = tableModel.indexOf(oldDir); table.getSelectionModel().setSelectionInterval(index, index); } else { // Auto-select the 1st entry (if there's one) if (tableModel.size() > 1) { table.getSelectionModel().setSelectionInterval(1, 1); } } if (logger.isDebugEnabled()) { logger.debug(String.format("[%s] Set directory to %s", getComponentLabel(), directory.getAbsolutePath())); } // Fire an event to ensure listeners are notified of the directory // change fireChangeEvent(); } @Override public void addChangeListener(ChangeListener listener) { this.eventSupport.addChangeListener(listener); } @Override public void removeChangeListener(ChangeListener listener) { this.eventSupport.removeChangeListener(listener); } private void fireChangeEvent() { this.eventSupport.fireEvent(new ChangeEvent(this)); } @Override public void valueChanged(ListSelectionEvent e) { if (e.getSource() == table.getSelectionModel()) { // The parent directory can't be selected final File parentDir = getParentDirectory(); if (parentDir != null) { if (getSelection().contains(parentDir)) { // Unselect the parent directory entry (always the 1st one) table.getSelectionModel().removeSelectionInterval(0, 0); } } if (logger.isDebugEnabled()) { logger.debug(String.format("[%s] Selection changed", getComponentLabel())); } // Propagate the event fireChangeEvent(); } } public List<File> getSelection() { return tableModel.getFilesAt(table.getSelectedRows()); } private String getComponentLabel() { return (getName() == null) ? "N/A" : getName(); } @Override public void keyPressed(KeyEvent e) { if (e.getSource() != table) { return; } if (e.getKeyCode() == KeyEvent.VK_ENTER) { // What's the current selection ? final List<File> selection = getSelection(); if (selection.size() == 1) { final File selectedFile = selection.iterator().next(); if (selectedFile.isDirectory()) { // Change to the selected directory setDirectory(selectedFile); } } } else if (e.getKeyCode() == KeyEvent.VK_BACK_SPACE) { // Return to the parent directory (if any) final File parentDir = getParentDirectory(); if ((parentDir != null) && parentDir.exists()) { setDirectory(parentDir); } } else { // Propagate event to our listeners processKeyEvent(new KeyEvent(this, e.getID(), e.getWhen(), e.getModifiers(), e.getKeyCode(), e.getKeyChar(), e.getKeyLocation())); } } @Override public void keyReleased(KeyEvent e) { if (e.getSource() != table) { return; } // Propagate event to our listeners processKeyEvent(new KeyEvent(this, e.getID(), e.getWhen(), e.getModifiers(), e.getKeyCode(), e.getKeyChar(), e.getKeyLocation())); } @Override public void keyTyped(KeyEvent e) { if (e.getSource() != table) { return; } // Propagate event to our listeners processKeyEvent(new KeyEvent(this, e.getID(), e.getWhen(), e.getModifiers(), e.getKeyCode(), e.getKeyChar(), e.getKeyLocation())); } @Override public void mouseClicked(MouseEvent e) { if (e.getSource() == table) { if (e.getClickCount() == 2) { // Only react to double clicks final List<File> selection = getSelection(); if (selection.size() == 1) { final File file = selection.iterator().next(); if (file.isDirectory()) { // Change to the clicked directory setDirectory(file); } } } } else if (e.getSource() == table.getTableHeader()) { final int columnIndex = table.convertColumnIndexToModel(table.columnAtPoint(e.getPoint())); if (columnIndex >= 0) { // TODO React to clicks on column headers System.err.println("Clicked on column header " + columnIndex); } } } @Override public void mouseEntered(MouseEvent e) { } @Override public void mouseExited(MouseEvent e) { } @Override public void mousePressed(MouseEvent e) { } @Override public void mouseReleased(MouseEvent e) { } @Override public void focusGained(FocusEvent e) { if (e.getSource() == table) { // Propagate the event final FocusListener[] listeners = getListeners(FocusListener.class); if (listeners != null) { final FocusEvent event = new FocusEvent(this, e.getID(), e.isTemporary(), e.getOppositeComponent()); for (FocusListener listener : listeners) { listener.focusGained(event); } } } } @Override public void focusLost(FocusEvent e) { if (e.getSource() == table) { // Propagate the event final FocusListener[] listeners = getListeners(FocusListener.class); if (listeners != null) { final FocusEvent event = new FocusEvent(this, e.getID(), e.isTemporary(), e.getOppositeComponent()); for (FocusListener listener : listeners) { listener.focusLost(event); } } } } @Override public void columnResized(ColumnEvent event) { System.err.println(event); } }
src/main/java/com/github/fritaly/dualcommander/DirectoryBrowser.java
/* * 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. */ package com.github.fritaly.dualcommander; import java.awt.Color; import java.awt.Component; import java.awt.Font; import java.awt.event.FocusEvent; import java.awt.event.FocusListener; import java.awt.event.KeyEvent; import java.awt.event.KeyListener; import java.awt.event.MouseEvent; import java.awt.event.MouseListener; import java.io.File; import java.io.IOException; import java.text.DecimalFormat; import java.text.DecimalFormatSymbols; import java.text.SimpleDateFormat; import java.util.Date; import java.util.List; import java.util.Locale; import javax.swing.BorderFactory; import javax.swing.DefaultListCellRenderer; import javax.swing.JButton; import javax.swing.JLabel; import javax.swing.JList; import javax.swing.JPanel; import javax.swing.JScrollPane; import javax.swing.JTable; import javax.swing.ListSelectionModel; import javax.swing.SwingConstants; import javax.swing.border.BevelBorder; import javax.swing.event.ChangeEvent; import javax.swing.event.ChangeListener; import javax.swing.event.ListSelectionEvent; import javax.swing.event.ListSelectionListener; import javax.swing.table.DefaultTableCellRenderer; import javax.swing.table.TableCellRenderer; import javax.swing.table.TableColumn; import net.miginfocom.swing.MigLayout; import org.apache.commons.lang.Validate; import org.apache.log4j.Logger; import com.github.fritaly.dualcommander.event.ChangeEventSource; import com.github.fritaly.dualcommander.event.ChangeEventSupport; import com.github.fritaly.dualcommander.event.ColumnEvent; import com.github.fritaly.dualcommander.event.ColumnEventHelper; import com.github.fritaly.dualcommander.event.ColumnEventListener; public class DirectoryBrowser extends JPanel implements ListSelectionListener, ChangeEventSource, KeyListener, MouseListener, HasParentDirectory, FocusListener, ColumnEventListener { private static final Color EVEN_ROW = Color.WHITE; private static final Color ODD_ROW = Color.decode("#DDDDFF"); private final class FileTableCellRenderer extends DefaultTableCellRenderer { private static final long serialVersionUID = -896199602148007012L; @Override public Component getTableCellRendererComponent(JTable table, Object value, boolean isSelected, boolean hasFocus, int row, int column) { final JLabel component = (JLabel) super.getTableCellRendererComponent(table, value, isSelected, hasFocus, row, column); final File file = (File) value; if (file.isDirectory()) { // Render the directories with a bold font final Font font = component.getFont(); component.setFont(new Font(font.getName(), Font.BOLD, component.getFont().getSize())); if (file.equals(getParentDirectory())) { // Render the parent directory entry as ".." component.setText("[..]"); } else { component.setText(String.format("[%s]", file.getName())); } } else { component.setText(file.getName()); } if (isSelected) { setBackground((row % 2 == 0) ? Color.decode("#FFC57A") : Color.decode("#F5AC4C")); } else { setBackground((row % 2 == 0) ? EVEN_ROW : ODD_ROW); } setForeground(file.isDirectory() ? Color.BLACK : Color.decode("#555555")); setBorder(BorderFactory.createEmptyBorder(2, 2, 2, 2)); return component; } } private final class FileSizeTableCellRenderer extends DefaultTableCellRenderer { private static final long serialVersionUID = -5094024636812268688L; private final DecimalFormat decimalFormat; public FileSizeTableCellRenderer() { final DecimalFormatSymbols symbols = new DecimalFormatSymbols(Locale.US); symbols.setGroupingSeparator(' '); this.decimalFormat = new DecimalFormat(); this.decimalFormat.setDecimalFormatSymbols(symbols); } @Override public Component getTableCellRendererComponent(JTable table, Object value, boolean isSelected, boolean hasFocus, int row, int column) { final JLabel component = (JLabel) super.getTableCellRendererComponent(table, value, isSelected, hasFocus, row, column); final File file = (File) value; if (file.isFile()) { // Render the file sizes with ' ' as grouping separator component.setText(decimalFormat.format(file.length())); component.setHorizontalAlignment(JLabel.RIGHT); } else { component.setText(""); } if (isSelected) { setBackground((row % 2 == 0) ? Color.decode("#FFC57A") : Color.decode("#F5AC4C")); } else { setBackground((row % 2 == 0) ? EVEN_ROW : ODD_ROW); } setForeground(Color.decode("#555555")); setBorder(BorderFactory.createEmptyBorder(2, 2, 2, 2)); return component; } } private final class LastUpdateTableCellRenderer extends DefaultTableCellRenderer { private static final long serialVersionUID = -1888924791239159846L; @Override public Component getTableCellRendererComponent(JTable table, Object value, boolean isSelected, boolean hasFocus, int row, int column) { final JLabel component = (JLabel) super.getTableCellRendererComponent(table, value, isSelected, hasFocus, row, column); final Long lastUpdate = (Long) value; component.setText(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date(lastUpdate))); if (isSelected) { setBackground((row % 2 == 0) ? Color.decode("#FFC57A") : Color.decode("#F5AC4C")); } else { setBackground((row % 2 == 0) ? EVEN_ROW : ODD_ROW); } setForeground(Color.decode("#555555")); setBorder(BorderFactory.createEmptyBorder(2, 2, 2, 2)); return component; } } private final class FileListCellRenderer extends DefaultListCellRenderer { private static final long serialVersionUID = -8630518399718717693L; @Override public Component getListCellRendererComponent(JList<?> list, Object value, int index, boolean isSelected, boolean cellHasFocus) { final JLabel component = (JLabel) super.getListCellRendererComponent(list, value, index, isSelected, cellHasFocus); final File file = (File) value; if (file.isDirectory()) { // Render the directories with a bold font final Font font = component.getFont(); component.setFont(new Font(font.getName(), Font.BOLD, component.getFont().getSize())); if (file.equals(getParentDirectory())) { // Render the parent directory entry as ".." component.setText("[..]"); } else { component.setText(String.format("[%s]", file.getName())); } } else { component.setText(file.getName()); } if (isSelected) { setBackground((index % 2 == 0) ? Color.decode("#FFC57A") : Color.decode("#F5AC4C")); } else { setBackground((index % 2 == 0) ? EVEN_ROW : ODD_ROW); } setForeground(file.isDirectory() ? Color.BLACK : Color.decode("#555555")); setBorder(BorderFactory.createEmptyBorder(2, 2, 2, 2)); return component; } } private static class TableHeaderRenderer extends JLabel implements TableCellRenderer { private static final long serialVersionUID = 596061491019164527L; @Override public Component getTableCellRendererComponent(JTable table, Object value, boolean isSelected, boolean hasFocus, int row, int column) { setText(value.toString()); setBorder(BorderFactory.createBevelBorder(BevelBorder.RAISED)); return this; } } private static String getCanonicalPath(File file) { try { return file.getCanonicalPath(); } catch (IOException e) { throw new RuntimeException(e); } } private static File getCanonicalFile(File file) { try { return file.getCanonicalFile(); } catch (IOException e) { throw new RuntimeException(e); } } private static final long serialVersionUID = 411590029543053088L; private final Logger logger = Logger.getLogger(this.getClass()); private File directory; private final FileTableModel tableModel; private final JTable table; private final JButton directoryButton = new JButton(Icons.FOLDER_ICON); private final ChangeEventSupport eventSupport = new ChangeEventSupport(); private final UserPreferences preferences; public DirectoryBrowser(UserPreferences preferences, File directory) { Validate.notNull(preferences, "The given user preferences are null"); Validate.notNull(directory, "The given directory is null"); Validate.isTrue(directory.exists(), String.format("The given directory '%s' doesn't exist", directory.getAbsolutePath())); Validate.isTrue(directory.isDirectory(), String.format("The given path '%s' doesn't denote a directory", directory.getAbsolutePath())); this.preferences = preferences; // Layout, columns & rows setLayout(new MigLayout("insets 0px", "[grow]", "[][grow]")); this.tableModel = new FileTableModel(this); this.table = new JTable(tableModel); this.table.setBackground(Utils.getDefaultBackgroundColor()); this.table.addKeyListener(this); this.table.addMouseListener(this); this.table.addFocusListener(this); this.table.setSelectionMode(ListSelectionModel.MULTIPLE_INTERVAL_SELECTION); this.table.getSelectionModel().addListSelectionListener(this); // Listen to column event resize events final ColumnEventHelper eventHelper = new ColumnEventHelper(this); this.table.getColumnModel().addColumnModelListener(eventHelper); this.table.getTableHeader().addMouseListener(eventHelper); // Render the table headers with a bold font this.table.getTableHeader().setFont(Utils.getBoldFont(this.table.getTableHeader().getFont())); this.table.getTableHeader().setBackground(Color.decode("#CCCCCC")); this.table.getTableHeader().setDefaultRenderer(new TableHeaderRenderer()); final TableColumn fileColumn = this.table.getColumn(FileTableModel.COLUMN_NAME); fileColumn.setCellRenderer(new FileTableCellRenderer()); fileColumn.setResizable(true); final TableColumn sizeColumn = this.table.getColumn(FileTableModel.COLUMN_SIZE); sizeColumn.setCellRenderer(new FileSizeTableCellRenderer()); sizeColumn.setResizable(true); final TableColumn lastUpdateColumn = this.table.getColumn(FileTableModel.COLUMN_LAST_UPDATE); lastUpdateColumn.setCellRenderer(new LastUpdateTableCellRenderer()); lastUpdateColumn.setResizable(true); this.directoryButton.setFocusable(false); this.directoryButton.setHorizontalAlignment(SwingConstants.LEFT); add(directoryButton, "grow, span"); add(new JScrollPane(table), "grow"); // Set the directory (this will populate the table) setDirectory(directory); } public File getDirectory() { return getCanonicalFile(directory); } @Override public File getParentDirectory() { final File parentDir = getCanonicalFile(directory).getParentFile(); return (parentDir != null) && parentDir.exists() ? parentDir : null; } public void refresh() { setDirectory(getDirectory()); } public void setDirectory(File directory) { Validate.notNull(directory, "The given directory is null"); Validate.isTrue(directory.exists(), String.format("The given directory '%s' doesn't exist", directory.getAbsolutePath())); Validate.isTrue(directory.isDirectory(), String.format("The given path '%s' doesn't denote a directory", directory.getAbsolutePath())); final File oldDir = this.directory; this.directory = directory; // Refresh the UI // Display the (normalized) canonical path directoryButton.setText(getCanonicalPath(directory)); this.tableModel.clear(); // Populate the list with the directory's entries for (File file : directory.listFiles()) { if (!file.isHidden() || preferences.isShowHidden()) { tableModel.add(file); } } // If there's a parent directory, add an entry rendered as ".." final File parentDir = getCanonicalFile(directory).getParentFile(); if ((parentDir != null) && parentDir.exists()) { tableModel.add(parentDir); } // Sort the entries tableModel.sort(); // Notify the listeners that all the entries changed tableModel.fireTableDataChanged(); if ((oldDir != null) && tableModel.contains(oldDir)) { // Auto-select the directory we just left final int index = tableModel.indexOf(oldDir); table.getSelectionModel().setSelectionInterval(index, index); } else { // Auto-select the 1st entry (if there's one) if (tableModel.size() > 1) { table.getSelectionModel().setSelectionInterval(1, 1); } } if (logger.isDebugEnabled()) { logger.debug(String.format("[%s] Set directory to %s", getComponentLabel(), directory.getAbsolutePath())); } // Fire an event to ensure listeners are notified of the directory // change fireChangeEvent(); } @Override public void addChangeListener(ChangeListener listener) { this.eventSupport.addChangeListener(listener); } @Override public void removeChangeListener(ChangeListener listener) { this.eventSupport.removeChangeListener(listener); } private void fireChangeEvent() { this.eventSupport.fireEvent(new ChangeEvent(this)); } @Override public void valueChanged(ListSelectionEvent e) { if (e.getSource() == table.getSelectionModel()) { // The parent directory can't be selected final File parentDir = getParentDirectory(); if (parentDir != null) { if (getSelection().contains(parentDir)) { // Unselect the parent directory entry (always the 1st one) table.getSelectionModel().removeSelectionInterval(0, 0); } } if (logger.isDebugEnabled()) { logger.debug(String.format("[%s] Selection changed", getComponentLabel())); } // Propagate the event fireChangeEvent(); } } public List<File> getSelection() { return tableModel.getFilesAt(table.getSelectedRows()); } private String getComponentLabel() { return (getName() == null) ? "N/A" : getName(); } @Override public void keyPressed(KeyEvent e) { if (e.getSource() != table) { return; } if (e.getKeyCode() == KeyEvent.VK_ENTER) { // What's the current selection ? final List<File> selection = getSelection(); if (selection.size() == 1) { final File selectedFile = selection.iterator().next(); if (selectedFile.isDirectory()) { // Change to the selected directory setDirectory(selectedFile); } } } else if (e.getKeyCode() == KeyEvent.VK_BACK_SPACE) { // Return to the parent directory (if any) final File parentDir = getParentDirectory(); if ((parentDir != null) && parentDir.exists()) { setDirectory(parentDir); } } else { // Propagate event to our listeners processKeyEvent(new KeyEvent(this, e.getID(), e.getWhen(), e.getModifiers(), e.getKeyCode(), e.getKeyChar(), e.getKeyLocation())); } } @Override public void keyReleased(KeyEvent e) { if (e.getSource() != table) { return; } // Propagate event to our listeners processKeyEvent(new KeyEvent(this, e.getID(), e.getWhen(), e.getModifiers(), e.getKeyCode(), e.getKeyChar(), e.getKeyLocation())); } @Override public void keyTyped(KeyEvent e) { if (e.getSource() != table) { return; } // Propagate event to our listeners processKeyEvent(new KeyEvent(this, e.getID(), e.getWhen(), e.getModifiers(), e.getKeyCode(), e.getKeyChar(), e.getKeyLocation())); } @Override public void mouseClicked(MouseEvent e) { if (e.getSource() == table) { if (e.getClickCount() == 2) { // Only react to double clicks final List<File> selection = getSelection(); if (selection.size() == 1) { final File file = selection.iterator().next(); if (file.isDirectory()) { // Change to the clicked directory setDirectory(file); } } } } } @Override public void mouseEntered(MouseEvent e) { } @Override public void mouseExited(MouseEvent e) { } @Override public void mousePressed(MouseEvent e) { } @Override public void mouseReleased(MouseEvent e) { } @Override public void focusGained(FocusEvent e) { if (e.getSource() == table) { // Propagate the event final FocusListener[] listeners = getListeners(FocusListener.class); if (listeners != null) { final FocusEvent event = new FocusEvent(this, e.getID(), e.isTemporary(), e.getOppositeComponent()); for (FocusListener listener : listeners) { listener.focusGained(event); } } } } @Override public void focusLost(FocusEvent e) { if (e.getSource() == table) { // Propagate the event final FocusListener[] listeners = getListeners(FocusListener.class); if (listeners != null) { final FocusEvent event = new FocusEvent(this, e.getID(), e.isTemporary(), e.getOppositeComponent()); for (FocusListener listener : listeners) { listener.focusLost(event); } } } } @Override public void columnResized(ColumnEvent event) { System.err.println(event); } }
Added code to detect clicks on table headers
src/main/java/com/github/fritaly/dualcommander/DirectoryBrowser.java
Added code to detect clicks on table headers
<ide><path>rc/main/java/com/github/fritaly/dualcommander/DirectoryBrowser.java <ide> this.table.getTableHeader().setFont(Utils.getBoldFont(this.table.getTableHeader().getFont())); <ide> this.table.getTableHeader().setBackground(Color.decode("#CCCCCC")); <ide> this.table.getTableHeader().setDefaultRenderer(new TableHeaderRenderer()); <add> this.table.getTableHeader().addMouseListener(this); <ide> <ide> final TableColumn fileColumn = this.table.getColumn(FileTableModel.COLUMN_NAME); <ide> fileColumn.setCellRenderer(new FileTableCellRenderer()); <ide> } <ide> } <ide> } <add> } else if (e.getSource() == table.getTableHeader()) { <add> final int columnIndex = table.convertColumnIndexToModel(table.columnAtPoint(e.getPoint())); <add> <add> if (columnIndex >= 0) { <add> // TODO React to clicks on column headers <add> System.err.println("Clicked on column header " + columnIndex); <add> } <ide> } <ide> } <ide>
JavaScript
mit
b49f46d15bbc17317cfabfab18910ce92b6cd532
0
thrashr888/node-angularcontext,apparentlymart/node-angularcontext,rit/node-angularcontext,fusikky/node-angularcontext
'use strict'; var jsdom = require('jsdom'); var fs = require('fs'); var Context = function () { // We provide an empty DOM that allows some basic parts of AngularJS to work, // but we're not actually expecting to render an app in here... it just gives // us an anchor document so we can do things like call document.createElement // when using jqLite/jQuery. var document = jsdom.jsdom( null, null, { // Don't do anything with external resources, since we're not actually // trying to emulate a browser here, just a DOM. FetchExternalResources: false, ProcessExternalResources: false, SkipExternalResources: false } ); var window = document.parentWindow; // 'window' has already been contextified by jsdom, so we can just use it. var rawContext = window; var runFiles = function (filenames, callback) { var loadedCount = 0; var firstError; var sources = []; sources.length = filenames.length; var runSources = function () { if (firstError) { callback(false, firstError); } else { // now run the sources in the correct order try { for (var i = 0; i < sources.length; i++) { rawContext.run(sources[i], filenames[i]); } } catch (err) { firstError = err; callback(false, err); } } if (! firstError) { callback(true); } }; var makeLoadHandler = function (i) { return function (err, data) { loadedCount++; if (err) { if (! firstError) { firstError = err; } } else { sources[i] = data; } if (loadedCount === filenames.length) { // we've got everything loaded, so now run them runSources(); } }; }; for (var i = 0; i < filenames.length; i++) { fs.readFile( filenames[i], 'utf8', makeLoadHandler(i) ); } }; return { run: function (source, filename) { rawContext.run(source, filename); }, runFile: function (fileName, callback) { runFiles([fileName], callback); fs.readFile( fileName, 'utf8', function (err, data) { if (err) { callback(undefined, err); } else { callback(rawContext.run(data, fileName)); } } ); }, runFiles: runFiles, hasAngular: function () { return typeof rawContext.angular === 'object'; }, getAngular: function () { return rawContext.angular; }, module: function () { return rawContext.angular.module.apply( rawContext.angular.module, arguments ); }, injector: function (modules) { return rawContext.angular.injector(modules); }, bootstrap: function (element, modules) { return rawContext.angular.bootstrap(element, modules); }, element: function (param) { return rawContext.angular.element(param); }, dispose: function () { rawContext.dispose(); } }; }; exports.Context = Context;
lib/main.js
'use strict'; var jsdom = require('jsdom'); var fs = require('fs'); var Context = function () { // We provide an empty DOM that allows some basic parts of AngularJS to work, // but we're not actually expecting to render an app in here... it just gives // us an anchor document so we can do things like call document.createElement // when using jqLite/jQuery. var document = jsdom.jsdom( null, null, { // Don't do anything with external resources, since we're not actually // trying to emulate a browser here, just a DOM. FetchExternalResources: false, ProcessExternalResources: false, SkipExternalResources: false } ); var window = document.parentWindow; // 'window' has already been contextified by jsdom, so we can just use it. var rawContext = window; var runFiles = function (filenames, callback) { var loadedCount = 0; var firstError; var sources = []; sources.length = filenames.length; var runSources = function () { if (firstError) { callback(false, firstError); } else { // now run the sources in the correct order try { for (var i = 0; i < sources.length; i++) { rawContext.run(sources[i], filenames[i]); } } catch (err) { firstError = err; callback(false, err); } } if (! firstError) { callback(true); } }; var makeLoadHandler = function (i) { return function (err, data) { loadedCount++; if (err) { if (! firstError) { firstError = err; } } else { sources[i] = data; } if (loadedCount === filenames.length) { // we've got everything loaded, so now run them runSources(); } }; }; for (var i = 0; i < filenames.length; i++) { fs.readFile( filenames[i], 'utf8', makeLoadHandler(i) ); } }; return { run: function (source, filename) { rawContext.run(source, filename); }, runFile: function (fileName, callback) { runFiles([fileName], callback); fs.readFile( fileName, 'utf8', function (err, data) { if (err) { callback(undefined, err); } else { callback(rawContext.run(data, fileName)); } } ); }, runFiles: runFiles, hasAngular: function () { return typeof rawContext.angular === 'object'; }, getAngular: function () { return rawContext.angular; }, module: function () { return rawContext.angular.module.apply( rawContext.angular.module, arguments ); }, injector: function (modules) { return rawContext.angular.injector(modules); }, dispose: function () { rawContext.dispose(); } }; }; exports.Context = Context;
Provide access to the bootstrap and element methods. This allows the caller to initialize an AngularJS application (with an associated DOM element) rather than just an injector.
lib/main.js
Provide access to the bootstrap and element methods.
<ide><path>ib/main.js <ide> return rawContext.angular.injector(modules); <ide> }, <ide> <add> bootstrap: function (element, modules) { <add> return rawContext.angular.bootstrap(element, modules); <add> }, <add> <add> element: function (param) { <add> return rawContext.angular.element(param); <add> }, <add> <ide> dispose: function () { <ide> rawContext.dispose(); <ide> }
Java
apache-2.0
de20f2dd7124413b12146f521bf81096361cb79d
0
sjwall/MaterialTapTargetPrompt
/* * Copyright (C) 2017 Samuel Wall * * 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 uk.co.samuelwall.materialtaptargetprompt.extras; import android.annotation.SuppressLint; import android.content.res.Resources; import android.graphics.PointF; import android.graphics.PorterDuff; import android.graphics.Rect; import android.graphics.RectF; import android.graphics.Typeface; import android.os.Build; import android.support.annotation.Nullable; import android.text.Layout; import android.text.SpannableStringBuilder; import android.text.Spanned; import android.text.StaticLayout; import android.text.TextPaint; import android.view.Gravity; import android.view.View; import java.text.Bidi; public class PromptUtils { private PromptUtils() {} /** * Determines if a point is in the centre of a circle with a radius from the point. * * @param x The x position in the view. * @param y The y position in the view. * @param circleCentre The circle centre position * @param radius The radius of the circle. * @return True if the point (x, y) is in the circle. */ public static boolean isPointInCircle(final float x, final float y, final PointF circleCentre, final float radius) { return Math.pow(x - circleCentre.x, 2) + Math.pow(y - circleCentre.y, 2) < Math.pow(radius, 2); } /** * Based on setTypeface in android TextView, Copyright (C) 2006 The Android Open Source * Project. https://android.googlesource.com/platform/frameworks/base.git/+/master/core/java/android/widget/TextView.java */ public static void setTypeface(TextPaint textPaint, Typeface typeface, int style) { if (style > 0) { if (typeface == null) { typeface = Typeface.defaultFromStyle(style); } else { typeface = Typeface.create(typeface, style); } textPaint.setTypeface(typeface); int typefaceStyle = typeface != null ? typeface.getStyle() : 0; int need = style & ~typefaceStyle; textPaint.setFakeBoldText((need & Typeface.BOLD) != 0); textPaint.setTextSkewX((need & Typeface.ITALIC) != 0 ? -0.25f : 0); } else if (typeface != null) { textPaint.setTypeface(typeface); } else { textPaint.setTypeface(Typeface.defaultFromStyle(style)); } } /** * Based on setTypefaceFromAttrs in android TextView, Copyright (C) 2006 The Android Open * Source Project. https://android.googlesource.com/platform/frameworks/base.git/+/master/core/java/android/widget/TextView.java */ public static Typeface setTypefaceFromAttrs(String familyName, int typefaceIndex, int styleIndex) { Typeface tf = null; if (familyName != null) { tf = Typeface.create(familyName, styleIndex); if (tf != null) { return tf; } } switch (typefaceIndex) { case 1: tf = Typeface.SANS_SERIF; break; case 2: tf = Typeface.SERIF; break; case 3: tf = Typeface.MONOSPACE; break; } return Typeface.create(tf, styleIndex); } /** * Based on parseTintMode in android appcompat v7 DrawableUtils, Copyright (C) 2014 The * Android Open Source Project. https://android.googlesource.com/platform/frameworks/support.git/+/master/v7/appcompat/src/android/support/v7/widget/DrawableUtils.java */ public static PorterDuff.Mode parseTintMode(int value, PorterDuff.Mode defaultMode) { switch (value) { case 3: return PorterDuff.Mode.SRC_OVER; case 5: return PorterDuff.Mode.SRC_IN; case 9: return PorterDuff.Mode.SRC_ATOP; case 14: return PorterDuff.Mode.MULTIPLY; case 15: return PorterDuff.Mode.SCREEN; case 16: return PorterDuff.Mode.valueOf("ADD"); default: return defaultMode; } } /** * Gets the absolute text alignment value based on the supplied gravity and the activities * layout direction. * * @param gravity The gravity to convert to absolute values * @return absolute layout direction */ @SuppressLint("RtlHardcoded") public static Layout.Alignment getTextAlignment(final Resources resources, final int gravity, final CharSequence text) { final int absoluteGravity; if (isVersionAfterJellyBeanMR1()) { int realGravity = gravity; final int layoutDirection = resources.getConfiguration().getLayoutDirection(); if (text != null && layoutDirection == View.LAYOUT_DIRECTION_RTL && new Bidi(text.toString(), Bidi.DIRECTION_DEFAULT_LEFT_TO_RIGHT).isRightToLeft()) { if (gravity == Gravity.START) { realGravity = Gravity.END; } else if (gravity == Gravity.END) { realGravity = Gravity.START; } } absoluteGravity = Gravity.getAbsoluteGravity(realGravity, layoutDirection); } else { if ((gravity & Gravity.START) == Gravity.START) { absoluteGravity = Gravity.LEFT; } else if ((gravity & Gravity.END) == Gravity.END) { absoluteGravity = Gravity.RIGHT; } else { absoluteGravity = gravity & Gravity.HORIZONTAL_GRAVITY_MASK; } } final Layout.Alignment alignment; switch (absoluteGravity) { case Gravity.RIGHT: alignment = Layout.Alignment.ALIGN_OPPOSITE; break; case Gravity.CENTER_HORIZONTAL: alignment = Layout.Alignment.ALIGN_CENTER; break; default: alignment = Layout.Alignment.ALIGN_NORMAL; break; } return alignment; } /** * Determines if Android is after Jelly Bean MR1. * * @return True if running on Android after Jelly Bean MR1. */ public static boolean isVersionAfterJellyBeanMR1() { return Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR1; } /** * Creates a static text layout. Uses the {@link android.text.StaticLayout.Builder} if * available. * * @param text The text to be laid out, optionally with spans * @param paint The base paint used for layout * @param maxTextWidth The width in pixels * @param textAlignment Alignment for the resulting {@link StaticLayout} * @param alphaModifier The modification to apply to the alpha value between 0 and 1. * @return the newly constructed {@link StaticLayout} object */ public static StaticLayout createStaticTextLayout(final CharSequence text, final TextPaint paint, final int maxTextWidth, final Layout.Alignment textAlignment, final float alphaModifier) { final SpannableStringBuilder wrappedText = new SpannableStringBuilder(text); wrappedText.setSpan(new AlphaSpan(alphaModifier), 0, wrappedText.length(), Spanned.SPAN_INCLUSIVE_INCLUSIVE); final StaticLayout layout; if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) { final StaticLayout.Builder builder = StaticLayout.Builder.obtain(wrappedText, 0, text.length(), paint, maxTextWidth); builder.setAlignment(textAlignment); layout = builder.build(); } else { layout = new StaticLayout(wrappedText, paint, maxTextWidth, textAlignment, 1f, 0f, false); } return layout; } public static void scale(final PointF origin, final RectF base, final RectF out, final float scale, final boolean even) { if (scale == 1) { out.set(base); return; } final float horizontalFromCentre = base.centerX() - base.left; final float verticalFromCentre = base.centerY() - base.top; if (even && scale > 1) { final float minChange = Math.min(horizontalFromCentre * scale - horizontalFromCentre, verticalFromCentre * scale - verticalFromCentre); out.left = base.left - minChange; out.top = base.top - minChange; out.right = base.right + minChange; out.bottom = base.bottom + minChange; } else { out.left = origin.x - horizontalFromCentre * scale * ((origin.x - base.left) / horizontalFromCentre); out.top = origin.y - verticalFromCentre * scale * ((origin.y - base.top) / verticalFromCentre); out.right = origin.x + horizontalFromCentre * scale * ((base.right - origin.x) / horizontalFromCentre); out.bottom = origin.y + verticalFromCentre * scale * ((base.bottom - origin.y) / verticalFromCentre); } } /** * Determines if the text in the supplied layout is displayed right to left. * * @param layout The layout to check. * @return True if the text in the supplied layout is displayed right to left. False otherwise. */ public static boolean isRtlText(final Layout layout, final Resources resources) { boolean result = false; if (layout != null) { // Treat align opposite as right to left by default result = layout.getAlignment() == Layout.Alignment.ALIGN_OPPOSITE; if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.ICE_CREAM_SANDWICH) { // If the first character is a right to left character final boolean textIsRtl = layout.isRtlCharAt(0); // If the text and result are right to left then false otherwise use the textIsRtl value result = (!(result && textIsRtl) && !(!result && !textIsRtl)) || textIsRtl; if (!result && layout.getAlignment() == Layout.Alignment.ALIGN_NORMAL && Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR1) { // If the layout and text are right to left and the alignment is normal then rtl result = resources.getConfiguration() .getLayoutDirection() == View.LAYOUT_DIRECTION_RTL; } else if (layout.getAlignment() == Layout.Alignment.ALIGN_OPPOSITE && textIsRtl) { result = false; } } } return result; } /** * Calculates the maximum width that the prompt can be. * * @return Maximum width in pixels that the prompt can be. */ public static float calculateMaxWidth(final float maxTextWidth, @Nullable final Rect clipBounds, final int parentWidth, final float textPadding) { return Math.max(80, Math.min(maxTextWidth, (clipBounds != null ? clipBounds.right - clipBounds.left : parentWidth) - (textPadding * 2))); } /** * Calculates the maximum width line in a text layout. * * @param textLayout The text layout * @return The maximum length line */ public static float calculateMaxTextWidth(final Layout textLayout) { float maxTextWidth = 0f; if (textLayout != null) { for (int i = 0, count = textLayout.getLineCount(); i < count; i++) { maxTextWidth = Math.max(maxTextWidth, textLayout.getLineWidth(i)); } } return maxTextWidth; } }
library/src/main/java/uk/co/samuelwall/materialtaptargetprompt/extras/PromptUtils.java
/* * Copyright (C) 2017 Samuel Wall * * 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 uk.co.samuelwall.materialtaptargetprompt.extras; import android.annotation.SuppressLint; import android.content.res.Resources; import android.graphics.PointF; import android.graphics.PorterDuff; import android.graphics.Rect; import android.graphics.RectF; import android.graphics.Typeface; import android.os.Build; import android.support.annotation.Nullable; import android.text.Layout; import android.text.SpannableStringBuilder; import android.text.Spanned; import android.text.StaticLayout; import android.text.TextPaint; import android.view.Gravity; import android.view.View; import java.text.Bidi; public class PromptUtils { private PromptUtils() {} /** * Determines if a point is in the centre of a circle with a radius from the point. * * @param x The x position in the view. * @param y The y position in the view. * @param circleCentre The circle centre position * @param radius The radius of the circle. * @return True if the point (x, y) is in the circle. */ public static boolean isPointInCircle(final float x, final float y, final PointF circleCentre, final float radius) { return Math.pow(x - circleCentre.x, 2) + Math.pow(y - circleCentre.y, 2) < Math.pow(radius, 2); } /** * Based on setTypeface in android TextView, Copyright (C) 2006 The Android Open Source * Project. https://android.googlesource.com/platform/frameworks/base.git/+/master/core/java/android/widget/TextView.java */ public static void setTypeface(TextPaint textPaint, Typeface typeface, int style) { if (style > 0) { if (typeface == null) { typeface = Typeface.defaultFromStyle(style); } else { typeface = Typeface.create(typeface, style); } textPaint.setTypeface(typeface); int typefaceStyle = typeface != null ? typeface.getStyle() : 0; int need = style & ~typefaceStyle; textPaint.setFakeBoldText((need & Typeface.BOLD) != 0); textPaint.setTextSkewX((need & Typeface.ITALIC) != 0 ? -0.25f : 0); } else if (typeface != null) { textPaint.setTypeface(typeface); } else { textPaint.setTypeface(Typeface.defaultFromStyle(style)); } } /** * Based on setTypefaceFromAttrs in android TextView, Copyright (C) 2006 The Android Open * Source Project. https://android.googlesource.com/platform/frameworks/base.git/+/master/core/java/android/widget/TextView.java */ public static Typeface setTypefaceFromAttrs(String familyName, int typefaceIndex, int styleIndex) { Typeface tf = null; if (familyName != null) { tf = Typeface.create(familyName, styleIndex); if (tf != null) { return tf; } } switch (typefaceIndex) { case 1: tf = Typeface.SANS_SERIF; break; case 2: tf = Typeface.SERIF; break; case 3: tf = Typeface.MONOSPACE; break; } return Typeface.create(tf, styleIndex); } /** * Based on parseTintMode in android appcompat v7 DrawableUtils, Copyright (C) 2014 The * Android Open Source Project. https://android.googlesource.com/platform/frameworks/support.git/+/master/v7/appcompat/src/android/support/v7/widget/DrawableUtils.java */ public static PorterDuff.Mode parseTintMode(int value, PorterDuff.Mode defaultMode) { switch (value) { case 3: return PorterDuff.Mode.SRC_OVER; case 5: return PorterDuff.Mode.SRC_IN; case 9: return PorterDuff.Mode.SRC_ATOP; case 14: return PorterDuff.Mode.MULTIPLY; case 15: return PorterDuff.Mode.SCREEN; case 16: return PorterDuff.Mode.valueOf("ADD"); default: return defaultMode; } } /** * Gets the absolute text alignment value based on the supplied gravity and the activities * layout direction. * * @param gravity The gravity to convert to absolute values * @return absolute layout direction */ @SuppressLint("RtlHardcoded") public static Layout.Alignment getTextAlignment(final Resources resources, final int gravity, final CharSequence text) { final int absoluteGravity; if (isVersionAfterJellyBeanMR1()) { int realGravity = gravity; final int layoutDirection = resources.getConfiguration().getLayoutDirection(); if (text != null && layoutDirection == View.LAYOUT_DIRECTION_RTL && new Bidi(text.toString(), Bidi.DIRECTION_DEFAULT_LEFT_TO_RIGHT).isRightToLeft()) { if (gravity == Gravity.START) { realGravity = Gravity.END; } else if (gravity == Gravity.END) { realGravity = Gravity.START; } } absoluteGravity = Gravity.getAbsoluteGravity(realGravity, layoutDirection); } else { if ((gravity & Gravity.START) == Gravity.START) { absoluteGravity = Gravity.LEFT; } else if ((gravity & Gravity.END) == Gravity.END) { absoluteGravity = Gravity.RIGHT; } else { absoluteGravity = gravity & Gravity.HORIZONTAL_GRAVITY_MASK; } } final Layout.Alignment alignment; switch (absoluteGravity) { case Gravity.RIGHT: alignment = Layout.Alignment.ALIGN_OPPOSITE; break; case Gravity.CENTER_HORIZONTAL: alignment = Layout.Alignment.ALIGN_CENTER; break; default: alignment = Layout.Alignment.ALIGN_NORMAL; break; } return alignment; } /** * Determines if Android is after Jelly Bean MR1. * * @return True if running on Android after Jelly Bean MR1. */ public static boolean isVersionAfterJellyBeanMR1() { return Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR1; } /** * Creates a static text layout. Uses the {@link android.text.StaticLayout.Builder} if * available. * * @param text The text to be laid out, optionally with spans * @param paint The base paint used for layout * @param maxTextWidth The width in pixels * @param textAlignment Alignment for the resulting {@link StaticLayout} * @param alphaModifier The modification to apply to the alpha value between 0 and 1. * @return the newly constructed {@link StaticLayout} object */ public static StaticLayout createStaticTextLayout(final CharSequence text, final TextPaint paint, final int maxTextWidth, final Layout.Alignment textAlignment, final float alphaModifier) { final SpannableStringBuilder wrappedText = new SpannableStringBuilder(text); wrappedText.setSpan(new AlphaSpan(alphaModifier), 0, wrappedText.length(), Spanned.SPAN_INCLUSIVE_INCLUSIVE); final StaticLayout layout; if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) { final StaticLayout.Builder builder = StaticLayout.Builder.obtain(wrappedText, 0, text.length(), paint, maxTextWidth); builder.setAlignment(textAlignment); layout = builder.build(); } else { layout = new StaticLayout(wrappedText, paint, maxTextWidth, textAlignment, 1f, 0f, false); } return layout; } public static void scale(final PointF origin, final RectF base, final RectF out, final float scale, final boolean even) { if (scale == 1) { out.set(base); return; } final float horizontalFromCentre = base.centerX() - base.left; final float verticalFromCentre = base.centerY() - base.top; if (even && scale > 1) { final float minChange = Math.min(horizontalFromCentre * scale - horizontalFromCentre, verticalFromCentre * scale - verticalFromCentre); out.left = base.left - minChange; out.top = base.top - minChange; out.right = base.right + minChange; out.bottom = base.bottom + minChange; } else { out.left = origin.x - horizontalFromCentre * scale * ((origin.x - base.left) / horizontalFromCentre); out.top = origin.y - verticalFromCentre * scale * ((origin.y - base.top) / verticalFromCentre); out.right = origin.x + horizontalFromCentre * scale * ((base.right - origin.x) / horizontalFromCentre); out.bottom = origin.y + verticalFromCentre * scale * ((base.bottom - origin.y) / verticalFromCentre); } } /** * Determines if the text in the supplied layout is displayed right to left. * * @param layout The layout to check. * @return True if the text in the supplied layout is displayed right to left. False otherwise. */ public static boolean isRtlText(final Layout layout, final Resources resources) { boolean result = false; if (layout != null) { // Treat align opposite as right to left by default result = layout.getAlignment() == Layout.Alignment.ALIGN_OPPOSITE; if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.ICE_CREAM_SANDWICH) { // If the first character is a right to left character final boolean textIsRtl = layout.isRtlCharAt(0); // If the text and result are right to left then false otherwise use the textIsRtl value result = (!(result && textIsRtl) && !(!result && !textIsRtl)) || textIsRtl; if (!result && layout.getAlignment() == Layout.Alignment.ALIGN_NORMAL && Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR1) { // If the layout and text are right to left and the alignment is normal then rtl result = textIsRtl && resources.getConfiguration() .getLayoutDirection() == View.LAYOUT_DIRECTION_RTL; } else if (layout.getAlignment() == Layout.Alignment.ALIGN_OPPOSITE && textIsRtl) { result = false; } } } return result; } /** * Calculates the maximum width that the prompt can be. * * @return Maximum width in pixels that the prompt can be. */ public static float calculateMaxWidth(final float maxTextWidth, @Nullable final Rect clipBounds, final int parentWidth, final float textPadding) { return Math.max(80, Math.min(maxTextWidth, (clipBounds != null ? clipBounds.right - clipBounds.left : parentWidth) - (textPadding * 2))); } /** * Calculates the maximum width line in a text layout. * * @param textLayout The text layout * @return The maximum length line */ public static float calculateMaxTextWidth(final Layout textLayout) { float maxTextWidth = 0f; if (textLayout != null) { for (int i = 0, count = textLayout.getLineCount(); i < count; i++) { maxTextWidth = Math.max(maxTextWidth, textLayout.getLineWidth(i)); } } return maxTextWidth; } }
Corrected rtl calculation
library/src/main/java/uk/co/samuelwall/materialtaptargetprompt/extras/PromptUtils.java
Corrected rtl calculation
<ide><path>ibrary/src/main/java/uk/co/samuelwall/materialtaptargetprompt/extras/PromptUtils.java <ide> && Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR1) <ide> { <ide> // If the layout and text are right to left and the alignment is normal then rtl <del> result = textIsRtl && resources.getConfiguration() <del> .getLayoutDirection() == View.LAYOUT_DIRECTION_RTL; <add> result = resources.getConfiguration() <add> .getLayoutDirection() == View.LAYOUT_DIRECTION_RTL; <ide> } <ide> else if (layout.getAlignment() == Layout.Alignment.ALIGN_OPPOSITE && textIsRtl) <ide> {
Java
apache-2.0
ef2920406d46f2f7a6f58bfea2d4b726f2122250
0
da1z/intellij-community,allotria/intellij-community,mglukhikh/intellij-community,allotria/intellij-community,allotria/intellij-community,mglukhikh/intellij-community,ThiagoGarciaAlves/intellij-community,mglukhikh/intellij-community,ThiagoGarciaAlves/intellij-community,allotria/intellij-community,da1z/intellij-community,ThiagoGarciaAlves/intellij-community,da1z/intellij-community,xfournet/intellij-community,xfournet/intellij-community,ThiagoGarciaAlves/intellij-community,mglukhikh/intellij-community,da1z/intellij-community,allotria/intellij-community,ThiagoGarciaAlves/intellij-community,allotria/intellij-community,xfournet/intellij-community,xfournet/intellij-community,allotria/intellij-community,ThiagoGarciaAlves/intellij-community,allotria/intellij-community,xfournet/intellij-community,allotria/intellij-community,da1z/intellij-community,xfournet/intellij-community,mglukhikh/intellij-community,da1z/intellij-community,xfournet/intellij-community,mglukhikh/intellij-community,mglukhikh/intellij-community,da1z/intellij-community,allotria/intellij-community,da1z/intellij-community,xfournet/intellij-community,ThiagoGarciaAlves/intellij-community,xfournet/intellij-community,da1z/intellij-community,xfournet/intellij-community,mglukhikh/intellij-community,ThiagoGarciaAlves/intellij-community,da1z/intellij-community,mglukhikh/intellij-community,ThiagoGarciaAlves/intellij-community,xfournet/intellij-community,da1z/intellij-community,allotria/intellij-community,mglukhikh/intellij-community,allotria/intellij-community,da1z/intellij-community,ThiagoGarciaAlves/intellij-community,ThiagoGarciaAlves/intellij-community,mglukhikh/intellij-community,da1z/intellij-community,xfournet/intellij-community,ThiagoGarciaAlves/intellij-community,allotria/intellij-community,mglukhikh/intellij-community,xfournet/intellij-community,mglukhikh/intellij-community
/* * Copyright 2000-2017 JetBrains s.r.o. * * 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.intellij.ide.ui; import com.intellij.ide.IdeBundle; import com.intellij.ide.SearchTopHitProvider; import com.intellij.ide.ui.search.OptionDescription; import com.intellij.openapi.Disposable; import com.intellij.openapi.application.Application; import com.intellij.openapi.application.ApplicationBundle; import com.intellij.openapi.application.PreloadingActivity; import com.intellij.openapi.components.ComponentManager; import com.intellij.openapi.diagnostic.Logger; import com.intellij.openapi.keymap.KeyMapBundle; import com.intellij.openapi.progress.ProgressIndicator; import com.intellij.openapi.project.Project; import com.intellij.openapi.startup.StartupActivity; import com.intellij.openapi.util.Disposer; import com.intellij.openapi.util.Key; import com.intellij.openapi.util.text.StringUtil; import com.intellij.psi.codeStyle.MinusculeMatcher; import com.intellij.psi.codeStyle.NameUtil; import com.intellij.util.Consumer; import org.jetbrains.annotations.NonNls; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import java.util.Collection; import java.util.List; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.atomic.AtomicLong; import static com.intellij.openapi.application.ApplicationManager.getApplication; import static java.util.Collections.emptyList; /** * @author Konstantin Bulenkov */ public abstract class OptionsTopHitProvider implements SearchTopHitProvider { private static final Logger LOG = Logger.getInstance(OptionsTopHitProvider.class); @NotNull public abstract Collection<OptionDescription> getOptions(@Nullable Project project); private Collection<OptionDescription> getCachedOptions(@Nullable Project project) { ComponentManager manager = project != null ? project : getApplication(); if (manager == null || manager.isDisposed()) return emptyList(); CachedOptions cache = manager.getUserData(CachedOptions.KEY); if (cache == null) cache = new CachedOptions(manager); return cache.map.computeIfAbsent(getClass(), type -> getOptions(project)); } @Override public final void consumeTopHits(@NonNls String pattern, Consumer<Object> collector, Project project) { if (!pattern.startsWith("#")) return; pattern = pattern.substring(1); final List<String> parts = StringUtil.split(pattern, " "); if (parts.size() == 0) { return; } String id = parts.get(0); if (getId().startsWith(id) || pattern.startsWith(" ")) { if (pattern.startsWith(" ")) { pattern = pattern.trim(); } else { pattern = pattern.substring(id.length()).trim().toLowerCase(); } final MinusculeMatcher matcher = NameUtil.buildMatcher("*" + pattern, NameUtil.MatchingCaseSensitivity.NONE); for (OptionDescription option : getCachedOptions(project)) { if (matcher.matches(option.getOption())) { collector.consume(option); } } } } public abstract String getId(); public boolean isEnabled(@Nullable Project project) { return true; } static String messageApp(String property) { return StringUtil.stripHtml(ApplicationBundle.message(property), false); } static String messageIde(String property) { return StringUtil.stripHtml(IdeBundle.message(property), false); } static String messageKeyMap(String property) { return StringUtil.stripHtml(KeyMapBundle.message(property), false); } /* * Marker interface for option provider containing only descriptors which are backed by toggle actions. * E.g. UiSettings.SHOW_STATUS_BAR is backed by View > Status Bar action. */ @Deprecated public interface CoveredByToggleActions { // for search everywhere only } private static final class CachedOptions implements Disposable { private static final Key<CachedOptions> KEY = Key.create("cached top hits"); private final ConcurrentHashMap<Class<?>, Collection<OptionDescription>> map = new ConcurrentHashMap<>(); private final ComponentManager manager; private CachedOptions(ComponentManager manager) { this.manager = manager; Disposer.register(manager, this); manager.putUserData(KEY, this); } @Override public void dispose() { manager.putUserData(KEY, null); map.values().forEach(CachedOptions::dispose); } private static void dispose(Collection<OptionDescription> options) { if (options != null) options.forEach(CachedOptions::dispose); } private static void dispose(OptionDescription option) { if (option instanceof Disposable) Disposer.dispose((Disposable)option); } } public static final class Activity extends PreloadingActivity implements StartupActivity { @Override public void preload(@NotNull ProgressIndicator indicator) { cacheAll(indicator, null); // for application } @Override public void runActivity(@NotNull Project project) { cacheAll(null, project); // for given project } private static void cacheAll(@Nullable ProgressIndicator indicator, @Nullable Project project) { Application application = getApplication(); if (application != null && !application.isUnitTestMode()) { long millis = System.currentTimeMillis(); String name = project == null ? "application" : "project"; AtomicLong time = new AtomicLong(); for (SearchTopHitProvider provider : SearchTopHitProvider.EP_NAME.getExtensions()) { if (provider instanceof OptionsTopHitProvider) { application.invokeLater(() -> time.addAndGet(cache((OptionsTopHitProvider)provider, indicator, project))); } } application.invokeLater(() -> LOG.info(time.get() + " ms spent to cache options in " + name)); time.addAndGet(System.currentTimeMillis() - millis); } } private static long cache(@NotNull OptionsTopHitProvider provider, @Nullable ProgressIndicator indicator, @Nullable Project project) { if (indicator != null && indicator.isCanceled()) return 0; // if application is closed if (project != null && project.isDisposed()) return 0; // if project is closed long millis = System.currentTimeMillis(); if (provider.isEnabled(project)) provider.getCachedOptions(project); return System.currentTimeMillis() - millis; } } }
platform/platform-impl/src/com/intellij/ide/ui/OptionsTopHitProvider.java
/* * Copyright 2000-2017 JetBrains s.r.o. * * 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.intellij.ide.ui; import com.intellij.ide.IdeBundle; import com.intellij.ide.SearchTopHitProvider; import com.intellij.ide.ui.search.OptionDescription; import com.intellij.openapi.Disposable; import com.intellij.openapi.application.Application; import com.intellij.openapi.application.ApplicationBundle; import com.intellij.openapi.application.PreloadingActivity; import com.intellij.openapi.components.ComponentManager; import com.intellij.openapi.diagnostic.Logger; import com.intellij.openapi.keymap.KeyMapBundle; import com.intellij.openapi.progress.ProgressIndicator; import com.intellij.openapi.project.Project; import com.intellij.openapi.startup.StartupActivity; import com.intellij.openapi.util.Disposer; import com.intellij.openapi.util.Key; import com.intellij.openapi.util.text.StringUtil; import com.intellij.psi.codeStyle.MinusculeMatcher; import com.intellij.psi.codeStyle.NameUtil; import com.intellij.util.Consumer; import org.jetbrains.annotations.NonNls; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import java.util.Collection; import java.util.List; import java.util.concurrent.ConcurrentHashMap; import static com.intellij.openapi.application.ApplicationManager.getApplication; import static java.util.Collections.emptyList; /** * @author Konstantin Bulenkov */ public abstract class OptionsTopHitProvider implements SearchTopHitProvider { private static final Logger LOG = Logger.getInstance(OptionsTopHitProvider.class); @NotNull public abstract Collection<OptionDescription> getOptions(@Nullable Project project); private Collection<OptionDescription> getCachedOptions(@Nullable Project project) { ComponentManager manager = project != null ? project : getApplication(); if (manager == null || manager.isDisposed()) return emptyList(); CachedOptions cache = manager.getUserData(CachedOptions.KEY); if (cache == null) cache = new CachedOptions(manager); return cache.map.computeIfAbsent(getClass(), type -> getOptions(project)); } @Override public final void consumeTopHits(@NonNls String pattern, Consumer<Object> collector, Project project) { if (!pattern.startsWith("#")) return; pattern = pattern.substring(1); final List<String> parts = StringUtil.split(pattern, " "); if (parts.size() == 0) { return; } String id = parts.get(0); if (getId().startsWith(id) || pattern.startsWith(" ")) { if (pattern.startsWith(" ")) { pattern = pattern.trim(); } else { pattern = pattern.substring(id.length()).trim().toLowerCase(); } final MinusculeMatcher matcher = NameUtil.buildMatcher("*" + pattern, NameUtil.MatchingCaseSensitivity.NONE); for (OptionDescription option : getCachedOptions(project)) { if (matcher.matches(option.getOption())) { collector.consume(option); } } } } public abstract String getId(); public boolean isEnabled(@Nullable Project project) { return true; } static String messageApp(String property) { return StringUtil.stripHtml(ApplicationBundle.message(property), false); } static String messageIde(String property) { return StringUtil.stripHtml(IdeBundle.message(property), false); } static String messageKeyMap(String property) { return StringUtil.stripHtml(KeyMapBundle.message(property), false); } /* * Marker interface for option provider containing only descriptors which are backed by toggle actions. * E.g. UiSettings.SHOW_STATUS_BAR is backed by View > Status Bar action. */ @Deprecated public interface CoveredByToggleActions { // for search everywhere only } private static final class CachedOptions implements Disposable { private static final Key<CachedOptions> KEY = Key.create("cached top hits"); private final ConcurrentHashMap<Class<?>, Collection<OptionDescription>> map = new ConcurrentHashMap<>(); private final ComponentManager manager; private CachedOptions(ComponentManager manager) { this.manager = manager; Disposer.register(manager, this); manager.putUserData(KEY, this); } @Override public void dispose() { manager.putUserData(KEY, null); map.values().forEach(CachedOptions::dispose); } private static void dispose(Collection<OptionDescription> options) { if (options != null) options.forEach(CachedOptions::dispose); } private static void dispose(OptionDescription option) { if (option instanceof Disposable) Disposer.dispose((Disposable)option); } } public static final class Activity extends PreloadingActivity implements StartupActivity { @Override public void preload(@NotNull ProgressIndicator indicator) { cacheAll(indicator, null); // for application } @Override public void runActivity(@NotNull Project project) { cacheAll(null, project); // for given project } private static void cacheAll(@Nullable ProgressIndicator indicator, @Nullable Project project) { Application application = getApplication(); if (application != null && !application.isUnitTestMode()) { for (SearchTopHitProvider provider : SearchTopHitProvider.EP_NAME.getExtensions()) { if (provider instanceof OptionsTopHitProvider) { application.invokeLater(() -> { if (indicator == null || !indicator.isCanceled()) { OptionsTopHitProvider options = (OptionsTopHitProvider)provider; if (options.isEnabled(project)) options.getCachedOptions(project); } }); } } } } } }
log time of loading top hit providers
platform/platform-impl/src/com/intellij/ide/ui/OptionsTopHitProvider.java
log time of loading top hit providers
<ide><path>latform/platform-impl/src/com/intellij/ide/ui/OptionsTopHitProvider.java <ide> import java.util.Collection; <ide> import java.util.List; <ide> import java.util.concurrent.ConcurrentHashMap; <add>import java.util.concurrent.atomic.AtomicLong; <ide> <ide> import static com.intellij.openapi.application.ApplicationManager.getApplication; <ide> import static java.util.Collections.emptyList; <ide> private static void cacheAll(@Nullable ProgressIndicator indicator, @Nullable Project project) { <ide> Application application = getApplication(); <ide> if (application != null && !application.isUnitTestMode()) { <add> long millis = System.currentTimeMillis(); <add> String name = project == null ? "application" : "project"; <add> AtomicLong time = new AtomicLong(); <ide> for (SearchTopHitProvider provider : SearchTopHitProvider.EP_NAME.getExtensions()) { <ide> if (provider instanceof OptionsTopHitProvider) { <del> application.invokeLater(() -> { <del> if (indicator == null || !indicator.isCanceled()) { <del> OptionsTopHitProvider options = (OptionsTopHitProvider)provider; <del> if (options.isEnabled(project)) options.getCachedOptions(project); <del> } <del> }); <add> application.invokeLater(() -> time.addAndGet(cache((OptionsTopHitProvider)provider, indicator, project))); <ide> } <ide> } <add> application.invokeLater(() -> LOG.info(time.get() + " ms spent to cache options in " + name)); <add> time.addAndGet(System.currentTimeMillis() - millis); <ide> } <add> } <add> <add> private static long cache(@NotNull OptionsTopHitProvider provider, @Nullable ProgressIndicator indicator, @Nullable Project project) { <add> if (indicator != null && indicator.isCanceled()) return 0; // if application is closed <add> if (project != null && project.isDisposed()) return 0; // if project is closed <add> long millis = System.currentTimeMillis(); <add> if (provider.isEnabled(project)) provider.getCachedOptions(project); <add> return System.currentTimeMillis() - millis; <ide> } <ide> } <ide> }
Java
apache-2.0
22b4e91bec66164837cb19770bef40e470b6eee0
0
mread/buck,marcinkwiatkowski/buck,1yvT0s/buck,Heart2009/buck,dsyang/buck,stuhood/buck,1yvT0s/buck,robbertvanginkel/buck,Dominator008/buck,Addepar/buck,vschs007/buck,artiya4u/buck,robbertvanginkel/buck,clonetwin26/buck,illicitonion/buck,shs96c/buck,marcinkwiatkowski/buck,rmaz/buck,MarkRunWu/buck,stuhood/buck,ilya-klyuchnikov/buck,marcinkwiatkowski/buck,grumpyjames/buck,raviagarwal7/buck,sdwilsh/buck,mnuessler/buck,JoelMarcey/buck,raviagarwal7/buck,clonetwin26/buck,darkforestzero/buck,shs96c/buck,daedric/buck,vschs007/buck,rmaz/buck,rhencke/buck,1yvT0s/buck,Distrotech/buck,Dominator008/buck,tgummerer/buck,tgummerer/buck,LegNeato/buck,ilya-klyuchnikov/buck,liuyang-li/buck,darkforestzero/buck,tgummerer/buck,dpursehouse/buck,robbertvanginkel/buck,rowillia/buck,SeleniumHQ/buck,robbertvanginkel/buck,mikekap/buck,romanoid/buck,dushmis/buck,marcinkwiatkowski/buck,rowillia/buck,k21/buck,vschs007/buck,clonetwin26/buck,romanoid/buck,JoelMarcey/buck,mogers/buck,Addepar/buck,illicitonion/buck,dsyang/buck,grumpyjames/buck,mikekap/buck,zhan-xiong/buck,dsyang/buck,sdwilsh/buck,mnuessler/buck,robbertvanginkel/buck,saleeh93/buck-cutom,luiseduardohdbackup/buck,brettwooldridge/buck,rmaz/buck,sdwilsh/buck,SeleniumHQ/buck,sdwilsh/buck,illicitonion/buck,Dominator008/buck,SeleniumHQ/buck,LegNeato/buck,artiya4u/buck,kageiit/buck,marcinkwiatkowski/buck,siddhartharay007/buck,liuyang-li/buck,JoelMarcey/buck,vschs007/buck,artiya4u/buck,bocon13/buck,facebook/buck,vschs007/buck,nguyentruongtho/buck,Heart2009/buck,MarkRunWu/buck,brettwooldridge/buck,darkforestzero/buck,Distrotech/buck,darkforestzero/buck,liuyang-li/buck,ilya-klyuchnikov/buck,rmaz/buck,mikekap/buck,rhencke/buck,dpursehouse/buck,mikekap/buck,darkforestzero/buck,OkBuilds/buck,SeleniumHQ/buck,tgummerer/buck,MarkRunWu/buck,janicduplessis/buck,grumpyjames/buck,marcinkwiatkowski/buck,siddhartharay007/buck,JoelMarcey/buck,saleeh93/buck-cutom,justinmuller/buck,pwz3n0/buck,brettwooldridge/buck,zhan-xiong/buck,ilya-klyuchnikov/buck,zpao/buck,Dominator008/buck,mikekap/buck,romanoid/buck,shs96c/buck,zhan-xiong/buck,brettwooldridge/buck,dushmis/buck,neonichu/buck,k21/buck,dsyang/buck,SeleniumHQ/buck,artiya4u/buck,JoelMarcey/buck,zhan-xiong/buck,rhencke/buck,zhuxiaohao/buck,clonetwin26/buck,clonetwin26/buck,sdwilsh/buck,vschs007/buck,SeleniumHQ/buck,mikekap/buck,rmaz/buck,LegNeato/buck,luiseduardohdbackup/buck,Dominator008/buck,kageiit/buck,romanoid/buck,Distrotech/buck,luiseduardohdbackup/buck,mread/buck,zhuxiaohao/buck,mogers/buck,facebook/buck,grumpyjames/buck,OkBuilds/buck,vine/buck,OkBuilds/buck,siddhartharay007/buck,1yvT0s/buck,rhencke/buck,darkforestzero/buck,clonetwin26/buck,kageiit/buck,LegNeato/buck,dushmis/buck,pwz3n0/buck,davido/buck,ilya-klyuchnikov/buck,grumpyjames/buck,clonetwin26/buck,raviagarwal7/buck,LegNeato/buck,pwz3n0/buck,Addepar/buck,brettwooldridge/buck,SeleniumHQ/buck,shs96c/buck,dsyang/buck,LegNeato/buck,davido/buck,vschs007/buck,neonichu/buck,daedric/buck,Addepar/buck,darkforestzero/buck,1yvT0s/buck,robbertvanginkel/buck,grumpyjames/buck,dsyang/buck,JoelMarcey/buck,k21/buck,illicitonion/buck,sdwilsh/buck,zhuxiaohao/buck,rowillia/buck,Distrotech/buck,mogers/buck,rhencke/buck,clonetwin26/buck,darkforestzero/buck,LegNeato/buck,luiseduardohdbackup/buck,davido/buck,siddhartharay007/buck,dsyang/buck,stuhood/buck,justinmuller/buck,vschs007/buck,Addepar/buck,lukw00/buck,bocon13/buck,luiseduardohdbackup/buck,neonichu/buck,OkBuilds/buck,lukw00/buck,mnuessler/buck,facebook/buck,Heart2009/buck,vine/buck,zhan-xiong/buck,janicduplessis/buck,siddhartharay007/buck,mnuessler/buck,raviagarwal7/buck,stuhood/buck,janicduplessis/buck,mnuessler/buck,lukw00/buck,hgl888/buck,saleeh93/buck-cutom,tgummerer/buck,ilya-klyuchnikov/buck,MarkRunWu/buck,justinmuller/buck,k21/buck,vschs007/buck,dsyang/buck,robbertvanginkel/buck,k21/buck,siddhartharay007/buck,zpao/buck,pwz3n0/buck,rmaz/buck,justinmuller/buck,shs96c/buck,clonetwin26/buck,shs96c/buck,rowillia/buck,ilya-klyuchnikov/buck,justinmuller/buck,Distrotech/buck,shybovycha/buck,dushmis/buck,1yvT0s/buck,daedric/buck,rowillia/buck,mnuessler/buck,darkforestzero/buck,nguyentruongtho/buck,zhuxiaohao/buck,dpursehouse/buck,Addepar/buck,mikekap/buck,hgl888/buck,Heart2009/buck,romanoid/buck,mogers/buck,shybovycha/buck,Dominator008/buck,nguyentruongtho/buck,grumpyjames/buck,dsyang/buck,dsyang/buck,rowillia/buck,rmaz/buck,k21/buck,brettwooldridge/buck,vschs007/buck,hgl888/buck,grumpyjames/buck,pwz3n0/buck,zhuxiaohao/buck,grumpyjames/buck,rowillia/buck,rhencke/buck,justinmuller/buck,pwz3n0/buck,rhencke/buck,davido/buck,illicitonion/buck,marcinkwiatkowski/buck,siddhartharay007/buck,neonichu/buck,illicitonion/buck,shybovycha/buck,Learn-Android-app/buck,Learn-Android-app/buck,davido/buck,shybovycha/buck,k21/buck,MarkRunWu/buck,vine/buck,luiseduardohdbackup/buck,bocon13/buck,illicitonion/buck,luiseduardohdbackup/buck,darkforestzero/buck,Distrotech/buck,JoelMarcey/buck,dushmis/buck,raviagarwal7/buck,janicduplessis/buck,daedric/buck,zhan-xiong/buck,bocon13/buck,vschs007/buck,janicduplessis/buck,darkforestzero/buck,dsyang/buck,Distrotech/buck,raviagarwal7/buck,Addepar/buck,davido/buck,Learn-Android-app/buck,mread/buck,brettwooldridge/buck,romanoid/buck,1yvT0s/buck,MarkRunWu/buck,hgl888/buck,stuhood/buck,bocon13/buck,JoelMarcey/buck,dpursehouse/buck,tgummerer/buck,shybovycha/buck,zhan-xiong/buck,ilya-klyuchnikov/buck,Learn-Android-app/buck,stuhood/buck,raviagarwal7/buck,Dominator008/buck,illicitonion/buck,bocon13/buck,dpursehouse/buck,mikekap/buck,vine/buck,neonichu/buck,zhuxiaohao/buck,rowillia/buck,lukw00/buck,davido/buck,Heart2009/buck,rowillia/buck,pwz3n0/buck,k21/buck,SeleniumHQ/buck,neonichu/buck,mnuessler/buck,sdwilsh/buck,mikekap/buck,Heart2009/buck,bocon13/buck,mnuessler/buck,Dominator008/buck,justinmuller/buck,SeleniumHQ/buck,sdwilsh/buck,Addepar/buck,vine/buck,liuyang-li/buck,liuyang-li/buck,davido/buck,Heart2009/buck,dsyang/buck,shybovycha/buck,brettwooldridge/buck,OkBuilds/buck,ilya-klyuchnikov/buck,sdwilsh/buck,kageiit/buck,zhuxiaohao/buck,daedric/buck,Distrotech/buck,vschs007/buck,OkBuilds/buck,brettwooldridge/buck,SeleniumHQ/buck,justinmuller/buck,k21/buck,vine/buck,zpao/buck,Addepar/buck,romanoid/buck,marcinkwiatkowski/buck,daedric/buck,ilya-klyuchnikov/buck,LegNeato/buck,zpao/buck,stuhood/buck,illicitonion/buck,lukw00/buck,illicitonion/buck,shybovycha/buck,artiya4u/buck,marcinkwiatkowski/buck,Distrotech/buck,bocon13/buck,dushmis/buck,vine/buck,bocon13/buck,rowillia/buck,robbertvanginkel/buck,marcinkwiatkowski/buck,rmaz/buck,k21/buck,marcinkwiatkowski/buck,OkBuilds/buck,facebook/buck,clonetwin26/buck,Learn-Android-app/buck,OkBuilds/buck,romanoid/buck,mogers/buck,clonetwin26/buck,dpursehouse/buck,Learn-Android-app/buck,facebook/buck,shs96c/buck,rowillia/buck,pwz3n0/buck,artiya4u/buck,raviagarwal7/buck,shybovycha/buck,Addepar/buck,JoelMarcey/buck,Learn-Android-app/buck,rmaz/buck,facebook/buck,davido/buck,facebook/buck,pwz3n0/buck,Distrotech/buck,OkBuilds/buck,JoelMarcey/buck,artiya4u/buck,mogers/buck,ilya-klyuchnikov/buck,liuyang-li/buck,Addepar/buck,Dominator008/buck,dushmis/buck,shs96c/buck,janicduplessis/buck,daedric/buck,JoelMarcey/buck,shybovycha/buck,sdwilsh/buck,rhencke/buck,tgummerer/buck,rowillia/buck,JoelMarcey/buck,shybovycha/buck,lukw00/buck,ilya-klyuchnikov/buck,daedric/buck,bocon13/buck,hgl888/buck,lukw00/buck,k21/buck,mikekap/buck,MarkRunWu/buck,1yvT0s/buck,zhuxiaohao/buck,neonichu/buck,grumpyjames/buck,robbertvanginkel/buck,tgummerer/buck,janicduplessis/buck,artiya4u/buck,janicduplessis/buck,shybovycha/buck,pwz3n0/buck,Dominator008/buck,lukw00/buck,kageiit/buck,marcinkwiatkowski/buck,Dominator008/buck,stuhood/buck,raviagarwal7/buck,robbertvanginkel/buck,zhan-xiong/buck,daedric/buck,rmaz/buck,lukw00/buck,mogers/buck,zhan-xiong/buck,hgl888/buck,rmaz/buck,hgl888/buck,OkBuilds/buck,LegNeato/buck,luiseduardohdbackup/buck,rmaz/buck,mnuessler/buck,rhencke/buck,Dominator008/buck,illicitonion/buck,LegNeato/buck,JoelMarcey/buck,rhencke/buck,rmaz/buck,k21/buck,mread/buck,daedric/buck,Heart2009/buck,lukw00/buck,mikekap/buck,daedric/buck,liuyang-li/buck,shybovycha/buck,zpao/buck,mogers/buck,janicduplessis/buck,clonetwin26/buck,zpao/buck,clonetwin26/buck,Learn-Android-app/buck,dsyang/buck,vine/buck,Addepar/buck,dushmis/buck,janicduplessis/buck,mread/buck,sdwilsh/buck,mogers/buck,davido/buck,robbertvanginkel/buck,brettwooldridge/buck,shs96c/buck,zhan-xiong/buck,SeleniumHQ/buck,dushmis/buck,marcinkwiatkowski/buck,brettwooldridge/buck,nguyentruongtho/buck,kageiit/buck,sdwilsh/buck,saleeh93/buck-cutom,shs96c/buck,MarkRunWu/buck,tgummerer/buck,romanoid/buck,raviagarwal7/buck,artiya4u/buck,OkBuilds/buck,brettwooldridge/buck,romanoid/buck,Learn-Android-app/buck,justinmuller/buck,zhan-xiong/buck,liuyang-li/buck,SeleniumHQ/buck,raviagarwal7/buck,OkBuilds/buck,mread/buck,zhan-xiong/buck,sdwilsh/buck,tgummerer/buck,stuhood/buck,daedric/buck,davido/buck,ilya-klyuchnikov/buck,grumpyjames/buck,nguyentruongtho/buck,justinmuller/buck,LegNeato/buck,dushmis/buck,rhencke/buck,SeleniumHQ/buck,vine/buck,LegNeato/buck,nguyentruongtho/buck,saleeh93/buck-cutom,illicitonion/buck,grumpyjames/buck,shs96c/buck,saleeh93/buck-cutom,bocon13/buck,davido/buck,liuyang-li/buck,dpursehouse/buck,janicduplessis/buck,shs96c/buck,artiya4u/buck,brettwooldridge/buck,daedric/buck,LegNeato/buck,k21/buck,janicduplessis/buck,pwz3n0/buck,shs96c/buck,zpao/buck,neonichu/buck,artiya4u/buck,romanoid/buck,zhuxiaohao/buck,illicitonion/buck,vine/buck,siddhartharay007/buck,Heart2009/buck,tgummerer/buck,justinmuller/buck,mogers/buck,bocon13/buck,justinmuller/buck,mogers/buck,zhan-xiong/buck,luiseduardohdbackup/buck,Distrotech/buck,robbertvanginkel/buck,romanoid/buck,kageiit/buck,Learn-Android-app/buck,romanoid/buck,vine/buck,hgl888/buck,OkBuilds/buck,vschs007/buck,siddhartharay007/buck,hgl888/buck,darkforestzero/buck,liuyang-li/buck,davido/buck,darkforestzero/buck,nguyentruongtho/buck,robbertvanginkel/buck,mikekap/buck,raviagarwal7/buck,shybovycha/buck,raviagarwal7/buck,stuhood/buck,neonichu/buck,1yvT0s/buck,liuyang-li/buck,stuhood/buck,lukw00/buck,Learn-Android-app/buck,Addepar/buck,dpursehouse/buck,justinmuller/buck
/* * Copyright 2014-present Facebook, Inc. * * 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.facebook.buck.android; import com.facebook.buck.android.AndroidBinary.PackageType; import com.facebook.buck.android.AndroidBinary.TargetCpuType; import com.facebook.buck.android.FilterResourcesStep.ResourceFilter; import com.facebook.buck.android.ResourcesFilter.ResourceCompressionMode; import com.facebook.buck.dalvik.ZipSplitter.DexSplitStrategy; import com.facebook.buck.java.JavaLibrary; import com.facebook.buck.java.JavacOptions; import com.facebook.buck.java.Keystore; import com.facebook.buck.model.BuildTarget; import com.facebook.buck.model.HasBuildTarget; import com.facebook.buck.rules.BuildRule; import com.facebook.buck.rules.BuildRuleParams; import com.facebook.buck.rules.BuildRuleResolver; import com.facebook.buck.rules.BuildRuleType; import com.facebook.buck.rules.BuildRules; import com.facebook.buck.rules.ConstructorArg; import com.facebook.buck.rules.Description; import com.facebook.buck.rules.SourcePath; import com.facebook.buck.rules.coercer.BuildConfigFields; import com.facebook.buck.util.HumanReadableException; import com.google.common.base.Optional; import com.google.common.base.Preconditions; import com.google.common.collect.FluentIterable; import com.google.common.collect.ImmutableList; import com.google.common.collect.ImmutableSet; import com.google.common.collect.ImmutableSortedSet; import java.nio.file.Path; import java.util.List; import java.util.Set; import com.facebook.infer.annotation.SuppressFieldNotInitialized; public class AndroidBinaryDescription implements Description<AndroidBinaryDescription.Arg> { public static final BuildRuleType TYPE = new BuildRuleType("android_binary"); /** * By default, assume we have 5MB of linear alloc, * 1MB of which is taken up by the framework, so that leaves 4MB. */ private static final long DEFAULT_LINEAR_ALLOC_HARD_LIMIT = 4 * 1024 * 1024; private final JavacOptions javacOptions; private final Optional<Path> proguardJarOverride; public AndroidBinaryDescription( JavacOptions javacOptions, Optional<Path> proguardJarOverride) { this.javacOptions = Preconditions.checkNotNull(javacOptions); this.proguardJarOverride = Preconditions.checkNotNull(proguardJarOverride); } @Override public BuildRuleType getBuildRuleType() { return TYPE; } @Override public Arg createUnpopulatedConstructorArg() { return new Arg(); } @Override public <A extends Arg> AndroidBinary createBuildRule( BuildRuleParams params, BuildRuleResolver resolver, A args) { if (!(args.keystore instanceof Keystore)) { throw new HumanReadableException( "In %s, keystore='%s' must be a keystore() but was %s().", params.getBuildTarget(), args.keystore.getFullyQualifiedName(), args.keystore.getType().getName()); } Keystore keystore = (Keystore) args.keystore; ProGuardObfuscateStep.SdkProguardType androidSdkProguardConfig = args.androidSdkProguardConfig.or(ProGuardObfuscateStep.SdkProguardType.DEFAULT); // If the old boolean version of this argument was specified, make sure the new form // was not specified, and allow the old form to override the default. if (args.useAndroidProguardConfigWithOptimizations.isPresent()) { Preconditions.checkArgument( !args.androidSdkProguardConfig.isPresent(), "The deprecated use_android_proguard_config_with_optimizations parameter" + " cannot be used with android_sdk_proguard_config."); androidSdkProguardConfig = args.useAndroidProguardConfigWithOptimizations.or(false) ? ProGuardObfuscateStep.SdkProguardType.OPTIMIZED : ProGuardObfuscateStep.SdkProguardType.DEFAULT; } DexSplitMode dexSplitMode = createDexSplitMode(args); boolean allowNonExistentRule = false; ImmutableSortedSet<BuildRule> buildRulesToExcludeFromDex = BuildRules.toBuildRulesFor( params.getBuildTarget(), resolver, args.noDx.or(ImmutableSet.<BuildTarget>of()), allowNonExistentRule); ImmutableSortedSet<JavaLibrary> rulesToExcludeFromDex = FluentIterable.from(buildRulesToExcludeFromDex) .filter(JavaLibrary.class) .toSortedSet(HasBuildTarget.BUILD_TARGET_COMPARATOR); PackageType packageType = getPackageType(args); boolean shouldPreDex = !args.disablePreDex.or(false) && PackageType.DEBUG.equals(packageType) && !args.preprocessJavaClassesBash.isPresent(); ResourceCompressionMode compressionMode = getCompressionMode(args); ResourceFilter resourceFilter = new ResourceFilter(args.resourceFilter.or(ImmutableList.<String>of())); AndroidBinaryGraphEnhancer graphEnhancer = new AndroidBinaryGraphEnhancer( params, resolver, compressionMode, resourceFilter, args.manifest, packageType, ImmutableSet.copyOf(args.cpuFilters.get()), args.buildStringSourceMap.or(false), shouldPreDex, AndroidBinary.getPrimaryDexPath(params.getBuildTarget()), dexSplitMode, ImmutableSet.copyOf(args.noDx.or(ImmutableSet.<BuildTarget>of())), /* resourcesToExclude */ ImmutableSet.<BuildTarget>of(), javacOptions, args.exopackage.or(false), keystore, args.buildConfigValues.get(), args.buildConfigValuesFile); AndroidBinaryGraphEnhancer.EnhancementResult result = graphEnhancer.createAdditionalBuildables(); return new AndroidBinary( params.copyWithExtraDeps(result.getFinalDeps()), proguardJarOverride, args.manifest, args.target, keystore, packageType, dexSplitMode, args.noDx.or(ImmutableSet.<BuildTarget>of()), androidSdkProguardConfig, args.optimizationPasses, args.proguardConfig, compressionMode, args.cpuFilters.get(), resourceFilter, args.exopackage.or(false), args.preprocessJavaClassesDeps.or(ImmutableSet.<BuildRule>of()), args.preprocessJavaClassesBash, rulesToExcludeFromDex, result); } private DexSplitMode createDexSplitMode(Arg args) { DexSplitStrategy dexSplitStrategy = args.minimizePrimaryDexSize.or(false) ? DexSplitStrategy.MINIMIZE_PRIMARY_DEX_SIZE : DexSplitStrategy.MAXIMIZE_PRIMARY_DEX_SIZE; return new DexSplitMode( args.useSplitDex.or(false), dexSplitStrategy, args.dexCompression.or(DexStore.JAR), args.useLinearAllocSplitDex.or(false), args.linearAllocHardLimit.or(DEFAULT_LINEAR_ALLOC_HARD_LIMIT), args.primaryDexPatterns.or(ImmutableList.<String>of()), args.primaryDexClassesFile, args.primaryDexScenarioFile, args.primaryDexScenarioOverflowAllowed.or(false)); } private PackageType getPackageType(Arg args) { if (!args.packageType.isPresent()) { return PackageType.DEBUG; } return PackageType.valueOf(args.packageType.get().toUpperCase()); } private ResourceCompressionMode getCompressionMode(Arg args) { if (!args.resourceCompression.isPresent()) { return ResourceCompressionMode.DISABLED; } return ResourceCompressionMode.valueOf(args.resourceCompression.get().toUpperCase()); } @SuppressFieldNotInitialized public static class Arg implements ConstructorArg { public SourcePath manifest; public String target; public BuildRule keystore; public Optional<String> packageType; public Optional<Set<BuildTarget>> noDx; public Optional<Boolean> useSplitDex; public Optional<Boolean> useLinearAllocSplitDex; public Optional<Boolean> minimizePrimaryDexSize; public Optional<Boolean> disablePreDex; public Optional<Boolean> exopackage; public Optional<DexStore> dexCompression; public Optional<ProGuardObfuscateStep.SdkProguardType> androidSdkProguardConfig; public Optional<Boolean> useAndroidProguardConfigWithOptimizations; public Optional<Integer> optimizationPasses; public Optional<SourcePath> proguardConfig; public Optional<String> resourceCompression; public Optional<List<String>> primaryDexPatterns; public Optional<SourcePath> primaryDexClassesFile; public Optional<SourcePath> primaryDexScenarioFile; public Optional<Boolean> primaryDexScenarioOverflowAllowed; public Optional<Long> linearAllocHardLimit; public Optional<List<String>> resourceFilter; public Optional<Boolean> buildStringSourceMap; public Optional<Set<TargetCpuType>> cpuFilters; public Optional<Set<BuildRule>> preprocessJavaClassesDeps; public Optional<String> preprocessJavaClassesBash; /** This will never be absent after this Arg is populated. */ public Optional<BuildConfigFields> buildConfigValues; public Optional<SourcePath> buildConfigValuesFile; public Optional<ImmutableSortedSet<BuildRule>> deps; } }
src/com/facebook/buck/android/AndroidBinaryDescription.java
/* * Copyright 2014-present Facebook, Inc. * * 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.facebook.buck.android; import com.facebook.buck.android.AndroidBinary.PackageType; import com.facebook.buck.android.AndroidBinary.TargetCpuType; import com.facebook.buck.android.FilterResourcesStep.ResourceFilter; import com.facebook.buck.android.ResourcesFilter.ResourceCompressionMode; import com.facebook.buck.dalvik.ZipSplitter.DexSplitStrategy; import com.facebook.buck.java.JavaLibrary; import com.facebook.buck.java.JavacOptions; import com.facebook.buck.java.Keystore; import com.facebook.buck.model.BuildTarget; import com.facebook.buck.model.HasBuildTarget; import com.facebook.buck.rules.BuildRule; import com.facebook.buck.rules.BuildRuleParams; import com.facebook.buck.rules.BuildRuleResolver; import com.facebook.buck.rules.BuildRuleType; import com.facebook.buck.rules.BuildRules; import com.facebook.buck.rules.ConstructorArg; import com.facebook.buck.rules.Description; import com.facebook.buck.rules.SourcePath; import com.facebook.buck.rules.coercer.BuildConfigFields; import com.facebook.buck.util.HumanReadableException; import com.google.common.base.Optional; import com.google.common.base.Preconditions; import com.google.common.collect.FluentIterable; import com.google.common.collect.ImmutableList; import com.google.common.collect.ImmutableSet; import com.google.common.collect.ImmutableSortedSet; import java.nio.file.Path; import java.util.List; import java.util.Set; import com.facebook.infer.annotation.SuppressFieldNotInitialized; public class AndroidBinaryDescription implements Description<AndroidBinaryDescription.Arg> { public static final BuildRuleType TYPE = new BuildRuleType("android_binary"); /** * By default, assume we have 5MB of linear alloc, * 1MB of which is taken up by the framework, so that leaves 4MB. */ private static final long DEFAULT_LINEAR_ALLOC_HARD_LIMIT = 4 * 1024 * 1024; private final JavacOptions javacOptions; private final Optional<Path> proguardJarOverride; public AndroidBinaryDescription( JavacOptions javacOptions, Optional<Path> proguardJarOverride) { this.javacOptions = Preconditions.checkNotNull(javacOptions); this.proguardJarOverride = Preconditions.checkNotNull(proguardJarOverride); } @Override public BuildRuleType getBuildRuleType() { return TYPE; } @Override public Arg createUnpopulatedConstructorArg() { return new Arg(); } @Override public <A extends Arg> AndroidBinary createBuildRule( BuildRuleParams params, BuildRuleResolver resolver, A args) { if (!(args.keystore instanceof Keystore)) { throw new HumanReadableException( "In %s, keystore='%s' must be a keystore() but was %s().", params.getBuildTarget(), args.keystore.getFullyQualifiedName(), args.keystore.getType().getName()); } Keystore keystore = (Keystore) args.keystore; ProGuardObfuscateStep.SdkProguardType androidSdkProguardConfig = args.androidSdkProguardConfig.or(ProGuardObfuscateStep.SdkProguardType.DEFAULT); // If the old boolean version of this argument was specified, make sure the new form // was not specified, and allow the old form to override the default. if (args.useAndroidProguardConfigWithOptimizations.isPresent()) { Preconditions.checkArgument( !args.androidSdkProguardConfig.isPresent(), "The deprecated use_android_proguard_config_with_optimizations parameter" + " cannot be used with android_sdk_proguard_config."); androidSdkProguardConfig = args.useAndroidProguardConfigWithOptimizations.or(false) ? ProGuardObfuscateStep.SdkProguardType.OPTIMIZED : ProGuardObfuscateStep.SdkProguardType.DEFAULT; } DexSplitMode dexSplitMode = createDexSplitMode(args); boolean allowNonExistentRule = false; ImmutableSortedSet<BuildRule> buildRulesToExcludeFromDex = BuildRules.toBuildRulesFor( params.getBuildTarget(), resolver, args.noDx.or(ImmutableSet.<BuildTarget>of()), allowNonExistentRule); ImmutableSortedSet<JavaLibrary> rulesToExcludeFromDex = FluentIterable.from(buildRulesToExcludeFromDex) .filter(JavaLibrary.class) .toSortedSet(HasBuildTarget.BUILD_TARGET_COMPARATOR); PackageType packageType = getPackageType(args); boolean shouldPreDex = !args.disablePreDex.or(false) && PackageType.DEBUG.equals(packageType) && !args.preprocessJavaClassesBash.isPresent(); ResourceCompressionMode compressionMode = getCompressionMode(args); ResourceFilter resourceFilter = new ResourceFilter(args.resourceFilter.or(ImmutableList.<String>of())); AndroidBinaryGraphEnhancer graphEnhancer = new AndroidBinaryGraphEnhancer( params, resolver, compressionMode, resourceFilter, args.manifest, packageType, ImmutableSet.copyOf(args.cpuFilters.get()), args.buildStringSourceMap.or(false), shouldPreDex, AndroidBinary.getPrimaryDexPath(params.getBuildTarget()), dexSplitMode, ImmutableSet.copyOf(args.noDx.or(ImmutableSet.<BuildTarget>of())), /* resourcesToExclude */ ImmutableSet.<BuildTarget>of(), javacOptions, args.exopackage.or(false), keystore, args.buildConfigValues.get(), args.buildConfigValuesFile); AndroidBinaryGraphEnhancer.EnhancementResult result = graphEnhancer.createAdditionalBuildables(); return new AndroidBinary( params.copyWithExtraDeps(result.getFinalDeps()), proguardJarOverride, args.manifest, args.target, keystore, packageType, dexSplitMode, args.noDx.or(ImmutableSet.<BuildTarget>of()), androidSdkProguardConfig, args.optimizationPasses, args.proguardConfig, compressionMode, args.cpuFilters.get(), resourceFilter, args.exopackage.or(false), args.preprocessJavaClassesDeps.or(ImmutableSet.<BuildRule>of()), args.preprocessJavaClassesBash, rulesToExcludeFromDex, result); } private DexSplitMode createDexSplitMode(Arg args) { DexStore dexStore = "xz".equals(args.dexCompression.or("jar")) ? DexStore.XZ : DexStore.JAR; DexSplitStrategy dexSplitStrategy = args.minimizePrimaryDexSize.or(false) ? DexSplitStrategy.MINIMIZE_PRIMARY_DEX_SIZE : DexSplitStrategy.MAXIMIZE_PRIMARY_DEX_SIZE; return new DexSplitMode( args.useSplitDex.or(false), dexSplitStrategy, dexStore, args.useLinearAllocSplitDex.or(false), args.linearAllocHardLimit.or(DEFAULT_LINEAR_ALLOC_HARD_LIMIT), args.primaryDexPatterns.or(ImmutableList.<String>of()), args.primaryDexClassesFile, args.primaryDexScenarioFile, args.primaryDexScenarioOverflowAllowed.or(false)); } private PackageType getPackageType(Arg args) { if (!args.packageType.isPresent()) { return PackageType.DEBUG; } return PackageType.valueOf(args.packageType.get().toUpperCase()); } private ResourceCompressionMode getCompressionMode(Arg args) { if (!args.resourceCompression.isPresent()) { return ResourceCompressionMode.DISABLED; } return ResourceCompressionMode.valueOf(args.resourceCompression.get().toUpperCase()); } @SuppressFieldNotInitialized public static class Arg implements ConstructorArg { public SourcePath manifest; public String target; public BuildRule keystore; public Optional<String> packageType; public Optional<Set<BuildTarget>> noDx; public Optional<Boolean> useSplitDex; public Optional<Boolean> useLinearAllocSplitDex; public Optional<Boolean> minimizePrimaryDexSize; public Optional<Boolean> disablePreDex; public Optional<Boolean> exopackage; public Optional<String> dexCompression; public Optional<ProGuardObfuscateStep.SdkProguardType> androidSdkProguardConfig; public Optional<Boolean> useAndroidProguardConfigWithOptimizations; public Optional<Integer> optimizationPasses; public Optional<SourcePath> proguardConfig; public Optional<String> resourceCompression; public Optional<List<String>> primaryDexPatterns; public Optional<SourcePath> primaryDexClassesFile; public Optional<SourcePath> primaryDexScenarioFile; public Optional<Boolean> primaryDexScenarioOverflowAllowed; public Optional<Long> linearAllocHardLimit; public Optional<List<String>> resourceFilter; public Optional<Boolean> buildStringSourceMap; public Optional<Set<TargetCpuType>> cpuFilters; public Optional<Set<BuildRule>> preprocessJavaClassesDeps; public Optional<String> preprocessJavaClassesBash; /** This will never be absent after this Arg is populated. */ public Optional<BuildConfigFields> buildConfigValues; public Optional<SourcePath> buildConfigValuesFile; public Optional<ImmutableSortedSet<BuildRule>> deps; } }
Use a real Enum arg for dexCompression Summary: With the new enum coercer, we can use less code and make this more extensible at the same time! Test Plan: Buildbot.
src/com/facebook/buck/android/AndroidBinaryDescription.java
Use a real Enum arg for dexCompression
<ide><path>rc/com/facebook/buck/android/AndroidBinaryDescription.java <ide> } <ide> <ide> private DexSplitMode createDexSplitMode(Arg args) { <del> DexStore dexStore = "xz".equals(args.dexCompression.or("jar")) <del> ? DexStore.XZ <del> : DexStore.JAR; <ide> DexSplitStrategy dexSplitStrategy = args.minimizePrimaryDexSize.or(false) <ide> ? DexSplitStrategy.MINIMIZE_PRIMARY_DEX_SIZE <ide> : DexSplitStrategy.MAXIMIZE_PRIMARY_DEX_SIZE; <ide> return new DexSplitMode( <ide> args.useSplitDex.or(false), <ide> dexSplitStrategy, <del> dexStore, <add> args.dexCompression.or(DexStore.JAR), <ide> args.useLinearAllocSplitDex.or(false), <ide> args.linearAllocHardLimit.or(DEFAULT_LINEAR_ALLOC_HARD_LIMIT), <ide> args.primaryDexPatterns.or(ImmutableList.<String>of()), <ide> public Optional<Boolean> minimizePrimaryDexSize; <ide> public Optional<Boolean> disablePreDex; <ide> public Optional<Boolean> exopackage; <del> public Optional<String> dexCompression; <add> public Optional<DexStore> dexCompression; <ide> public Optional<ProGuardObfuscateStep.SdkProguardType> androidSdkProguardConfig; <ide> public Optional<Boolean> useAndroidProguardConfigWithOptimizations; <ide> public Optional<Integer> optimizationPasses;
Java
apache-2.0
27f8d11d70890016729b9d6956e7198ac4b23c57
0
smkniazi/hops,smkniazi/hops,smkniazi/hops,smkniazi/hops,smkniazi/hops,smkniazi/hops,hopshadoop/hops,hopshadoop/hops,hopshadoop/hops,hopshadoop/hops,hopshadoop/hops,smkniazi/hops,hopshadoop/hops,hopshadoop/hops,smkniazi/hops,hopshadoop/hops
/** * 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. */ package org.apache.hadoop.hdfs; import org.apache.hadoop.classification.InterfaceAudience; import org.apache.hadoop.fs.CommonConfigurationKeys; import org.apache.hadoop.hdfs.server.blockmanagement.BlockPlacementPolicyDefault; /** * This class contains constants for configuration keys used * in hdfs. */ @InterfaceAudience.Private public class DFSConfigKeys extends CommonConfigurationKeys { public static final String DFS_STORAGE_DRIVER_JAR_FILE = "dfs.storage.driver.jarFile"; public static final String DFS_STORAGE_DRIVER_JAR_FILE_DEFAULT = ""; public static final String DFS_STORAGE_DRIVER_CLASS = "dfs.storage.driver.class"; public static final String DFS_STORAGE_DRIVER_CLASS_DEFAULT = "io.hops.metadata.ndb.NdbStorageFactory"; public static final String DFS_STORAGE_DRIVER_CONFIG_FILE = "dfs.storage.driver.configfile"; public static final String DFS_STORAGE_DRIVER_CONFIG_FILE_DEFAULT = "ndb-config.properties"; public static final String DFS_STORAGE_ANCESTOR_LOCK_TYPE = "dfs.storage.ancestor.lock.type"; public static final String DFS_STORAGE_ANCESTOR_LOCK_TYPE_DEFAULT = "READ_COMMITTED"; // "READ" | "READ_COMMITTED" public static final String DFS_NAMENODE_QUOTA_ENABLED_KEY = "dfs.namenode.quota.enabled"; public static final boolean DFS_NAMENODE_QUOTA_ENABLED_DEFAULT = true; public static final String DFS_NAMENODE_QUOTA_UPDATE_INTERVAL_KEY = "dfs.namenode.quota.update.interval"; public static final int DFS_NAMENODE_QUOTA_UPDATE_INTERVAL_DEFAULT = 1000; public static final String DFS_NAMENODE_QUOTA_UPDATE_LIMIT_KEY = "dfs.namenode.quota.update.limit"; public static final int DFS_NAMENODE_QUOTA_UPDATE_LIMIT_DEFAULT = 100000; public static final String DFS_NAMENODE_QUOTA_UPDATE_ID_BATCH_SIZE = "dfs.namenode.quota.update.id.batchsize"; public static final int DFS_NAMENODE_QUOTA_UPDATE_ID_BATCH_SIZ_DEFAULT = 100000; public static final String DFS_NAMENODE_QUOTA_UPDATE_ID_UPDATE_THRESHOLD = "dfs.namenode.quota.update.updateThreshold"; public static final float DFS_NAMENODE_QUOTA_UPDATE_ID_UPDATE_THRESHOLD_DEFAULT = (float) 0.5; public static final String DFS_NAMENODE_INODEID_BATCH_SIZE = "dfs.namenode.inodeid.batchsize"; public static final int DFS_NAMENODE_INODEID_BATCH_SIZE_DEFAULT = 1000; public static final String DFS_NAMENODE_BLOCKID_BATCH_SIZE = "dfs.namenode.blockid.batchsize"; public static final int DFS_NAMENODE_BLOCKID_BATCH_SIZE_DEFAULT = 1000; public static final String DFS_NAMENODE_INODEID_UPDATE_THRESHOLD = "dfs.namenode.inodeid.updateThreshold"; public static final float DFS_NAMENODE_INODEID_UPDATE_THRESHOLD_DEFAULT = (float) 0.5; public static final String DFS_NAMENODE_BLOCKID_UPDATE_THRESHOLD = "dfs.namenode.blockid.updateThreshold"; public static final float DFS_NAMENODE_BLOCKID_UPDATE_THRESHOLD_DEFAULT = (float) 0.5; public static final String DFS_NAMENODE_IDSMONITOR_CHECK_INTERVAL_IN_MS = "dfs.namenode.id.updateThreshold"; public static final int DFS_NAMENODE_IDSMONITOR_CHECK_INTERVAL_IN_MS_DEFAULT = 1000; public static final String DFS_NAMENODE_PROCESS_REPORT_BATCH_SIZE = "dfs.namenode.processReport.batchsize"; public static final int DFS_NAMENODE_PROCESS_REPORT_BATCH_SIZE_DEFAULT = 5000; public static final String DFS_NAMENODE_PROCESS_MISREPLICATED_BATCH_SIZE = "dfs.namenode.misreplicated.batchsize"; public static final int DFS_NAMENODE_PROCESS_MISREPLICATED_BATCH_SIZE_DEFAULT = 500; public static final String DFS_NAMENODE_PROCESS_MISREPLICATED_NO_OF_BATCHS = "dfs.namenode.misreplicated.noofbatches"; public static final int DFS_NAMENODE_PROCESS_MISREPLICATED_NO_OF_BATCHS_DEFAULT = 10; public static final String DFS_TRANSACTION_STATS_ENABLED = "dfs.transaction.stats.enabled"; public static final boolean DFS_TRANSACTION_STATS_ENABLED_DEFAULT = false; public static final String DFS_TRANSACTION_STATS_DETAILED_ENABLED = "dfs.transaction.stats.detailed.enabled"; public static final boolean DFS_TRANSACTION_STATS_DETAILED_ENABLED_DEFAULT = false; public static final String DFS_TRANSACTION_STATS_DIR = "dfs.transaction.stats.dir"; public static final String DFS_TRANSACTION_STATS_DIR_DEFAULT = "/tmp/hopsstats"; public static final String DFS_TRANSACTION_STATS_WRITER_ROUND = "dfs.transaction.stats.writerround"; public static final int DFS_TRANSACTION_STATS_WRITER_ROUND_DEFAULT = 120; public static final String DFS_DIR_DELETE_BATCH_SIZE= "dfs.dir.delete.batch.size"; public static final int DFS_DIR_DELETE_BATCH_SIZE_DEFAULT = 50; /*for client failover api*/ // format {ip:port, ip:port, ip:port} comma separated public static final String DFS_NAMENODES_RPC_ADDRESS_KEY = "dfs.namenodes.rpc.addresses"; public static final String DFS_NAMENODES_RPC_ADDRESS_DEFAULT = ""; // format {ip:port, ip:port, ip:port} comma separated public static final String DFS_NAMENODES_SERVICE_RPC_ADDRESS_KEY = "dfs.namenodes.servicerpc.addresses"; public static final String DFS_NAMENODE_SELECTOR_POLICY_KEY = "dfs.namenode.selector-policy"; public static final String DFS_NAMENODE_SELECTOR_POLICY_DEFAULT = "RANDOM_STICKY"; //RANDOM ROUND_ROBIN RANDOM_STICKY public static final String DFS_BLOCK_POOL_ID_KEY = "dfs.block.pool.id"; public static final String DFS_BLOCK_POOL_ID_DEFAULT = "HOP_BLOCK_POOL_123"; public static final String DFS_NAME_SPACE_ID_KEY = "dfs.name.space.id"; public static final int DFS_NAME_SPACE_ID_DEFAULT = 911; // :) public static final String DFS_CLIENT_RETRIES_ON_FAILURE_KEY = "dfs.client.max.retries.on.failure"; public static final int DFS_CLIENT_RETRIES_ON_FAILURE_DEFAULT = 2; //min value is 0. Better set it >= 1 public static final String DFS_NAMENODE_TX_RETRY_COUNT_KEY = "dfs.namenode.tx.retry.count"; public static final int DFS_NAMENODE_TX_RETRY_COUNT_DEFAULT = 5; public static final String DFS_NAMENODE_TX_INITIAL_WAIT_TIME_BEFORE_RETRY_KEY = "dfs.namenode.tx.initial.wait.time.before.retry"; public static final int DFS_NAMENODE_TX_INITIAL_WAIT_TIME_BEFORE_RETRY_DEFAULT = 2000; public static final String DFS_CLIENT_INITIAL_WAIT_ON_RETRY_IN_MS_KEY = "dfs.client.initial.wait.on.retry"; public static final int DFS_CLIENT_INITIAL_WAIT_ON_RETRY_IN_MS_DEFAULT = 1000; public static final String DFS_CLIENT_REFRESH_NAMENODE_LIST_IN_MS_KEY = "dfs.client.refresh.namenode.list"; public static final int DFS_CLIENT_REFRESH_NAMENODE_LIST_IN_MS_DEFAULT = 60 * 1000; //time in milliseconds. public static final String DFS_SET_PARTITION_KEY_ENABLED = "dfs.ndb.setpartitionkey.enabled"; public static final boolean DFS_SET_PARTITION_KEY_ENABLED_DEFAULT = true; public static final String DFS_SET_RANDOM_PARTITION_KEY_ENABLED = "dfs.ndb.setrandompartitionkey.enabled"; public static final boolean DFS_SET_RANDOM_PARTITION_KEY_ENABLED_DEFAULT = true; public static final String DFS_RESOLVING_CACHE_ENABLED = "dfs" + ".resolvingcache.enabled"; public static final boolean DFS_RESOLVING_CACHE_ENABLED_DEFAULT = true; public static final String DFS_MEMCACHE_SERVER = "dfs.resolvingcache.memcache.server.address"; public static final String DFS_MEMCACHE_SERVER_DEFAULT = "127.0.0.1:11212"; public static final String DFS_MEMCACHE_CONNECTION_POOL_SIZE = "dfs.resolvingcache.memcache.connectionpool.size"; public static final int DFS_MEMCACHE_CONNECTION_POOL_SIZE_DEFAULT = 10; public static final String DFS_MEMCACHE_KEY_PREFIX = "dfs.resolvingcache.memcache.key.prefix"; public static final String DFS_MEMCACHE_KEY_PREFIX_DEFAULT = "p:"; public static final String DFS_MEMCACHE_KEY_EXPIRY_IN_SECONDS = "dfs.resolvingcache.memcache.key.expiry"; public static final int DFS_MEMCACHE_KEY_EXPIRY_IN_SECONDS_DEFAULT = 0; public static final String DFS_RESOLVING_CACHE_TYPE = "dfs.resolvingcache" + ".type"; //INode, Path, InMemory, Optimal public static final String DFS_RESOLVING_CACHE_TYPE_DEFAULT = "InMemory"; public static final String DFS_INMEMORY_CACHE_MAX_SIZE = "dfs" + ".resolvingcache.inmemory.maxsize"; public static final int DFS_INMEMORY_CACHE_MAX_SIZE_DEFAULT = 100000; public static final String DFS_NDC_ENABLED_KEY = "dfs.ndc.enable"; public static final boolean DFS_NDC_ENABLED_DEFAULT = false; public static final String DFS_SUBTREE_EXECUTOR_LIMIT_KEY = "dfs.namenode.subtree-executor-limit"; public static final int DFS_SUBTREE_EXECUTOR_LIMIT_DEFAULT = 80; public static final String ERASURE_CODING_CODECS_KEY = "dfs.erasure_coding.codecs.json"; public static final String ERASURE_CODING_ENABLED_KEY = "dfs.erasure_coding.enabled"; public static final boolean DEFAULT_ERASURE_CODING_ENABLED_KEY = false; public static final String PARITY_FOLDER = "dfs.erasure_coding.parity_folder"; public static final String DEFAULT_PARITY_FOLDER = "/parity"; public static final String ENCODING_MANAGER_CLASSNAME_KEY = "dfs.erasure_coding.encoding_manager"; public static final String DEFAULT_ENCODING_MANAGER_CLASSNAME = "io.hops.erasure_coding.MapReduceEncodingManager"; public static final String BLOCK_REPAIR_MANAGER_CLASSNAME_KEY = "dfs.erasure_coding.block_rapair_manager"; public static final String DEFAULT_BLOCK_REPAIR_MANAGER_CLASSNAME = "io.hops.erasure_coding.MapReduceBlockRepairManager"; public static final String RECHECK_INTERVAL_KEY = "dfs.erasure_coding.recheck_interval"; public static final int DEFAULT_RECHECK_INTERVAL = 5 * 60 * 1000; public static final String ACTIVE_ENCODING_LIMIT_KEY = "dfs.erasure_coding.active_encoding_limit"; public static final int DEFAULT_ACTIVE_ENCODING_LIMIT = 10; public static final String ACTIVE_REPAIR_LIMIT_KEY = "dfs.erasure_coding.active_repair_limit"; public static final int DEFAULT_ACTIVE_REPAIR_LIMIT = 10; public static final String REPAIR_DELAY_KEY = "dfs.erasure_coding.repair_delay"; public static final int DEFAULT_REPAIR_DELAY_KEY = 30 * 60 * 1000; public static final String ACTIVE_PARITY_REPAIR_LIMIT_KEY = "dfs.erasure_coding.active_parity_repair_limit"; public static final int DEFAULT_ACTIVE_PARITY_REPAIR_LIMIT = 10; public static final String PARITY_REPAIR_DELAY_KEY = "dfs.erasure_coding.parity_repair_delay"; public static final int DEFAULT_PARITY_REPAIR_DELAY = 30 * 60 * 1000; public static final String DELETION_LIMIT_KEY = "dfs.erasure_coding.deletion_limit"; public static final int DEFAULT_DELETION_LIMIT = 100; public static final String DFS_BR_LB_MAX_BLK_PER_TW = "dfs.block.report.load.balancing.max.blks.per.time.window"; public static final long DFS_BR_LB_MAX_BLK_PER_TW_DEFAULT = 1000000; public static final String DFS_BR_LB_TIME_WINDOW_SIZE = "dfs.block.report.load.balancing.time.window.size"; public static final long DFS_BR_LB_TIME_WINDOW_SIZE_DEFAULT = 60*1000; //1 min public static final String DFS_BR_LB_DB_VAR_UPDATE_THRESHOLD = "dfs.blk.report.load.balancing.db.var.update.threashold"; public static final long DFS_BR_LB_DB_VAR_UPDATE_THRESHOLD_DEFAULT = 60*1000; public static final String DFS_STORE_SMALL_FILES_IN_DB_KEY = "dfs.store.small.files.in.db"; public static final boolean DFS_STORE_SMALL_FILES_IN_DB_DEFAULT = false; public static final String DFS_DB_ONDISK_SMALL_FILE_MAX_SIZE_KEY = "dfs.db.ondisk.small.file.max.size"; public static final int DFS_DB_ONDISK_SMALL_FILE_MAX_SIZE_DEFAULT = 2000; public static final String DFS_DB_ONDISK_MEDIUM_FILE_MAX_SIZE_KEY = "dfs.db.ondisk.medium.file.max.size"; public static final int DFS_DB_ONDISK_MEDIUM_FILE_MAX_SIZE_DEFAULT = 4000; public static final String DFS_DB_ONDISK_LARGE_FILE_MAX_SIZE_KEY = "dfs.db.ondisk.large.file.max.size"; public static final int DFS_DB_ONDISK_LARGE_FILE_MAX_SIZE_DEFAULT = 64*1024; public static final String DFS_DB_FILE_MAX_SIZE_KEY = "dfs.db.file.max.size"; public static final int DFS_DB_FILE_MAX_SIZE_DEFAULT = 64 * 1024; public static final String DFS_DB_INMEMORY_FILE_MAX_SIZE_KEY = "dfs.db.inmemory.file.max.size"; public static final int DFS_DB_INMEMORY_FILE_MAX_SIZE_DEFAULT = 1*1024; // 1KB public static final String DFS_DN_INCREMENTAL_BR_DISPATCHER_THREAD_POOL_SIZE_KEY = "dfs.dn.incremental.br.thread.pool.size"; public static final int DFS_DN_INCREMENTAL_BR_DISPATCHER_THREAD_POOL_SIZE_DEFAULT = 256; public static final String DFS_CLIENT_DELAY_BEFORE_FILE_CLOSE_KEY = "dsf.client.delay.before.file.close"; public static final int DFS_CLIENT_DELAY_BEFORE_FILE_CLOSE_DEFAULT = 0; public static final String DFS_BLOCK_SIZE_KEY = "dfs.blocksize"; public static final long DFS_BLOCK_SIZE_DEFAULT = 128 * 1024 * 1024; public static final String DFS_REPLICATION_KEY = "dfs.replication"; public static final short DFS_REPLICATION_DEFAULT = 3; public static final String DFS_STREAM_BUFFER_SIZE_KEY = "dfs.stream-buffer-size"; public static final int DFS_STREAM_BUFFER_SIZE_DEFAULT = 4096; public static final String DFS_BYTES_PER_CHECKSUM_KEY = "dfs.bytes-per-checksum"; public static final int DFS_BYTES_PER_CHECKSUM_DEFAULT = 512; public static final String DFS_CLIENT_RETRY_POLICY_ENABLED_KEY = "dfs.client.retry.policy.enabled"; public static final boolean DFS_CLIENT_RETRY_POLICY_ENABLED_DEFAULT = false; public static final String DFS_CLIENT_RETRY_POLICY_SPEC_KEY = "dfs.client.retry.policy.spec"; public static final String DFS_CLIENT_RETRY_POLICY_SPEC_DEFAULT = "10000,6,60000,10"; //t1,n1,t2,n2,... public static final String DFS_CHECKSUM_TYPE_KEY = "dfs.checksum.type"; public static final String DFS_CHECKSUM_TYPE_DEFAULT = "CRC32C"; public static final String DFS_CLIENT_WRITE_PACKET_SIZE_KEY = "dfs.client-write-packet-size"; public static final int DFS_CLIENT_WRITE_PACKET_SIZE_DEFAULT = 64 * 1024; public static final String DFS_CLIENT_WRITE_REPLACE_DATANODE_ON_FAILURE_ENABLE_KEY = "dfs.client.block.write.replace-datanode-on-failure.enable"; public static final boolean DFS_CLIENT_WRITE_REPLACE_DATANODE_ON_FAILURE_ENABLE_DEFAULT = true; public static final String DFS_CLIENT_WRITE_REPLACE_DATANODE_ON_FAILURE_POLICY_KEY = "dfs.client.block.write.replace-datanode-on-failure.policy"; public static final String DFS_CLIENT_WRITE_REPLACE_DATANODE_ON_FAILURE_POLICY_DEFAULT = "DEFAULT"; public static final String DFS_CLIENT_SOCKET_CACHE_CAPACITY_KEY = "dfs.client.socketcache.capacity"; public static final int DFS_CLIENT_SOCKET_CACHE_CAPACITY_DEFAULT = 16; public static final String DFS_CLIENT_USE_DN_HOSTNAME = "dfs.client.use.datanode.hostname"; public static final boolean DFS_CLIENT_USE_DN_HOSTNAME_DEFAULT = false; public static final String DFS_CLIENT_CACHE_DROP_BEHIND_WRITES = "dfs.client.cache.drop.behind.writes"; public static final String DFS_CLIENT_CACHE_DROP_BEHIND_READS = "dfs.client.cache.drop.behind.reads"; public static final String DFS_CLIENT_CACHE_READAHEAD = "dfs.client.cache.readahead"; public static final String DFS_HDFS_BLOCKS_METADATA_ENABLED = "dfs.datanode.hdfs-blocks-metadata.enabled"; public static final boolean DFS_HDFS_BLOCKS_METADATA_ENABLED_DEFAULT = false; public static final String DFS_CLIENT_FILE_BLOCK_STORAGE_LOCATIONS_NUM_THREADS = "dfs.client.file-block-storage-locations.num-threads"; public static final int DFS_CLIENT_FILE_BLOCK_STORAGE_LOCATIONS_NUM_THREADS_DEFAULT = 10; public static final String DFS_CLIENT_FILE_BLOCK_STORAGE_LOCATIONS_TIMEOUT = "dfs.client.file-block-storage-locations.timeout"; public static final int DFS_CLIENT_FILE_BLOCK_STORAGE_LOCATIONS_TIMEOUT_DEFAULT = 60; // HA related configuration public static final String DFS_CLIENT_FAILOVER_PROXY_PROVIDER_KEY_PREFIX = "dfs.client.failover.proxy.provider"; public static final String DFS_CLIENT_FAILOVER_MAX_ATTEMPTS_KEY = "dfs.client.failover.max.attempts"; public static final int DFS_CLIENT_FAILOVER_MAX_ATTEMPTS_DEFAULT = 15; public static final String DFS_CLIENT_FAILOVER_SLEEPTIME_BASE_KEY = "dfs.client.failover.sleep.base.millis"; public static final int DFS_CLIENT_FAILOVER_SLEEPTIME_BASE_DEFAULT = 500; public static final String DFS_CLIENT_FAILOVER_SLEEPTIME_MAX_KEY = "dfs.client.failover.sleep.max.millis"; public static final int DFS_CLIENT_FAILOVER_SLEEPTIME_MAX_DEFAULT = 15000; public static final String DFS_CLIENT_FAILOVER_CONNECTION_RETRIES_KEY = "dfs.client.failover.connection.retries"; public static final int DFS_CLIENT_FAILOVER_CONNECTION_RETRIES_DEFAULT = 0; public static final String DFS_CLIENT_FAILOVER_CONNECTION_RETRIES_ON_SOCKET_TIMEOUTS_KEY = "dfs.client.failover.connection.retries.on.timeouts"; public static final int DFS_CLIENT_FAILOVER_CONNECTION_RETRIES_ON_SOCKET_TIMEOUTS_DEFAULT = 0; public static final String DFS_CLIENT_SOCKET_CACHE_EXPIRY_MSEC_KEY = "dfs.client.socketcache.expiryMsec"; public static final long DFS_CLIENT_SOCKET_CACHE_EXPIRY_MSEC_DEFAULT = 2 * 60 * 1000; public static final String DFS_DATANODE_BALANCE_BANDWIDTHPERSEC_KEY = "dfs.datanode.balance.bandwidthPerSec"; public static final long DFS_DATANODE_BALANCE_BANDWIDTHPERSEC_DEFAULT = 1024 * 1024; public static final String DFS_DATANODE_BALANCE_MAX_NUM_CONCURRENT_MOVES_KEY = "dfs.datanode.balance.max.concurrent.moves"; public static final int DFS_DATANODE_BALANCE_MAX_NUM_CONCURRENT_MOVES_DEFAULT = 5; public static final String DFS_DATANODE_READAHEAD_BYTES_KEY = "dfs.datanode.readahead.bytes"; public static final long DFS_DATANODE_READAHEAD_BYTES_DEFAULT = 4 * 1024 * 1024; // 4MB public static final String DFS_DATANODE_DROP_CACHE_BEHIND_WRITES_KEY = "dfs.datanode.drop.cache.behind.writes"; public static final boolean DFS_DATANODE_DROP_CACHE_BEHIND_WRITES_DEFAULT = false; public static final String DFS_DATANODE_SYNC_BEHIND_WRITES_KEY = "dfs.datanode.sync.behind.writes"; public static final boolean DFS_DATANODE_SYNC_BEHIND_WRITES_DEFAULT = false; public static final String DFS_DATANODE_DROP_CACHE_BEHIND_READS_KEY = "dfs.datanode.drop.cache.behind.reads"; public static final boolean DFS_DATANODE_DROP_CACHE_BEHIND_READS_DEFAULT = false; public static final String DFS_DATANODE_USE_DN_HOSTNAME = "dfs.datanode.use.datanode.hostname"; public static final boolean DFS_DATANODE_USE_DN_HOSTNAME_DEFAULT = false; public static final String DFS_NAMENODE_HTTP_PORT_KEY = "dfs.http.port"; public static final int DFS_NAMENODE_HTTP_PORT_DEFAULT = 50070; public static final String DFS_NAMENODE_HTTP_ADDRESS_KEY = "dfs.namenode.http-address"; public static final String DFS_NAMENODE_HTTP_ADDRESS_DEFAULT = "0.0.0.0:" + DFS_NAMENODE_HTTP_PORT_DEFAULT; public static final String DFS_NAMENODE_RPC_ADDRESS_KEY = "dfs.namenode.rpc-address"; public static final String DFS_NAMENODE_SERVICE_RPC_ADDRESS_KEY = "dfs.namenode.servicerpc-address"; public static final String DFS_NAMENODE_MAX_OBJECTS_KEY = "dfs.namenode.max.objects"; public static final long DFS_NAMENODE_MAX_OBJECTS_DEFAULT = 0; public static final String DFS_NAMENODE_SAFEMODE_EXTENSION_KEY = "dfs.namenode.safemode.extension"; public static final int DFS_NAMENODE_SAFEMODE_EXTENSION_DEFAULT = 30000; public static final String DFS_NAMENODE_SAFEMODE_THRESHOLD_PCT_KEY = "dfs.namenode.safemode.threshold-pct"; public static final float DFS_NAMENODE_SAFEMODE_THRESHOLD_PCT_DEFAULT = 0.999f; // set this to a slightly smaller value than // DFS_NAMENODE_SAFEMODE_THRESHOLD_PCT_DEFAULT to populate // needed replication queues before exiting safe mode public static final String DFS_NAMENODE_REPL_QUEUE_THRESHOLD_PCT_KEY = "dfs.namenode.replqueue.threshold-pct"; public static final String DFS_NAMENODE_SAFEMODE_MIN_DATANODES_KEY = "dfs.namenode.safemode.min.datanodes"; public static final int DFS_NAMENODE_SAFEMODE_MIN_DATANODES_DEFAULT = 0; public static final String DFS_NAMENODE_HEARTBEAT_RECHECK_INTERVAL_KEY = "dfs.namenode.heartbeat.recheck-interval"; public static final int DFS_NAMENODE_HEARTBEAT_RECHECK_INTERVAL_DEFAULT = 5 * 60 * 1000; public static final String DFS_NAMENODE_TOLERATE_HEARTBEAT_MULTIPLIER_KEY = "dfs.namenode.tolerate.heartbeat.multiplier"; public static final int DFS_NAMENODE_TOLERATE_HEARTBEAT_MULTIPLIER_DEFAULT = 4; public static final String DFS_CLIENT_HTTPS_KEYSTORE_RESOURCE_KEY = "dfs.client.https.keystore.resource"; public static final String DFS_CLIENT_HTTPS_KEYSTORE_RESOURCE_DEFAULT = "ssl-client.xml"; public static final String DFS_CLIENT_HTTPS_NEED_AUTH_KEY = "dfs.client.https.need-auth"; public static final boolean DFS_CLIENT_HTTPS_NEED_AUTH_DEFAULT = false; public static final String DFS_CLIENT_CACHED_CONN_RETRY_KEY = "dfs.client.cached.conn.retry"; public static final int DFS_CLIENT_CACHED_CONN_RETRY_DEFAULT = 3; public static final String DFS_NAMENODE_ACCESSTIME_PRECISION_KEY = "dfs.namenode.accesstime.precision"; public static final long DFS_NAMENODE_ACCESSTIME_PRECISION_DEFAULT = 3600000; public static final String DFS_NAMENODE_REPLICATION_CONSIDERLOAD_KEY = "dfs.namenode.replication.considerLoad"; public static final boolean DFS_NAMENODE_REPLICATION_CONSIDERLOAD_DEFAULT = true; public static final String DFS_NAMENODE_REPLICATION_INTERVAL_KEY = "dfs.namenode.replication.interval"; public static final int DFS_NAMENODE_REPLICATION_INTERVAL_DEFAULT = 3; public static final String DFS_NAMENODE_REPLICATION_MIN_KEY = "dfs.namenode.replication.min"; public static final int DFS_NAMENODE_REPLICATION_MIN_DEFAULT = 1; public static final String DFS_NAMENODE_REPLICATION_PENDING_TIMEOUT_SEC_KEY = "dfs.namenode.replication.pending.timeout-sec"; public static final int DFS_NAMENODE_REPLICATION_PENDING_TIMEOUT_SEC_DEFAULT = -1; public static final String DFS_NAMENODE_REPLICATION_MAX_STREAMS_KEY = "dfs.namenode.replication.max-streams"; public static final int DFS_NAMENODE_REPLICATION_MAX_STREAMS_DEFAULT = 2; public static final String DFS_NAMENODE_REPLICATION_STREAMS_HARD_LIMIT_KEY = "dfs.namenode.replication.max-streams-hard-limit"; public static final int DFS_NAMENODE_REPLICATION_STREAMS_HARD_LIMIT_DEFAULT = 4; public static final String DFS_WEBHDFS_ENABLED_KEY = "dfs.webhdfs.enabled"; public static final boolean DFS_WEBHDFS_ENABLED_DEFAULT = false; public static final String DFS_PERMISSIONS_ENABLED_KEY = "dfs.permissions.enabled"; public static final boolean DFS_PERMISSIONS_ENABLED_DEFAULT = true; public static final String DFS_PERSIST_BLOCKS_KEY = "dfs.persist.blocks"; public static final boolean DFS_PERSIST_BLOCKS_DEFAULT = false; public static final String DFS_PERMISSIONS_SUPERUSERGROUP_KEY = "dfs.permissions.superusergroup"; public static final String DFS_PERMISSIONS_SUPERUSERGROUP_DEFAULT = "supergroup"; public static final String DFS_ADMIN = "dfs.cluster.administrators"; public static final String DFS_SERVER_HTTPS_KEYSTORE_RESOURCE_KEY = "dfs.https.server.keystore.resource"; public static final String DFS_SERVER_HTTPS_KEYSTORE_RESOURCE_DEFAULT = "ssl-server.xml"; public static final String DFS_NAMENODE_NAME_DIR_RESTORE_KEY = "dfs.namenode.name.dir.restore"; public static final boolean DFS_NAMENODE_NAME_DIR_RESTORE_DEFAULT = false; public static final String DFS_NAMENODE_SUPPORT_ALLOW_FORMAT_KEY = "dfs.namenode.support.allow.format"; public static final boolean DFS_NAMENODE_SUPPORT_ALLOW_FORMAT_DEFAULT = true; public static final String DFS_NAMENODE_MIN_SUPPORTED_DATANODE_VERSION_KEY = "dfs.namenode.min.supported.datanode.version"; public static final String DFS_NAMENODE_MIN_SUPPORTED_DATANODE_VERSION_DEFAULT = "2.1.0-beta"; public static final String DFS_LIST_LIMIT = "dfs.ls.limit"; public static final int DFS_LIST_LIMIT_DEFAULT = Integer.MAX_VALUE; //1000; [HopsFS] Jira Hops-45 public static final String DFS_DATANODE_FAILED_VOLUMES_TOLERATED_KEY = "dfs.datanode.failed.volumes.tolerated"; public static final int DFS_DATANODE_FAILED_VOLUMES_TOLERATED_DEFAULT = 0; public static final String DFS_DATANODE_SYNCONCLOSE_KEY = "dfs.datanode.synconclose"; public static final boolean DFS_DATANODE_SYNCONCLOSE_DEFAULT = false; public static final String DFS_DATANODE_SOCKET_REUSE_KEEPALIVE_KEY = "dfs.datanode.socket.reuse.keepalive"; public static final int DFS_DATANODE_SOCKET_REUSE_KEEPALIVE_DEFAULT = 1000; public static final String DFS_NAMENODE_DATANODE_REGISTRATION_IP_HOSTNAME_CHECK_KEY = "dfs.namenode.datanode.registration.ip-hostname-check"; public static final boolean DFS_NAMENODE_DATANODE_REGISTRATION_IP_HOSTNAME_CHECK_DEFAULT = true; // Whether to enable datanode's stale state detection and usage for reads public static final String DFS_NAMENODE_AVOID_STALE_DATANODE_FOR_READ_KEY = "dfs.namenode.avoid.read.stale.datanode"; public static final boolean DFS_NAMENODE_AVOID_STALE_DATANODE_FOR_READ_DEFAULT = false; // Whether to enable datanode's stale state detection and usage for writes public static final String DFS_NAMENODE_AVOID_STALE_DATANODE_FOR_WRITE_KEY = "dfs.namenode.avoid.write.stale.datanode"; public static final boolean DFS_NAMENODE_AVOID_STALE_DATANODE_FOR_WRITE_DEFAULT = false; // The default value of the time interval for marking datanodes as stale public static final String DFS_NAMENODE_STALE_DATANODE_INTERVAL_KEY = "dfs.namenode.stale.datanode.interval"; public static final long DFS_NAMENODE_STALE_DATANODE_INTERVAL_DEFAULT = 30 * 1000; // 30s // The stale interval cannot be too small since otherwise this may cause too frequent churn on stale states. // This value uses the times of heartbeat interval to define the minimum value for stale interval. public static final String DFS_NAMENODE_STALE_DATANODE_MINIMUM_INTERVAL_KEY = "dfs.namenode.stale.datanode.minimum.interval"; public static final int DFS_NAMENODE_STALE_DATANODE_MINIMUM_INTERVAL_DEFAULT = 3; // i.e. min_interval is 3 * heartbeat_interval = 9s // When the percentage of stale datanodes reaches this ratio, // allow writing to stale nodes to prevent hotspots. public static final String DFS_NAMENODE_USE_STALE_DATANODE_FOR_WRITE_RATIO_KEY = "dfs.namenode.write.stale.datanode.ratio"; public static final float DFS_NAMENODE_USE_STALE_DATANODE_FOR_WRITE_RATIO_DEFAULT = 0.5f; // Replication monitoring related keys public static final String DFS_NAMENODE_INVALIDATE_WORK_PCT_PER_ITERATION = "dfs.namenode.invalidate.work.pct.per.iteration"; public static final float DFS_NAMENODE_INVALIDATE_WORK_PCT_PER_ITERATION_DEFAULT = 0.32f; public static final String DFS_NAMENODE_REPLICATION_WORK_MULTIPLIER_PER_ITERATION = "dfs.namenode.replication.work.multiplier.per.iteration"; public static final int DFS_NAMENODE_REPLICATION_WORK_MULTIPLIER_PER_ITERATION_DEFAULT = 2; //Delegation token related keys public static final String DFS_NAMENODE_DELEGATION_KEY_UPDATE_INTERVAL_KEY = "dfs.namenode.delegation.key.update-interval"; public static final long DFS_NAMENODE_DELEGATION_KEY_UPDATE_INTERVAL_DEFAULT = 24 * 60 * 60 * 1000; // 1 day public static final String DFS_NAMENODE_DELEGATION_TOKEN_RENEW_INTERVAL_KEY = "dfs.namenode.delegation.token.renew-interval"; public static final long DFS_NAMENODE_DELEGATION_TOKEN_RENEW_INTERVAL_DEFAULT = 24 * 60 * 60 * 1000; // 1 day public static final String DFS_NAMENODE_DELEGATION_TOKEN_MAX_LIFETIME_KEY = "dfs.namenode.delegation.token.max-lifetime"; public static final long DFS_NAMENODE_DELEGATION_TOKEN_MAX_LIFETIME_DEFAULT = 7 * 24 * 60 * 60 * 1000; // 7 days public static final String DFS_NAMENODE_DELEGATION_TOKEN_ALWAYS_USE_KEY = "dfs.namenode.delegation.token.always-use"; // for tests public static final boolean DFS_NAMENODE_DELEGATION_TOKEN_ALWAYS_USE_DEFAULT = false; //Filesystem limit keys public static final String DFS_NAMENODE_MAX_COMPONENT_LENGTH_KEY = "dfs.namenode.fs-limits.max-component-length"; public static final int DFS_NAMENODE_MAX_COMPONENT_LENGTH_DEFAULT = 0; // no limit public static final String DFS_NAMENODE_MAX_DIRECTORY_ITEMS_KEY = "dfs.namenode.fs-limits.max-directory-items"; public static final int DFS_NAMENODE_MAX_DIRECTORY_ITEMS_DEFAULT = 0; public static final String DFS_NAMENODE_MIN_BLOCK_SIZE_KEY = "dfs.namenode.fs-limits.min-block-size"; public static final long DFS_NAMENODE_MIN_BLOCK_SIZE_DEFAULT = 1024*1024; public static final String DFS_NAMENODE_MAX_BLOCKS_PER_FILE_KEY = "dfs.namenode.fs-limits.max-blocks-per-file"; public static final long DFS_NAMENODE_MAX_BLOCKS_PER_FILE_DEFAULT = 1024*1024; //Following keys have no defaults public static final String DFS_DATANODE_DATA_DIR_KEY = "dfs.datanode.data.dir"; public static final String DFS_NAMENODE_HTTPS_PORT_KEY = "dfs.https.port"; public static final int DFS_NAMENODE_HTTPS_PORT_DEFAULT = 50470; public static final String DFS_NAMENODE_HTTPS_ADDRESS_KEY = "dfs.namenode.https-address"; public static final String DFS_NAMENODE_HTTPS_ADDRESS_DEFAULT = "0.0.0.0:" + DFS_NAMENODE_HTTPS_PORT_DEFAULT; public static final String DFS_CLIENT_READ_PREFETCH_SIZE_KEY = "dfs.client.read.prefetch.size"; public static final String DFS_CLIENT_RETRY_WINDOW_BASE = "dfs.client.retry.window.base"; public static final String DFS_METRICS_SESSION_ID_KEY = "dfs.metrics.session-id"; public static final String DFS_METRICS_PERCENTILES_INTERVALS_KEY = "dfs.metrics.percentiles.intervals"; public static final String DFS_DATANODE_HOST_NAME_KEY = "dfs.datanode.hostname"; public static final String DFS_NAMENODE_HOSTS_KEY = "dfs.namenode.hosts"; public static final String DFS_NAMENODE_HOSTS_EXCLUDE_KEY = "dfs.namenode.hosts.exclude"; public static final String DFS_CLIENT_SOCKET_TIMEOUT_KEY = "dfs.client.socket-timeout"; public static final String DFS_HOSTS = "dfs.hosts"; public static final String DFS_HOSTS_EXCLUDE = "dfs.hosts.exclude"; public static final String DFS_CLIENT_LOCAL_INTERFACES = "dfs.client.local.interfaces"; public static final String DFS_NAMENODE_AUDIT_LOGGERS_KEY = "dfs.namenode.audit.loggers"; public static final String DFS_NAMENODE_DEFAULT_AUDIT_LOGGER_NAME = "default"; // Much code in hdfs is not yet updated to use these keys. public static final String DFS_CLIENT_BLOCK_WRITE_LOCATEFOLLOWINGBLOCK_RETRIES_KEY = "dfs.client.block.write.locateFollowingBlock.retries"; public static final int DFS_CLIENT_BLOCK_WRITE_LOCATEFOLLOWINGBLOCK_RETRIES_DEFAULT = 10; //HOP default was 5 public static final String DFS_CLIENT_BLOCK_WRITE_RETRIES_KEY = "dfs.client.block.write.retries"; public static final int DFS_CLIENT_BLOCK_WRITE_RETRIES_DEFAULT = 3; public static final String DFS_CLIENT_MAX_BLOCK_ACQUIRE_FAILURES_KEY = "dfs.client.max.block.acquire.failures"; public static final int DFS_CLIENT_MAX_BLOCK_ACQUIRE_FAILURES_DEFAULT = 3; public static final String DFS_CLIENT_USE_LEGACY_BLOCKREADER = "dfs.client.use.legacy.blockreader"; public static final boolean DFS_CLIENT_USE_LEGACY_BLOCKREADER_DEFAULT = false; public static final String DFS_CLIENT_USE_LEGACY_BLOCKREADERLOCAL = "dfs.client.use.legacy.blockreader.local"; public static final boolean DFS_CLIENT_USE_LEGACY_BLOCKREADERLOCAL_DEFAULT = false; public static final String DFS_BALANCER_MOVEDWINWIDTH_KEY = "dfs.balancer.movedWinWidth"; public static final long DFS_BALANCER_MOVEDWINWIDTH_DEFAULT = 5400*1000L; public static final String DFS_BALANCER_MOVERTHREADS_KEY = "dfs.balancer.moverThreads"; public static final int DFS_BALANCER_MOVERTHREADS_DEFAULT = 1000; public static final String DFS_BALANCER_DISPATCHERTHREADS_KEY = "dfs.balancer.dispatcherThreads"; public static final int DFS_BALANCER_DISPATCHERTHREADS_DEFAULT = 200; public static final String DFS_MOVER_MOVEDWINWIDTH_KEY = "dfs.mover.movedWinWidth"; public static final long DFS_MOVER_MOVEDWINWIDTH_DEFAULT = 5400*1000L; public static final String DFS_MOVER_MOVERTHREADS_KEY = "dfs.mover.moverThreads"; public static final int DFS_MOVER_MOVERTHREADS_DEFAULT = 1000; public static final String DFS_DATANODE_ADDRESS_KEY = "dfs.datanode.address"; public static final int DFS_DATANODE_DEFAULT_PORT = 50010; public static final String DFS_DATANODE_ADDRESS_DEFAULT = "0.0.0.0:" + DFS_DATANODE_DEFAULT_PORT; public static final String DFS_DATANODE_DATA_DIR_PERMISSION_KEY = "dfs.datanode.data.dir.perm"; public static final String DFS_DATANODE_DATA_DIR_PERMISSION_DEFAULT = "700"; public static final String DFS_DATANODE_DIRECTORYSCAN_INTERVAL_KEY = "dfs.datanode.directoryscan.interval"; public static final int DFS_DATANODE_DIRECTORYSCAN_INTERVAL_DEFAULT = 21600; public static final String DFS_DATANODE_DIRECTORYSCAN_THREADS_KEY = "dfs.datanode.directoryscan.threads"; public static final int DFS_DATANODE_DIRECTORYSCAN_THREADS_DEFAULT = 1; public static final String DFS_DATANODE_DNS_INTERFACE_KEY = "dfs.datanode.dns.interface"; public static final String DFS_DATANODE_DNS_INTERFACE_DEFAULT = "default"; public static final String DFS_DATANODE_DNS_NAMESERVER_KEY = "dfs.datanode.dns.nameserver"; public static final String DFS_DATANODE_DNS_NAMESERVER_DEFAULT = "default"; public static final String DFS_DATANODE_DU_RESERVED_KEY = "dfs.datanode.du.reserved"; public static final long DFS_DATANODE_DU_RESERVED_DEFAULT = 0; public static final String DFS_DATANODE_HANDLER_COUNT_KEY = "dfs.datanode.handler.count"; public static final int DFS_DATANODE_HANDLER_COUNT_DEFAULT = 10; public static final String DFS_DATANODE_HTTP_ADDRESS_KEY = "dfs.datanode.http.address"; public static final int DFS_DATANODE_HTTP_DEFAULT_PORT = 50075; public static final String DFS_DATANODE_HTTP_ADDRESS_DEFAULT = "0.0.0.0:" + DFS_DATANODE_HTTP_DEFAULT_PORT; public static final String DFS_DATANODE_MAX_RECEIVER_THREADS_KEY = "dfs.datanode.max.transfer.threads"; public static final int DFS_DATANODE_MAX_RECEIVER_THREADS_DEFAULT = 4096; public static final String DFS_DATANODE_NUMBLOCKS_KEY = "dfs.datanode.numblocks"; public static final int DFS_DATANODE_NUMBLOCKS_DEFAULT = 64; public static final String DFS_DATANODE_SCAN_PERIOD_HOURS_KEY = "dfs.datanode.scan.period.hours"; public static final int DFS_DATANODE_SCAN_PERIOD_HOURS_DEFAULT = 0; public static final String DFS_DATANODE_TRANSFERTO_ALLOWED_KEY = "dfs.datanode.transferTo.allowed"; public static final boolean DFS_DATANODE_TRANSFERTO_ALLOWED_DEFAULT = true; public static final String DFS_HEARTBEAT_INTERVAL_KEY = "dfs.heartbeat.interval"; public static final long DFS_HEARTBEAT_INTERVAL_DEFAULT = 3; public static final String DFS_NAMENODE_DECOMMISSION_INTERVAL_KEY = "dfs.namenode.decommission.interval"; public static final int DFS_NAMENODE_DECOMMISSION_INTERVAL_DEFAULT = 30; public static final String DFS_NAMENODE_DECOMMISSION_NODES_PER_INTERVAL_KEY = "dfs.namenode.decommission.nodes.per.interval"; public static final int DFS_NAMENODE_DECOMMISSION_NODES_PER_INTERVAL_DEFAULT = 5; public static final String DFS_NAMENODE_HANDLER_COUNT_KEY = "dfs.namenode.handler.count"; public static final int DFS_NAMENODE_HANDLER_COUNT_DEFAULT = 10; public static final String DFS_NAMENODE_SERVICE_HANDLER_COUNT_KEY = "dfs.namenode.service.handler.count"; public static final int DFS_NAMENODE_SERVICE_HANDLER_COUNT_DEFAULT = 10; public static final String DFS_SUPPORT_APPEND_KEY = "dfs.support.append"; public static final boolean DFS_SUPPORT_APPEND_DEFAULT = true; public static final String DFS_HTTPS_ENABLE_KEY = "dfs.https.enable"; public static final boolean DFS_HTTPS_ENABLE_DEFAULT = false; public static final String DFS_DEFAULT_CHUNK_VIEW_SIZE_KEY = "dfs.default.chunk.view.size"; public static final int DFS_DEFAULT_CHUNK_VIEW_SIZE_DEFAULT = 32 * 1024; public static final String DFS_DATANODE_HTTPS_ADDRESS_KEY = "dfs.datanode.https.address"; public static final String DFS_DATANODE_HTTPS_PORT_KEY = "datanode.https.port"; public static final int DFS_DATANODE_HTTPS_DEFAULT_PORT = 50475; public static final String DFS_DATANODE_HTTPS_ADDRESS_DEFAULT = "0.0.0.0:" + DFS_DATANODE_HTTPS_DEFAULT_PORT; public static final String DFS_DATANODE_IPC_ADDRESS_KEY = "dfs.datanode.ipc.address"; public static final int DFS_DATANODE_IPC_DEFAULT_PORT = 50020; public static final String DFS_DATANODE_IPC_ADDRESS_DEFAULT = "0.0.0.0:" + DFS_DATANODE_IPC_DEFAULT_PORT; public static final String DFS_DATANODE_MIN_SUPPORTED_NAMENODE_VERSION_KEY = "dfs.datanode.min.supported.namenode.version"; public static final String DFS_DATANODE_MIN_SUPPORTED_NAMENODE_VERSION_DEFAULT = "2.1.0-beta"; public static final String DFS_BLOCK_ACCESS_TOKEN_ENABLE_KEY = "dfs.block.access.token.enable"; public static final boolean DFS_BLOCK_ACCESS_TOKEN_ENABLE_DEFAULT = false; public static final String DFS_BLOCK_ACCESS_KEY_UPDATE_INTERVAL_KEY = "dfs.block.access.key.update.interval"; public static final long DFS_BLOCK_ACCESS_KEY_UPDATE_INTERVAL_DEFAULT = 600L; public static final String DFS_BLOCK_ACCESS_TOKEN_LIFETIME_KEY = "dfs.block.access.token.lifetime"; public static final long DFS_BLOCK_ACCESS_TOKEN_LIFETIME_DEFAULT = 600L; public static final String DFS_BLOCK_REPLICATOR_CLASSNAME_KEY = "dfs.block.replicator.classname"; public static final Class<BlockPlacementPolicyDefault> DFS_BLOCK_REPLICATOR_CLASSNAME_DEFAULT = BlockPlacementPolicyDefault.class; public static final String DFS_REPLICATION_MAX_KEY = "dfs.replication.max"; public static final int DFS_REPLICATION_MAX_DEFAULT = 512; public static final String DFS_DF_INTERVAL_KEY = "dfs.df.interval"; public static final int DFS_DF_INTERVAL_DEFAULT = 60000; public static final String DFS_BLOCKREPORT_INTERVAL_MSEC_KEY = "dfs.blockreport.intervalMsec"; public static final long DFS_BLOCKREPORT_INTERVAL_MSEC_DEFAULT = 60 * 60 * 1000L; public static final String DFS_BLOCKREPORT_INITIAL_DELAY_KEY = "dfs.blockreport.initialDelay"; public static final int DFS_BLOCKREPORT_INITIAL_DELAY_DEFAULT = 0; public static final String DFS_BLOCKREPORT_SPLIT_THRESHOLD_KEY = "dfs.blockreport.split.threshold"; public static final long DFS_BLOCKREPORT_SPLIT_THRESHOLD_DEFAULT = 1000 * 1000; public static final String DFS_BLOCK_INVALIDATE_LIMIT_KEY = "dfs.block.invalidate.limit"; public static final int DFS_BLOCK_INVALIDATE_LIMIT_DEFAULT = 1000; public static final String DFS_DEFAULT_MAX_CORRUPT_FILES_RETURNED_KEY = "dfs.corruptfilesreturned.max"; public static final int DFS_DEFAULT_MAX_CORRUPT_FILES_RETURNED = 500; public static final String DFS_CLIENT_READ_SHORTCIRCUIT_KEY = "dfs.client.read.shortcircuit"; public static final boolean DFS_CLIENT_READ_SHORTCIRCUIT_DEFAULT = false; public static final String DFS_CLIENT_READ_SHORTCIRCUIT_SKIP_CHECKSUM_KEY = "dfs.client.read.shortcircuit.skip.checksum"; public static final boolean DFS_CLIENT_READ_SHORTCIRCUIT_SKIP_CHECKSUM_DEFAULT = false; public static final String DFS_CLIENT_READ_SHORTCIRCUIT_BUFFER_SIZE_KEY = "dfs.client.read.shortcircuit.buffer.size"; public static final String DFS_CLIENT_READ_SHORTCIRCUIT_STREAMS_CACHE_SIZE_KEY = "dfs.client.read.shortcircuit.streams.cache.size"; public static final int DFS_CLIENT_READ_SHORTCIRCUIT_STREAMS_CACHE_SIZE_DEFAULT = 100; public static final String DFS_CLIENT_READ_SHORTCIRCUIT_STREAMS_CACHE_EXPIRY_MS_KEY = "dfs.client.read.shortcircuit.streams.cache.expiry.ms"; public static final long DFS_CLIENT_READ_SHORTCIRCUIT_STREAMS_CACHE_EXPIRY_MS_DEFAULT = 5000; public static final int DFS_CLIENT_READ_SHORTCIRCUIT_BUFFER_SIZE_DEFAULT = 1024 * 1024; public static final String DFS_CLIENT_DOMAIN_SOCKET_DATA_TRAFFIC = "dfs.client.domain.socket.data.traffic"; public static final boolean DFS_CLIENT_DOMAIN_SOCKET_DATA_TRAFFIC_DEFAULT = false; //Keys with no defaults public static final String DFS_DATANODE_PLUGINS_KEY = "dfs.datanode.plugins"; public static final String DFS_DATANODE_FSDATASET_FACTORY_KEY = "dfs.datanode.fsdataset.factory"; public static final String DFS_DATANODE_FSDATASET_VOLUME_CHOOSING_POLICY_KEY = "dfs.datanode.fsdataset.volume.choosing.policy"; public static final String DFS_DATANODE_AVAILABLE_SPACE_VOLUME_CHOOSING_POLICY_BALANCED_SPACE_THRESHOLD_KEY = "dfs.datanode.available-space-volume-choosing-policy.balanced-space-threshold"; public static final long DFS_DATANODE_AVAILABLE_SPACE_VOLUME_CHOOSING_POLICY_BALANCED_SPACE_THRESHOLD_DEFAULT = 1024L * 1024L * 1024L * 10L; // 10 GB public static final String DFS_DATANODE_AVAILABLE_SPACE_VOLUME_CHOOSING_POLICY_BALANCED_SPACE_PREFERENCE_FRACTION_KEY = "dfs.datanode.available-space-volume-choosing-policy.balanced-space-preference-fraction"; public static final float DFS_DATANODE_AVAILABLE_SPACE_VOLUME_CHOOSING_POLICY_BALANCED_SPACE_PREFERENCE_FRACTION_DEFAULT = 0.75f; public static final String DFS_DATANODE_SOCKET_WRITE_TIMEOUT_KEY = "dfs.datanode.socket.write.timeout"; public static final String DFS_DATANODE_STARTUP_KEY = "dfs.datanode.startup"; public static final String DFS_NAMENODE_PLUGINS_KEY = "dfs.namenode.plugins"; public static final String DFS_WEB_UGI_KEY = "dfs.web.ugi"; public static final String DFS_NAMENODE_STARTUP_KEY = "dfs.namenode.startup"; public static final String DFS_DATANODE_KEYTAB_FILE_KEY = "dfs.datanode.keytab.file"; public static final String DFS_DATANODE_USER_NAME_KEY = "dfs.datanode.kerberos.principal"; public static final String DFS_NAMENODE_KEYTAB_FILE_KEY = "dfs.namenode.keytab.file"; public static final String DFS_NAMENODE_USER_NAME_KEY = "dfs.namenode.kerberos.principal"; public static final String DFS_NAMENODE_INTERNAL_SPNEGO_USER_NAME_KEY = "dfs.namenode.kerberos.internal.spnego.principal"; public static final String DFS_NAMENODE_NAME_CACHE_THRESHOLD_KEY = "dfs.namenode.name.cache.threshold"; public static final int DFS_NAMENODE_NAME_CACHE_THRESHOLD_DEFAULT = 10; public static final String DFS_NAMENODE_RESOURCE_CHECK_INTERVAL_KEY = "dfs.namenode.resource.check.interval"; public static final int DFS_NAMENODE_RESOURCE_CHECK_INTERVAL_DEFAULT = 5000; public static final String DFS_NAMENODE_DU_RESERVED_KEY = "dfs.namenode.resource.du.reserved"; public static final long DFS_NAMENODE_DU_RESERVED_DEFAULT = 1024 * 1024 * 100; // 100 MB public static final String DFS_NAMENODE_CHECKED_VOLUMES_KEY = "dfs.namenode.resource.checked.volumes"; public static final String DFS_NAMENODE_CHECKED_VOLUMES_MINIMUM_KEY = "dfs.namenode.resource.checked.volumes.minimum"; public static final int DFS_NAMENODE_CHECKED_VOLUMES_MINIMUM_DEFAULT = 1; public static final String DFS_WEB_AUTHENTICATION_KERBEROS_PRINCIPAL_KEY = "dfs.web.authentication.kerberos.principal"; public static final String DFS_WEB_AUTHENTICATION_KERBEROS_KEYTAB_KEY = "dfs.web.authentication.kerberos.keytab"; public static final String DFS_NAMENODE_MAX_OP_SIZE_KEY = "dfs.namenode.max.op.size"; public static final int DFS_NAMENODE_MAX_OP_SIZE_DEFAULT = 50 * 1024 * 1024; public static final String DFS_BLOCK_LOCAL_PATH_ACCESS_USER_KEY = "dfs.block.local-path-access.user"; public static final String DFS_DOMAIN_SOCKET_PATH_KEY = "dfs.domain.socket.path"; public static final String DFS_DOMAIN_SOCKET_PATH_DEFAULT = ""; public static final String DFS_STORAGE_POLICY_ENABLED_KEY = "dfs.storage.policy.enabled"; public static final boolean DFS_STORAGE_POLICY_ENABLED_DEFAULT = true; // Security-related configs public static final String DFS_ENCRYPT_DATA_TRANSFER_KEY = "dfs.encrypt.data.transfer"; public static final boolean DFS_ENCRYPT_DATA_TRANSFER_DEFAULT = false; public static final String DFS_DATA_ENCRYPTION_ALGORITHM_KEY = "dfs.encrypt.data.transfer.algorithm"; // Hash bucket config public static final String DFS_NUM_BUCKETS_KEY = "dfs.blockreport.numbuckets"; public static final int DFS_NUM_BUCKETS_DEFAULT = 1000; // Handling unresolved DN topology mapping public static final String DFS_REJECT_UNRESOLVED_DN_TOPOLOGY_MAPPING_KEY = "dfs.namenode.reject-unresolved-dn-topology-mapping"; public static final boolean DFS_REJECT_UNRESOLVED_DN_TOPOLOGY_MAPPING_DEFAULT = false; public static final String DFS_MAX_NUM_BLOCKS_TO_LOG_KEY = "dfs.namenode.max-num-blocks-to-log"; public static final long DFS_MAX_NUM_BLOCKS_TO_LOG_DEFAULT = 1000l; public static final String DFS_NAMENODE_ENABLE_RETRY_CACHE_KEY = "dfs.namenode.enable.retrycache"; public static final boolean DFS_NAMENODE_ENABLE_RETRY_CACHE_DEFAULT = true; public static final String DFS_NAMENODE_RETRY_CACHE_EXPIRYTIME_MILLIS_KEY = "dfs.namenode.retrycache.expirytime.millis"; public static final long DFS_NAMENODE_RETRY_CACHE_EXPIRYTIME_MILLIS_DEFAULT = 600000; // 10 minutes public static final String DFS_NAMENODE_RETRY_CACHE_HEAP_PERCENT_KEY = "dfs.namenode.retrycache.heap.percent"; public static final float DFS_NAMENODE_RETRY_CACHE_HEAP_PERCENT_DEFAULT = 0.03f; // Hidden configuration undocumented in hdfs-site. xml // Timeout to wait for block receiver and responder thread to stop public static final String DFS_DATANODE_XCEIVER_STOP_TIMEOUT_MILLIS_KEY = "dfs.datanode.xceiver.stop.timeout.millis"; public static final long DFS_DATANODE_XCEIVER_STOP_TIMEOUT_MILLIS_DEFAULT = 60000; }
hadoop-hdfs-project/hadoop-hdfs/src/main/java/org/apache/hadoop/hdfs/DFSConfigKeys.java
/** * 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. */ package org.apache.hadoop.hdfs; import org.apache.hadoop.classification.InterfaceAudience; import org.apache.hadoop.fs.CommonConfigurationKeys; import org.apache.hadoop.hdfs.server.blockmanagement.BlockPlacementPolicyDefault; /** * This class contains constants for configuration keys used * in hdfs. */ @InterfaceAudience.Private public class DFSConfigKeys extends CommonConfigurationKeys { public static final String DFS_STORAGE_DRIVER_JAR_FILE = "dfs.storage.driver.jarFile"; public static final String DFS_STORAGE_DRIVER_JAR_FILE_DEFAULT = ""; public static final String DFS_STORAGE_DRIVER_CLASS = "dfs.storage.driver.class"; public static final String DFS_STORAGE_DRIVER_CLASS_DEFAULT = "io.hops.metadata.ndb.NdbStorageFactory"; public static final String DFS_STORAGE_DRIVER_CONFIG_FILE = "dfs.storage.driver.configfile"; public static final String DFS_STORAGE_DRIVER_CONFIG_FILE_DEFAULT = "ndb-config.properties"; public static final String DFS_STORAGE_ANCESTOR_LOCK_TYPE = "dfs.storage.ancestor.lock.type"; public static final String DFS_STORAGE_ANCESTOR_LOCK_TYPE_DEFAULT = "READ_COMMITTED"; // "READ" | "READ_COMMITTED" public static final String DFS_NAMENODE_QUOTA_ENABLED_KEY = "dfs.namenode.quota.enabled"; public static final boolean DFS_NAMENODE_QUOTA_ENABLED_DEFAULT = true; public static final String DFS_NAMENODE_QUOTA_UPDATE_INTERVAL_KEY = "dfs.namenode.quota.update.interval"; public static final int DFS_NAMENODE_QUOTA_UPDATE_INTERVAL_DEFAULT = 1000; public static final String DFS_NAMENODE_QUOTA_UPDATE_LIMIT_KEY = "dfs.namenode.quota.update.limit"; public static final int DFS_NAMENODE_QUOTA_UPDATE_LIMIT_DEFAULT = 100000; public static final String DFS_NAMENODE_QUOTA_UPDATE_ID_BATCH_SIZE = "dfs.namenode.quota.update.id.batchsize"; public static final int DFS_NAMENODE_QUOTA_UPDATE_ID_BATCH_SIZ_DEFAULT = 100000; public static final String DFS_NAMENODE_QUOTA_UPDATE_ID_UPDATE_THRESHOLD = "dfs.namenode.quota.update.updateThreshold"; public static final float DFS_NAMENODE_QUOTA_UPDATE_ID_UPDATE_THRESHOLD_DEFAULT = (float) 0.5; public static final String DFS_NAMENODE_INODEID_BATCH_SIZE = "dfs.namenode.inodeid.batchsize"; public static final int DFS_NAMENODE_INODEID_BATCH_SIZE_DEFAULT = 1000; public static final String DFS_NAMENODE_BLOCKID_BATCH_SIZE = "dfs.namenode.blockid.batchsize"; public static final int DFS_NAMENODE_BLOCKID_BATCH_SIZE_DEFAULT = 1000; public static final String DFS_NAMENODE_INODEID_UPDATE_THRESHOLD = "dfs.namenode.inodeid.updateThreshold"; public static final float DFS_NAMENODE_INODEID_UPDATE_THRESHOLD_DEFAULT = (float) 0.5; public static final String DFS_NAMENODE_BLOCKID_UPDATE_THRESHOLD = "dfs.namenode.blockid.updateThreshold"; public static final float DFS_NAMENODE_BLOCKID_UPDATE_THRESHOLD_DEFAULT = (float) 0.5; public static final String DFS_NAMENODE_IDSMONITOR_CHECK_INTERVAL_IN_MS = "dfs.namenode.id.updateThreshold"; public static final int DFS_NAMENODE_IDSMONITOR_CHECK_INTERVAL_IN_MS_DEFAULT = 1000; public static final String DFS_NAMENODE_PROCESS_REPORT_BATCH_SIZE = "dfs.namenode.processReport.batchsize"; public static final int DFS_NAMENODE_PROCESS_REPORT_BATCH_SIZE_DEFAULT = 5000; public static final String DFS_NAMENODE_PROCESS_MISREPLICATED_BATCH_SIZE = "dfs.namenode.misreplicated.batchsize"; public static final int DFS_NAMENODE_PROCESS_MISREPLICATED_BATCH_SIZE_DEFAULT = 500; public static final String DFS_NAMENODE_PROCESS_MISREPLICATED_NO_OF_BATCHS = "dfs.namenode.misreplicated.noofbatches"; public static final int DFS_NAMENODE_PROCESS_MISREPLICATED_NO_OF_BATCHS_DEFAULT = 10; public static final String DFS_TRANSACTION_STATS_ENABLED = "dfs.transaction.stats.enabled"; public static final boolean DFS_TRANSACTION_STATS_ENABLED_DEFAULT = false; public static final String DFS_TRANSACTION_STATS_DETAILED_ENABLED = "dfs.transaction.stats.detailed.enabled"; public static final boolean DFS_TRANSACTION_STATS_DETAILED_ENABLED_DEFAULT = false; public static final String DFS_TRANSACTION_STATS_DIR = "dfs.transaction.stats.dir"; public static final String DFS_TRANSACTION_STATS_DIR_DEFAULT = "/tmp/hopsstats"; public static final String DFS_TRANSACTION_STATS_WRITER_ROUND = "dfs.transaction.stats.writerround"; public static final int DFS_TRANSACTION_STATS_WRITER_ROUND_DEFAULT = 120; public static final String DFS_DIR_DELETE_BATCH_SIZE= "dfs.dir.delete.batch.size"; public static final int DFS_DIR_DELETE_BATCH_SIZE_DEFAULT = 50; /*for client failover api*/ // format {ip:port, ip:port, ip:port} comma separated public static final String DFS_NAMENODES_RPC_ADDRESS_KEY = "dfs.namenodes.rpc.addresses"; public static final String DFS_NAMENODES_RPC_ADDRESS_DEFAULT = ""; // format {ip:port, ip:port, ip:port} comma separated public static final String DFS_NAMENODES_SERVICE_RPC_ADDRESS_KEY = "dfs.namenodes.servicerpc.addresses"; public static final String DFS_NAMENODE_SELECTOR_POLICY_KEY = "dfs.namenode.selector-policy"; public static final String DFS_NAMENODE_SELECTOR_POLICY_DEFAULT = "RANDOM_STICKY"; //RANDOM ROUND_ROBIN RANDOM_STICKY public static final String DFS_BLOCK_POOL_ID_KEY = "dfs.block.pool.id"; public static final String DFS_BLOCK_POOL_ID_DEFAULT = "HOP_BLOCK_POOL_123"; public static final String DFS_NAME_SPACE_ID_KEY = "dfs.name.space.id"; public static final int DFS_NAME_SPACE_ID_DEFAULT = 911; // :) public static final String DFS_CLIENT_RETRIES_ON_FAILURE_KEY = "dfs.client.max.retries.on.failure"; public static final int DFS_CLIENT_RETRIES_ON_FAILURE_DEFAULT = 2; //min value is 0. Better set it >= 1 public static final String DFS_NAMENODE_TX_RETRY_COUNT_KEY = "dfs.namenode.tx.retry.count"; public static final int DFS_NAMENODE_TX_RETRY_COUNT_DEFAULT = 5; public static final String DFS_NAMENODE_TX_INITIAL_WAIT_TIME_BEFORE_RETRY_KEY = "dfs.namenode.tx.initial.wait.time.before.retry"; public static final int DFS_NAMENODE_TX_INITIAL_WAIT_TIME_BEFORE_RETRY_DEFAULT = 2000; public static final String DFS_CLIENT_INITIAL_WAIT_ON_RETRY_IN_MS_KEY = "dfs.client.initial.wait.on.retry"; public static final int DFS_CLIENT_INITIAL_WAIT_ON_RETRY_IN_MS_DEFAULT = 1000; public static final String DFS_CLIENT_REFRESH_NAMENODE_LIST_IN_MS_KEY = "dfs.client.refresh.namenode.list"; public static final int DFS_CLIENT_REFRESH_NAMENODE_LIST_IN_MS_DEFAULT = 60 * 1000; //time in milliseconds. public static final String DFS_SET_PARTITION_KEY_ENABLED = "dfs.ndb.setpartitionkey.enabled"; public static final boolean DFS_SET_PARTITION_KEY_ENABLED_DEFAULT = true; public static final String DFS_SET_RANDOM_PARTITION_KEY_ENABLED = "dfs.ndb.setrandompartitionkey.enabled"; public static final boolean DFS_SET_RANDOM_PARTITION_KEY_ENABLED_DEFAULT = true; public static final String DFS_RESOLVING_CACHE_ENABLED = "dfs" + ".resolvingcache.enabled"; public static final boolean DFS_RESOLVING_CACHE_ENABLED_DEFAULT = true; public static final String DFS_MEMCACHE_SERVER = "dfs.resolvingcache.memcache.server.address"; public static final String DFS_MEMCACHE_SERVER_DEFAULT = "127.0.0.1:11212"; public static final String DFS_MEMCACHE_CONNECTION_POOL_SIZE = "dfs.resolvingcache.memcache.connectionpool.size"; public static final int DFS_MEMCACHE_CONNECTION_POOL_SIZE_DEFAULT = 10; public static final String DFS_MEMCACHE_KEY_PREFIX = "dfs.resolvingcache.memcache.key.prefix"; public static final String DFS_MEMCACHE_KEY_PREFIX_DEFAULT = "p:"; public static final String DFS_MEMCACHE_KEY_EXPIRY_IN_SECONDS = "dfs.resolvingcache.memcache.key.expiry"; public static final int DFS_MEMCACHE_KEY_EXPIRY_IN_SECONDS_DEFAULT = 0; public static final String DFS_RESOLVING_CACHE_TYPE = "dfs.resolvingcache" + ".type"; //INode, Path, InMemory, Optimal public static final String DFS_RESOLVING_CACHE_TYPE_DEFAULT = "InMemory"; public static final String DFS_INMEMORY_CACHE_MAX_SIZE = "dfs" + ".resolvingcache.inmemory.maxsize"; public static final int DFS_INMEMORY_CACHE_MAX_SIZE_DEFAULT = 100000; public static final String DFS_NDC_ENABLED_KEY = "dfs.ndc.enable"; public static final boolean DFS_NDC_ENABLED_DEFAULT = false; public static final String DFS_SUBTREE_EXECUTOR_LIMIT_KEY = "dfs.namenode.subtree-executor-limit"; public static final int DFS_SUBTREE_EXECUTOR_LIMIT_DEFAULT = 80; public static final String ERASURE_CODING_CODECS_KEY = "dfs.erasure_coding.codecs.json"; public static final String ERASURE_CODING_ENABLED_KEY = "dfs.erasure_coding.enabled"; public static final boolean DEFAULT_ERASURE_CODING_ENABLED_KEY = false; public static final String PARITY_FOLDER = "dfs.erasure_coding.parity_folder"; public static final String DEFAULT_PARITY_FOLDER = "/parity"; public static final String ENCODING_MANAGER_CLASSNAME_KEY = "dfs.erasure_coding.encoding_manager"; public static final String DEFAULT_ENCODING_MANAGER_CLASSNAME = "io.hops.erasure_coding.MapReduceEncodingManager"; public static final String BLOCK_REPAIR_MANAGER_CLASSNAME_KEY = "dfs.erasure_coding.block_rapair_manager"; public static final String DEFAULT_BLOCK_REPAIR_MANAGER_CLASSNAME = "io.hops.erasure_coding.MapReduceBlockRepairManager"; public static final String RECHECK_INTERVAL_KEY = "dfs.erasure_coding.recheck_interval"; public static final int DEFAULT_RECHECK_INTERVAL = 5 * 60 * 1000; public static final String ACTIVE_ENCODING_LIMIT_KEY = "dfs.erasure_coding.active_encoding_limit"; public static final int DEFAULT_ACTIVE_ENCODING_LIMIT = 10; public static final String ACTIVE_REPAIR_LIMIT_KEY = "dfs.erasure_coding.active_repair_limit"; public static final int DEFAULT_ACTIVE_REPAIR_LIMIT = 10; public static final String REPAIR_DELAY_KEY = "dfs.erasure_coding.repair_delay"; public static final int DEFAULT_REPAIR_DELAY_KEY = 30 * 60 * 1000; public static final String ACTIVE_PARITY_REPAIR_LIMIT_KEY = "dfs.erasure_coding.active_parity_repair_limit"; public static final int DEFAULT_ACTIVE_PARITY_REPAIR_LIMIT = 10; public static final String PARITY_REPAIR_DELAY_KEY = "dfs.erasure_coding.parity_repair_delay"; public static final int DEFAULT_PARITY_REPAIR_DELAY = 30 * 60 * 1000; public static final String DELETION_LIMIT_KEY = "dfs.erasure_coding.deletion_limit"; public static final int DEFAULT_DELETION_LIMIT = 100; public static final String DFS_BR_LB_MAX_BLK_PER_TW = "dfs.block.report.load.balancing.max.blks.per.time.window"; public static final long DFS_BR_LB_MAX_BLK_PER_TW_DEFAULT = 1000000; public static final String DFS_BR_LB_TIME_WINDOW_SIZE = "dfs.block.report.load.balancing.time.window.size"; public static final long DFS_BR_LB_TIME_WINDOW_SIZE_DEFAULT = 60*1000; //1 min public static final String DFS_BR_LB_DB_VAR_UPDATE_THRESHOLD = "dfs.blk.report.load.balancing.db.var.update.threashold"; public static final long DFS_BR_LB_DB_VAR_UPDATE_THRESHOLD_DEFAULT = 60*1000; public static final String DFS_STORE_SMALL_FILES_IN_DB_KEY = "dfs.store.small.files.in.db"; public static final boolean DFS_STORE_SMALL_FILES_IN_DB_DEFAULT = false; public static final String DFS_DB_ONDISK_SMALL_FILE_MAX_SIZE_KEY = "dfs.db.ondisk.small.file.max.size"; public static final int DFS_DB_ONDISK_SMALL_FILE_MAX_SIZE_DEFAULT = 2000; public static final String DFS_DB_ONDISK_MEDIUM_FILE_MAX_SIZE_KEY = "dfs.db.ondisk.medium.file.max.size"; public static final int DFS_DB_ONDISK_MEDIUM_FILE_MAX_SIZE_DEFAULT = 4000; public static final String DFS_DB_ONDISK_LARGE_FILE_MAX_SIZE_KEY = "dfs.db.ondisk.large.file.max.size"; public static final int DFS_DB_ONDISK_LARGE_FILE_MAX_SIZE_DEFAULT = 64*1024; public static final String DFS_DB_FILE_MAX_SIZE_KEY = "dfs.db.file.max.size"; public static final int DFS_DB_FILE_MAX_SIZE_DEFAULT = 64 * 1024; public static final String DFS_DB_INMEMORY_FILE_MAX_SIZE_KEY = "dfs.db.inmemory.file.max.size"; public static final int DFS_DB_INMEMORY_FILE_MAX_SIZE_DEFAULT = 1*1024; // 1KB public static final String DFS_DN_INCREMENTAL_BR_DISPATCHER_THREAD_POOL_SIZE_KEY = "dfs.dn.incremental.br.thread.pool.size"; public static final int DFS_DN_INCREMENTAL_BR_DISPATCHER_THREAD_POOL_SIZE_DEFAULT = 256; public static final String DFS_CLIENT_DELAY_BEFORE_FILE_CLOSE_KEY = "dsf.client.delay.before.file.close"; public static final int DFS_CLIENT_DELAY_BEFORE_FILE_CLOSE_DEFAULT = 0; public static final String DFS_BLOCK_SIZE_KEY = "dfs.blocksize"; public static final long DFS_BLOCK_SIZE_DEFAULT = 128 * 1024 * 1024; public static final String DFS_REPLICATION_KEY = "dfs.replication"; public static final short DFS_REPLICATION_DEFAULT = 3; public static final String DFS_STREAM_BUFFER_SIZE_KEY = "dfs.stream-buffer-size"; public static final int DFS_STREAM_BUFFER_SIZE_DEFAULT = 4096; public static final String DFS_BYTES_PER_CHECKSUM_KEY = "dfs.bytes-per-checksum"; public static final int DFS_BYTES_PER_CHECKSUM_DEFAULT = 512; public static final String DFS_CLIENT_RETRY_POLICY_ENABLED_KEY = "dfs.client.retry.policy.enabled"; public static final boolean DFS_CLIENT_RETRY_POLICY_ENABLED_DEFAULT = false; public static final String DFS_CLIENT_RETRY_POLICY_SPEC_KEY = "dfs.client.retry.policy.spec"; public static final String DFS_CLIENT_RETRY_POLICY_SPEC_DEFAULT = "10000,6,60000,10"; //t1,n1,t2,n2,... public static final String DFS_CHECKSUM_TYPE_KEY = "dfs.checksum.type"; public static final String DFS_CHECKSUM_TYPE_DEFAULT = "CRC32C"; public static final String DFS_CLIENT_WRITE_PACKET_SIZE_KEY = "dfs.client-write-packet-size"; public static final int DFS_CLIENT_WRITE_PACKET_SIZE_DEFAULT = 64 * 1024; public static final String DFS_CLIENT_WRITE_REPLACE_DATANODE_ON_FAILURE_ENABLE_KEY = "dfs.client.block.write.replace-datanode-on-failure.enable"; public static final boolean DFS_CLIENT_WRITE_REPLACE_DATANODE_ON_FAILURE_ENABLE_DEFAULT = true; public static final String DFS_CLIENT_WRITE_REPLACE_DATANODE_ON_FAILURE_POLICY_KEY = "dfs.client.block.write.replace-datanode-on-failure.policy"; public static final String DFS_CLIENT_WRITE_REPLACE_DATANODE_ON_FAILURE_POLICY_DEFAULT = "DEFAULT"; public static final String DFS_CLIENT_SOCKET_CACHE_CAPACITY_KEY = "dfs.client.socketcache.capacity"; public static final int DFS_CLIENT_SOCKET_CACHE_CAPACITY_DEFAULT = 16; public static final String DFS_CLIENT_USE_DN_HOSTNAME = "dfs.client.use.datanode.hostname"; public static final boolean DFS_CLIENT_USE_DN_HOSTNAME_DEFAULT = false; public static final String DFS_CLIENT_CACHE_DROP_BEHIND_WRITES = "dfs.client.cache.drop.behind.writes"; public static final String DFS_CLIENT_CACHE_DROP_BEHIND_READS = "dfs.client.cache.drop.behind.reads"; public static final String DFS_CLIENT_CACHE_READAHEAD = "dfs.client.cache.readahead"; public static final String DFS_HDFS_BLOCKS_METADATA_ENABLED = "dfs.datanode.hdfs-blocks-metadata.enabled"; public static final boolean DFS_HDFS_BLOCKS_METADATA_ENABLED_DEFAULT = false; public static final String DFS_CLIENT_FILE_BLOCK_STORAGE_LOCATIONS_NUM_THREADS = "dfs.client.file-block-storage-locations.num-threads"; public static final int DFS_CLIENT_FILE_BLOCK_STORAGE_LOCATIONS_NUM_THREADS_DEFAULT = 10; public static final String DFS_CLIENT_FILE_BLOCK_STORAGE_LOCATIONS_TIMEOUT = "dfs.client.file-block-storage-locations.timeout"; public static final int DFS_CLIENT_FILE_BLOCK_STORAGE_LOCATIONS_TIMEOUT_DEFAULT = 60; // HA related configuration public static final String DFS_CLIENT_FAILOVER_PROXY_PROVIDER_KEY_PREFIX = "dfs.client.failover.proxy.provider"; public static final String DFS_CLIENT_FAILOVER_MAX_ATTEMPTS_KEY = "dfs.client.failover.max.attempts"; public static final int DFS_CLIENT_FAILOVER_MAX_ATTEMPTS_DEFAULT = 15; public static final String DFS_CLIENT_FAILOVER_SLEEPTIME_BASE_KEY = "dfs.client.failover.sleep.base.millis"; public static final int DFS_CLIENT_FAILOVER_SLEEPTIME_BASE_DEFAULT = 500; public static final String DFS_CLIENT_FAILOVER_SLEEPTIME_MAX_KEY = "dfs.client.failover.sleep.max.millis"; public static final int DFS_CLIENT_FAILOVER_SLEEPTIME_MAX_DEFAULT = 15000; public static final String DFS_CLIENT_FAILOVER_CONNECTION_RETRIES_KEY = "dfs.client.failover.connection.retries"; public static final int DFS_CLIENT_FAILOVER_CONNECTION_RETRIES_DEFAULT = 0; public static final String DFS_CLIENT_FAILOVER_CONNECTION_RETRIES_ON_SOCKET_TIMEOUTS_KEY = "dfs.client.failover.connection.retries.on.timeouts"; public static final int DFS_CLIENT_FAILOVER_CONNECTION_RETRIES_ON_SOCKET_TIMEOUTS_DEFAULT = 0; public static final String DFS_CLIENT_SOCKET_CACHE_EXPIRY_MSEC_KEY = "dfs.client.socketcache.expiryMsec"; public static final long DFS_CLIENT_SOCKET_CACHE_EXPIRY_MSEC_DEFAULT = 2 * 60 * 1000; public static final String DFS_DATANODE_BALANCE_BANDWIDTHPERSEC_KEY = "dfs.datanode.balance.bandwidthPerSec"; public static final long DFS_DATANODE_BALANCE_BANDWIDTHPERSEC_DEFAULT = 1024 * 1024; public static final String DFS_DATANODE_BALANCE_MAX_NUM_CONCURRENT_MOVES_KEY = "dfs.datanode.balance.max.concurrent.moves"; public static final int DFS_DATANODE_BALANCE_MAX_NUM_CONCURRENT_MOVES_DEFAULT = 5; public static final String DFS_DATANODE_READAHEAD_BYTES_KEY = "dfs.datanode.readahead.bytes"; public static final long DFS_DATANODE_READAHEAD_BYTES_DEFAULT = 4 * 1024 * 1024; // 4MB public static final String DFS_DATANODE_DROP_CACHE_BEHIND_WRITES_KEY = "dfs.datanode.drop.cache.behind.writes"; public static final boolean DFS_DATANODE_DROP_CACHE_BEHIND_WRITES_DEFAULT = false; public static final String DFS_DATANODE_SYNC_BEHIND_WRITES_KEY = "dfs.datanode.sync.behind.writes"; public static final boolean DFS_DATANODE_SYNC_BEHIND_WRITES_DEFAULT = false; public static final String DFS_DATANODE_DROP_CACHE_BEHIND_READS_KEY = "dfs.datanode.drop.cache.behind.reads"; public static final boolean DFS_DATANODE_DROP_CACHE_BEHIND_READS_DEFAULT = false; public static final String DFS_DATANODE_USE_DN_HOSTNAME = "dfs.datanode.use.datanode.hostname"; public static final boolean DFS_DATANODE_USE_DN_HOSTNAME_DEFAULT = false; public static final String DFS_NAMENODE_HTTP_PORT_KEY = "dfs.http.port"; public static final int DFS_NAMENODE_HTTP_PORT_DEFAULT = 50070; public static final String DFS_NAMENODE_HTTP_ADDRESS_KEY = "dfs.namenode.http-address"; public static final String DFS_NAMENODE_HTTP_ADDRESS_DEFAULT = "0.0.0.0:" + DFS_NAMENODE_HTTP_PORT_DEFAULT; public static final String DFS_NAMENODE_RPC_ADDRESS_KEY = "dfs.namenode.rpc-address"; public static final String DFS_NAMENODE_SERVICE_RPC_ADDRESS_KEY = "dfs.namenode.servicerpc-address"; public static final String DFS_NAMENODE_MAX_OBJECTS_KEY = "dfs.namenode.max.objects"; public static final long DFS_NAMENODE_MAX_OBJECTS_DEFAULT = 0; public static final String DFS_NAMENODE_SAFEMODE_EXTENSION_KEY = "dfs.namenode.safemode.extension"; public static final int DFS_NAMENODE_SAFEMODE_EXTENSION_DEFAULT = 30000; public static final String DFS_NAMENODE_SAFEMODE_THRESHOLD_PCT_KEY = "dfs.namenode.safemode.threshold-pct"; public static final float DFS_NAMENODE_SAFEMODE_THRESHOLD_PCT_DEFAULT = 0.999f; // set this to a slightly smaller value than // DFS_NAMENODE_SAFEMODE_THRESHOLD_PCT_DEFAULT to populate // needed replication queues before exiting safe mode public static final String DFS_NAMENODE_REPL_QUEUE_THRESHOLD_PCT_KEY = "dfs.namenode.replqueue.threshold-pct"; public static final String DFS_NAMENODE_SAFEMODE_MIN_DATANODES_KEY = "dfs.namenode.safemode.min.datanodes"; public static final int DFS_NAMENODE_SAFEMODE_MIN_DATANODES_DEFAULT = 0; public static final String DFS_NAMENODE_HEARTBEAT_RECHECK_INTERVAL_KEY = "dfs.namenode.heartbeat.recheck-interval"; public static final int DFS_NAMENODE_HEARTBEAT_RECHECK_INTERVAL_DEFAULT = 5 * 60 * 1000; public static final String DFS_NAMENODE_TOLERATE_HEARTBEAT_MULTIPLIER_KEY = "dfs.namenode.tolerate.heartbeat.multiplier"; public static final int DFS_NAMENODE_TOLERATE_HEARTBEAT_MULTIPLIER_DEFAULT = 4; public static final String DFS_CLIENT_HTTPS_KEYSTORE_RESOURCE_KEY = "dfs.client.https.keystore.resource"; public static final String DFS_CLIENT_HTTPS_KEYSTORE_RESOURCE_DEFAULT = "ssl-client.xml"; public static final String DFS_CLIENT_HTTPS_NEED_AUTH_KEY = "dfs.client.https.need-auth"; public static final boolean DFS_CLIENT_HTTPS_NEED_AUTH_DEFAULT = false; public static final String DFS_CLIENT_CACHED_CONN_RETRY_KEY = "dfs.client.cached.conn.retry"; public static final int DFS_CLIENT_CACHED_CONN_RETRY_DEFAULT = 3; public static final String DFS_NAMENODE_ACCESSTIME_PRECISION_KEY = "dfs.namenode.accesstime.precision"; public static final long DFS_NAMENODE_ACCESSTIME_PRECISION_DEFAULT = 3600000; public static final String DFS_NAMENODE_REPLICATION_CONSIDERLOAD_KEY = "dfs.namenode.replication.considerLoad"; public static final boolean DFS_NAMENODE_REPLICATION_CONSIDERLOAD_DEFAULT = true; public static final String DFS_NAMENODE_REPLICATION_INTERVAL_KEY = "dfs.namenode.replication.interval"; public static final int DFS_NAMENODE_REPLICATION_INTERVAL_DEFAULT = 3; public static final String DFS_NAMENODE_REPLICATION_MIN_KEY = "dfs.namenode.replication.min"; public static final int DFS_NAMENODE_REPLICATION_MIN_DEFAULT = 1; public static final String DFS_NAMENODE_REPLICATION_PENDING_TIMEOUT_SEC_KEY = "dfs.namenode.replication.pending.timeout-sec"; public static final int DFS_NAMENODE_REPLICATION_PENDING_TIMEOUT_SEC_DEFAULT = -1; public static final String DFS_NAMENODE_REPLICATION_MAX_STREAMS_KEY = "dfs.namenode.replication.max-streams"; public static final int DFS_NAMENODE_REPLICATION_MAX_STREAMS_DEFAULT = 2; public static final String DFS_NAMENODE_REPLICATION_STREAMS_HARD_LIMIT_KEY = "dfs.namenode.replication.max-streams-hard-limit"; public static final int DFS_NAMENODE_REPLICATION_STREAMS_HARD_LIMIT_DEFAULT = 4; public static final String DFS_WEBHDFS_ENABLED_KEY = "dfs.webhdfs.enabled"; public static final boolean DFS_WEBHDFS_ENABLED_DEFAULT = false; public static final String DFS_PERMISSIONS_ENABLED_KEY = "dfs.permissions.enabled"; public static final boolean DFS_PERMISSIONS_ENABLED_DEFAULT = true; public static final String DFS_PERSIST_BLOCKS_KEY = "dfs.persist.blocks"; public static final boolean DFS_PERSIST_BLOCKS_DEFAULT = false; public static final String DFS_PERMISSIONS_SUPERUSERGROUP_KEY = "dfs.permissions.superusergroup"; public static final String DFS_PERMISSIONS_SUPERUSERGROUP_DEFAULT = "supergroup"; public static final String DFS_ADMIN = "dfs.cluster.administrators"; public static final String DFS_SERVER_HTTPS_KEYSTORE_RESOURCE_KEY = "dfs.https.server.keystore.resource"; public static final String DFS_SERVER_HTTPS_KEYSTORE_RESOURCE_DEFAULT = "ssl-server.xml"; public static final String DFS_NAMENODE_NAME_DIR_RESTORE_KEY = "dfs.namenode.name.dir.restore"; public static final boolean DFS_NAMENODE_NAME_DIR_RESTORE_DEFAULT = false; public static final String DFS_NAMENODE_SUPPORT_ALLOW_FORMAT_KEY = "dfs.namenode.support.allow.format"; public static final boolean DFS_NAMENODE_SUPPORT_ALLOW_FORMAT_DEFAULT = true; public static final String DFS_NAMENODE_MIN_SUPPORTED_DATANODE_VERSION_KEY = "dfs.namenode.min.supported.datanode.version"; public static final String DFS_NAMENODE_MIN_SUPPORTED_DATANODE_VERSION_DEFAULT = "2.0.0-SNAPSHOT"; public static final String DFS_LIST_LIMIT = "dfs.ls.limit"; public static final int DFS_LIST_LIMIT_DEFAULT = Integer.MAX_VALUE; //1000; [HopsFS] Jira Hops-45 public static final String DFS_DATANODE_FAILED_VOLUMES_TOLERATED_KEY = "dfs.datanode.failed.volumes.tolerated"; public static final int DFS_DATANODE_FAILED_VOLUMES_TOLERATED_DEFAULT = 0; public static final String DFS_DATANODE_SYNCONCLOSE_KEY = "dfs.datanode.synconclose"; public static final boolean DFS_DATANODE_SYNCONCLOSE_DEFAULT = false; public static final String DFS_DATANODE_SOCKET_REUSE_KEEPALIVE_KEY = "dfs.datanode.socket.reuse.keepalive"; public static final int DFS_DATANODE_SOCKET_REUSE_KEEPALIVE_DEFAULT = 1000; public static final String DFS_NAMENODE_DATANODE_REGISTRATION_IP_HOSTNAME_CHECK_KEY = "dfs.namenode.datanode.registration.ip-hostname-check"; public static final boolean DFS_NAMENODE_DATANODE_REGISTRATION_IP_HOSTNAME_CHECK_DEFAULT = true; // Whether to enable datanode's stale state detection and usage for reads public static final String DFS_NAMENODE_AVOID_STALE_DATANODE_FOR_READ_KEY = "dfs.namenode.avoid.read.stale.datanode"; public static final boolean DFS_NAMENODE_AVOID_STALE_DATANODE_FOR_READ_DEFAULT = false; // Whether to enable datanode's stale state detection and usage for writes public static final String DFS_NAMENODE_AVOID_STALE_DATANODE_FOR_WRITE_KEY = "dfs.namenode.avoid.write.stale.datanode"; public static final boolean DFS_NAMENODE_AVOID_STALE_DATANODE_FOR_WRITE_DEFAULT = false; // The default value of the time interval for marking datanodes as stale public static final String DFS_NAMENODE_STALE_DATANODE_INTERVAL_KEY = "dfs.namenode.stale.datanode.interval"; public static final long DFS_NAMENODE_STALE_DATANODE_INTERVAL_DEFAULT = 30 * 1000; // 30s // The stale interval cannot be too small since otherwise this may cause too frequent churn on stale states. // This value uses the times of heartbeat interval to define the minimum value for stale interval. public static final String DFS_NAMENODE_STALE_DATANODE_MINIMUM_INTERVAL_KEY = "dfs.namenode.stale.datanode.minimum.interval"; public static final int DFS_NAMENODE_STALE_DATANODE_MINIMUM_INTERVAL_DEFAULT = 3; // i.e. min_interval is 3 * heartbeat_interval = 9s // When the percentage of stale datanodes reaches this ratio, // allow writing to stale nodes to prevent hotspots. public static final String DFS_NAMENODE_USE_STALE_DATANODE_FOR_WRITE_RATIO_KEY = "dfs.namenode.write.stale.datanode.ratio"; public static final float DFS_NAMENODE_USE_STALE_DATANODE_FOR_WRITE_RATIO_DEFAULT = 0.5f; // Replication monitoring related keys public static final String DFS_NAMENODE_INVALIDATE_WORK_PCT_PER_ITERATION = "dfs.namenode.invalidate.work.pct.per.iteration"; public static final float DFS_NAMENODE_INVALIDATE_WORK_PCT_PER_ITERATION_DEFAULT = 0.32f; public static final String DFS_NAMENODE_REPLICATION_WORK_MULTIPLIER_PER_ITERATION = "dfs.namenode.replication.work.multiplier.per.iteration"; public static final int DFS_NAMENODE_REPLICATION_WORK_MULTIPLIER_PER_ITERATION_DEFAULT = 2; //Delegation token related keys public static final String DFS_NAMENODE_DELEGATION_KEY_UPDATE_INTERVAL_KEY = "dfs.namenode.delegation.key.update-interval"; public static final long DFS_NAMENODE_DELEGATION_KEY_UPDATE_INTERVAL_DEFAULT = 24 * 60 * 60 * 1000; // 1 day public static final String DFS_NAMENODE_DELEGATION_TOKEN_RENEW_INTERVAL_KEY = "dfs.namenode.delegation.token.renew-interval"; public static final long DFS_NAMENODE_DELEGATION_TOKEN_RENEW_INTERVAL_DEFAULT = 24 * 60 * 60 * 1000; // 1 day public static final String DFS_NAMENODE_DELEGATION_TOKEN_MAX_LIFETIME_KEY = "dfs.namenode.delegation.token.max-lifetime"; public static final long DFS_NAMENODE_DELEGATION_TOKEN_MAX_LIFETIME_DEFAULT = 7 * 24 * 60 * 60 * 1000; // 7 days public static final String DFS_NAMENODE_DELEGATION_TOKEN_ALWAYS_USE_KEY = "dfs.namenode.delegation.token.always-use"; // for tests public static final boolean DFS_NAMENODE_DELEGATION_TOKEN_ALWAYS_USE_DEFAULT = false; //Filesystem limit keys public static final String DFS_NAMENODE_MAX_COMPONENT_LENGTH_KEY = "dfs.namenode.fs-limits.max-component-length"; public static final int DFS_NAMENODE_MAX_COMPONENT_LENGTH_DEFAULT = 0; // no limit public static final String DFS_NAMENODE_MAX_DIRECTORY_ITEMS_KEY = "dfs.namenode.fs-limits.max-directory-items"; public static final int DFS_NAMENODE_MAX_DIRECTORY_ITEMS_DEFAULT = 0; public static final String DFS_NAMENODE_MIN_BLOCK_SIZE_KEY = "dfs.namenode.fs-limits.min-block-size"; public static final long DFS_NAMENODE_MIN_BLOCK_SIZE_DEFAULT = 1024*1024; public static final String DFS_NAMENODE_MAX_BLOCKS_PER_FILE_KEY = "dfs.namenode.fs-limits.max-blocks-per-file"; public static final long DFS_NAMENODE_MAX_BLOCKS_PER_FILE_DEFAULT = 1024*1024; //Following keys have no defaults public static final String DFS_DATANODE_DATA_DIR_KEY = "dfs.datanode.data.dir"; public static final String DFS_NAMENODE_HTTPS_PORT_KEY = "dfs.https.port"; public static final int DFS_NAMENODE_HTTPS_PORT_DEFAULT = 50470; public static final String DFS_NAMENODE_HTTPS_ADDRESS_KEY = "dfs.namenode.https-address"; public static final String DFS_NAMENODE_HTTPS_ADDRESS_DEFAULT = "0.0.0.0:" + DFS_NAMENODE_HTTPS_PORT_DEFAULT; public static final String DFS_CLIENT_READ_PREFETCH_SIZE_KEY = "dfs.client.read.prefetch.size"; public static final String DFS_CLIENT_RETRY_WINDOW_BASE = "dfs.client.retry.window.base"; public static final String DFS_METRICS_SESSION_ID_KEY = "dfs.metrics.session-id"; public static final String DFS_METRICS_PERCENTILES_INTERVALS_KEY = "dfs.metrics.percentiles.intervals"; public static final String DFS_DATANODE_HOST_NAME_KEY = "dfs.datanode.hostname"; public static final String DFS_NAMENODE_HOSTS_KEY = "dfs.namenode.hosts"; public static final String DFS_NAMENODE_HOSTS_EXCLUDE_KEY = "dfs.namenode.hosts.exclude"; public static final String DFS_CLIENT_SOCKET_TIMEOUT_KEY = "dfs.client.socket-timeout"; public static final String DFS_HOSTS = "dfs.hosts"; public static final String DFS_HOSTS_EXCLUDE = "dfs.hosts.exclude"; public static final String DFS_CLIENT_LOCAL_INTERFACES = "dfs.client.local.interfaces"; public static final String DFS_NAMENODE_AUDIT_LOGGERS_KEY = "dfs.namenode.audit.loggers"; public static final String DFS_NAMENODE_DEFAULT_AUDIT_LOGGER_NAME = "default"; // Much code in hdfs is not yet updated to use these keys. public static final String DFS_CLIENT_BLOCK_WRITE_LOCATEFOLLOWINGBLOCK_RETRIES_KEY = "dfs.client.block.write.locateFollowingBlock.retries"; public static final int DFS_CLIENT_BLOCK_WRITE_LOCATEFOLLOWINGBLOCK_RETRIES_DEFAULT = 10; //HOP default was 5 public static final String DFS_CLIENT_BLOCK_WRITE_RETRIES_KEY = "dfs.client.block.write.retries"; public static final int DFS_CLIENT_BLOCK_WRITE_RETRIES_DEFAULT = 3; public static final String DFS_CLIENT_MAX_BLOCK_ACQUIRE_FAILURES_KEY = "dfs.client.max.block.acquire.failures"; public static final int DFS_CLIENT_MAX_BLOCK_ACQUIRE_FAILURES_DEFAULT = 3; public static final String DFS_CLIENT_USE_LEGACY_BLOCKREADER = "dfs.client.use.legacy.blockreader"; public static final boolean DFS_CLIENT_USE_LEGACY_BLOCKREADER_DEFAULT = false; public static final String DFS_CLIENT_USE_LEGACY_BLOCKREADERLOCAL = "dfs.client.use.legacy.blockreader.local"; public static final boolean DFS_CLIENT_USE_LEGACY_BLOCKREADERLOCAL_DEFAULT = false; public static final String DFS_BALANCER_MOVEDWINWIDTH_KEY = "dfs.balancer.movedWinWidth"; public static final long DFS_BALANCER_MOVEDWINWIDTH_DEFAULT = 5400*1000L; public static final String DFS_BALANCER_MOVERTHREADS_KEY = "dfs.balancer.moverThreads"; public static final int DFS_BALANCER_MOVERTHREADS_DEFAULT = 1000; public static final String DFS_BALANCER_DISPATCHERTHREADS_KEY = "dfs.balancer.dispatcherThreads"; public static final int DFS_BALANCER_DISPATCHERTHREADS_DEFAULT = 200; public static final String DFS_MOVER_MOVEDWINWIDTH_KEY = "dfs.mover.movedWinWidth"; public static final long DFS_MOVER_MOVEDWINWIDTH_DEFAULT = 5400*1000L; public static final String DFS_MOVER_MOVERTHREADS_KEY = "dfs.mover.moverThreads"; public static final int DFS_MOVER_MOVERTHREADS_DEFAULT = 1000; public static final String DFS_DATANODE_ADDRESS_KEY = "dfs.datanode.address"; public static final int DFS_DATANODE_DEFAULT_PORT = 50010; public static final String DFS_DATANODE_ADDRESS_DEFAULT = "0.0.0.0:" + DFS_DATANODE_DEFAULT_PORT; public static final String DFS_DATANODE_DATA_DIR_PERMISSION_KEY = "dfs.datanode.data.dir.perm"; public static final String DFS_DATANODE_DATA_DIR_PERMISSION_DEFAULT = "700"; public static final String DFS_DATANODE_DIRECTORYSCAN_INTERVAL_KEY = "dfs.datanode.directoryscan.interval"; public static final int DFS_DATANODE_DIRECTORYSCAN_INTERVAL_DEFAULT = 21600; public static final String DFS_DATANODE_DIRECTORYSCAN_THREADS_KEY = "dfs.datanode.directoryscan.threads"; public static final int DFS_DATANODE_DIRECTORYSCAN_THREADS_DEFAULT = 1; public static final String DFS_DATANODE_DNS_INTERFACE_KEY = "dfs.datanode.dns.interface"; public static final String DFS_DATANODE_DNS_INTERFACE_DEFAULT = "default"; public static final String DFS_DATANODE_DNS_NAMESERVER_KEY = "dfs.datanode.dns.nameserver"; public static final String DFS_DATANODE_DNS_NAMESERVER_DEFAULT = "default"; public static final String DFS_DATANODE_DU_RESERVED_KEY = "dfs.datanode.du.reserved"; public static final long DFS_DATANODE_DU_RESERVED_DEFAULT = 0; public static final String DFS_DATANODE_HANDLER_COUNT_KEY = "dfs.datanode.handler.count"; public static final int DFS_DATANODE_HANDLER_COUNT_DEFAULT = 10; public static final String DFS_DATANODE_HTTP_ADDRESS_KEY = "dfs.datanode.http.address"; public static final int DFS_DATANODE_HTTP_DEFAULT_PORT = 50075; public static final String DFS_DATANODE_HTTP_ADDRESS_DEFAULT = "0.0.0.0:" + DFS_DATANODE_HTTP_DEFAULT_PORT; public static final String DFS_DATANODE_MAX_RECEIVER_THREADS_KEY = "dfs.datanode.max.transfer.threads"; public static final int DFS_DATANODE_MAX_RECEIVER_THREADS_DEFAULT = 4096; public static final String DFS_DATANODE_NUMBLOCKS_KEY = "dfs.datanode.numblocks"; public static final int DFS_DATANODE_NUMBLOCKS_DEFAULT = 64; public static final String DFS_DATANODE_SCAN_PERIOD_HOURS_KEY = "dfs.datanode.scan.period.hours"; public static final int DFS_DATANODE_SCAN_PERIOD_HOURS_DEFAULT = 0; public static final String DFS_DATANODE_TRANSFERTO_ALLOWED_KEY = "dfs.datanode.transferTo.allowed"; public static final boolean DFS_DATANODE_TRANSFERTO_ALLOWED_DEFAULT = true; public static final String DFS_HEARTBEAT_INTERVAL_KEY = "dfs.heartbeat.interval"; public static final long DFS_HEARTBEAT_INTERVAL_DEFAULT = 3; public static final String DFS_NAMENODE_DECOMMISSION_INTERVAL_KEY = "dfs.namenode.decommission.interval"; public static final int DFS_NAMENODE_DECOMMISSION_INTERVAL_DEFAULT = 30; public static final String DFS_NAMENODE_DECOMMISSION_NODES_PER_INTERVAL_KEY = "dfs.namenode.decommission.nodes.per.interval"; public static final int DFS_NAMENODE_DECOMMISSION_NODES_PER_INTERVAL_DEFAULT = 5; public static final String DFS_NAMENODE_HANDLER_COUNT_KEY = "dfs.namenode.handler.count"; public static final int DFS_NAMENODE_HANDLER_COUNT_DEFAULT = 10; public static final String DFS_NAMENODE_SERVICE_HANDLER_COUNT_KEY = "dfs.namenode.service.handler.count"; public static final int DFS_NAMENODE_SERVICE_HANDLER_COUNT_DEFAULT = 10; public static final String DFS_SUPPORT_APPEND_KEY = "dfs.support.append"; public static final boolean DFS_SUPPORT_APPEND_DEFAULT = true; public static final String DFS_HTTPS_ENABLE_KEY = "dfs.https.enable"; public static final boolean DFS_HTTPS_ENABLE_DEFAULT = false; public static final String DFS_DEFAULT_CHUNK_VIEW_SIZE_KEY = "dfs.default.chunk.view.size"; public static final int DFS_DEFAULT_CHUNK_VIEW_SIZE_DEFAULT = 32 * 1024; public static final String DFS_DATANODE_HTTPS_ADDRESS_KEY = "dfs.datanode.https.address"; public static final String DFS_DATANODE_HTTPS_PORT_KEY = "datanode.https.port"; public static final int DFS_DATANODE_HTTPS_DEFAULT_PORT = 50475; public static final String DFS_DATANODE_HTTPS_ADDRESS_DEFAULT = "0.0.0.0:" + DFS_DATANODE_HTTPS_DEFAULT_PORT; public static final String DFS_DATANODE_IPC_ADDRESS_KEY = "dfs.datanode.ipc.address"; public static final int DFS_DATANODE_IPC_DEFAULT_PORT = 50020; public static final String DFS_DATANODE_IPC_ADDRESS_DEFAULT = "0.0.0.0:" + DFS_DATANODE_IPC_DEFAULT_PORT; public static final String DFS_DATANODE_MIN_SUPPORTED_NAMENODE_VERSION_KEY = "dfs.datanode.min.supported.namenode.version"; public static final String DFS_DATANODE_MIN_SUPPORTED_NAMENODE_VERSION_DEFAULT = "2.0.0-SNAPSHOT"; public static final String DFS_BLOCK_ACCESS_TOKEN_ENABLE_KEY = "dfs.block.access.token.enable"; public static final boolean DFS_BLOCK_ACCESS_TOKEN_ENABLE_DEFAULT = false; public static final String DFS_BLOCK_ACCESS_KEY_UPDATE_INTERVAL_KEY = "dfs.block.access.key.update.interval"; public static final long DFS_BLOCK_ACCESS_KEY_UPDATE_INTERVAL_DEFAULT = 600L; public static final String DFS_BLOCK_ACCESS_TOKEN_LIFETIME_KEY = "dfs.block.access.token.lifetime"; public static final long DFS_BLOCK_ACCESS_TOKEN_LIFETIME_DEFAULT = 600L; public static final String DFS_BLOCK_REPLICATOR_CLASSNAME_KEY = "dfs.block.replicator.classname"; public static final Class<BlockPlacementPolicyDefault> DFS_BLOCK_REPLICATOR_CLASSNAME_DEFAULT = BlockPlacementPolicyDefault.class; public static final String DFS_REPLICATION_MAX_KEY = "dfs.replication.max"; public static final int DFS_REPLICATION_MAX_DEFAULT = 512; public static final String DFS_DF_INTERVAL_KEY = "dfs.df.interval"; public static final int DFS_DF_INTERVAL_DEFAULT = 60000; public static final String DFS_BLOCKREPORT_INTERVAL_MSEC_KEY = "dfs.blockreport.intervalMsec"; public static final long DFS_BLOCKREPORT_INTERVAL_MSEC_DEFAULT = 60 * 60 * 1000L; public static final String DFS_BLOCKREPORT_INITIAL_DELAY_KEY = "dfs.blockreport.initialDelay"; public static final int DFS_BLOCKREPORT_INITIAL_DELAY_DEFAULT = 0; public static final String DFS_BLOCKREPORT_SPLIT_THRESHOLD_KEY = "dfs.blockreport.split.threshold"; public static final long DFS_BLOCKREPORT_SPLIT_THRESHOLD_DEFAULT = 1000 * 1000; public static final String DFS_BLOCK_INVALIDATE_LIMIT_KEY = "dfs.block.invalidate.limit"; public static final int DFS_BLOCK_INVALIDATE_LIMIT_DEFAULT = 1000; public static final String DFS_DEFAULT_MAX_CORRUPT_FILES_RETURNED_KEY = "dfs.corruptfilesreturned.max"; public static final int DFS_DEFAULT_MAX_CORRUPT_FILES_RETURNED = 500; public static final String DFS_CLIENT_READ_SHORTCIRCUIT_KEY = "dfs.client.read.shortcircuit"; public static final boolean DFS_CLIENT_READ_SHORTCIRCUIT_DEFAULT = false; public static final String DFS_CLIENT_READ_SHORTCIRCUIT_SKIP_CHECKSUM_KEY = "dfs.client.read.shortcircuit.skip.checksum"; public static final boolean DFS_CLIENT_READ_SHORTCIRCUIT_SKIP_CHECKSUM_DEFAULT = false; public static final String DFS_CLIENT_READ_SHORTCIRCUIT_BUFFER_SIZE_KEY = "dfs.client.read.shortcircuit.buffer.size"; public static final String DFS_CLIENT_READ_SHORTCIRCUIT_STREAMS_CACHE_SIZE_KEY = "dfs.client.read.shortcircuit.streams.cache.size"; public static final int DFS_CLIENT_READ_SHORTCIRCUIT_STREAMS_CACHE_SIZE_DEFAULT = 100; public static final String DFS_CLIENT_READ_SHORTCIRCUIT_STREAMS_CACHE_EXPIRY_MS_KEY = "dfs.client.read.shortcircuit.streams.cache.expiry.ms"; public static final long DFS_CLIENT_READ_SHORTCIRCUIT_STREAMS_CACHE_EXPIRY_MS_DEFAULT = 5000; public static final int DFS_CLIENT_READ_SHORTCIRCUIT_BUFFER_SIZE_DEFAULT = 1024 * 1024; public static final String DFS_CLIENT_DOMAIN_SOCKET_DATA_TRAFFIC = "dfs.client.domain.socket.data.traffic"; public static final boolean DFS_CLIENT_DOMAIN_SOCKET_DATA_TRAFFIC_DEFAULT = false; //Keys with no defaults public static final String DFS_DATANODE_PLUGINS_KEY = "dfs.datanode.plugins"; public static final String DFS_DATANODE_FSDATASET_FACTORY_KEY = "dfs.datanode.fsdataset.factory"; public static final String DFS_DATANODE_FSDATASET_VOLUME_CHOOSING_POLICY_KEY = "dfs.datanode.fsdataset.volume.choosing.policy"; public static final String DFS_DATANODE_AVAILABLE_SPACE_VOLUME_CHOOSING_POLICY_BALANCED_SPACE_THRESHOLD_KEY = "dfs.datanode.available-space-volume-choosing-policy.balanced-space-threshold"; public static final long DFS_DATANODE_AVAILABLE_SPACE_VOLUME_CHOOSING_POLICY_BALANCED_SPACE_THRESHOLD_DEFAULT = 1024L * 1024L * 1024L * 10L; // 10 GB public static final String DFS_DATANODE_AVAILABLE_SPACE_VOLUME_CHOOSING_POLICY_BALANCED_SPACE_PREFERENCE_FRACTION_KEY = "dfs.datanode.available-space-volume-choosing-policy.balanced-space-preference-fraction"; public static final float DFS_DATANODE_AVAILABLE_SPACE_VOLUME_CHOOSING_POLICY_BALANCED_SPACE_PREFERENCE_FRACTION_DEFAULT = 0.75f; public static final String DFS_DATANODE_SOCKET_WRITE_TIMEOUT_KEY = "dfs.datanode.socket.write.timeout"; public static final String DFS_DATANODE_STARTUP_KEY = "dfs.datanode.startup"; public static final String DFS_NAMENODE_PLUGINS_KEY = "dfs.namenode.plugins"; public static final String DFS_WEB_UGI_KEY = "dfs.web.ugi"; public static final String DFS_NAMENODE_STARTUP_KEY = "dfs.namenode.startup"; public static final String DFS_DATANODE_KEYTAB_FILE_KEY = "dfs.datanode.keytab.file"; public static final String DFS_DATANODE_USER_NAME_KEY = "dfs.datanode.kerberos.principal"; public static final String DFS_NAMENODE_KEYTAB_FILE_KEY = "dfs.namenode.keytab.file"; public static final String DFS_NAMENODE_USER_NAME_KEY = "dfs.namenode.kerberos.principal"; public static final String DFS_NAMENODE_INTERNAL_SPNEGO_USER_NAME_KEY = "dfs.namenode.kerberos.internal.spnego.principal"; public static final String DFS_NAMENODE_NAME_CACHE_THRESHOLD_KEY = "dfs.namenode.name.cache.threshold"; public static final int DFS_NAMENODE_NAME_CACHE_THRESHOLD_DEFAULT = 10; public static final String DFS_NAMENODE_RESOURCE_CHECK_INTERVAL_KEY = "dfs.namenode.resource.check.interval"; public static final int DFS_NAMENODE_RESOURCE_CHECK_INTERVAL_DEFAULT = 5000; public static final String DFS_NAMENODE_DU_RESERVED_KEY = "dfs.namenode.resource.du.reserved"; public static final long DFS_NAMENODE_DU_RESERVED_DEFAULT = 1024 * 1024 * 100; // 100 MB public static final String DFS_NAMENODE_CHECKED_VOLUMES_KEY = "dfs.namenode.resource.checked.volumes"; public static final String DFS_NAMENODE_CHECKED_VOLUMES_MINIMUM_KEY = "dfs.namenode.resource.checked.volumes.minimum"; public static final int DFS_NAMENODE_CHECKED_VOLUMES_MINIMUM_DEFAULT = 1; public static final String DFS_WEB_AUTHENTICATION_KERBEROS_PRINCIPAL_KEY = "dfs.web.authentication.kerberos.principal"; public static final String DFS_WEB_AUTHENTICATION_KERBEROS_KEYTAB_KEY = "dfs.web.authentication.kerberos.keytab"; public static final String DFS_NAMENODE_MAX_OP_SIZE_KEY = "dfs.namenode.max.op.size"; public static final int DFS_NAMENODE_MAX_OP_SIZE_DEFAULT = 50 * 1024 * 1024; public static final String DFS_BLOCK_LOCAL_PATH_ACCESS_USER_KEY = "dfs.block.local-path-access.user"; public static final String DFS_DOMAIN_SOCKET_PATH_KEY = "dfs.domain.socket.path"; public static final String DFS_DOMAIN_SOCKET_PATH_DEFAULT = ""; public static final String DFS_STORAGE_POLICY_ENABLED_KEY = "dfs.storage.policy.enabled"; public static final boolean DFS_STORAGE_POLICY_ENABLED_DEFAULT = true; // Security-related configs public static final String DFS_ENCRYPT_DATA_TRANSFER_KEY = "dfs.encrypt.data.transfer"; public static final boolean DFS_ENCRYPT_DATA_TRANSFER_DEFAULT = false; public static final String DFS_DATA_ENCRYPTION_ALGORITHM_KEY = "dfs.encrypt.data.transfer.algorithm"; // Hash bucket config public static final String DFS_NUM_BUCKETS_KEY = "dfs.blockreport.numbuckets"; public static final int DFS_NUM_BUCKETS_DEFAULT = 1000; // Handling unresolved DN topology mapping public static final String DFS_REJECT_UNRESOLVED_DN_TOPOLOGY_MAPPING_KEY = "dfs.namenode.reject-unresolved-dn-topology-mapping"; public static final boolean DFS_REJECT_UNRESOLVED_DN_TOPOLOGY_MAPPING_DEFAULT = false; public static final String DFS_MAX_NUM_BLOCKS_TO_LOG_KEY = "dfs.namenode.max-num-blocks-to-log"; public static final long DFS_MAX_NUM_BLOCKS_TO_LOG_DEFAULT = 1000l; public static final String DFS_NAMENODE_ENABLE_RETRY_CACHE_KEY = "dfs.namenode.enable.retrycache"; public static final boolean DFS_NAMENODE_ENABLE_RETRY_CACHE_DEFAULT = true; public static final String DFS_NAMENODE_RETRY_CACHE_EXPIRYTIME_MILLIS_KEY = "dfs.namenode.retrycache.expirytime.millis"; public static final long DFS_NAMENODE_RETRY_CACHE_EXPIRYTIME_MILLIS_DEFAULT = 600000; // 10 minutes public static final String DFS_NAMENODE_RETRY_CACHE_HEAP_PERCENT_KEY = "dfs.namenode.retrycache.heap.percent"; public static final float DFS_NAMENODE_RETRY_CACHE_HEAP_PERCENT_DEFAULT = 0.03f; // Hidden configuration undocumented in hdfs-site. xml // Timeout to wait for block receiver and responder thread to stop public static final String DFS_DATANODE_XCEIVER_STOP_TIMEOUT_MILLIS_KEY = "dfs.datanode.xceiver.stop.timeout.millis"; public static final long DFS_DATANODE_XCEIVER_STOP_TIMEOUT_MILLIS_DEFAULT = 60000; }
[HOPS-289] apply HDFS-5083
hadoop-hdfs-project/hadoop-hdfs/src/main/java/org/apache/hadoop/hdfs/DFSConfigKeys.java
[HOPS-289] apply HDFS-5083
<ide><path>adoop-hdfs-project/hadoop-hdfs/src/main/java/org/apache/hadoop/hdfs/DFSConfigKeys.java <ide> public static final String DFS_NAMENODE_MIN_SUPPORTED_DATANODE_VERSION_KEY = <ide> "dfs.namenode.min.supported.datanode.version"; <ide> public static final String <del> DFS_NAMENODE_MIN_SUPPORTED_DATANODE_VERSION_DEFAULT = "2.0.0-SNAPSHOT"; <add> DFS_NAMENODE_MIN_SUPPORTED_DATANODE_VERSION_DEFAULT = "2.1.0-beta"; <ide> <ide> public static final String DFS_LIST_LIMIT = "dfs.ls.limit"; <ide> public static final int DFS_LIST_LIMIT_DEFAULT = Integer.MAX_VALUE; //1000; [HopsFS] Jira Hops-45 <ide> public static final String DFS_DATANODE_MIN_SUPPORTED_NAMENODE_VERSION_KEY = <ide> "dfs.datanode.min.supported.namenode.version"; <ide> public static final String <del> DFS_DATANODE_MIN_SUPPORTED_NAMENODE_VERSION_DEFAULT = "2.0.0-SNAPSHOT"; <add> DFS_DATANODE_MIN_SUPPORTED_NAMENODE_VERSION_DEFAULT = "2.1.0-beta"; <ide> <ide> public static final String DFS_BLOCK_ACCESS_TOKEN_ENABLE_KEY = <ide> "dfs.block.access.token.enable";
Java
apache-2.0
5e37db2f27a02b5c31c8b7a76b18f42e9d243111
0
nizhikov/ignite,nizhikov/ignite,apache/ignite,NSAmelchev/ignite,daradurvs/ignite,xtern/ignite,nizhikov/ignite,nizhikov/ignite,NSAmelchev/ignite,apache/ignite,daradurvs/ignite,xtern/ignite,NSAmelchev/ignite,daradurvs/ignite,daradurvs/ignite,chandresh-pancholi/ignite,NSAmelchev/ignite,nizhikov/ignite,NSAmelchev/ignite,apache/ignite,xtern/ignite,NSAmelchev/ignite,ascherbakoff/ignite,chandresh-pancholi/ignite,ascherbakoff/ignite,xtern/ignite,nizhikov/ignite,NSAmelchev/ignite,ascherbakoff/ignite,ascherbakoff/ignite,daradurvs/ignite,apache/ignite,chandresh-pancholi/ignite,apache/ignite,chandresh-pancholi/ignite,chandresh-pancholi/ignite,xtern/ignite,nizhikov/ignite,NSAmelchev/ignite,xtern/ignite,ascherbakoff/ignite,xtern/ignite,apache/ignite,daradurvs/ignite,ascherbakoff/ignite,chandresh-pancholi/ignite,apache/ignite,ascherbakoff/ignite,ascherbakoff/ignite,daradurvs/ignite,apache/ignite,xtern/ignite,daradurvs/ignite,ascherbakoff/ignite,NSAmelchev/ignite,nizhikov/ignite,chandresh-pancholi/ignite,xtern/ignite,chandresh-pancholi/ignite,daradurvs/ignite,chandresh-pancholi/ignite,daradurvs/ignite,apache/ignite,nizhikov/ignite
/* * 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. */ package org.apache.ignite.internal; import java.io.Externalizable; import java.io.File; import java.io.IOException; import java.io.InputStream; import java.io.InvalidObjectException; import java.io.ObjectInput; import java.io.ObjectOutput; import java.io.ObjectStreamException; import java.io.Serializable; import java.io.UncheckedIOException; import java.lang.management.ManagementFactory; import java.lang.management.RuntimeMXBean; import java.lang.reflect.Constructor; import java.nio.charset.Charset; import java.nio.file.DirectoryStream; import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.Paths; import java.text.DateFormat; import java.text.DecimalFormat; import java.text.DecimalFormatSymbols; import java.util.ArrayList; import java.util.Arrays; import java.util.Collection; import java.util.Collections; import java.util.Date; import java.util.HashMap; import java.util.List; import java.util.ListIterator; import java.util.Locale; import java.util.Map; import java.util.Properties; import java.util.UUID; import java.util.concurrent.ExecutorService; import java.util.concurrent.ThreadPoolExecutor; import java.util.concurrent.atomic.AtomicBoolean; import java.util.concurrent.atomic.AtomicReference; import javax.cache.CacheException; import javax.management.JMException; import org.apache.ignite.DataRegionMetrics; import org.apache.ignite.DataRegionMetricsAdapter; import org.apache.ignite.DataStorageMetrics; import org.apache.ignite.DataStorageMetricsAdapter; import org.apache.ignite.Ignite; import org.apache.ignite.IgniteAtomicLong; import org.apache.ignite.IgniteAtomicReference; import org.apache.ignite.IgniteAtomicSequence; import org.apache.ignite.IgniteAtomicStamped; import org.apache.ignite.IgniteBinary; import org.apache.ignite.IgniteCache; import org.apache.ignite.IgniteCheckedException; import org.apache.ignite.IgniteClientDisconnectedException; import org.apache.ignite.IgniteCompute; import org.apache.ignite.IgniteCountDownLatch; import org.apache.ignite.IgniteDataStreamer; import org.apache.ignite.IgniteEncryption; import org.apache.ignite.IgniteEvents; import org.apache.ignite.IgniteException; import org.apache.ignite.IgniteLock; import org.apache.ignite.IgniteLogger; import org.apache.ignite.IgniteMessaging; import org.apache.ignite.IgniteQueue; import org.apache.ignite.IgniteScheduler; import org.apache.ignite.IgniteSemaphore; import org.apache.ignite.IgniteServices; import org.apache.ignite.IgniteSet; import org.apache.ignite.IgniteSnapshot; import org.apache.ignite.IgniteSystemProperties; import org.apache.ignite.IgniteTransactions; import org.apache.ignite.Ignition; import org.apache.ignite.MemoryMetrics; import org.apache.ignite.PersistenceMetrics; import org.apache.ignite.cache.affinity.Affinity; import org.apache.ignite.cluster.BaselineNode; import org.apache.ignite.cluster.ClusterGroup; import org.apache.ignite.cluster.ClusterMetrics; import org.apache.ignite.cluster.ClusterNode; import org.apache.ignite.cluster.ClusterState; import org.apache.ignite.compute.ComputeJob; import org.apache.ignite.configuration.AtomicConfiguration; import org.apache.ignite.configuration.BinaryConfiguration; import org.apache.ignite.configuration.CacheConfiguration; import org.apache.ignite.configuration.CollectionConfiguration; import org.apache.ignite.configuration.DataRegionConfiguration; import org.apache.ignite.configuration.DataStorageConfiguration; import org.apache.ignite.configuration.IgniteConfiguration; import org.apache.ignite.configuration.MemoryConfiguration; import org.apache.ignite.configuration.NearCacheConfiguration; import org.apache.ignite.events.EventType; import org.apache.ignite.internal.binary.BinaryEnumCache; import org.apache.ignite.internal.binary.BinaryMarshaller; import org.apache.ignite.internal.binary.BinaryUtils; import org.apache.ignite.internal.cluster.ClusterGroupAdapter; import org.apache.ignite.internal.cluster.IgniteClusterEx; import org.apache.ignite.internal.maintenance.MaintenanceProcessor; import org.apache.ignite.internal.managers.GridManager; import org.apache.ignite.internal.managers.IgniteMBeansManager; import org.apache.ignite.internal.managers.checkpoint.GridCheckpointManager; import org.apache.ignite.internal.managers.collision.GridCollisionManager; import org.apache.ignite.internal.managers.communication.GridIoManager; import org.apache.ignite.internal.managers.deployment.GridDeploymentManager; import org.apache.ignite.internal.managers.discovery.DiscoveryLocalJoinData; import org.apache.ignite.internal.managers.discovery.GridDiscoveryManager; import org.apache.ignite.internal.managers.encryption.GridEncryptionManager; import org.apache.ignite.internal.managers.eventstorage.GridEventStorageManager; import org.apache.ignite.internal.managers.failover.GridFailoverManager; import org.apache.ignite.internal.managers.indexing.GridIndexingManager; import org.apache.ignite.internal.managers.loadbalancer.GridLoadBalancerManager; import org.apache.ignite.internal.managers.systemview.GridSystemViewManager; import org.apache.ignite.internal.managers.tracing.GridTracingManager; import org.apache.ignite.internal.marshaller.optimized.OptimizedMarshaller; import org.apache.ignite.internal.processors.GridProcessor; import org.apache.ignite.internal.processors.GridProcessorAdapter; import org.apache.ignite.internal.processors.affinity.AffinityTopologyVersion; import org.apache.ignite.internal.processors.affinity.GridAffinityProcessor; import org.apache.ignite.internal.processors.authentication.IgniteAuthenticationProcessor; import org.apache.ignite.internal.processors.cache.CacheConfigurationOverride; import org.apache.ignite.internal.processors.cache.GridCacheAdapter; import org.apache.ignite.internal.processors.cache.GridCacheContext; import org.apache.ignite.internal.processors.cache.GridCacheProcessor; import org.apache.ignite.internal.processors.cache.GridCacheUtilityKey; import org.apache.ignite.internal.processors.cache.IgniteCacheProxy; import org.apache.ignite.internal.processors.cache.IgniteInternalCache; import org.apache.ignite.internal.processors.cache.binary.CacheObjectBinaryProcessorImpl; import org.apache.ignite.internal.processors.cache.mvcc.MvccProcessorImpl; import org.apache.ignite.internal.processors.cache.persistence.DataRegion; import org.apache.ignite.internal.processors.cache.persistence.IgniteCacheDatabaseSharedManager; import org.apache.ignite.internal.processors.cache.persistence.filename.PdsConsistentIdProcessor; import org.apache.ignite.internal.processors.cacheobject.IgniteCacheObjectProcessor; import org.apache.ignite.internal.processors.closure.GridClosureProcessor; import org.apache.ignite.internal.processors.cluster.ClusterProcessor; import org.apache.ignite.internal.processors.cluster.DiscoveryDataClusterState; import org.apache.ignite.internal.processors.cluster.GridClusterStateProcessor; import org.apache.ignite.internal.processors.cluster.IGridClusterStateProcessor; import org.apache.ignite.internal.processors.configuration.distributed.DistributedConfigurationProcessor; import org.apache.ignite.internal.processors.continuous.GridContinuousProcessor; import org.apache.ignite.internal.processors.datastreamer.DataStreamProcessor; import org.apache.ignite.internal.processors.datastructures.DataStructuresProcessor; import org.apache.ignite.internal.processors.diagnostic.DiagnosticProcessor; import org.apache.ignite.internal.processors.failure.FailureProcessor; import org.apache.ignite.internal.processors.job.GridJobProcessor; import org.apache.ignite.internal.processors.jobmetrics.GridJobMetricsProcessor; import org.apache.ignite.internal.processors.localtask.DurableBackgroundTasksProcessor; import org.apache.ignite.internal.processors.marshaller.GridMarshallerMappingProcessor; import org.apache.ignite.internal.processors.metastorage.persistence.DistributedMetaStorageImpl; import org.apache.ignite.internal.processors.metric.GridMetricManager; import org.apache.ignite.internal.processors.metric.MetricRegistry; import org.apache.ignite.internal.processors.nodevalidation.DiscoveryNodeValidationProcessor; import org.apache.ignite.internal.processors.nodevalidation.OsDiscoveryNodeValidationProcessor; import org.apache.ignite.internal.processors.odbc.ClientListenerProcessor; import org.apache.ignite.internal.processors.platform.PlatformNoopProcessor; import org.apache.ignite.internal.processors.platform.PlatformProcessor; import org.apache.ignite.internal.processors.platform.plugin.PlatformPluginProcessor; import org.apache.ignite.internal.processors.plugin.IgnitePluginProcessor; import org.apache.ignite.internal.processors.pool.PoolProcessor; import org.apache.ignite.internal.processors.port.GridPortProcessor; import org.apache.ignite.internal.processors.port.GridPortRecord; import org.apache.ignite.internal.processors.query.GridQueryProcessor; import org.apache.ignite.internal.processors.resource.GridResourceProcessor; import org.apache.ignite.internal.processors.resource.GridSpringResourceContext; import org.apache.ignite.internal.processors.rest.GridRestProcessor; import org.apache.ignite.internal.processors.rest.IgniteRestProcessor; import org.apache.ignite.internal.processors.security.GridSecurityProcessor; import org.apache.ignite.internal.processors.security.IgniteSecurity; import org.apache.ignite.internal.processors.security.IgniteSecurityProcessor; import org.apache.ignite.internal.processors.security.NoOpIgniteSecurityProcessor; import org.apache.ignite.internal.processors.segmentation.GridSegmentationProcessor; import org.apache.ignite.internal.processors.service.GridServiceProcessor; import org.apache.ignite.internal.processors.service.IgniteServiceProcessor; import org.apache.ignite.internal.processors.session.GridTaskSessionProcessor; import org.apache.ignite.internal.processors.subscription.GridInternalSubscriptionProcessor; import org.apache.ignite.internal.processors.task.GridTaskProcessor; import org.apache.ignite.internal.processors.timeout.GridTimeoutProcessor; import org.apache.ignite.internal.suggestions.GridPerformanceSuggestions; import org.apache.ignite.internal.suggestions.JvmConfigurationSuggestions; import org.apache.ignite.internal.suggestions.OsConfigurationSuggestions; import org.apache.ignite.internal.util.StripedExecutor; import org.apache.ignite.internal.util.TimeBag; import org.apache.ignite.internal.util.future.GridCompoundFuture; import org.apache.ignite.internal.util.future.GridFinishedFuture; import org.apache.ignite.internal.util.future.GridFutureAdapter; import org.apache.ignite.internal.util.future.IgniteFutureImpl; import org.apache.ignite.internal.util.lang.GridAbsClosure; import org.apache.ignite.internal.util.tostring.GridToStringExclude; import org.apache.ignite.internal.util.typedef.C1; import org.apache.ignite.internal.util.typedef.CI1; import org.apache.ignite.internal.util.typedef.F; import org.apache.ignite.internal.util.typedef.X; import org.apache.ignite.internal.util.typedef.internal.A; import org.apache.ignite.internal.util.typedef.internal.CU; import org.apache.ignite.internal.util.typedef.internal.LT; import org.apache.ignite.internal.util.typedef.internal.S; import org.apache.ignite.internal.util.typedef.internal.SB; import org.apache.ignite.internal.util.typedef.internal.U; import org.apache.ignite.internal.worker.WorkersRegistry; import org.apache.ignite.lang.IgniteBiTuple; import org.apache.ignite.lang.IgniteFuture; import org.apache.ignite.lang.IgnitePredicate; import org.apache.ignite.lang.IgniteProductVersion; import org.apache.ignite.lifecycle.LifecycleAware; import org.apache.ignite.lifecycle.LifecycleBean; import org.apache.ignite.lifecycle.LifecycleEventType; import org.apache.ignite.marshaller.MarshallerExclusions; import org.apache.ignite.marshaller.MarshallerUtils; import org.apache.ignite.marshaller.jdk.JdkMarshaller; import org.apache.ignite.mxbean.IgniteMXBean; import org.apache.ignite.plugin.IgnitePlugin; import org.apache.ignite.plugin.PluginNotFoundException; import org.apache.ignite.plugin.PluginProvider; import org.apache.ignite.spi.IgniteSpi; import org.apache.ignite.spi.IgniteSpiVersionCheckException; import org.apache.ignite.spi.communication.tcp.TcpCommunicationSpi; import org.apache.ignite.spi.discovery.isolated.IsolatedDiscoverySpi; import org.apache.ignite.spi.discovery.tcp.internal.TcpDiscoveryNode; import org.apache.ignite.spi.tracing.TracingConfigurationManager; import org.apache.ignite.thread.IgniteStripedThreadPoolExecutor; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import static org.apache.ignite.IgniteSystemProperties.IGNITE_BINARY_MARSHALLER_USE_STRING_SERIALIZATION_VER_2; import static org.apache.ignite.IgniteSystemProperties.IGNITE_CONFIG_URL; import static org.apache.ignite.IgniteSystemProperties.IGNITE_DAEMON; import static org.apache.ignite.IgniteSystemProperties.IGNITE_EVENT_DRIVEN_SERVICE_PROCESSOR_ENABLED; import static org.apache.ignite.IgniteSystemProperties.IGNITE_LOG_CLASSPATH_CONTENT_ON_STARTUP; import static org.apache.ignite.IgniteSystemProperties.IGNITE_NO_ASCII; import static org.apache.ignite.IgniteSystemProperties.IGNITE_OPTIMIZED_MARSHALLER_USE_DEFAULT_SUID; import static org.apache.ignite.IgniteSystemProperties.IGNITE_REST_START_ON_CLIENT; import static org.apache.ignite.IgniteSystemProperties.IGNITE_SKIP_CONFIGURATION_CONSISTENCY_CHECK; import static org.apache.ignite.IgniteSystemProperties.IGNITE_STARVATION_CHECK_INTERVAL; import static org.apache.ignite.IgniteSystemProperties.IGNITE_SUCCESS_FILE; import static org.apache.ignite.IgniteSystemProperties.getBoolean; import static org.apache.ignite.internal.GridKernalState.DISCONNECTED; import static org.apache.ignite.internal.GridKernalState.STARTED; import static org.apache.ignite.internal.GridKernalState.STARTING; import static org.apache.ignite.internal.GridKernalState.STOPPED; import static org.apache.ignite.internal.GridKernalState.STOPPING; import static org.apache.ignite.internal.IgniteComponentType.COMPRESSION; import static org.apache.ignite.internal.IgniteComponentType.SCHEDULE; import static org.apache.ignite.internal.IgniteNodeAttributes.ATTR_BUILD_DATE; import static org.apache.ignite.internal.IgniteNodeAttributes.ATTR_BUILD_VER; import static org.apache.ignite.internal.IgniteNodeAttributes.ATTR_CLIENT_MODE; import static org.apache.ignite.internal.IgniteNodeAttributes.ATTR_CONSISTENCY_CHECK_SKIPPED; import static org.apache.ignite.internal.IgniteNodeAttributes.ATTR_DAEMON; import static org.apache.ignite.internal.IgniteNodeAttributes.ATTR_DATA_STORAGE_CONFIG; import static org.apache.ignite.internal.IgniteNodeAttributes.ATTR_DATA_STREAMER_POOL_SIZE; import static org.apache.ignite.internal.IgniteNodeAttributes.ATTR_DEPLOYMENT_MODE; import static org.apache.ignite.internal.IgniteNodeAttributes.ATTR_DYNAMIC_CACHE_START_ROLLBACK_SUPPORTED; import static org.apache.ignite.internal.IgniteNodeAttributes.ATTR_EVENT_DRIVEN_SERVICE_PROCESSOR_ENABLED; import static org.apache.ignite.internal.IgniteNodeAttributes.ATTR_IGNITE_FEATURES; import static org.apache.ignite.internal.IgniteNodeAttributes.ATTR_IGNITE_INSTANCE_NAME; import static org.apache.ignite.internal.IgniteNodeAttributes.ATTR_IPS; import static org.apache.ignite.internal.IgniteNodeAttributes.ATTR_JIT_NAME; import static org.apache.ignite.internal.IgniteNodeAttributes.ATTR_JMX_PORT; import static org.apache.ignite.internal.IgniteNodeAttributes.ATTR_JVM_ARGS; import static org.apache.ignite.internal.IgniteNodeAttributes.ATTR_JVM_PID; import static org.apache.ignite.internal.IgniteNodeAttributes.ATTR_LANG_RUNTIME; import static org.apache.ignite.internal.IgniteNodeAttributes.ATTR_LATE_AFFINITY_ASSIGNMENT; import static org.apache.ignite.internal.IgniteNodeAttributes.ATTR_MACS; import static org.apache.ignite.internal.IgniteNodeAttributes.ATTR_MARSHALLER; import static org.apache.ignite.internal.IgniteNodeAttributes.ATTR_MARSHALLER_COMPACT_FOOTER; import static org.apache.ignite.internal.IgniteNodeAttributes.ATTR_MARSHALLER_USE_BINARY_STRING_SER_VER_2; import static org.apache.ignite.internal.IgniteNodeAttributes.ATTR_MARSHALLER_USE_DFLT_SUID; import static org.apache.ignite.internal.IgniteNodeAttributes.ATTR_MEMORY_CONFIG; import static org.apache.ignite.internal.IgniteNodeAttributes.ATTR_NODE_CONSISTENT_ID; import static org.apache.ignite.internal.IgniteNodeAttributes.ATTR_OFFHEAP_SIZE; import static org.apache.ignite.internal.IgniteNodeAttributes.ATTR_PEER_CLASSLOADING; import static org.apache.ignite.internal.IgniteNodeAttributes.ATTR_PHY_RAM; import static org.apache.ignite.internal.IgniteNodeAttributes.ATTR_PREFIX; import static org.apache.ignite.internal.IgniteNodeAttributes.ATTR_REBALANCE_POOL_SIZE; import static org.apache.ignite.internal.IgniteNodeAttributes.ATTR_RESTART_ENABLED; import static org.apache.ignite.internal.IgniteNodeAttributes.ATTR_REST_PORT_RANGE; import static org.apache.ignite.internal.IgniteNodeAttributes.ATTR_SHUTDOWN_POLICY; import static org.apache.ignite.internal.IgniteNodeAttributes.ATTR_SPI_CLASS; import static org.apache.ignite.internal.IgniteNodeAttributes.ATTR_TX_CONFIG; import static org.apache.ignite.internal.IgniteNodeAttributes.ATTR_USER_NAME; import static org.apache.ignite.internal.IgniteNodeAttributes.ATTR_VALIDATE_CACHE_REQUESTS; import static org.apache.ignite.internal.IgniteVersionUtils.ACK_VER_STR; import static org.apache.ignite.internal.IgniteVersionUtils.BUILD_TSTAMP_STR; import static org.apache.ignite.internal.IgniteVersionUtils.COPYRIGHT; import static org.apache.ignite.internal.IgniteVersionUtils.REV_HASH_STR; import static org.apache.ignite.internal.IgniteVersionUtils.VER; import static org.apache.ignite.internal.IgniteVersionUtils.VER_STR; import static org.apache.ignite.internal.processors.cache.persistence.IgniteCacheDatabaseSharedManager.INTERNAL_DATA_REGION_NAMES; import static org.apache.ignite.lifecycle.LifecycleEventType.AFTER_NODE_START; import static org.apache.ignite.lifecycle.LifecycleEventType.BEFORE_NODE_START; /** * This class represents an implementation of the main Ignite API {@link Ignite} which is expanded by additional * methods of {@link IgniteEx} for the internal Ignite needs. It also controls the Ignite life cycle, checks * thread pools state for starvation, detects long JVM pauses and prints out the local node metrics. * <p> * Please, refer to the wiki <a href="http://en.wikipedia.org/wiki/Kernal">http://en.wikipedia.org/wiki/Kernal</a> * for the information on the misspelling. * <p> * <h3>Starting</h3> * The main entry point for all the Ignite instances creation is the method - {@link #start}. * <p> * It starts internal Ignite components (see {@link GridComponent}), for instance: * <ul> * <li>{@link GridManager} - a layer of indirection between kernal and SPI modules.</li> * <li>{@link GridProcessor} - an objects responsible for particular internal process implementation.</li> * <li>{@link IgnitePlugin} - an Ignite addition of user-provided functionality.</li> * </ul> * The {@code start} method also performs additional validation of the provided {@link IgniteConfiguration} and * prints some suggestions such as: * <ul> * <li>Ignite configuration optimizations (e.g. disabling {@link EventType} events).</li> * <li>{@link JvmConfigurationSuggestions} optimizations.</li> * <li>{@link OsConfigurationSuggestions} optimizations.</li> * </ul> * <h3>Stopping</h3> * To stop Ignite instance the {@link #stop(boolean)} method is used. The {@code cancel} argument of this method is used: * <ul> * <li>With {@code true} value. To interrupt all currently acitve {@link GridComponent}s related to the Ignite node. * For instance, {@link ComputeJob} will be interrupted by calling {@link ComputeJob#cancel()} method. Note that just * like with {@link Thread#interrupt()}, it is up to the actual job to exit from execution.</li> * <li>With {@code false} value. To stop the Ignite node gracefully. All jobs currently running will not be interrupted. * The Ignite node will wait for the completion of all {@link GridComponent}s running on it before stopping. * </li> * </ul> */ public class IgniteKernal implements IgniteEx, IgniteMXBean, Externalizable { /** Class serialization version number. */ private static final long serialVersionUID = 0L; /** Ignite web-site that is shown in log messages. */ public static final String SITE = "ignite.apache.org"; /** System line separator. */ private static final String NL = U.nl(); /** System megabyte. */ private static final int MEGABYTE = 1024 * 1024; /** * Default interval of checking thread pool state for the starvation. Will be used only if the * {@link IgniteSystemProperties#IGNITE_STARVATION_CHECK_INTERVAL} system property is not set. * <p> * Value is {@code 30 sec}. */ public static final long DFLT_PERIODIC_STARVATION_CHECK_FREQ = 1000 * 30; /** Object is used to force completion the previous reconnection attempt. See {@link ReconnectState} for details. */ private static final Object STOP_RECONNECT = new Object(); /** The separator is used for coordinator properties formatted as a string. */ public static final String COORDINATOR_PROPERTIES_SEPARATOR = ","; /** * Default timeout in milliseconds for dumping long running operations. Will be used if the * {@link IgniteSystemProperties#IGNITE_LONG_OPERATIONS_DUMP_TIMEOUT} is not set. * <p> * Value is {@code 60 sec}. */ public static final long DFLT_LONG_OPERATIONS_DUMP_TIMEOUT = 60_000L; /** @see IgniteSystemProperties#IGNITE_EVENT_DRIVEN_SERVICE_PROCESSOR_ENABLED */ public static final boolean DFLT_EVENT_DRIVEN_SERVICE_PROCESSOR_ENABLED = true; /** @see IgniteSystemProperties#IGNITE_LOG_CLASSPATH_CONTENT_ON_STARTUP */ public static final boolean DFLT_LOG_CLASSPATH_CONTENT_ON_STARTUP = true; /** Currently used instance of JVM pause detector thread. See {@link LongJVMPauseDetector} for details. */ private LongJVMPauseDetector longJVMPauseDetector; /** The main kernal context which holds all the {@link GridComponent}s. */ @GridToStringExclude private GridKernalContextImpl ctx; /** Helper which registers and unregisters MBeans. */ @GridToStringExclude private IgniteMBeansManager mBeansMgr; /** Ignite configuration instance. */ private IgniteConfiguration cfg; /** Ignite logger instance which enriches log messages with the node instance name and the node id. */ @GridToStringExclude private GridLoggerProxy log; /** Name of Ignite node. */ private String igniteInstanceName; /** Kernal start timestamp. */ private long startTime = U.currentTimeMillis(); /** Spring context, potentially {@code null}. */ private GridSpringResourceContext rsrcCtx; /** * The instance of scheduled thread pool starvation checker. {@code null} if starvation checks have been * disabled by the value of {@link IgniteSystemProperties#IGNITE_STARVATION_CHECK_INTERVAL} system property. */ @GridToStringExclude private GridTimeoutProcessor.CancelableTask starveTask; /** * The instance of scheduled metrics logger. {@code null} means that the metrics loggin have been disabled * by configuration. See {@link IgniteConfiguration#getMetricsLogFrequency()} for details. */ @GridToStringExclude private GridTimeoutProcessor.CancelableTask metricsLogTask; /** {@code true} if an error occurs at Ignite instance stop. */ @GridToStringExclude private boolean errOnStop; /** An instance of the scheduler which provides functionality for scheduling jobs locally. */ @GridToStringExclude private IgniteScheduler scheduler; /** The kernal state guard. See {@link GridKernalGateway} for details. */ @GridToStringExclude private final AtomicReference<GridKernalGateway> gw = new AtomicReference<>(); /** Flag indicates that the ignite instance is scheduled to be stopped. */ @GridToStringExclude private final AtomicBoolean stopGuard = new AtomicBoolean(); /** The state object is used when reconnection occurs. See {@link IgniteKernal#onReconnected(boolean)}. */ private final ReconnectState reconnectState = new ReconnectState(); /** * No-arg constructor is required by externalization. */ public IgniteKernal() { this(null); } /** * @param rsrcCtx Optional Spring application context. */ public IgniteKernal(@Nullable GridSpringResourceContext rsrcCtx) { this.rsrcCtx = rsrcCtx; } /** {@inheritDoc} */ @Override public IgniteClusterEx cluster() { return ctx.cluster().get(); } /** {@inheritDoc} */ @Override public ClusterNode localNode() { return ctx.cluster().get().localNode(); } /** {@inheritDoc} */ @Override public IgniteCompute compute() { return ((ClusterGroupAdapter)ctx.cluster().get().forServers()).compute(); } /** {@inheritDoc} */ @Override public IgniteMessaging message() { return ctx.cluster().get().message(); } /** {@inheritDoc} */ @Override public IgniteEvents events() { return ctx.cluster().get().events(); } /** {@inheritDoc} */ @Override public IgniteServices services() { checkClusterState(); return ((ClusterGroupAdapter)ctx.cluster().get().forServers()).services(); } /** {@inheritDoc} */ @Override public ExecutorService executorService() { return ctx.cluster().get().executorService(); } /** {@inheritDoc} */ @Override public final IgniteCompute compute(ClusterGroup grp) { return ((ClusterGroupAdapter)grp).compute(); } /** {@inheritDoc} */ @Override public final IgniteMessaging message(ClusterGroup prj) { return ((ClusterGroupAdapter)prj).message(); } /** {@inheritDoc} */ @Override public final IgniteEvents events(ClusterGroup grp) { return ((ClusterGroupAdapter)grp).events(); } /** {@inheritDoc} */ @Override public IgniteServices services(ClusterGroup grp) { checkClusterState(); return ((ClusterGroupAdapter)grp).services(); } /** {@inheritDoc} */ @Override public ExecutorService executorService(ClusterGroup grp) { return ((ClusterGroupAdapter)grp).executorService(); } /** {@inheritDoc} */ @Override public String name() { return igniteInstanceName; } /** {@inheritDoc} */ @Override public String getCopyright() { return COPYRIGHT; } /** {@inheritDoc} */ @Override public long getStartTimestamp() { return startTime; } /** {@inheritDoc} */ @Override public String getStartTimestampFormatted() { return DateFormat.getDateTimeInstance().format(new Date(startTime)); } /** {@inheritDoc} */ @Override public boolean isRebalanceEnabled() { return ctx.cache().context().isRebalanceEnabled(); } /** {@inheritDoc} */ @Override public void rebalanceEnabled(boolean rebalanceEnabled) { ctx.cache().context().rebalanceEnabled(rebalanceEnabled); } /** {@inheritDoc} */ @Override public long getUpTime() { return U.currentTimeMillis() - startTime; } /** {@inheritDoc} */ @Override public long getLongJVMPausesCount() { return longJVMPauseDetector != null ? longJVMPauseDetector.longPausesCount() : 0; } /** {@inheritDoc} */ @Override public long getLongJVMPausesTotalDuration() { return longJVMPauseDetector != null ? longJVMPauseDetector.longPausesTotalDuration() : 0; } /** {@inheritDoc} */ @Override public Map<Long, Long> getLongJVMPauseLastEvents() { return longJVMPauseDetector != null ? longJVMPauseDetector.longPauseEvents() : Collections.emptyMap(); } /** {@inheritDoc} */ @Override public String getUpTimeFormatted() { return X.timeSpan2DHMSM(U.currentTimeMillis() - startTime); } /** {@inheritDoc} */ @Override public String getFullVersion() { return VER_STR + '-' + BUILD_TSTAMP_STR; } /** {@inheritDoc} */ @Override public String getCheckpointSpiFormatted() { assert cfg != null; return Arrays.toString(cfg.getCheckpointSpi()); } /** {@inheritDoc} */ @Override public String getCurrentCoordinatorFormatted() { ClusterNode node = ctx.discovery().oldestAliveServerNode(AffinityTopologyVersion.NONE); if (node == null) return ""; return new StringBuilder() .append(node.addresses()) .append(COORDINATOR_PROPERTIES_SEPARATOR) .append(node.id()) .append(COORDINATOR_PROPERTIES_SEPARATOR) .append(node.order()) .append(COORDINATOR_PROPERTIES_SEPARATOR) .append(node.hostNames()) .toString(); } /** {@inheritDoc} */ @Override public boolean isNodeInBaseline() { ctx.gateway().readLockAnyway(); try { if (ctx.gateway().getState() != STARTED) return false; ClusterNode locNode = localNode(); if (locNode.isClient() || locNode.isDaemon()) return false; DiscoveryDataClusterState clusterState = ctx.state().clusterState(); return clusterState.hasBaselineTopology() && CU.baselineNode(locNode, clusterState); } finally { ctx.gateway().readUnlock(); } } /** {@inheritDoc} */ @Override public String getCommunicationSpiFormatted() { assert cfg != null; return cfg.getCommunicationSpi().toString(); } /** {@inheritDoc} */ @Override public String getDeploymentSpiFormatted() { assert cfg != null; return cfg.getDeploymentSpi().toString(); } /** {@inheritDoc} */ @Override public String getDiscoverySpiFormatted() { assert cfg != null; return cfg.getDiscoverySpi().toString(); } /** {@inheritDoc} */ @Override public String getEventStorageSpiFormatted() { assert cfg != null; return cfg.getEventStorageSpi().toString(); } /** {@inheritDoc} */ @Override public String getCollisionSpiFormatted() { assert cfg != null; return cfg.getCollisionSpi().toString(); } /** {@inheritDoc} */ @Override public String getFailoverSpiFormatted() { assert cfg != null; return Arrays.toString(cfg.getFailoverSpi()); } /** {@inheritDoc} */ @Override public String getLoadBalancingSpiFormatted() { assert cfg != null; return Arrays.toString(cfg.getLoadBalancingSpi()); } /** {@inheritDoc} */ @Override public String getOsInformation() { return U.osString(); } /** {@inheritDoc} */ @Override public String getJdkInformation() { return U.jdkString(); } /** {@inheritDoc} */ @Override public String getOsUser() { return System.getProperty("user.name"); } /** {@inheritDoc} */ @Override public void printLastErrors() { ctx.exceptionRegistry().printErrors(log); } /** {@inheritDoc} */ @Override public String getVmName() { return ManagementFactory.getRuntimeMXBean().getName(); } /** {@inheritDoc} */ @Override public String getInstanceName() { return igniteInstanceName; } /** {@inheritDoc} */ @Override public String getExecutorServiceFormatted() { assert cfg != null; return String.valueOf(cfg.getPublicThreadPoolSize()); } /** {@inheritDoc} */ @Override public String getIgniteHome() { assert cfg != null; return cfg.getIgniteHome(); } /** {@inheritDoc} */ @Override public String getGridLoggerFormatted() { assert cfg != null; return cfg.getGridLogger().toString(); } /** {@inheritDoc} */ @Override public String getMBeanServerFormatted() { assert cfg != null; return cfg.getMBeanServer().toString(); } /** {@inheritDoc} */ @Override public UUID getLocalNodeId() { assert cfg != null; return cfg.getNodeId(); } /** {@inheritDoc} */ @Override public List<String> getUserAttributesFormatted() { assert cfg != null; return (List<String>)F.transform(cfg.getUserAttributes().entrySet(), new C1<Map.Entry<String, ?>, String>() { @Override public String apply(Map.Entry<String, ?> e) { return e.getKey() + ", " + e.getValue().toString(); } }); } /** {@inheritDoc} */ @Override public boolean isPeerClassLoadingEnabled() { assert cfg != null; return cfg.isPeerClassLoadingEnabled(); } /** {@inheritDoc} */ @Override public List<String> getLifecycleBeansFormatted() { LifecycleBean[] beans = cfg.getLifecycleBeans(); if (F.isEmpty(beans)) return Collections.emptyList(); else { List<String> res = new ArrayList<>(beans.length); for (LifecycleBean bean : beans) res.add(String.valueOf(bean)); return res; } } /** {@inheritDoc} */ @Override public String clusterState() { return ctx.state().clusterState().state().toString(); } /** {@inheritDoc} */ @Override public long lastClusterStateChangeTime() { return ctx.state().lastStateChangeTime(); } /** * @param name New attribute name. * @param val New attribute value. * @throws IgniteCheckedException If duplicated SPI name found. */ private void add(String name, @Nullable Serializable val) throws IgniteCheckedException { assert name != null; if (ctx.addNodeAttribute(name, val) != null) { if (name.endsWith(ATTR_SPI_CLASS)) // User defined duplicated names for the different SPIs. throw new IgniteCheckedException("Failed to set SPI attribute. Duplicated SPI name found: " + name.substring(0, name.length() - ATTR_SPI_CLASS.length())); // Otherwise it's a mistake of setting up duplicated attribute. assert false : "Duplicate attribute: " + name; } } /** * Notifies life-cycle beans of ignite event. * * @param evt Lifecycle event to notify beans with. * @throws IgniteCheckedException If user threw exception during start. */ private void notifyLifecycleBeans(LifecycleEventType evt) throws IgniteCheckedException { if (!cfg.isDaemon() && cfg.getLifecycleBeans() != null) { for (LifecycleBean bean : cfg.getLifecycleBeans()) if (bean != null) { try { bean.onLifecycleEvent(evt); } catch (Exception e) { throw new IgniteCheckedException(e); } } } } /** * Notifies life-cycle beans of ignite event. * * @param evt Lifecycle event to notify beans with. */ private void notifyLifecycleBeansEx(LifecycleEventType evt) { try { notifyLifecycleBeans(evt); } // Catch generic throwable to secure against user assertions. catch (Throwable e) { U.error(log, "Failed to notify lifecycle bean (safely ignored) [evt=" + evt + (igniteInstanceName == null ? "" : ", igniteInstanceName=" + igniteInstanceName) + ']', e); if (e instanceof Error) throw (Error)e; } } /** * @param clsPathEntry Classpath string to process. * @param clsPathContent StringBuilder to attach path to. */ private void ackClassPathEntry(String clsPathEntry, SB clsPathContent) { File clsPathElementFile = new File(clsPathEntry); if (clsPathElementFile.isDirectory()) clsPathContent.a(clsPathEntry).a(";"); else { String extension = clsPathEntry.length() >= 4 ? clsPathEntry.substring(clsPathEntry.length() - 4).toLowerCase() : null; if (".jar".equals(extension) || ".zip".equals(extension)) clsPathContent.a(clsPathEntry).a(";"); } } /** * @param clsPathEntry Classpath string to process. * @param clsPathContent StringBuilder to attach path to. */ private void ackClassPathWildCard(String clsPathEntry, SB clsPathContent) { final int lastSeparatorIdx = clsPathEntry.lastIndexOf(File.separator); final int asteriskIdx = clsPathEntry.indexOf('*'); //just to log possibly incorrent entries to err if (asteriskIdx >= 0 && asteriskIdx < lastSeparatorIdx) throw new RuntimeException("Could not parse classpath entry"); final int fileMaskFirstIdx = lastSeparatorIdx + 1; final String fileMask = (fileMaskFirstIdx >= clsPathEntry.length()) ? "*.jar" : clsPathEntry.substring(fileMaskFirstIdx); Path path = Paths.get(lastSeparatorIdx > 0 ? clsPathEntry.substring(0, lastSeparatorIdx) : ".") .toAbsolutePath() .normalize(); if (lastSeparatorIdx == 0) path = path.getRoot(); try { DirectoryStream<Path> files = Files.newDirectoryStream(path, fileMask); for (Path f : files) { String s = f.toString(); if (s.toLowerCase().endsWith(".jar")) clsPathContent.a(f.toString()).a(";"); } } catch (IOException e) { throw new UncheckedIOException(e); } } /** * Prints the list of {@code *.jar} and {@code *.class} files containing in the classpath. */ private void ackClassPathContent() { assert log != null; boolean enabled = IgniteSystemProperties.getBoolean(IGNITE_LOG_CLASSPATH_CONTENT_ON_STARTUP, DFLT_LOG_CLASSPATH_CONTENT_ON_STARTUP); if (enabled) { String clsPath = System.getProperty("java.class.path", "."); String[] clsPathElements = clsPath.split(File.pathSeparator); U.log(log, "Classpath value: " + clsPath); SB clsPathContent = new SB("List of files containing in classpath: "); for (String clsPathEntry : clsPathElements) { try { if (clsPathEntry.contains("*")) ackClassPathWildCard(clsPathEntry, clsPathContent); else ackClassPathEntry(clsPathEntry, clsPathContent); } catch (Exception e) { U.warn(log, String.format("Could not log class path entry '%s': %s", clsPathEntry, e.getMessage())); } } U.log(log, clsPathContent.toString()); } } /** * @param cfg Ignite configuration to use. * @param utilityCachePool Utility cache pool. * @param execSvc Executor service. * @param svcExecSvc Services executor service. * @param sysExecSvc System executor service. * @param stripedExecSvc Striped executor. * @param p2pExecSvc P2P executor service. * @param mgmtExecSvc Management executor service. * @param dataStreamExecSvc Data streamer executor service. * @param restExecSvc Reset executor service. * @param affExecSvc Affinity executor service. * @param idxExecSvc Indexing executor service. * @param buildIdxExecSvc Create/rebuild indexes executor service. * @param callbackExecSvc Callback executor service. * @param qryExecSvc Query executor service. * @param schemaExecSvc Schema executor service. * @param rebalanceExecSvc Rebalance excutor service. * @param rebalanceStripedExecSvc Striped rebalance excutor service. * @param customExecSvcs Custom named executors. * @param errHnd Error handler to use for notification about startup problems. * @param workerRegistry Worker registry. * @param hnd Default uncaught exception handler used by thread pools. * @throws IgniteCheckedException Thrown in case of any errors. */ public void start( final IgniteConfiguration cfg, ExecutorService utilityCachePool, final ExecutorService execSvc, final ExecutorService svcExecSvc, final ExecutorService sysExecSvc, final StripedExecutor stripedExecSvc, ExecutorService p2pExecSvc, ExecutorService mgmtExecSvc, StripedExecutor dataStreamExecSvc, ExecutorService restExecSvc, ExecutorService affExecSvc, @Nullable ExecutorService idxExecSvc, @Nullable ExecutorService buildIdxExecSvc, IgniteStripedThreadPoolExecutor callbackExecSvc, ExecutorService qryExecSvc, ExecutorService schemaExecSvc, ExecutorService rebalanceExecSvc, IgniteStripedThreadPoolExecutor rebalanceStripedExecSvc, @Nullable final Map<String, ? extends ExecutorService> customExecSvcs, GridAbsClosure errHnd, WorkersRegistry workerRegistry, Thread.UncaughtExceptionHandler hnd, TimeBag startTimer ) throws IgniteCheckedException { gw.compareAndSet(null, new GridKernalGatewayImpl(cfg.getIgniteInstanceName())); GridKernalGateway gw = this.gw.get(); gw.writeLock(); try { switch (gw.getState()) { case STARTED: { U.warn(log, "Grid has already been started (ignored)."); return; } case STARTING: { U.warn(log, "Grid is already in process of being started (ignored)."); return; } case STOPPING: { throw new IgniteCheckedException("Grid is in process of being stopped"); } case STOPPED: { break; } } gw.setState(STARTING); } finally { gw.writeUnlock(); } assert cfg != null; // Make sure we got proper configuration. validateCommon(cfg); igniteInstanceName = cfg.getIgniteInstanceName(); this.cfg = cfg; log = (GridLoggerProxy)cfg.getGridLogger().getLogger( getClass().getName() + (igniteInstanceName != null ? '%' + igniteInstanceName : "")); longJVMPauseDetector = new LongJVMPauseDetector(log); longJVMPauseDetector.start(); RuntimeMXBean rtBean = ManagementFactory.getRuntimeMXBean(); // Ack various information. ackAsciiLogo(); ackConfigUrl(); ackConfiguration(cfg); ackDaemon(); ackOsInfo(); ackLanguageRuntime(); ackRemoteManagement(); ackLogger(); ackVmArguments(rtBean); ackClassPaths(rtBean); ackSystemProperties(); ackEnvironmentVariables(); ackMemoryConfiguration(); ackCacheConfiguration(); ackP2pConfiguration(); ackRebalanceConfiguration(); ackIPv4StackFlagIsSet(); // Run background network diagnostics. GridDiagnostic.runBackgroundCheck(igniteInstanceName, execSvc, log); // Ack 3-rd party licenses location. if (log.isInfoEnabled() && cfg.getIgniteHome() != null) log.info("3-rd party licenses can be found at: " + cfg.getIgniteHome() + File.separatorChar + "libs" + File.separatorChar + "licenses"); // Check that user attributes are not conflicting // with internally reserved names. for (String name : cfg.getUserAttributes().keySet()) if (name.startsWith(ATTR_PREFIX)) throw new IgniteCheckedException("User attribute has illegal name: '" + name + "'. Note that all names " + "starting with '" + ATTR_PREFIX + "' are reserved for internal use."); // Ack local node user attributes. logNodeUserAttributes(); // Ack configuration. ackSpis(); List<PluginProvider> plugins = cfg.getPluginProviders() != null && cfg.getPluginProviders().length > 0 ? Arrays.asList(cfg.getPluginProviders()) : U.allPluginProviders(); // Spin out SPIs & managers. try { ctx = new GridKernalContextImpl(log, this, cfg, gw, utilityCachePool, execSvc, svcExecSvc, sysExecSvc, stripedExecSvc, p2pExecSvc, mgmtExecSvc, dataStreamExecSvc, restExecSvc, affExecSvc, idxExecSvc, buildIdxExecSvc, callbackExecSvc, qryExecSvc, schemaExecSvc, rebalanceExecSvc, rebalanceStripedExecSvc, customExecSvcs, plugins, MarshallerUtils.classNameFilter(this.getClass().getClassLoader()), workerRegistry, hnd, longJVMPauseDetector ); startProcessor(new DiagnosticProcessor(ctx)); mBeansMgr = new IgniteMBeansManager(this); cfg.getMarshaller().setContext(ctx.marshallerContext()); startProcessor(new GridInternalSubscriptionProcessor(ctx)); ClusterProcessor clusterProc = new ClusterProcessor(ctx); startProcessor(clusterProc); U.onGridStart(); // Start and configure resource processor first as it contains resources used // by all other managers and processors. GridResourceProcessor rsrcProc = new GridResourceProcessor(ctx); rsrcProc.setSpringContext(rsrcCtx); scheduler = new IgniteSchedulerImpl(ctx); startProcessor(rsrcProc); // Inject resources into lifecycle beans. if (!cfg.isDaemon() && cfg.getLifecycleBeans() != null) { for (LifecycleBean bean : cfg.getLifecycleBeans()) { if (bean != null) rsrcProc.inject(bean); } } // Lifecycle notification. notifyLifecycleBeans(BEFORE_NODE_START); // Starts lifecycle aware components. U.startLifecycleAware(lifecycleAwares(cfg)); startProcessor(new IgnitePluginProcessor(ctx, cfg, plugins)); startProcessor(new FailureProcessor(ctx)); startProcessor(new PoolProcessor(ctx)); // Closure processor should be started before all others // (except for resource processor), as many components can depend on it. startProcessor(new GridClosureProcessor(ctx)); // Start some other processors (order & place is important). startProcessor(new GridPortProcessor(ctx)); startProcessor(new GridJobMetricsProcessor(ctx)); // Timeout processor needs to be started before managers, // as managers may depend on it. startProcessor(new GridTimeoutProcessor(ctx)); // Start security processors. startProcessor(securityProcessor()); // Start SPI managers. // NOTE: that order matters as there are dependencies between managers. try { startManager(new GridTracingManager(ctx, false)); } catch (IgniteCheckedException e) { startManager(new GridTracingManager(ctx, true)); } startManager(new GridMetricManager(ctx)); startManager(new GridSystemViewManager(ctx)); startManager(new GridIoManager(ctx)); startManager(new GridCheckpointManager(ctx)); startManager(new GridEventStorageManager(ctx)); startManager(new GridDeploymentManager(ctx)); startManager(new GridLoadBalancerManager(ctx)); startManager(new GridFailoverManager(ctx)); startManager(new GridCollisionManager(ctx)); startManager(new GridIndexingManager(ctx)); ackSecurity(); // Assign discovery manager to context before other processors start so they // are able to register custom event listener. GridManager discoMgr = new GridDiscoveryManager(ctx); ctx.add(discoMgr, false); // Start the encryption manager after assigning the discovery manager to context, so it will be // able to register custom event listener. startManager(new GridEncryptionManager(ctx)); startProcessor(new PdsConsistentIdProcessor(ctx)); MaintenanceProcessor mntcProcessor = new MaintenanceProcessor(ctx); startProcessor(mntcProcessor); if (mntcProcessor.isMaintenanceMode()) { ctx.config().setDiscoverySpi(new IsolatedDiscoverySpi()); discoMgr = new GridDiscoveryManager(ctx); ctx.add(discoMgr, false); } // Start processors before discovery manager, so they will // be able to start receiving messages once discovery completes. try { startProcessor(COMPRESSION.createOptional(ctx)); startProcessor(new GridMarshallerMappingProcessor(ctx)); startProcessor(new MvccProcessorImpl(ctx)); startProcessor(createComponent(DiscoveryNodeValidationProcessor.class, ctx)); startProcessor(new GridAffinityProcessor(ctx)); startProcessor(createComponent(GridSegmentationProcessor.class, ctx)); startTimer.finishGlobalStage("Start managers"); startProcessor(createComponent(IgniteCacheObjectProcessor.class, ctx)); startTimer.finishGlobalStage("Configure binary metadata"); startProcessor(createComponent(IGridClusterStateProcessor.class, ctx)); startProcessor(new IgniteAuthenticationProcessor(ctx)); startProcessor(new GridCacheProcessor(ctx)); startProcessor(new GridQueryProcessor(ctx)); startProcessor(new ClientListenerProcessor(ctx)); startProcessor(createServiceProcessor()); startProcessor(new GridTaskSessionProcessor(ctx)); startProcessor(new GridJobProcessor(ctx)); startProcessor(new GridTaskProcessor(ctx)); startProcessor((GridProcessor)SCHEDULE.createOptional(ctx)); startProcessor(createComponent(IgniteRestProcessor.class, ctx)); startProcessor(new DataStreamProcessor(ctx)); startProcessor(new GridContinuousProcessor(ctx)); startProcessor(new DataStructuresProcessor(ctx)); startProcessor(createComponent(PlatformProcessor.class, ctx)); startProcessor(new DistributedMetaStorageImpl(ctx)); startProcessor(new DistributedConfigurationProcessor(ctx)); startProcessor(new DurableBackgroundTasksProcessor(ctx)); startTimer.finishGlobalStage("Start processors"); // Start plugins. for (PluginProvider provider : ctx.plugins().allProviders()) { ctx.add(new GridPluginComponent(provider)); provider.start(ctx.plugins().pluginContextForProvider(provider)); startTimer.finishGlobalStage("Start '" + provider.name() + "' plugin"); } // Start platform plugins. if (ctx.config().getPlatformConfiguration() != null) startProcessor(new PlatformPluginProcessor(ctx)); mBeansMgr.registerMBeansDuringInitPhase(); ctx.cluster().initDiagnosticListeners(); fillNodeAttributes(clusterProc.updateNotifierEnabled()); ctx.cache().context().database().notifyMetaStorageSubscribersOnReadyForRead(); ((DistributedMetaStorageImpl)ctx.distributedMetastorage()).inMemoryReadyForRead(); startTimer.finishGlobalStage("Init metastore"); ctx.cache().context().database().startMemoryRestore(ctx, startTimer); ctx.recoveryMode(false); startTimer.finishGlobalStage("Finish recovery"); } catch (Throwable e) { U.error( log, "Exception during start processors, node will be stopped and close connections", e); // Stop discovery spi to close tcp socket. ctx.discovery().stop(true); throw e; } // All components exept Discovery are started, time to check if maintenance is still needed mntcProcessor.prepareAndExecuteMaintenance(); gw.writeLock(); try { gw.setState(STARTED); // Start discovery manager last to make sure that grid is fully initialized. startManager(discoMgr); } finally { gw.writeUnlock(); } startTimer.finishGlobalStage("Join topology"); // Check whether UTF-8 is the default character encoding. checkFileEncoding(); // Check whether physical RAM is not exceeded. checkPhysicalRam(); // Suggest configuration optimizations. suggestOptimizations(cfg); // Suggest JVM optimizations. ctx.performance().addAll(JvmConfigurationSuggestions.getSuggestions()); // Suggest Operation System optimizations. ctx.performance().addAll(OsConfigurationSuggestions.getSuggestions()); DiscoveryLocalJoinData joinData = ctx.discovery().localJoin(); IgniteInternalFuture<Boolean> transitionWaitFut = joinData.transitionWaitFuture(); // Notify discovery manager the first to make sure that topology is discovered. // Active flag is not used in managers, so it is safe to pass true. ctx.discovery().onKernalStart(true); // Notify IO manager the second so further components can send and receive messages. // Must notify the IO manager before transition state await to make sure IO connection can be established. ctx.io().onKernalStart(true); boolean active; if (transitionWaitFut != null) { if (log.isInfoEnabled()) { log.info("Join cluster while cluster state transition is in progress, " + "waiting when transition finish."); } active = transitionWaitFut.get(); } else active = joinData.active(); startTimer.finishGlobalStage("Await transition"); ctx.metric().registerThreadPools(utilityCachePool, execSvc, svcExecSvc, sysExecSvc, stripedExecSvc, p2pExecSvc, mgmtExecSvc, dataStreamExecSvc, restExecSvc, affExecSvc, idxExecSvc, callbackExecSvc, qryExecSvc, schemaExecSvc, rebalanceExecSvc, rebalanceStripedExecSvc, customExecSvcs); registerMetrics(); ctx.cluster().registerMetrics(); // Register MBeans. mBeansMgr.registerMBeansAfterNodeStarted(utilityCachePool, execSvc, svcExecSvc, sysExecSvc, stripedExecSvc, p2pExecSvc, mgmtExecSvc, dataStreamExecSvc, restExecSvc, affExecSvc, idxExecSvc, callbackExecSvc, qryExecSvc, schemaExecSvc, rebalanceExecSvc, rebalanceStripedExecSvc, customExecSvcs, ctx.workersRegistry()); ctx.systemView().registerThreadPools(stripedExecSvc, dataStreamExecSvc); boolean recon = false; // Callbacks. for (GridComponent comp : ctx) { // Skip discovery manager. if (comp instanceof GridDiscoveryManager) continue; // Skip IO manager. if (comp instanceof GridIoManager) continue; if (comp instanceof GridPluginComponent) continue; if (!skipDaemon(comp)) { try { comp.onKernalStart(active); } catch (IgniteNeedReconnectException e) { ClusterNode locNode = ctx.discovery().localNode(); assert locNode.isClient(); if (!ctx.discovery().reconnectSupported()) throw new IgniteCheckedException("Client node in forceServerMode " + "is not allowed to reconnect to the cluster and will be stopped."); if (log.isDebugEnabled()) log.debug("Failed to start node components on node start, will wait for reconnect: " + e); recon = true; } } } // Start plugins. for (PluginProvider provider : ctx.plugins().allProviders()) provider.onIgniteStart(); if (recon) reconnectState.waitFirstReconnect(); // Lifecycle bean notifications. notifyLifecycleBeans(AFTER_NODE_START); } catch (Throwable e) { IgniteSpiVersionCheckException verCheckErr = X.cause(e, IgniteSpiVersionCheckException.class); if (verCheckErr != null) U.error(log, verCheckErr.getMessage()); else if (X.hasCause(e, InterruptedException.class, IgniteInterruptedCheckedException.class)) U.warn(log, "Grid startup routine has been interrupted (will rollback)."); else U.error(log, "Got exception while starting (will rollback startup routine).", e); errHnd.apply(); stop(true); if (e instanceof Error) throw e; else if (e instanceof IgniteCheckedException) throw (IgniteCheckedException)e; else throw new IgniteCheckedException(e); } // Mark start timestamp. startTime = U.currentTimeMillis(); String intervalStr = IgniteSystemProperties.getString(IGNITE_STARVATION_CHECK_INTERVAL); // Start starvation checker if enabled. boolean starveCheck = !isDaemon() && !"0".equals(intervalStr); if (starveCheck) { final long interval = F.isEmpty(intervalStr) ? DFLT_PERIODIC_STARVATION_CHECK_FREQ : Long.parseLong(intervalStr); starveTask = ctx.timeout().schedule(new Runnable() { /** Last completed task count. */ private long lastCompletedCntPub; /** Last completed task count. */ private long lastCompletedCntSys; /** Last completed task count. */ private long lastCompletedCntQry; @Override public void run() { if (execSvc instanceof ThreadPoolExecutor) { ThreadPoolExecutor exec = (ThreadPoolExecutor)execSvc; lastCompletedCntPub = checkPoolStarvation(exec, lastCompletedCntPub, "public"); } if (sysExecSvc instanceof ThreadPoolExecutor) { ThreadPoolExecutor exec = (ThreadPoolExecutor)sysExecSvc; lastCompletedCntSys = checkPoolStarvation(exec, lastCompletedCntSys, "system"); } if (qryExecSvc instanceof ThreadPoolExecutor) { ThreadPoolExecutor exec = (ThreadPoolExecutor)qryExecSvc; lastCompletedCntQry = checkPoolStarvation(exec, lastCompletedCntQry, "query"); } if (stripedExecSvc != null) stripedExecSvc.detectStarvation(); } /** * @param exec Thread pool executor to check. * @param lastCompletedCnt Last completed tasks count. * @param pool Pool name for message. * @return Current completed tasks count. */ private long checkPoolStarvation( ThreadPoolExecutor exec, long lastCompletedCnt, String pool ) { long completedCnt = exec.getCompletedTaskCount(); // If all threads are active and no task has completed since last time and there is // at least one waiting request, then it is possible starvation. if (exec.getPoolSize() == exec.getActiveCount() && completedCnt == lastCompletedCnt && !exec.getQueue().isEmpty()) LT.warn( log, "Possible thread pool starvation detected (no task completed in last " + interval + "ms, is " + pool + " thread pool size large enough?)"); return completedCnt; } }, interval, interval); } long metricsLogFreq = cfg.getMetricsLogFrequency(); if (metricsLogFreq > 0) { metricsLogTask = ctx.timeout().schedule(new Runnable() { private final DecimalFormat dblFmt = doubleFormat(); @Override public void run() { ackNodeMetrics(dblFmt, execSvc, sysExecSvc, customExecSvcs); } }, metricsLogFreq, metricsLogFreq); } ctx.performance().add("Disable assertions (remove '-ea' from JVM options)", !U.assertionsEnabled()); ctx.performance().logSuggestions(log, igniteInstanceName); U.quietAndInfo(log, "To start Console Management & Monitoring run ignitevisorcmd.{sh|bat}"); if (!IgniteSystemProperties.getBoolean(IgniteSystemProperties.IGNITE_QUIET, true)) ackClassPathContent(); ackStart(rtBean); if (!isDaemon()) ctx.discovery().ackTopology(ctx.discovery().localJoin().joinTopologyVersion().topologyVersion(), EventType.EVT_NODE_JOINED, localNode()); startTimer.finishGlobalStage("Await exchange"); } /** */ private static DecimalFormat doubleFormat() { return new DecimalFormat("#.##", DecimalFormatSymbols.getInstance(Locale.US)); } /** * @return Ignite security processor. See {@link IgniteSecurity} for details. */ private GridProcessor securityProcessor() throws IgniteCheckedException { GridSecurityProcessor prc = createComponent(GridSecurityProcessor.class, ctx); return prc != null && prc.enabled() ? new IgniteSecurityProcessor(ctx, prc) : new NoOpIgniteSecurityProcessor(ctx); } /** * Create description of an executor service for logging. * * @param execSvcName Name of the service. * @param execSvc Service to create a description for. */ private String createExecutorDescription(String execSvcName, ExecutorService execSvc) { int poolActiveThreads = 0; int poolIdleThreads = 0; int poolQSize = 0; if (execSvc instanceof ThreadPoolExecutor) { ThreadPoolExecutor exec = (ThreadPoolExecutor)execSvc; int poolSize = exec.getPoolSize(); poolActiveThreads = Math.min(poolSize, exec.getActiveCount()); poolIdleThreads = poolSize - poolActiveThreads; poolQSize = exec.getQueue().size(); } return execSvcName + " [active=" + poolActiveThreads + ", idle=" + poolIdleThreads + ", qSize=" + poolQSize + "]"; } /** * Creates service processor depend on {@link IgniteSystemProperties#IGNITE_EVENT_DRIVEN_SERVICE_PROCESSOR_ENABLED}. * * @return The service processor. See {@link IgniteServiceProcessor} for details. */ private GridProcessorAdapter createServiceProcessor() { final boolean srvcProcMode = getBoolean(IGNITE_EVENT_DRIVEN_SERVICE_PROCESSOR_ENABLED, DFLT_EVENT_DRIVEN_SERVICE_PROCESSOR_ENABLED); if (srvcProcMode) return new IgniteServiceProcessor(ctx); return new GridServiceProcessor(ctx); } /** * Validates common configuration parameters. * * @param cfg Ignite configuration to validate. */ private void validateCommon(IgniteConfiguration cfg) { A.notNull(cfg.getNodeId(), "cfg.getNodeId()"); if (!U.IGNITE_MBEANS_DISABLED) A.notNull(cfg.getMBeanServer(), "cfg.getMBeanServer()"); A.notNull(cfg.getGridLogger(), "cfg.getGridLogger()"); A.notNull(cfg.getMarshaller(), "cfg.getMarshaller()"); A.notNull(cfg.getUserAttributes(), "cfg.getUserAttributes()"); // All SPIs should be non-null. A.notNull(cfg.getCheckpointSpi(), "cfg.getCheckpointSpi()"); A.notNull(cfg.getCommunicationSpi(), "cfg.getCommunicationSpi()"); A.notNull(cfg.getDeploymentSpi(), "cfg.getDeploymentSpi()"); A.notNull(cfg.getDiscoverySpi(), "cfg.getDiscoverySpi()"); A.notNull(cfg.getEventStorageSpi(), "cfg.getEventStorageSpi()"); A.notNull(cfg.getCollisionSpi(), "cfg.getCollisionSpi()"); A.notNull(cfg.getFailoverSpi(), "cfg.getFailoverSpi()"); A.notNull(cfg.getLoadBalancingSpi(), "cfg.getLoadBalancingSpi()"); A.notNull(cfg.getIndexingSpi(), "cfg.getIndexingSpi()"); A.ensure(cfg.getNetworkTimeout() > 0, "cfg.getNetworkTimeout() > 0"); A.ensure(cfg.getNetworkSendRetryDelay() > 0, "cfg.getNetworkSendRetryDelay() > 0"); A.ensure(cfg.getNetworkSendRetryCount() > 0, "cfg.getNetworkSendRetryCount() > 0"); } /** * Check whether UTF-8 is the default character encoding. * Differing character encodings across cluster may lead to erratic behavior. */ private void checkFileEncoding() { String encodingDisplayName = Charset.defaultCharset().displayName(Locale.ENGLISH); if (!"UTF-8".equals(encodingDisplayName)) { U.quietAndWarn(log, "Default character encoding is " + encodingDisplayName + ". Specify UTF-8 character encoding by setting -Dfile.encoding=UTF-8 JVM parameter. " + "Differing character encodings across cluster may lead to erratic behavior."); } } /** * Checks whether physical RAM is not exceeded. */ @SuppressWarnings("ConstantConditions") private void checkPhysicalRam() { long ram = ctx.discovery().localNode().attribute(ATTR_PHY_RAM); if (ram != -1) { String macs = ctx.discovery().localNode().attribute(ATTR_MACS); long totalHeap = 0; long totalOffheap = 0; for (ClusterNode node : ctx.discovery().allNodes()) { if (macs.equals(node.attribute(ATTR_MACS))) { long heap = node.metrics().getHeapMemoryMaximum(); Long offheap = node.<Long>attribute(ATTR_OFFHEAP_SIZE); if (heap != -1) totalHeap += heap; if (offheap != null) totalOffheap += offheap; } } long total = totalHeap + totalOffheap; if (total < 0) total = Long.MAX_VALUE; // 4GB or 20% of available memory is expected to be used by OS and user applications long safeToUse = ram - Math.max(4L << 30, (long)(ram * 0.2)); if (total > safeToUse) { U.quietAndWarn(log, "Nodes started on local machine require more than 80% of physical RAM what can " + "lead to significant slowdown due to swapping (please decrease JVM heap size, data region " + "size or checkpoint buffer size) [required=" + (total >> 20) + "MB, available=" + (ram >> 20) + "MB]"); } } } /** * @param cfg Ignite configuration to check for possible performance issues. */ private void suggestOptimizations(IgniteConfiguration cfg) { GridPerformanceSuggestions perf = ctx.performance(); if (ctx.collision().enabled()) perf.add("Disable collision resolution (remove 'collisionSpi' from configuration)"); if (ctx.checkpoint().enabled()) perf.add("Disable checkpoints (remove 'checkpointSpi' from configuration)"); if (cfg.isMarshalLocalJobs()) perf.add("Disable local jobs marshalling (set 'marshalLocalJobs' to false)"); if (cfg.getIncludeEventTypes() != null && cfg.getIncludeEventTypes().length != 0) perf.add("Disable grid events (remove 'includeEventTypes' from configuration)"); if (BinaryMarshaller.available() && (cfg.getMarshaller() != null && !(cfg.getMarshaller() instanceof BinaryMarshaller))) perf.add("Use default binary marshaller (do not set 'marshaller' explicitly)"); } /** * Creates attributes map and fills it in. * * @param notifyEnabled Update notifier flag. * @throws IgniteCheckedException thrown if was unable to set up attribute. */ private void fillNodeAttributes(boolean notifyEnabled) throws IgniteCheckedException { ctx.addNodeAttribute(ATTR_REBALANCE_POOL_SIZE, configuration().getRebalanceThreadPoolSize()); ctx.addNodeAttribute(ATTR_DATA_STREAMER_POOL_SIZE, configuration().getDataStreamerThreadPoolSize()); final String[] incProps = cfg.getIncludeProperties(); try { // Stick all environment settings into node attributes. for (Map.Entry<String, String> sysEntry : System.getenv().entrySet()) { String name = sysEntry.getKey(); if (incProps == null || U.containsStringArray(incProps, name, true) || U.isVisorNodeStartProperty(name) || U.isVisorRequiredProperty(name)) ctx.addNodeAttribute(name, sysEntry.getValue()); } if (log.isDebugEnabled()) log.debug("Added environment properties to node attributes."); } catch (SecurityException e) { throw new IgniteCheckedException("Failed to add environment properties to node attributes due to " + "security violation: " + e.getMessage()); } try { // Stick all system properties into node's attributes overwriting any // identical names from environment properties. for (Map.Entry<Object, Object> e : IgniteSystemProperties.snapshot().entrySet()) { String key = (String)e.getKey(); if (incProps == null || U.containsStringArray(incProps, key, true) || U.isVisorRequiredProperty(key)) { Object val = ctx.nodeAttribute(key); if (val != null && !val.equals(e.getValue())) U.warn(log, "System property will override environment variable with the same name: " + key); ctx.addNodeAttribute(key, e.getValue()); } } ctx.addNodeAttribute(IgniteNodeAttributes.ATTR_UPDATE_NOTIFIER_ENABLED, notifyEnabled); if (log.isDebugEnabled()) log.debug("Added system properties to node attributes."); } catch (SecurityException e) { throw new IgniteCheckedException("Failed to add system properties to node attributes due to security " + "violation: " + e.getMessage()); } // Add local network IPs and MACs. String ips = F.concat(U.allLocalIps(), ", "); // Exclude loopbacks. String macs = F.concat(U.allLocalMACs(), ", "); // Only enabled network interfaces. // Ack network context. if (log.isInfoEnabled()) { log.info("Non-loopback local IPs: " + (F.isEmpty(ips) ? "N/A" : ips)); log.info("Enabled local MACs: " + (F.isEmpty(macs) ? "N/A" : macs)); } // Warn about loopback. if (ips.isEmpty() && macs.isEmpty()) U.warn(log, "Ignite is starting on loopback address... Only nodes on the same physical " + "computer can participate in topology."); // Stick in network context into attributes. add(ATTR_IPS, (ips.isEmpty() ? "" : ips)); Map<String, ?> userAttrs = configuration().getUserAttributes(); if (userAttrs != null && userAttrs.get(IgniteNodeAttributes.ATTR_MACS_OVERRIDE) != null) add(ATTR_MACS, (Serializable)userAttrs.get(IgniteNodeAttributes.ATTR_MACS_OVERRIDE)); else add(ATTR_MACS, (macs.isEmpty() ? "" : macs)); // Stick in some system level attributes add(ATTR_JIT_NAME, U.getCompilerMx() == null ? "" : U.getCompilerMx().getName()); add(ATTR_BUILD_VER, VER_STR); add(ATTR_BUILD_DATE, BUILD_TSTAMP_STR); add(ATTR_MARSHALLER, cfg.getMarshaller().getClass().getName()); add(ATTR_MARSHALLER_USE_DFLT_SUID, getBoolean(IGNITE_OPTIMIZED_MARSHALLER_USE_DEFAULT_SUID, OptimizedMarshaller.USE_DFLT_SUID)); add(ATTR_LATE_AFFINITY_ASSIGNMENT, cfg.isLateAffinityAssignment()); if (cfg.getMarshaller() instanceof BinaryMarshaller) { add(ATTR_MARSHALLER_COMPACT_FOOTER, cfg.getBinaryConfiguration() == null ? BinaryConfiguration.DFLT_COMPACT_FOOTER : cfg.getBinaryConfiguration().isCompactFooter()); add(ATTR_MARSHALLER_USE_BINARY_STRING_SER_VER_2, getBoolean(IGNITE_BINARY_MARSHALLER_USE_STRING_SERIALIZATION_VER_2, BinaryUtils.USE_STR_SERIALIZATION_VER_2)); } add(ATTR_USER_NAME, System.getProperty("user.name")); add(ATTR_IGNITE_INSTANCE_NAME, igniteInstanceName); add(ATTR_PEER_CLASSLOADING, cfg.isPeerClassLoadingEnabled()); add(ATTR_SHUTDOWN_POLICY, cfg.getShutdownPolicy().index()); add(ATTR_DEPLOYMENT_MODE, cfg.getDeploymentMode()); add(ATTR_LANG_RUNTIME, getLanguage()); add(ATTR_JVM_PID, U.jvmPid()); add(ATTR_CLIENT_MODE, cfg.isClientMode()); add(ATTR_CONSISTENCY_CHECK_SKIPPED, getBoolean(IGNITE_SKIP_CONFIGURATION_CONSISTENCY_CHECK)); add(ATTR_VALIDATE_CACHE_REQUESTS, Boolean.TRUE); if (cfg.getConsistentId() != null) add(ATTR_NODE_CONSISTENT_ID, cfg.getConsistentId()); // Build a string from JVM arguments, because parameters with spaces are split. SB jvmArgs = new SB(512); for (String arg : U.jvmArgs()) { if (arg.startsWith("-")) jvmArgs.a("@@@"); else jvmArgs.a(' '); jvmArgs.a(arg); } // Add it to attributes. add(ATTR_JVM_ARGS, jvmArgs.toString()); // Check daemon system property and override configuration if it's set. if (isDaemon()) add(ATTR_DAEMON, "true"); // In case of the parsing error, JMX remote disabled or port not being set // node attribute won't be set. if (isJmxRemoteEnabled()) { String portStr = System.getProperty("com.sun.management.jmxremote.port"); if (portStr != null) try { add(ATTR_JMX_PORT, Integer.parseInt(portStr)); } catch (NumberFormatException ignore) { // No-op. } } // Whether restart is enabled and stick the attribute. add(ATTR_RESTART_ENABLED, Boolean.toString(isRestartEnabled())); // Save port range, port numbers will be stored by rest processor at runtime. if (cfg.getConnectorConfiguration() != null) add(ATTR_REST_PORT_RANGE, cfg.getConnectorConfiguration().getPortRange()); // Whether rollback of dynamic cache start is supported or not. // This property is added because of backward compatibility. add(ATTR_DYNAMIC_CACHE_START_ROLLBACK_SUPPORTED, Boolean.TRUE); // Save data storage configuration. addDataStorageConfigurationAttributes(); // Save transactions configuration. add(ATTR_TX_CONFIG, cfg.getTransactionConfiguration()); // Supported features. add(ATTR_IGNITE_FEATURES, IgniteFeatures.allFeatures()); // Stick in SPI versions and classes attributes. addSpiAttributes(cfg.getCollisionSpi()); addSpiAttributes(cfg.getDiscoverySpi()); addSpiAttributes(cfg.getFailoverSpi()); addSpiAttributes(cfg.getCommunicationSpi()); addSpiAttributes(cfg.getEventStorageSpi()); addSpiAttributes(cfg.getCheckpointSpi()); addSpiAttributes(cfg.getLoadBalancingSpi()); addSpiAttributes(cfg.getDeploymentSpi()); addSpiAttributes(cfg.getTracingSpi()); // Set user attributes for this node. if (cfg.getUserAttributes() != null) { for (Map.Entry<String, ?> e : cfg.getUserAttributes().entrySet()) { if (ctx.hasNodeAttribute(e.getKey())) U.warn(log, "User or internal attribute has the same name as environment or system " + "property and will take precedence: " + e.getKey()); ctx.addNodeAttribute(e.getKey(), e.getValue()); } } ctx.addNodeAttribute(ATTR_EVENT_DRIVEN_SERVICE_PROCESSOR_ENABLED, ctx.service() instanceof IgniteServiceProcessor); } /** * @throws IgniteCheckedException If duplicated SPI name found. */ private void addDataStorageConfigurationAttributes() throws IgniteCheckedException { MemoryConfiguration memCfg = cfg.getMemoryConfiguration(); // Save legacy memory configuration if it's present. if (memCfg != null) { // Page size initialization is suspended, see IgniteCacheDatabaseSharedManager#checkPageSize. // We should copy initialized value from new configuration. memCfg.setPageSize(cfg.getDataStorageConfiguration().getPageSize()); add(ATTR_MEMORY_CONFIG, memCfg); } // Save data storage configuration. add(ATTR_DATA_STORAGE_CONFIG, new JdkMarshaller().marshal(cfg.getDataStorageConfiguration())); } /** * Add SPI version and class attributes into node attributes. * * @param spiList Collection of SPIs to get attributes from. * @throws IgniteCheckedException Thrown if was unable to set up attribute. */ private void addSpiAttributes(IgniteSpi... spiList) throws IgniteCheckedException { for (IgniteSpi spi : spiList) { Class<? extends IgniteSpi> spiCls = spi.getClass(); add(U.spiAttribute(spi, ATTR_SPI_CLASS), spiCls.getName()); } } /** * @param mgr Manager to start. * @throws IgniteCheckedException Throw in case of any errors. */ private void startManager(GridManager mgr) throws IgniteCheckedException { // Add manager to registry before it starts to avoid cases when manager is started // but registry does not have it yet. ctx.add(mgr); try { if (!skipDaemon(mgr)) mgr.start(); } catch (IgniteCheckedException e) { U.error(log, "Failed to start manager: " + mgr, e); throw new IgniteCheckedException("Failed to start manager: " + mgr, e); } } /** * @param proc Processor to start. * @throws IgniteCheckedException Thrown in case of any error. */ private void startProcessor(GridProcessor proc) throws IgniteCheckedException { ctx.add(proc); try { if (!skipDaemon(proc)) proc.start(); } catch (IgniteCheckedException e) { throw new IgniteCheckedException("Failed to start processor: " + proc, e); } } /** * @param helper Helper to attach to kernal context. */ private void addHelper(Object helper) { ctx.addHelper(helper); } /** * Gets "on" or "off" string for given boolean value. * * @param b Boolean value to convert. * @return Result string. */ private String onOff(boolean b) { return b ? "on" : "off"; } /** * @return {@code true} if the REST processor is enabled, {@code false} the otherwise. */ private boolean isRestEnabled() { assert cfg != null; return cfg.getConnectorConfiguration() != null && // By default rest processor doesn't start on client nodes. (!isClientNode() || (isClientNode() && IgniteSystemProperties.getBoolean(IGNITE_REST_START_ON_CLIENT))); } /** * @return {@code True} if node client or daemon otherwise {@code false}. */ private boolean isClientNode() { return cfg.isClientMode() || cfg.isDaemon(); } /** * Acks remote management. */ private void ackRemoteManagement() { assert log != null; if (!log.isInfoEnabled()) return; SB sb = new SB(); sb.a("Remote Management ["); boolean on = isJmxRemoteEnabled(); sb.a("restart: ").a(onOff(isRestartEnabled())).a(", "); sb.a("REST: ").a(onOff(isRestEnabled())).a(", "); sb.a("JMX ("); sb.a("remote: ").a(onOff(on)); if (on) { sb.a(", "); sb.a("port: ").a(System.getProperty("com.sun.management.jmxremote.port", "<n/a>")).a(", "); sb.a("auth: ").a(onOff(Boolean.getBoolean("com.sun.management.jmxremote.authenticate"))).a(", "); // By default SSL is enabled, that's why additional check for null is needed. // See http://docs.oracle.com/javase/6/docs/technotes/guides/management/agent.html sb.a("ssl: ").a(onOff(Boolean.getBoolean("com.sun.management.jmxremote.ssl") || System.getProperty("com.sun.management.jmxremote.ssl") == null)); } sb.a(")"); sb.a(']'); log.info(sb.toString()); } /** * Acks configuration URL. */ private void ackConfigUrl() { assert log != null; if (log.isInfoEnabled()) log.info("Config URL: " + System.getProperty(IGNITE_CONFIG_URL, "n/a")); } /** * @param cfg Ignite configuration to ack. */ private void ackConfiguration(IgniteConfiguration cfg) { assert log != null; if (log.isInfoEnabled()) log.info(cfg.toString()); } /** * Acks Logger configuration. */ private void ackLogger() { assert log != null; if (log.isInfoEnabled()) log.info("Logger: " + log.getLoggerInfo()); } /** * Acks ASCII-logo. Thanks to http://patorjk.com/software/taag */ private void ackAsciiLogo() { assert log != null; if (System.getProperty(IGNITE_NO_ASCII) == null) { String ver = "ver. " + ACK_VER_STR; // Big thanks to: http://patorjk.com/software/taag // Font name "Small Slant" if (log.isInfoEnabled()) { log.info(NL + NL + ">>> __________ ________________ " + NL + ">>> / _/ ___/ |/ / _/_ __/ __/ " + NL + ">>> _/ // (7 7 // / / / / _/ " + NL + ">>> /___/\\___/_/|_/___/ /_/ /___/ " + NL + ">>> " + NL + ">>> " + ver + NL + ">>> " + COPYRIGHT + NL + ">>> " + NL + ">>> Ignite documentation: " + "http://" + SITE + NL ); } if (log.isQuiet()) { U.quiet(false, " __________ ________________ ", " / _/ ___/ |/ / _/_ __/ __/ ", " _/ // (7 7 // / / / / _/ ", "/___/\\___/_/|_/___/ /_/ /___/ ", "", ver, COPYRIGHT, "", "Ignite documentation: " + "http://" + SITE, "", "Quiet mode."); String fileName = log.fileName(); if (fileName != null) U.quiet(false, " ^-- Logging to file '" + fileName + '\''); U.quiet(false, " ^-- Logging by '" + log.getLoggerInfo() + '\''); U.quiet(false, " ^-- To see **FULL** console log here add -DIGNITE_QUIET=false or \"-v\" to ignite.{sh|bat}", ""); } } } /** * Prints start info. * * @param rtBean Java runtime bean. */ private void ackStart(RuntimeMXBean rtBean) { ClusterNode locNode = localNode(); if (log.isQuiet()) { U.quiet(false, ""); U.quiet(false, "Ignite node started OK (id=" + U.id8(locNode.id()) + (F.isEmpty(igniteInstanceName) ? "" : ", instance name=" + igniteInstanceName) + ')'); } if (log.isInfoEnabled()) { String ack = "Ignite ver. " + VER_STR + '#' + BUILD_TSTAMP_STR + "-sha1:" + REV_HASH_STR; String dash = U.dash(ack.length()); SB sb = new SB(); for (GridPortRecord rec : ctx.ports().records()) sb.a(rec.protocol()).a(":").a(rec.port()).a(" "); String str = NL + NL + ">>> " + dash + NL + ">>> " + ack + NL + ">>> " + dash + NL + ">>> OS name: " + U.osString() + NL + ">>> CPU(s): " + locNode.metrics().getTotalCpus() + NL + ">>> Heap: " + U.heapSize(locNode, 2) + "GB" + NL + ">>> VM name: " + rtBean.getName() + NL + (igniteInstanceName == null ? "" : ">>> Ignite instance name: " + igniteInstanceName + NL) + ">>> Local node [" + "ID=" + locNode.id().toString().toUpperCase() + ", order=" + locNode.order() + ", clientMode=" + ctx.clientNode() + "]" + NL + ">>> Local node addresses: " + U.addressesAsString(locNode) + NL + ">>> Local ports: " + sb + NL; log.info(str); } if (ctx.state().clusterState().state() == ClusterState.INACTIVE) { U.quietAndInfo(log, ">>> Ignite cluster is in INACTIVE state (limited functionality available). " + "Use control.(sh|bat) script or IgniteCluster.state(ClusterState.ACTIVE) to change the state."); } } /** * Logs out OS information. */ private void ackOsInfo() { assert log != null; if (log.isQuiet()) U.quiet(false, "OS: " + U.osString()); if (log.isInfoEnabled()) { log.info("OS: " + U.osString()); log.info("OS user: " + System.getProperty("user.name")); int jvmPid = U.jvmPid(); log.info("PID: " + (jvmPid == -1 ? "N/A" : jvmPid)); } } /** * Logs out language runtime. */ private void ackLanguageRuntime() { assert log != null; if (log.isQuiet()) U.quiet(false, "VM information: " + U.jdkString()); if (log.isInfoEnabled()) { log.info("Language runtime: " + getLanguage()); log.info("VM information: " + U.jdkString()); log.info("VM total memory: " + U.heapSize(2) + "GB"); } } /** * Logs out node metrics. * * @param dblFmt Decimal format. * @param execSvc Executor service. * @param sysExecSvc System executor service. * @param customExecSvcs Custom named executors. */ private void ackNodeMetrics(DecimalFormat dblFmt, ExecutorService execSvc, ExecutorService sysExecSvc, Map<String, ? extends ExecutorService> customExecSvcs ) { if (!log.isInfoEnabled()) return; try { ClusterMetrics m = cluster().localNode().metrics(); int localCpus = m.getTotalCpus(); double cpuLoadPct = m.getCurrentCpuLoad() * 100; double avgCpuLoadPct = m.getAverageCpuLoad() * 100; double gcPct = m.getCurrentGcCpuLoad() * 100; // Heap params. long heapUsed = m.getHeapMemoryUsed(); long heapMax = m.getHeapMemoryMaximum(); long heapUsedInMBytes = heapUsed / MEGABYTE; long heapCommInMBytes = m.getHeapMemoryCommitted() / MEGABYTE; double freeHeapPct = heapMax > 0 ? ((double)((heapMax - heapUsed) * 100)) / heapMax : -1; int hosts = 0; int servers = 0; int clients = 0; int cpus = 0; try { ClusterMetrics metrics = cluster().metrics(); Collection<ClusterNode> nodes0 = cluster().nodes(); hosts = U.neighborhood(nodes0).size(); servers = cluster().forServers().nodes().size(); clients = cluster().forClients().nodes().size(); cpus = metrics.getTotalCpus(); } catch (IgniteException ignore) { // No-op. } String dataStorageInfo = dataStorageReport(ctx.cache().context().database(), dblFmt, true); String id = U.id8(localNode().id()); AffinityTopologyVersion topVer = ctx.discovery().topologyVersionEx(); ClusterNode locNode = ctx.discovery().localNode(); String networkDetails = ""; if (!F.isEmpty(cfg.getLocalHost())) networkDetails += ", localHost=" + cfg.getLocalHost(); if (locNode instanceof TcpDiscoveryNode) networkDetails += ", discoPort=" + ((TcpDiscoveryNode)locNode).discoveryPort(); if (cfg.getCommunicationSpi() instanceof TcpCommunicationSpi) networkDetails += ", commPort=" + ((TcpCommunicationSpi)cfg.getCommunicationSpi()).boundPort(); SB msg = new SB(); msg.nl() .a("Metrics for local node (to disable set 'metricsLogFrequency' to 0)").nl() .a(" ^-- Node [id=").a(id).a(name() != null ? ", name=" + name() : "").a(", uptime=") .a(getUpTimeFormatted()).a("]").nl() .a(" ^-- Cluster [hosts=").a(hosts).a(", CPUs=").a(cpus).a(", servers=").a(servers) .a(", clients=").a(clients).a(", topVer=").a(topVer.topologyVersion()) .a(", minorTopVer=").a(topVer.minorTopologyVersion()).a("]").nl() .a(" ^-- Network [addrs=").a(locNode.addresses()).a(networkDetails).a("]").nl() .a(" ^-- CPU [CPUs=").a(localCpus).a(", curLoad=").a(dblFmt.format(cpuLoadPct)) .a("%, avgLoad=").a(dblFmt.format(avgCpuLoadPct)).a("%, GC=").a(dblFmt.format(gcPct)).a("%]").nl() .a(" ^-- Heap [used=").a(dblFmt.format(heapUsedInMBytes)) .a("MB, free=").a(dblFmt.format(freeHeapPct)) .a("%, comm=").a(dblFmt.format(heapCommInMBytes)).a("MB]").nl() .a(dataStorageInfo) .a(" ^-- Outbound messages queue [size=").a(m.getOutboundMessagesQueueSize()).a("]").nl() .a(" ^-- ").a(createExecutorDescription("Public thread pool", execSvc)).nl() .a(" ^-- ").a(createExecutorDescription("System thread pool", sysExecSvc)); if (customExecSvcs != null) { for (Map.Entry<String, ? extends ExecutorService> entry : customExecSvcs.entrySet()) msg.nl().a(" ^-- ").a(createExecutorDescription(entry.getKey(), entry.getValue())); } log.info(msg.toString()); ctx.cache().context().database().dumpStatistics(log); } catch (IgniteClientDisconnectedException ignore) { // No-op. } } /** */ public static String dataStorageReport(IgniteCacheDatabaseSharedManager db, boolean includeMemoryStatistics) { return dataStorageReport(db, doubleFormat(), includeMemoryStatistics); } /** */ private static String dataStorageReport(IgniteCacheDatabaseSharedManager db, DecimalFormat dblFmt, boolean includeMemoryStatistics) { // Off-heap params. Collection<DataRegion> regions = db.dataRegions(); SB dataRegionsInfo = new SB(); long loadedPages = 0; long offHeapUsedSummary = 0; long offHeapMaxSummary = 0; long offHeapCommSummary = 0; long pdsUsedSummary = 0; boolean persistenceEnabled = false; if (!F.isEmpty(regions)) { for (DataRegion region : regions) { DataRegionConfiguration regCfg = region.config(); long pagesCnt = region.pageMemory().loadedPages(); long offHeapUsed = region.pageMemory().systemPageSize() * pagesCnt; long offHeapInit = regCfg.getInitialSize(); long offHeapMax = regCfg.getMaxSize(); long offHeapComm = region.memoryMetrics().getOffHeapSize(); long offHeapUsedInMBytes = offHeapUsed / MEGABYTE; long offHeapMaxInMBytes = offHeapMax / MEGABYTE; long offHeapCommInMBytes = offHeapComm / MEGABYTE; long offHeapInitInMBytes = offHeapInit / MEGABYTE; double freeOffHeapPct = offHeapMax > 0 ? ((double)((offHeapMax - offHeapUsed) * 100)) / offHeapMax : -1; offHeapUsedSummary += offHeapUsed; offHeapMaxSummary += offHeapMax; offHeapCommSummary += offHeapComm; loadedPages += pagesCnt; String type = "user"; try { if (region == db.dataRegion(null)) type = "default"; else if (INTERNAL_DATA_REGION_NAMES.contains(regCfg.getName())) type = "internal"; } catch (IgniteCheckedException ice) { // Should never happen ice.printStackTrace(); } dataRegionsInfo.a(" ^-- ") .a(regCfg.getName()).a(" region [type=").a(type) .a(", persistence=").a(regCfg.isPersistenceEnabled()) .a(", lazyAlloc=").a(regCfg.isLazyMemoryAllocation()).a(',').nl() .a(" ... ") .a("initCfg=").a(dblFmt.format(offHeapInitInMBytes)) .a("MB, maxCfg=").a(dblFmt.format(offHeapMaxInMBytes)) .a("MB, usedRam=").a(dblFmt.format(offHeapUsedInMBytes)) .a("MB, freeRam=").a(dblFmt.format(freeOffHeapPct)) .a("%, allocRam=").a(dblFmt.format(offHeapCommInMBytes)).a("MB"); if (regCfg.isPersistenceEnabled()) { long pdsUsed = region.memoryMetrics().getTotalAllocatedSize(); long pdsUsedInMBytes = pdsUsed / MEGABYTE; pdsUsedSummary += pdsUsed; dataRegionsInfo.a(", allocTotal=").a(dblFmt.format(pdsUsedInMBytes)).a("MB"); persistenceEnabled = true; } dataRegionsInfo.a(']').nl(); } } SB info = new SB(); if (includeMemoryStatistics) { long offHeapUsedInMBytes = offHeapUsedSummary / MEGABYTE; long offHeapCommInMBytes = offHeapCommSummary / MEGABYTE; double freeOffHeapPct = offHeapMaxSummary > 0 ? ((double)((offHeapMaxSummary - offHeapUsedSummary) * 100)) / offHeapMaxSummary : -1; info.a(" ^-- Off-heap memory [used=").a(dblFmt.format(offHeapUsedInMBytes)) .a("MB, free=").a(dblFmt.format(freeOffHeapPct)) .a("%, allocated=").a(dblFmt.format(offHeapCommInMBytes)).a("MB]").nl() .a(" ^-- Page memory [pages=").a(loadedPages).a("]").nl(); } info.a(dataRegionsInfo); if (persistenceEnabled) { long pdsUsedMBytes = pdsUsedSummary / MEGABYTE; info.a(" ^-- Ignite persistence [used=").a(dblFmt.format(pdsUsedMBytes)).a("MB]").nl(); } return info.toString(); } /** * @return Language runtime. */ private String getLanguage() { boolean scala = false; boolean groovy = false; boolean clojure = false; for (StackTraceElement elem : Thread.currentThread().getStackTrace()) { String s = elem.getClassName().toLowerCase(); if (s.contains("scala")) { scala = true; break; } else if (s.contains("groovy")) { groovy = true; break; } else if (s.contains("clojure")) { clojure = true; break; } } if (scala) { try (InputStream in = getClass().getResourceAsStream("/library.properties")) { Properties props = new Properties(); if (in != null) props.load(in); return "Scala ver. " + props.getProperty("version.number", "<unknown>"); } catch (Exception ignore) { return "Scala ver. <unknown>"; } } // How to get Groovy and Clojure version at runtime?!? return groovy ? "Groovy" : clojure ? "Clojure" : U.jdkName() + " ver. " + U.jdkVersion(); } /** * Stops Ignite instance. * * @param cancel Whether or not to cancel running jobs. */ public void stop(boolean cancel) { // Make sure that thread stopping grid is not interrupted. boolean interrupted = Thread.interrupted(); try { stop0(cancel); } finally { if (interrupted) Thread.currentThread().interrupt(); } } /** * @return {@code True} if node started shutdown sequence. */ public boolean isStopping() { return stopGuard.get(); } /** * @param cancel Whether or not to cancel running jobs. */ private void stop0(boolean cancel) { gw.compareAndSet(null, new GridKernalGatewayImpl(igniteInstanceName)); GridKernalGateway gw = this.gw.get(); if (stopGuard.compareAndSet(false, true)) { // Only one thread is allowed to perform stop sequence. boolean firstStop = false; GridKernalState state = gw.getState(); if (state == STARTED || state == DISCONNECTED) firstStop = true; else if (state == STARTING) U.warn(log, "Attempt to stop starting grid. This operation " + "cannot be guaranteed to be successful."); if (firstStop) { // Notify lifecycle beans. if (log.isDebugEnabled()) log.debug("Notifying lifecycle beans."); notifyLifecycleBeansEx(LifecycleEventType.BEFORE_NODE_STOP); } List<GridComponent> comps = ctx.components(); // Callback component in reverse order while kernal is still functional // if called in the same thread, at least. for (ListIterator<GridComponent> it = comps.listIterator(comps.size()); it.hasPrevious(); ) { GridComponent comp = it.previous(); try { if (!skipDaemon(comp)) comp.onKernalStop(cancel); } catch (Throwable e) { errOnStop = true; U.error(log, "Failed to pre-stop processor: " + comp, e); if (e instanceof Error) throw e; } } if (starveTask != null) starveTask.close(); if (metricsLogTask != null) metricsLogTask.close(); if (longJVMPauseDetector != null) longJVMPauseDetector.stop(); boolean interrupted = false; while (true) { try { if (gw.tryWriteLock(10)) break; } catch (InterruptedException ignored) { // Preserve interrupt status & ignore. // Note that interrupted flag is cleared. interrupted = true; } } if (interrupted) Thread.currentThread().interrupt(); try { assert gw.getState() == STARTED || gw.getState() == STARTING || gw.getState() == DISCONNECTED; // No more kernal calls from this point on. gw.setState(STOPPING); ctx.cluster().get().clearNodeMap(); if (log.isDebugEnabled()) log.debug("Grid " + (igniteInstanceName == null ? "" : '\'' + igniteInstanceName + "' ") + "is stopping."); } finally { gw.writeUnlock(); } // Stopping cache operations. GridCacheProcessor cache = ctx.cache(); if (cache != null) cache.blockGateways(); // Unregister MBeans. if (!mBeansMgr.unregisterAllMBeans()) errOnStop = true; // Stop components in reverse order. for (ListIterator<GridComponent> it = comps.listIterator(comps.size()); it.hasPrevious(); ) { GridComponent comp = it.previous(); try { if (!skipDaemon(comp)) { comp.stop(cancel); if (log.isDebugEnabled()) log.debug("Component stopped: " + comp); } } catch (Throwable e) { errOnStop = true; U.error(log, "Failed to stop component (ignoring): " + comp, e); if (e instanceof Error) throw (Error)e; } } // Stops lifecycle aware components. U.stopLifecycleAware(log, lifecycleAwares(cfg)); // Lifecycle notification. notifyLifecycleBeansEx(LifecycleEventType.AFTER_NODE_STOP); // Clean internal class/classloader caches to avoid stopped contexts held in memory. U.clearClassCache(); MarshallerExclusions.clearCache(); BinaryEnumCache.clear(); gw.writeLock(); try { gw.setState(STOPPED); } finally { gw.writeUnlock(); } // Ack stop. if (log.isQuiet()) { String nodeName = igniteInstanceName == null ? "" : "name=" + igniteInstanceName + ", "; if (!errOnStop) U.quiet(false, "Ignite node stopped OK [" + nodeName + "uptime=" + X.timeSpan2DHMSM(U.currentTimeMillis() - startTime) + ']'); else U.quiet(true, "Ignite node stopped wih ERRORS [" + nodeName + "uptime=" + X.timeSpan2DHMSM(U.currentTimeMillis() - startTime) + ']'); } if (log.isInfoEnabled()) if (!errOnStop) { String ack = "Ignite ver. " + VER_STR + '#' + BUILD_TSTAMP_STR + "-sha1:" + REV_HASH_STR + " stopped OK"; String dash = U.dash(ack.length()); log.info(NL + NL + ">>> " + dash + NL + ">>> " + ack + NL + ">>> " + dash + NL + (igniteInstanceName == null ? "" : ">>> Ignite instance name: " + igniteInstanceName + NL) + ">>> Grid uptime: " + X.timeSpan2DHMSM(U.currentTimeMillis() - startTime) + NL + NL); } else { String ack = "Ignite ver. " + VER_STR + '#' + BUILD_TSTAMP_STR + "-sha1:" + REV_HASH_STR + " stopped with ERRORS"; String dash = U.dash(ack.length()); log.info(NL + NL + ">>> " + ack + NL + ">>> " + dash + NL + (igniteInstanceName == null ? "" : ">>> Ignite instance name: " + igniteInstanceName + NL) + ">>> Grid uptime: " + X.timeSpan2DHMSM(U.currentTimeMillis() - startTime) + NL + ">>> See log above for detailed error message." + NL + ">>> Note that some errors during stop can prevent grid from" + NL + ">>> maintaining correct topology since this node may have" + NL + ">>> not exited grid properly." + NL + NL); } try { U.onGridStop(); } catch (InterruptedException ignored) { // Preserve interrupt status. Thread.currentThread().interrupt(); } } else { // Proper notification. if (log.isDebugEnabled()) { if (gw.getState() == STOPPED) log.debug("Grid is already stopped. Nothing to do."); else log.debug("Grid is being stopped by another thread. Aborting this stop sequence " + "allowing other thread to finish."); } } } /** * USED ONLY FOR TESTING. * * @param name Cache name. * @param <K> Key type. * @param <V> Value type. * @return Internal cache instance. */ /*@java.test.only*/ public <K, V> GridCacheAdapter<K, V> internalCache(String name) { CU.validateCacheName(name); checkClusterState(); return ctx.cache().internalCache(name); } /** * It's intended for use by internal marshalling implementation only. * * @return Kernal context. */ @Override public GridKernalContext context() { return ctx; } /** * Prints all system properties in debug mode. */ private void ackSystemProperties() { assert log != null; if (log.isDebugEnabled() && S.includeSensitive()) for (Map.Entry<Object, Object> entry : IgniteSystemProperties.snapshot().entrySet()) log.debug("System property [" + entry.getKey() + '=' + entry.getValue() + ']'); } /** * Prints all user attributes in info mode. */ private void logNodeUserAttributes() { assert log != null; if (log.isInfoEnabled()) for (Map.Entry<?, ?> attr : cfg.getUserAttributes().entrySet()) log.info("Local node user attribute [" + attr.getKey() + '=' + attr.getValue() + ']'); } /** * Prints all environment variables in debug mode. */ private void ackEnvironmentVariables() { assert log != null; if (log.isDebugEnabled()) for (Map.Entry<?, ?> envVar : System.getenv().entrySet()) log.debug("Environment variable [" + envVar.getKey() + '=' + envVar.getValue() + ']'); } /** * Acks daemon mode status. */ private void ackDaemon() { assert log != null; if (log.isInfoEnabled()) log.info("Daemon mode: " + (isDaemon() ? "on" : "off")); } /** * @return {@code True} is this node is daemon. */ private boolean isDaemon() { assert cfg != null; return cfg.isDaemon() || IgniteSystemProperties.getBoolean(IGNITE_DAEMON); } /** * Whether or not remote JMX management is enabled for this node. Remote JMX management is enabled when the * following system property is set: <ul> <li>{@code com.sun.management.jmxremote}</li> </ul> * * @return {@code True} if remote JMX management is enabled - {@code false} otherwise. */ @Override public boolean isJmxRemoteEnabled() { return System.getProperty("com.sun.management.jmxremote") != null; } /** * Whether or not node restart is enabled. Node restart us supported when this node was started with {@code * bin/ignite.{sh|bat}} script using {@code -r} argument. Node can be programmatically restarted using {@link * Ignition#restart(boolean)}} method. * * @return {@code True} if restart mode is enabled, {@code false} otherwise. * @see Ignition#restart(boolean) */ @Override public boolean isRestartEnabled() { return System.getProperty(IGNITE_SUCCESS_FILE) != null; } /** * Prints all configuration properties in info mode and SPIs in debug mode. */ private void ackSpis() { assert log != null; if (log.isDebugEnabled()) { log.debug("+-------------+"); log.debug("START SPI LIST:"); log.debug("+-------------+"); log.debug("Grid checkpoint SPI : " + Arrays.toString(cfg.getCheckpointSpi())); log.debug("Grid collision SPI : " + cfg.getCollisionSpi()); log.debug("Grid communication SPI : " + cfg.getCommunicationSpi()); log.debug("Grid deployment SPI : " + cfg.getDeploymentSpi()); log.debug("Grid discovery SPI : " + cfg.getDiscoverySpi()); log.debug("Grid event storage SPI : " + cfg.getEventStorageSpi()); log.debug("Grid failover SPI : " + Arrays.toString(cfg.getFailoverSpi())); log.debug("Grid load balancing SPI : " + Arrays.toString(cfg.getLoadBalancingSpi())); } } /** * Acknowledge that the rebalance configuration properties are setted correctly. * * @throws IgniteCheckedException If rebalance configuration validation fail. */ private void ackRebalanceConfiguration() throws IgniteCheckedException { if (cfg.isClientMode()) { if (cfg.getRebalanceThreadPoolSize() != IgniteConfiguration.DFLT_REBALANCE_THREAD_POOL_SIZE) U.warn(log, "Setting the rebalance pool size has no effect on the client mode"); } else { if (cfg.getRebalanceThreadPoolSize() < 1) throw new IgniteCheckedException("Rebalance thread pool size minimal allowed value is 1. " + "Change IgniteConfiguration.rebalanceThreadPoolSize property before next start."); if (cfg.getRebalanceBatchesPrefetchCount() < 1) throw new IgniteCheckedException("Rebalance batches prefetch count minimal allowed value is 1. " + "Change IgniteConfiguration.rebalanceBatchesPrefetchCount property before next start."); if (cfg.getRebalanceBatchSize() <= 0) throw new IgniteCheckedException("Rebalance batch size must be greater than zero. " + "Change IgniteConfiguration.rebalanceBatchSize property before next start."); if (cfg.getRebalanceThrottle() < 0) throw new IgniteCheckedException("Rebalance throttle can't have negative value. " + "Change IgniteConfiguration.rebalanceThrottle property before next start."); if (cfg.getRebalanceTimeout() < 0) throw new IgniteCheckedException("Rebalance message timeout can't have negative value. " + "Change IgniteConfiguration.rebalanceTimeout property before next start."); for (CacheConfiguration ccfg : cfg.getCacheConfiguration()) { if (ccfg.getRebalanceBatchesPrefetchCount() < 1) throw new IgniteCheckedException("Rebalance batches prefetch count minimal allowed value is 1. " + "Change CacheConfiguration.rebalanceBatchesPrefetchCount property before next start. " + "[cache=" + ccfg.getName() + "]"); } } } /** * Acknowledge the Ignite configuration related to the data storage. */ private void ackMemoryConfiguration() { DataStorageConfiguration memCfg = cfg.getDataStorageConfiguration(); if (memCfg == null) return; U.log(log, "System cache's DataRegion size is configured to " + (memCfg.getSystemRegionInitialSize() / (1024 * 1024)) + " MB. " + "Use DataStorageConfiguration.systemRegionInitialSize property to change the setting."); } /** * Acknowledge all caches configurations presented in the IgniteConfiguration. */ private void ackCacheConfiguration() { CacheConfiguration[] cacheCfgs = cfg.getCacheConfiguration(); if (cacheCfgs == null || cacheCfgs.length == 0) U.warn(log, "Cache is not configured - in-memory data grid is off."); else { SB sb = new SB(); HashMap<String, ArrayList<String>> memPlcNamesMapping = new HashMap<>(); for (CacheConfiguration c : cacheCfgs) { String cacheName = U.maskName(c.getName()); String memPlcName = c.getDataRegionName(); if (CU.isSystemCache(cacheName)) memPlcName = "sysMemPlc"; else if (memPlcName == null && cfg.getDataStorageConfiguration() != null) memPlcName = cfg.getDataStorageConfiguration().getDefaultDataRegionConfiguration().getName(); if (!memPlcNamesMapping.containsKey(memPlcName)) memPlcNamesMapping.put(memPlcName, new ArrayList<String>()); ArrayList<String> cacheNames = memPlcNamesMapping.get(memPlcName); cacheNames.add(cacheName); } for (Map.Entry<String, ArrayList<String>> e : memPlcNamesMapping.entrySet()) { sb.a("in '").a(e.getKey()).a("' dataRegion: ["); for (String s : e.getValue()) sb.a("'").a(s).a("', "); sb.d(sb.length() - 2, sb.length()).a("], "); } U.log(log, "Configured caches [" + sb.d(sb.length() - 2, sb.length()).toString() + ']'); } } /** * Acknowledge configuration related to the peer class loading. */ private void ackP2pConfiguration() { assert cfg != null; if (cfg.isPeerClassLoadingEnabled()) U.warn( log, "Peer class loading is enabled (disable it in production for performance and " + "deployment consistency reasons)"); } /** * Prints security status. */ private void ackSecurity() { assert log != null; U.quietAndInfo(log, "Security status [authentication=" + onOff(ctx.security().enabled()) + ", sandbox=" + onOff(ctx.security().sandbox().enabled()) + ", tls/ssl=" + onOff(ctx.config().getSslContextFactory() != null) + ']'); } /** * Prints out VM arguments and IGNITE_HOME in info mode. * * @param rtBean Java runtime bean. */ private void ackVmArguments(RuntimeMXBean rtBean) { assert log != null; // Ack IGNITE_HOME and VM arguments. if (log.isInfoEnabled() && S.includeSensitive()) { log.info("IGNITE_HOME=" + cfg.getIgniteHome()); log.info("VM arguments: " + rtBean.getInputArguments()); } } /** * Prints out class paths in debug mode. * * @param rtBean Java runtime bean. */ private void ackClassPaths(RuntimeMXBean rtBean) { assert log != null; // Ack all class paths. if (log.isDebugEnabled()) { try { log.debug("Boot class path: " + rtBean.getBootClassPath()); log.debug("Class path: " + rtBean.getClassPath()); log.debug("Library path: " + rtBean.getLibraryPath()); } catch (Exception ignore) { // No-op: ignore for Java 9+ and non-standard JVMs. } } } /** * Prints warning if 'java.net.preferIPv4Stack=true' is not set. */ private void ackIPv4StackFlagIsSet() { boolean preferIPv4 = Boolean.valueOf(System.getProperty("java.net.preferIPv4Stack")); if (!preferIPv4) { assert log != null; U.quietAndWarn(log, "Please set system property '-Djava.net.preferIPv4Stack=true' " + "to avoid possible problems in mixed environments."); } } /** * @param cfg Ignite configuration to use. * @return Components provided in configuration which can implement {@link LifecycleAware} interface. */ private Iterable<Object> lifecycleAwares(IgniteConfiguration cfg) { Collection<Object> objs = new ArrayList<>(); if (cfg.getLifecycleBeans() != null) Collections.addAll(objs, cfg.getLifecycleBeans()); if (cfg.getSegmentationResolvers() != null) Collections.addAll(objs, cfg.getSegmentationResolvers()); if (cfg.getConnectorConfiguration() != null) { objs.add(cfg.getConnectorConfiguration().getMessageInterceptor()); objs.add(cfg.getConnectorConfiguration().getSslContextFactory()); } objs.add(cfg.getMarshaller()); objs.add(cfg.getGridLogger()); objs.add(cfg.getMBeanServer()); if (cfg.getCommunicationFailureResolver() != null) objs.add(cfg.getCommunicationFailureResolver()); return objs; } /** {@inheritDoc} */ @Override public IgniteConfiguration configuration() { return cfg; } /** {@inheritDoc} */ @Override public IgniteLogger log() { return cfg.getGridLogger(); } /** {@inheritDoc} */ @Override public boolean removeCheckpoint(String key) { A.notNull(key, "key"); guard(); try { checkClusterState(); return ctx.checkpoint().removeCheckpoint(key); } finally { unguard(); } } /** {@inheritDoc} */ @Override public boolean pingNode(String nodeId) { A.notNull(nodeId, "nodeId"); return cluster().pingNode(UUID.fromString(nodeId)); } /** {@inheritDoc} */ @Override public void undeployTaskFromGrid(String taskName) throws JMException { A.notNull(taskName, "taskName"); try { compute().undeployTask(taskName); } catch (IgniteException e) { throw U.jmException(e); } } /** {@inheritDoc} */ @Override public String executeTask(String taskName, String arg) throws JMException { try { return compute().execute(taskName, arg); } catch (IgniteException e) { throw U.jmException(e); } } /** {@inheritDoc} */ @Override public boolean pingNodeByAddress(String host) { guard(); try { for (ClusterNode n : cluster().nodes()) if (n.addresses().contains(host)) return ctx.discovery().pingNode(n.id()); return false; } catch (IgniteCheckedException e) { throw U.convertException(e); } finally { unguard(); } } /** {@inheritDoc} */ @Override public boolean eventUserRecordable(int type) { guard(); try { return ctx.event().isUserRecordable(type); } finally { unguard(); } } /** {@inheritDoc} */ @Override public boolean allEventsUserRecordable(int[] types) { A.notNull(types, "types"); guard(); try { return ctx.event().isAllUserRecordable(types); } finally { unguard(); } } /** {@inheritDoc} */ @Override public IgniteTransactions transactions() { guard(); try { checkClusterState(); return ctx.cache().transactions(); } finally { unguard(); } } /** * @param name Cache name. * @return Ignite internal cache instance related to the given name. */ public <K, V> IgniteInternalCache<K, V> getCache(String name) { CU.validateCacheName(name); guard(); try { checkClusterState(); return ctx.cache().publicCache(name); } finally { unguard(); } } /** {@inheritDoc} */ @Override public <K, V> IgniteCache<K, V> cache(String name) { CU.validateCacheName(name); guard(); try { checkClusterState(); return ctx.cache().publicJCache(name, false, true); } catch (IgniteCheckedException e) { throw CU.convertToCacheException(e); } finally { unguard(); } } /** {@inheritDoc} */ @Override public <K, V> IgniteCache<K, V> createCache(CacheConfiguration<K, V> cacheCfg) { A.notNull(cacheCfg, "cacheCfg"); CU.validateNewCacheName(cacheCfg.getName()); guard(); try { checkClusterState(); ctx.cache().dynamicStartCache(cacheCfg, cacheCfg.getName(), null, true, true, true).get(); return ctx.cache().publicJCache(cacheCfg.getName()); } catch (IgniteCheckedException e) { throw CU.convertToCacheException(e); } finally { unguard(); } } /** {@inheritDoc} */ @Override public Collection<IgniteCache> createCaches(Collection<CacheConfiguration> cacheCfgs) { A.notNull(cacheCfgs, "cacheCfgs"); CU.validateConfigurationCacheNames(cacheCfgs); guard(); try { checkClusterState(); ctx.cache().dynamicStartCaches(cacheCfgs, true, true, false).get(); List<IgniteCache> createdCaches = new ArrayList<>(cacheCfgs.size()); for (CacheConfiguration cacheCfg : cacheCfgs) createdCaches.add(ctx.cache().publicJCache(cacheCfg.getName())); return createdCaches; } catch (IgniteCheckedException e) { throw CU.convertToCacheException(e); } finally { unguard(); } } /** {@inheritDoc} */ @Override public <K, V> IgniteCache<K, V> createCache(String cacheName) { CU.validateNewCacheName(cacheName); guard(); try { checkClusterState(); ctx.cache().createFromTemplate(cacheName).get(); return ctx.cache().publicJCache(cacheName); } catch (IgniteCheckedException e) { throw CU.convertToCacheException(e); } finally { unguard(); } } /** {@inheritDoc} */ @Override public <K, V> IgniteCache<K, V> getOrCreateCache(CacheConfiguration<K, V> cacheCfg) { return getOrCreateCache0(cacheCfg, false).get1(); } /** {@inheritDoc} */ @Override public <K, V> IgniteBiTuple<IgniteCache<K, V>, Boolean> getOrCreateCache0( CacheConfiguration<K, V> cacheCfg, boolean sql) { A.notNull(cacheCfg, "cacheCfg"); String cacheName = cacheCfg.getName(); CU.validateNewCacheName(cacheName); guard(); try { checkClusterState(); Boolean res = false; IgniteCacheProxy<K, V> cache = ctx.cache().publicJCache(cacheName, false, true); if (cache == null) { res = sql ? ctx.cache().dynamicStartSqlCache(cacheCfg).get() : ctx.cache().dynamicStartCache(cacheCfg, cacheName, null, false, true, true).get(); return new IgniteBiTuple<>(ctx.cache().publicJCache(cacheName), res); } else return new IgniteBiTuple<>(cache, res); } catch (IgniteCheckedException e) { throw CU.convertToCacheException(e); } finally { unguard(); } } /** {@inheritDoc} */ @Override public Collection<IgniteCache> getOrCreateCaches(Collection<CacheConfiguration> cacheCfgs) { A.notNull(cacheCfgs, "cacheCfgs"); CU.validateConfigurationCacheNames(cacheCfgs); guard(); try { checkClusterState(); ctx.cache().dynamicStartCaches(cacheCfgs, false, true, false).get(); List<IgniteCache> createdCaches = new ArrayList<>(cacheCfgs.size()); for (CacheConfiguration cacheCfg : cacheCfgs) createdCaches.add(ctx.cache().publicJCache(cacheCfg.getName())); return createdCaches; } catch (IgniteCheckedException e) { throw CU.convertToCacheException(e); } finally { unguard(); } } /** {@inheritDoc} */ @Override public <K, V> IgniteCache<K, V> createCache( CacheConfiguration<K, V> cacheCfg, NearCacheConfiguration<K, V> nearCfg ) { A.notNull(cacheCfg, "cacheCfg"); CU.validateNewCacheName(cacheCfg.getName()); A.notNull(nearCfg, "nearCfg"); guard(); try { checkClusterState(); ctx.cache().dynamicStartCache(cacheCfg, cacheCfg.getName(), nearCfg, true, true, true).get(); return ctx.cache().publicJCache(cacheCfg.getName()); } catch (IgniteCheckedException e) { throw CU.convertToCacheException(e); } finally { unguard(); } } /** {@inheritDoc} */ @Override public <K, V> IgniteCache<K, V> getOrCreateCache(CacheConfiguration<K, V> cacheCfg, NearCacheConfiguration<K, V> nearCfg) { A.notNull(cacheCfg, "cacheCfg"); CU.validateNewCacheName(cacheCfg.getName()); A.notNull(nearCfg, "nearCfg"); guard(); try { checkClusterState(); IgniteInternalCache<Object, Object> cache = ctx.cache().cache(cacheCfg.getName()); if (cache == null) { ctx.cache().dynamicStartCache(cacheCfg, cacheCfg.getName(), nearCfg, false, true, true).get(); } else { if (cache.configuration().getNearConfiguration() == null) { ctx.cache().dynamicStartCache(cacheCfg, cacheCfg.getName(), nearCfg, false, true, true).get(); } } return ctx.cache().publicJCache(cacheCfg.getName()); } catch (IgniteCheckedException e) { throw CU.convertToCacheException(e); } finally { unguard(); } } /** {@inheritDoc} */ @Override public <K, V> IgniteCache<K, V> createNearCache(String cacheName, NearCacheConfiguration<K, V> nearCfg) { CU.validateNewCacheName(cacheName); A.notNull(nearCfg, "nearCfg"); guard(); try { checkClusterState(); ctx.cache().dynamicStartCache(null, cacheName, nearCfg, true, true, true).get(); IgniteCacheProxy<K, V> cache = ctx.cache().publicJCache(cacheName); checkNearCacheStarted(cache); return cache; } catch (IgniteCheckedException e) { throw CU.convertToCacheException(e); } finally { unguard(); } } /** {@inheritDoc} */ @Override public <K, V> IgniteCache<K, V> getOrCreateNearCache(String cacheName, NearCacheConfiguration<K, V> nearCfg) { CU.validateNewCacheName(cacheName); A.notNull(nearCfg, "nearCfg"); guard(); try { checkClusterState(); IgniteInternalCache<Object, Object> internalCache = ctx.cache().cache(cacheName); if (internalCache == null) { ctx.cache().dynamicStartCache(null, cacheName, nearCfg, false, true, true).get(); } else { if (internalCache.configuration().getNearConfiguration() == null) { ctx.cache().dynamicStartCache(null, cacheName, nearCfg, false, true, true).get(); } } IgniteCacheProxy<K, V> cache = ctx.cache().publicJCache(cacheName); checkNearCacheStarted(cache); return cache; } catch (IgniteCheckedException e) { throw CU.convertToCacheException(e); } finally { unguard(); } } /** * @param cache Ignite cache instance to check. * @throws IgniteCheckedException If cache without near cache was already started. */ private void checkNearCacheStarted(IgniteCacheProxy<?, ?> cache) throws IgniteCheckedException { if (!cache.context().isNear()) throw new IgniteCheckedException("Failed to start near cache " + "(a cache with the same name without near cache is already started)"); } /** {@inheritDoc} */ @Override public void destroyCache(String cacheName) { destroyCache0(cacheName, false); } /** {@inheritDoc} */ @Override public boolean destroyCache0(String cacheName, boolean sql) throws CacheException { CU.validateCacheName(cacheName); IgniteInternalFuture<Boolean> stopFut = destroyCacheAsync(cacheName, sql, true); try { return stopFut.get(); } catch (IgniteCheckedException e) { throw CU.convertToCacheException(e); } } /** {@inheritDoc} */ @Override public void destroyCaches(Collection<String> cacheNames) { CU.validateCacheNames(cacheNames); IgniteInternalFuture stopFut = destroyCachesAsync(cacheNames, true); try { stopFut.get(); } catch (IgniteCheckedException e) { throw CU.convertToCacheException(e); } } /** * @param cacheName Cache name. * @param sql If the cache needs to be destroyed only if it was created by SQL {@code CREATE TABLE} command. * @param checkThreadTx If {@code true} checks that current thread does not have active transactions. * @return Ignite future. */ public IgniteInternalFuture<Boolean> destroyCacheAsync(String cacheName, boolean sql, boolean checkThreadTx) { CU.validateCacheName(cacheName); guard(); try { checkClusterState(); return ctx.cache().dynamicDestroyCache(cacheName, sql, checkThreadTx, false, null); } finally { unguard(); } } /** * @param cacheNames Collection of cache names. * @param checkThreadTx If {@code true} checks that current thread does not have active transactions. * @return Ignite future which will be completed when cache is destored. */ public IgniteInternalFuture<?> destroyCachesAsync(Collection<String> cacheNames, boolean checkThreadTx) { CU.validateCacheNames(cacheNames); guard(); try { checkClusterState(); return ctx.cache().dynamicDestroyCaches(cacheNames, checkThreadTx); } finally { unguard(); } } /** {@inheritDoc} */ @Override public <K, V> IgniteCache<K, V> getOrCreateCache(String cacheName) { CU.validateNewCacheName(cacheName); guard(); try { checkClusterState(); IgniteCacheProxy<K, V> cache = ctx.cache().publicJCache(cacheName, false, true); if (cache == null) { ctx.cache().getOrCreateFromTemplate(cacheName, true).get(); return ctx.cache().publicJCache(cacheName); } return cache; } catch (IgniteCheckedException e) { throw CU.convertToCacheException(e); } finally { unguard(); } } /** * @param cacheName Cache name. * @param templateName Template name. * @param cfgOverride Cache config properties to override. * @param checkThreadTx If {@code true} checks that current thread does not have active transactions. * @return Future that will be completed when cache is deployed. */ public IgniteInternalFuture<?> getOrCreateCacheAsync(String cacheName, String templateName, CacheConfigurationOverride cfgOverride, boolean checkThreadTx) { CU.validateNewCacheName(cacheName); guard(); try { checkClusterState(); if (ctx.cache().cache(cacheName) == null) return ctx.cache().getOrCreateFromTemplate(cacheName, templateName, cfgOverride, checkThreadTx); return new GridFinishedFuture<>(); } finally { unguard(); } } /** {@inheritDoc} */ @Override public <K, V> void addCacheConfiguration(CacheConfiguration<K, V> cacheCfg) { A.notNull(cacheCfg, "cacheCfg"); CU.validateNewCacheName(cacheCfg.getName()); guard(); try { checkClusterState(); ctx.cache().addCacheConfiguration(cacheCfg); } catch (IgniteCheckedException e) { throw CU.convertToCacheException(e); } finally { unguard(); } } /** * @return Collection of public cache instances. */ public Collection<IgniteCacheProxy<?, ?>> caches() { guard(); try { checkClusterState(); return ctx.cache().publicCaches(); } finally { unguard(); } } /** {@inheritDoc} */ @Override public Collection<String> cacheNames() { guard(); try { checkClusterState(); return ctx.cache().publicCacheNames(); } finally { unguard(); } } /** {@inheritDoc} */ @Override public <K extends GridCacheUtilityKey, V> IgniteInternalCache<K, V> utilityCache() { guard(); try { checkClusterState(); return ctx.cache().utilityCache(); } finally { unguard(); } } /** {@inheritDoc} */ @Override public <K, V> IgniteInternalCache<K, V> cachex(String name) { CU.validateCacheName(name); guard(); try { checkClusterState(); return ctx.cache().cache(name); } finally { unguard(); } } /** {@inheritDoc} */ @Override public Collection<IgniteInternalCache<?, ?>> cachesx( IgnitePredicate<? super IgniteInternalCache<?, ?>>[] p) { guard(); try { checkClusterState(); return F.retain(ctx.cache().caches(), true, p); } finally { unguard(); } } /** {@inheritDoc} */ @Override public <K, V> IgniteDataStreamer<K, V> dataStreamer(String cacheName) { CU.validateCacheName(cacheName); guard(); try { checkClusterState(); return ctx.<K, V>dataStream().dataStreamer(cacheName); } finally { unguard(); } } /** {@inheritDoc} */ @Override public <T extends IgnitePlugin> T plugin(String name) throws PluginNotFoundException { guard(); try { checkClusterState(); return (T)ctx.pluginProvider(name).plugin(); } finally { unguard(); } } /** {@inheritDoc} */ @Override public IgniteBinary binary() { checkClusterState(); IgniteCacheObjectProcessor objProc = ctx.cacheObjects(); return objProc.binary(); } /** {@inheritDoc} */ @Override public IgniteProductVersion version() { return VER; } /** {@inheritDoc} */ @Override public String latestVersion() { ctx.gateway().readLock(); try { return ctx.cluster().latestVersion(); } finally { ctx.gateway().readUnlock(); } } /** {@inheritDoc} */ @Override public IgniteScheduler scheduler() { return scheduler; } /** {@inheritDoc} */ @Override public void close() throws IgniteException { Ignition.stop(igniteInstanceName, true); } /** {@inheritDoc} */ @Override public <K> Affinity<K> affinity(String cacheName) { CU.validateCacheName(cacheName); checkClusterState(); GridCacheAdapter<K, ?> cache = ctx.cache().internalCache(cacheName); if (cache != null) return cache.affinity(); return ctx.affinity().affinityProxy(cacheName); } /** {@inheritDoc} */ @Override public boolean active() { guard(); try { return context().state().publicApiActiveState(true); } finally { unguard(); } } /** {@inheritDoc} */ @Override public void active(boolean active) { cluster().active(active); } /** */ private Collection<BaselineNode> baselineNodes() { Collection<ClusterNode> srvNodes = cluster().forServers().nodes(); ArrayList baselineNodes = new ArrayList(srvNodes.size()); for (ClusterNode clN : srvNodes) baselineNodes.add(clN); return baselineNodes; } /** {@inheritDoc} */ @Override public void resetLostPartitions(Collection<String> cacheNames) { CU.validateCacheNames(cacheNames); guard(); try { ctx.cache().resetCacheState(cacheNames.isEmpty() ? ctx.cache().cacheNames() : cacheNames).get(); } catch (IgniteCheckedException e) { throw U.convertException(e); } finally { unguard(); } } /** {@inheritDoc} */ @Override public Collection<DataRegionMetrics> dataRegionMetrics() { guard(); try { return ctx.cache().context().database().memoryMetrics(); } finally { unguard(); } } /** {@inheritDoc} */ @Nullable @Override public DataRegionMetrics dataRegionMetrics(String memPlcName) { guard(); try { return ctx.cache().context().database().memoryMetrics(memPlcName); } finally { unguard(); } } /** {@inheritDoc} */ @Override public DataStorageMetrics dataStorageMetrics() { guard(); try { return ctx.cache().context().database().persistentStoreMetrics(); } finally { unguard(); } } /** {@inheritDoc} */ @Override public @NotNull TracingConfigurationManager tracingConfiguration() { guard(); try { return ctx.tracing().configuration(); } finally { unguard(); } } /** {@inheritDoc} */ @Override public IgniteEncryption encryption() { return ctx.encryption(); } /** {@inheritDoc} */ @Override public IgniteSnapshot snapshot() { return ctx.cache().context().snapshotMgr(); } /** {@inheritDoc} */ @Override public Collection<MemoryMetrics> memoryMetrics() { return DataRegionMetricsAdapter.collectionOf(dataRegionMetrics()); } /** {@inheritDoc} */ @Nullable @Override public MemoryMetrics memoryMetrics(String memPlcName) { return DataRegionMetricsAdapter.valueOf(dataRegionMetrics(memPlcName)); } /** {@inheritDoc} */ @Override public PersistenceMetrics persistentStoreMetrics() { return DataStorageMetricsAdapter.valueOf(dataStorageMetrics()); } /** {@inheritDoc} */ @Nullable @Override public IgniteAtomicSequence atomicSequence(String name, long initVal, boolean create) { return atomicSequence(name, null, initVal, create); } /** {@inheritDoc} */ @Nullable @Override public IgniteAtomicSequence atomicSequence(String name, AtomicConfiguration cfg, long initVal, boolean create) throws IgniteException { guard(); try { checkClusterState(); return ctx.dataStructures().sequence(name, cfg, initVal, create); } catch (IgniteCheckedException e) { throw U.convertException(e); } finally { unguard(); } } /** {@inheritDoc} */ @Nullable @Override public IgniteAtomicLong atomicLong(String name, long initVal, boolean create) { return atomicLong(name, null, initVal, create); } /** {@inheritDoc} */ @Nullable @Override public IgniteAtomicLong atomicLong(String name, AtomicConfiguration cfg, long initVal, boolean create) throws IgniteException { guard(); try { checkClusterState(); return ctx.dataStructures().atomicLong(name, cfg, initVal, create); } catch (IgniteCheckedException e) { throw U.convertException(e); } finally { unguard(); } } /** {@inheritDoc} */ @Nullable @Override public <T> IgniteAtomicReference<T> atomicReference( String name, @Nullable T initVal, boolean create ) { return atomicReference(name, null, initVal, create); } /** {@inheritDoc} */ @Override public <T> IgniteAtomicReference<T> atomicReference(String name, AtomicConfiguration cfg, @Nullable T initVal, boolean create) throws IgniteException { guard(); try { checkClusterState(); return ctx.dataStructures().atomicReference(name, cfg, initVal, create); } catch (IgniteCheckedException e) { throw U.convertException(e); } finally { unguard(); } } /** {@inheritDoc} */ @Nullable @Override public <T, S> IgniteAtomicStamped<T, S> atomicStamped(String name, @Nullable T initVal, @Nullable S initStamp, boolean create) { return atomicStamped(name, null, initVal, initStamp, create); } /** {@inheritDoc} */ @Override public <T, S> IgniteAtomicStamped<T, S> atomicStamped(String name, AtomicConfiguration cfg, @Nullable T initVal, @Nullable S initStamp, boolean create) throws IgniteException { guard(); try { checkClusterState(); return ctx.dataStructures().atomicStamped(name, cfg, initVal, initStamp, create); } catch (IgniteCheckedException e) { throw U.convertException(e); } finally { unguard(); } } /** {@inheritDoc} */ @Nullable @Override public IgniteCountDownLatch countDownLatch(String name, int cnt, boolean autoDel, boolean create) { guard(); try { checkClusterState(); return ctx.dataStructures().countDownLatch(name, null, cnt, autoDel, create); } catch (IgniteCheckedException e) { throw U.convertException(e); } finally { unguard(); } } /** {@inheritDoc} */ @Nullable @Override public IgniteSemaphore semaphore( String name, int cnt, boolean failoverSafe, boolean create ) { guard(); try { checkClusterState(); return ctx.dataStructures().semaphore(name, null, cnt, failoverSafe, create); } catch (IgniteCheckedException e) { throw U.convertException(e); } finally { unguard(); } } /** {@inheritDoc} */ @Nullable @Override public IgniteLock reentrantLock( String name, boolean failoverSafe, boolean fair, boolean create ) { guard(); try { checkClusterState(); return ctx.dataStructures().reentrantLock(name, null, failoverSafe, fair, create); } catch (IgniteCheckedException e) { throw U.convertException(e); } finally { unguard(); } } /** {@inheritDoc} */ @Nullable @Override public <T> IgniteQueue<T> queue(String name, int cap, CollectionConfiguration cfg) { guard(); try { checkClusterState(); return ctx.dataStructures().queue(name, null, cap, cfg); } catch (IgniteCheckedException e) { throw U.convertException(e); } finally { unguard(); } } /** {@inheritDoc} */ @Nullable @Override public <T> IgniteSet<T> set(String name, CollectionConfiguration cfg) { guard(); try { checkClusterState(); return ctx.dataStructures().set(name, null, cfg); } catch (IgniteCheckedException e) { throw U.convertException(e); } finally { unguard(); } } /** * The {@code ctx.gateway().readLock()} is used underneath. */ private void guard() { assert ctx != null; ctx.gateway().readLock(); } /** * The {@code ctx.gateway().readUnlock()} is used underneath. */ private void unguard() { assert ctx != null; ctx.gateway().readUnlock(); } /** * Validate operation on cluster. Check current cluster state. * * @throws IgniteException If cluster in inActive state. */ private void checkClusterState() throws IgniteException { if (!ctx.state().publicApiActiveState(true)) { throw new IgniteException("Can not perform the operation because the cluster is inactive. Note, that " + "the cluster is considered inactive by default if Ignite Persistent Store is used to let all the nodes " + "join the cluster. To activate the cluster call Ignite.active(true)."); } } /** * Method is responsible for handling the {@link EventType#EVT_CLIENT_NODE_DISCONNECTED} event. Notify all the * GridComponents that the such even has been occurred (e.g. if the local client node disconnected from the cluster * components will be notified with a future which will be completed when the client is reconnected). */ public void onDisconnected() { Throwable err = null; reconnectState.waitPreviousReconnect(); GridFutureAdapter<?> reconnectFut = ctx.gateway().onDisconnected(); if (reconnectFut == null) { assert ctx.gateway().getState() != STARTED : ctx.gateway().getState(); return; } IgniteFutureImpl<?> curFut = (IgniteFutureImpl<?>)ctx.cluster().get().clientReconnectFuture(); IgniteFuture<?> userFut; // In case of previous reconnect did not finish keep reconnect future. if (curFut != null && curFut.internalFuture() == reconnectFut) userFut = curFut; else { userFut = new IgniteFutureImpl<>(reconnectFut); ctx.cluster().get().clientReconnectFuture(userFut); } ctx.disconnected(true); List<GridComponent> comps = ctx.components(); for (ListIterator<GridComponent> it = comps.listIterator(comps.size()); it.hasPrevious(); ) { GridComponent comp = it.previous(); try { if (!skipDaemon(comp)) comp.onDisconnected(userFut); } catch (IgniteCheckedException e) { err = e; } catch (Throwable e) { err = e; if (e instanceof Error) throw e; } } for (GridCacheContext cctx : ctx.cache().context().cacheContexts()) { cctx.gate().writeLock(); cctx.gate().writeUnlock(); } ctx.gateway().writeLock(); ctx.gateway().writeUnlock(); if (err != null) { reconnectFut.onDone(err); U.error(log, "Failed to reconnect, will stop node", err); close(); } } /** * @param clusterRestarted {@code True} if all cluster nodes restarted while client was disconnected. */ @SuppressWarnings("unchecked") public void onReconnected(final boolean clusterRestarted) { Throwable err = null; try { ctx.disconnected(false); GridCompoundFuture curReconnectFut = reconnectState.curReconnectFut = new GridCompoundFuture<>(); reconnectState.reconnectDone = new GridFutureAdapter<>(); for (GridComponent comp : ctx.components()) { IgniteInternalFuture<?> fut = comp.onReconnected(clusterRestarted); if (fut != null) curReconnectFut.add(fut); } curReconnectFut.add(ctx.cache().context().exchange().reconnectExchangeFuture()); curReconnectFut.markInitialized(); final GridFutureAdapter reconnectDone = reconnectState.reconnectDone; curReconnectFut.listen(new CI1<IgniteInternalFuture<?>>() { @Override public void apply(IgniteInternalFuture<?> fut) { try { Object res = fut.get(); if (res == STOP_RECONNECT) return; ctx.gateway().onReconnected(); reconnectState.firstReconnectFut.onDone(); } catch (IgniteCheckedException e) { if (!X.hasCause(e, IgniteNeedReconnectException.class, IgniteClientDisconnectedCheckedException.class, IgniteInterruptedCheckedException.class)) { U.error(log, "Failed to reconnect, will stop node.", e); reconnectState.firstReconnectFut.onDone(e); new Thread(() -> { U.error(log, "Stopping the node after a failed reconnect attempt."); close(); }, "node-stopper").start(); } else { assert ctx.discovery().reconnectSupported(); U.error(log, "Failed to finish reconnect, will retry [locNodeId=" + ctx.localNodeId() + ", err=" + e.getMessage() + ']'); } } finally { reconnectDone.onDone(); } } }); } catch (IgniteCheckedException e) { err = e; } catch (Throwable e) { err = e; if (e instanceof Error) throw e; } if (err != null) { U.error(log, "Failed to reconnect, will stop node", err); if (!X.hasCause(err, NodeStoppingException.class)) close(); } } /** * Creates optional component. * * @param cls Component interface. * @param ctx Kernal context. * @return Created component. * @throws IgniteCheckedException If failed to create component. */ private static <T extends GridComponent> T createComponent(Class<T> cls, GridKernalContext ctx) throws IgniteCheckedException { assert cls.isInterface() : cls; T comp = ctx.plugins().createComponent(cls); if (comp != null) return comp; if (cls.equals(IgniteCacheObjectProcessor.class)) return (T)new CacheObjectBinaryProcessorImpl(ctx); if (cls.equals(DiscoveryNodeValidationProcessor.class)) return (T)new OsDiscoveryNodeValidationProcessor(ctx); if (cls.equals(IGridClusterStateProcessor.class)) return (T)new GridClusterStateProcessor(ctx); if (cls.equals(GridSecurityProcessor.class)) return null; if (cls.equals(IgniteRestProcessor.class)) return (T)new GridRestProcessor(ctx); Class<T> implCls = null; try { String clsName; // Handle special case for PlatformProcessor if (cls.equals(PlatformProcessor.class)) clsName = ctx.config().getPlatformConfiguration() == null ? PlatformNoopProcessor.class.getName() : cls.getName() + "Impl"; else clsName = componentClassName(cls); implCls = (Class<T>)Class.forName(clsName); } catch (ClassNotFoundException ignore) { // No-op. } if (implCls == null) throw new IgniteCheckedException("Failed to find component implementation: " + cls.getName()); if (!cls.isAssignableFrom(implCls)) throw new IgniteCheckedException("Component implementation does not implement component interface " + "[component=" + cls.getName() + ", implementation=" + implCls.getName() + ']'); Constructor<T> constructor; try { constructor = implCls.getConstructor(GridKernalContext.class); } catch (NoSuchMethodException e) { throw new IgniteCheckedException("Component does not have expected constructor: " + implCls.getName(), e); } try { return constructor.newInstance(ctx); } catch (ReflectiveOperationException e) { throw new IgniteCheckedException("Failed to create component [component=" + cls.getName() + ", implementation=" + implCls.getName() + ']', e); } } /** * @param cls Component interface. * @return Name of component implementation class for open source edition. */ private static String componentClassName(Class<?> cls) { return cls.getPackage().getName() + ".os." + cls.getSimpleName().replace("Grid", "GridOs"); } /** {@inheritDoc} */ @Override public void readExternal(ObjectInput in) throws IOException, ClassNotFoundException { igniteInstanceName = U.readString(in); } /** {@inheritDoc} */ @Override public void writeExternal(ObjectOutput out) throws IOException { U.writeString(out, igniteInstanceName); } /** * @return IgniteKernal instance. * @throws ObjectStreamException If failed. */ protected Object readResolve() throws ObjectStreamException { try { return IgnitionEx.localIgnite(); } catch (IllegalStateException e) { throw U.withCause(new InvalidObjectException(e.getMessage()), e); } } /** * @param comp Grid component. * @return {@code true} if node running in daemon mode and component marked by {@code SkipDaemon} annotation. */ private boolean skipDaemon(GridComponent comp) { return ctx.isDaemon() && U.hasAnnotation(comp.getClass(), SkipDaemon.class); } /** {@inheritDoc} */ @Override public void dumpDebugInfo() { try { GridKernalContextImpl ctx = this.ctx; GridDiscoveryManager discoMrg = ctx != null ? ctx.discovery() : null; ClusterNode locNode = discoMrg != null ? discoMrg.localNode() : null; if (ctx != null && discoMrg != null && locNode != null) { boolean client = ctx.clientNode(); UUID routerId = locNode instanceof TcpDiscoveryNode ? ((TcpDiscoveryNode)locNode).clientRouterNodeId() : null; U.warn(ctx.cluster().diagnosticLog(), "Dumping debug info for node [id=" + locNode.id() + ", name=" + ctx.igniteInstanceName() + ", order=" + locNode.order() + ", topVer=" + discoMrg.topologyVersion() + ", client=" + client + (client && routerId != null ? ", routerId=" + routerId : "") + ']'); ctx.cache().context().exchange().dumpDebugInfo(null); } else U.warn(log, "Dumping debug info for node, context is not initialized [name=" + igniteInstanceName + ']'); } catch (Exception e) { U.error(log, "Failed to dump debug info for node: " + e, e); } } /** * @param node Node. * @param payload Message payload. * @param procFromNioThread If {@code true} message is processed from NIO thread. * @return Response future. */ public IgniteInternalFuture sendIoTest(ClusterNode node, byte[] payload, boolean procFromNioThread) { return ctx.io().sendIoTest(node, payload, procFromNioThread); } /** * @param nodes Nodes. * @param payload Message payload. * @param procFromNioThread If {@code true} message is processed from NIO thread. * @return Response future. */ public IgniteInternalFuture sendIoTest(List<ClusterNode> nodes, byte[] payload, boolean procFromNioThread) { return ctx.io().sendIoTest(nodes, payload, procFromNioThread); } /** * Registers metrics. */ private void registerMetrics() { if (!ctx.metric().enabled()) return; MetricRegistry reg = ctx.metric().registry(GridMetricManager.IGNITE_METRICS); reg.register("fullVersion", this::getFullVersion, String.class, FULL_VER_DESC); reg.register("copyright", this::getCopyright, String.class, COPYRIGHT_DESC); reg.register("startTimestampFormatted", this::getStartTimestampFormatted, String.class, START_TIMESTAMP_FORMATTED_DESC); reg.register("isRebalanceEnabled", this::isRebalanceEnabled, IS_REBALANCE_ENABLED_DESC); reg.register("uptimeFormatted", this::getUpTimeFormatted, String.class, UPTIME_FORMATTED_DESC); reg.register("startTimestamp", this::getStartTimestamp, START_TIMESTAMP_DESC); reg.register("uptime", this::getUpTime, UPTIME_DESC); reg.register("osInformation", this::getOsInformation, String.class, OS_INFO_DESC); reg.register("jdkInformation", this::getJdkInformation, String.class, JDK_INFO_DESC); reg.register("osUser", this::getOsUser, String.class, OS_USER_DESC); reg.register("vmName", this::getVmName, String.class, VM_NAME_DESC); reg.register("instanceName", this::getInstanceName, String.class, INSTANCE_NAME_DESC); reg.register("currentCoordinatorFormatted", this::getCurrentCoordinatorFormatted, String.class, CUR_COORDINATOR_FORMATTED_DESC); reg.register("isNodeInBaseline", this::isNodeInBaseline, IS_NODE_BASELINE_DESC); reg.register("longJVMPausesCount", this::getLongJVMPausesCount, LONG_JVM_PAUSES_CNT_DESC); reg.register("longJVMPausesTotalDuration", this::getLongJVMPausesTotalDuration, LONG_JVM_PAUSES_TOTAL_DURATION_DESC); reg.register("longJVMPauseLastEvents", this::getLongJVMPauseLastEvents, Map.class, LONG_JVM_PAUSE_LAST_EVENTS_DESC); reg.register("active", () -> ctx.state().clusterState().state().active(), Boolean.class, ACTIVE_DESC); reg.register("clusterState", this::clusterState, String.class, CLUSTER_STATE_DESC); reg.register("lastClusterStateChangeTime", this::lastClusterStateChangeTime, LAST_CLUSTER_STATE_CHANGE_TIME_DESC); reg.register("userAttributesFormatted", this::getUserAttributesFormatted, List.class, USER_ATTRS_FORMATTED_DESC); reg.register("gridLoggerFormatted", this::getGridLoggerFormatted, String.class, GRID_LOG_FORMATTED_DESC); reg.register("executorServiceFormatted", this::getExecutorServiceFormatted, String.class, EXECUTOR_SRVC_FORMATTED_DESC); reg.register("igniteHome", this::getIgniteHome, String.class, IGNITE_HOME_DESC); reg.register("mBeanServerFormatted", this::getMBeanServerFormatted, String.class, MBEAN_SERVER_FORMATTED_DESC); reg.register("localNodeId", this::getLocalNodeId, UUID.class, LOC_NODE_ID_DESC); reg.register("isPeerClassLoadingEnabled", this::isPeerClassLoadingEnabled, Boolean.class, IS_PEER_CLS_LOADING_ENABLED_DESC); reg.register("lifecycleBeansFormatted", this::getLifecycleBeansFormatted, List.class, LIFECYCLE_BEANS_FORMATTED_DESC); reg.register("discoverySpiFormatted", this::getDiscoverySpiFormatted, String.class, DISCOVERY_SPI_FORMATTED_DESC); reg.register("communicationSpiFormatted", this::getCommunicationSpiFormatted, String.class, COMMUNICATION_SPI_FORMATTED_DESC); reg.register("deploymentSpiFormatted", this::getDeploymentSpiFormatted, String.class, DEPLOYMENT_SPI_FORMATTED_DESC); reg.register("checkpointSpiFormatted", this::getCheckpointSpiFormatted, String.class, CHECKPOINT_SPI_FORMATTED_DESC); reg.register("collisionSpiFormatted", this::getCollisionSpiFormatted, String.class, COLLISION_SPI_FORMATTED_DESC); reg.register("eventStorageSpiFormatted", this::getEventStorageSpiFormatted, String.class, EVT_STORAGE_SPI_FORMATTED_DESC); reg.register("failoverSpiFormatted", this::getFailoverSpiFormatted, String.class, FAILOVER_SPI_FORMATTED_DESC); reg.register("loadBalancingSpiFormatted", this::getLoadBalancingSpiFormatted, String.class, LOAD_BALANCING_SPI_FORMATTED_DESC); } /** * Class holds client reconnection event handling state. */ private class ReconnectState { /** Future will be completed when the client node connected the first time. */ private final GridFutureAdapter firstReconnectFut = new GridFutureAdapter(); /** * Composed future of all {@link GridComponent#onReconnected(boolean)} callbacks. * The future completes when all Ignite components are finished handle given client reconnect event. */ private GridCompoundFuture<?, Object> curReconnectFut; /** Future completes when reconnection handling is done (doesn't matter successfully or not). */ private GridFutureAdapter<?> reconnectDone; /** * @throws IgniteCheckedException If failed. */ void waitFirstReconnect() throws IgniteCheckedException { firstReconnectFut.get(); } /** * Wait for the previous reconnection handling finished or force completion if not. */ void waitPreviousReconnect() { if (curReconnectFut != null && !curReconnectFut.isDone()) { assert reconnectDone != null; curReconnectFut.onDone(STOP_RECONNECT); try { reconnectDone.get(); } catch (IgniteCheckedException ignore) { // No-op. } } } /** {@inheritDoc} */ @Override public String toString() { return S.toString(ReconnectState.class, this); } } /** {@inheritDoc} */ @Override public void runIoTest( long warmup, long duration, int threads, long maxLatency, int rangesCnt, int payLoadSize, boolean procFromNioThread ) { ctx.io().runIoTest(warmup, duration, threads, maxLatency, rangesCnt, payLoadSize, procFromNioThread, new ArrayList(ctx.cluster().get().forServers().forRemotes().nodes())); } /** {@inheritDoc} */ @Override public void clearNodeLocalMap() { ctx.cluster().get().clearNodeMap(); } /** {@inheritDoc} */ @Override public void clusterState(String state) { ClusterState newState = ClusterState.valueOf(state); cluster().state(newState); } /** {@inheritDoc} */ @Override public String toString() { return S.toString(IgniteKernal.class, this); } }
modules/core/src/main/java/org/apache/ignite/internal/IgniteKernal.java
/* * 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. */ package org.apache.ignite.internal; import java.io.Externalizable; import java.io.File; import java.io.IOException; import java.io.InputStream; import java.io.InvalidObjectException; import java.io.ObjectInput; import java.io.ObjectOutput; import java.io.ObjectStreamException; import java.io.Serializable; import java.io.UncheckedIOException; import java.lang.management.ManagementFactory; import java.lang.management.RuntimeMXBean; import java.lang.reflect.Constructor; import java.nio.charset.Charset; import java.nio.file.DirectoryStream; import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.Paths; import java.text.DateFormat; import java.text.DecimalFormat; import java.text.DecimalFormatSymbols; import java.util.ArrayList; import java.util.Arrays; import java.util.Collection; import java.util.Collections; import java.util.Date; import java.util.HashMap; import java.util.List; import java.util.ListIterator; import java.util.Locale; import java.util.Map; import java.util.Properties; import java.util.UUID; import java.util.concurrent.ExecutorService; import java.util.concurrent.ThreadPoolExecutor; import java.util.concurrent.atomic.AtomicBoolean; import java.util.concurrent.atomic.AtomicReference; import javax.cache.CacheException; import javax.management.JMException; import org.apache.ignite.DataRegionMetrics; import org.apache.ignite.DataRegionMetricsAdapter; import org.apache.ignite.DataStorageMetrics; import org.apache.ignite.DataStorageMetricsAdapter; import org.apache.ignite.Ignite; import org.apache.ignite.IgniteAtomicLong; import org.apache.ignite.IgniteAtomicReference; import org.apache.ignite.IgniteAtomicSequence; import org.apache.ignite.IgniteAtomicStamped; import org.apache.ignite.IgniteBinary; import org.apache.ignite.IgniteCache; import org.apache.ignite.IgniteCheckedException; import org.apache.ignite.IgniteClientDisconnectedException; import org.apache.ignite.IgniteCompute; import org.apache.ignite.IgniteCountDownLatch; import org.apache.ignite.IgniteDataStreamer; import org.apache.ignite.IgniteEncryption; import org.apache.ignite.IgniteEvents; import org.apache.ignite.IgniteException; import org.apache.ignite.IgniteLock; import org.apache.ignite.IgniteLogger; import org.apache.ignite.IgniteMessaging; import org.apache.ignite.IgniteQueue; import org.apache.ignite.IgniteScheduler; import org.apache.ignite.IgniteSemaphore; import org.apache.ignite.IgniteServices; import org.apache.ignite.IgniteSet; import org.apache.ignite.IgniteSnapshot; import org.apache.ignite.IgniteSystemProperties; import org.apache.ignite.IgniteTransactions; import org.apache.ignite.Ignition; import org.apache.ignite.MemoryMetrics; import org.apache.ignite.PersistenceMetrics; import org.apache.ignite.cache.affinity.Affinity; import org.apache.ignite.cluster.BaselineNode; import org.apache.ignite.cluster.ClusterGroup; import org.apache.ignite.cluster.ClusterMetrics; import org.apache.ignite.cluster.ClusterNode; import org.apache.ignite.cluster.ClusterState; import org.apache.ignite.compute.ComputeJob; import org.apache.ignite.configuration.AtomicConfiguration; import org.apache.ignite.configuration.BinaryConfiguration; import org.apache.ignite.configuration.CacheConfiguration; import org.apache.ignite.configuration.CollectionConfiguration; import org.apache.ignite.configuration.DataRegionConfiguration; import org.apache.ignite.configuration.DataStorageConfiguration; import org.apache.ignite.configuration.IgniteConfiguration; import org.apache.ignite.configuration.MemoryConfiguration; import org.apache.ignite.configuration.NearCacheConfiguration; import org.apache.ignite.events.EventType; import org.apache.ignite.internal.binary.BinaryEnumCache; import org.apache.ignite.internal.binary.BinaryMarshaller; import org.apache.ignite.internal.binary.BinaryUtils; import org.apache.ignite.internal.cluster.ClusterGroupAdapter; import org.apache.ignite.internal.cluster.IgniteClusterEx; import org.apache.ignite.internal.maintenance.MaintenanceProcessor; import org.apache.ignite.internal.managers.GridManager; import org.apache.ignite.internal.managers.IgniteMBeansManager; import org.apache.ignite.internal.managers.checkpoint.GridCheckpointManager; import org.apache.ignite.internal.managers.collision.GridCollisionManager; import org.apache.ignite.internal.managers.communication.GridIoManager; import org.apache.ignite.internal.managers.deployment.GridDeploymentManager; import org.apache.ignite.internal.managers.discovery.DiscoveryLocalJoinData; import org.apache.ignite.internal.managers.discovery.GridDiscoveryManager; import org.apache.ignite.internal.managers.encryption.GridEncryptionManager; import org.apache.ignite.internal.managers.eventstorage.GridEventStorageManager; import org.apache.ignite.internal.managers.failover.GridFailoverManager; import org.apache.ignite.internal.managers.indexing.GridIndexingManager; import org.apache.ignite.internal.managers.loadbalancer.GridLoadBalancerManager; import org.apache.ignite.internal.managers.systemview.GridSystemViewManager; import org.apache.ignite.internal.managers.tracing.GridTracingManager; import org.apache.ignite.internal.marshaller.optimized.OptimizedMarshaller; import org.apache.ignite.internal.processors.GridProcessor; import org.apache.ignite.internal.processors.GridProcessorAdapter; import org.apache.ignite.internal.processors.affinity.AffinityTopologyVersion; import org.apache.ignite.internal.processors.affinity.GridAffinityProcessor; import org.apache.ignite.internal.processors.authentication.IgniteAuthenticationProcessor; import org.apache.ignite.internal.processors.cache.CacheConfigurationOverride; import org.apache.ignite.internal.processors.cache.GridCacheAdapter; import org.apache.ignite.internal.processors.cache.GridCacheContext; import org.apache.ignite.internal.processors.cache.GridCacheProcessor; import org.apache.ignite.internal.processors.cache.GridCacheUtilityKey; import org.apache.ignite.internal.processors.cache.IgniteCacheProxy; import org.apache.ignite.internal.processors.cache.IgniteInternalCache; import org.apache.ignite.internal.processors.cache.binary.CacheObjectBinaryProcessorImpl; import org.apache.ignite.internal.processors.cache.mvcc.MvccProcessorImpl; import org.apache.ignite.internal.processors.cache.persistence.DataRegion; import org.apache.ignite.internal.processors.cache.persistence.IgniteCacheDatabaseSharedManager; import org.apache.ignite.internal.processors.cache.persistence.filename.PdsConsistentIdProcessor; import org.apache.ignite.internal.processors.cacheobject.IgniteCacheObjectProcessor; import org.apache.ignite.internal.processors.closure.GridClosureProcessor; import org.apache.ignite.internal.processors.cluster.ClusterProcessor; import org.apache.ignite.internal.processors.cluster.DiscoveryDataClusterState; import org.apache.ignite.internal.processors.cluster.GridClusterStateProcessor; import org.apache.ignite.internal.processors.cluster.IGridClusterStateProcessor; import org.apache.ignite.internal.processors.configuration.distributed.DistributedConfigurationProcessor; import org.apache.ignite.internal.processors.continuous.GridContinuousProcessor; import org.apache.ignite.internal.processors.datastreamer.DataStreamProcessor; import org.apache.ignite.internal.processors.datastructures.DataStructuresProcessor; import org.apache.ignite.internal.processors.diagnostic.DiagnosticProcessor; import org.apache.ignite.internal.processors.failure.FailureProcessor; import org.apache.ignite.internal.processors.job.GridJobProcessor; import org.apache.ignite.internal.processors.jobmetrics.GridJobMetricsProcessor; import org.apache.ignite.internal.processors.localtask.DurableBackgroundTasksProcessor; import org.apache.ignite.internal.processors.marshaller.GridMarshallerMappingProcessor; import org.apache.ignite.internal.processors.metastorage.persistence.DistributedMetaStorageImpl; import org.apache.ignite.internal.processors.metric.GridMetricManager; import org.apache.ignite.internal.processors.metric.MetricRegistry; import org.apache.ignite.internal.processors.nodevalidation.DiscoveryNodeValidationProcessor; import org.apache.ignite.internal.processors.nodevalidation.OsDiscoveryNodeValidationProcessor; import org.apache.ignite.internal.processors.odbc.ClientListenerProcessor; import org.apache.ignite.internal.processors.platform.PlatformNoopProcessor; import org.apache.ignite.internal.processors.platform.PlatformProcessor; import org.apache.ignite.internal.processors.platform.plugin.PlatformPluginProcessor; import org.apache.ignite.internal.processors.plugin.IgnitePluginProcessor; import org.apache.ignite.internal.processors.pool.PoolProcessor; import org.apache.ignite.internal.processors.port.GridPortProcessor; import org.apache.ignite.internal.processors.port.GridPortRecord; import org.apache.ignite.internal.processors.query.GridQueryProcessor; import org.apache.ignite.internal.processors.resource.GridResourceProcessor; import org.apache.ignite.internal.processors.resource.GridSpringResourceContext; import org.apache.ignite.internal.processors.rest.GridRestProcessor; import org.apache.ignite.internal.processors.rest.IgniteRestProcessor; import org.apache.ignite.internal.processors.security.GridSecurityProcessor; import org.apache.ignite.internal.processors.security.IgniteSecurity; import org.apache.ignite.internal.processors.security.IgniteSecurityProcessor; import org.apache.ignite.internal.processors.security.NoOpIgniteSecurityProcessor; import org.apache.ignite.internal.processors.segmentation.GridSegmentationProcessor; import org.apache.ignite.internal.processors.service.GridServiceProcessor; import org.apache.ignite.internal.processors.service.IgniteServiceProcessor; import org.apache.ignite.internal.processors.session.GridTaskSessionProcessor; import org.apache.ignite.internal.processors.subscription.GridInternalSubscriptionProcessor; import org.apache.ignite.internal.processors.task.GridTaskProcessor; import org.apache.ignite.internal.processors.timeout.GridTimeoutProcessor; import org.apache.ignite.internal.suggestions.GridPerformanceSuggestions; import org.apache.ignite.internal.suggestions.JvmConfigurationSuggestions; import org.apache.ignite.internal.suggestions.OsConfigurationSuggestions; import org.apache.ignite.internal.util.StripedExecutor; import org.apache.ignite.internal.util.TimeBag; import org.apache.ignite.internal.util.future.GridCompoundFuture; import org.apache.ignite.internal.util.future.GridFinishedFuture; import org.apache.ignite.internal.util.future.GridFutureAdapter; import org.apache.ignite.internal.util.future.IgniteFutureImpl; import org.apache.ignite.internal.util.lang.GridAbsClosure; import org.apache.ignite.internal.util.tostring.GridToStringExclude; import org.apache.ignite.internal.util.typedef.C1; import org.apache.ignite.internal.util.typedef.CI1; import org.apache.ignite.internal.util.typedef.F; import org.apache.ignite.internal.util.typedef.X; import org.apache.ignite.internal.util.typedef.internal.A; import org.apache.ignite.internal.util.typedef.internal.CU; import org.apache.ignite.internal.util.typedef.internal.LT; import org.apache.ignite.internal.util.typedef.internal.S; import org.apache.ignite.internal.util.typedef.internal.SB; import org.apache.ignite.internal.util.typedef.internal.U; import org.apache.ignite.internal.worker.WorkersRegistry; import org.apache.ignite.lang.IgniteBiTuple; import org.apache.ignite.lang.IgniteFuture; import org.apache.ignite.lang.IgnitePredicate; import org.apache.ignite.lang.IgniteProductVersion; import org.apache.ignite.lifecycle.LifecycleAware; import org.apache.ignite.lifecycle.LifecycleBean; import org.apache.ignite.lifecycle.LifecycleEventType; import org.apache.ignite.marshaller.MarshallerExclusions; import org.apache.ignite.marshaller.MarshallerUtils; import org.apache.ignite.marshaller.jdk.JdkMarshaller; import org.apache.ignite.mxbean.IgniteMXBean; import org.apache.ignite.plugin.IgnitePlugin; import org.apache.ignite.plugin.PluginNotFoundException; import org.apache.ignite.plugin.PluginProvider; import org.apache.ignite.spi.IgniteSpi; import org.apache.ignite.spi.IgniteSpiVersionCheckException; import org.apache.ignite.spi.communication.tcp.TcpCommunicationSpi; import org.apache.ignite.spi.discovery.isolated.IsolatedDiscoverySpi; import org.apache.ignite.spi.discovery.tcp.internal.TcpDiscoveryNode; import org.apache.ignite.spi.tracing.TracingConfigurationManager; import org.apache.ignite.thread.IgniteStripedThreadPoolExecutor; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import static org.apache.ignite.IgniteSystemProperties.IGNITE_BINARY_MARSHALLER_USE_STRING_SERIALIZATION_VER_2; import static org.apache.ignite.IgniteSystemProperties.IGNITE_CONFIG_URL; import static org.apache.ignite.IgniteSystemProperties.IGNITE_DAEMON; import static org.apache.ignite.IgniteSystemProperties.IGNITE_EVENT_DRIVEN_SERVICE_PROCESSOR_ENABLED; import static org.apache.ignite.IgniteSystemProperties.IGNITE_LOG_CLASSPATH_CONTENT_ON_STARTUP; import static org.apache.ignite.IgniteSystemProperties.IGNITE_NO_ASCII; import static org.apache.ignite.IgniteSystemProperties.IGNITE_OPTIMIZED_MARSHALLER_USE_DEFAULT_SUID; import static org.apache.ignite.IgniteSystemProperties.IGNITE_REST_START_ON_CLIENT; import static org.apache.ignite.IgniteSystemProperties.IGNITE_SKIP_CONFIGURATION_CONSISTENCY_CHECK; import static org.apache.ignite.IgniteSystemProperties.IGNITE_STARVATION_CHECK_INTERVAL; import static org.apache.ignite.IgniteSystemProperties.IGNITE_SUCCESS_FILE; import static org.apache.ignite.IgniteSystemProperties.getBoolean; import static org.apache.ignite.internal.GridKernalState.DISCONNECTED; import static org.apache.ignite.internal.GridKernalState.STARTED; import static org.apache.ignite.internal.GridKernalState.STARTING; import static org.apache.ignite.internal.GridKernalState.STOPPED; import static org.apache.ignite.internal.GridKernalState.STOPPING; import static org.apache.ignite.internal.IgniteComponentType.COMPRESSION; import static org.apache.ignite.internal.IgniteComponentType.SCHEDULE; import static org.apache.ignite.internal.IgniteNodeAttributes.ATTR_BUILD_DATE; import static org.apache.ignite.internal.IgniteNodeAttributes.ATTR_BUILD_VER; import static org.apache.ignite.internal.IgniteNodeAttributes.ATTR_CLIENT_MODE; import static org.apache.ignite.internal.IgniteNodeAttributes.ATTR_CONSISTENCY_CHECK_SKIPPED; import static org.apache.ignite.internal.IgniteNodeAttributes.ATTR_DAEMON; import static org.apache.ignite.internal.IgniteNodeAttributes.ATTR_DATA_STORAGE_CONFIG; import static org.apache.ignite.internal.IgniteNodeAttributes.ATTR_DATA_STREAMER_POOL_SIZE; import static org.apache.ignite.internal.IgniteNodeAttributes.ATTR_DEPLOYMENT_MODE; import static org.apache.ignite.internal.IgniteNodeAttributes.ATTR_DYNAMIC_CACHE_START_ROLLBACK_SUPPORTED; import static org.apache.ignite.internal.IgniteNodeAttributes.ATTR_EVENT_DRIVEN_SERVICE_PROCESSOR_ENABLED; import static org.apache.ignite.internal.IgniteNodeAttributes.ATTR_IGNITE_FEATURES; import static org.apache.ignite.internal.IgniteNodeAttributes.ATTR_IGNITE_INSTANCE_NAME; import static org.apache.ignite.internal.IgniteNodeAttributes.ATTR_IPS; import static org.apache.ignite.internal.IgniteNodeAttributes.ATTR_JIT_NAME; import static org.apache.ignite.internal.IgniteNodeAttributes.ATTR_JMX_PORT; import static org.apache.ignite.internal.IgniteNodeAttributes.ATTR_JVM_ARGS; import static org.apache.ignite.internal.IgniteNodeAttributes.ATTR_JVM_PID; import static org.apache.ignite.internal.IgniteNodeAttributes.ATTR_LANG_RUNTIME; import static org.apache.ignite.internal.IgniteNodeAttributes.ATTR_LATE_AFFINITY_ASSIGNMENT; import static org.apache.ignite.internal.IgniteNodeAttributes.ATTR_MACS; import static org.apache.ignite.internal.IgniteNodeAttributes.ATTR_MARSHALLER; import static org.apache.ignite.internal.IgniteNodeAttributes.ATTR_MARSHALLER_COMPACT_FOOTER; import static org.apache.ignite.internal.IgniteNodeAttributes.ATTR_MARSHALLER_USE_BINARY_STRING_SER_VER_2; import static org.apache.ignite.internal.IgniteNodeAttributes.ATTR_MARSHALLER_USE_DFLT_SUID; import static org.apache.ignite.internal.IgniteNodeAttributes.ATTR_MEMORY_CONFIG; import static org.apache.ignite.internal.IgniteNodeAttributes.ATTR_NODE_CONSISTENT_ID; import static org.apache.ignite.internal.IgniteNodeAttributes.ATTR_OFFHEAP_SIZE; import static org.apache.ignite.internal.IgniteNodeAttributes.ATTR_PEER_CLASSLOADING; import static org.apache.ignite.internal.IgniteNodeAttributes.ATTR_PHY_RAM; import static org.apache.ignite.internal.IgniteNodeAttributes.ATTR_PREFIX; import static org.apache.ignite.internal.IgniteNodeAttributes.ATTR_REBALANCE_POOL_SIZE; import static org.apache.ignite.internal.IgniteNodeAttributes.ATTR_RESTART_ENABLED; import static org.apache.ignite.internal.IgniteNodeAttributes.ATTR_REST_PORT_RANGE; import static org.apache.ignite.internal.IgniteNodeAttributes.ATTR_SHUTDOWN_POLICY; import static org.apache.ignite.internal.IgniteNodeAttributes.ATTR_SPI_CLASS; import static org.apache.ignite.internal.IgniteNodeAttributes.ATTR_TX_CONFIG; import static org.apache.ignite.internal.IgniteNodeAttributes.ATTR_USER_NAME; import static org.apache.ignite.internal.IgniteNodeAttributes.ATTR_VALIDATE_CACHE_REQUESTS; import static org.apache.ignite.internal.IgniteVersionUtils.ACK_VER_STR; import static org.apache.ignite.internal.IgniteVersionUtils.BUILD_TSTAMP_STR; import static org.apache.ignite.internal.IgniteVersionUtils.COPYRIGHT; import static org.apache.ignite.internal.IgniteVersionUtils.REV_HASH_STR; import static org.apache.ignite.internal.IgniteVersionUtils.VER; import static org.apache.ignite.internal.IgniteVersionUtils.VER_STR; import static org.apache.ignite.internal.processors.cache.persistence.IgniteCacheDatabaseSharedManager.INTERNAL_DATA_REGION_NAMES; import static org.apache.ignite.lifecycle.LifecycleEventType.AFTER_NODE_START; import static org.apache.ignite.lifecycle.LifecycleEventType.BEFORE_NODE_START; /** * This class represents an implementation of the main Ignite API {@link Ignite} which is expanded by additional * methods of {@link IgniteEx} for the internal Ignite needs. It also controls the Ignite life cycle, checks * thread pools state for starvation, detects long JVM pauses and prints out the local node metrics. * <p> * Please, refer to the wiki <a href="http://en.wikipedia.org/wiki/Kernal">http://en.wikipedia.org/wiki/Kernal</a> * for the information on the misspelling. * <p> * <h3>Starting</h3> * The main entry point for all the Ignite instances creation is the method - {@link #start}. * <p> * It starts internal Ignite components (see {@link GridComponent}), for instance: * <ul> * <li>{@link GridManager} - a layer of indirection between kernal and SPI modules.</li> * <li>{@link GridProcessor} - an objects responsible for particular internal process implementation.</li> * <li>{@link IgnitePlugin} - an Ignite addition of user-provided functionality.</li> * </ul> * The {@code start} method also performs additional validation of the provided {@link IgniteConfiguration} and * prints some suggestions such as: * <ul> * <li>Ignite configuration optimizations (e.g. disabling {@link EventType} events).</li> * <li>{@link JvmConfigurationSuggestions} optimizations.</li> * <li>{@link OsConfigurationSuggestions} optimizations.</li> * </ul> * <h3>Stopping</h3> * To stop Ignite instance the {@link #stop(boolean)} method is used. The {@code cancel} argument of this method is used: * <ul> * <li>With {@code true} value. To interrupt all currently acitve {@link GridComponent}s related to the Ignite node. * For instance, {@link ComputeJob} will be interrupted by calling {@link ComputeJob#cancel()} method. Note that just * like with {@link Thread#interrupt()}, it is up to the actual job to exit from execution.</li> * <li>With {@code false} value. To stop the Ignite node gracefully. All jobs currently running will not be interrupted. * The Ignite node will wait for the completion of all {@link GridComponent}s running on it before stopping. * </li> * </ul> */ public class IgniteKernal implements IgniteEx, IgniteMXBean, Externalizable { /** Class serialization version number. */ private static final long serialVersionUID = 0L; /** Ignite web-site that is shown in log messages. */ public static final String SITE = "ignite.apache.org"; /** System line separator. */ private static final String NL = U.nl(); /** System megabyte. */ private static final int MEGABYTE = 1024 * 1024; /** * Default interval of checking thread pool state for the starvation. Will be used only if the * {@link IgniteSystemProperties#IGNITE_STARVATION_CHECK_INTERVAL} system property is not set. * <p> * Value is {@code 30 sec}. */ public static final long DFLT_PERIODIC_STARVATION_CHECK_FREQ = 1000 * 30; /** Object is used to force completion the previous reconnection attempt. See {@link ReconnectState} for details. */ private static final Object STOP_RECONNECT = new Object(); /** The separator is used for coordinator properties formatted as a string. */ public static final String COORDINATOR_PROPERTIES_SEPARATOR = ","; /** * Default timeout in milliseconds for dumping long running operations. Will be used if the * {@link IgniteSystemProperties#IGNITE_LONG_OPERATIONS_DUMP_TIMEOUT} is not set. * <p> * Value is {@code 60 sec}. */ public static final long DFLT_LONG_OPERATIONS_DUMP_TIMEOUT = 60_000L; /** @see IgniteSystemProperties#IGNITE_EVENT_DRIVEN_SERVICE_PROCESSOR_ENABLED */ public static final boolean DFLT_EVENT_DRIVEN_SERVICE_PROCESSOR_ENABLED = true; /** @see IgniteSystemProperties#IGNITE_LOG_CLASSPATH_CONTENT_ON_STARTUP */ public static final boolean DFLT_LOG_CLASSPATH_CONTENT_ON_STARTUP = true; /** Currently used instance of JVM pause detector thread. See {@link LongJVMPauseDetector} for details. */ private LongJVMPauseDetector longJVMPauseDetector; /** The main kernal context which holds all the {@link GridComponent}s. */ @GridToStringExclude private GridKernalContextImpl ctx; /** Helper which registers and unregisters MBeans. */ @GridToStringExclude private IgniteMBeansManager mBeansMgr; /** Ignite configuration instance. */ private IgniteConfiguration cfg; /** Ignite logger instance which enriches log messages with the node instance name and the node id. */ @GridToStringExclude private GridLoggerProxy log; /** Name of Ignite node. */ private String igniteInstanceName; /** Kernal start timestamp. */ private long startTime = U.currentTimeMillis(); /** Spring context, potentially {@code null}. */ private GridSpringResourceContext rsrcCtx; /** * The instance of scheduled thread pool starvation checker. {@code null} if starvation checks have been * disabled by the value of {@link IgniteSystemProperties#IGNITE_STARVATION_CHECK_INTERVAL} system property. */ @GridToStringExclude private GridTimeoutProcessor.CancelableTask starveTask; /** * The instance of scheduled metrics logger. {@code null} means that the metrics loggin have been disabled * by configuration. See {@link IgniteConfiguration#getMetricsLogFrequency()} for details. */ @GridToStringExclude private GridTimeoutProcessor.CancelableTask metricsLogTask; /** {@code true} if an error occurs at Ignite instance stop. */ @GridToStringExclude private boolean errOnStop; /** An instance of the scheduler which provides functionality for scheduling jobs locally. */ @GridToStringExclude private IgniteScheduler scheduler; /** The kernal state guard. See {@link GridKernalGateway} for details. */ @GridToStringExclude private final AtomicReference<GridKernalGateway> gw = new AtomicReference<>(); /** Flag indicates that the ignite instance is scheduled to be stopped. */ @GridToStringExclude private final AtomicBoolean stopGuard = new AtomicBoolean(); /** The state object is used when reconnection occurs. See {@link IgniteKernal#onReconnected(boolean)}. */ private final ReconnectState reconnectState = new ReconnectState(); /** * No-arg constructor is required by externalization. */ public IgniteKernal() { this(null); } /** * @param rsrcCtx Optional Spring application context. */ public IgniteKernal(@Nullable GridSpringResourceContext rsrcCtx) { this.rsrcCtx = rsrcCtx; } /** {@inheritDoc} */ @Override public IgniteClusterEx cluster() { return ctx.cluster().get(); } /** {@inheritDoc} */ @Override public ClusterNode localNode() { return ctx.cluster().get().localNode(); } /** {@inheritDoc} */ @Override public IgniteCompute compute() { return ((ClusterGroupAdapter)ctx.cluster().get().forServers()).compute(); } /** {@inheritDoc} */ @Override public IgniteMessaging message() { return ctx.cluster().get().message(); } /** {@inheritDoc} */ @Override public IgniteEvents events() { return ctx.cluster().get().events(); } /** {@inheritDoc} */ @Override public IgniteServices services() { checkClusterState(); return ((ClusterGroupAdapter)ctx.cluster().get().forServers()).services(); } /** {@inheritDoc} */ @Override public ExecutorService executorService() { return ctx.cluster().get().executorService(); } /** {@inheritDoc} */ @Override public final IgniteCompute compute(ClusterGroup grp) { return ((ClusterGroupAdapter)grp).compute(); } /** {@inheritDoc} */ @Override public final IgniteMessaging message(ClusterGroup prj) { return ((ClusterGroupAdapter)prj).message(); } /** {@inheritDoc} */ @Override public final IgniteEvents events(ClusterGroup grp) { return ((ClusterGroupAdapter)grp).events(); } /** {@inheritDoc} */ @Override public IgniteServices services(ClusterGroup grp) { checkClusterState(); return ((ClusterGroupAdapter)grp).services(); } /** {@inheritDoc} */ @Override public ExecutorService executorService(ClusterGroup grp) { return ((ClusterGroupAdapter)grp).executorService(); } /** {@inheritDoc} */ @Override public String name() { return igniteInstanceName; } /** {@inheritDoc} */ @Override public String getCopyright() { return COPYRIGHT; } /** {@inheritDoc} */ @Override public long getStartTimestamp() { return startTime; } /** {@inheritDoc} */ @Override public String getStartTimestampFormatted() { return DateFormat.getDateTimeInstance().format(new Date(startTime)); } /** {@inheritDoc} */ @Override public boolean isRebalanceEnabled() { return ctx.cache().context().isRebalanceEnabled(); } /** {@inheritDoc} */ @Override public void rebalanceEnabled(boolean rebalanceEnabled) { ctx.cache().context().rebalanceEnabled(rebalanceEnabled); } /** {@inheritDoc} */ @Override public long getUpTime() { return U.currentTimeMillis() - startTime; } /** {@inheritDoc} */ @Override public long getLongJVMPausesCount() { return longJVMPauseDetector != null ? longJVMPauseDetector.longPausesCount() : 0; } /** {@inheritDoc} */ @Override public long getLongJVMPausesTotalDuration() { return longJVMPauseDetector != null ? longJVMPauseDetector.longPausesTotalDuration() : 0; } /** {@inheritDoc} */ @Override public Map<Long, Long> getLongJVMPauseLastEvents() { return longJVMPauseDetector != null ? longJVMPauseDetector.longPauseEvents() : Collections.emptyMap(); } /** {@inheritDoc} */ @Override public String getUpTimeFormatted() { return X.timeSpan2DHMSM(U.currentTimeMillis() - startTime); } /** {@inheritDoc} */ @Override public String getFullVersion() { return VER_STR + '-' + BUILD_TSTAMP_STR; } /** {@inheritDoc} */ @Override public String getCheckpointSpiFormatted() { assert cfg != null; return Arrays.toString(cfg.getCheckpointSpi()); } /** {@inheritDoc} */ @Override public String getCurrentCoordinatorFormatted() { ClusterNode node = ctx.discovery().oldestAliveServerNode(AffinityTopologyVersion.NONE); if (node == null) return ""; return new StringBuilder() .append(node.addresses()) .append(COORDINATOR_PROPERTIES_SEPARATOR) .append(node.id()) .append(COORDINATOR_PROPERTIES_SEPARATOR) .append(node.order()) .append(COORDINATOR_PROPERTIES_SEPARATOR) .append(node.hostNames()) .toString(); } /** {@inheritDoc} */ @Override public boolean isNodeInBaseline() { ctx.gateway().readLockAnyway(); try { if (ctx.gateway().getState() != STARTED) return false; ClusterNode locNode = localNode(); if (locNode.isClient() || locNode.isDaemon()) return false; DiscoveryDataClusterState clusterState = ctx.state().clusterState(); return clusterState.hasBaselineTopology() && CU.baselineNode(locNode, clusterState); } finally { ctx.gateway().readUnlock(); } } /** {@inheritDoc} */ @Override public String getCommunicationSpiFormatted() { assert cfg != null; return cfg.getCommunicationSpi().toString(); } /** {@inheritDoc} */ @Override public String getDeploymentSpiFormatted() { assert cfg != null; return cfg.getDeploymentSpi().toString(); } /** {@inheritDoc} */ @Override public String getDiscoverySpiFormatted() { assert cfg != null; return cfg.getDiscoverySpi().toString(); } /** {@inheritDoc} */ @Override public String getEventStorageSpiFormatted() { assert cfg != null; return cfg.getEventStorageSpi().toString(); } /** {@inheritDoc} */ @Override public String getCollisionSpiFormatted() { assert cfg != null; return cfg.getCollisionSpi().toString(); } /** {@inheritDoc} */ @Override public String getFailoverSpiFormatted() { assert cfg != null; return Arrays.toString(cfg.getFailoverSpi()); } /** {@inheritDoc} */ @Override public String getLoadBalancingSpiFormatted() { assert cfg != null; return Arrays.toString(cfg.getLoadBalancingSpi()); } /** {@inheritDoc} */ @Override public String getOsInformation() { return U.osString(); } /** {@inheritDoc} */ @Override public String getJdkInformation() { return U.jdkString(); } /** {@inheritDoc} */ @Override public String getOsUser() { return System.getProperty("user.name"); } /** {@inheritDoc} */ @Override public void printLastErrors() { ctx.exceptionRegistry().printErrors(log); } /** {@inheritDoc} */ @Override public String getVmName() { return ManagementFactory.getRuntimeMXBean().getName(); } /** {@inheritDoc} */ @Override public String getInstanceName() { return igniteInstanceName; } /** {@inheritDoc} */ @Override public String getExecutorServiceFormatted() { assert cfg != null; return String.valueOf(cfg.getPublicThreadPoolSize()); } /** {@inheritDoc} */ @Override public String getIgniteHome() { assert cfg != null; return cfg.getIgniteHome(); } /** {@inheritDoc} */ @Override public String getGridLoggerFormatted() { assert cfg != null; return cfg.getGridLogger().toString(); } /** {@inheritDoc} */ @Override public String getMBeanServerFormatted() { assert cfg != null; return cfg.getMBeanServer().toString(); } /** {@inheritDoc} */ @Override public UUID getLocalNodeId() { assert cfg != null; return cfg.getNodeId(); } /** {@inheritDoc} */ @Override public List<String> getUserAttributesFormatted() { assert cfg != null; return (List<String>)F.transform(cfg.getUserAttributes().entrySet(), new C1<Map.Entry<String, ?>, String>() { @Override public String apply(Map.Entry<String, ?> e) { return e.getKey() + ", " + e.getValue().toString(); } }); } /** {@inheritDoc} */ @Override public boolean isPeerClassLoadingEnabled() { assert cfg != null; return cfg.isPeerClassLoadingEnabled(); } /** {@inheritDoc} */ @Override public List<String> getLifecycleBeansFormatted() { LifecycleBean[] beans = cfg.getLifecycleBeans(); if (F.isEmpty(beans)) return Collections.emptyList(); else { List<String> res = new ArrayList<>(beans.length); for (LifecycleBean bean : beans) res.add(String.valueOf(bean)); return res; } } /** {@inheritDoc} */ @Override public String clusterState() { return ctx.state().clusterState().state().toString(); } /** {@inheritDoc} */ @Override public long lastClusterStateChangeTime() { return ctx.state().lastStateChangeTime(); } /** * @param name New attribute name. * @param val New attribute value. * @throws IgniteCheckedException If duplicated SPI name found. */ private void add(String name, @Nullable Serializable val) throws IgniteCheckedException { assert name != null; if (ctx.addNodeAttribute(name, val) != null) { if (name.endsWith(ATTR_SPI_CLASS)) // User defined duplicated names for the different SPIs. throw new IgniteCheckedException("Failed to set SPI attribute. Duplicated SPI name found: " + name.substring(0, name.length() - ATTR_SPI_CLASS.length())); // Otherwise it's a mistake of setting up duplicated attribute. assert false : "Duplicate attribute: " + name; } } /** * Notifies life-cycle beans of ignite event. * * @param evt Lifecycle event to notify beans with. * @throws IgniteCheckedException If user threw exception during start. */ private void notifyLifecycleBeans(LifecycleEventType evt) throws IgniteCheckedException { if (!cfg.isDaemon() && cfg.getLifecycleBeans() != null) { for (LifecycleBean bean : cfg.getLifecycleBeans()) if (bean != null) { try { bean.onLifecycleEvent(evt); } catch (Exception e) { throw new IgniteCheckedException(e); } } } } /** * Notifies life-cycle beans of ignite event. * * @param evt Lifecycle event to notify beans with. */ private void notifyLifecycleBeansEx(LifecycleEventType evt) { try { notifyLifecycleBeans(evt); } // Catch generic throwable to secure against user assertions. catch (Throwable e) { U.error(log, "Failed to notify lifecycle bean (safely ignored) [evt=" + evt + (igniteInstanceName == null ? "" : ", igniteInstanceName=" + igniteInstanceName) + ']', e); if (e instanceof Error) throw (Error)e; } } /** * @param clsPathEntry Classpath string to process. * @param clsPathContent StringBuilder to attach path to. */ private void ackClassPathEntry(String clsPathEntry, SB clsPathContent) { File clsPathElementFile = new File(clsPathEntry); if (clsPathElementFile.isDirectory()) clsPathContent.a(clsPathEntry).a(";"); else { String extension = clsPathEntry.length() >= 4 ? clsPathEntry.substring(clsPathEntry.length() - 4).toLowerCase() : null; if (".jar".equals(extension) || ".zip".equals(extension)) clsPathContent.a(clsPathEntry).a(";"); } } /** * @param clsPathEntry Classpath string to process. * @param clsPathContent StringBuilder to attach path to. */ private void ackClassPathWildCard(String clsPathEntry, SB clsPathContent) { final int lastSeparatorIdx = clsPathEntry.lastIndexOf(File.separator); final int asteriskIdx = clsPathEntry.indexOf('*'); //just to log possibly incorrent entries to err if (asteriskIdx >= 0 && asteriskIdx < lastSeparatorIdx) throw new RuntimeException("Could not parse classpath entry"); final int fileMaskFirstIdx = lastSeparatorIdx + 1; final String fileMask = (fileMaskFirstIdx >= clsPathEntry.length()) ? "*.jar" : clsPathEntry.substring(fileMaskFirstIdx); Path path = Paths.get(lastSeparatorIdx > 0 ? clsPathEntry.substring(0, lastSeparatorIdx) : ".") .toAbsolutePath() .normalize(); if (lastSeparatorIdx == 0) path = path.getRoot(); try { DirectoryStream<Path> files = Files.newDirectoryStream(path, fileMask); for (Path f : files) { String s = f.toString(); if (s.toLowerCase().endsWith(".jar")) clsPathContent.a(f.toString()).a(";"); } } catch (IOException e) { throw new UncheckedIOException(e); } } /** * Prints the list of {@code *.jar} and {@code *.class} files containing in the classpath. */ private void ackClassPathContent() { assert log != null; boolean enabled = IgniteSystemProperties.getBoolean(IGNITE_LOG_CLASSPATH_CONTENT_ON_STARTUP, DFLT_LOG_CLASSPATH_CONTENT_ON_STARTUP); if (enabled) { String clsPath = System.getProperty("java.class.path", "."); String[] clsPathElements = clsPath.split(File.pathSeparator); U.log(log, "Classpath value: " + clsPath); SB clsPathContent = new SB("List of files containing in classpath: "); for (String clsPathEntry : clsPathElements) { try { if (clsPathEntry.contains("*")) ackClassPathWildCard(clsPathEntry, clsPathContent); else ackClassPathEntry(clsPathEntry, clsPathContent); } catch (Exception e) { U.warn(log, String.format("Could not log class path entry '%s': %s", clsPathEntry, e.getMessage())); } } U.log(log, clsPathContent.toString()); } } /** * @param cfg Ignite configuration to use. * @param utilityCachePool Utility cache pool. * @param execSvc Executor service. * @param svcExecSvc Services executor service. * @param sysExecSvc System executor service. * @param stripedExecSvc Striped executor. * @param p2pExecSvc P2P executor service. * @param mgmtExecSvc Management executor service. * @param dataStreamExecSvc Data streamer executor service. * @param restExecSvc Reset executor service. * @param affExecSvc Affinity executor service. * @param idxExecSvc Indexing executor service. * @param buildIdxExecSvc Create/rebuild indexes executor service. * @param callbackExecSvc Callback executor service. * @param qryExecSvc Query executor service. * @param schemaExecSvc Schema executor service. * @param rebalanceExecSvc Rebalance excutor service. * @param rebalanceStripedExecSvc Striped rebalance excutor service. * @param customExecSvcs Custom named executors. * @param errHnd Error handler to use for notification about startup problems. * @param workerRegistry Worker registry. * @param hnd Default uncaught exception handler used by thread pools. * @throws IgniteCheckedException Thrown in case of any errors. */ public void start( final IgniteConfiguration cfg, ExecutorService utilityCachePool, final ExecutorService execSvc, final ExecutorService svcExecSvc, final ExecutorService sysExecSvc, final StripedExecutor stripedExecSvc, ExecutorService p2pExecSvc, ExecutorService mgmtExecSvc, StripedExecutor dataStreamExecSvc, ExecutorService restExecSvc, ExecutorService affExecSvc, @Nullable ExecutorService idxExecSvc, @Nullable ExecutorService buildIdxExecSvc, IgniteStripedThreadPoolExecutor callbackExecSvc, ExecutorService qryExecSvc, ExecutorService schemaExecSvc, ExecutorService rebalanceExecSvc, IgniteStripedThreadPoolExecutor rebalanceStripedExecSvc, @Nullable final Map<String, ? extends ExecutorService> customExecSvcs, GridAbsClosure errHnd, WorkersRegistry workerRegistry, Thread.UncaughtExceptionHandler hnd, TimeBag startTimer ) throws IgniteCheckedException { gw.compareAndSet(null, new GridKernalGatewayImpl(cfg.getIgniteInstanceName())); GridKernalGateway gw = this.gw.get(); gw.writeLock(); try { switch (gw.getState()) { case STARTED: { U.warn(log, "Grid has already been started (ignored)."); return; } case STARTING: { U.warn(log, "Grid is already in process of being started (ignored)."); return; } case STOPPING: { throw new IgniteCheckedException("Grid is in process of being stopped"); } case STOPPED: { break; } } gw.setState(STARTING); } finally { gw.writeUnlock(); } assert cfg != null; // Make sure we got proper configuration. validateCommon(cfg); igniteInstanceName = cfg.getIgniteInstanceName(); this.cfg = cfg; log = (GridLoggerProxy)cfg.getGridLogger().getLogger( getClass().getName() + (igniteInstanceName != null ? '%' + igniteInstanceName : "")); longJVMPauseDetector = new LongJVMPauseDetector(log); longJVMPauseDetector.start(); RuntimeMXBean rtBean = ManagementFactory.getRuntimeMXBean(); // Ack various information. ackAsciiLogo(); ackConfigUrl(); ackConfiguration(cfg); ackDaemon(); ackOsInfo(); ackLanguageRuntime(); ackRemoteManagement(); ackLogger(); ackVmArguments(rtBean); ackClassPaths(rtBean); ackSystemProperties(); ackEnvironmentVariables(); ackMemoryConfiguration(); ackCacheConfiguration(); ackP2pConfiguration(); ackRebalanceConfiguration(); ackIPv4StackFlagIsSet(); // Run background network diagnostics. GridDiagnostic.runBackgroundCheck(igniteInstanceName, execSvc, log); // Ack 3-rd party licenses location. if (log.isInfoEnabled() && cfg.getIgniteHome() != null) log.info("3-rd party licenses can be found at: " + cfg.getIgniteHome() + File.separatorChar + "libs" + File.separatorChar + "licenses"); // Check that user attributes are not conflicting // with internally reserved names. for (String name : cfg.getUserAttributes().keySet()) if (name.startsWith(ATTR_PREFIX)) throw new IgniteCheckedException("User attribute has illegal name: '" + name + "'. Note that all names " + "starting with '" + ATTR_PREFIX + "' are reserved for internal use."); // Ack local node user attributes. logNodeUserAttributes(); // Ack configuration. ackSpis(); List<PluginProvider> plugins = cfg.getPluginProviders() != null && cfg.getPluginProviders().length > 0 ? Arrays.asList(cfg.getPluginProviders()) : U.allPluginProviders(); // Spin out SPIs & managers. try { ctx = new GridKernalContextImpl(log, this, cfg, gw, utilityCachePool, execSvc, svcExecSvc, sysExecSvc, stripedExecSvc, p2pExecSvc, mgmtExecSvc, dataStreamExecSvc, restExecSvc, affExecSvc, idxExecSvc, buildIdxExecSvc, callbackExecSvc, qryExecSvc, schemaExecSvc, rebalanceExecSvc, rebalanceStripedExecSvc, customExecSvcs, plugins, MarshallerUtils.classNameFilter(this.getClass().getClassLoader()), workerRegistry, hnd, longJVMPauseDetector ); startProcessor(new DiagnosticProcessor(ctx)); mBeansMgr = new IgniteMBeansManager(this); cfg.getMarshaller().setContext(ctx.marshallerContext()); startProcessor(new GridInternalSubscriptionProcessor(ctx)); ClusterProcessor clusterProc = new ClusterProcessor(ctx); startProcessor(clusterProc); U.onGridStart(); // Start and configure resource processor first as it contains resources used // by all other managers and processors. GridResourceProcessor rsrcProc = new GridResourceProcessor(ctx); rsrcProc.setSpringContext(rsrcCtx); scheduler = new IgniteSchedulerImpl(ctx); startProcessor(rsrcProc); // Inject resources into lifecycle beans. if (!cfg.isDaemon() && cfg.getLifecycleBeans() != null) { for (LifecycleBean bean : cfg.getLifecycleBeans()) { if (bean != null) rsrcProc.inject(bean); } } // Lifecycle notification. notifyLifecycleBeans(BEFORE_NODE_START); // Starts lifecycle aware components. U.startLifecycleAware(lifecycleAwares(cfg)); startProcessor(new IgnitePluginProcessor(ctx, cfg, plugins)); startProcessor(new FailureProcessor(ctx)); startProcessor(new PoolProcessor(ctx)); // Closure processor should be started before all others // (except for resource processor), as many components can depend on it. startProcessor(new GridClosureProcessor(ctx)); // Start some other processors (order & place is important). startProcessor(new GridPortProcessor(ctx)); startProcessor(new GridJobMetricsProcessor(ctx)); // Timeout processor needs to be started before managers, // as managers may depend on it. startProcessor(new GridTimeoutProcessor(ctx)); // Start security processors. startProcessor(securityProcessor()); // Start SPI managers. // NOTE: that order matters as there are dependencies between managers. try { startManager(new GridTracingManager(ctx, false)); } catch (IgniteCheckedException e) { startManager(new GridTracingManager(ctx, true)); } startManager(new GridMetricManager(ctx)); startManager(new GridSystemViewManager(ctx)); startManager(new GridIoManager(ctx)); startManager(new GridCheckpointManager(ctx)); startManager(new GridEventStorageManager(ctx)); startManager(new GridDeploymentManager(ctx)); startManager(new GridLoadBalancerManager(ctx)); startManager(new GridFailoverManager(ctx)); startManager(new GridCollisionManager(ctx)); startManager(new GridIndexingManager(ctx)); ackSecurity(); // Assign discovery manager to context before other processors start so they // are able to register custom event listener. GridManager discoMgr = new GridDiscoveryManager(ctx); ctx.add(discoMgr, false); // Start the encryption manager after assigning the discovery manager to context, so it will be // able to register custom event listener. startManager(new GridEncryptionManager(ctx)); startProcessor(new PdsConsistentIdProcessor(ctx)); MaintenanceProcessor mntcProcessor = new MaintenanceProcessor(ctx); startProcessor(mntcProcessor); if (mntcProcessor.isMaintenanceMode()) { ctx.config().setDiscoverySpi(new IsolatedDiscoverySpi()); discoMgr = new GridDiscoveryManager(ctx); ctx.add(discoMgr, false); } // Start processors before discovery manager, so they will // be able to start receiving messages once discovery completes. try { startProcessor(COMPRESSION.createOptional(ctx)); startProcessor(new GridMarshallerMappingProcessor(ctx)); startProcessor(new MvccProcessorImpl(ctx)); startProcessor(createComponent(DiscoveryNodeValidationProcessor.class, ctx)); startProcessor(new GridAffinityProcessor(ctx)); startProcessor(createComponent(GridSegmentationProcessor.class, ctx)); startTimer.finishGlobalStage("Start managers"); startProcessor(createComponent(IgniteCacheObjectProcessor.class, ctx)); startTimer.finishGlobalStage("Configure binary metadata"); startProcessor(createComponent(IGridClusterStateProcessor.class, ctx)); startProcessor(new IgniteAuthenticationProcessor(ctx)); startProcessor(new GridCacheProcessor(ctx)); startProcessor(new GridQueryProcessor(ctx)); startProcessor(new ClientListenerProcessor(ctx)); startProcessor(createServiceProcessor()); startProcessor(new GridTaskSessionProcessor(ctx)); startProcessor(new GridJobProcessor(ctx)); startProcessor(new GridTaskProcessor(ctx)); startProcessor((GridProcessor)SCHEDULE.createOptional(ctx)); startProcessor(createComponent(IgniteRestProcessor.class, ctx)); startProcessor(new DataStreamProcessor(ctx)); startProcessor(new GridContinuousProcessor(ctx)); startProcessor(new DataStructuresProcessor(ctx)); startProcessor(createComponent(PlatformProcessor.class, ctx)); startProcessor(new DistributedMetaStorageImpl(ctx)); startProcessor(new DistributedConfigurationProcessor(ctx)); startProcessor(new DurableBackgroundTasksProcessor(ctx)); startTimer.finishGlobalStage("Start processors"); // Start plugins. for (PluginProvider provider : ctx.plugins().allProviders()) { ctx.add(new GridPluginComponent(provider)); provider.start(ctx.plugins().pluginContextForProvider(provider)); startTimer.finishGlobalStage("Start '" + provider.name() + "' plugin"); } // Start platform plugins. if (ctx.config().getPlatformConfiguration() != null) startProcessor(new PlatformPluginProcessor(ctx)); mBeansMgr.registerMBeansDuringInitPhase(); ctx.cluster().initDiagnosticListeners(); fillNodeAttributes(clusterProc.updateNotifierEnabled()); ctx.cache().context().database().notifyMetaStorageSubscribersOnReadyForRead(); ((DistributedMetaStorageImpl)ctx.distributedMetastorage()).inMemoryReadyForRead(); startTimer.finishGlobalStage("Init metastore"); ctx.cache().context().database().startMemoryRestore(ctx, startTimer); ctx.recoveryMode(false); startTimer.finishGlobalStage("Finish recovery"); } catch (Throwable e) { U.error( log, "Exception during start processors, node will be stopped and close connections", e); // Stop discovery spi to close tcp socket. ctx.discovery().stop(true); throw e; } // All components exept Discovery are started, time to check if maintenance is still needed mntcProcessor.prepareAndExecuteMaintenance(); gw.writeLock(); try { gw.setState(STARTED); // Start discovery manager last to make sure that grid is fully initialized. startManager(discoMgr); } finally { gw.writeUnlock(); } startTimer.finishGlobalStage("Join topology"); // Check whether UTF-8 is the default character encoding. checkFileEncoding(); // Check whether physical RAM is not exceeded. checkPhysicalRam(); // Suggest configuration optimizations. suggestOptimizations(cfg); // Suggest JVM optimizations. ctx.performance().addAll(JvmConfigurationSuggestions.getSuggestions()); // Suggest Operation System optimizations. ctx.performance().addAll(OsConfigurationSuggestions.getSuggestions()); DiscoveryLocalJoinData joinData = ctx.discovery().localJoin(); IgniteInternalFuture<Boolean> transitionWaitFut = joinData.transitionWaitFuture(); // Notify discovery manager the first to make sure that topology is discovered. // Active flag is not used in managers, so it is safe to pass true. ctx.discovery().onKernalStart(true); // Notify IO manager the second so further components can send and receive messages. // Must notify the IO manager before transition state await to make sure IO connection can be established. ctx.io().onKernalStart(true); boolean active; if (transitionWaitFut != null) { if (log.isInfoEnabled()) { log.info("Join cluster while cluster state transition is in progress, " + "waiting when transition finish."); } active = transitionWaitFut.get(); } else active = joinData.active(); startTimer.finishGlobalStage("Await transition"); ctx.metric().registerThreadPools(utilityCachePool, execSvc, svcExecSvc, sysExecSvc, stripedExecSvc, p2pExecSvc, mgmtExecSvc, dataStreamExecSvc, restExecSvc, affExecSvc, idxExecSvc, callbackExecSvc, qryExecSvc, schemaExecSvc, rebalanceExecSvc, rebalanceStripedExecSvc, customExecSvcs); registerMetrics(); ctx.cluster().registerMetrics(); // Register MBeans. mBeansMgr.registerMBeansAfterNodeStarted(utilityCachePool, execSvc, svcExecSvc, sysExecSvc, stripedExecSvc, p2pExecSvc, mgmtExecSvc, dataStreamExecSvc, restExecSvc, affExecSvc, idxExecSvc, callbackExecSvc, qryExecSvc, schemaExecSvc, rebalanceExecSvc, rebalanceStripedExecSvc, customExecSvcs, ctx.workersRegistry()); ctx.systemView().registerThreadPools(stripedExecSvc, dataStreamExecSvc); boolean recon = false; // Callbacks. for (GridComponent comp : ctx) { // Skip discovery manager. if (comp instanceof GridDiscoveryManager) continue; // Skip IO manager. if (comp instanceof GridIoManager) continue; if (comp instanceof GridPluginComponent) continue; if (!skipDaemon(comp)) { try { comp.onKernalStart(active); } catch (IgniteNeedReconnectException e) { ClusterNode locNode = ctx.discovery().localNode(); assert locNode.isClient(); if (!ctx.discovery().reconnectSupported()) throw new IgniteCheckedException("Client node in forceServerMode " + "is not allowed to reconnect to the cluster and will be stopped."); if (log.isDebugEnabled()) log.debug("Failed to start node components on node start, will wait for reconnect: " + e); recon = true; } } } // Start plugins. for (PluginProvider provider : ctx.plugins().allProviders()) provider.onIgniteStart(); if (recon) reconnectState.waitFirstReconnect(); // Lifecycle bean notifications. notifyLifecycleBeans(AFTER_NODE_START); } catch (Throwable e) { IgniteSpiVersionCheckException verCheckErr = X.cause(e, IgniteSpiVersionCheckException.class); if (verCheckErr != null) U.error(log, verCheckErr.getMessage()); else if (X.hasCause(e, InterruptedException.class, IgniteInterruptedCheckedException.class)) U.warn(log, "Grid startup routine has been interrupted (will rollback)."); else U.error(log, "Got exception while starting (will rollback startup routine).", e); errHnd.apply(); stop(true); if (e instanceof Error) throw e; else if (e instanceof IgniteCheckedException) throw (IgniteCheckedException)e; else throw new IgniteCheckedException(e); } // Mark start timestamp. startTime = U.currentTimeMillis(); String intervalStr = IgniteSystemProperties.getString(IGNITE_STARVATION_CHECK_INTERVAL); // Start starvation checker if enabled. boolean starveCheck = !isDaemon() && !"0".equals(intervalStr); if (starveCheck) { final long interval = F.isEmpty(intervalStr) ? DFLT_PERIODIC_STARVATION_CHECK_FREQ : Long.parseLong(intervalStr); starveTask = ctx.timeout().schedule(new Runnable() { /** Last completed task count. */ private long lastCompletedCntPub; /** Last completed task count. */ private long lastCompletedCntSys; /** Last completed task count. */ private long lastCompletedCntQry; @Override public void run() { if (execSvc instanceof ThreadPoolExecutor) { ThreadPoolExecutor exec = (ThreadPoolExecutor)execSvc; lastCompletedCntPub = checkPoolStarvation(exec, lastCompletedCntPub, "public"); } if (sysExecSvc instanceof ThreadPoolExecutor) { ThreadPoolExecutor exec = (ThreadPoolExecutor)sysExecSvc; lastCompletedCntSys = checkPoolStarvation(exec, lastCompletedCntSys, "system"); } if (qryExecSvc instanceof ThreadPoolExecutor) { ThreadPoolExecutor exec = (ThreadPoolExecutor)qryExecSvc; lastCompletedCntQry = checkPoolStarvation(exec, lastCompletedCntQry, "query"); } if (stripedExecSvc != null) stripedExecSvc.detectStarvation(); } /** * @param exec Thread pool executor to check. * @param lastCompletedCnt Last completed tasks count. * @param pool Pool name for message. * @return Current completed tasks count. */ private long checkPoolStarvation( ThreadPoolExecutor exec, long lastCompletedCnt, String pool ) { long completedCnt = exec.getCompletedTaskCount(); // If all threads are active and no task has completed since last time and there is // at least one waiting request, then it is possible starvation. if (exec.getPoolSize() == exec.getActiveCount() && completedCnt == lastCompletedCnt && !exec.getQueue().isEmpty()) LT.warn( log, "Possible thread pool starvation detected (no task completed in last " + interval + "ms, is " + pool + " thread pool size large enough?)"); return completedCnt; } }, interval, interval); } long metricsLogFreq = cfg.getMetricsLogFrequency(); if (metricsLogFreq > 0) { metricsLogTask = ctx.timeout().schedule(new Runnable() { private final DecimalFormat dblFmt = doubleFormat(); @Override public void run() { ackNodeMetrics(dblFmt, execSvc, sysExecSvc, customExecSvcs); } }, metricsLogFreq, metricsLogFreq); } ctx.performance().add("Disable assertions (remove '-ea' from JVM options)", !U.assertionsEnabled()); ctx.performance().logSuggestions(log, igniteInstanceName); U.quietAndInfo(log, "To start Console Management & Monitoring run ignitevisorcmd.{sh|bat}"); if (!IgniteSystemProperties.getBoolean(IgniteSystemProperties.IGNITE_QUIET, true)) ackClassPathContent(); ackStart(rtBean); if (!isDaemon()) ctx.discovery().ackTopology(ctx.discovery().localJoin().joinTopologyVersion().topologyVersion(), EventType.EVT_NODE_JOINED, localNode()); startTimer.finishGlobalStage("Await exchange"); } /** */ private static DecimalFormat doubleFormat() { return new DecimalFormat("#.##", DecimalFormatSymbols.getInstance(Locale.US)); } /** * @return Ignite security processor. See {@link IgniteSecurity} for details. */ private GridProcessor securityProcessor() throws IgniteCheckedException { GridSecurityProcessor prc = createComponent(GridSecurityProcessor.class, ctx); return prc != null && prc.enabled() ? new IgniteSecurityProcessor(ctx, prc) : new NoOpIgniteSecurityProcessor(ctx); } /** * Create description of an executor service for logging. * * @param execSvcName Name of the service. * @param execSvc Service to create a description for. */ private String createExecutorDescription(String execSvcName, ExecutorService execSvc) { int poolActiveThreads = 0; int poolIdleThreads = 0; int poolQSize = 0; if (execSvc instanceof ThreadPoolExecutor) { ThreadPoolExecutor exec = (ThreadPoolExecutor)execSvc; int poolSize = exec.getPoolSize(); poolActiveThreads = Math.min(poolSize, exec.getActiveCount()); poolIdleThreads = poolSize - poolActiveThreads; poolQSize = exec.getQueue().size(); } return execSvcName + " [active=" + poolActiveThreads + ", idle=" + poolIdleThreads + ", qSize=" + poolQSize + "]"; } /** * Creates service processor depend on {@link IgniteSystemProperties#IGNITE_EVENT_DRIVEN_SERVICE_PROCESSOR_ENABLED}. * * @return The service processor. See {@link IgniteServiceProcessor} for details. */ private GridProcessorAdapter createServiceProcessor() { final boolean srvcProcMode = getBoolean(IGNITE_EVENT_DRIVEN_SERVICE_PROCESSOR_ENABLED, DFLT_EVENT_DRIVEN_SERVICE_PROCESSOR_ENABLED); if (srvcProcMode) return new IgniteServiceProcessor(ctx); return new GridServiceProcessor(ctx); } /** * Validates common configuration parameters. * * @param cfg Ignite configuration to validate. */ private void validateCommon(IgniteConfiguration cfg) { A.notNull(cfg.getNodeId(), "cfg.getNodeId()"); if (!U.IGNITE_MBEANS_DISABLED) A.notNull(cfg.getMBeanServer(), "cfg.getMBeanServer()"); A.notNull(cfg.getGridLogger(), "cfg.getGridLogger()"); A.notNull(cfg.getMarshaller(), "cfg.getMarshaller()"); A.notNull(cfg.getUserAttributes(), "cfg.getUserAttributes()"); // All SPIs should be non-null. A.notNull(cfg.getCheckpointSpi(), "cfg.getCheckpointSpi()"); A.notNull(cfg.getCommunicationSpi(), "cfg.getCommunicationSpi()"); A.notNull(cfg.getDeploymentSpi(), "cfg.getDeploymentSpi()"); A.notNull(cfg.getDiscoverySpi(), "cfg.getDiscoverySpi()"); A.notNull(cfg.getEventStorageSpi(), "cfg.getEventStorageSpi()"); A.notNull(cfg.getCollisionSpi(), "cfg.getCollisionSpi()"); A.notNull(cfg.getFailoverSpi(), "cfg.getFailoverSpi()"); A.notNull(cfg.getLoadBalancingSpi(), "cfg.getLoadBalancingSpi()"); A.notNull(cfg.getIndexingSpi(), "cfg.getIndexingSpi()"); A.ensure(cfg.getNetworkTimeout() > 0, "cfg.getNetworkTimeout() > 0"); A.ensure(cfg.getNetworkSendRetryDelay() > 0, "cfg.getNetworkSendRetryDelay() > 0"); A.ensure(cfg.getNetworkSendRetryCount() > 0, "cfg.getNetworkSendRetryCount() > 0"); } /** * Check whether UTF-8 is the default character encoding. * Differing character encodings across cluster may lead to erratic behavior. */ private void checkFileEncoding() { String encodingDisplayName = Charset.defaultCharset().displayName(Locale.ENGLISH); if (!"UTF-8".equals(encodingDisplayName)) { U.quietAndWarn(log, "Default character encoding is " + encodingDisplayName + ". Specify UTF-8 character encoding by setting -Dfile.encoding=UTF-8 JVM parameter. " + "Differing character encodings across cluster may lead to erratic behavior."); } } /** * Checks whether physical RAM is not exceeded. */ @SuppressWarnings("ConstantConditions") private void checkPhysicalRam() { long ram = ctx.discovery().localNode().attribute(ATTR_PHY_RAM); if (ram != -1) { String macs = ctx.discovery().localNode().attribute(ATTR_MACS); long totalHeap = 0; long totalOffheap = 0; for (ClusterNode node : ctx.discovery().allNodes()) { if (macs.equals(node.attribute(ATTR_MACS))) { long heap = node.metrics().getHeapMemoryMaximum(); Long offheap = node.<Long>attribute(ATTR_OFFHEAP_SIZE); if (heap != -1) totalHeap += heap; if (offheap != null) totalOffheap += offheap; } } long total = totalHeap + totalOffheap; if (total < 0) total = Long.MAX_VALUE; // 4GB or 20% of available memory is expected to be used by OS and user applications long safeToUse = ram - Math.max(4L << 30, (long)(ram * 0.2)); if (total > safeToUse) { U.quietAndWarn(log, "Nodes started on local machine require more than 80% of physical RAM what can " + "lead to significant slowdown due to swapping (please decrease JVM heap size, data region " + "size or checkpoint buffer size) [required=" + (total >> 20) + "MB, available=" + (ram >> 20) + "MB]"); } } } /** * @param cfg Ignite configuration to check for possible performance issues. */ private void suggestOptimizations(IgniteConfiguration cfg) { GridPerformanceSuggestions perf = ctx.performance(); if (ctx.collision().enabled()) perf.add("Disable collision resolution (remove 'collisionSpi' from configuration)"); if (ctx.checkpoint().enabled()) perf.add("Disable checkpoints (remove 'checkpointSpi' from configuration)"); if (cfg.isMarshalLocalJobs()) perf.add("Disable local jobs marshalling (set 'marshalLocalJobs' to false)"); if (cfg.getIncludeEventTypes() != null && cfg.getIncludeEventTypes().length != 0) perf.add("Disable grid events (remove 'includeEventTypes' from configuration)"); if (BinaryMarshaller.available() && (cfg.getMarshaller() != null && !(cfg.getMarshaller() instanceof BinaryMarshaller))) perf.add("Use default binary marshaller (do not set 'marshaller' explicitly)"); } /** * Creates attributes map and fills it in. * * @param notifyEnabled Update notifier flag. * @throws IgniteCheckedException thrown if was unable to set up attribute. */ private void fillNodeAttributes(boolean notifyEnabled) throws IgniteCheckedException { ctx.addNodeAttribute(ATTR_REBALANCE_POOL_SIZE, configuration().getRebalanceThreadPoolSize()); ctx.addNodeAttribute(ATTR_DATA_STREAMER_POOL_SIZE, configuration().getDataStreamerThreadPoolSize()); final String[] incProps = cfg.getIncludeProperties(); try { // Stick all environment settings into node attributes. for (Map.Entry<String, String> sysEntry : System.getenv().entrySet()) { String name = sysEntry.getKey(); if (incProps == null || U.containsStringArray(incProps, name, true) || U.isVisorNodeStartProperty(name) || U.isVisorRequiredProperty(name)) ctx.addNodeAttribute(name, sysEntry.getValue()); } if (log.isDebugEnabled()) log.debug("Added environment properties to node attributes."); } catch (SecurityException e) { throw new IgniteCheckedException("Failed to add environment properties to node attributes due to " + "security violation: " + e.getMessage()); } try { // Stick all system properties into node's attributes overwriting any // identical names from environment properties. for (Map.Entry<Object, Object> e : IgniteSystemProperties.snapshot().entrySet()) { String key = (String)e.getKey(); if (incProps == null || U.containsStringArray(incProps, key, true) || U.isVisorRequiredProperty(key)) { Object val = ctx.nodeAttribute(key); if (val != null && !val.equals(e.getValue())) U.warn(log, "System property will override environment variable with the same name: " + key); ctx.addNodeAttribute(key, e.getValue()); } } ctx.addNodeAttribute(IgniteNodeAttributes.ATTR_UPDATE_NOTIFIER_ENABLED, notifyEnabled); if (log.isDebugEnabled()) log.debug("Added system properties to node attributes."); } catch (SecurityException e) { throw new IgniteCheckedException("Failed to add system properties to node attributes due to security " + "violation: " + e.getMessage()); } // Add local network IPs and MACs. String ips = F.concat(U.allLocalIps(), ", "); // Exclude loopbacks. String macs = F.concat(U.allLocalMACs(), ", "); // Only enabled network interfaces. // Ack network context. if (log.isInfoEnabled()) { log.info("Non-loopback local IPs: " + (F.isEmpty(ips) ? "N/A" : ips)); log.info("Enabled local MACs: " + (F.isEmpty(macs) ? "N/A" : macs)); } // Warn about loopback. if (ips.isEmpty() && macs.isEmpty()) U.warn(log, "Ignite is starting on loopback address... Only nodes on the same physical " + "computer can participate in topology."); // Stick in network context into attributes. add(ATTR_IPS, (ips.isEmpty() ? "" : ips)); Map<String, ?> userAttrs = configuration().getUserAttributes(); if (userAttrs != null && userAttrs.get(IgniteNodeAttributes.ATTR_MACS_OVERRIDE) != null) add(ATTR_MACS, (Serializable)userAttrs.get(IgniteNodeAttributes.ATTR_MACS_OVERRIDE)); else add(ATTR_MACS, (macs.isEmpty() ? "" : macs)); // Stick in some system level attributes add(ATTR_JIT_NAME, U.getCompilerMx() == null ? "" : U.getCompilerMx().getName()); add(ATTR_BUILD_VER, VER_STR); add(ATTR_BUILD_DATE, BUILD_TSTAMP_STR); add(ATTR_MARSHALLER, cfg.getMarshaller().getClass().getName()); add(ATTR_MARSHALLER_USE_DFLT_SUID, getBoolean(IGNITE_OPTIMIZED_MARSHALLER_USE_DEFAULT_SUID, OptimizedMarshaller.USE_DFLT_SUID)); add(ATTR_LATE_AFFINITY_ASSIGNMENT, cfg.isLateAffinityAssignment()); if (cfg.getMarshaller() instanceof BinaryMarshaller) { add(ATTR_MARSHALLER_COMPACT_FOOTER, cfg.getBinaryConfiguration() == null ? BinaryConfiguration.DFLT_COMPACT_FOOTER : cfg.getBinaryConfiguration().isCompactFooter()); add(ATTR_MARSHALLER_USE_BINARY_STRING_SER_VER_2, getBoolean(IGNITE_BINARY_MARSHALLER_USE_STRING_SERIALIZATION_VER_2, BinaryUtils.USE_STR_SERIALIZATION_VER_2)); } add(ATTR_USER_NAME, System.getProperty("user.name")); add(ATTR_IGNITE_INSTANCE_NAME, igniteInstanceName); add(ATTR_PEER_CLASSLOADING, cfg.isPeerClassLoadingEnabled()); add(ATTR_SHUTDOWN_POLICY, cfg.getShutdownPolicy().index()); add(ATTR_DEPLOYMENT_MODE, cfg.getDeploymentMode()); add(ATTR_LANG_RUNTIME, getLanguage()); add(ATTR_JVM_PID, U.jvmPid()); add(ATTR_CLIENT_MODE, cfg.isClientMode()); add(ATTR_CONSISTENCY_CHECK_SKIPPED, getBoolean(IGNITE_SKIP_CONFIGURATION_CONSISTENCY_CHECK)); add(ATTR_VALIDATE_CACHE_REQUESTS, Boolean.TRUE); if (cfg.getConsistentId() != null) add(ATTR_NODE_CONSISTENT_ID, cfg.getConsistentId()); // Build a string from JVM arguments, because parameters with spaces are split. SB jvmArgs = new SB(512); for (String arg : U.jvmArgs()) { if (arg.startsWith("-")) jvmArgs.a("@@@"); else jvmArgs.a(' '); jvmArgs.a(arg); } // Add it to attributes. add(ATTR_JVM_ARGS, jvmArgs.toString()); // Check daemon system property and override configuration if it's set. if (isDaemon()) add(ATTR_DAEMON, "true"); // In case of the parsing error, JMX remote disabled or port not being set // node attribute won't be set. if (isJmxRemoteEnabled()) { String portStr = System.getProperty("com.sun.management.jmxremote.port"); if (portStr != null) try { add(ATTR_JMX_PORT, Integer.parseInt(portStr)); } catch (NumberFormatException ignore) { // No-op. } } // Whether restart is enabled and stick the attribute. add(ATTR_RESTART_ENABLED, Boolean.toString(isRestartEnabled())); // Save port range, port numbers will be stored by rest processor at runtime. if (cfg.getConnectorConfiguration() != null) add(ATTR_REST_PORT_RANGE, cfg.getConnectorConfiguration().getPortRange()); // Whether rollback of dynamic cache start is supported or not. // This property is added because of backward compatibility. add(ATTR_DYNAMIC_CACHE_START_ROLLBACK_SUPPORTED, Boolean.TRUE); // Save data storage configuration. addDataStorageConfigurationAttributes(); // Save transactions configuration. add(ATTR_TX_CONFIG, cfg.getTransactionConfiguration()); // Supported features. add(ATTR_IGNITE_FEATURES, IgniteFeatures.allFeatures()); // Stick in SPI versions and classes attributes. addSpiAttributes(cfg.getCollisionSpi()); addSpiAttributes(cfg.getDiscoverySpi()); addSpiAttributes(cfg.getFailoverSpi()); addSpiAttributes(cfg.getCommunicationSpi()); addSpiAttributes(cfg.getEventStorageSpi()); addSpiAttributes(cfg.getCheckpointSpi()); addSpiAttributes(cfg.getLoadBalancingSpi()); addSpiAttributes(cfg.getDeploymentSpi()); addSpiAttributes(cfg.getTracingSpi()); // Set user attributes for this node. if (cfg.getUserAttributes() != null) { for (Map.Entry<String, ?> e : cfg.getUserAttributes().entrySet()) { if (ctx.hasNodeAttribute(e.getKey())) U.warn(log, "User or internal attribute has the same name as environment or system " + "property and will take precedence: " + e.getKey()); ctx.addNodeAttribute(e.getKey(), e.getValue()); } } ctx.addNodeAttribute(ATTR_EVENT_DRIVEN_SERVICE_PROCESSOR_ENABLED, ctx.service() instanceof IgniteServiceProcessor); } /** * @throws IgniteCheckedException If duplicated SPI name found. */ private void addDataStorageConfigurationAttributes() throws IgniteCheckedException { MemoryConfiguration memCfg = cfg.getMemoryConfiguration(); // Save legacy memory configuration if it's present. if (memCfg != null) { // Page size initialization is suspended, see IgniteCacheDatabaseSharedManager#checkPageSize. // We should copy initialized value from new configuration. memCfg.setPageSize(cfg.getDataStorageConfiguration().getPageSize()); add(ATTR_MEMORY_CONFIG, memCfg); } // Save data storage configuration. add(ATTR_DATA_STORAGE_CONFIG, new JdkMarshaller().marshal(cfg.getDataStorageConfiguration())); } /** * Add SPI version and class attributes into node attributes. * * @param spiList Collection of SPIs to get attributes from. * @throws IgniteCheckedException Thrown if was unable to set up attribute. */ private void addSpiAttributes(IgniteSpi... spiList) throws IgniteCheckedException { for (IgniteSpi spi : spiList) { Class<? extends IgniteSpi> spiCls = spi.getClass(); add(U.spiAttribute(spi, ATTR_SPI_CLASS), spiCls.getName()); } } /** * @param mgr Manager to start. * @throws IgniteCheckedException Throw in case of any errors. */ private void startManager(GridManager mgr) throws IgniteCheckedException { // Add manager to registry before it starts to avoid cases when manager is started // but registry does not have it yet. ctx.add(mgr); try { if (!skipDaemon(mgr)) mgr.start(); } catch (IgniteCheckedException e) { U.error(log, "Failed to start manager: " + mgr, e); throw new IgniteCheckedException("Failed to start manager: " + mgr, e); } } /** * @param proc Processor to start. * @throws IgniteCheckedException Thrown in case of any error. */ private void startProcessor(GridProcessor proc) throws IgniteCheckedException { ctx.add(proc); try { if (!skipDaemon(proc)) proc.start(); } catch (IgniteCheckedException e) { throw new IgniteCheckedException("Failed to start processor: " + proc, e); } } /** * @param helper Helper to attach to kernal context. */ private void addHelper(Object helper) { ctx.addHelper(helper); } /** * Gets "on" or "off" string for given boolean value. * * @param b Boolean value to convert. * @return Result string. */ private String onOff(boolean b) { return b ? "on" : "off"; } /** * @return {@code true} if the REST processor is enabled, {@code false} the otherwise. */ private boolean isRestEnabled() { assert cfg != null; return cfg.getConnectorConfiguration() != null && // By default rest processor doesn't start on client nodes. (!isClientNode() || (isClientNode() && IgniteSystemProperties.getBoolean(IGNITE_REST_START_ON_CLIENT))); } /** * @return {@code True} if node client or daemon otherwise {@code false}. */ private boolean isClientNode() { return cfg.isClientMode() || cfg.isDaemon(); } /** * Acks remote management. */ private void ackRemoteManagement() { assert log != null; if (!log.isInfoEnabled()) return; SB sb = new SB(); sb.a("Remote Management ["); boolean on = isJmxRemoteEnabled(); sb.a("restart: ").a(onOff(isRestartEnabled())).a(", "); sb.a("REST: ").a(onOff(isRestEnabled())).a(", "); sb.a("JMX ("); sb.a("remote: ").a(onOff(on)); if (on) { sb.a(", "); sb.a("port: ").a(System.getProperty("com.sun.management.jmxremote.port", "<n/a>")).a(", "); sb.a("auth: ").a(onOff(Boolean.getBoolean("com.sun.management.jmxremote.authenticate"))).a(", "); // By default SSL is enabled, that's why additional check for null is needed. // See http://docs.oracle.com/javase/6/docs/technotes/guides/management/agent.html sb.a("ssl: ").a(onOff(Boolean.getBoolean("com.sun.management.jmxremote.ssl") || System.getProperty("com.sun.management.jmxremote.ssl") == null)); } sb.a(")"); sb.a(']'); log.info(sb.toString()); } /** * Acks configuration URL. */ private void ackConfigUrl() { assert log != null; if (log.isInfoEnabled()) log.info("Config URL: " + System.getProperty(IGNITE_CONFIG_URL, "n/a")); } /** * @param cfg Ignite configuration to ack. */ private void ackConfiguration(IgniteConfiguration cfg) { assert log != null; if (log.isInfoEnabled()) log.info(cfg.toString()); } /** * Acks Logger configuration. */ private void ackLogger() { assert log != null; if (log.isInfoEnabled()) log.info("Logger: " + log.getLoggerInfo()); } /** * Acks ASCII-logo. Thanks to http://patorjk.com/software/taag */ private void ackAsciiLogo() { assert log != null; if (System.getProperty(IGNITE_NO_ASCII) == null) { String ver = "ver. " + ACK_VER_STR; // Big thanks to: http://patorjk.com/software/taag // Font name "Small Slant" if (log.isInfoEnabled()) { log.info(NL + NL + ">>> __________ ________________ " + NL + ">>> / _/ ___/ |/ / _/_ __/ __/ " + NL + ">>> _/ // (7 7 // / / / / _/ " + NL + ">>> /___/\\___/_/|_/___/ /_/ /___/ " + NL + ">>> " + NL + ">>> " + ver + NL + ">>> " + COPYRIGHT + NL + ">>> " + NL + ">>> Ignite documentation: " + "http://" + SITE + NL ); } if (log.isQuiet()) { U.quiet(false, " __________ ________________ ", " / _/ ___/ |/ / _/_ __/ __/ ", " _/ // (7 7 // / / / / _/ ", "/___/\\___/_/|_/___/ /_/ /___/ ", "", ver, COPYRIGHT, "", "Ignite documentation: " + "http://" + SITE, "", "Quiet mode."); String fileName = log.fileName(); if (fileName != null) U.quiet(false, " ^-- Logging to file '" + fileName + '\''); U.quiet(false, " ^-- Logging by '" + log.getLoggerInfo() + '\''); U.quiet(false, " ^-- To see **FULL** console log here add -DIGNITE_QUIET=false or \"-v\" to ignite.{sh|bat}", ""); } } } /** * Prints start info. * * @param rtBean Java runtime bean. */ private void ackStart(RuntimeMXBean rtBean) { ClusterNode locNode = localNode(); if (log.isQuiet()) { U.quiet(false, ""); U.quiet(false, "Ignite node started OK (id=" + U.id8(locNode.id()) + (F.isEmpty(igniteInstanceName) ? "" : ", instance name=" + igniteInstanceName) + ')'); } if (log.isInfoEnabled()) { String ack = "Ignite ver. " + VER_STR + '#' + BUILD_TSTAMP_STR + "-sha1:" + REV_HASH_STR; String dash = U.dash(ack.length()); SB sb = new SB(); for (GridPortRecord rec : ctx.ports().records()) sb.a(rec.protocol()).a(":").a(rec.port()).a(" "); String str = NL + NL + ">>> " + dash + NL + ">>> " + ack + NL + ">>> " + dash + NL + ">>> OS name: " + U.osString() + NL + ">>> CPU(s): " + locNode.metrics().getTotalCpus() + NL + ">>> Heap: " + U.heapSize(locNode, 2) + "GB" + NL + ">>> VM name: " + rtBean.getName() + NL + (igniteInstanceName == null ? "" : ">>> Ignite instance name: " + igniteInstanceName + NL) + ">>> Local node [" + "ID=" + locNode.id().toString().toUpperCase() + ", order=" + locNode.order() + ", clientMode=" + ctx.clientNode() + "]" + NL + ">>> Local node addresses: " + U.addressesAsString(locNode) + NL + ">>> Local ports: " + sb + NL; log.info(str); } if (!ctx.state().clusterState().active()) { U.quietAndInfo(log, ">>> Ignite cluster is not active (limited functionality available). " + "Use control.(sh|bat) script or IgniteCluster interface to activate."); } } /** * Logs out OS information. */ private void ackOsInfo() { assert log != null; if (log.isQuiet()) U.quiet(false, "OS: " + U.osString()); if (log.isInfoEnabled()) { log.info("OS: " + U.osString()); log.info("OS user: " + System.getProperty("user.name")); int jvmPid = U.jvmPid(); log.info("PID: " + (jvmPid == -1 ? "N/A" : jvmPid)); } } /** * Logs out language runtime. */ private void ackLanguageRuntime() { assert log != null; if (log.isQuiet()) U.quiet(false, "VM information: " + U.jdkString()); if (log.isInfoEnabled()) { log.info("Language runtime: " + getLanguage()); log.info("VM information: " + U.jdkString()); log.info("VM total memory: " + U.heapSize(2) + "GB"); } } /** * Logs out node metrics. * * @param dblFmt Decimal format. * @param execSvc Executor service. * @param sysExecSvc System executor service. * @param customExecSvcs Custom named executors. */ private void ackNodeMetrics(DecimalFormat dblFmt, ExecutorService execSvc, ExecutorService sysExecSvc, Map<String, ? extends ExecutorService> customExecSvcs ) { if (!log.isInfoEnabled()) return; try { ClusterMetrics m = cluster().localNode().metrics(); int localCpus = m.getTotalCpus(); double cpuLoadPct = m.getCurrentCpuLoad() * 100; double avgCpuLoadPct = m.getAverageCpuLoad() * 100; double gcPct = m.getCurrentGcCpuLoad() * 100; // Heap params. long heapUsed = m.getHeapMemoryUsed(); long heapMax = m.getHeapMemoryMaximum(); long heapUsedInMBytes = heapUsed / MEGABYTE; long heapCommInMBytes = m.getHeapMemoryCommitted() / MEGABYTE; double freeHeapPct = heapMax > 0 ? ((double)((heapMax - heapUsed) * 100)) / heapMax : -1; int hosts = 0; int servers = 0; int clients = 0; int cpus = 0; try { ClusterMetrics metrics = cluster().metrics(); Collection<ClusterNode> nodes0 = cluster().nodes(); hosts = U.neighborhood(nodes0).size(); servers = cluster().forServers().nodes().size(); clients = cluster().forClients().nodes().size(); cpus = metrics.getTotalCpus(); } catch (IgniteException ignore) { // No-op. } String dataStorageInfo = dataStorageReport(ctx.cache().context().database(), dblFmt, true); String id = U.id8(localNode().id()); AffinityTopologyVersion topVer = ctx.discovery().topologyVersionEx(); ClusterNode locNode = ctx.discovery().localNode(); String networkDetails = ""; if (!F.isEmpty(cfg.getLocalHost())) networkDetails += ", localHost=" + cfg.getLocalHost(); if (locNode instanceof TcpDiscoveryNode) networkDetails += ", discoPort=" + ((TcpDiscoveryNode)locNode).discoveryPort(); if (cfg.getCommunicationSpi() instanceof TcpCommunicationSpi) networkDetails += ", commPort=" + ((TcpCommunicationSpi)cfg.getCommunicationSpi()).boundPort(); SB msg = new SB(); msg.nl() .a("Metrics for local node (to disable set 'metricsLogFrequency' to 0)").nl() .a(" ^-- Node [id=").a(id).a(name() != null ? ", name=" + name() : "").a(", uptime=") .a(getUpTimeFormatted()).a("]").nl() .a(" ^-- Cluster [hosts=").a(hosts).a(", CPUs=").a(cpus).a(", servers=").a(servers) .a(", clients=").a(clients).a(", topVer=").a(topVer.topologyVersion()) .a(", minorTopVer=").a(topVer.minorTopologyVersion()).a("]").nl() .a(" ^-- Network [addrs=").a(locNode.addresses()).a(networkDetails).a("]").nl() .a(" ^-- CPU [CPUs=").a(localCpus).a(", curLoad=").a(dblFmt.format(cpuLoadPct)) .a("%, avgLoad=").a(dblFmt.format(avgCpuLoadPct)).a("%, GC=").a(dblFmt.format(gcPct)).a("%]").nl() .a(" ^-- Heap [used=").a(dblFmt.format(heapUsedInMBytes)) .a("MB, free=").a(dblFmt.format(freeHeapPct)) .a("%, comm=").a(dblFmt.format(heapCommInMBytes)).a("MB]").nl() .a(dataStorageInfo) .a(" ^-- Outbound messages queue [size=").a(m.getOutboundMessagesQueueSize()).a("]").nl() .a(" ^-- ").a(createExecutorDescription("Public thread pool", execSvc)).nl() .a(" ^-- ").a(createExecutorDescription("System thread pool", sysExecSvc)); if (customExecSvcs != null) { for (Map.Entry<String, ? extends ExecutorService> entry : customExecSvcs.entrySet()) msg.nl().a(" ^-- ").a(createExecutorDescription(entry.getKey(), entry.getValue())); } log.info(msg.toString()); ctx.cache().context().database().dumpStatistics(log); } catch (IgniteClientDisconnectedException ignore) { // No-op. } } /** */ public static String dataStorageReport(IgniteCacheDatabaseSharedManager db, boolean includeMemoryStatistics) { return dataStorageReport(db, doubleFormat(), includeMemoryStatistics); } /** */ private static String dataStorageReport(IgniteCacheDatabaseSharedManager db, DecimalFormat dblFmt, boolean includeMemoryStatistics) { // Off-heap params. Collection<DataRegion> regions = db.dataRegions(); SB dataRegionsInfo = new SB(); long loadedPages = 0; long offHeapUsedSummary = 0; long offHeapMaxSummary = 0; long offHeapCommSummary = 0; long pdsUsedSummary = 0; boolean persistenceEnabled = false; if (!F.isEmpty(regions)) { for (DataRegion region : regions) { DataRegionConfiguration regCfg = region.config(); long pagesCnt = region.pageMemory().loadedPages(); long offHeapUsed = region.pageMemory().systemPageSize() * pagesCnt; long offHeapInit = regCfg.getInitialSize(); long offHeapMax = regCfg.getMaxSize(); long offHeapComm = region.memoryMetrics().getOffHeapSize(); long offHeapUsedInMBytes = offHeapUsed / MEGABYTE; long offHeapMaxInMBytes = offHeapMax / MEGABYTE; long offHeapCommInMBytes = offHeapComm / MEGABYTE; long offHeapInitInMBytes = offHeapInit / MEGABYTE; double freeOffHeapPct = offHeapMax > 0 ? ((double)((offHeapMax - offHeapUsed) * 100)) / offHeapMax : -1; offHeapUsedSummary += offHeapUsed; offHeapMaxSummary += offHeapMax; offHeapCommSummary += offHeapComm; loadedPages += pagesCnt; String type = "user"; try { if (region == db.dataRegion(null)) type = "default"; else if (INTERNAL_DATA_REGION_NAMES.contains(regCfg.getName())) type = "internal"; } catch (IgniteCheckedException ice) { // Should never happen ice.printStackTrace(); } dataRegionsInfo.a(" ^-- ") .a(regCfg.getName()).a(" region [type=").a(type) .a(", persistence=").a(regCfg.isPersistenceEnabled()) .a(", lazyAlloc=").a(regCfg.isLazyMemoryAllocation()).a(',').nl() .a(" ... ") .a("initCfg=").a(dblFmt.format(offHeapInitInMBytes)) .a("MB, maxCfg=").a(dblFmt.format(offHeapMaxInMBytes)) .a("MB, usedRam=").a(dblFmt.format(offHeapUsedInMBytes)) .a("MB, freeRam=").a(dblFmt.format(freeOffHeapPct)) .a("%, allocRam=").a(dblFmt.format(offHeapCommInMBytes)).a("MB"); if (regCfg.isPersistenceEnabled()) { long pdsUsed = region.memoryMetrics().getTotalAllocatedSize(); long pdsUsedInMBytes = pdsUsed / MEGABYTE; pdsUsedSummary += pdsUsed; dataRegionsInfo.a(", allocTotal=").a(dblFmt.format(pdsUsedInMBytes)).a("MB"); persistenceEnabled = true; } dataRegionsInfo.a(']').nl(); } } SB info = new SB(); if (includeMemoryStatistics) { long offHeapUsedInMBytes = offHeapUsedSummary / MEGABYTE; long offHeapCommInMBytes = offHeapCommSummary / MEGABYTE; double freeOffHeapPct = offHeapMaxSummary > 0 ? ((double)((offHeapMaxSummary - offHeapUsedSummary) * 100)) / offHeapMaxSummary : -1; info.a(" ^-- Off-heap memory [used=").a(dblFmt.format(offHeapUsedInMBytes)) .a("MB, free=").a(dblFmt.format(freeOffHeapPct)) .a("%, allocated=").a(dblFmt.format(offHeapCommInMBytes)).a("MB]").nl() .a(" ^-- Page memory [pages=").a(loadedPages).a("]").nl(); } info.a(dataRegionsInfo); if (persistenceEnabled) { long pdsUsedMBytes = pdsUsedSummary / MEGABYTE; info.a(" ^-- Ignite persistence [used=").a(dblFmt.format(pdsUsedMBytes)).a("MB]").nl(); } return info.toString(); } /** * @return Language runtime. */ private String getLanguage() { boolean scala = false; boolean groovy = false; boolean clojure = false; for (StackTraceElement elem : Thread.currentThread().getStackTrace()) { String s = elem.getClassName().toLowerCase(); if (s.contains("scala")) { scala = true; break; } else if (s.contains("groovy")) { groovy = true; break; } else if (s.contains("clojure")) { clojure = true; break; } } if (scala) { try (InputStream in = getClass().getResourceAsStream("/library.properties")) { Properties props = new Properties(); if (in != null) props.load(in); return "Scala ver. " + props.getProperty("version.number", "<unknown>"); } catch (Exception ignore) { return "Scala ver. <unknown>"; } } // How to get Groovy and Clojure version at runtime?!? return groovy ? "Groovy" : clojure ? "Clojure" : U.jdkName() + " ver. " + U.jdkVersion(); } /** * Stops Ignite instance. * * @param cancel Whether or not to cancel running jobs. */ public void stop(boolean cancel) { // Make sure that thread stopping grid is not interrupted. boolean interrupted = Thread.interrupted(); try { stop0(cancel); } finally { if (interrupted) Thread.currentThread().interrupt(); } } /** * @return {@code True} if node started shutdown sequence. */ public boolean isStopping() { return stopGuard.get(); } /** * @param cancel Whether or not to cancel running jobs. */ private void stop0(boolean cancel) { gw.compareAndSet(null, new GridKernalGatewayImpl(igniteInstanceName)); GridKernalGateway gw = this.gw.get(); if (stopGuard.compareAndSet(false, true)) { // Only one thread is allowed to perform stop sequence. boolean firstStop = false; GridKernalState state = gw.getState(); if (state == STARTED || state == DISCONNECTED) firstStop = true; else if (state == STARTING) U.warn(log, "Attempt to stop starting grid. This operation " + "cannot be guaranteed to be successful."); if (firstStop) { // Notify lifecycle beans. if (log.isDebugEnabled()) log.debug("Notifying lifecycle beans."); notifyLifecycleBeansEx(LifecycleEventType.BEFORE_NODE_STOP); } List<GridComponent> comps = ctx.components(); // Callback component in reverse order while kernal is still functional // if called in the same thread, at least. for (ListIterator<GridComponent> it = comps.listIterator(comps.size()); it.hasPrevious(); ) { GridComponent comp = it.previous(); try { if (!skipDaemon(comp)) comp.onKernalStop(cancel); } catch (Throwable e) { errOnStop = true; U.error(log, "Failed to pre-stop processor: " + comp, e); if (e instanceof Error) throw e; } } if (starveTask != null) starveTask.close(); if (metricsLogTask != null) metricsLogTask.close(); if (longJVMPauseDetector != null) longJVMPauseDetector.stop(); boolean interrupted = false; while (true) { try { if (gw.tryWriteLock(10)) break; } catch (InterruptedException ignored) { // Preserve interrupt status & ignore. // Note that interrupted flag is cleared. interrupted = true; } } if (interrupted) Thread.currentThread().interrupt(); try { assert gw.getState() == STARTED || gw.getState() == STARTING || gw.getState() == DISCONNECTED; // No more kernal calls from this point on. gw.setState(STOPPING); ctx.cluster().get().clearNodeMap(); if (log.isDebugEnabled()) log.debug("Grid " + (igniteInstanceName == null ? "" : '\'' + igniteInstanceName + "' ") + "is stopping."); } finally { gw.writeUnlock(); } // Stopping cache operations. GridCacheProcessor cache = ctx.cache(); if (cache != null) cache.blockGateways(); // Unregister MBeans. if (!mBeansMgr.unregisterAllMBeans()) errOnStop = true; // Stop components in reverse order. for (ListIterator<GridComponent> it = comps.listIterator(comps.size()); it.hasPrevious(); ) { GridComponent comp = it.previous(); try { if (!skipDaemon(comp)) { comp.stop(cancel); if (log.isDebugEnabled()) log.debug("Component stopped: " + comp); } } catch (Throwable e) { errOnStop = true; U.error(log, "Failed to stop component (ignoring): " + comp, e); if (e instanceof Error) throw (Error)e; } } // Stops lifecycle aware components. U.stopLifecycleAware(log, lifecycleAwares(cfg)); // Lifecycle notification. notifyLifecycleBeansEx(LifecycleEventType.AFTER_NODE_STOP); // Clean internal class/classloader caches to avoid stopped contexts held in memory. U.clearClassCache(); MarshallerExclusions.clearCache(); BinaryEnumCache.clear(); gw.writeLock(); try { gw.setState(STOPPED); } finally { gw.writeUnlock(); } // Ack stop. if (log.isQuiet()) { String nodeName = igniteInstanceName == null ? "" : "name=" + igniteInstanceName + ", "; if (!errOnStop) U.quiet(false, "Ignite node stopped OK [" + nodeName + "uptime=" + X.timeSpan2DHMSM(U.currentTimeMillis() - startTime) + ']'); else U.quiet(true, "Ignite node stopped wih ERRORS [" + nodeName + "uptime=" + X.timeSpan2DHMSM(U.currentTimeMillis() - startTime) + ']'); } if (log.isInfoEnabled()) if (!errOnStop) { String ack = "Ignite ver. " + VER_STR + '#' + BUILD_TSTAMP_STR + "-sha1:" + REV_HASH_STR + " stopped OK"; String dash = U.dash(ack.length()); log.info(NL + NL + ">>> " + dash + NL + ">>> " + ack + NL + ">>> " + dash + NL + (igniteInstanceName == null ? "" : ">>> Ignite instance name: " + igniteInstanceName + NL) + ">>> Grid uptime: " + X.timeSpan2DHMSM(U.currentTimeMillis() - startTime) + NL + NL); } else { String ack = "Ignite ver. " + VER_STR + '#' + BUILD_TSTAMP_STR + "-sha1:" + REV_HASH_STR + " stopped with ERRORS"; String dash = U.dash(ack.length()); log.info(NL + NL + ">>> " + ack + NL + ">>> " + dash + NL + (igniteInstanceName == null ? "" : ">>> Ignite instance name: " + igniteInstanceName + NL) + ">>> Grid uptime: " + X.timeSpan2DHMSM(U.currentTimeMillis() - startTime) + NL + ">>> See log above for detailed error message." + NL + ">>> Note that some errors during stop can prevent grid from" + NL + ">>> maintaining correct topology since this node may have" + NL + ">>> not exited grid properly." + NL + NL); } try { U.onGridStop(); } catch (InterruptedException ignored) { // Preserve interrupt status. Thread.currentThread().interrupt(); } } else { // Proper notification. if (log.isDebugEnabled()) { if (gw.getState() == STOPPED) log.debug("Grid is already stopped. Nothing to do."); else log.debug("Grid is being stopped by another thread. Aborting this stop sequence " + "allowing other thread to finish."); } } } /** * USED ONLY FOR TESTING. * * @param name Cache name. * @param <K> Key type. * @param <V> Value type. * @return Internal cache instance. */ /*@java.test.only*/ public <K, V> GridCacheAdapter<K, V> internalCache(String name) { CU.validateCacheName(name); checkClusterState(); return ctx.cache().internalCache(name); } /** * It's intended for use by internal marshalling implementation only. * * @return Kernal context. */ @Override public GridKernalContext context() { return ctx; } /** * Prints all system properties in debug mode. */ private void ackSystemProperties() { assert log != null; if (log.isDebugEnabled() && S.includeSensitive()) for (Map.Entry<Object, Object> entry : IgniteSystemProperties.snapshot().entrySet()) log.debug("System property [" + entry.getKey() + '=' + entry.getValue() + ']'); } /** * Prints all user attributes in info mode. */ private void logNodeUserAttributes() { assert log != null; if (log.isInfoEnabled()) for (Map.Entry<?, ?> attr : cfg.getUserAttributes().entrySet()) log.info("Local node user attribute [" + attr.getKey() + '=' + attr.getValue() + ']'); } /** * Prints all environment variables in debug mode. */ private void ackEnvironmentVariables() { assert log != null; if (log.isDebugEnabled()) for (Map.Entry<?, ?> envVar : System.getenv().entrySet()) log.debug("Environment variable [" + envVar.getKey() + '=' + envVar.getValue() + ']'); } /** * Acks daemon mode status. */ private void ackDaemon() { assert log != null; if (log.isInfoEnabled()) log.info("Daemon mode: " + (isDaemon() ? "on" : "off")); } /** * @return {@code True} is this node is daemon. */ private boolean isDaemon() { assert cfg != null; return cfg.isDaemon() || IgniteSystemProperties.getBoolean(IGNITE_DAEMON); } /** * Whether or not remote JMX management is enabled for this node. Remote JMX management is enabled when the * following system property is set: <ul> <li>{@code com.sun.management.jmxremote}</li> </ul> * * @return {@code True} if remote JMX management is enabled - {@code false} otherwise. */ @Override public boolean isJmxRemoteEnabled() { return System.getProperty("com.sun.management.jmxremote") != null; } /** * Whether or not node restart is enabled. Node restart us supported when this node was started with {@code * bin/ignite.{sh|bat}} script using {@code -r} argument. Node can be programmatically restarted using {@link * Ignition#restart(boolean)}} method. * * @return {@code True} if restart mode is enabled, {@code false} otherwise. * @see Ignition#restart(boolean) */ @Override public boolean isRestartEnabled() { return System.getProperty(IGNITE_SUCCESS_FILE) != null; } /** * Prints all configuration properties in info mode and SPIs in debug mode. */ private void ackSpis() { assert log != null; if (log.isDebugEnabled()) { log.debug("+-------------+"); log.debug("START SPI LIST:"); log.debug("+-------------+"); log.debug("Grid checkpoint SPI : " + Arrays.toString(cfg.getCheckpointSpi())); log.debug("Grid collision SPI : " + cfg.getCollisionSpi()); log.debug("Grid communication SPI : " + cfg.getCommunicationSpi()); log.debug("Grid deployment SPI : " + cfg.getDeploymentSpi()); log.debug("Grid discovery SPI : " + cfg.getDiscoverySpi()); log.debug("Grid event storage SPI : " + cfg.getEventStorageSpi()); log.debug("Grid failover SPI : " + Arrays.toString(cfg.getFailoverSpi())); log.debug("Grid load balancing SPI : " + Arrays.toString(cfg.getLoadBalancingSpi())); } } /** * Acknowledge that the rebalance configuration properties are setted correctly. * * @throws IgniteCheckedException If rebalance configuration validation fail. */ private void ackRebalanceConfiguration() throws IgniteCheckedException { if (cfg.isClientMode()) { if (cfg.getRebalanceThreadPoolSize() != IgniteConfiguration.DFLT_REBALANCE_THREAD_POOL_SIZE) U.warn(log, "Setting the rebalance pool size has no effect on the client mode"); } else { if (cfg.getRebalanceThreadPoolSize() < 1) throw new IgniteCheckedException("Rebalance thread pool size minimal allowed value is 1. " + "Change IgniteConfiguration.rebalanceThreadPoolSize property before next start."); if (cfg.getRebalanceBatchesPrefetchCount() < 1) throw new IgniteCheckedException("Rebalance batches prefetch count minimal allowed value is 1. " + "Change IgniteConfiguration.rebalanceBatchesPrefetchCount property before next start."); if (cfg.getRebalanceBatchSize() <= 0) throw new IgniteCheckedException("Rebalance batch size must be greater than zero. " + "Change IgniteConfiguration.rebalanceBatchSize property before next start."); if (cfg.getRebalanceThrottle() < 0) throw new IgniteCheckedException("Rebalance throttle can't have negative value. " + "Change IgniteConfiguration.rebalanceThrottle property before next start."); if (cfg.getRebalanceTimeout() < 0) throw new IgniteCheckedException("Rebalance message timeout can't have negative value. " + "Change IgniteConfiguration.rebalanceTimeout property before next start."); for (CacheConfiguration ccfg : cfg.getCacheConfiguration()) { if (ccfg.getRebalanceBatchesPrefetchCount() < 1) throw new IgniteCheckedException("Rebalance batches prefetch count minimal allowed value is 1. " + "Change CacheConfiguration.rebalanceBatchesPrefetchCount property before next start. " + "[cache=" + ccfg.getName() + "]"); } } } /** * Acknowledge the Ignite configuration related to the data storage. */ private void ackMemoryConfiguration() { DataStorageConfiguration memCfg = cfg.getDataStorageConfiguration(); if (memCfg == null) return; U.log(log, "System cache's DataRegion size is configured to " + (memCfg.getSystemRegionInitialSize() / (1024 * 1024)) + " MB. " + "Use DataStorageConfiguration.systemRegionInitialSize property to change the setting."); } /** * Acknowledge all caches configurations presented in the IgniteConfiguration. */ private void ackCacheConfiguration() { CacheConfiguration[] cacheCfgs = cfg.getCacheConfiguration(); if (cacheCfgs == null || cacheCfgs.length == 0) U.warn(log, "Cache is not configured - in-memory data grid is off."); else { SB sb = new SB(); HashMap<String, ArrayList<String>> memPlcNamesMapping = new HashMap<>(); for (CacheConfiguration c : cacheCfgs) { String cacheName = U.maskName(c.getName()); String memPlcName = c.getDataRegionName(); if (CU.isSystemCache(cacheName)) memPlcName = "sysMemPlc"; else if (memPlcName == null && cfg.getDataStorageConfiguration() != null) memPlcName = cfg.getDataStorageConfiguration().getDefaultDataRegionConfiguration().getName(); if (!memPlcNamesMapping.containsKey(memPlcName)) memPlcNamesMapping.put(memPlcName, new ArrayList<String>()); ArrayList<String> cacheNames = memPlcNamesMapping.get(memPlcName); cacheNames.add(cacheName); } for (Map.Entry<String, ArrayList<String>> e : memPlcNamesMapping.entrySet()) { sb.a("in '").a(e.getKey()).a("' dataRegion: ["); for (String s : e.getValue()) sb.a("'").a(s).a("', "); sb.d(sb.length() - 2, sb.length()).a("], "); } U.log(log, "Configured caches [" + sb.d(sb.length() - 2, sb.length()).toString() + ']'); } } /** * Acknowledge configuration related to the peer class loading. */ private void ackP2pConfiguration() { assert cfg != null; if (cfg.isPeerClassLoadingEnabled()) U.warn( log, "Peer class loading is enabled (disable it in production for performance and " + "deployment consistency reasons)"); } /** * Prints security status. */ private void ackSecurity() { assert log != null; U.quietAndInfo(log, "Security status [authentication=" + onOff(ctx.security().enabled()) + ", sandbox=" + onOff(ctx.security().sandbox().enabled()) + ", tls/ssl=" + onOff(ctx.config().getSslContextFactory() != null) + ']'); } /** * Prints out VM arguments and IGNITE_HOME in info mode. * * @param rtBean Java runtime bean. */ private void ackVmArguments(RuntimeMXBean rtBean) { assert log != null; // Ack IGNITE_HOME and VM arguments. if (log.isInfoEnabled() && S.includeSensitive()) { log.info("IGNITE_HOME=" + cfg.getIgniteHome()); log.info("VM arguments: " + rtBean.getInputArguments()); } } /** * Prints out class paths in debug mode. * * @param rtBean Java runtime bean. */ private void ackClassPaths(RuntimeMXBean rtBean) { assert log != null; // Ack all class paths. if (log.isDebugEnabled()) { try { log.debug("Boot class path: " + rtBean.getBootClassPath()); log.debug("Class path: " + rtBean.getClassPath()); log.debug("Library path: " + rtBean.getLibraryPath()); } catch (Exception ignore) { // No-op: ignore for Java 9+ and non-standard JVMs. } } } /** * Prints warning if 'java.net.preferIPv4Stack=true' is not set. */ private void ackIPv4StackFlagIsSet() { boolean preferIPv4 = Boolean.valueOf(System.getProperty("java.net.preferIPv4Stack")); if (!preferIPv4) { assert log != null; U.quietAndWarn(log, "Please set system property '-Djava.net.preferIPv4Stack=true' " + "to avoid possible problems in mixed environments."); } } /** * @param cfg Ignite configuration to use. * @return Components provided in configuration which can implement {@link LifecycleAware} interface. */ private Iterable<Object> lifecycleAwares(IgniteConfiguration cfg) { Collection<Object> objs = new ArrayList<>(); if (cfg.getLifecycleBeans() != null) Collections.addAll(objs, cfg.getLifecycleBeans()); if (cfg.getSegmentationResolvers() != null) Collections.addAll(objs, cfg.getSegmentationResolvers()); if (cfg.getConnectorConfiguration() != null) { objs.add(cfg.getConnectorConfiguration().getMessageInterceptor()); objs.add(cfg.getConnectorConfiguration().getSslContextFactory()); } objs.add(cfg.getMarshaller()); objs.add(cfg.getGridLogger()); objs.add(cfg.getMBeanServer()); if (cfg.getCommunicationFailureResolver() != null) objs.add(cfg.getCommunicationFailureResolver()); return objs; } /** {@inheritDoc} */ @Override public IgniteConfiguration configuration() { return cfg; } /** {@inheritDoc} */ @Override public IgniteLogger log() { return cfg.getGridLogger(); } /** {@inheritDoc} */ @Override public boolean removeCheckpoint(String key) { A.notNull(key, "key"); guard(); try { checkClusterState(); return ctx.checkpoint().removeCheckpoint(key); } finally { unguard(); } } /** {@inheritDoc} */ @Override public boolean pingNode(String nodeId) { A.notNull(nodeId, "nodeId"); return cluster().pingNode(UUID.fromString(nodeId)); } /** {@inheritDoc} */ @Override public void undeployTaskFromGrid(String taskName) throws JMException { A.notNull(taskName, "taskName"); try { compute().undeployTask(taskName); } catch (IgniteException e) { throw U.jmException(e); } } /** {@inheritDoc} */ @Override public String executeTask(String taskName, String arg) throws JMException { try { return compute().execute(taskName, arg); } catch (IgniteException e) { throw U.jmException(e); } } /** {@inheritDoc} */ @Override public boolean pingNodeByAddress(String host) { guard(); try { for (ClusterNode n : cluster().nodes()) if (n.addresses().contains(host)) return ctx.discovery().pingNode(n.id()); return false; } catch (IgniteCheckedException e) { throw U.convertException(e); } finally { unguard(); } } /** {@inheritDoc} */ @Override public boolean eventUserRecordable(int type) { guard(); try { return ctx.event().isUserRecordable(type); } finally { unguard(); } } /** {@inheritDoc} */ @Override public boolean allEventsUserRecordable(int[] types) { A.notNull(types, "types"); guard(); try { return ctx.event().isAllUserRecordable(types); } finally { unguard(); } } /** {@inheritDoc} */ @Override public IgniteTransactions transactions() { guard(); try { checkClusterState(); return ctx.cache().transactions(); } finally { unguard(); } } /** * @param name Cache name. * @return Ignite internal cache instance related to the given name. */ public <K, V> IgniteInternalCache<K, V> getCache(String name) { CU.validateCacheName(name); guard(); try { checkClusterState(); return ctx.cache().publicCache(name); } finally { unguard(); } } /** {@inheritDoc} */ @Override public <K, V> IgniteCache<K, V> cache(String name) { CU.validateCacheName(name); guard(); try { checkClusterState(); return ctx.cache().publicJCache(name, false, true); } catch (IgniteCheckedException e) { throw CU.convertToCacheException(e); } finally { unguard(); } } /** {@inheritDoc} */ @Override public <K, V> IgniteCache<K, V> createCache(CacheConfiguration<K, V> cacheCfg) { A.notNull(cacheCfg, "cacheCfg"); CU.validateNewCacheName(cacheCfg.getName()); guard(); try { checkClusterState(); ctx.cache().dynamicStartCache(cacheCfg, cacheCfg.getName(), null, true, true, true).get(); return ctx.cache().publicJCache(cacheCfg.getName()); } catch (IgniteCheckedException e) { throw CU.convertToCacheException(e); } finally { unguard(); } } /** {@inheritDoc} */ @Override public Collection<IgniteCache> createCaches(Collection<CacheConfiguration> cacheCfgs) { A.notNull(cacheCfgs, "cacheCfgs"); CU.validateConfigurationCacheNames(cacheCfgs); guard(); try { checkClusterState(); ctx.cache().dynamicStartCaches(cacheCfgs, true, true, false).get(); List<IgniteCache> createdCaches = new ArrayList<>(cacheCfgs.size()); for (CacheConfiguration cacheCfg : cacheCfgs) createdCaches.add(ctx.cache().publicJCache(cacheCfg.getName())); return createdCaches; } catch (IgniteCheckedException e) { throw CU.convertToCacheException(e); } finally { unguard(); } } /** {@inheritDoc} */ @Override public <K, V> IgniteCache<K, V> createCache(String cacheName) { CU.validateNewCacheName(cacheName); guard(); try { checkClusterState(); ctx.cache().createFromTemplate(cacheName).get(); return ctx.cache().publicJCache(cacheName); } catch (IgniteCheckedException e) { throw CU.convertToCacheException(e); } finally { unguard(); } } /** {@inheritDoc} */ @Override public <K, V> IgniteCache<K, V> getOrCreateCache(CacheConfiguration<K, V> cacheCfg) { return getOrCreateCache0(cacheCfg, false).get1(); } /** {@inheritDoc} */ @Override public <K, V> IgniteBiTuple<IgniteCache<K, V>, Boolean> getOrCreateCache0( CacheConfiguration<K, V> cacheCfg, boolean sql) { A.notNull(cacheCfg, "cacheCfg"); String cacheName = cacheCfg.getName(); CU.validateNewCacheName(cacheName); guard(); try { checkClusterState(); Boolean res = false; IgniteCacheProxy<K, V> cache = ctx.cache().publicJCache(cacheName, false, true); if (cache == null) { res = sql ? ctx.cache().dynamicStartSqlCache(cacheCfg).get() : ctx.cache().dynamicStartCache(cacheCfg, cacheName, null, false, true, true).get(); return new IgniteBiTuple<>(ctx.cache().publicJCache(cacheName), res); } else return new IgniteBiTuple<>(cache, res); } catch (IgniteCheckedException e) { throw CU.convertToCacheException(e); } finally { unguard(); } } /** {@inheritDoc} */ @Override public Collection<IgniteCache> getOrCreateCaches(Collection<CacheConfiguration> cacheCfgs) { A.notNull(cacheCfgs, "cacheCfgs"); CU.validateConfigurationCacheNames(cacheCfgs); guard(); try { checkClusterState(); ctx.cache().dynamicStartCaches(cacheCfgs, false, true, false).get(); List<IgniteCache> createdCaches = new ArrayList<>(cacheCfgs.size()); for (CacheConfiguration cacheCfg : cacheCfgs) createdCaches.add(ctx.cache().publicJCache(cacheCfg.getName())); return createdCaches; } catch (IgniteCheckedException e) { throw CU.convertToCacheException(e); } finally { unguard(); } } /** {@inheritDoc} */ @Override public <K, V> IgniteCache<K, V> createCache( CacheConfiguration<K, V> cacheCfg, NearCacheConfiguration<K, V> nearCfg ) { A.notNull(cacheCfg, "cacheCfg"); CU.validateNewCacheName(cacheCfg.getName()); A.notNull(nearCfg, "nearCfg"); guard(); try { checkClusterState(); ctx.cache().dynamicStartCache(cacheCfg, cacheCfg.getName(), nearCfg, true, true, true).get(); return ctx.cache().publicJCache(cacheCfg.getName()); } catch (IgniteCheckedException e) { throw CU.convertToCacheException(e); } finally { unguard(); } } /** {@inheritDoc} */ @Override public <K, V> IgniteCache<K, V> getOrCreateCache(CacheConfiguration<K, V> cacheCfg, NearCacheConfiguration<K, V> nearCfg) { A.notNull(cacheCfg, "cacheCfg"); CU.validateNewCacheName(cacheCfg.getName()); A.notNull(nearCfg, "nearCfg"); guard(); try { checkClusterState(); IgniteInternalCache<Object, Object> cache = ctx.cache().cache(cacheCfg.getName()); if (cache == null) { ctx.cache().dynamicStartCache(cacheCfg, cacheCfg.getName(), nearCfg, false, true, true).get(); } else { if (cache.configuration().getNearConfiguration() == null) { ctx.cache().dynamicStartCache(cacheCfg, cacheCfg.getName(), nearCfg, false, true, true).get(); } } return ctx.cache().publicJCache(cacheCfg.getName()); } catch (IgniteCheckedException e) { throw CU.convertToCacheException(e); } finally { unguard(); } } /** {@inheritDoc} */ @Override public <K, V> IgniteCache<K, V> createNearCache(String cacheName, NearCacheConfiguration<K, V> nearCfg) { CU.validateNewCacheName(cacheName); A.notNull(nearCfg, "nearCfg"); guard(); try { checkClusterState(); ctx.cache().dynamicStartCache(null, cacheName, nearCfg, true, true, true).get(); IgniteCacheProxy<K, V> cache = ctx.cache().publicJCache(cacheName); checkNearCacheStarted(cache); return cache; } catch (IgniteCheckedException e) { throw CU.convertToCacheException(e); } finally { unguard(); } } /** {@inheritDoc} */ @Override public <K, V> IgniteCache<K, V> getOrCreateNearCache(String cacheName, NearCacheConfiguration<K, V> nearCfg) { CU.validateNewCacheName(cacheName); A.notNull(nearCfg, "nearCfg"); guard(); try { checkClusterState(); IgniteInternalCache<Object, Object> internalCache = ctx.cache().cache(cacheName); if (internalCache == null) { ctx.cache().dynamicStartCache(null, cacheName, nearCfg, false, true, true).get(); } else { if (internalCache.configuration().getNearConfiguration() == null) { ctx.cache().dynamicStartCache(null, cacheName, nearCfg, false, true, true).get(); } } IgniteCacheProxy<K, V> cache = ctx.cache().publicJCache(cacheName); checkNearCacheStarted(cache); return cache; } catch (IgniteCheckedException e) { throw CU.convertToCacheException(e); } finally { unguard(); } } /** * @param cache Ignite cache instance to check. * @throws IgniteCheckedException If cache without near cache was already started. */ private void checkNearCacheStarted(IgniteCacheProxy<?, ?> cache) throws IgniteCheckedException { if (!cache.context().isNear()) throw new IgniteCheckedException("Failed to start near cache " + "(a cache with the same name without near cache is already started)"); } /** {@inheritDoc} */ @Override public void destroyCache(String cacheName) { destroyCache0(cacheName, false); } /** {@inheritDoc} */ @Override public boolean destroyCache0(String cacheName, boolean sql) throws CacheException { CU.validateCacheName(cacheName); IgniteInternalFuture<Boolean> stopFut = destroyCacheAsync(cacheName, sql, true); try { return stopFut.get(); } catch (IgniteCheckedException e) { throw CU.convertToCacheException(e); } } /** {@inheritDoc} */ @Override public void destroyCaches(Collection<String> cacheNames) { CU.validateCacheNames(cacheNames); IgniteInternalFuture stopFut = destroyCachesAsync(cacheNames, true); try { stopFut.get(); } catch (IgniteCheckedException e) { throw CU.convertToCacheException(e); } } /** * @param cacheName Cache name. * @param sql If the cache needs to be destroyed only if it was created by SQL {@code CREATE TABLE} command. * @param checkThreadTx If {@code true} checks that current thread does not have active transactions. * @return Ignite future. */ public IgniteInternalFuture<Boolean> destroyCacheAsync(String cacheName, boolean sql, boolean checkThreadTx) { CU.validateCacheName(cacheName); guard(); try { checkClusterState(); return ctx.cache().dynamicDestroyCache(cacheName, sql, checkThreadTx, false, null); } finally { unguard(); } } /** * @param cacheNames Collection of cache names. * @param checkThreadTx If {@code true} checks that current thread does not have active transactions. * @return Ignite future which will be completed when cache is destored. */ public IgniteInternalFuture<?> destroyCachesAsync(Collection<String> cacheNames, boolean checkThreadTx) { CU.validateCacheNames(cacheNames); guard(); try { checkClusterState(); return ctx.cache().dynamicDestroyCaches(cacheNames, checkThreadTx); } finally { unguard(); } } /** {@inheritDoc} */ @Override public <K, V> IgniteCache<K, V> getOrCreateCache(String cacheName) { CU.validateNewCacheName(cacheName); guard(); try { checkClusterState(); IgniteCacheProxy<K, V> cache = ctx.cache().publicJCache(cacheName, false, true); if (cache == null) { ctx.cache().getOrCreateFromTemplate(cacheName, true).get(); return ctx.cache().publicJCache(cacheName); } return cache; } catch (IgniteCheckedException e) { throw CU.convertToCacheException(e); } finally { unguard(); } } /** * @param cacheName Cache name. * @param templateName Template name. * @param cfgOverride Cache config properties to override. * @param checkThreadTx If {@code true} checks that current thread does not have active transactions. * @return Future that will be completed when cache is deployed. */ public IgniteInternalFuture<?> getOrCreateCacheAsync(String cacheName, String templateName, CacheConfigurationOverride cfgOverride, boolean checkThreadTx) { CU.validateNewCacheName(cacheName); guard(); try { checkClusterState(); if (ctx.cache().cache(cacheName) == null) return ctx.cache().getOrCreateFromTemplate(cacheName, templateName, cfgOverride, checkThreadTx); return new GridFinishedFuture<>(); } finally { unguard(); } } /** {@inheritDoc} */ @Override public <K, V> void addCacheConfiguration(CacheConfiguration<K, V> cacheCfg) { A.notNull(cacheCfg, "cacheCfg"); CU.validateNewCacheName(cacheCfg.getName()); guard(); try { checkClusterState(); ctx.cache().addCacheConfiguration(cacheCfg); } catch (IgniteCheckedException e) { throw CU.convertToCacheException(e); } finally { unguard(); } } /** * @return Collection of public cache instances. */ public Collection<IgniteCacheProxy<?, ?>> caches() { guard(); try { checkClusterState(); return ctx.cache().publicCaches(); } finally { unguard(); } } /** {@inheritDoc} */ @Override public Collection<String> cacheNames() { guard(); try { checkClusterState(); return ctx.cache().publicCacheNames(); } finally { unguard(); } } /** {@inheritDoc} */ @Override public <K extends GridCacheUtilityKey, V> IgniteInternalCache<K, V> utilityCache() { guard(); try { checkClusterState(); return ctx.cache().utilityCache(); } finally { unguard(); } } /** {@inheritDoc} */ @Override public <K, V> IgniteInternalCache<K, V> cachex(String name) { CU.validateCacheName(name); guard(); try { checkClusterState(); return ctx.cache().cache(name); } finally { unguard(); } } /** {@inheritDoc} */ @Override public Collection<IgniteInternalCache<?, ?>> cachesx( IgnitePredicate<? super IgniteInternalCache<?, ?>>[] p) { guard(); try { checkClusterState(); return F.retain(ctx.cache().caches(), true, p); } finally { unguard(); } } /** {@inheritDoc} */ @Override public <K, V> IgniteDataStreamer<K, V> dataStreamer(String cacheName) { CU.validateCacheName(cacheName); guard(); try { checkClusterState(); return ctx.<K, V>dataStream().dataStreamer(cacheName); } finally { unguard(); } } /** {@inheritDoc} */ @Override public <T extends IgnitePlugin> T plugin(String name) throws PluginNotFoundException { guard(); try { checkClusterState(); return (T)ctx.pluginProvider(name).plugin(); } finally { unguard(); } } /** {@inheritDoc} */ @Override public IgniteBinary binary() { checkClusterState(); IgniteCacheObjectProcessor objProc = ctx.cacheObjects(); return objProc.binary(); } /** {@inheritDoc} */ @Override public IgniteProductVersion version() { return VER; } /** {@inheritDoc} */ @Override public String latestVersion() { ctx.gateway().readLock(); try { return ctx.cluster().latestVersion(); } finally { ctx.gateway().readUnlock(); } } /** {@inheritDoc} */ @Override public IgniteScheduler scheduler() { return scheduler; } /** {@inheritDoc} */ @Override public void close() throws IgniteException { Ignition.stop(igniteInstanceName, true); } /** {@inheritDoc} */ @Override public <K> Affinity<K> affinity(String cacheName) { CU.validateCacheName(cacheName); checkClusterState(); GridCacheAdapter<K, ?> cache = ctx.cache().internalCache(cacheName); if (cache != null) return cache.affinity(); return ctx.affinity().affinityProxy(cacheName); } /** {@inheritDoc} */ @Override public boolean active() { guard(); try { return context().state().publicApiActiveState(true); } finally { unguard(); } } /** {@inheritDoc} */ @Override public void active(boolean active) { cluster().active(active); } /** */ private Collection<BaselineNode> baselineNodes() { Collection<ClusterNode> srvNodes = cluster().forServers().nodes(); ArrayList baselineNodes = new ArrayList(srvNodes.size()); for (ClusterNode clN : srvNodes) baselineNodes.add(clN); return baselineNodes; } /** {@inheritDoc} */ @Override public void resetLostPartitions(Collection<String> cacheNames) { CU.validateCacheNames(cacheNames); guard(); try { ctx.cache().resetCacheState(cacheNames.isEmpty() ? ctx.cache().cacheNames() : cacheNames).get(); } catch (IgniteCheckedException e) { throw U.convertException(e); } finally { unguard(); } } /** {@inheritDoc} */ @Override public Collection<DataRegionMetrics> dataRegionMetrics() { guard(); try { return ctx.cache().context().database().memoryMetrics(); } finally { unguard(); } } /** {@inheritDoc} */ @Nullable @Override public DataRegionMetrics dataRegionMetrics(String memPlcName) { guard(); try { return ctx.cache().context().database().memoryMetrics(memPlcName); } finally { unguard(); } } /** {@inheritDoc} */ @Override public DataStorageMetrics dataStorageMetrics() { guard(); try { return ctx.cache().context().database().persistentStoreMetrics(); } finally { unguard(); } } /** {@inheritDoc} */ @Override public @NotNull TracingConfigurationManager tracingConfiguration() { guard(); try { return ctx.tracing().configuration(); } finally { unguard(); } } /** {@inheritDoc} */ @Override public IgniteEncryption encryption() { return ctx.encryption(); } /** {@inheritDoc} */ @Override public IgniteSnapshot snapshot() { return ctx.cache().context().snapshotMgr(); } /** {@inheritDoc} */ @Override public Collection<MemoryMetrics> memoryMetrics() { return DataRegionMetricsAdapter.collectionOf(dataRegionMetrics()); } /** {@inheritDoc} */ @Nullable @Override public MemoryMetrics memoryMetrics(String memPlcName) { return DataRegionMetricsAdapter.valueOf(dataRegionMetrics(memPlcName)); } /** {@inheritDoc} */ @Override public PersistenceMetrics persistentStoreMetrics() { return DataStorageMetricsAdapter.valueOf(dataStorageMetrics()); } /** {@inheritDoc} */ @Nullable @Override public IgniteAtomicSequence atomicSequence(String name, long initVal, boolean create) { return atomicSequence(name, null, initVal, create); } /** {@inheritDoc} */ @Nullable @Override public IgniteAtomicSequence atomicSequence(String name, AtomicConfiguration cfg, long initVal, boolean create) throws IgniteException { guard(); try { checkClusterState(); return ctx.dataStructures().sequence(name, cfg, initVal, create); } catch (IgniteCheckedException e) { throw U.convertException(e); } finally { unguard(); } } /** {@inheritDoc} */ @Nullable @Override public IgniteAtomicLong atomicLong(String name, long initVal, boolean create) { return atomicLong(name, null, initVal, create); } /** {@inheritDoc} */ @Nullable @Override public IgniteAtomicLong atomicLong(String name, AtomicConfiguration cfg, long initVal, boolean create) throws IgniteException { guard(); try { checkClusterState(); return ctx.dataStructures().atomicLong(name, cfg, initVal, create); } catch (IgniteCheckedException e) { throw U.convertException(e); } finally { unguard(); } } /** {@inheritDoc} */ @Nullable @Override public <T> IgniteAtomicReference<T> atomicReference( String name, @Nullable T initVal, boolean create ) { return atomicReference(name, null, initVal, create); } /** {@inheritDoc} */ @Override public <T> IgniteAtomicReference<T> atomicReference(String name, AtomicConfiguration cfg, @Nullable T initVal, boolean create) throws IgniteException { guard(); try { checkClusterState(); return ctx.dataStructures().atomicReference(name, cfg, initVal, create); } catch (IgniteCheckedException e) { throw U.convertException(e); } finally { unguard(); } } /** {@inheritDoc} */ @Nullable @Override public <T, S> IgniteAtomicStamped<T, S> atomicStamped(String name, @Nullable T initVal, @Nullable S initStamp, boolean create) { return atomicStamped(name, null, initVal, initStamp, create); } /** {@inheritDoc} */ @Override public <T, S> IgniteAtomicStamped<T, S> atomicStamped(String name, AtomicConfiguration cfg, @Nullable T initVal, @Nullable S initStamp, boolean create) throws IgniteException { guard(); try { checkClusterState(); return ctx.dataStructures().atomicStamped(name, cfg, initVal, initStamp, create); } catch (IgniteCheckedException e) { throw U.convertException(e); } finally { unguard(); } } /** {@inheritDoc} */ @Nullable @Override public IgniteCountDownLatch countDownLatch(String name, int cnt, boolean autoDel, boolean create) { guard(); try { checkClusterState(); return ctx.dataStructures().countDownLatch(name, null, cnt, autoDel, create); } catch (IgniteCheckedException e) { throw U.convertException(e); } finally { unguard(); } } /** {@inheritDoc} */ @Nullable @Override public IgniteSemaphore semaphore( String name, int cnt, boolean failoverSafe, boolean create ) { guard(); try { checkClusterState(); return ctx.dataStructures().semaphore(name, null, cnt, failoverSafe, create); } catch (IgniteCheckedException e) { throw U.convertException(e); } finally { unguard(); } } /** {@inheritDoc} */ @Nullable @Override public IgniteLock reentrantLock( String name, boolean failoverSafe, boolean fair, boolean create ) { guard(); try { checkClusterState(); return ctx.dataStructures().reentrantLock(name, null, failoverSafe, fair, create); } catch (IgniteCheckedException e) { throw U.convertException(e); } finally { unguard(); } } /** {@inheritDoc} */ @Nullable @Override public <T> IgniteQueue<T> queue(String name, int cap, CollectionConfiguration cfg) { guard(); try { checkClusterState(); return ctx.dataStructures().queue(name, null, cap, cfg); } catch (IgniteCheckedException e) { throw U.convertException(e); } finally { unguard(); } } /** {@inheritDoc} */ @Nullable @Override public <T> IgniteSet<T> set(String name, CollectionConfiguration cfg) { guard(); try { checkClusterState(); return ctx.dataStructures().set(name, null, cfg); } catch (IgniteCheckedException e) { throw U.convertException(e); } finally { unguard(); } } /** * The {@code ctx.gateway().readLock()} is used underneath. */ private void guard() { assert ctx != null; ctx.gateway().readLock(); } /** * The {@code ctx.gateway().readUnlock()} is used underneath. */ private void unguard() { assert ctx != null; ctx.gateway().readUnlock(); } /** * Validate operation on cluster. Check current cluster state. * * @throws IgniteException If cluster in inActive state. */ private void checkClusterState() throws IgniteException { if (!ctx.state().publicApiActiveState(true)) { throw new IgniteException("Can not perform the operation because the cluster is inactive. Note, that " + "the cluster is considered inactive by default if Ignite Persistent Store is used to let all the nodes " + "join the cluster. To activate the cluster call Ignite.active(true)."); } } /** * Method is responsible for handling the {@link EventType#EVT_CLIENT_NODE_DISCONNECTED} event. Notify all the * GridComponents that the such even has been occurred (e.g. if the local client node disconnected from the cluster * components will be notified with a future which will be completed when the client is reconnected). */ public void onDisconnected() { Throwable err = null; reconnectState.waitPreviousReconnect(); GridFutureAdapter<?> reconnectFut = ctx.gateway().onDisconnected(); if (reconnectFut == null) { assert ctx.gateway().getState() != STARTED : ctx.gateway().getState(); return; } IgniteFutureImpl<?> curFut = (IgniteFutureImpl<?>)ctx.cluster().get().clientReconnectFuture(); IgniteFuture<?> userFut; // In case of previous reconnect did not finish keep reconnect future. if (curFut != null && curFut.internalFuture() == reconnectFut) userFut = curFut; else { userFut = new IgniteFutureImpl<>(reconnectFut); ctx.cluster().get().clientReconnectFuture(userFut); } ctx.disconnected(true); List<GridComponent> comps = ctx.components(); for (ListIterator<GridComponent> it = comps.listIterator(comps.size()); it.hasPrevious(); ) { GridComponent comp = it.previous(); try { if (!skipDaemon(comp)) comp.onDisconnected(userFut); } catch (IgniteCheckedException e) { err = e; } catch (Throwable e) { err = e; if (e instanceof Error) throw e; } } for (GridCacheContext cctx : ctx.cache().context().cacheContexts()) { cctx.gate().writeLock(); cctx.gate().writeUnlock(); } ctx.gateway().writeLock(); ctx.gateway().writeUnlock(); if (err != null) { reconnectFut.onDone(err); U.error(log, "Failed to reconnect, will stop node", err); close(); } } /** * @param clusterRestarted {@code True} if all cluster nodes restarted while client was disconnected. */ @SuppressWarnings("unchecked") public void onReconnected(final boolean clusterRestarted) { Throwable err = null; try { ctx.disconnected(false); GridCompoundFuture curReconnectFut = reconnectState.curReconnectFut = new GridCompoundFuture<>(); reconnectState.reconnectDone = new GridFutureAdapter<>(); for (GridComponent comp : ctx.components()) { IgniteInternalFuture<?> fut = comp.onReconnected(clusterRestarted); if (fut != null) curReconnectFut.add(fut); } curReconnectFut.add(ctx.cache().context().exchange().reconnectExchangeFuture()); curReconnectFut.markInitialized(); final GridFutureAdapter reconnectDone = reconnectState.reconnectDone; curReconnectFut.listen(new CI1<IgniteInternalFuture<?>>() { @Override public void apply(IgniteInternalFuture<?> fut) { try { Object res = fut.get(); if (res == STOP_RECONNECT) return; ctx.gateway().onReconnected(); reconnectState.firstReconnectFut.onDone(); } catch (IgniteCheckedException e) { if (!X.hasCause(e, IgniteNeedReconnectException.class, IgniteClientDisconnectedCheckedException.class, IgniteInterruptedCheckedException.class)) { U.error(log, "Failed to reconnect, will stop node.", e); reconnectState.firstReconnectFut.onDone(e); new Thread(() -> { U.error(log, "Stopping the node after a failed reconnect attempt."); close(); }, "node-stopper").start(); } else { assert ctx.discovery().reconnectSupported(); U.error(log, "Failed to finish reconnect, will retry [locNodeId=" + ctx.localNodeId() + ", err=" + e.getMessage() + ']'); } } finally { reconnectDone.onDone(); } } }); } catch (IgniteCheckedException e) { err = e; } catch (Throwable e) { err = e; if (e instanceof Error) throw e; } if (err != null) { U.error(log, "Failed to reconnect, will stop node", err); if (!X.hasCause(err, NodeStoppingException.class)) close(); } } /** * Creates optional component. * * @param cls Component interface. * @param ctx Kernal context. * @return Created component. * @throws IgniteCheckedException If failed to create component. */ private static <T extends GridComponent> T createComponent(Class<T> cls, GridKernalContext ctx) throws IgniteCheckedException { assert cls.isInterface() : cls; T comp = ctx.plugins().createComponent(cls); if (comp != null) return comp; if (cls.equals(IgniteCacheObjectProcessor.class)) return (T)new CacheObjectBinaryProcessorImpl(ctx); if (cls.equals(DiscoveryNodeValidationProcessor.class)) return (T)new OsDiscoveryNodeValidationProcessor(ctx); if (cls.equals(IGridClusterStateProcessor.class)) return (T)new GridClusterStateProcessor(ctx); if (cls.equals(GridSecurityProcessor.class)) return null; if (cls.equals(IgniteRestProcessor.class)) return (T)new GridRestProcessor(ctx); Class<T> implCls = null; try { String clsName; // Handle special case for PlatformProcessor if (cls.equals(PlatformProcessor.class)) clsName = ctx.config().getPlatformConfiguration() == null ? PlatformNoopProcessor.class.getName() : cls.getName() + "Impl"; else clsName = componentClassName(cls); implCls = (Class<T>)Class.forName(clsName); } catch (ClassNotFoundException ignore) { // No-op. } if (implCls == null) throw new IgniteCheckedException("Failed to find component implementation: " + cls.getName()); if (!cls.isAssignableFrom(implCls)) throw new IgniteCheckedException("Component implementation does not implement component interface " + "[component=" + cls.getName() + ", implementation=" + implCls.getName() + ']'); Constructor<T> constructor; try { constructor = implCls.getConstructor(GridKernalContext.class); } catch (NoSuchMethodException e) { throw new IgniteCheckedException("Component does not have expected constructor: " + implCls.getName(), e); } try { return constructor.newInstance(ctx); } catch (ReflectiveOperationException e) { throw new IgniteCheckedException("Failed to create component [component=" + cls.getName() + ", implementation=" + implCls.getName() + ']', e); } } /** * @param cls Component interface. * @return Name of component implementation class for open source edition. */ private static String componentClassName(Class<?> cls) { return cls.getPackage().getName() + ".os." + cls.getSimpleName().replace("Grid", "GridOs"); } /** {@inheritDoc} */ @Override public void readExternal(ObjectInput in) throws IOException, ClassNotFoundException { igniteInstanceName = U.readString(in); } /** {@inheritDoc} */ @Override public void writeExternal(ObjectOutput out) throws IOException { U.writeString(out, igniteInstanceName); } /** * @return IgniteKernal instance. * @throws ObjectStreamException If failed. */ protected Object readResolve() throws ObjectStreamException { try { return IgnitionEx.localIgnite(); } catch (IllegalStateException e) { throw U.withCause(new InvalidObjectException(e.getMessage()), e); } } /** * @param comp Grid component. * @return {@code true} if node running in daemon mode and component marked by {@code SkipDaemon} annotation. */ private boolean skipDaemon(GridComponent comp) { return ctx.isDaemon() && U.hasAnnotation(comp.getClass(), SkipDaemon.class); } /** {@inheritDoc} */ @Override public void dumpDebugInfo() { try { GridKernalContextImpl ctx = this.ctx; GridDiscoveryManager discoMrg = ctx != null ? ctx.discovery() : null; ClusterNode locNode = discoMrg != null ? discoMrg.localNode() : null; if (ctx != null && discoMrg != null && locNode != null) { boolean client = ctx.clientNode(); UUID routerId = locNode instanceof TcpDiscoveryNode ? ((TcpDiscoveryNode)locNode).clientRouterNodeId() : null; U.warn(ctx.cluster().diagnosticLog(), "Dumping debug info for node [id=" + locNode.id() + ", name=" + ctx.igniteInstanceName() + ", order=" + locNode.order() + ", topVer=" + discoMrg.topologyVersion() + ", client=" + client + (client && routerId != null ? ", routerId=" + routerId : "") + ']'); ctx.cache().context().exchange().dumpDebugInfo(null); } else U.warn(log, "Dumping debug info for node, context is not initialized [name=" + igniteInstanceName + ']'); } catch (Exception e) { U.error(log, "Failed to dump debug info for node: " + e, e); } } /** * @param node Node. * @param payload Message payload. * @param procFromNioThread If {@code true} message is processed from NIO thread. * @return Response future. */ public IgniteInternalFuture sendIoTest(ClusterNode node, byte[] payload, boolean procFromNioThread) { return ctx.io().sendIoTest(node, payload, procFromNioThread); } /** * @param nodes Nodes. * @param payload Message payload. * @param procFromNioThread If {@code true} message is processed from NIO thread. * @return Response future. */ public IgniteInternalFuture sendIoTest(List<ClusterNode> nodes, byte[] payload, boolean procFromNioThread) { return ctx.io().sendIoTest(nodes, payload, procFromNioThread); } /** * Registers metrics. */ private void registerMetrics() { if (!ctx.metric().enabled()) return; MetricRegistry reg = ctx.metric().registry(GridMetricManager.IGNITE_METRICS); reg.register("fullVersion", this::getFullVersion, String.class, FULL_VER_DESC); reg.register("copyright", this::getCopyright, String.class, COPYRIGHT_DESC); reg.register("startTimestampFormatted", this::getStartTimestampFormatted, String.class, START_TIMESTAMP_FORMATTED_DESC); reg.register("isRebalanceEnabled", this::isRebalanceEnabled, IS_REBALANCE_ENABLED_DESC); reg.register("uptimeFormatted", this::getUpTimeFormatted, String.class, UPTIME_FORMATTED_DESC); reg.register("startTimestamp", this::getStartTimestamp, START_TIMESTAMP_DESC); reg.register("uptime", this::getUpTime, UPTIME_DESC); reg.register("osInformation", this::getOsInformation, String.class, OS_INFO_DESC); reg.register("jdkInformation", this::getJdkInformation, String.class, JDK_INFO_DESC); reg.register("osUser", this::getOsUser, String.class, OS_USER_DESC); reg.register("vmName", this::getVmName, String.class, VM_NAME_DESC); reg.register("instanceName", this::getInstanceName, String.class, INSTANCE_NAME_DESC); reg.register("currentCoordinatorFormatted", this::getCurrentCoordinatorFormatted, String.class, CUR_COORDINATOR_FORMATTED_DESC); reg.register("isNodeInBaseline", this::isNodeInBaseline, IS_NODE_BASELINE_DESC); reg.register("longJVMPausesCount", this::getLongJVMPausesCount, LONG_JVM_PAUSES_CNT_DESC); reg.register("longJVMPausesTotalDuration", this::getLongJVMPausesTotalDuration, LONG_JVM_PAUSES_TOTAL_DURATION_DESC); reg.register("longJVMPauseLastEvents", this::getLongJVMPauseLastEvents, Map.class, LONG_JVM_PAUSE_LAST_EVENTS_DESC); reg.register("active", () -> ctx.state().clusterState().active()/*this::active*/, Boolean.class, ACTIVE_DESC); reg.register("clusterState", this::clusterState, String.class, CLUSTER_STATE_DESC); reg.register("lastClusterStateChangeTime", this::lastClusterStateChangeTime, LAST_CLUSTER_STATE_CHANGE_TIME_DESC); reg.register("userAttributesFormatted", this::getUserAttributesFormatted, List.class, USER_ATTRS_FORMATTED_DESC); reg.register("gridLoggerFormatted", this::getGridLoggerFormatted, String.class, GRID_LOG_FORMATTED_DESC); reg.register("executorServiceFormatted", this::getExecutorServiceFormatted, String.class, EXECUTOR_SRVC_FORMATTED_DESC); reg.register("igniteHome", this::getIgniteHome, String.class, IGNITE_HOME_DESC); reg.register("mBeanServerFormatted", this::getMBeanServerFormatted, String.class, MBEAN_SERVER_FORMATTED_DESC); reg.register("localNodeId", this::getLocalNodeId, UUID.class, LOC_NODE_ID_DESC); reg.register("isPeerClassLoadingEnabled", this::isPeerClassLoadingEnabled, Boolean.class, IS_PEER_CLS_LOADING_ENABLED_DESC); reg.register("lifecycleBeansFormatted", this::getLifecycleBeansFormatted, List.class, LIFECYCLE_BEANS_FORMATTED_DESC); reg.register("discoverySpiFormatted", this::getDiscoverySpiFormatted, String.class, DISCOVERY_SPI_FORMATTED_DESC); reg.register("communicationSpiFormatted", this::getCommunicationSpiFormatted, String.class, COMMUNICATION_SPI_FORMATTED_DESC); reg.register("deploymentSpiFormatted", this::getDeploymentSpiFormatted, String.class, DEPLOYMENT_SPI_FORMATTED_DESC); reg.register("checkpointSpiFormatted", this::getCheckpointSpiFormatted, String.class, CHECKPOINT_SPI_FORMATTED_DESC); reg.register("collisionSpiFormatted", this::getCollisionSpiFormatted, String.class, COLLISION_SPI_FORMATTED_DESC); reg.register("eventStorageSpiFormatted", this::getEventStorageSpiFormatted, String.class, EVT_STORAGE_SPI_FORMATTED_DESC); reg.register("failoverSpiFormatted", this::getFailoverSpiFormatted, String.class, FAILOVER_SPI_FORMATTED_DESC); reg.register("loadBalancingSpiFormatted", this::getLoadBalancingSpiFormatted, String.class, LOAD_BALANCING_SPI_FORMATTED_DESC); } /** * Class holds client reconnection event handling state. */ private class ReconnectState { /** Future will be completed when the client node connected the first time. */ private final GridFutureAdapter firstReconnectFut = new GridFutureAdapter(); /** * Composed future of all {@link GridComponent#onReconnected(boolean)} callbacks. * The future completes when all Ignite components are finished handle given client reconnect event. */ private GridCompoundFuture<?, Object> curReconnectFut; /** Future completes when reconnection handling is done (doesn't matter successfully or not). */ private GridFutureAdapter<?> reconnectDone; /** * @throws IgniteCheckedException If failed. */ void waitFirstReconnect() throws IgniteCheckedException { firstReconnectFut.get(); } /** * Wait for the previous reconnection handling finished or force completion if not. */ void waitPreviousReconnect() { if (curReconnectFut != null && !curReconnectFut.isDone()) { assert reconnectDone != null; curReconnectFut.onDone(STOP_RECONNECT); try { reconnectDone.get(); } catch (IgniteCheckedException ignore) { // No-op. } } } /** {@inheritDoc} */ @Override public String toString() { return S.toString(ReconnectState.class, this); } } /** {@inheritDoc} */ @Override public void runIoTest( long warmup, long duration, int threads, long maxLatency, int rangesCnt, int payLoadSize, boolean procFromNioThread ) { ctx.io().runIoTest(warmup, duration, threads, maxLatency, rangesCnt, payLoadSize, procFromNioThread, new ArrayList(ctx.cluster().get().forServers().forRemotes().nodes())); } /** {@inheritDoc} */ @Override public void clearNodeLocalMap() { ctx.cluster().get().clearNodeMap(); } /** {@inheritDoc} */ @Override public void clusterState(String state) { ClusterState newState = ClusterState.valueOf(state); cluster().state(newState); } /** {@inheritDoc} */ @Override public String toString() { return S.toString(IgniteKernal.class, this); } }
IGNITE-13534 Fixed uninformative message in console about using deprecated active() - Fixes #8347. Signed-off-by: Ilya Kasnacheev <[email protected]>
modules/core/src/main/java/org/apache/ignite/internal/IgniteKernal.java
IGNITE-13534 Fixed uninformative message in console about using deprecated active() - Fixes #8347.
<ide><path>odules/core/src/main/java/org/apache/ignite/internal/IgniteKernal.java <ide> log.info(str); <ide> } <ide> <del> if (!ctx.state().clusterState().active()) { <del> U.quietAndInfo(log, ">>> Ignite cluster is not active (limited functionality available). " + <del> "Use control.(sh|bat) script or IgniteCluster interface to activate."); <add> if (ctx.state().clusterState().state() == ClusterState.INACTIVE) { <add> U.quietAndInfo(log, ">>> Ignite cluster is in INACTIVE state (limited functionality available). " + <add> "Use control.(sh|bat) script or IgniteCluster.state(ClusterState.ACTIVE) to change the state."); <ide> } <ide> } <ide> <ide> reg.register("longJVMPauseLastEvents", this::getLongJVMPauseLastEvents, Map.class, <ide> LONG_JVM_PAUSE_LAST_EVENTS_DESC); <ide> <del> reg.register("active", () -> ctx.state().clusterState().active()/*this::active*/, Boolean.class, <add> reg.register("active", () -> ctx.state().clusterState().state().active(), Boolean.class, <ide> ACTIVE_DESC); <ide> <ide> reg.register("clusterState", this::clusterState, String.class, CLUSTER_STATE_DESC);
Java
mit
938a60ce38c4dd94bda00a53b5a4dbe260faf1a6
0
sk89q/CommandHelper,Techcable/CommandHelper,Techcable/CommandHelper,Techcable/CommandHelper,dbuxo/CommandHelper,Techcable/CommandHelper,sk89q/CommandHelper,dbuxo/CommandHelper,sk89q/CommandHelper,dbuxo/CommandHelper,dbuxo/CommandHelper,sk89q/CommandHelper
package com.laytonsmith.core.functions; import com.laytonsmith.PureUtilities.Common.StringUtils; import com.laytonsmith.PureUtilities.Version; import com.laytonsmith.abstraction.MCAnimalTamer; import com.laytonsmith.abstraction.MCColor; import com.laytonsmith.abstraction.MCCreatureSpawner; import com.laytonsmith.abstraction.MCEntity; import com.laytonsmith.abstraction.MCFireworkBuilder; import com.laytonsmith.abstraction.MCItem; import com.laytonsmith.abstraction.MCItemStack; import com.laytonsmith.abstraction.MCLivingEntity; import com.laytonsmith.abstraction.MCLocation; import com.laytonsmith.abstraction.MCOfflinePlayer; import com.laytonsmith.abstraction.MCPlayer; import com.laytonsmith.abstraction.MCPlugin; import com.laytonsmith.abstraction.MCServer; import com.laytonsmith.abstraction.MCTameable; import com.laytonsmith.abstraction.MCWorld; import com.laytonsmith.abstraction.StaticLayer; import com.laytonsmith.abstraction.blocks.MCMaterial; import com.laytonsmith.abstraction.entities.MCHorse; import com.laytonsmith.abstraction.enums.MCCreeperType; import com.laytonsmith.abstraction.enums.MCDyeColor; import com.laytonsmith.abstraction.enums.MCEffect; import com.laytonsmith.abstraction.enums.MCEntityType; import com.laytonsmith.abstraction.enums.MCFireworkType; import com.laytonsmith.abstraction.enums.MCMobs; import com.laytonsmith.abstraction.enums.MCOcelotType; import com.laytonsmith.abstraction.enums.MCPigType; import com.laytonsmith.abstraction.enums.MCProfession; import com.laytonsmith.abstraction.enums.MCSkeletonType; import com.laytonsmith.abstraction.enums.MCWolfType; import com.laytonsmith.abstraction.enums.MCZombieType; import com.laytonsmith.annotations.api; import com.laytonsmith.core.CHVersion; import com.laytonsmith.core.ObjectGenerator; import com.laytonsmith.core.Optimizable; import com.laytonsmith.core.Static; import com.laytonsmith.core.constructs.CArray; import com.laytonsmith.core.constructs.CBoolean; import com.laytonsmith.core.constructs.CDouble; import com.laytonsmith.core.constructs.CInt; import com.laytonsmith.core.constructs.CNull; import com.laytonsmith.core.constructs.CString; import com.laytonsmith.core.constructs.CVoid; import com.laytonsmith.core.constructs.Construct; import com.laytonsmith.core.constructs.Target; import com.laytonsmith.core.environments.CommandHelperEnvironment; import com.laytonsmith.core.environments.Environment; import com.laytonsmith.core.events.drivers.ServerEvents; import com.laytonsmith.core.exceptions.CancelCommandException; import com.laytonsmith.core.exceptions.ConfigRuntimeException; import com.laytonsmith.core.functions.Exceptions.ExceptionType; import java.io.IOException; import java.lang.management.ManagementFactory; import java.lang.reflect.Field; import java.util.ArrayList; import java.util.Calendar; import java.util.EnumSet; import java.util.Enumeration; import java.util.GregorianCalendar; import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.Properties; import java.util.Set; import java.util.SortedMap; import java.util.TreeMap; import java.util.logging.Level; import java.util.logging.Logger; /** * */ public class Minecraft { public static String docs() { return "These functions provide a hook into game functionality."; } private static final SortedMap<String, Construct> DataValueLookup = new TreeMap<String, Construct>(); private static final SortedMap<String, Construct> DataNameLookup = new TreeMap<String, Construct>(); static { Properties p1 = new Properties(); try { p1.load(Minecraft.class.getResourceAsStream("/data_values.txt")); Enumeration e = p1.propertyNames(); while (e.hasMoreElements()) { String name = e.nextElement().toString(); DataValueLookup.put(name, new CString(p1.getProperty(name).toString(), Target.UNKNOWN)); } } catch (IOException ex) { Logger.getLogger(Minecraft.class.getName()).log(Level.SEVERE, null, ex); } Properties p2 = new Properties(); try { p2.load(Minecraft.class.getResourceAsStream("/data_names.txt")); Enumeration e = p2.propertyNames(); while (e.hasMoreElements()) { String name = e.nextElement().toString(); DataNameLookup.put(name, new CString(p2.getProperty(name).toString(), Target.UNKNOWN)); } } catch (IOException ex) { Logger.getLogger(Minecraft.class.getName()).log(Level.SEVERE, null, ex); } } @api public static class data_values extends AbstractFunction { @Override public String getName() { return "data_values"; } @Override public Integer[] numArgs() { return new Integer[]{1}; } @Override public Construct exec(Target t, Environment env, Construct... args) throws CancelCommandException, ConfigRuntimeException { if (args[0] instanceof CInt) { return new CInt(Static.getInt(args[0], t), t); } else { String c = args[0].val(); int number = StaticLayer.LookupItemId(c); if (number != -1) { return new CInt(number, t); } String changed = c; if (changed.contains(":")) { //Split on that, and reverse. Change wool:red to redwool String split[] = changed.split(":"); if (split.length == 2) { changed = split[1] + split[0]; } } //Remove anything that isn't a letter or a number changed = changed.replaceAll("[^a-zA-Z0-9]", "").toLowerCase(); //Do a lookup in the DataLookup table if (DataValueLookup.containsKey(changed)) { String split[] = DataValueLookup.get(changed).toString().split(":"); if (split[1].equals("0")) { return new CInt(split[0], t); } return new CString(split[0] + ":" + split[1], t); } return CNull.NULL; } } @Override public String docs() { return "int {var1} Does a lookup to return the data value of a name. For instance, returns 1 for 'stone'. If an integer is given," + " simply returns that number. If the data value cannot be found, null is returned."; } @Override public ExceptionType[] thrown() { return new ExceptionType[]{}; } @Override public boolean isRestricted() { return false; } @Override public CHVersion since() { return CHVersion.V3_0_1; } @Override public Boolean runAsync() { return false; } } @api public static class data_name extends AbstractFunction { @Override public String getName() { return "data_name"; } @Override public Integer[] numArgs() { return new Integer[]{1}; } @Override public String docs() { return "string {int | itemArray} Performs the reverse functionality as data_values. Given 1, returns 'Stone'. Note that the enum value" + " given in bukkit's Material class is what is returned as a fallback, if the id doesn't match a value in the internally maintained list." + " If a completely invalid argument is passed" + " in, null is returned."; } @Override public ExceptionType[] thrown() { return new ExceptionType[]{ExceptionType.CastException, ExceptionType.FormatException}; } @Override public boolean isRestricted() { return false; } @Override public CHVersion since() { return CHVersion.V3_3_0; } @Override public Boolean runAsync() { return false; } @Override public Construct exec(Target t, Environment environment, Construct... args) throws ConfigRuntimeException { int i = -1; int i2 = -1; if (args[0] instanceof CString) { //We also accept item notation if (args[0].val().contains(":")) { String[] split = args[0].val().split(":"); try { i = Integer.parseInt(split[0]); i2 = Integer.parseInt(split[1]); } catch (NumberFormatException e) { } catch (ArrayIndexOutOfBoundsException e){ throw new Exceptions.FormatException("Incorrect format for the item notation: " + args[0].val(), t); } } } else if (args[0] instanceof CArray) { MCItemStack is = ObjectGenerator.GetGenerator().item(args[0], t); i = is.getTypeId(); i2 = (int) is.getData().getData(); } if (i == -1) { i = Static.getInt32(args[0], t); } if (i2 == -1) { i2 = 0; } if (DataNameLookup.containsKey(i + "_" + i2)) { return DataNameLookup.get(i + "_" + i2); } else if (DataNameLookup.containsKey(i + "_0")) { return DataNameLookup.get(i + "_0"); } else { try { return new CString(StaticLayer.LookupMaterialName(i), t); } catch (NullPointerException e) { return CNull.NULL; } } } } @api public static class max_stack_size extends AbstractFunction { @Override public String getName() { return "max_stack_size"; } @Override public Integer[] numArgs() { return new Integer[]{1}; } @Override public String docs() { return "integer {itemType | itemArray} Given an item type, returns" + " the maximum allowed stack size. This method will accept either" + " a single data value (i.e. 278) or an item array like is returned" + " from pinv(). Additionally, if a single value, it can also be in" + " the old item notation (i.e. '35:11'), though for the purposes of this" + " function, the data is unneccesary."; } @Override public ExceptionType[] thrown() { return new ExceptionType[]{ExceptionType.CastException, ExceptionType.FormatException}; } @Override public boolean isRestricted() { return false; } @Override public Boolean runAsync() { return false; } @Override public Construct exec(Target t, Environment environment, Construct... args) throws ConfigRuntimeException { if (args[0] instanceof CArray) { MCItemStack is = ObjectGenerator.GetGenerator().item(args[0], t); return new CInt(is.getType().getMaxStackSize(), t); } else { String item = args[0].val(); if (item.contains(":")) { String[] split = item.split(":"); item = split[0]; } try { int iitem = Integer.parseInt(item); int max = StaticLayer.GetItemStack(iitem, 1).getType().getMaxStackSize(); return new CInt(max, t); } catch (NumberFormatException e) { } } throw new ConfigRuntimeException("Improper value passed to max_stack. Expecting a number, or an item array, but received \"" + args[0].val() + "\"", ExceptionType.CastException, t); } @Override public CHVersion since() { return CHVersion.V3_3_0; } } @api(environments = {CommandHelperEnvironment.class}) public static class spawn_mob extends AbstractFunction { @Override public String getName() { return "spawn_mob"; } @Override public Integer[] numArgs() { return new Integer[]{1, 2, 3}; } @Override public String docs() { return "array {mobType, [qty], [location]} Spawns qty mob of one of the following types at location. qty defaults to 1, and location defaults" + " to the location of the player. An array of the entity IDs spawned is returned." + " ---- mobType can be one of: " + StringUtils.Join(MCMobs.values(), ", ", ", or ", " or ") + "." + " Spelling matters, but capitalization doesn't. At this time, the function is limited to spawning a maximum of 50 at a time." + " Further, subtypes can be applied by specifying MOBTYPE:SUBTYPE, for example the sheep subtype can be any of the dye colors: " + StringUtils.Join(MCDyeColor.values(), ", ", ", or ", " or ") + ". COLOR defaults to white if not specified. For mobs with multiple" + " subtypes, separate each type with a \"-\", currently only zombies which, using ZOMBIE:TYPE1-TYPE2 can be any non-conflicting two of: " + StringUtils.Join(MCZombieType.values(), ", ", ", or ", " or ") + ", but default to normal zombies. Ocelots may be one of: " + StringUtils.Join(MCOcelotType.values(), ", ", ", or ", " or ") + ", defaulting to the wild variety. Villagers can have a profession as a subtype: " + StringUtils.Join(MCProfession.values(), ", ", ", or ", " or ") + ", defaulting to farmer if not specified. Skeletons can be " + StringUtils.Join(MCSkeletonType.values(), ", ", ", or ", " or ") + ". PigZombies' subtype represents their anger," + " and accepts an integer, where 0 is neutral and 400 is the normal response to being attacked. Defaults to 0. Similarly, Slime" + " and MagmaCube size can be set by integer, otherwise will be a random natural size. If a material is specified as the subtype" + " for Endermen, they will hold that material, otherwise they will hold nothing. Creepers can be set to " + StringUtils.Join(MCCreeperType.values(), ", ", ", or ", " or ") + ", wolves can be " + StringUtils.Join(MCWolfType.values(), ", ", ", or ", " or ") + ", and pigs can be " + StringUtils.Join(MCPigType.values(), ", ", ", or ", " or ") + "." + " Horses can have three different subTypes, the variant: " + StringUtils.Join(MCHorse.MCHorseVariant.values(), ", ", ", or ", " or ") + "," + " the color: " + StringUtils.Join(MCHorse.MCHorseColor.values(), ", ", ", or ", " or ") + "," + " and the pattern: " + StringUtils.Join(MCHorse.MCHorsePattern.values(), ", ", ", or ", " or ") + "."; } @Override public ExceptionType[] thrown() { return new ExceptionType[]{ExceptionType.CastException, ExceptionType.RangeException, ExceptionType.FormatException, ExceptionType.PlayerOfflineException, ExceptionType.InvalidWorldException}; } @Override public boolean isRestricted() { return true; } @Override public CHVersion since() { return CHVersion.V3_1_2; } @Override public Boolean runAsync() { return false; } @Override public Construct exec(Target t, Environment env, Construct... args) throws CancelCommandException, ConfigRuntimeException { String mob = args[0].val(); String secondary = ""; if (mob.contains(":")) { secondary = mob.substring(mob.indexOf(':') + 1); mob = mob.substring(0, mob.indexOf(':')); } int qty = 1; if (args.length > 1) { qty = Static.getInt32(args[1], t); } if (qty > 50) { throw new ConfigRuntimeException("A bit excessive, don't you think? Let's scale that back some, huh?", ExceptionType.RangeException, t); } MCLocation l; MCPlayer p = env.getEnv(CommandHelperEnvironment.class).GetPlayer(); if (args.length == 3) { l = ObjectGenerator.GetGenerator().location(args[2], (p != null ? p.getWorld() : null), t); } else if (p != null) { l = p.getLocation(); } else { throw new ConfigRuntimeException("Invalid sender!", ExceptionType.PlayerOfflineException, t); } try{ return l.getWorld().spawnMob(MCMobs.valueOf(mob.toUpperCase().replaceAll(" ", "")), secondary, qty, l, t); } catch(IllegalArgumentException e){ throw new ConfigRuntimeException("Invalid mob name: " + mob, ExceptionType.FormatException, t); } } } @api(environments={CommandHelperEnvironment.class}) public static class tame_mob extends AbstractFunction { @Override public String getName() { return "tame_mob"; } @Override public Integer[] numArgs() { return new Integer[]{1, 2}; } @Override public String docs() { return "void {[player], entityID} Tames any tameable mob to the specified player. Offline players are" + " supported, but this means that partial matches are NOT supported. You must type the players" + " name exactly. Setting the player to null will untame the mob. If the entity doesn't exist," + " nothing happens."; } @Override public ExceptionType[] thrown() { return new ExceptionType[]{ExceptionType.UntameableMobException, ExceptionType.CastException, ExceptionType.BadEntityException}; } @Override public boolean isRestricted() { return true; } @Override public CHVersion since() { return CHVersion.V3_3_0; } @Override public Boolean runAsync() { return false; } @Override public Construct exec(Target t, Environment environment, Construct... args) throws ConfigRuntimeException { String player = null; MCPlayer mcPlayer = environment.getEnv(CommandHelperEnvironment.class).GetPlayer(); if (mcPlayer != null) { player = mcPlayer.getName(); } Construct entityID = null; if (args.length == 2) { if (args[0] instanceof CNull) { player = null; } else { player = args[0].val(); } entityID = args[1]; } else { entityID = args[0]; } int id = Static.getInt32(entityID, t); MCLivingEntity e = Static.getLivingEntity(id, t); if (e == null) { return CVoid.VOID; } else if (e instanceof MCTameable) { MCTameable mct = ((MCTameable) e); if (player != null) { mct.setOwner(Static.getServer().getOfflinePlayer(player)); } else { mct.setOwner(null); } return CVoid.VOID; } else { throw new ConfigRuntimeException("The specified entity is not tameable", ExceptionType.UntameableMobException, t); } } } @api public static class get_mob_owner extends AbstractFunction { @Override public String getName() { return "get_mob_owner"; } @Override public Integer[] numArgs() { return new Integer[]{1}; } @Override public String docs() { return "string {entityID} Returns the owner's name, or null if the mob is unowned. An UntameableMobException is thrown if" + " mob isn't tameable to begin with."; } @Override public ExceptionType[] thrown() { return new ExceptionType[]{ExceptionType.UntameableMobException, ExceptionType.CastException, ExceptionType.BadEntityException}; } @Override public boolean isRestricted() { return true; } @Override public CHVersion since() { return CHVersion.V3_3_0; } @Override public Boolean runAsync() { return false; } @Override public Construct exec(Target t, Environment environment, Construct... args) throws ConfigRuntimeException { int id = Static.getInt32(args[0], t); MCLivingEntity e = Static.getLivingEntity(id, t); if (e == null) { return CNull.NULL; } else if (e instanceof MCTameable) { MCAnimalTamer at = ((MCTameable) e).getOwner(); if (null != at) { return new CString(at.getName(), t); } else { return CNull.NULL; } } else { throw new ConfigRuntimeException("The specified entity is not tameable", ExceptionType.UntameableMobException, t); } } } @api public static class is_tameable extends AbstractFunction { @Override public String getName() { return "is_tameable"; } @Override public Integer[] numArgs() { return new Integer[]{1}; } @Override public String docs() { return "boolean {entityID} Returns true or false if the specified entity is tameable"; } @Override public ExceptionType[] thrown() { return new ExceptionType[]{ExceptionType.CastException, ExceptionType.BadEntityException}; } @Override public boolean isRestricted() { return true; } @Override public CHVersion since() { return CHVersion.V3_3_0; } @Override public Boolean runAsync() { return false; } @Override public Construct exec(Target t, Environment environment, Construct... args) throws ConfigRuntimeException { int id = Static.getInt32(args[0], t); MCEntity e = Static.getEntity(id, t); boolean ret; if (e == null) { ret = false; } else if (e instanceof MCTameable) { ret = true; } else { ret = false; } return CBoolean.get(ret); } } @api(environments={CommandHelperEnvironment.class}) public static class make_effect extends AbstractFunction { @Override public String getName() { return "make_effect"; } @Override public Integer[] numArgs() { return new Integer[]{2, 3}; } @Override public String docs() { return "void {xyzArray, effect, [radius]} Plays the specified effect (sound effect) at the given location, for all players within" + " the radius (or 64 by default). The effect can be one of the following: " + StringUtils.Join(MCEffect.values(), ", ", ", or ", " or ") + ". Additional data can be supplied with the syntax EFFECT:DATA. The RECORD_PLAY effect takes the item" + " id of a disc as data, STEP_SOUND takes a blockID and SMOKE takes a direction bit (4 is upwards)."; } @Override public ExceptionType[] thrown() { return new ExceptionType[]{ExceptionType.CastException, ExceptionType.FormatException}; } @Override public boolean isRestricted() { return true; } @Override public CHVersion since() { return CHVersion.V3_1_3; } @Override public Boolean runAsync() { return false; } @Override public Construct exec(Target t, Environment env, Construct... args) throws ConfigRuntimeException { MCLocation l = ObjectGenerator.GetGenerator().location(args[0], (env.getEnv(CommandHelperEnvironment.class).GetCommandSender() instanceof MCPlayer ? env.getEnv(CommandHelperEnvironment.class).GetPlayer().getWorld() : null), t); MCEffect e = null; String preEff = args[1].val(); int data = 0; int radius = 64; if (preEff.contains(":")) { try { data = Integer.parseInt(preEff.substring(preEff.indexOf(':') + 1)); } catch (NumberFormatException ex) { throw new ConfigRuntimeException("Effect data expected an integer", ExceptionType.CastException, t); } preEff = preEff.substring(0, preEff.indexOf(':')); } try { e = MCEffect.valueOf(preEff.toUpperCase()); } catch (IllegalArgumentException ex) { throw new ConfigRuntimeException("The effect type " + args[1].val() + " is not valid", ExceptionType.FormatException, t); } if (e.equals(MCEffect.STEP_SOUND) && (data < 0 || data > StaticLayer.GetConvertor().getMaxBlockID())) { throw new ConfigRuntimeException("This effect requires a valid BlockID", ExceptionType.FormatException, t); } if (args.length == 3) { radius = Static.getInt32(args[2], t); } l.getWorld().playEffect(l, e, data, radius); return CVoid.VOID; } } @api public static class set_entity_health extends AbstractFunction { @Override public String getName() { return "set_entity_health"; } @Override public Integer[] numArgs() { return new Integer[]{2}; } @Override public String docs() { return "void {entityID, healthPercent} Sets the specified entity's health as a percentage," + " where 0 kills it and 100 gives it full health." + " An exception is thrown if the entityID doesn't exist or isn't a LivingEntity."; } @Override public ExceptionType[] thrown() { return new ExceptionType[]{ExceptionType.CastException, ExceptionType.BadEntityException, ExceptionType.RangeException}; } @Override public boolean isRestricted() { return true; } @Override public CHVersion since() { return CHVersion.V3_3_0; } @Override public Boolean runAsync() { return false; } @Override public Construct exec(Target t, Environment environment, Construct... args) throws ConfigRuntimeException { MCLivingEntity e = Static.getLivingEntity(Static.getInt32(args[0], t), t); double percent = Static.getDouble(args[1], t); if (percent < 0 || percent > 100) { throw new ConfigRuntimeException("Health was expected to be a percentage between 0 and 100", ExceptionType.RangeException, t); } else { e.setHealth(percent / 100.0 * e.getMaxHealth()); } return CVoid.VOID; } } @api public static class get_entity_health extends AbstractFunction { @Override public String getName() { return "get_entity_health"; } @Override public Integer[] numArgs() { return new Integer[]{1}; } @Override public String docs() { return "double {entityID} Returns the entity's health as a percentage of its maximum health." + " If the specified entity doesn't exist, or is not a LivingEntity, a format exception is thrown."; } @Override public ExceptionType[] thrown() { return new ExceptionType[]{ExceptionType.CastException, ExceptionType.BadEntityException}; } @Override public boolean isRestricted() { return true; } @Override public CHVersion since() { return CHVersion.V3_3_0; } @Override public Boolean runAsync() { return false; } @Override public Construct exec(Target t, Environment environment, Construct... args) throws ConfigRuntimeException { MCLivingEntity e = Static.getLivingEntity(Static.getInt32(args[0], t), t); return new CDouble(e.getHealth() / e.getMaxHealth() * 100.0, t); } } @api(environments={CommandHelperEnvironment.class}) public static class get_server_info extends AbstractFunction { @Override public String getName() { return "get_server_info"; } @Override public Integer[] numArgs() { return new Integer[]{0, 1}; } @Override public String docs() { return "mixed {[value]} Returns various information about server." + "If value is set, it should be an integer of one of the following indexes, and only that information for that index" + " will be returned. ---- Otherwise if value is not specified (or is -1), it returns an array of" + " information with the following pieces of information in the specified index: " + "<ul><li>0 - Server name; the name of the server in server.properties.</li>" + "<li>1 - API version; The version of the plugin API this server is implementing.</li>" + "<li>2 - Server version; The bare version string of the server implementation.</li>" + "<li>3 - Allow flight; If true, Minecraft's inbuilt anti fly check is enabled.</li>" + "<li>4 - Allow nether; is true, the Nether dimension is enabled</li>" + "<li>5 - Allow end; if true, the End is enabled</li>" + "<li>6 - World container; The path to the world container.</li>" + "<li>7 - Max player limit; returns the player limit.</li>" + "<li>8 - Operators; An array of operators on the server.</li>" + "<li>9 - Plugins; An array of plugins loaded by the server.</li>" + "<li>10 - Online Mode; If true, users are authenticated with Mojang before login</li>" + "<li>11 - Server port; Get the game port that the server runs on</li>" + "<li>12 - Server IP; Get the IP that the server runs on</li>" + "<li>13 - Uptime; The number of milliseconds the server has been running</li>" + "<li>14 - gcmax; The maximum amount of memory that the Java virtual machine will attempt to use, in bytes</li>" + "<li>15 - gctotal; The total amount of memory in the Java virtual machine, in bytes</li>" + "<li>16 - gcfree; The amount of free memory in the Java Virtual Machine, in bytes</li></ul>"; } @Override public ExceptionType[] thrown() { return new ExceptionType[]{ExceptionType.CastException, ExceptionType.RangeException}; } @Override public boolean isRestricted() { return false; } @Override public CHVersion since() { return CHVersion.V3_3_1; } @Override public Boolean runAsync() { return true; } @Override public Construct exec(Target t, Environment env, Construct... args) throws CancelCommandException, ConfigRuntimeException { MCServer server = StaticLayer.GetServer(); int index = -1; if (args.length == 0) { index = -1; } else if (args.length == 1) { index = Static.getInt32(args[0], t); } if (index < -1 || index > 12) { throw new ConfigRuntimeException("get_server_info expects the index to be between -1 and 12 (inclusive)", ExceptionType.RangeException, t); } assert index >= -1 && index <= 12; // Is this needed? Above statement should cause this to never be true. - entityreborn ArrayList<Construct> retVals = new ArrayList<Construct>(); if (index == 0 || index == -1) { //Server name retVals.add(new CString(server.getServerName(), t)); } if (index == 1 || index == -1) { // API Version retVals.add(new CString(server.getAPIVersion(), t)); } if (index == 2 || index == -1) { // Server Version retVals.add(new CString(server.getServerVersion(), t)); } if (index == 3 || index == -1) { //Allow flight retVals.add(CBoolean.get(server.getAllowFlight())); } if (index == 4 || index == -1) { //Allow nether retVals.add(CBoolean.get(server.getAllowNether())); } if (index == 5 || index == -1) { //Allow end retVals.add(CBoolean.get(server.getAllowEnd())); } if (index == 6 || index == -1) { //World container retVals.add(new CString(server.getWorldContainer(), t)); } if (index == 7 || index == -1) { //Max player limit retVals.add(new CInt(server.getMaxPlayers(), t)); } if (index == 8 || index == -1) { //Array of op's CArray co = new CArray(t); List<MCOfflinePlayer> so = server.getOperators(); for (MCOfflinePlayer o : so) { if (o == null) { continue; } CString os = new CString(o.getName(), t); co.push(os); } retVals.add(co); } if (index == 9 || index == -1) { //Array of plugins CArray co = new CArray(t); List<MCPlugin> plugs = server.getPluginManager().getPlugins(); for (MCPlugin p : plugs) { if (p == null) { continue; } CString name = new CString(p.getName(), t); co.push(name); } retVals.add(co); } if (index == 10 || index == -1) { //Online Mode retVals.add(CBoolean.get(server.getOnlineMode())); } if (index == 11 || index == -1) { //Server port retVals.add(new CInt(server.getPort(), t)); } if (index == 12 || index == -1) { //Server Ip retVals.add(new CString(server.getIp(), t)); } if (index == 13 || index == -1) { //Uptime double uptime = (double)(new GregorianCalendar().getTimeInMillis() - ManagementFactory.getRuntimeMXBean().getStartTime()); retVals.add(new CDouble(uptime, t)); } if (index == 14 || index == -1) { //gcmax retVals.add(new CInt((Runtime.getRuntime().maxMemory()), t)); } if (index == 15 || index == -1) { //gctotal retVals.add(new CInt((Runtime.getRuntime().totalMemory()), t)); } if (index == 16 || index == -1) { //gcfree retVals.add(new CInt((Runtime.getRuntime().freeMemory()), t)); } if (retVals.size() == 1) { return retVals.get(0); } else { CArray ca = new CArray(t); for (Construct c : retVals) { ca.push(c); } return ca; } } } @api(environments={CommandHelperEnvironment.class}) public static class get_banned_players extends AbstractFunction { @Override public String getName() { return "get_banned_players"; } @Override public Integer[] numArgs() { return new Integer[]{0}; } @Override public String docs() { return "Array {} An array of players banned on the server."; } @Override public ExceptionType[] thrown() { return new ExceptionType[]{}; } @Override public boolean isRestricted() { return false; } @Override public CHVersion since() { return CHVersion.V3_3_1; } @Override public Boolean runAsync() { return true; } @Override public Construct exec(Target t, Environment env, Construct... args) throws CancelCommandException, ConfigRuntimeException { MCServer server = env.getEnv(CommandHelperEnvironment.class).GetCommandSender().getServer(); CArray co = new CArray(t); List<MCOfflinePlayer> so = server.getBannedPlayers(); for (MCOfflinePlayer o : so) { if (o == null) { continue; } CString os = new CString(o.getName(), t); co.push(os); } return co; } } @api(environments={CommandHelperEnvironment.class}) public static class get_whitelisted_players extends AbstractFunction { @Override public String getName() { return "get_whitelisted_players"; } @Override public Integer[] numArgs() { return new Integer[]{0}; } @Override public String docs() { return "Array {} An array of players whitelisted on the server."; } @Override public ExceptionType[] thrown() { return new ExceptionType[]{}; } @Override public boolean isRestricted() { return false; } @Override public CHVersion since() { return CHVersion.V3_3_1; } @Override public Boolean runAsync() { return true; } @Override public Construct exec(Target t, Environment env, Construct... args) throws CancelCommandException, ConfigRuntimeException { MCServer server = env.getEnv(CommandHelperEnvironment.class).GetCommandSender().getServer(); CArray co = new CArray(t); List<MCOfflinePlayer> so = server.getWhitelistedPlayers(); for (MCOfflinePlayer o : so) { if (o == null) { continue; } CString os = new CString(o.getName(), t); co.push(os); } return co; } } @api(environments={CommandHelperEnvironment.class}) public static class get_spawner_type extends AbstractFunction{ @Override public ExceptionType[] thrown() { return new ExceptionType[]{ExceptionType.FormatException}; } @Override public boolean isRestricted() { return true; } @Override public Boolean runAsync() { return false; } @Override public Construct exec(Target t, Environment environment, Construct... args) throws ConfigRuntimeException { MCWorld w = null; MCPlayer p = environment.getEnv(CommandHelperEnvironment.class).GetPlayer(); if(p != null){ w = p.getWorld(); } MCLocation location = ObjectGenerator.GetGenerator().location(args[0], w, t); if(location.getBlock().getState() instanceof MCCreatureSpawner){ String type = ((MCCreatureSpawner)location.getBlock().getState()).getSpawnedType().name(); return new CString(type, t); } else { throw new Exceptions.FormatException("The block at " + location.toString() + " is not a spawner block", t); } } @Override public String getName() { return "get_spawner_type"; } @Override public Integer[] numArgs() { return new Integer[]{1}; } @Override public String docs() { return "string {locationArray} Gets the spawner type of the specified mob spawner. ----" + " Valid types will be one of the mob types."; } @Override public CHVersion since() { return CHVersion.V3_3_1; } } @api(environments={CommandHelperEnvironment.class}) public static class set_spawner_type extends AbstractFunction{ @Override public ExceptionType[] thrown() { return new ExceptionType[]{ExceptionType.FormatException}; } @Override public boolean isRestricted() { return true; } @Override public Boolean runAsync() { return false; } @Override public Construct exec(Target t, Environment environment, Construct... args) throws ConfigRuntimeException { MCWorld w = null; MCPlayer p = environment.getEnv(CommandHelperEnvironment.class).GetPlayer(); if(p != null){ w = p.getWorld(); } MCLocation location = ObjectGenerator.GetGenerator().location(args[0], w, t); MCEntityType type; try { type = MCEntityType.valueOf(args[1].val().toUpperCase()); } catch (IllegalArgumentException iae) { throw new ConfigRuntimeException("Not a registered entity type: " + args[1].val(), ExceptionType.BadEntityException, t); } if(location.getBlock().getState() instanceof MCCreatureSpawner){ ((MCCreatureSpawner)location.getBlock().getState()).setSpawnedType(type); return CVoid.VOID; } else { throw new Exceptions.FormatException("The block at " + location.toString() + " is not a spawner block", t); } } @Override public String getName() { return "set_spawner_type"; } @Override public Integer[] numArgs() { return new Integer[]{2}; } @Override public String docs() { return "void {locationArray, type} Sets the mob spawner type at the location specified. If the location is not a mob spawner," + " or if the type is invalid, a FormatException is thrown. The type may be one of either " + StringUtils.Join(MCEntityType.MCVanillaEntityType.values(), ", ", ", or "); } @Override public CHVersion since() { return CHVersion.V3_3_1; } } @api(environments={CommandHelperEnvironment.class}) public static class launch_firework extends AbstractFunction { @Override public ExceptionType[] thrown() { return new ExceptionType[]{ExceptionType.FormatException}; } @Override public boolean isRestricted() { return true; } @Override public Boolean runAsync() { return false; } @Override public Construct exec(Target t, Environment environment, Construct... args) throws ConfigRuntimeException { MCPlayer p = environment.getEnv(CommandHelperEnvironment.class).GetPlayer(); MCWorld w = null; if(p != null){ w = p.getWorld(); } MCLocation loc = ObjectGenerator.GetGenerator().location(args[0], w, t); CArray options = new CArray(t); if(args.length == 2){ options = Static.getArray(args[1], t); } int strength = 2; boolean flicker = false; boolean trail = true; Set<MCColor> colors = new HashSet<MCColor>(); colors.add(MCColor.WHITE); Set<MCColor> fade = new HashSet<MCColor>(); MCFireworkType type = MCFireworkType.BALL; if(options.containsKey("strength")){ strength = Static.getInt32(options.get("strength", t), t); if (strength < 0 || strength > 128) { throw new ConfigRuntimeException("Strength must be between 0 and 128", ExceptionType.RangeException, t); } } if(options.containsKey("flicker")){ flicker = Static.getBoolean(options.get("flicker", t)); } if(options.containsKey("trail")){ trail = Static.getBoolean(options.get("trail", t)); } if(options.containsKey("colors")){ colors = parseColors(options.get("colors", t), t); } if(options.containsKey("fade")){ fade = parseColors(options.get("fade", t), t); } if(options.containsKey("type")){ try{ type = MCFireworkType.valueOf(options.get("type", t).val().toUpperCase()); } catch(IllegalArgumentException e){ throw new Exceptions.FormatException("Invalid type: " + options.get("type", t).val(), t); } } MCFireworkBuilder fw = StaticLayer.GetConvertor().GetFireworkBuilder(); fw.setStrength(strength); fw.setFlicker(flicker); fw.setTrail(trail); fw.setType(type); for(MCColor color : colors){ fw.addColor(color); } for(MCColor color : fade){ fw.addFadeColor(color); } return new CInt(fw.launch(loc), t); } private Set<MCColor> parseColors(Construct c, Target t){ Set<MCColor> colors = new HashSet<MCColor>(); if(c instanceof CArray){ CArray ca = ((CArray)c); if(ca.size() == 3 && ca.get(0, t) instanceof CInt && ca.get(1, t) instanceof CInt && ca.get(2, t) instanceof CInt ){ //It's a single custom color colors.add(parseColor(ca, t)); } else { for(String key : ca.stringKeySet()){ Construct val = ca.get(key, t); if(val instanceof CArray){ colors.add(parseColor(((CArray)val), t)); } else if(val instanceof CString){ colors.addAll(parseColor(((CString)val), t)); } } } } else if(c instanceof CString){ colors.addAll(parseColor(((CString)c), t)); } return colors; } private MCColor parseColor(CArray ca, Target t){ return StaticLayer.GetConvertor().GetColor( Static.getInt32(ca.get(0, t), t), Static.getInt32(ca.get(1, t), t), Static.getInt32(ca.get(2, t), t) ); } private List<MCColor> parseColor(CString cs, Target t){ String split[] = cs.val().split("\\|"); List<MCColor> colors = new ArrayList<>(); for(String s : split){ colors.add(StaticLayer.GetConvertor().GetColor(s, t)); } return colors; } @Override public String getName() { return "launch_firework"; } @Override public Integer[] numArgs() { return new Integer[]{1, 2}; } @Override public String docs() { Class c; try { //Since MCColor actually depends on a bukkit server, we don't want to require that for //the sake of documentation, so we'll build the color list much more carefully. //Note the false, so we don't actually initialize the class. c = Class.forName(MCColor.class.getName(), false, this.getClass().getClassLoader()); } catch (ClassNotFoundException ex) { //Hrm... Logger.getLogger(Minecraft.class.getName()).log(Level.SEVERE, null, ex); return ""; } List<String> names = new ArrayList<String>(); for(Field f : c.getFields()){ if(f.getType() == MCColor.class){ names.add(f.getName()); } } return "void {locationArray, [optionsArray]} Launches a firework. The location array specifies where it is launched from," + " and the options array is an associative array described below. All parameters in the associative array are" + " optional, and default to the specified values if not set. The default options being set will make it look like" + " a normal firework, with a white explosion. ----" + " The options array may have the following keys:\n" + "{| cellspacing=\"1\" cellpadding=\"1\" border=\"1\" class=\"wikitable\"\n" + "! Array key !! Description !! Default\n" + "|-\n" + "| strength || A number specifying how far up the firework should go || 2\n" + "|-\n" + "| flicker || A boolean, determining if the firework will flicker\n || false\n" + "|-\n" + "| trail || A boolean, determining if the firework will leave a trail || true\n" + "|-\n" + "| colors || An array of colors, or a pipe seperated string of color names (for the named colors only)" + " for instance: array('WHITE') or 'WHITE<nowiki>|</nowiki>BLUE'. If you want custom colors, you must use an array, though" + " you can still use color names as an item in the array, for instance: array('ORANGE', array(30, 45, 150))." + " These colors are used as the primary colors. || 'WHITE'\n" + "|-\n" + "| fade || An array of colors to be used as the fade colors. This parameter should be formatted the same as" + " the colors parameter || array()\n" + "|-\n" + "| type || An enum value of one of the firework types, one of: " + StringUtils.Join(MCFireworkType.values(), ", ", " or ") + " || " + MCFireworkType.BALL.name() + "\n" + "|}\n" + "The \"named colors\" can be one of: " + StringUtils.Join(names, ", ", " or "); } @Override public CHVersion since() { return CHVersion.V3_3_1; } } @api public static class send_texturepack extends AbstractFunction { @Override public ExceptionType[] thrown() { return new ExceptionType[]{ExceptionType.PlayerOfflineException}; } @Override public boolean isRestricted() { return true; } @Override public Boolean runAsync() { return false; } @Override public Construct exec(Target t, Environment environment, Construct... args) throws ConfigRuntimeException { MCPlayer p = Static.GetPlayer(args[0], t); p.sendTexturePack(args[1].val()); return CVoid.VOID; } @Override public String getName() { return "send_texturepack"; } @Override public Integer[] numArgs() { return new Integer[]{2}; } @Override public String docs() { return "void {player, url} Sends a texturepack URL to the player's client." + " If the client has not been requested to change textures in the" + " past, they will recieve a confirmation dialog before downloading" + " and switching to the new pack. Clients that ignore server textures" + " will not recieve the request, so this function will not affect them."; } @Override public CHVersion since() { return CHVersion.V3_3_1; } } @api public static class send_resourcepack extends AbstractFunction { @Override public ExceptionType[] thrown() { return new ExceptionType[]{ExceptionType.PlayerOfflineException}; } @Override public boolean isRestricted() { return true; } @Override public Boolean runAsync() { return false; } @Override public Construct exec(Target t, Environment environment, Construct... args) throws ConfigRuntimeException { MCPlayer p = Static.GetPlayer(args[0], t); p.sendResourcePack(args[1].val()); return CVoid.VOID; } @Override public String getName() { return "send_resourcepack"; } @Override public Integer[] numArgs() { return new Integer[]{2}; } @Override public String docs() { return "void {player, url} Sends a resourcepack URL to the player's client." + " If the client has not been requested to change resources in the" + " past, they will recieve a confirmation dialog before downloading" + " and switching to the new pack. Clients that ignore server resources" + " will not recieve the request, so this function will not affect them."; } @Override public CHVersion since() { return CHVersion.V3_3_1; } } @api public static class get_ip_bans extends AbstractFunction { @Override public ExceptionType[] thrown() { return new ExceptionType[]{}; } @Override public boolean isRestricted() { return true; } @Override public Boolean runAsync() { return false; } @Override public Construct exec(Target t, Environment environment, Construct... args) throws ConfigRuntimeException { MCServer s = Static.getServer(); CArray ret = new CArray(t); for (String ip : s.getIPBans()) { ret.push(new CString(ip, t)); } return ret; } @Override public String getName() { return "get_ip_bans"; } @Override public Integer[] numArgs() { return new Integer[]{0}; } @Override public String docs() { return "array {} Returns an array of entries from banned-ips.txt."; } @Override public CHVersion since() { return CHVersion.V3_3_1; } } @api public static class set_ip_banned extends AbstractFunction { @Override public ExceptionType[] thrown() { return new ExceptionType[]{}; } @Override public boolean isRestricted() { return true; } @Override public Boolean runAsync() { return false; } @Override public Construct exec(Target t, Environment environment, Construct... args) throws ConfigRuntimeException { MCServer s = Static.getServer(); String ip = args[0].val(); if (Static.getBoolean(args[1])) { s.banIP(ip); } else { s.unbanIP(ip); } return CVoid.VOID; } @Override public String getName() { return "set_ip_banned"; } @Override public Integer[] numArgs() { return new Integer[]{2}; } @Override public String docs() { return "void {address, banned} If banned is true, address is added to banned-ips.txt," + " if false, the address is removed."; } @Override public CHVersion since() { return CHVersion.V3_3_1; } } @api public static class material_info extends AbstractFunction { @Override public ExceptionType[] thrown() { return new ExceptionType[]{ExceptionType.CastException, ExceptionType.FormatException}; } @Override public Construct exec(Target t, Environment environment, Construct... args) throws ConfigRuntimeException { MCMaterial i = StaticLayer.GetConvertor().getMaterial(Static.getInt32(args[0], t)); CArray ret = new CArray(t); ret.set("maxStacksize", new CInt(i.getMaxStackSize(), t), t); ret.set("maxDurability", new CInt(i.getMaxDurability(), t), t); ret.set("hasGravity", CBoolean.get(i.hasGravity()), t); ret.set("isBlock", CBoolean.get(i.isBlock()), t); ret.set("isBurnable", CBoolean.get(i.isBurnable()), t); ret.set("isEdible", CBoolean.get(i.isEdible()), t); ret.set("isFlammable", CBoolean.get(i.isFlammable()), t); ret.set("isOccluding", CBoolean.get(i.isOccluding()), t); ret.set("isRecord", CBoolean.get(i.isRecord()), t); ret.set("isSolid", CBoolean.get(i.isSolid()), t); ret.set("isTransparent", CBoolean.get(i.isTransparent()), t); return ret; } @Override public String getName() { return "material_info"; } @Override public Integer[] numArgs() { return new Integer[]{1}; } @Override public String docs() { return "array {int} Returns an array of info about the material."; } @Override public boolean isRestricted() { return true; } @Override public Boolean runAsync() { return false; } @Override public Version since() { return CHVersion.V3_3_1; } } @api(environments={CommandHelperEnvironment.class}) public static class drop_item extends AbstractFunction { @Override public String getName() { return "drop_item"; } @Override public Integer[] numArgs() { return new Integer[]{1, 2, 3}; } @Override public String docs() { return "int {[player/LocationArray], item, [spawnNaturally]} Drops the specified item stack at the specified player's feet (or " + " at an arbitrary Location, if an array is given), and returns its entity id" + " Like the vanilla /give command. player defaults to the current player, and qty defaults to 1." + " item takes an item array." + " spawnNaturally takes a boolean, which forces the way the item will be spawned. If true, the item will be dropped with a random offset."; } @Override public ExceptionType[] thrown() { return new ExceptionType[]{ExceptionType.CastException, ExceptionType.FormatException, ExceptionType.PlayerOfflineException, ExceptionType.InvalidWorldException}; } @Override public boolean isRestricted() { return true; } @Override public CHVersion since() { return CHVersion.V3_2_0; } @Override public Boolean runAsync() { return false; } @Override public Construct exec(Target t, Environment env, Construct... args) throws ConfigRuntimeException { MCLocation l; MCItemStack is; boolean natural; if (args.length == 1) { if (env.getEnv(CommandHelperEnvironment.class).GetPlayer() != null) { l = env.getEnv(CommandHelperEnvironment.class).GetPlayer().getEyeLocation(); natural = false; } else { throw new ConfigRuntimeException("Invalid sender!", ExceptionType.PlayerOfflineException, t); } is = ObjectGenerator.GetGenerator().item(args[0], t); } else { MCPlayer p; if (args[0] instanceof CArray) { p = env.getEnv(CommandHelperEnvironment.class).GetPlayer(); l = ObjectGenerator.GetGenerator().location(args[0], (p != null ? p.getWorld() : null), t); natural = true; } else { p = Static.GetPlayer(args[0].val(), t); Static.AssertPlayerNonNull(p, t); l = p.getEyeLocation(); natural = false; } is = ObjectGenerator.GetGenerator().item(args[1], t); } if (args.length == 3) { natural = Static.getBoolean(args[2]); } MCItem item; if (natural) { item = l.getWorld().dropItemNaturally(l, is); } else { item = l.getWorld().dropItem(l, is); } if (item != null) { return new CInt(item.getEntityId(), t); } else { return CNull.NULL; } } } @api public static class shutdown_server extends AbstractFunction implements Optimizable { @Override public String getName() { return "shutdown_server"; } @Override public Integer[] numArgs() { return new Integer[]{0}; } @Override public ExceptionType[] thrown() { return new ExceptionType[]{}; } @Override public boolean isRestricted() { return true; } @Override public Boolean runAsync() { return false; } @Override public String docs() { return "void {} Shuts down the minecraft server instance."; } @Override public Version since() { return CHVersion.V3_3_1; } @Override public Construct exec(Target t, Environment environment, Construct... args) throws CancelCommandException { Static.getServer().shutdown(); throw new CancelCommandException("", t); } @Override public Set<OptimizationOption> optimizationOptions() { return EnumSet.of( OptimizationOption.TERMINAL ); } } @api public static class monitor_redstone extends AbstractFunction { @Override public ExceptionType[] thrown() { return new ExceptionType[]{ExceptionType.CastException, ExceptionType.FormatException}; } @Override public boolean isRestricted() { return true; } @Override public Boolean runAsync() { return null; } @Override public Construct exec(Target t, Environment environment, Construct... args) throws ConfigRuntimeException { MCWorld world = null; MCPlayer p = environment.getEnv(CommandHelperEnvironment.class).GetPlayer(); if(p != null){ world = p.getWorld(); } MCLocation location = ObjectGenerator.GetGenerator().location(args[0], world, t); boolean add = true; if(args.length > 1){ add = Static.getBoolean(args[1]); } Map<MCLocation, Boolean> redstoneMonitors = ServerEvents.getRedstoneMonitors(); if(add){ redstoneMonitors.put(location, location.getBlock().isBlockPowered()); } else { redstoneMonitors.remove(location); } return CVoid.VOID; } @Override public String getName() { return "monitor_redstone"; } @Override public Integer[] numArgs() { return new Integer[]{1, 2}; } @Override public String docs() { return "void {location, [isMonitored]} Sets up a location to be monitored for redstone changes. If a location is monitored," + " it will cause redstone_changed events to be trigged. By default, isMonitored is true, however, setting it to false" + " will remove the previously monitored location from the list of monitors."; } @Override public Version since() { return CHVersion.V3_3_1; } } }
src/main/java/com/laytonsmith/core/functions/Minecraft.java
package com.laytonsmith.core.functions; import com.laytonsmith.PureUtilities.Common.StringUtils; import com.laytonsmith.PureUtilities.Version; import com.laytonsmith.abstraction.MCAnimalTamer; import com.laytonsmith.abstraction.MCColor; import com.laytonsmith.abstraction.MCCreatureSpawner; import com.laytonsmith.abstraction.MCEntity; import com.laytonsmith.abstraction.MCFireworkBuilder; import com.laytonsmith.abstraction.MCItem; import com.laytonsmith.abstraction.MCItemStack; import com.laytonsmith.abstraction.MCLivingEntity; import com.laytonsmith.abstraction.MCLocation; import com.laytonsmith.abstraction.MCOfflinePlayer; import com.laytonsmith.abstraction.MCPlayer; import com.laytonsmith.abstraction.MCPlugin; import com.laytonsmith.abstraction.MCServer; import com.laytonsmith.abstraction.MCTameable; import com.laytonsmith.abstraction.MCWorld; import com.laytonsmith.abstraction.StaticLayer; import com.laytonsmith.abstraction.blocks.MCMaterial; import com.laytonsmith.abstraction.entities.MCHorse; import com.laytonsmith.abstraction.enums.MCCreeperType; import com.laytonsmith.abstraction.enums.MCDyeColor; import com.laytonsmith.abstraction.enums.MCEffect; import com.laytonsmith.abstraction.enums.MCEntityType; import com.laytonsmith.abstraction.enums.MCFireworkType; import com.laytonsmith.abstraction.enums.MCMobs; import com.laytonsmith.abstraction.enums.MCOcelotType; import com.laytonsmith.abstraction.enums.MCPigType; import com.laytonsmith.abstraction.enums.MCProfession; import com.laytonsmith.abstraction.enums.MCSkeletonType; import com.laytonsmith.abstraction.enums.MCWolfType; import com.laytonsmith.abstraction.enums.MCZombieType; import com.laytonsmith.annotations.api; import com.laytonsmith.core.CHVersion; import com.laytonsmith.core.ObjectGenerator; import com.laytonsmith.core.Optimizable; import com.laytonsmith.core.Static; import com.laytonsmith.core.constructs.CArray; import com.laytonsmith.core.constructs.CBoolean; import com.laytonsmith.core.constructs.CDouble; import com.laytonsmith.core.constructs.CInt; import com.laytonsmith.core.constructs.CNull; import com.laytonsmith.core.constructs.CString; import com.laytonsmith.core.constructs.CVoid; import com.laytonsmith.core.constructs.Construct; import com.laytonsmith.core.constructs.Target; import com.laytonsmith.core.environments.CommandHelperEnvironment; import com.laytonsmith.core.environments.Environment; import com.laytonsmith.core.events.drivers.ServerEvents; import com.laytonsmith.core.exceptions.CancelCommandException; import com.laytonsmith.core.exceptions.ConfigRuntimeException; import com.laytonsmith.core.functions.Exceptions.ExceptionType; import java.io.IOException; import java.lang.management.ManagementFactory; import java.lang.reflect.Field; import java.util.ArrayList; import java.util.Calendar; import java.util.EnumSet; import java.util.Enumeration; import java.util.GregorianCalendar; import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.Properties; import java.util.Set; import java.util.SortedMap; import java.util.TreeMap; import java.util.logging.Level; import java.util.logging.Logger; /** * */ public class Minecraft { public static String docs() { return "These functions provide a hook into game functionality."; } private static final SortedMap<String, Construct> DataValueLookup = new TreeMap<String, Construct>(); private static final SortedMap<String, Construct> DataNameLookup = new TreeMap<String, Construct>(); static { Properties p1 = new Properties(); try { p1.load(Minecraft.class.getResourceAsStream("/data_values.txt")); Enumeration e = p1.propertyNames(); while (e.hasMoreElements()) { String name = e.nextElement().toString(); DataValueLookup.put(name, new CString(p1.getProperty(name).toString(), Target.UNKNOWN)); } } catch (IOException ex) { Logger.getLogger(Minecraft.class.getName()).log(Level.SEVERE, null, ex); } Properties p2 = new Properties(); try { p2.load(Minecraft.class.getResourceAsStream("/data_names.txt")); Enumeration e = p2.propertyNames(); while (e.hasMoreElements()) { String name = e.nextElement().toString(); DataNameLookup.put(name, new CString(p2.getProperty(name).toString(), Target.UNKNOWN)); } } catch (IOException ex) { Logger.getLogger(Minecraft.class.getName()).log(Level.SEVERE, null, ex); } } @api public static class data_values extends AbstractFunction { @Override public String getName() { return "data_values"; } @Override public Integer[] numArgs() { return new Integer[]{1}; } @Override public Construct exec(Target t, Environment env, Construct... args) throws CancelCommandException, ConfigRuntimeException { if (args[0] instanceof CInt) { return new CInt(Static.getInt(args[0], t), t); } else { String c = args[0].val(); int number = StaticLayer.LookupItemId(c); if (number != -1) { return new CInt(number, t); } String changed = c; if (changed.contains(":")) { //Split on that, and reverse. Change wool:red to redwool String split[] = changed.split(":"); if (split.length == 2) { changed = split[1] + split[0]; } } //Remove anything that isn't a letter or a number changed = changed.replaceAll("[^a-zA-Z0-9]", "").toLowerCase(); //Do a lookup in the DataLookup table if (DataValueLookup.containsKey(changed)) { String split[] = DataValueLookup.get(changed).toString().split(":"); if (split[1].equals("0")) { return new CInt(split[0], t); } return new CString(split[0] + ":" + split[1], t); } return CNull.NULL; } } @Override public String docs() { return "int {var1} Does a lookup to return the data value of a name. For instance, returns 1 for 'stone'. If an integer is given," + " simply returns that number. If the data value cannot be found, null is returned."; } @Override public ExceptionType[] thrown() { return new ExceptionType[]{}; } @Override public boolean isRestricted() { return false; } @Override public CHVersion since() { return CHVersion.V3_0_1; } @Override public Boolean runAsync() { return false; } } @api public static class data_name extends AbstractFunction { @Override public String getName() { return "data_name"; } @Override public Integer[] numArgs() { return new Integer[]{1}; } @Override public String docs() { return "string {int | itemArray} Performs the reverse functionality as data_values. Given 1, returns 'Stone'. Note that the enum value" + " given in bukkit's Material class is what is returned as a fallback, if the id doesn't match a value in the internally maintained list." + " If a completely invalid argument is passed" + " in, null is returned."; } @Override public ExceptionType[] thrown() { return new ExceptionType[]{ExceptionType.CastException, ExceptionType.FormatException}; } @Override public boolean isRestricted() { return false; } @Override public CHVersion since() { return CHVersion.V3_3_0; } @Override public Boolean runAsync() { return false; } @Override public Construct exec(Target t, Environment environment, Construct... args) throws ConfigRuntimeException { int i = -1; int i2 = -1; if (args[0] instanceof CString) { //We also accept item notation if (args[0].val().contains(":")) { String[] split = args[0].val().split(":"); try { i = Integer.parseInt(split[0]); i2 = Integer.parseInt(split[1]); } catch (NumberFormatException e) { } catch (ArrayIndexOutOfBoundsException e){ throw new Exceptions.FormatException("Incorrect format for the item notation: " + args[0].val(), t); } } } else if (args[0] instanceof CArray) { MCItemStack is = ObjectGenerator.GetGenerator().item(args[0], t); i = is.getTypeId(); i2 = (int) is.getData().getData(); } if (i == -1) { i = Static.getInt32(args[0], t); } if (i2 == -1) { i2 = 0; } if (DataNameLookup.containsKey(i + "_" + i2)) { return DataNameLookup.get(i + "_" + i2); } else if (DataNameLookup.containsKey(i + "_0")) { return DataNameLookup.get(i + "_0"); } else { try { return new CString(StaticLayer.LookupMaterialName(i), t); } catch (NullPointerException e) { return CNull.NULL; } } } } @api public static class max_stack_size extends AbstractFunction { @Override public String getName() { return "max_stack_size"; } @Override public Integer[] numArgs() { return new Integer[]{1}; } @Override public String docs() { return "integer {itemType | itemArray} Given an item type, returns" + " the maximum allowed stack size. This method will accept either" + " a single data value (i.e. 278) or an item array like is returned" + " from pinv(). Additionally, if a single value, it can also be in" + " the old item notation (i.e. '35:11'), though for the purposes of this" + " function, the data is unneccesary."; } @Override public ExceptionType[] thrown() { return new ExceptionType[]{ExceptionType.CastException, ExceptionType.FormatException}; } @Override public boolean isRestricted() { return false; } @Override public Boolean runAsync() { return false; } @Override public Construct exec(Target t, Environment environment, Construct... args) throws ConfigRuntimeException { if (args[0] instanceof CArray) { MCItemStack is = ObjectGenerator.GetGenerator().item(args[0], t); return new CInt(is.getType().getMaxStackSize(), t); } else { String item = args[0].val(); if (item.contains(":")) { String[] split = item.split(":"); item = split[0]; } try { int iitem = Integer.parseInt(item); int max = StaticLayer.GetItemStack(iitem, 1).getType().getMaxStackSize(); return new CInt(max, t); } catch (NumberFormatException e) { } } throw new ConfigRuntimeException("Improper value passed to max_stack. Expecting a number, or an item array, but received \"" + args[0].val() + "\"", ExceptionType.CastException, t); } @Override public CHVersion since() { return CHVersion.V3_3_0; } } @api(environments = {CommandHelperEnvironment.class}) public static class spawn_mob extends AbstractFunction { @Override public String getName() { return "spawn_mob"; } @Override public Integer[] numArgs() { return new Integer[]{1, 2, 3}; } @Override public String docs() { return "array {mobType, [qty], [location]} Spawns qty mob of one of the following types at location. qty defaults to 1, and location defaults" + " to the location of the player. An array of the entity IDs spawned is returned." + " ---- mobType can be one of: " + StringUtils.Join(MCMobs.values(), ", ", ", or ", " or ") + "." + " Spelling matters, but capitalization doesn't. At this time, the function is limited to spawning a maximum of 50 at a time." + " Further, subtypes can be applied by specifying MOBTYPE:SUBTYPE, for example the sheep subtype can be any of the dye colors: " + StringUtils.Join(MCDyeColor.values(), ", ", ", or ", " or ") + ". COLOR defaults to white if not specified. For mobs with multiple" + " subtypes, separate each type with a \"-\", currently only zombies which, using ZOMBIE:TYPE1-TYPE2 can be any non-conflicting two of: " + StringUtils.Join(MCZombieType.values(), ", ", ", or ", " or ") + ", but default to normal zombies. Ocelots may be one of: " + StringUtils.Join(MCOcelotType.values(), ", ", ", or ", " or ") + ", defaulting to the wild variety. Villagers can have a profession as a subtype: " + StringUtils.Join(MCProfession.values(), ", ", ", or ", " or ") + ", defaulting to farmer if not specified. Skeletons can be " + StringUtils.Join(MCSkeletonType.values(), ", ", ", or ", " or ") + ". PigZombies' subtype represents their anger," + " and accepts an integer, where 0 is neutral and 400 is the normal response to being attacked. Defaults to 0. Similarly, Slime" + " and MagmaCube size can be set by integer, otherwise will be a random natural size. If a material is specified as the subtype" + " for Endermen, they will hold that material, otherwise they will hold nothing. Creepers can be set to " + StringUtils.Join(MCCreeperType.values(), ", ", ", or ", " or ") + ", wolves can be " + StringUtils.Join(MCWolfType.values(), ", ", ", or ", " or ") + ", and pigs can be " + StringUtils.Join(MCPigType.values(), ", ", ", or ", " or ") + "." + " Horses can have three different subTypes, the variant: " + StringUtils.Join(MCHorse.MCHorseVariant.values(), ", ", ", or ", " or ") + "," + " the color: " + StringUtils.Join(MCHorse.MCHorseColor.values(), ", ", ", or ", " or ") + "," + " and the pattern: " + StringUtils.Join(MCHorse.MCHorsePattern.values(), ", ", ", or ", " or ") + "."; } @Override public ExceptionType[] thrown() { return new ExceptionType[]{ExceptionType.CastException, ExceptionType.RangeException, ExceptionType.FormatException, ExceptionType.PlayerOfflineException, ExceptionType.InvalidWorldException}; } @Override public boolean isRestricted() { return true; } @Override public CHVersion since() { return CHVersion.V3_1_2; } @Override public Boolean runAsync() { return false; } @Override public Construct exec(Target t, Environment env, Construct... args) throws CancelCommandException, ConfigRuntimeException { String mob = args[0].val(); String secondary = ""; if (mob.contains(":")) { secondary = mob.substring(mob.indexOf(':') + 1); mob = mob.substring(0, mob.indexOf(':')); } int qty = 1; if (args.length > 1) { qty = Static.getInt32(args[1], t); } if (qty > 50) { throw new ConfigRuntimeException("A bit excessive, don't you think? Let's scale that back some, huh?", ExceptionType.RangeException, t); } MCLocation l; MCPlayer p = env.getEnv(CommandHelperEnvironment.class).GetPlayer(); if (args.length == 3) { l = ObjectGenerator.GetGenerator().location(args[2], (p != null ? p.getWorld() : null), t); } else if (p != null) { l = p.getLocation(); } else { throw new ConfigRuntimeException("Invalid sender!", ExceptionType.PlayerOfflineException, t); } try{ return l.getWorld().spawnMob(MCMobs.valueOf(mob.toUpperCase().replaceAll(" ", "")), secondary, qty, l, t); } catch(IllegalArgumentException e){ throw new ConfigRuntimeException("Invalid mob name: " + mob, ExceptionType.FormatException, t); } } } @api(environments={CommandHelperEnvironment.class}) public static class tame_mob extends AbstractFunction { @Override public String getName() { return "tame_mob"; } @Override public Integer[] numArgs() { return new Integer[]{1, 2}; } @Override public String docs() { return "void {[player], entityID} Tames any tameable mob to the specified player. Offline players are" + " supported, but this means that partial matches are NOT supported. You must type the players" + " name exactly. Setting the player to null will untame the mob. If the entity doesn't exist," + " nothing happens."; } @Override public ExceptionType[] thrown() { return new ExceptionType[]{ExceptionType.UntameableMobException, ExceptionType.CastException, ExceptionType.BadEntityException}; } @Override public boolean isRestricted() { return true; } @Override public CHVersion since() { return CHVersion.V3_3_0; } @Override public Boolean runAsync() { return false; } @Override public Construct exec(Target t, Environment environment, Construct... args) throws ConfigRuntimeException { String player = null; MCPlayer mcPlayer = environment.getEnv(CommandHelperEnvironment.class).GetPlayer(); if (mcPlayer != null) { player = mcPlayer.getName(); } Construct entityID = null; if (args.length == 2) { if (args[0] instanceof CNull) { player = null; } else { player = args[0].val(); } entityID = args[1]; } else { entityID = args[0]; } int id = Static.getInt32(entityID, t); MCLivingEntity e = Static.getLivingEntity(id, t); if (e == null) { return CVoid.VOID; } else if (e instanceof MCTameable) { MCTameable mct = ((MCTameable) e); if (player != null) { mct.setOwner(Static.getServer().getOfflinePlayer(player)); } else { mct.setOwner(null); } return CVoid.VOID; } else { throw new ConfigRuntimeException("The specified entity is not tameable", ExceptionType.UntameableMobException, t); } } } @api public static class get_mob_owner extends AbstractFunction { @Override public String getName() { return "get_mob_owner"; } @Override public Integer[] numArgs() { return new Integer[]{1}; } @Override public String docs() { return "string {entityID} Returns the owner's name, or null if the mob is unowned. An UntameableMobException is thrown if" + " mob isn't tameable to begin with."; } @Override public ExceptionType[] thrown() { return new ExceptionType[]{ExceptionType.UntameableMobException, ExceptionType.CastException, ExceptionType.BadEntityException}; } @Override public boolean isRestricted() { return true; } @Override public CHVersion since() { return CHVersion.V3_3_0; } @Override public Boolean runAsync() { return false; } @Override public Construct exec(Target t, Environment environment, Construct... args) throws ConfigRuntimeException { int id = Static.getInt32(args[0], t); MCLivingEntity e = Static.getLivingEntity(id, t); if (e == null) { return CNull.NULL; } else if (e instanceof MCTameable) { MCAnimalTamer at = ((MCTameable) e).getOwner(); if (null != at) { return new CString(at.getName(), t); } else { return CNull.NULL; } } else { throw new ConfigRuntimeException("The specified entity is not tameable", ExceptionType.UntameableMobException, t); } } } @api public static class is_tameable extends AbstractFunction { @Override public String getName() { return "is_tameable"; } @Override public Integer[] numArgs() { return new Integer[]{1}; } @Override public String docs() { return "boolean {entityID} Returns true or false if the specified entity is tameable"; } @Override public ExceptionType[] thrown() { return new ExceptionType[]{ExceptionType.CastException, ExceptionType.BadEntityException}; } @Override public boolean isRestricted() { return true; } @Override public CHVersion since() { return CHVersion.V3_3_0; } @Override public Boolean runAsync() { return false; } @Override public Construct exec(Target t, Environment environment, Construct... args) throws ConfigRuntimeException { int id = Static.getInt32(args[0], t); MCEntity e = Static.getEntity(id, t); boolean ret; if (e == null) { ret = false; } else if (e instanceof MCTameable) { ret = true; } else { ret = false; } return CBoolean.get(ret); } } @api(environments={CommandHelperEnvironment.class}) public static class make_effect extends AbstractFunction { @Override public String getName() { return "make_effect"; } @Override public Integer[] numArgs() { return new Integer[]{2, 3}; } @Override public String docs() { return "void {xyzArray, effect, [radius]} Plays the specified effect (sound effect) at the given location, for all players within" + " the radius (or 64 by default). The effect can be one of the following: " + StringUtils.Join(MCEffect.values(), ", ", ", or ", " or ") + ". Additional data can be supplied with the syntax EFFECT:DATA. The RECORD_PLAY effect takes the item" + " id of a disc as data, STEP_SOUND takes a blockID and SMOKE takes a direction bit (4 is upwards)."; } @Override public ExceptionType[] thrown() { return new ExceptionType[]{ExceptionType.CastException, ExceptionType.FormatException}; } @Override public boolean isRestricted() { return true; } @Override public CHVersion since() { return CHVersion.V3_1_3; } @Override public Boolean runAsync() { return false; } @Override public Construct exec(Target t, Environment env, Construct... args) throws ConfigRuntimeException { MCLocation l = ObjectGenerator.GetGenerator().location(args[0], (env.getEnv(CommandHelperEnvironment.class).GetCommandSender() instanceof MCPlayer ? env.getEnv(CommandHelperEnvironment.class).GetPlayer().getWorld() : null), t); MCEffect e = null; String preEff = args[1].val(); int data = 0; int radius = 64; if (preEff.contains(":")) { try { data = Integer.parseInt(preEff.substring(preEff.indexOf(':') + 1)); } catch (NumberFormatException ex) { throw new ConfigRuntimeException("Effect data expected an integer", ExceptionType.CastException, t); } preEff = preEff.substring(0, preEff.indexOf(':')); } try { e = MCEffect.valueOf(preEff.toUpperCase()); } catch (IllegalArgumentException ex) { throw new ConfigRuntimeException("The effect type " + args[1].val() + " is not valid", ExceptionType.FormatException, t); } if (e.equals(MCEffect.STEP_SOUND) && (data < 0 || data > StaticLayer.GetConvertor().getMaxBlockID())) { throw new ConfigRuntimeException("This effect requires a valid BlockID", ExceptionType.FormatException, t); } if (args.length == 3) { radius = Static.getInt32(args[2], t); } l.getWorld().playEffect(l, e, data, radius); return CVoid.VOID; } } @api public static class set_entity_health extends AbstractFunction { @Override public String getName() { return "set_entity_health"; } @Override public Integer[] numArgs() { return new Integer[]{2}; } @Override public String docs() { return "void {entityID, healthPercent} Sets the specified entity's health as a percentage," + " where 0 kills it and 100 gives it full health." + " An exception is thrown if the entityID doesn't exist or isn't a LivingEntity."; } @Override public ExceptionType[] thrown() { return new ExceptionType[]{ExceptionType.CastException, ExceptionType.BadEntityException, ExceptionType.RangeException}; } @Override public boolean isRestricted() { return true; } @Override public CHVersion since() { return CHVersion.V3_3_0; } @Override public Boolean runAsync() { return false; } @Override public Construct exec(Target t, Environment environment, Construct... args) throws ConfigRuntimeException { MCLivingEntity e = Static.getLivingEntity(Static.getInt32(args[0], t), t); double percent = Static.getDouble(args[1], t); if (percent < 0 || percent > 100) { throw new ConfigRuntimeException("Health was expected to be a percentage between 0 and 100", ExceptionType.RangeException, t); } else { e.setHealth(percent / 100.0 * e.getMaxHealth()); } return CVoid.VOID; } } @api public static class get_entity_health extends AbstractFunction { @Override public String getName() { return "get_entity_health"; } @Override public Integer[] numArgs() { return new Integer[]{1}; } @Override public String docs() { return "double {entityID} Returns the entity's health as a percentage of its maximum health." + " If the specified entity doesn't exist, or is not a LivingEntity, a format exception is thrown."; } @Override public ExceptionType[] thrown() { return new ExceptionType[]{ExceptionType.CastException, ExceptionType.BadEntityException}; } @Override public boolean isRestricted() { return true; } @Override public CHVersion since() { return CHVersion.V3_3_0; } @Override public Boolean runAsync() { return false; } @Override public Construct exec(Target t, Environment environment, Construct... args) throws ConfigRuntimeException { MCLivingEntity e = Static.getLivingEntity(Static.getInt32(args[0], t), t); return new CDouble(e.getHealth() / e.getMaxHealth() * 100.0, t); } } @api(environments={CommandHelperEnvironment.class}) public static class get_server_info extends AbstractFunction { @Override public String getName() { return "get_server_info"; } @Override public Integer[] numArgs() { return new Integer[]{0, 1}; } @Override public String docs() { return "mixed {[value]} Returns various information about server." + "If value is set, it should be an integer of one of the following indexes, and only that information for that index" + " will be returned. ---- Otherwise if value is not specified (or is -1), it returns an array of" + " information with the following pieces of information in the specified index: " + "<ul><li>0 - Server name; the name of the server in server.properties.</li>" + "<li>1 - API version; The version of the plugin API this server is implementing.</li>" + "<li>2 - Server version; The bare version string of the server implementation.</li>" + "<li>3 - Allow flight; If true, Minecraft's inbuilt anti fly check is enabled.</li>" + "<li>4 - Allow nether; is true, the Nether dimension is enabled</li>" + "<li>5 - Allow end; if true, the End is enabled</li>" + "<li>6 - World container; The path to the world container.</li>" + "<li>7 - Max player limit; returns the player limit.</li>" + "<li>8 - Operators; An array of operators on the server.</li>" + "<li>9 - Plugins; An array of plugins loaded by the server.</li>" + "<li>10 - Online Mode; If true, users are authenticated with Mojang before login</li>" + "<li>11 - Server port; Get the game port that the server runs on</li>" + "<li>12 - Server IP; Get the IP that the server runs on</li>" + "<li>13 - Uptime; The number of milliseconds the server has been running</li>" + "<li>14 - gcmax; The maximum amount of memory that the Java virtual machine will attempt to use</li>" + "<li>15 - gctotal; The total amount of memory in the Java virtual machine</li>" + "<li>16 - gcfree; The amount of free memory in the Java Virtual Machine</li></ul>"; } @Override public ExceptionType[] thrown() { return new ExceptionType[]{ExceptionType.CastException, ExceptionType.RangeException}; } @Override public boolean isRestricted() { return false; } @Override public CHVersion since() { return CHVersion.V3_3_1; } @Override public Boolean runAsync() { return true; } @Override public Construct exec(Target t, Environment env, Construct... args) throws CancelCommandException, ConfigRuntimeException { MCServer server = StaticLayer.GetServer(); int index = -1; if (args.length == 0) { index = -1; } else if (args.length == 1) { index = Static.getInt32(args[0], t); } if (index < -1 || index > 12) { throw new ConfigRuntimeException("get_server_info expects the index to be between -1 and 12 (inclusive)", ExceptionType.RangeException, t); } assert index >= -1 && index <= 12; // Is this needed? Above statement should cause this to never be true. - entityreborn ArrayList<Construct> retVals = new ArrayList<Construct>(); if (index == 0 || index == -1) { //Server name retVals.add(new CString(server.getServerName(), t)); } if (index == 1 || index == -1) { // API Version retVals.add(new CString(server.getAPIVersion(), t)); } if (index == 2 || index == -1) { // Server Version retVals.add(new CString(server.getServerVersion(), t)); } if (index == 3 || index == -1) { //Allow flight retVals.add(CBoolean.get(server.getAllowFlight())); } if (index == 4 || index == -1) { //Allow nether retVals.add(CBoolean.get(server.getAllowNether())); } if (index == 5 || index == -1) { //Allow end retVals.add(CBoolean.get(server.getAllowEnd())); } if (index == 6 || index == -1) { //World container retVals.add(new CString(server.getWorldContainer(), t)); } if (index == 7 || index == -1) { //Max player limit retVals.add(new CInt(server.getMaxPlayers(), t)); } if (index == 8 || index == -1) { //Array of op's CArray co = new CArray(t); List<MCOfflinePlayer> so = server.getOperators(); for (MCOfflinePlayer o : so) { if (o == null) { continue; } CString os = new CString(o.getName(), t); co.push(os); } retVals.add(co); } if (index == 9 || index == -1) { //Array of plugins CArray co = new CArray(t); List<MCPlugin> plugs = server.getPluginManager().getPlugins(); for (MCPlugin p : plugs) { if (p == null) { continue; } CString name = new CString(p.getName(), t); co.push(name); } retVals.add(co); } if (index == 10 || index == -1) { //Online Mode retVals.add(CBoolean.get(server.getOnlineMode())); } if (index == 11 || index == -1) { //Server port retVals.add(new CInt(server.getPort(), t)); } if (index == 12 || index == -1) { //Server Ip retVals.add(new CString(server.getIp(), t)); } if (index == 13 || index == -1) { //Uptime double uptime = (double)(new GregorianCalendar().getTimeInMillis() - ManagementFactory.getRuntimeMXBean().getStartTime()); retVals.add(new CDouble(uptime, t)); } if (index == 14 || index == -1) { //gcmax retVals.add(new CInt((Runtime.getRuntime().maxMemory() / 1024 / 1024), t)); } if (index == 15 || index == -1) { //gctotal retVals.add(new CInt((Runtime.getRuntime().totalMemory() / 1024 / 1024), t)); } if (index == 16 || index == -1) { //gcfree retVals.add(new CInt((Runtime.getRuntime().freeMemory() / 1024 / 1024), t)); } if (retVals.size() == 1) { return retVals.get(0); } else { CArray ca = new CArray(t); for (Construct c : retVals) { ca.push(c); } return ca; } } } @api(environments={CommandHelperEnvironment.class}) public static class get_banned_players extends AbstractFunction { @Override public String getName() { return "get_banned_players"; } @Override public Integer[] numArgs() { return new Integer[]{0}; } @Override public String docs() { return "Array {} An array of players banned on the server."; } @Override public ExceptionType[] thrown() { return new ExceptionType[]{}; } @Override public boolean isRestricted() { return false; } @Override public CHVersion since() { return CHVersion.V3_3_1; } @Override public Boolean runAsync() { return true; } @Override public Construct exec(Target t, Environment env, Construct... args) throws CancelCommandException, ConfigRuntimeException { MCServer server = env.getEnv(CommandHelperEnvironment.class).GetCommandSender().getServer(); CArray co = new CArray(t); List<MCOfflinePlayer> so = server.getBannedPlayers(); for (MCOfflinePlayer o : so) { if (o == null) { continue; } CString os = new CString(o.getName(), t); co.push(os); } return co; } } @api(environments={CommandHelperEnvironment.class}) public static class get_whitelisted_players extends AbstractFunction { @Override public String getName() { return "get_whitelisted_players"; } @Override public Integer[] numArgs() { return new Integer[]{0}; } @Override public String docs() { return "Array {} An array of players whitelisted on the server."; } @Override public ExceptionType[] thrown() { return new ExceptionType[]{}; } @Override public boolean isRestricted() { return false; } @Override public CHVersion since() { return CHVersion.V3_3_1; } @Override public Boolean runAsync() { return true; } @Override public Construct exec(Target t, Environment env, Construct... args) throws CancelCommandException, ConfigRuntimeException { MCServer server = env.getEnv(CommandHelperEnvironment.class).GetCommandSender().getServer(); CArray co = new CArray(t); List<MCOfflinePlayer> so = server.getWhitelistedPlayers(); for (MCOfflinePlayer o : so) { if (o == null) { continue; } CString os = new CString(o.getName(), t); co.push(os); } return co; } } @api(environments={CommandHelperEnvironment.class}) public static class get_spawner_type extends AbstractFunction{ @Override public ExceptionType[] thrown() { return new ExceptionType[]{ExceptionType.FormatException}; } @Override public boolean isRestricted() { return true; } @Override public Boolean runAsync() { return false; } @Override public Construct exec(Target t, Environment environment, Construct... args) throws ConfigRuntimeException { MCWorld w = null; MCPlayer p = environment.getEnv(CommandHelperEnvironment.class).GetPlayer(); if(p != null){ w = p.getWorld(); } MCLocation location = ObjectGenerator.GetGenerator().location(args[0], w, t); if(location.getBlock().getState() instanceof MCCreatureSpawner){ String type = ((MCCreatureSpawner)location.getBlock().getState()).getSpawnedType().name(); return new CString(type, t); } else { throw new Exceptions.FormatException("The block at " + location.toString() + " is not a spawner block", t); } } @Override public String getName() { return "get_spawner_type"; } @Override public Integer[] numArgs() { return new Integer[]{1}; } @Override public String docs() { return "string {locationArray} Gets the spawner type of the specified mob spawner. ----" + " Valid types will be one of the mob types."; } @Override public CHVersion since() { return CHVersion.V3_3_1; } } @api(environments={CommandHelperEnvironment.class}) public static class set_spawner_type extends AbstractFunction{ @Override public ExceptionType[] thrown() { return new ExceptionType[]{ExceptionType.FormatException}; } @Override public boolean isRestricted() { return true; } @Override public Boolean runAsync() { return false; } @Override public Construct exec(Target t, Environment environment, Construct... args) throws ConfigRuntimeException { MCWorld w = null; MCPlayer p = environment.getEnv(CommandHelperEnvironment.class).GetPlayer(); if(p != null){ w = p.getWorld(); } MCLocation location = ObjectGenerator.GetGenerator().location(args[0], w, t); MCEntityType type; try { type = MCEntityType.valueOf(args[1].val().toUpperCase()); } catch (IllegalArgumentException iae) { throw new ConfigRuntimeException("Not a registered entity type: " + args[1].val(), ExceptionType.BadEntityException, t); } if(location.getBlock().getState() instanceof MCCreatureSpawner){ ((MCCreatureSpawner)location.getBlock().getState()).setSpawnedType(type); return CVoid.VOID; } else { throw new Exceptions.FormatException("The block at " + location.toString() + " is not a spawner block", t); } } @Override public String getName() { return "set_spawner_type"; } @Override public Integer[] numArgs() { return new Integer[]{2}; } @Override public String docs() { return "void {locationArray, type} Sets the mob spawner type at the location specified. If the location is not a mob spawner," + " or if the type is invalid, a FormatException is thrown. The type may be one of either " + StringUtils.Join(MCEntityType.MCVanillaEntityType.values(), ", ", ", or "); } @Override public CHVersion since() { return CHVersion.V3_3_1; } } @api(environments={CommandHelperEnvironment.class}) public static class launch_firework extends AbstractFunction { @Override public ExceptionType[] thrown() { return new ExceptionType[]{ExceptionType.FormatException}; } @Override public boolean isRestricted() { return true; } @Override public Boolean runAsync() { return false; } @Override public Construct exec(Target t, Environment environment, Construct... args) throws ConfigRuntimeException { MCPlayer p = environment.getEnv(CommandHelperEnvironment.class).GetPlayer(); MCWorld w = null; if(p != null){ w = p.getWorld(); } MCLocation loc = ObjectGenerator.GetGenerator().location(args[0], w, t); CArray options = new CArray(t); if(args.length == 2){ options = Static.getArray(args[1], t); } int strength = 2; boolean flicker = false; boolean trail = true; Set<MCColor> colors = new HashSet<MCColor>(); colors.add(MCColor.WHITE); Set<MCColor> fade = new HashSet<MCColor>(); MCFireworkType type = MCFireworkType.BALL; if(options.containsKey("strength")){ strength = Static.getInt32(options.get("strength", t), t); if (strength < 0 || strength > 128) { throw new ConfigRuntimeException("Strength must be between 0 and 128", ExceptionType.RangeException, t); } } if(options.containsKey("flicker")){ flicker = Static.getBoolean(options.get("flicker", t)); } if(options.containsKey("trail")){ trail = Static.getBoolean(options.get("trail", t)); } if(options.containsKey("colors")){ colors = parseColors(options.get("colors", t), t); } if(options.containsKey("fade")){ fade = parseColors(options.get("fade", t), t); } if(options.containsKey("type")){ try{ type = MCFireworkType.valueOf(options.get("type", t).val().toUpperCase()); } catch(IllegalArgumentException e){ throw new Exceptions.FormatException("Invalid type: " + options.get("type", t).val(), t); } } MCFireworkBuilder fw = StaticLayer.GetConvertor().GetFireworkBuilder(); fw.setStrength(strength); fw.setFlicker(flicker); fw.setTrail(trail); fw.setType(type); for(MCColor color : colors){ fw.addColor(color); } for(MCColor color : fade){ fw.addFadeColor(color); } return new CInt(fw.launch(loc), t); } private Set<MCColor> parseColors(Construct c, Target t){ Set<MCColor> colors = new HashSet<MCColor>(); if(c instanceof CArray){ CArray ca = ((CArray)c); if(ca.size() == 3 && ca.get(0, t) instanceof CInt && ca.get(1, t) instanceof CInt && ca.get(2, t) instanceof CInt ){ //It's a single custom color colors.add(parseColor(ca, t)); } else { for(String key : ca.stringKeySet()){ Construct val = ca.get(key, t); if(val instanceof CArray){ colors.add(parseColor(((CArray)val), t)); } else if(val instanceof CString){ colors.addAll(parseColor(((CString)val), t)); } } } } else if(c instanceof CString){ colors.addAll(parseColor(((CString)c), t)); } return colors; } private MCColor parseColor(CArray ca, Target t){ return StaticLayer.GetConvertor().GetColor( Static.getInt32(ca.get(0, t), t), Static.getInt32(ca.get(1, t), t), Static.getInt32(ca.get(2, t), t) ); } private List<MCColor> parseColor(CString cs, Target t){ String split[] = cs.val().split("\\|"); List<MCColor> colors = new ArrayList<>(); for(String s : split){ colors.add(StaticLayer.GetConvertor().GetColor(s, t)); } return colors; } @Override public String getName() { return "launch_firework"; } @Override public Integer[] numArgs() { return new Integer[]{1, 2}; } @Override public String docs() { Class c; try { //Since MCColor actually depends on a bukkit server, we don't want to require that for //the sake of documentation, so we'll build the color list much more carefully. //Note the false, so we don't actually initialize the class. c = Class.forName(MCColor.class.getName(), false, this.getClass().getClassLoader()); } catch (ClassNotFoundException ex) { //Hrm... Logger.getLogger(Minecraft.class.getName()).log(Level.SEVERE, null, ex); return ""; } List<String> names = new ArrayList<String>(); for(Field f : c.getFields()){ if(f.getType() == MCColor.class){ names.add(f.getName()); } } return "void {locationArray, [optionsArray]} Launches a firework. The location array specifies where it is launched from," + " and the options array is an associative array described below. All parameters in the associative array are" + " optional, and default to the specified values if not set. The default options being set will make it look like" + " a normal firework, with a white explosion. ----" + " The options array may have the following keys:\n" + "{| cellspacing=\"1\" cellpadding=\"1\" border=\"1\" class=\"wikitable\"\n" + "! Array key !! Description !! Default\n" + "|-\n" + "| strength || A number specifying how far up the firework should go || 2\n" + "|-\n" + "| flicker || A boolean, determining if the firework will flicker\n || false\n" + "|-\n" + "| trail || A boolean, determining if the firework will leave a trail || true\n" + "|-\n" + "| colors || An array of colors, or a pipe seperated string of color names (for the named colors only)" + " for instance: array('WHITE') or 'WHITE<nowiki>|</nowiki>BLUE'. If you want custom colors, you must use an array, though" + " you can still use color names as an item in the array, for instance: array('ORANGE', array(30, 45, 150))." + " These colors are used as the primary colors. || 'WHITE'\n" + "|-\n" + "| fade || An array of colors to be used as the fade colors. This parameter should be formatted the same as" + " the colors parameter || array()\n" + "|-\n" + "| type || An enum value of one of the firework types, one of: " + StringUtils.Join(MCFireworkType.values(), ", ", " or ") + " || " + MCFireworkType.BALL.name() + "\n" + "|}\n" + "The \"named colors\" can be one of: " + StringUtils.Join(names, ", ", " or "); } @Override public CHVersion since() { return CHVersion.V3_3_1; } } @api public static class send_texturepack extends AbstractFunction { @Override public ExceptionType[] thrown() { return new ExceptionType[]{ExceptionType.PlayerOfflineException}; } @Override public boolean isRestricted() { return true; } @Override public Boolean runAsync() { return false; } @Override public Construct exec(Target t, Environment environment, Construct... args) throws ConfigRuntimeException { MCPlayer p = Static.GetPlayer(args[0], t); p.sendTexturePack(args[1].val()); return CVoid.VOID; } @Override public String getName() { return "send_texturepack"; } @Override public Integer[] numArgs() { return new Integer[]{2}; } @Override public String docs() { return "void {player, url} Sends a texturepack URL to the player's client." + " If the client has not been requested to change textures in the" + " past, they will recieve a confirmation dialog before downloading" + " and switching to the new pack. Clients that ignore server textures" + " will not recieve the request, so this function will not affect them."; } @Override public CHVersion since() { return CHVersion.V3_3_1; } } @api public static class send_resourcepack extends AbstractFunction { @Override public ExceptionType[] thrown() { return new ExceptionType[]{ExceptionType.PlayerOfflineException}; } @Override public boolean isRestricted() { return true; } @Override public Boolean runAsync() { return false; } @Override public Construct exec(Target t, Environment environment, Construct... args) throws ConfigRuntimeException { MCPlayer p = Static.GetPlayer(args[0], t); p.sendResourcePack(args[1].val()); return CVoid.VOID; } @Override public String getName() { return "send_resourcepack"; } @Override public Integer[] numArgs() { return new Integer[]{2}; } @Override public String docs() { return "void {player, url} Sends a resourcepack URL to the player's client." + " If the client has not been requested to change resources in the" + " past, they will recieve a confirmation dialog before downloading" + " and switching to the new pack. Clients that ignore server resources" + " will not recieve the request, so this function will not affect them."; } @Override public CHVersion since() { return CHVersion.V3_3_1; } } @api public static class get_ip_bans extends AbstractFunction { @Override public ExceptionType[] thrown() { return new ExceptionType[]{}; } @Override public boolean isRestricted() { return true; } @Override public Boolean runAsync() { return false; } @Override public Construct exec(Target t, Environment environment, Construct... args) throws ConfigRuntimeException { MCServer s = Static.getServer(); CArray ret = new CArray(t); for (String ip : s.getIPBans()) { ret.push(new CString(ip, t)); } return ret; } @Override public String getName() { return "get_ip_bans"; } @Override public Integer[] numArgs() { return new Integer[]{0}; } @Override public String docs() { return "array {} Returns an array of entries from banned-ips.txt."; } @Override public CHVersion since() { return CHVersion.V3_3_1; } } @api public static class set_ip_banned extends AbstractFunction { @Override public ExceptionType[] thrown() { return new ExceptionType[]{}; } @Override public boolean isRestricted() { return true; } @Override public Boolean runAsync() { return false; } @Override public Construct exec(Target t, Environment environment, Construct... args) throws ConfigRuntimeException { MCServer s = Static.getServer(); String ip = args[0].val(); if (Static.getBoolean(args[1])) { s.banIP(ip); } else { s.unbanIP(ip); } return CVoid.VOID; } @Override public String getName() { return "set_ip_banned"; } @Override public Integer[] numArgs() { return new Integer[]{2}; } @Override public String docs() { return "void {address, banned} If banned is true, address is added to banned-ips.txt," + " if false, the address is removed."; } @Override public CHVersion since() { return CHVersion.V3_3_1; } } @api public static class material_info extends AbstractFunction { @Override public ExceptionType[] thrown() { return new ExceptionType[]{ExceptionType.CastException, ExceptionType.FormatException}; } @Override public Construct exec(Target t, Environment environment, Construct... args) throws ConfigRuntimeException { MCMaterial i = StaticLayer.GetConvertor().getMaterial(Static.getInt32(args[0], t)); CArray ret = new CArray(t); ret.set("maxStacksize", new CInt(i.getMaxStackSize(), t), t); ret.set("maxDurability", new CInt(i.getMaxDurability(), t), t); ret.set("hasGravity", CBoolean.get(i.hasGravity()), t); ret.set("isBlock", CBoolean.get(i.isBlock()), t); ret.set("isBurnable", CBoolean.get(i.isBurnable()), t); ret.set("isEdible", CBoolean.get(i.isEdible()), t); ret.set("isFlammable", CBoolean.get(i.isFlammable()), t); ret.set("isOccluding", CBoolean.get(i.isOccluding()), t); ret.set("isRecord", CBoolean.get(i.isRecord()), t); ret.set("isSolid", CBoolean.get(i.isSolid()), t); ret.set("isTransparent", CBoolean.get(i.isTransparent()), t); return ret; } @Override public String getName() { return "material_info"; } @Override public Integer[] numArgs() { return new Integer[]{1}; } @Override public String docs() { return "array {int} Returns an array of info about the material."; } @Override public boolean isRestricted() { return true; } @Override public Boolean runAsync() { return false; } @Override public Version since() { return CHVersion.V3_3_1; } } @api(environments={CommandHelperEnvironment.class}) public static class drop_item extends AbstractFunction { @Override public String getName() { return "drop_item"; } @Override public Integer[] numArgs() { return new Integer[]{1, 2, 3}; } @Override public String docs() { return "int {[player/LocationArray], item, [spawnNaturally]} Drops the specified item stack at the specified player's feet (or " + " at an arbitrary Location, if an array is given), and returns its entity id" + " Like the vanilla /give command. player defaults to the current player, and qty defaults to 1." + " item takes an item array." + " spawnNaturally takes a boolean, which forces the way the item will be spawned. If true, the item will be dropped with a random offset."; } @Override public ExceptionType[] thrown() { return new ExceptionType[]{ExceptionType.CastException, ExceptionType.FormatException, ExceptionType.PlayerOfflineException, ExceptionType.InvalidWorldException}; } @Override public boolean isRestricted() { return true; } @Override public CHVersion since() { return CHVersion.V3_2_0; } @Override public Boolean runAsync() { return false; } @Override public Construct exec(Target t, Environment env, Construct... args) throws ConfigRuntimeException { MCLocation l; MCItemStack is; boolean natural; if (args.length == 1) { if (env.getEnv(CommandHelperEnvironment.class).GetPlayer() != null) { l = env.getEnv(CommandHelperEnvironment.class).GetPlayer().getEyeLocation(); natural = false; } else { throw new ConfigRuntimeException("Invalid sender!", ExceptionType.PlayerOfflineException, t); } is = ObjectGenerator.GetGenerator().item(args[0], t); } else { MCPlayer p; if (args[0] instanceof CArray) { p = env.getEnv(CommandHelperEnvironment.class).GetPlayer(); l = ObjectGenerator.GetGenerator().location(args[0], (p != null ? p.getWorld() : null), t); natural = true; } else { p = Static.GetPlayer(args[0].val(), t); Static.AssertPlayerNonNull(p, t); l = p.getEyeLocation(); natural = false; } is = ObjectGenerator.GetGenerator().item(args[1], t); } if (args.length == 3) { natural = Static.getBoolean(args[2]); } MCItem item; if (natural) { item = l.getWorld().dropItemNaturally(l, is); } else { item = l.getWorld().dropItem(l, is); } if (item != null) { return new CInt(item.getEntityId(), t); } else { return CNull.NULL; } } } @api public static class shutdown_server extends AbstractFunction implements Optimizable { @Override public String getName() { return "shutdown_server"; } @Override public Integer[] numArgs() { return new Integer[]{0}; } @Override public ExceptionType[] thrown() { return new ExceptionType[]{}; } @Override public boolean isRestricted() { return true; } @Override public Boolean runAsync() { return false; } @Override public String docs() { return "void {} Shuts down the minecraft server instance."; } @Override public Version since() { return CHVersion.V3_3_1; } @Override public Construct exec(Target t, Environment environment, Construct... args) throws CancelCommandException { Static.getServer().shutdown(); throw new CancelCommandException("", t); } @Override public Set<OptimizationOption> optimizationOptions() { return EnumSet.of( OptimizationOption.TERMINAL ); } } @api public static class monitor_redstone extends AbstractFunction { @Override public ExceptionType[] thrown() { return new ExceptionType[]{ExceptionType.CastException, ExceptionType.FormatException}; } @Override public boolean isRestricted() { return true; } @Override public Boolean runAsync() { return null; } @Override public Construct exec(Target t, Environment environment, Construct... args) throws ConfigRuntimeException { MCWorld world = null; MCPlayer p = environment.getEnv(CommandHelperEnvironment.class).GetPlayer(); if(p != null){ world = p.getWorld(); } MCLocation location = ObjectGenerator.GetGenerator().location(args[0], world, t); boolean add = true; if(args.length > 1){ add = Static.getBoolean(args[1]); } Map<MCLocation, Boolean> redstoneMonitors = ServerEvents.getRedstoneMonitors(); if(add){ redstoneMonitors.put(location, location.getBlock().isBlockPowered()); } else { redstoneMonitors.remove(location); } return CVoid.VOID; } @Override public String getName() { return "monitor_redstone"; } @Override public Integer[] numArgs() { return new Integer[]{1, 2}; } @Override public String docs() { return "void {location, [isMonitored]} Sets up a location to be monitored for redstone changes. If a location is monitored," + " it will cause redstone_changed events to be trigged. By default, isMonitored is true, however, setting it to false" + " will remove the previously monitored location from the list of monitors."; } @Override public Version since() { return CHVersion.V3_3_1; } } }
Return memory information in bytes
src/main/java/com/laytonsmith/core/functions/Minecraft.java
Return memory information in bytes
<ide><path>rc/main/java/com/laytonsmith/core/functions/Minecraft.java <ide> + "<li>11 - Server port; Get the game port that the server runs on</li>" <ide> + "<li>12 - Server IP; Get the IP that the server runs on</li>" <ide> + "<li>13 - Uptime; The number of milliseconds the server has been running</li>" <del> + "<li>14 - gcmax; The maximum amount of memory that the Java virtual machine will attempt to use</li>" <del> + "<li>15 - gctotal; The total amount of memory in the Java virtual machine</li>" <del> + "<li>16 - gcfree; The amount of free memory in the Java Virtual Machine</li></ul>"; <add> + "<li>14 - gcmax; The maximum amount of memory that the Java virtual machine will attempt to use, in bytes</li>" <add> + "<li>15 - gctotal; The total amount of memory in the Java virtual machine, in bytes</li>" <add> + "<li>16 - gcfree; The amount of free memory in the Java Virtual Machine, in bytes</li></ul>"; <ide> } <ide> <ide> @Override <ide> } <ide> if (index == 14 || index == -1) { <ide> //gcmax <del> retVals.add(new CInt((Runtime.getRuntime().maxMemory() / 1024 / 1024), t)); <add> retVals.add(new CInt((Runtime.getRuntime().maxMemory()), t)); <ide> } <ide> if (index == 15 || index == -1) { <ide> //gctotal <del> retVals.add(new CInt((Runtime.getRuntime().totalMemory() / 1024 / 1024), t)); <add> retVals.add(new CInt((Runtime.getRuntime().totalMemory()), t)); <ide> } <ide> if (index == 16 || index == -1) { <ide> //gcfree <del> retVals.add(new CInt((Runtime.getRuntime().freeMemory() / 1024 / 1024), t)); <add> retVals.add(new CInt((Runtime.getRuntime().freeMemory()), t)); <ide> } <ide> <ide> if (retVals.size() == 1) {
Java
apache-2.0
468c79baf057dbd4968d5c941fdee07c79f22221
0
4treesCH/strolch,eitchnet/strolch,eitchnet/strolch,4treesCH/strolch,4treesCH/strolch,4treesCH/strolch,eitchnet/strolch,eitchnet/strolch
/* * Copyright 2013 Robert von Burg <[email protected]> * * 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 ch.eitchnet.utils.helper; import java.io.PrintWriter; import java.io.StringWriter; import java.io.UnsupportedEncodingException; import java.security.MessageDigest; import java.security.NoSuchAlgorithmException; import java.text.MessageFormat; import java.util.Properties; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * A helper class to perform different actions on {@link String}s * * @author Robert von Burg <[email protected]> */ public class StringHelper { public static final String NEW_LINE = "\n"; //$NON-NLS-1$ public static final String EMPTY = ""; //$NON-NLS-1$ public static final String SPACE = " "; //$NON-NLS-1$ public static final String NULL = "null"; //$NON-NLS-1$ public static final String DASH = "-"; //$NON-NLS-1$ public static final String UNDERLINE = "_"; //$NON-NLS-1$ public static final String COMMA = ","; //$NON-NLS-1$ public static final String DOT = "."; //$NON-NLS-1$ public static final String SEMICOLON = ";"; //$NON-NLS-1$ public static final String COLON = ":"; //$NON-NLS-1$ private static final Logger logger = LoggerFactory.getLogger(StringHelper.class); /** * Hex char table for fast calculating of hex values */ private static final byte[] HEX_CHAR_TABLE = { (byte) '0', (byte) '1', (byte) '2', (byte) '3', (byte) '4', (byte) '5', (byte) '6', (byte) '7', (byte) '8', (byte) '9', (byte) 'a', (byte) 'b', (byte) 'c', (byte) 'd', (byte) 'e', (byte) 'f' }; /** * Converts each byte of the given byte array to a HEX value and returns the concatenation of these values * * @param raw * the bytes to convert to String using numbers in hexadecimal * * @return the encoded string * * @throws RuntimeException */ public static String getHexString(byte[] raw) throws RuntimeException { try { byte[] hex = new byte[2 * raw.length]; int index = 0; for (byte b : raw) { int v = b & 0xFF; hex[index++] = HEX_CHAR_TABLE[v >>> 4]; hex[index++] = HEX_CHAR_TABLE[v & 0xF]; } return new String(hex, "ASCII"); //$NON-NLS-1$ } catch (UnsupportedEncodingException e) { String msg = MessageFormat.format("Something went wrong while converting to HEX: {0}", e.getMessage()); //$NON-NLS-1$ throw new RuntimeException(msg, e); } } /** * Returns a byte array of a given string by converting each character of the string to a number base 16 * * @param encoded * the string to convert to a byt string * * @return the encoded byte stream */ public static byte[] fromHexString(String encoded) { if ((encoded.length() % 2) != 0) throw new IllegalArgumentException("Input string must contain an even number of characters."); //$NON-NLS-1$ final byte result[] = new byte[encoded.length() / 2]; final char enc[] = encoded.toCharArray(); for (int i = 0; i < enc.length; i += 2) { StringBuilder curr = new StringBuilder(2); curr.append(enc[i]).append(enc[i + 1]); result[i / 2] = (byte) Integer.parseInt(curr.toString(), 16); } return result; } /** * Generates the MD5 Hash of a string and converts it to a HEX string * * @param string * the string to hash * * @return the hash or null, if an exception was thrown */ public static String hashMd5AsHex(String string) { return getHexString(hashMd5(string.getBytes())); } /** * Generates the MD5 Hash of a string. Use {@link StringHelper#getHexString(byte[])} to convert the byte array to a * Hex String which is printable * * @param string * the string to hash * * @return the hash or null, if an exception was thrown */ public static byte[] hashMd5(String string) { return hashMd5(string.getBytes()); } /** * Generates the MD5 Hash of a byte array Use {@link StringHelper#getHexString(byte[])} to convert the byte array to * a Hex String which is printable * * @param bytes * the bytes to hash * * @return the hash or null, if an exception was thrown */ public static byte[] hashMd5(byte[] bytes) { return hash("MD5", bytes); //$NON-NLS-1$ } /** * Generates the SHA1 Hash of a string and converts it to a HEX String * * @param string * the string to hash * * @return the hash or null, if an exception was thrown */ public static String hashSha1AsHex(String string) { return getHexString(hashSha1(string.getBytes())); } /** * Generates the SHA1 Hash of a string Use {@link StringHelper#getHexString(byte[])} to convert the byte array to a * Hex String which is printable * * @param string * the string to hash * * @return the hash or null, if an exception was thrown */ public static byte[] hashSha1(String string) { return hashSha1(string.getBytes()); } /** * Generates the SHA1 Hash of a byte array Use {@link StringHelper#getHexString(byte[])} to convert the byte array * to a Hex String which is printable * * @param bytes * the bytes to hash * * @return the hash or null, if an exception was thrown */ public static byte[] hashSha1(byte[] bytes) { return hash("SHA-1", bytes); //$NON-NLS-1$ } /** * Generates the SHA-256 Hash of a string and converts it to a HEX String * * @param string * the string to hash * * @return the hash or null, if an exception was thrown */ public static String hashSha256AsHex(String string) { return getHexString(hashSha256(string.getBytes())); } /** * Generates the SHA-256 Hash of a string Use {@link StringHelper#getHexString(byte[])} to convert the byte array to * a Hex String which is printable * * @param string * the string to hash * * @return the hash or null, if an exception was thrown */ public static byte[] hashSha256(String string) { return hashSha256(string.getBytes()); } /** * Generates the SHA1 Hash of a byte array Use {@link StringHelper#getHexString(byte[])} to convert the byte array * to a Hex String which is printable * * @param bytes * the bytes to hash * * @return the hash or null, if an exception was thrown */ public static byte[] hashSha256(byte[] bytes) { return hash("SHA-256", bytes); //$NON-NLS-1$ } /** * Returns the hash of an algorithm * * @param algorithm * the algorithm to use * @param string * the string to hash * * @return the hash or null, if an exception was thrown */ public static String hashAsHex(String algorithm, String string) { return getHexString(hash(algorithm, string)); } /** * Returns the hash of an algorithm * * @param algorithm * the algorithm to use * @param string * the string to hash * * @return the hash or null, if an exception was thrown */ public static byte[] hash(String algorithm, String string) { try { MessageDigest digest = MessageDigest.getInstance(algorithm); byte[] hashArray = digest.digest(string.getBytes()); return hashArray; } catch (NoSuchAlgorithmException e) { String msg = MessageFormat.format("Algorithm {0} does not exist!", algorithm); //$NON-NLS-1$ throw new RuntimeException(msg, e); } } /** * Returns the hash of an algorithm * * @param algorithm * the algorithm to use * @param bytes * the bytes to hash * * @return the hash or null, if an exception was thrown */ public static String hashAsHex(String algorithm, byte[] bytes) { return getHexString(hash(algorithm, bytes)); } /** * Returns the hash of an algorithm * * @param algorithm * the algorithm to use * @param bytes * the bytes to hash * * @return the hash or null, if an exception was thrown */ public static byte[] hash(String algorithm, byte[] bytes) { try { MessageDigest digest = MessageDigest.getInstance(algorithm); byte[] hashArray = digest.digest(bytes); return hashArray; } catch (NoSuchAlgorithmException e) { String msg = MessageFormat.format("Algorithm {0} does not exist!", algorithm); //$NON-NLS-1$ throw new RuntimeException(msg, e); } } /** * Normalizes the length of a String. Does not shorten it when it is too long, but lengthens it, depending on the * options set: adding the char at the beginning or appending it at the end * * @param value * string to normalize * @param length * length string must have * @param beginning * add at beginning of value * @param c * char to append when appending * @return the new string */ public static String normalizeLength(String value, int length, boolean beginning, char c) { return normalizeLength(value, length, beginning, false, c); } /** * Normalizes the length of a String. Shortens it when it is too long, giving out a logger warning, or lengthens it, * depending on the options set: appending the char at the beginning or the end * * @param value * string to normalize * @param length * length string must have * @param beginning * append at beginning of value * @param shorten * allow shortening of value * @param c * char to append when appending * @return the new string */ public static String normalizeLength(String value, int length, boolean beginning, boolean shorten, char c) { if (value.length() == length) return value; if (value.length() < length) { String tmp = value; while (tmp.length() != length) { if (beginning) { tmp = c + tmp; } else { tmp = tmp + c; } } return tmp; } else if (shorten) { logger.warn(MessageFormat.format("Shortening length of value: {0}", value)); //$NON-NLS-1$ logger.warn(MessageFormat.format("Length is: {0} max: {1}", value.length(), length)); //$NON-NLS-1$ return value.substring(0, length); } return value; } /** * Calls {@link #replacePropertiesIn(Properties, String)}, with {@link System#getProperties()} as input * * @return a new string with all defined system properties replaced or if an error occurred the original value is * returned */ public static String replaceSystemPropertiesIn(String value) { return replacePropertiesIn(System.getProperties(), value); } /** * Traverses the given string searching for occurrences of ${...} sequences. Theses sequences are replaced with a * {@link Properties#getProperty(String)} value if such a value exists in the properties map. If the value of the * sequence is not in the properties, then the sequence is not replaced * * @param properties * the {@link Properties} in which to get the value * @param value * the value in which to replace any system properties * * @return a new string with all defined properties replaced or if an error occurred the original value is returned */ public static String replacePropertiesIn(Properties properties, String value) { // get a copy of the value String tmpValue = value; // get first occurrence of $ character int pos = -1; int stop = 0; // loop on $ character positions while ((pos = tmpValue.indexOf('$', pos + 1)) != -1) { // if pos+1 is not { character then continue if (tmpValue.charAt(pos + 1) != '{') { continue; } // find end of sequence with } character stop = tmpValue.indexOf('}', pos + 1); // if no stop found, then break as another sequence should be able to start if (stop == -1) { logger.error(MessageFormat.format("Sequence starts at offset {0} but does not end!", pos)); //$NON-NLS-1$ tmpValue = value; break; } // get sequence enclosed by pos and stop String sequence = tmpValue.substring(pos + 2, stop); // make sure sequence doesn't contain $ { } characters if (sequence.contains("$") || sequence.contains("{") || sequence.contains("}")) { //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ String msg = "Enclosed sequence in offsets {0} - {1} contains one of the illegal chars: $ { }: {2}"; //$NON-NLS-1$ msg = MessageFormat.format(msg, pos, stop, sequence); logger.error(msg); tmpValue = value; break; } // sequence is good, so see if we have a property for it String property = properties.getProperty(sequence, StringHelper.EMPTY); // if no property exists, then log and continue if (property.isEmpty()) { // logger.warn("No system property found for sequence " + sequence); continue; } // property exists, so replace in value tmpValue = tmpValue.replace("${" + sequence + "}", property); //$NON-NLS-1$ //$NON-NLS-2$ } return tmpValue; } /** * Calls {@link #replaceProperties(Properties, Properties)} with null as the second argument. This allows for * replacing all properties with itself * * @param properties * the properties in which the values must have any ${...} replaced by values of the respective key */ public static void replaceProperties(Properties properties) { replaceProperties(properties, null); } /** * Checks every value in the {@link Properties} and then then replaces any ${...} variables with keys in this * {@link Properties} value using {@link StringHelper#replacePropertiesIn(Properties, String)} * * @param properties * the properties in which the values must have any ${...} replaced by values of the respective key * @param altProperties * if properties does not contain the ${...} key, then try these alternative properties */ public static void replaceProperties(Properties properties, Properties altProperties) { for (Object keyObj : properties.keySet()) { String key = (String) keyObj; String property = properties.getProperty(key); String newProperty = replacePropertiesIn(properties, property); // try first properties if (!property.equals(newProperty)) { // logger.info("Key " + key + " has replaced property " + property + " with new value " + newProperty); properties.put(key, newProperty); } else if (altProperties != null) { // try alternative properties newProperty = replacePropertiesIn(altProperties, property); if (!property.equals(newProperty)) { // logger.info("Key " + key + " has replaced property " + property + " from alternative properties with new value " + newProperty); properties.put(key, newProperty); } } } } /** * This is a helper method with which it is possible to print the location in the two given strings where they start * to differ. The length of string returned is currently 40 characters, or less if either of the given strings are * shorter. The format of the string is 3 lines. The first line has information about where in the strings the * difference occurs, and the second and third lines contain contexts * * @param s1 * the first string * @param s2 * the second string * * @return the string from which the strings differ with a length of 40 characters within the original strings */ public static String printUnequalContext(String s1, String s2) { byte[] bytes1 = s1.getBytes(); byte[] bytes2 = s2.getBytes(); int i = 0; for (; i < bytes1.length; i++) { if (i > bytes2.length) break; if (bytes1[i] != bytes2[i]) break; } int maxContext = 40; int start = Math.max(0, (i - maxContext)); int end = Math.min(i + maxContext, (Math.min(bytes1.length, bytes2.length))); StringBuilder sb = new StringBuilder(); sb.append("Strings are not equal! Start of inequality is at " + i); //$NON-NLS-1$ sb.append(". Showing " + maxContext); //$NON-NLS-1$ sb.append(" extra characters and start and end:\n"); //$NON-NLS-1$ sb.append("context s1: "); //$NON-NLS-1$ sb.append(s1.substring(start, end)); sb.append("\n"); //$NON-NLS-1$ sb.append("context s2: "); //$NON-NLS-1$ sb.append(s2.substring(start, end)); sb.append("\n"); //$NON-NLS-1$ return sb.toString(); } /** * Formats the given number of milliseconds to a time like #h/m/s/ms/us/ns * * @param millis * the number of milliseconds * * @return format the given number of milliseconds to a time like #h/m/s/ms/us/ns */ public static String formatMillisecondsDuration(final long millis) { return formatNanoDuration(millis * 1000000L); } /** * Formats the given number of nanoseconds to a time like #h/m/s/ms/us/ns * * @param nanos * the number of nanoseconds * * @return format the given number of nanoseconds to a time like #h/m/s/ms/us/ns */ public static String formatNanoDuration(final long nanos) { if (nanos >= 3600000000000L) { return String.format("%.0fh", (nanos / 3600000000000.0D)); //$NON-NLS-1$ } else if (nanos >= 60000000000L) { return String.format("%.0fm", (nanos / 60000000000.0D)); //$NON-NLS-1$ } else if (nanos >= 1000000000L) { return String.format("%.0fs", (nanos / 1000000000.0D)); //$NON-NLS-1$ } else if (nanos >= 1000000L) { return String.format("%.0fms", (nanos / 1000000.0D)); //$NON-NLS-1$ } else if (nanos >= 1000L) { return String.format("%.0fus", (nanos / 1000.0D)); //$NON-NLS-1$ } else { return nanos + "ns"; //$NON-NLS-1$ } } /** * Formats the given {@link Throwable}'s stack trace to a string * * @param t * the throwable for which the stack trace is to be formatted to string * * @return a string representation of the given {@link Throwable}'s stack trace */ public static String formatException(Throwable t) { StringWriter stringWriter = new StringWriter(); PrintWriter writer = new PrintWriter(stringWriter); t.printStackTrace(writer); return stringWriter.toString(); } /** * Simply returns true if the value is null, or empty * * @param value * the value to check * * @return true if the value is null, or empty */ public static boolean isEmpty(String value) { return value == null || value.isEmpty(); } /** * Simply returns true if the value is neither null nor empty * * @param value * the value to check * * @return true if the value is neither null nor empty */ public static boolean isNotEmpty(String value) { return value != null && !value.isEmpty(); } /** * <p> * Parses the given string value to a boolean. This extends the default {@link Boolean#parseBoolean(String)} as it * throws an exception if the string value is not equal to "true" or "false" being case insensitive. * </p> * * <p> * This additional restriction is important where false should really be caught, not any random vaue for false * </p> * * @param value * the value to check * * @return true or false, depending on the string value * * @throws RuntimeException * if the value is empty, or not equal to the case insensitive value "true" or "false" */ public static boolean parseBoolean(String value) throws RuntimeException { if (isEmpty(value)) throw new RuntimeException("Value to parse to boolean is empty! Expected case insensitive true or false"); //$NON-NLS-1$ String tmp = value.toLowerCase(); if (tmp.equals(Boolean.TRUE.toString())) { return true; } else if (tmp.equals(Boolean.FALSE.toString())) { return false; } else { String msg = "Value {0} can not be parsed to boolean! Expected case insensitive true or false"; //$NON-NLS-1$ msg = MessageFormat.format(msg, value); throw new RuntimeException(msg); } } }
src/main/java/ch/eitchnet/utils/helper/StringHelper.java
/* * Copyright 2013 Robert von Burg <[email protected]> * * 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 ch.eitchnet.utils.helper; import java.io.PrintWriter; import java.io.StringWriter; import java.io.UnsupportedEncodingException; import java.security.MessageDigest; import java.security.NoSuchAlgorithmException; import java.text.MessageFormat; import java.util.Properties; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * A helper class to perform different actions on {@link String}s * * @author Robert von Burg <[email protected]> */ public class StringHelper { public static final String NEW_LINE = "\n"; //$NON-NLS-1$ public static final String EMPTY = ""; //$NON-NLS-1$ public static final String SPACE = " "; //$NON-NLS-1$ public static final String NULL = "null"; //$NON-NLS-1$ public static final String DASH = "-"; //$NON-NLS-1$ public static final String UNDERLINE = "_"; //$NON-NLS-1$ public static final String COMMA = ","; //$NON-NLS-1$ public static final String DOT = "."; //$NON-NLS-1$ public static final String SEMICOLON = ";"; //$NON-NLS-1$ public static final String COLON = ":"; //$NON-NLS-1$ private static final Logger logger = LoggerFactory.getLogger(StringHelper.class); /** * Hex char table for fast calculating of hex values */ private static final byte[] HEX_CHAR_TABLE = { (byte) '0', (byte) '1', (byte) '2', (byte) '3', (byte) '4', (byte) '5', (byte) '6', (byte) '7', (byte) '8', (byte) '9', (byte) 'a', (byte) 'b', (byte) 'c', (byte) 'd', (byte) 'e', (byte) 'f' }; /** * Converts each byte of the given byte array to a HEX value and returns the concatenation of these values * * @param raw * the bytes to convert to String using numbers in hexadecimal * * @return the encoded string * * @throws RuntimeException */ public static String getHexString(byte[] raw) throws RuntimeException { try { byte[] hex = new byte[2 * raw.length]; int index = 0; for (byte b : raw) { int v = b & 0xFF; hex[index++] = HEX_CHAR_TABLE[v >>> 4]; hex[index++] = HEX_CHAR_TABLE[v & 0xF]; } return new String(hex, "ASCII"); //$NON-NLS-1$ } catch (UnsupportedEncodingException e) { String msg = MessageFormat.format("Something went wrong while converting to HEX: {0}", e.getMessage()); //$NON-NLS-1$ throw new RuntimeException(msg, e); } } /** * Returns a byte array of a given string by converting each character of the string to a number base 16 * * @param encoded * the string to convert to a byt string * * @return the encoded byte stream */ public static byte[] fromHexString(String encoded) { if ((encoded.length() % 2) != 0) throw new IllegalArgumentException("Input string must contain an even number of characters."); //$NON-NLS-1$ final byte result[] = new byte[encoded.length() / 2]; final char enc[] = encoded.toCharArray(); for (int i = 0; i < enc.length; i += 2) { StringBuilder curr = new StringBuilder(2); curr.append(enc[i]).append(enc[i + 1]); result[i / 2] = (byte) Integer.parseInt(curr.toString(), 16); } return result; } /** * Generates the MD5 Hash of a string and converts it to a HEX string * * @param string * the string to hash * * @return the hash or null, if an exception was thrown */ public static String hashMd5AsHex(String string) { return getHexString(hashMd5(string.getBytes())); } /** * Generates the MD5 Hash of a string. Use {@link StringHelper#getHexString(byte[])} to convert the byte array to a * Hex String which is printable * * @param string * the string to hash * * @return the hash or null, if an exception was thrown */ public static byte[] hashMd5(String string) { return hashMd5(string.getBytes()); } /** * Generates the MD5 Hash of a byte array Use {@link StringHelper#getHexString(byte[])} to convert the byte array to * a Hex String which is printable * * @param bytes * the bytes to hash * * @return the hash or null, if an exception was thrown */ public static byte[] hashMd5(byte[] bytes) { return hash("MD5", bytes); //$NON-NLS-1$ } /** * Generates the SHA1 Hash of a string and converts it to a HEX String * * @param string * the string to hash * * @return the hash or null, if an exception was thrown */ public static String hashSha1AsHex(String string) { return getHexString(hashSha1(string.getBytes())); } /** * Generates the SHA1 Hash of a string Use {@link StringHelper#getHexString(byte[])} to convert the byte array to a * Hex String which is printable * * @param string * the string to hash * * @return the hash or null, if an exception was thrown */ public static byte[] hashSha1(String string) { return hashSha1(string.getBytes()); } /** * Generates the SHA1 Hash of a byte array Use {@link StringHelper#getHexString(byte[])} to convert the byte array * to a Hex String which is printable * * @param bytes * the bytes to hash * * @return the hash or null, if an exception was thrown */ public static byte[] hashSha1(byte[] bytes) { return hash("SHA-1", bytes); //$NON-NLS-1$ } /** * Generates the SHA-256 Hash of a string and converts it to a HEX String * * @param string * the string to hash * * @return the hash or null, if an exception was thrown */ public static String hashSha256AsHex(String string) { return getHexString(hashSha256(string.getBytes())); } /** * Generates the SHA-256 Hash of a string Use {@link StringHelper#getHexString(byte[])} to convert the byte array to * a Hex String which is printable * * @param string * the string to hash * * @return the hash or null, if an exception was thrown */ public static byte[] hashSha256(String string) { return hashSha256(string.getBytes()); } /** * Generates the SHA1 Hash of a byte array Use {@link StringHelper#getHexString(byte[])} to convert the byte array * to a Hex String which is printable * * @param bytes * the bytes to hash * * @return the hash or null, if an exception was thrown */ public static byte[] hashSha256(byte[] bytes) { return hash("SHA-256", bytes); //$NON-NLS-1$ } /** * Returns the hash of an algorithm * * @param algorithm * the algorithm to use * @param string * the string to hash * * @return the hash or null, if an exception was thrown */ public static String hashAsHex(String algorithm, String string) { return getHexString(hash(algorithm, string)); } /** * Returns the hash of an algorithm * * @param algorithm * the algorithm to use * @param string * the string to hash * * @return the hash or null, if an exception was thrown */ public static byte[] hash(String algorithm, String string) { try { MessageDigest digest = MessageDigest.getInstance(algorithm); byte[] hashArray = digest.digest(string.getBytes()); return hashArray; } catch (NoSuchAlgorithmException e) { String msg = MessageFormat.format("Algorithm {0} does not exist!", algorithm); //$NON-NLS-1$ throw new RuntimeException(msg, e); } } /** * Returns the hash of an algorithm * * @param algorithm * the algorithm to use * @param bytes * the bytes to hash * * @return the hash or null, if an exception was thrown */ public static String hashAsHex(String algorithm, byte[] bytes) { return getHexString(hash(algorithm, bytes)); } /** * Returns the hash of an algorithm * * @param algorithm * the algorithm to use * @param bytes * the bytes to hash * * @return the hash or null, if an exception was thrown */ public static byte[] hash(String algorithm, byte[] bytes) { try { MessageDigest digest = MessageDigest.getInstance(algorithm); byte[] hashArray = digest.digest(bytes); return hashArray; } catch (NoSuchAlgorithmException e) { String msg = MessageFormat.format("Algorithm {0} does not exist!", algorithm); //$NON-NLS-1$ throw new RuntimeException(msg, e); } } /** * Normalizes the length of a String. Does not shorten it when it is too long, but lengthens it, depending on the * options set: adding the char at the beginning or appending it at the end * * @param value * string to normalize * @param length * length string must have * @param beginning * add at beginning of value * @param c * char to append when appending * @return the new string */ public static String normalizeLength(String value, int length, boolean beginning, char c) { return normalizeLength(value, length, beginning, false, c); } /** * Normalizes the length of a String. Shortens it when it is too long, giving out a logger warning, or lengthens it, * depending on the options set: appending the char at the beginning or the end * * @param value * string to normalize * @param length * length string must have * @param beginning * append at beginning of value * @param shorten * allow shortening of value * @param c * char to append when appending * @return the new string */ public static String normalizeLength(String value, int length, boolean beginning, boolean shorten, char c) { if (value.length() == length) return value; if (value.length() < length) { String tmp = value; while (tmp.length() != length) { if (beginning) { tmp = c + tmp; } else { tmp = tmp + c; } } return tmp; } else if (shorten) { logger.warn(MessageFormat.format("Shortening length of value: {0}", value)); //$NON-NLS-1$ logger.warn(MessageFormat.format("Length is: {0} max: {1}", value.length(), length)); //$NON-NLS-1$ return value.substring(0, length); } return value; } /** * Calls {@link #replacePropertiesIn(Properties, String)}, with {@link System#getProperties()} as input * * @return a new string with all defined system properties replaced or if an error occurred the original value is * returned */ public static String replaceSystemPropertiesIn(String value) { return replacePropertiesIn(System.getProperties(), value); } /** * Traverses the given string searching for occurrences of ${...} sequences. Theses sequences are replaced with a * {@link Properties#getProperty(String)} value if such a value exists in the properties map. If the value of the * sequence is not in the properties, then the sequence is not replaced * * @param properties * the {@link Properties} in which to get the value * @param value * the value in which to replace any system properties * * @return a new string with all defined properties replaced or if an error occurred the original value is returned */ public static String replacePropertiesIn(Properties properties, String value) { // get a copy of the value String tmpValue = value; // get first occurrence of $ character int pos = -1; int stop = 0; // loop on $ character positions while ((pos = tmpValue.indexOf('$', pos + 1)) != -1) { // if pos+1 is not { character then continue if (tmpValue.charAt(pos + 1) != '{') { continue; } // find end of sequence with } character stop = tmpValue.indexOf('}', pos + 1); // if no stop found, then break as another sequence should be able to start if (stop == -1) { logger.error(MessageFormat.format("Sequence starts at offset {0} but does not end!", pos)); //$NON-NLS-1$ tmpValue = value; break; } // get sequence enclosed by pos and stop String sequence = tmpValue.substring(pos + 2, stop); // make sure sequence doesn't contain $ { } characters if (sequence.contains("$") || sequence.contains("{") || sequence.contains("}")) { //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ String msg = "Enclosed sequence in offsets {0} - {1} contains one of the illegal chars: $ { }: {2}"; //$NON-NLS-1$ msg = MessageFormat.format(msg, pos, stop, sequence); logger.error(msg); tmpValue = value; break; } // sequence is good, so see if we have a property for it String property = properties.getProperty(sequence, StringHelper.EMPTY); // if no property exists, then log and continue if (property.isEmpty()) { // logger.warn("No system property found for sequence " + sequence); continue; } // property exists, so replace in value tmpValue = tmpValue.replace("${" + sequence + "}", property); //$NON-NLS-1$ //$NON-NLS-2$ } return tmpValue; } /** * Calls {@link #replaceProperties(Properties, Properties)} with null as the second argument. This allows for * replacing all properties with itself * * @param properties * the properties in which the values must have any ${...} replaced by values of the respective key */ public static void replaceProperties(Properties properties) { replaceProperties(properties, null); } /** * Checks every value in the {@link Properties} and then then replaces any ${...} variables with keys in this * {@link Properties} value using {@link StringHelper#replacePropertiesIn(Properties, String)} * * @param properties * the properties in which the values must have any ${...} replaced by values of the respective key * @param altProperties * if properties does not contain the ${...} key, then try these alternative properties */ public static void replaceProperties(Properties properties, Properties altProperties) { for (Object keyObj : properties.keySet()) { String key = (String) keyObj; String property = properties.getProperty(key); String newProperty = replacePropertiesIn(properties, property); // try first properties if (!property.equals(newProperty)) { // logger.info("Key " + key + " has replaced property " + property + " with new value " + newProperty); properties.put(key, newProperty); } else if (altProperties != null) { // try alternative properties newProperty = replacePropertiesIn(altProperties, property); if (!property.equals(newProperty)) { // logger.info("Key " + key + " has replaced property " + property + " from alternative properties with new value " + newProperty); properties.put(key, newProperty); } } } } /** * This is a helper method with which it is possible to print the location in the two given strings where they start * to differ. The length of string returned is currently 40 characters, or less if either of the given strings are * shorter. The format of the string is 3 lines. The first line has information about where in the strings the * difference occurs, and the second and third lines contain contexts * * @param s1 * the first string * @param s2 * the second string * * @return the string from which the strings differ with a length of 40 characters within the original strings */ public static String printUnequalContext(String s1, String s2) { byte[] bytes1 = s1.getBytes(); byte[] bytes2 = s2.getBytes(); int i = 0; for (; i < bytes1.length; i++) { if (i > bytes2.length) break; if (bytes1[i] != bytes2[i]) break; } int maxContext = 40; int start = Math.max(0, (i - maxContext)); int end = Math.min(i + maxContext, (Math.min(bytes1.length, bytes2.length))); StringBuilder sb = new StringBuilder(); sb.append("Strings are not equal! Start of inequality is at " + i); //$NON-NLS-1$ sb.append(". Showing " + maxContext); //$NON-NLS-1$ sb.append(" extra characters and start and end:\n"); //$NON-NLS-1$ sb.append("context s1: "); //$NON-NLS-1$ sb.append(s1.substring(start, end)); sb.append("\n"); //$NON-NLS-1$ sb.append("context s2: "); //$NON-NLS-1$ sb.append(s2.substring(start, end)); sb.append("\n"); //$NON-NLS-1$ return sb.toString(); } /** * Formats the given number of milliseconds to a time like 0.000h/m/s/ms/us/ns * * @param millis * the number of milliseconds * * @return format the given number of milliseconds to a time like 0.000h/m/s/ms/us/ns */ public static String formatMillisecondsDuration(final long millis) { return formatNanoDuration(millis * 1000000L); } /** * Formats the given number of nanoseconds to a time like 0.000h/m/s/ms/us/ns * * @param nanos * the number of nanoseconds * * @return format the given number of nanoseconds to a time like 0.000h/m/s/ms/us/ns */ public static String formatNanoDuration(final long nanos) { if (nanos > 3600000000000L) { return String.format("%.3fh", (nanos / 3600000000000.0D)); //$NON-NLS-1$ } else if (nanos > 60000000000L) { return String.format("%.3fm", (nanos / 60000000000.0D)); //$NON-NLS-1$ } else if (nanos > 1000000000L) { return String.format("%.3fs", (nanos / 1000000000.0D)); //$NON-NLS-1$ } else if (nanos > 1000000L) { return String.format("%.3fms", (nanos / 1000000.0D)); //$NON-NLS-1$ } else if (nanos > 1000L) { return String.format("%.3fus", (nanos / 1000.0D)); //$NON-NLS-1$ } else { return nanos + "ns"; //$NON-NLS-1$ } } /** * Formats the given {@link Throwable}'s stack trace to a string * * @param t * the throwable for which the stack trace is to be formatted to string * * @return a string representation of the given {@link Throwable}'s stack trace */ public static String formatException(Throwable t) { StringWriter stringWriter = new StringWriter(); PrintWriter writer = new PrintWriter(stringWriter); t.printStackTrace(writer); return stringWriter.toString(); } /** * Simply returns true if the value is null, or empty * * @param value * the value to check * * @return true if the value is null, or empty */ public static boolean isEmpty(String value) { return value == null || value.isEmpty(); } /** * Simply returns true if the value is neither null nor empty * * @param value * the value to check * * @return true if the value is neither null nor empty */ public static boolean isNotEmpty(String value) { return value != null && !value.isEmpty(); } /** * <p> * Parses the given string value to a boolean. This extends the default {@link Boolean#parseBoolean(String)} as it * throws an exception if the string value is not equal to "true" or "false" being case insensitive. * </p> * * <p> * This additional restriction is important where false should really be caught, not any random vaue for false * </p> * * @param value * the value to check * * @return true or false, depending on the string value * * @throws RuntimeException * if the value is empty, or not equal to the case insensitive value "true" or "false" */ public static boolean parseBoolean(String value) throws RuntimeException { if (isEmpty(value)) throw new RuntimeException("Value to parse to boolean is empty! Expected case insensitive true or false"); //$NON-NLS-1$ String tmp = value.toLowerCase(); if (tmp.equals(Boolean.TRUE.toString())) { return true; } else if (tmp.equals(Boolean.FALSE.toString())) { return false; } else { String msg = "Value {0} can not be parsed to boolean! Expected case insensitive true or false"; //$NON-NLS-1$ msg = MessageFormat.format(msg, value); throw new RuntimeException(msg); } } }
[Minor] StringHelper.formatNanos() does not use decimals anymore
src/main/java/ch/eitchnet/utils/helper/StringHelper.java
[Minor] StringHelper.formatNanos() does not use decimals anymore
<ide><path>rc/main/java/ch/eitchnet/utils/helper/StringHelper.java <ide> } <ide> <ide> /** <del> * Formats the given number of milliseconds to a time like 0.000h/m/s/ms/us/ns <add> * Formats the given number of milliseconds to a time like #h/m/s/ms/us/ns <ide> * <ide> * @param millis <ide> * the number of milliseconds <ide> * <del> * @return format the given number of milliseconds to a time like 0.000h/m/s/ms/us/ns <add> * @return format the given number of milliseconds to a time like #h/m/s/ms/us/ns <ide> */ <ide> public static String formatMillisecondsDuration(final long millis) { <ide> return formatNanoDuration(millis * 1000000L); <ide> } <ide> <ide> /** <del> * Formats the given number of nanoseconds to a time like 0.000h/m/s/ms/us/ns <add> * Formats the given number of nanoseconds to a time like #h/m/s/ms/us/ns <ide> * <ide> * @param nanos <ide> * the number of nanoseconds <ide> * <del> * @return format the given number of nanoseconds to a time like 0.000h/m/s/ms/us/ns <add> * @return format the given number of nanoseconds to a time like #h/m/s/ms/us/ns <ide> */ <ide> public static String formatNanoDuration(final long nanos) { <del> if (nanos > 3600000000000L) { <del> return String.format("%.3fh", (nanos / 3600000000000.0D)); //$NON-NLS-1$ <del> } else if (nanos > 60000000000L) { <del> return String.format("%.3fm", (nanos / 60000000000.0D)); //$NON-NLS-1$ <del> } else if (nanos > 1000000000L) { <del> return String.format("%.3fs", (nanos / 1000000000.0D)); //$NON-NLS-1$ <del> } else if (nanos > 1000000L) { <del> return String.format("%.3fms", (nanos / 1000000.0D)); //$NON-NLS-1$ <del> } else if (nanos > 1000L) { <del> return String.format("%.3fus", (nanos / 1000.0D)); //$NON-NLS-1$ <add> if (nanos >= 3600000000000L) { <add> return String.format("%.0fh", (nanos / 3600000000000.0D)); //$NON-NLS-1$ <add> } else if (nanos >= 60000000000L) { <add> return String.format("%.0fm", (nanos / 60000000000.0D)); //$NON-NLS-1$ <add> } else if (nanos >= 1000000000L) { <add> return String.format("%.0fs", (nanos / 1000000000.0D)); //$NON-NLS-1$ <add> } else if (nanos >= 1000000L) { <add> return String.format("%.0fms", (nanos / 1000000.0D)); //$NON-NLS-1$ <add> } else if (nanos >= 1000L) { <add> return String.format("%.0fus", (nanos / 1000.0D)); //$NON-NLS-1$ <ide> } else { <ide> return nanos + "ns"; //$NON-NLS-1$ <ide> }
Java
mit
1afc64bd4bb30640b1e0906fbaa90c5a6fc86dea
0
takenspc/validator,YOTOV-LIMITED/validator,sammuelyee/validator,takenspc/validator,validator/validator,sammuelyee/validator,validator/validator,sammuelyee/validator,tripu/validator,takenspc/validator,YOTOV-LIMITED/validator,validator/validator,validator/validator,tripu/validator,YOTOV-LIMITED/validator,sammuelyee/validator,YOTOV-LIMITED/validator,takenspc/validator,tripu/validator,sammuelyee/validator,tripu/validator,takenspc/validator,tripu/validator,YOTOV-LIMITED/validator,validator/validator
/* * Copyright (c) 2011 Mozilla Foundation * * Permission is hereby granted, free of charge, to any person obtaining a * copy of this software and associated documentation files (the "Software"), * to deal in the Software without restriction, including without limitation * the rights to use, copy, modify, merge, publish, distribute, sublicense, * and/or sell copies of the Software, and to permit persons to whom the * Software is furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER * DEALINGS IN THE SOFTWARE. */ package org.whattf.datatype; import java.util.Arrays; public class LinkRel extends AbstractRel { private static final String[] REGISTERED_TOKENS = { "alternate", "apple-touch-icon", // extension "apple-touch-icon-precomposed", // extension "apple-touch-startup-image", // extension "author", "canonical", // extension "dns-prefetch", // extension "help", "icon", "license", "me", // extension (Formats table) "next", "openid.delegate", // extension "openid.server", // extension "openid2.local_id", // extension "openid2.provider", // extension "p3pv1", // extension "pgpkey", // extension "pingback", "prefetch", "prerender", // extension "prev", "search", "service", // extension "shortcut", // extension "shortlink", // extension "sidebar", "stylesheet", // tag removed as a spec bug "timesheet", // extension "transformation", // extension (Formats table) "widget", // extension "wlwmanifest" // extension }; /** * The singleton instance. */ public static final LinkRel THE_INSTANCE = new LinkRel(); /** * Package-private constructor */ private LinkRel() { super(); } @Override protected boolean isRegistered(String token) { return Arrays.binarySearch(REGISTERED_TOKENS, token) >= 0; } @Override public String getName() { return "link type valid for <link>"; } }
relaxng/datatype/java/src/org/whattf/datatype/LinkRel.java
/* * Copyright (c) 2011 Mozilla Foundation * * Permission is hereby granted, free of charge, to any person obtaining a * copy of this software and associated documentation files (the "Software"), * to deal in the Software without restriction, including without limitation * the rights to use, copy, modify, merge, publish, distribute, sublicense, * and/or sell copies of the Software, and to permit persons to whom the * Software is furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER * DEALINGS IN THE SOFTWARE. */ package org.whattf.datatype; import java.util.Arrays; public class LinkRel extends AbstractRel { private static final String[] REGISTERED_TOKENS = { "alternate", "apple-touch-icon", // extension "apple-touch-icon-precomposed", // extension "apple-touch-startup-image", // extension "author", "canonical", // extension "dns-prefetch", // extension "help", "icon", "license", "me", // extension (Formats table) "next", "openid.delegate", // extension "openid.server", // extension "openid2.local_id", // extension "openid2.provider", // extension "p3pv1", // extension "pingback", "prefetch", "prerender", // extension "prev", "search", "service", // extension "shortcut", // extension "shortlink", // extension "sidebar", "stylesheet", // tag removed as a spec bug "timesheet", // extension "transformation", // extension (Formats table) "widget", // extension "wlwmanifest" // extension }; /** * The singleton instance. */ public static final LinkRel THE_INSTANCE = new LinkRel(); /** * Package-private constructor */ private LinkRel() { super(); } @Override protected boolean isRegistered(String token) { return Arrays.binarySearch(REGISTERED_TOKENS, token) >= 0; } @Override public String getName() { return "link type valid for <link>"; } }
Add pgpkey to link rels.
relaxng/datatype/java/src/org/whattf/datatype/LinkRel.java
Add pgpkey to link rels.
<ide><path>elaxng/datatype/java/src/org/whattf/datatype/LinkRel.java <ide> "openid2.local_id", // extension <ide> "openid2.provider", // extension <ide> "p3pv1", // extension <add> "pgpkey", // extension <ide> "pingback", <ide> "prefetch", <ide> "prerender", // extension
Java
apache-2.0
28fde9864af7944df7ceb61f1e3b5e4a10added5
0
jenetics/jenetics,jenetics/jenetics,jenetics/jenetics,jenetics/jenetics,jenetics/jenetics,jenetics/jenetics,jenetics/jenetics
/* * Java Genetic Algorithm Library (@__identifier__@). * Copyright (c) @__year__@ Franz Wilhelmstötter * * 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. * * Author: * Franz Wilhelmstötter ([email protected]) */ package org.jenetics.engine; import static java.lang.Math.max; import static java.lang.Math.min; import static java.util.Objects.requireNonNull; import java.util.function.BiPredicate; import java.util.function.DoubleConsumer; import java.util.function.Predicate; import org.jenetics.stat.DoubleMomentStatistics; import org.jenetics.stat.DoubleMoments; /** * @author <a href="mailto:[email protected]">Franz Wilhelmstötter</a> * @version !__version__! * @since !__version__! */ final class FitnessConvergenceLimit<N extends Number & Comparable<? super N>> implements Predicate<EvolutionResult<?, N>> { private final Buffer _shortBuffer; private final Buffer _longBuffer; private final BiPredicate<DoubleMoments, DoubleMoments> _limit; private long _generation; FitnessConvergenceLimit( final int shortFilterSize, final int longFilterSize, final BiPredicate<DoubleMoments, DoubleMoments> limit ) { _shortBuffer = new Buffer(shortFilterSize); _longBuffer = new Buffer(longFilterSize); _limit = requireNonNull(limit); } @Override public boolean test(final EvolutionResult<?, N> result) { final Number fitness = result.getBestFitness(); if (fitness != null) { _shortBuffer.accept(fitness.doubleValue()); _longBuffer.accept(fitness.doubleValue()); ++_generation; } return _generation < _longBuffer.capacity() || _limit.test(_shortBuffer.doubleMoments(), _longBuffer.doubleMoments()); } /** * */ static final class Buffer implements DoubleConsumer { private final double[] _buffer; private int _pos; private int _length; Buffer(final int length) { _buffer = new double[length]; } @Override public void accept(final double value) { _buffer[_pos] = value; _pos = (_pos + 1)%_buffer.length; _length = max(_length + 1, _buffer.length); } public int capacity() { return _buffer.length; } public int length() { return _length; } public DoubleMoments doubleMoments(final int windowSize) { final int length = min(windowSize, _length); final DoubleMomentStatistics statistics = new DoubleMomentStatistics(); for (int i = 0; i < length; ++i) { final int index = (_pos - _length + i)%_buffer.length; statistics.accept(_buffer[index]); } return DoubleMoments.of(statistics); } public DoubleMoments doubleMoments() { final DoubleMomentStatistics statistics = new DoubleMomentStatistics(); for (int i = _buffer.length; --i >=0;) { statistics.accept(_buffer[i]); } return DoubleMoments.of(statistics); } } }
org.jenetics/src/main/java/org/jenetics/engine/FitnessConvergenceLimit.java
/* * Java Genetic Algorithm Library (@__identifier__@). * Copyright (c) @__year__@ Franz Wilhelmstötter * * 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. * * Author: * Franz Wilhelmstötter ([email protected]) */ package org.jenetics.engine; import static java.util.Objects.requireNonNull; import java.util.function.BiPredicate; import java.util.function.DoubleConsumer; import java.util.function.Predicate; import org.jenetics.stat.DoubleMomentStatistics; import org.jenetics.stat.DoubleMoments; /** * @author <a href="mailto:[email protected]">Franz Wilhelmstötter</a> * @version !__version__! * @since !__version__! */ final class FitnessConvergenceLimit<N extends Number & Comparable<? super N>> implements Predicate<EvolutionResult<?, N>> { private final Buffer _shortBuffer; private final Buffer _longBuffer; private final BiPredicate<DoubleMoments, DoubleMoments> _limit; private long _generation; FitnessConvergenceLimit( final int shortFilterSize, final int longFilterSize, final BiPredicate<DoubleMoments, DoubleMoments> limit ) { _shortBuffer = new Buffer(shortFilterSize); _longBuffer = new Buffer(longFilterSize); _limit = requireNonNull(limit); } @Override public boolean test(final EvolutionResult<?, N> result) { final Number fitness = result.getBestFitness(); if (fitness != null) { _shortBuffer.accept(fitness.doubleValue()); _longBuffer.accept(fitness.doubleValue()); ++_generation; } return _generation < _longBuffer.length() || _limit.test(_shortBuffer.doubleMoments(), _longBuffer.doubleMoments()); } private static final class Buffer implements DoubleConsumer { private final double[] _buffer; private int _next; Buffer(final int length) { _buffer = new double[length]; } @Override public void accept(final double value) { _buffer[_next++] = value; if (_next == _buffer.length) { _next = 0; } } public int length() { return _buffer.length; } public DoubleMoments doubleMoments() { final DoubleMomentStatistics statistics = new DoubleMomentStatistics(); for (int i = _buffer.length; --i >=0;) { statistics.accept(_buffer[i]); } return DoubleMoments.of(statistics); } } final static class ModInt extends Number { private final int _modulus; private final int _value; ModInt(final int modulus, final int value) { _modulus = modulus; _value = value; } ModInt add(final int value) { return new ModInt(_modulus, (value + _value)%_modulus); } @Override public int intValue() { return _value; } @Override public long longValue() { return _value; } @Override public float floatValue() { return _value; } @Override public double doubleValue() { return _value; } } }
#150: Implement double Buffer.
org.jenetics/src/main/java/org/jenetics/engine/FitnessConvergenceLimit.java
#150: Implement double Buffer.
<ide><path>rg.jenetics/src/main/java/org/jenetics/engine/FitnessConvergenceLimit.java <ide> */ <ide> package org.jenetics.engine; <ide> <add>import static java.lang.Math.max; <add>import static java.lang.Math.min; <ide> import static java.util.Objects.requireNonNull; <ide> <ide> import java.util.function.BiPredicate; <ide> ++_generation; <ide> } <ide> <del> return _generation < _longBuffer.length() || <add> return _generation < _longBuffer.capacity() || <ide> _limit.test(_shortBuffer.doubleMoments(), _longBuffer.doubleMoments()); <ide> } <ide> <del> private static final class Buffer implements DoubleConsumer { <add> /** <add> * <add> */ <add> static final class Buffer implements DoubleConsumer { <ide> private final double[] _buffer; <ide> <del> private int _next; <add> private int _pos; <add> private int _length; <ide> <ide> Buffer(final int length) { <ide> _buffer = new double[length]; <ide> <ide> @Override <ide> public void accept(final double value) { <del> _buffer[_next++] = value; <del> if (_next == _buffer.length) { <del> _next = 0; <del> } <add> _buffer[_pos] = value; <add> <add> _pos = (_pos + 1)%_buffer.length; <add> _length = max(_length + 1, _buffer.length); <add> } <add> <add> public int capacity() { <add> return _buffer.length; <ide> } <ide> <ide> public int length() { <del> return _buffer.length; <add> return _length; <add> } <add> <add> public DoubleMoments doubleMoments(final int windowSize) { <add> final int length = min(windowSize, _length); <add> final DoubleMomentStatistics statistics = new DoubleMomentStatistics(); <add> <add> for (int i = 0; i < length; ++i) { <add> final int index = (_pos - _length + i)%_buffer.length; <add> statistics.accept(_buffer[index]); <add> } <add> <add> return DoubleMoments.of(statistics); <ide> } <ide> <ide> public DoubleMoments doubleMoments() { <ide> } <ide> } <ide> <del> final static class ModInt extends Number { <del> private final int _modulus; <del> private final int _value; <del> <del> ModInt(final int modulus, final int value) { <del> _modulus = modulus; <del> _value = value; <del> } <del> <del> ModInt add(final int value) { <del> return new ModInt(_modulus, (value + _value)%_modulus); <del> } <del> <del> @Override <del> public int intValue() { <del> return _value; <del> } <del> <del> @Override <del> public long longValue() { <del> return _value; <del> } <del> <del> @Override <del> public float floatValue() { <del> return _value; <del> } <del> <del> @Override <del> public double doubleValue() { <del> return _value; <del> } <del> } <del> <ide> }
Java
bsd-3-clause
83183a8b1dc2d1b20cdcc284f6ad38e29f51f541
0
MobileChromeApps/mobile-chrome-apps,hgl888/mobile-chrome-apps,guozanhua/mobile-chrome-apps,hgl888/mobile-chrome-apps,hgl888/mobile-chrome-apps,guozanhua/mobile-chrome-apps,hgl888/mobile-chrome-apps,MobileChromeApps/mobile-chrome-apps,hgl888/mobile-chrome-apps,wudkj/mobile-chrome-apps,guozanhua/mobile-chrome-apps,chirilo/mobile-chrome-apps,guozanhua/mobile-chrome-apps,wudkj/mobile-chrome-apps,MobileChromeApps/mobile-chrome-apps,xiaoyanit/mobile-chrome-apps,xiaoyanit/mobile-chrome-apps,xiaoyanit/mobile-chrome-apps,chirilo/mobile-chrome-apps,hgl888/mobile-chrome-apps,liqingzhu/mobile-chrome-apps,liqingzhu/mobile-chrome-apps,MobileChromeApps/mobile-chrome-apps,wudkj/mobile-chrome-apps,xiaoyanit/mobile-chrome-apps,chirilo/mobile-chrome-apps,chirilo/mobile-chrome-apps,wudkj/mobile-chrome-apps,hgl888/mobile-chrome-apps,liqingzhu/mobile-chrome-apps,liqingzhu/mobile-chrome-apps
package org.chromium; import java.io.IOException; import java.net.InetSocketAddress; import java.net.SocketException; import java.nio.ByteBuffer; import java.nio.channels.SelectionKey; import java.nio.channels.Selector; import java.nio.channels.SocketChannel; import java.util.Iterator; import java.util.Map; import java.util.concurrent.BlockingQueue; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.LinkedBlockingQueue; import org.apache.cordova.CallbackContext; import org.apache.cordova.CordovaArgs; import org.apache.cordova.CordovaPlugin; import org.apache.cordova.PluginResult; import org.apache.cordova.PluginResult.Status; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; import android.util.Log; public class ChromeSocketsTcp extends CordovaPlugin { private static final String LOG_TAG = "ChromeSocketsTcp"; private Map<Integer, TcpSocket> sockets = new ConcurrentHashMap<Integer, TcpSocket>(); private BlockingQueue<SelectorMessage> selectorMessages = new LinkedBlockingQueue<SelectorMessage>(); private int nextSocket = 1; private CallbackContext recvContext; private Selector selector; private SelectorThread selectorThread; @Override public boolean execute(String action, CordovaArgs args, final CallbackContext callbackContext) throws JSONException { if ("create".equals(action)) { create(args, callbackContext); } else if ("update".equals(action)) { update(args, callbackContext); } else if ("setPaused".equals(action)) { setPaused(args, callbackContext); } else if ("setKeepAlive".equals(action)) { setKeepAlive(args, callbackContext); } else if ("setNoDelay".equals(action)) { setNoDelay(args, callbackContext); } else if ("connect".equals(action)) { connect(args, callbackContext); } else if ("disconnect".equals(action)) { disconnect(args, callbackContext); } else if ("send".equals(action)) { send(args, callbackContext); } else if ("close".equals(action)) { close(args, callbackContext); } else if ("getInfo".equals(action)) { getInfo(args, callbackContext); } else if ("getSockets".equals(action)) { getSockets(args, callbackContext); } else if ("registerReceiveEvents".equals(action)) { registerReceiveEvents(args, callbackContext); } else { return false; } return true; } public void onDestory() { closeAllSockets(); stopSelectorThread(); } public void onReset() { closeAllSockets(); stopSelectorThread(); } public int registerAcceptedSocketChannel(SocketChannel socketChannel) throws IOException, InterruptedException { TcpSocket socket = new TcpSocket(nextSocket++, recvContext, socketChannel); sockets.put(Integer.valueOf(socket.getSocketId()), socket); selectorMessages.put(new SelectorMessage(socket, SelectorMessageType.SO_ACCEPTED, null)); selector.wakeup(); return socket.getSocketId(); } private void create(CordovaArgs args, final CallbackContext callbackContext) throws JSONException { JSONObject properties = args.getJSONObject(0); try { TcpSocket socket = new TcpSocket(nextSocket++, recvContext, properties); sockets.put(Integer.valueOf(socket.getSocketId()), socket); callbackContext.success(socket.getSocketId()); } catch (SocketException e) { } catch (IOException e) { } } private void update(CordovaArgs args, final CallbackContext callbackContext) throws JSONException { int socketId = args.getInt(0); JSONObject properties = args.getJSONObject(1); TcpSocket socket = sockets.get(Integer.valueOf(socketId)); if (socket == null) { Log.e(LOG_TAG, "No socket with socketId " + socketId); return; } try { socket.setProperties(properties); callbackContext.success(); } catch (SocketException e) { } } private void setPaused(CordovaArgs args, final CallbackContext callbackContext) throws JSONException { int socketId = args.getInt(0); boolean paused = args.getBoolean(1); TcpSocket socket = sockets.get(Integer.valueOf(socketId)); if (socket == null) { Log.e(LOG_TAG, "No socket with socketId " + socketId); return; } socket.setPaused(paused); callbackContext.success(); } private void setKeepAlive(CordovaArgs args, final CallbackContext callbackContext) throws JSONException { int socketId = args.getInt(0); boolean enable = args.getBoolean(1); TcpSocket socket = sockets.get(Integer.valueOf(socketId)); if (socket == null) { Log.e(LOG_TAG, "No socket with socketId " + socketId); callbackContext.error(-1000); return; } try { socket.setKeepAlive(enable); callbackContext.success(); } catch (SocketException e) { callbackContext.error(-1000); } } private void setNoDelay(CordovaArgs args, final CallbackContext callbackContext) throws JSONException { int socketId = args.getInt(0); boolean noDelay = args.getBoolean(1); TcpSocket socket = sockets.get(Integer.valueOf(socketId)); if (socket == null) { Log.e(LOG_TAG, "No socket with socketId " + socketId); callbackContext.error(-1000); return; } try { socket.setNoDelay(noDelay); callbackContext.success(); } catch (SocketException e) { callbackContext.error(-1000); } } private void connect(CordovaArgs args, final CallbackContext callbackContext) throws JSONException { int socketId = args.getInt(0); String peerAddress = args.getString(1); int peerPort = args.getInt(2); TcpSocket socket = sockets.get(Integer.valueOf(socketId)); if (socket == null) { Log.e(LOG_TAG, "No socket with socketId " + socketId); callbackContext.error(-1000); return; } try { if (socket.connect(peerAddress, peerPort, callbackContext)) { selectorMessages.put(new SelectorMessage(socket, SelectorMessageType.SO_CONNECTED, null)); } else { selectorMessages.put(new SelectorMessage(socket, SelectorMessageType.SO_CONNECT, null)); } selector.wakeup(); } catch (IOException e) { callbackContext.error(-1000); } catch (InterruptedException e) { } } private void disconnect(CordovaArgs args, final CallbackContext callbackContext) throws JSONException { int socketId = args.getInt(0); TcpSocket socket = sockets.get(Integer.valueOf(socketId)); if (socket == null) { Log.e(LOG_TAG, "No socket with socketId " + socketId); return; } try { selectorMessages.put( new SelectorMessage(socket, SelectorMessageType.SO_DISCONNECTED, callbackContext)); selector.wakeup(); } catch (InterruptedException e) { } } private void send(CordovaArgs args, final CallbackContext callbackContext) throws JSONException { int socketId = args.getInt(0); byte[] data = args.getArrayBuffer(1); TcpSocket socket = sockets.get(Integer.valueOf(socketId)); if (socket == null) { Log.e(LOG_TAG, "No socket with socketId " + socketId); callbackContext.error(-1000); return; } if (!socket.isConnected()) { Log.e(LOG_TAG, "Socket is not connected with host " + socketId); callbackContext.error(-1000); return; } try { int bytesSent = socket.send(data); if (bytesSent > 0) { callbackContext.success(bytesSent); } else { socket.addSendPacket(data, callbackContext); } } catch (IOException e) { callbackContext.error(-1000); } } private void sendCloseMessage(TcpSocket socket, CallbackContext callbackContext) throws InterruptedException { selectorMessages.put( new SelectorMessage(socket, SelectorMessageType.SO_CLOSE, callbackContext)); } private void closeAllSockets() { try { for (TcpSocket socket: sockets.values()) { sendCloseMessage(socket, null); } selector.wakeup(); } catch (InterruptedException e) { } } private void close(CordovaArgs args, final CallbackContext callbackContext) throws JSONException { int socketId = args.getInt(0); TcpSocket socket = sockets.get(Integer.valueOf(socketId)); if (socket == null) { Log.e(LOG_TAG, "No socket with socketId " + socketId); return; } try { sendCloseMessage(socket, callbackContext); selector.wakeup(); } catch (InterruptedException e) { } } private void getInfo(CordovaArgs args, final CallbackContext callbackContext) throws JSONException { int socketId = args.getInt(0); TcpSocket socket = sockets.get(Integer.valueOf(socketId)); if (socket == null) { Log.e(LOG_TAG, "No socket with socketId " + socketId); return; } callbackContext.success(socket.getInfo()); } private void getSockets(CordovaArgs args, final CallbackContext callbackContext) throws JSONException { JSONArray results = new JSONArray(); for (TcpSocket socket: sockets.values()) { results.put(socket.getInfo()); } callbackContext.success(results); } private void registerReceiveEvents(CordovaArgs args, final CallbackContext callbackContext) throws JSONException { recvContext = callbackContext; startSelectorThread(); } private void startSelectorThread() { if (selector != null && selectorThread != null) return; try { selector = Selector.open(); selectorThread = new SelectorThread(selector, selectorMessages, sockets); selectorThread.start(); } catch (IOException e) { selector = null; selectorThread = null; PluginResult err = new PluginResult(Status.ERROR, -1000); err.setKeepCallback(true); recvContext.sendPluginResult(err); } } private void stopSelectorThread() { if (selector == null && selectorThread == null) return; try { selectorMessages.put(new SelectorMessage(null, SelectorMessageType.T_STOP, null)); selector.wakeup(); selectorThread.join(); selector = null; selectorThread = null; } catch (InterruptedException e) { } } private enum SelectorMessageType { SO_CONNECT, SO_CONNECTED, SO_ACCEPTED, SO_DISCONNECTED, SO_CLOSE, T_STOP; } private class SelectorMessage { final TcpSocket socket; final SelectorMessageType type; final CallbackContext callbackContext; SelectorMessage( TcpSocket socket, SelectorMessageType type, CallbackContext callbackContext) { this.socket = socket; this.type = type; this.callbackContext = callbackContext; } } private class SelectorThread extends Thread { private final Selector selector; private BlockingQueue<SelectorMessage> selectorMessages; private Map<Integer, TcpSocket> sockets; private boolean running = true; SelectorThread( Selector selector, BlockingQueue<SelectorMessage> selectorMessages, Map<Integer, TcpSocket> sockets) { this.selector = selector; this.selectorMessages = selectorMessages; this.sockets = sockets; } private void processPendingMessages() { while (selectorMessages.peek() != null) { SelectorMessage msg = null; try { msg = selectorMessages.take(); switch (msg.type) { case SO_CONNECT: msg.socket.register(selector, SelectionKey.OP_CONNECT); break; case SO_CONNECTED: msg.socket.register(selector, SelectionKey.OP_READ); break; case SO_ACCEPTED: msg.socket.register(selector, 0); break; case SO_DISCONNECTED: msg.socket.disconnect(); if (msg.callbackContext != null) msg.callbackContext.success(); break; case SO_CLOSE: msg.socket.disconnect(); sockets.remove(Integer.valueOf(msg.socket.getSocketId())); if (msg.callbackContext != null) msg.callbackContext.success(); break; case T_STOP: running = false; break; } } catch (InterruptedException e) { } catch (IOException e) { if (msg.callbackContext != null) msg.callbackContext.error(-1000); } } } public void run() { Iterator<SelectionKey> it; while (running) { try { selector.select(); } catch (IOException e) { continue; } it = selector.selectedKeys().iterator(); while (it.hasNext()) { SelectionKey key = it.next(); it.remove(); if (!key.isValid()) { continue; } TcpSocket socket = (TcpSocket)key.attachment(); if (key.isReadable()) { try { if (socket.read() < 0) { selectorMessages.put( new SelectorMessage(socket, SelectorMessageType.SO_DISCONNECTED, null)); } } catch (JSONException e) { } catch (InterruptedException e) { } } if (key.isWritable()) { socket.dequeueSend(); } if (key.isConnectable()) { if (socket.finishConnect()) { try { selectorMessages.put( new SelectorMessage(socket, SelectorMessageType.SO_CONNECTED, null)); } catch (InterruptedException e) { } } } } // while next processPendingMessages(); } } } private class TcpSocket { private final int socketId; private final CallbackContext recvContext; private SocketChannel channel; private BlockingQueue<TcpSendPacket> sendPackets = new LinkedBlockingQueue<TcpSendPacket>(); private SelectionKey key; private boolean paused; private boolean persistent; private String name; private int bufferSize; private CallbackContext connectCallback; TcpSocket(int socketId, CallbackContext recvContext, JSONObject properties) throws JSONException, IOException { this.socketId = socketId; this.recvContext = recvContext; channel = SocketChannel.open(); channel.configureBlocking(false); setDefaultProperties(); setProperties(properties); setBufferSize(); } TcpSocket(int socketId, CallbackContext recvContext, SocketChannel acceptedSocket) throws IOException { this.socketId = socketId; this.recvContext = recvContext; channel = acceptedSocket; channel.configureBlocking(false); setDefaultProperties(); setBufferSize(); // accepted socket paused by default paused = true; } void setDefaultProperties() { paused = false; persistent = false; bufferSize = 4096; name = ""; } void addInterestSet(int interestSet) { if (key != null) { key.interestOps(key.interestOps() | interestSet); key.selector().wakeup(); } } void removeInterestSet(int interestSet) { if (key != null) { key.interestOps(key.interestOps() & ~interestSet); key.selector().wakeup(); } } int getSocketId() { return socketId; } boolean isConnected() { return channel.isOpen() && channel.isConnected(); } void register(Selector selector, int interestSets) throws IOException { key = channel.register(selector, interestSets, this); } void setProperties(JSONObject properties) throws JSONException, SocketException { if (!properties.isNull("persistent")) persistent = properties.getBoolean("persistent"); if (!properties.isNull("name")) name = properties.getString("name"); if (!properties.isNull("bufferSize")) { bufferSize = properties.getInt("bufferSize"); setBufferSize(); } } void setBufferSize() throws SocketException { channel.socket().setSendBufferSize(bufferSize); channel.socket().setReceiveBufferSize(bufferSize); } void setPaused(boolean paused) { this.paused = paused; if (paused) { removeInterestSet(SelectionKey.OP_READ); } else { addInterestSet(SelectionKey.OP_READ); } } void setKeepAlive(boolean enable) throws SocketException { channel.socket().setKeepAlive(enable); } void setNoDelay(boolean noDelay) throws SocketException { channel.socket().setTcpNoDelay(noDelay); } boolean connect(String address, int port, CallbackContext connectCallback) throws IOException { this.connectCallback = connectCallback; if (!channel.isOpen()) { channel = SocketChannel.open(); channel.configureBlocking(false); setBufferSize(); } boolean connected = channel.connect(new InetSocketAddress(address, port)); if (connected) { connectCallback.success(); connectCallback = null; } return connected; } boolean finishConnect() { if (channel.isConnectionPending() && connectCallback != null) { try { boolean connected = channel.finishConnect(); if (connected) { connectCallback.success(); connectCallback = null; } return connected; } catch (IOException e) { connectCallback.error(-1000); connectCallback = null; } } return false; } void disconnect() throws IOException { if (key != null && channel.isRegistered()) key.cancel(); channel.close(); } int send(byte[] data) throws IOException { return channel.write(ByteBuffer.wrap(data)); } void addSendPacket(byte[] data, CallbackContext callbackContext) { TcpSendPacket sendPacket = new TcpSendPacket(data, callbackContext); addInterestSet(SelectionKey.OP_WRITE); try { sendPackets.put(sendPacket); } catch (InterruptedException e) { } } void dequeueSend() { if (sendPackets.peek() != null) { TcpSendPacket sendPacket = null; try { sendPacket = sendPackets.take(); int bytesSent = channel.write(sendPacket.data); sendPacket.callbackContext.success(bytesSent); } catch (InterruptedException e) { } catch (IOException e) { sendPacket.callbackContext.error(-1000); } } else { removeInterestSet(SelectionKey.OP_WRITE); } } JSONObject getInfo() throws JSONException { JSONObject info = new JSONObject(); info.put("socketId", socketId); info.put("persistent", persistent); info.put("bufferSize", bufferSize); info.put("connected", channel.isConnected()); info.put("name", name); info.put("paused", paused); if (channel.socket().getLocalAddress() != null) { info.put("localAddress", channel.socket().getLocalAddress().getHostAddress()); info.put("localPort", channel.socket().getLocalPort()); } if (channel.socket().getInetAddress() != null) { info.put("peerAddress", channel.socket().getInetAddress().getHostAddress()); info.put("peerPort", channel.socket().getPort()); } return info; } int read() throws JSONException { int bytesRead = 0; if (paused) return bytesRead; ByteBuffer recvBuffer = ByteBuffer.allocate(bufferSize); recvBuffer.clear(); try { bytesRead = channel.read(recvBuffer); if (bytesRead < 0) { sendReceiveError(); return bytesRead; } recvBuffer.flip(); byte[] recvBytes = new byte[recvBuffer.limit()]; recvBuffer.get(recvBytes); PluginResult dataResult = new PluginResult(Status.OK, recvBytes); dataResult.setKeepCallback(true); recvContext.sendPluginResult(dataResult); JSONObject metadata = new JSONObject(); metadata.put("socketId", socketId); PluginResult metadataResult = new PluginResult(Status.OK, metadata); metadataResult.setKeepCallback(true); recvContext.sendPluginResult(metadataResult); } catch (IOException e) { sendReceiveError(); } return bytesRead; } private void sendReceiveError() throws JSONException { JSONObject info = new JSONObject(); info.put("socketId", socketId); info.put("resultCode", -1000); PluginResult errResult = new PluginResult(Status.ERROR, info); errResult.setKeepCallback(true); recvContext.sendPluginResult(errResult); } private class TcpSendPacket { final ByteBuffer data; final CallbackContext callbackContext; TcpSendPacket(byte[] data, CallbackContext callbackContext) { this.data = ByteBuffer.wrap(data); this.callbackContext = callbackContext; } } } }
chrome-cordova/plugins/chrome.sockets.tcp/src/android/ChromeSocketsTcp.java
package org.chromium; import java.io.IOException; import java.net.InetSocketAddress; import java.net.SocketException; import java.nio.ByteBuffer; import java.nio.channels.SelectionKey; import java.nio.channels.Selector; import java.nio.channels.SocketChannel; import java.util.Iterator; import java.util.Map; import java.util.concurrent.BlockingQueue; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.LinkedBlockingQueue; import org.apache.cordova.CallbackContext; import org.apache.cordova.CordovaArgs; import org.apache.cordova.CordovaPlugin; import org.apache.cordova.PluginResult; import org.apache.cordova.PluginResult.Status; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; import android.util.Log; public class ChromeSocketsTcp extends CordovaPlugin { private static final String LOG_TAG = "ChromeSocketsTcp"; private Map<Integer, TcpSocket> sockets = new ConcurrentHashMap<Integer, TcpSocket>(); private BlockingQueue<SelectorMessage> selectorMessages = new LinkedBlockingQueue<SelectorMessage>(); private int nextSocket = 0; private CallbackContext recvContext; private Selector selector; private SelectorThread selectorThread; @Override public boolean execute(String action, CordovaArgs args, final CallbackContext callbackContext) throws JSONException { if ("create".equals(action)) { create(args, callbackContext); } else if ("update".equals(action)) { update(args, callbackContext); } else if ("setPaused".equals(action)) { setPaused(args, callbackContext); } else if ("setKeepAlive".equals(action)) { setKeepAlive(args, callbackContext); } else if ("setNoDelay".equals(action)) { setNoDelay(args, callbackContext); } else if ("connect".equals(action)) { connect(args, callbackContext); } else if ("disconnect".equals(action)) { disconnect(args, callbackContext); } else if ("send".equals(action)) { send(args, callbackContext); } else if ("close".equals(action)) { close(args, callbackContext); } else if ("getInfo".equals(action)) { getInfo(args, callbackContext); } else if ("getSockets".equals(action)) { getSockets(args, callbackContext); } else if ("registerReceiveEvents".equals(action)) { registerReceiveEvents(args, callbackContext); } else { return false; } return true; } public void onDestory() { closeAllSockets(); stopSelectorThread(); } public void onReset() { closeAllSockets(); stopSelectorThread(); } public int registerAcceptedSocketChannel(SocketChannel socketChannel) throws IOException, InterruptedException { TcpSocket socket = new TcpSocket(nextSocket++, recvContext, socketChannel); sockets.put(Integer.valueOf(socket.getSocketId()), socket); selectorMessages.put(new SelectorMessage(socket, SelectorMessageType.SO_ACCEPTED, null)); selector.wakeup(); return socket.getSocketId(); } private void create(CordovaArgs args, final CallbackContext callbackContext) throws JSONException { JSONObject properties = args.getJSONObject(0); try { TcpSocket socket = new TcpSocket(nextSocket++, recvContext, properties); sockets.put(Integer.valueOf(socket.getSocketId()), socket); callbackContext.success(socket.getSocketId()); } catch (SocketException e) { } catch (IOException e) { } } private void update(CordovaArgs args, final CallbackContext callbackContext) throws JSONException { int socketId = args.getInt(0); JSONObject properties = args.getJSONObject(1); TcpSocket socket = sockets.get(Integer.valueOf(socketId)); if (socket == null) { Log.e(LOG_TAG, "No socket with socketId " + socketId); return; } try { socket.setProperties(properties); callbackContext.success(); } catch (SocketException e) { } } private void setPaused(CordovaArgs args, final CallbackContext callbackContext) throws JSONException { int socketId = args.getInt(0); boolean paused = args.getBoolean(1); TcpSocket socket = sockets.get(Integer.valueOf(socketId)); if (socket == null) { Log.e(LOG_TAG, "No socket with socketId " + socketId); return; } socket.setPaused(paused); callbackContext.success(); } private void setKeepAlive(CordovaArgs args, final CallbackContext callbackContext) throws JSONException { int socketId = args.getInt(0); boolean enable = args.getBoolean(1); TcpSocket socket = sockets.get(Integer.valueOf(socketId)); if (socket == null) { Log.e(LOG_TAG, "No socket with socketId " + socketId); callbackContext.error(-1000); return; } try { socket.setKeepAlive(enable); callbackContext.success(); } catch (SocketException e) { callbackContext.error(-1000); } } private void setNoDelay(CordovaArgs args, final CallbackContext callbackContext) throws JSONException { int socketId = args.getInt(0); boolean noDelay = args.getBoolean(1); TcpSocket socket = sockets.get(Integer.valueOf(socketId)); if (socket == null) { Log.e(LOG_TAG, "No socket with socketId " + socketId); callbackContext.error(-1000); return; } try { socket.setNoDelay(noDelay); callbackContext.success(); } catch (SocketException e) { callbackContext.error(-1000); } } private void connect(CordovaArgs args, final CallbackContext callbackContext) throws JSONException { int socketId = args.getInt(0); String peerAddress = args.getString(1); int peerPort = args.getInt(2); TcpSocket socket = sockets.get(Integer.valueOf(socketId)); if (socket == null) { Log.e(LOG_TAG, "No socket with socketId " + socketId); callbackContext.error(-1000); return; } try { if (socket.connect(peerAddress, peerPort, callbackContext)) { selectorMessages.put(new SelectorMessage(socket, SelectorMessageType.SO_CONNECTED, null)); } else { selectorMessages.put(new SelectorMessage(socket, SelectorMessageType.SO_CONNECT, null)); } selector.wakeup(); } catch (IOException e) { callbackContext.error(-1000); } catch (InterruptedException e) { } } private void disconnect(CordovaArgs args, final CallbackContext callbackContext) throws JSONException { int socketId = args.getInt(0); TcpSocket socket = sockets.get(Integer.valueOf(socketId)); if (socket == null) { Log.e(LOG_TAG, "No socket with socketId " + socketId); return; } try { selectorMessages.put( new SelectorMessage(socket, SelectorMessageType.SO_DISCONNECTED, callbackContext)); selector.wakeup(); } catch (InterruptedException e) { } } private void send(CordovaArgs args, final CallbackContext callbackContext) throws JSONException { int socketId = args.getInt(0); byte[] data = args.getArrayBuffer(1); TcpSocket socket = sockets.get(Integer.valueOf(socketId)); if (socket == null) { Log.e(LOG_TAG, "No socket with socketId " + socketId); callbackContext.error(-1000); return; } if (!socket.isConnected()) { Log.e(LOG_TAG, "Socket is not connected with host " + socketId); callbackContext.error(-1000); return; } try { int bytesSent = socket.send(data); if (bytesSent > 0) { callbackContext.success(bytesSent); } else { socket.addSendPacket(data, callbackContext); } } catch (IOException e) { callbackContext.error(-1000); } } private void sendCloseMessage(TcpSocket socket, CallbackContext callbackContext) throws InterruptedException { selectorMessages.put( new SelectorMessage(socket, SelectorMessageType.SO_CLOSE, callbackContext)); } private void closeAllSockets() { try { for (TcpSocket socket: sockets.values()) { sendCloseMessage(socket, null); } selector.wakeup(); } catch (InterruptedException e) { } } private void close(CordovaArgs args, final CallbackContext callbackContext) throws JSONException { int socketId = args.getInt(0); TcpSocket socket = sockets.get(Integer.valueOf(socketId)); if (socket == null) { Log.e(LOG_TAG, "No socket with socketId " + socketId); return; } try { sendCloseMessage(socket, callbackContext); selector.wakeup(); } catch (InterruptedException e) { } } private void getInfo(CordovaArgs args, final CallbackContext callbackContext) throws JSONException { int socketId = args.getInt(0); TcpSocket socket = sockets.get(Integer.valueOf(socketId)); if (socket == null) { Log.e(LOG_TAG, "No socket with socketId " + socketId); return; } callbackContext.success(socket.getInfo()); } private void getSockets(CordovaArgs args, final CallbackContext callbackContext) throws JSONException { JSONArray results = new JSONArray(); for (TcpSocket socket: sockets.values()) { results.put(socket.getInfo()); } callbackContext.success(results); } private void registerReceiveEvents(CordovaArgs args, final CallbackContext callbackContext) throws JSONException { recvContext = callbackContext; startSelectorThread(); } private void startSelectorThread() { if (selector != null && selectorThread != null) return; try { selector = Selector.open(); selectorThread = new SelectorThread(selector, selectorMessages, sockets); selectorThread.start(); } catch (IOException e) { selector = null; selectorThread = null; PluginResult err = new PluginResult(Status.ERROR, -1000); err.setKeepCallback(true); recvContext.sendPluginResult(err); } } private void stopSelectorThread() { if (selector == null && selectorThread == null) return; try { selectorMessages.put(new SelectorMessage(null, SelectorMessageType.T_STOP, null)); selector.wakeup(); selectorThread.join(); selector = null; selectorThread = null; } catch (InterruptedException e) { } } private enum SelectorMessageType { SO_CONNECT, SO_CONNECTED, SO_ACCEPTED, SO_DISCONNECTED, SO_CLOSE, T_STOP; } private class SelectorMessage { final TcpSocket socket; final SelectorMessageType type; final CallbackContext callbackContext; SelectorMessage( TcpSocket socket, SelectorMessageType type, CallbackContext callbackContext) { this.socket = socket; this.type = type; this.callbackContext = callbackContext; } } private class SelectorThread extends Thread { private final Selector selector; private BlockingQueue<SelectorMessage> selectorMessages; private Map<Integer, TcpSocket> sockets; private boolean running = true; SelectorThread( Selector selector, BlockingQueue<SelectorMessage> selectorMessages, Map<Integer, TcpSocket> sockets) { this.selector = selector; this.selectorMessages = selectorMessages; this.sockets = sockets; } private void processPendingMessages() { while (selectorMessages.peek() != null) { SelectorMessage msg = null; try { msg = selectorMessages.take(); switch (msg.type) { case SO_CONNECT: msg.socket.register(selector, SelectionKey.OP_CONNECT); break; case SO_CONNECTED: msg.socket.register(selector, SelectionKey.OP_READ); break; case SO_ACCEPTED: msg.socket.register(selector, 0); break; case SO_DISCONNECTED: msg.socket.disconnect(); if (msg.callbackContext != null) msg.callbackContext.success(); break; case SO_CLOSE: msg.socket.disconnect(); sockets.remove(Integer.valueOf(msg.socket.getSocketId())); if (msg.callbackContext != null) msg.callbackContext.success(); break; case T_STOP: running = false; break; } } catch (InterruptedException e) { } catch (IOException e) { if (msg.callbackContext != null) msg.callbackContext.error(-1000); } } } public void run() { Iterator<SelectionKey> it; while (running) { try { selector.select(); } catch (IOException e) { continue; } it = selector.selectedKeys().iterator(); while (it.hasNext()) { SelectionKey key = it.next(); it.remove(); if (!key.isValid()) { continue; } TcpSocket socket = (TcpSocket)key.attachment(); if (key.isReadable()) { try { if (socket.read() < 0) { selectorMessages.put( new SelectorMessage(socket, SelectorMessageType.SO_DISCONNECTED, null)); } } catch (JSONException e) { } catch (InterruptedException e) { } } if (key.isWritable()) { socket.dequeueSend(); } if (key.isConnectable()) { if (socket.finishConnect()) { try { selectorMessages.put( new SelectorMessage(socket, SelectorMessageType.SO_CONNECTED, null)); } catch (InterruptedException e) { } } } } // while next processPendingMessages(); } } } private class TcpSocket { private final int socketId; private final CallbackContext recvContext; private SocketChannel channel; private BlockingQueue<TcpSendPacket> sendPackets = new LinkedBlockingQueue<TcpSendPacket>(); private SelectionKey key; private boolean paused; private boolean persistent; private String name; private int bufferSize; private CallbackContext connectCallback; TcpSocket(int socketId, CallbackContext recvContext, JSONObject properties) throws JSONException, IOException { this.socketId = socketId; this.recvContext = recvContext; channel = SocketChannel.open(); channel.configureBlocking(false); setDefaultProperties(); setProperties(properties); setBufferSize(); } TcpSocket(int socketId, CallbackContext recvContext, SocketChannel acceptedSocket) throws IOException { this.socketId = socketId; this.recvContext = recvContext; channel = acceptedSocket; channel.configureBlocking(false); setDefaultProperties(); setBufferSize(); // accepted socket paused by default paused = true; } void setDefaultProperties() { paused = false; persistent = false; bufferSize = 4096; name = ""; } void addInterestSet(int interestSet) { if (key != null) { key.interestOps(key.interestOps() | interestSet); key.selector().wakeup(); } } void removeInterestSet(int interestSet) { if (key != null) { key.interestOps(key.interestOps() & ~interestSet); key.selector().wakeup(); } } int getSocketId() { return socketId; } boolean isConnected() { return channel.isOpen() && channel.isConnected(); } void register(Selector selector, int interestSets) throws IOException { key = channel.register(selector, interestSets, this); } void setProperties(JSONObject properties) throws JSONException, SocketException { if (!properties.isNull("persistent")) persistent = properties.getBoolean("persistent"); if (!properties.isNull("name")) name = properties.getString("name"); if (!properties.isNull("bufferSize")) { bufferSize = properties.getInt("bufferSize"); setBufferSize(); } } void setBufferSize() throws SocketException { channel.socket().setSendBufferSize(bufferSize); channel.socket().setReceiveBufferSize(bufferSize); } void setPaused(boolean paused) { this.paused = paused; if (paused) { removeInterestSet(SelectionKey.OP_READ); } else { addInterestSet(SelectionKey.OP_READ); } } void setKeepAlive(boolean enable) throws SocketException { channel.socket().setKeepAlive(enable); } void setNoDelay(boolean noDelay) throws SocketException { channel.socket().setTcpNoDelay(noDelay); } boolean connect(String address, int port, CallbackContext connectCallback) throws IOException { this.connectCallback = connectCallback; if (!channel.isOpen()) { channel = SocketChannel.open(); channel.configureBlocking(false); setBufferSize(); } boolean connected = channel.connect(new InetSocketAddress(address, port)); if (connected) { connectCallback.success(); connectCallback = null; } return connected; } boolean finishConnect() { if (channel.isConnectionPending() && connectCallback != null) { try { boolean connected = channel.finishConnect(); if (connected) { connectCallback.success(); connectCallback = null; } return connected; } catch (IOException e) { connectCallback.error(-1000); connectCallback = null; } } return false; } void disconnect() throws IOException { if (key != null && channel.isRegistered()) key.cancel(); channel.close(); } int send(byte[] data) throws IOException { return channel.write(ByteBuffer.wrap(data)); } void addSendPacket(byte[] data, CallbackContext callbackContext) { TcpSendPacket sendPacket = new TcpSendPacket(data, callbackContext); addInterestSet(SelectionKey.OP_WRITE); try { sendPackets.put(sendPacket); } catch (InterruptedException e) { } } void dequeueSend() { if (sendPackets.peek() != null) { TcpSendPacket sendPacket = null; try { sendPacket = sendPackets.take(); int bytesSent = channel.write(sendPacket.data); sendPacket.callbackContext.success(bytesSent); } catch (InterruptedException e) { } catch (IOException e) { sendPacket.callbackContext.error(-1000); } } else { removeInterestSet(SelectionKey.OP_WRITE); } } JSONObject getInfo() throws JSONException { JSONObject info = new JSONObject(); info.put("socketId", socketId); info.put("persistent", persistent); info.put("bufferSize", bufferSize); info.put("connected", channel.isConnected()); info.put("name", name); info.put("paused", paused); if (channel.socket().getLocalAddress() != null) { info.put("localAddress", channel.socket().getLocalAddress().getHostAddress()); info.put("localPort", channel.socket().getLocalPort()); } if (channel.socket().getInetAddress() != null) { info.put("peerAddress", channel.socket().getInetAddress().getHostAddress()); info.put("peerPort", channel.socket().getPort()); } return info; } int read() throws JSONException { int bytesRead = 0; if (paused) return bytesRead; ByteBuffer recvBuffer = ByteBuffer.allocate(bufferSize); recvBuffer.clear(); try { bytesRead = channel.read(recvBuffer); if (bytesRead < 0) { sendReceiveError(); return bytesRead; } recvBuffer.flip(); byte[] recvBytes = new byte[recvBuffer.limit()]; recvBuffer.get(recvBytes); PluginResult dataResult = new PluginResult(Status.OK, recvBytes); dataResult.setKeepCallback(true); recvContext.sendPluginResult(dataResult); JSONObject metadata = new JSONObject(); metadata.put("socketId", socketId); PluginResult metadataResult = new PluginResult(Status.OK, metadata); metadataResult.setKeepCallback(true); recvContext.sendPluginResult(metadataResult); } catch (IOException e) { sendReceiveError(); } return bytesRead; } private void sendReceiveError() throws JSONException { JSONObject info = new JSONObject(); info.put("socketId", socketId); info.put("resultCode", -1000); PluginResult errResult = new PluginResult(Status.ERROR, info); errResult.setKeepCallback(true); recvContext.sendPluginResult(errResult); } private class TcpSendPacket { final ByteBuffer data; final CallbackContext callbackContext; TcpSendPacket(byte[] data, CallbackContext callbackContext) { this.data = ByteBuffer.wrap(data); this.callbackContext = callbackContext; } } } }
Changed initial socketId to 1.
chrome-cordova/plugins/chrome.sockets.tcp/src/android/ChromeSocketsTcp.java
Changed initial socketId to 1.
<ide><path>hrome-cordova/plugins/chrome.sockets.tcp/src/android/ChromeSocketsTcp.java <ide> private Map<Integer, TcpSocket> sockets = new ConcurrentHashMap<Integer, TcpSocket>(); <ide> private BlockingQueue<SelectorMessage> selectorMessages = <ide> new LinkedBlockingQueue<SelectorMessage>(); <del> private int nextSocket = 0; <add> private int nextSocket = 1; <ide> private CallbackContext recvContext; <ide> private Selector selector; <ide> private SelectorThread selectorThread;
Java
apache-2.0
fd56d326028f81c2150b7859003a19643f51de3a
0
mdogan/hazelcast,emre-aydin/hazelcast,emre-aydin/hazelcast,mdogan/hazelcast,mdogan/hazelcast,emre-aydin/hazelcast,mesutcelik/hazelcast,mesutcelik/hazelcast,mesutcelik/hazelcast
/* * Copyright (c) 2008-2018, 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.config; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import static java.util.Arrays.asList; /** * Utility class for Aliased Discovery Configs. */ public final class AliasedDiscoveryConfigUtils { private static final Map<String, String> ALIAS_MAPPINGS = new HashMap<String, String>(); private AliasedDiscoveryConfigUtils() { } static { ALIAS_MAPPINGS.put("aws", "com.hazelcast.aws.AwsDiscoveryStrategy"); ALIAS_MAPPINGS.put("gcp", "com.hazelcast.gcp.GcpDiscoveryStrategy"); ALIAS_MAPPINGS.put("azure", "com.hazelcast.azure.AzureDiscoveryStrategy"); ALIAS_MAPPINGS.put("kubernetes", "com.hazelcast.kubernetes.HazelcastKubernetesDiscoveryStrategy"); ALIAS_MAPPINGS.put("eureka", "com.hazelcast.eureka.one.HazelcastKubernetesDiscoveryStrategy"); } /** * Checks whether the given XML {@code tag} is supported. */ public static boolean supports(String tag) { return ALIAS_MAPPINGS.containsKey(tag); } /** * Returns an XML tag (e.g. {@literal <gcp>}) for the given config. */ public static String tagFor(AliasedDiscoveryConfig config) { return config.getTag(); } /** * Extracts aliased discovery configs from {@code config} and creates a list of {@link DiscoveryStrategyConfig} out of them. */ public static List<DiscoveryStrategyConfig> createDiscoveryStrategyConfigs(JoinConfig config) { return map(aliasedDiscoveryConfigsFrom(config)); } /** * Extracts aliased discovery configs from {@code config} and creates a list of {@link DiscoveryStrategyConfig} out of them. */ public static List<DiscoveryStrategyConfig> createDiscoveryStrategyConfigs(WanPublisherConfig config) { return map(aliasedDiscoveryConfigsFrom(config)); } /** * Maps aliased discovery strategy configs into discovery strategy configs. */ public static List<DiscoveryStrategyConfig> map(List<AliasedDiscoveryConfig<?>> aliasedDiscoveryConfigs) { List<DiscoveryStrategyConfig> result = new ArrayList<DiscoveryStrategyConfig>(); for (AliasedDiscoveryConfig config : aliasedDiscoveryConfigs) { if (config.isEnabled()) { result.add(createDiscoveryStrategyConfig(config)); } } return result; } private static DiscoveryStrategyConfig createDiscoveryStrategyConfig(AliasedDiscoveryConfig<?> config) { validateConfig(config); String className = discoveryStrategyFrom(config); Map<String, Comparable> properties = new HashMap<String, Comparable>(); for (String key : config.getProperties().keySet()) { putIfKeyNotNull(properties, key, config.getProperties().get(key)); } return new DiscoveryStrategyConfig(className, properties); } private static void validateConfig(AliasedDiscoveryConfig config) { if (!ALIAS_MAPPINGS.containsKey(config.getTag())) { throw new InvalidConfigurationException( String.format("Invalid configuration class: '%s'", config.getClass().getName())); } } private static String discoveryStrategyFrom(AliasedDiscoveryConfig config) { return ALIAS_MAPPINGS.get(config.getTag()); } private static void putIfKeyNotNull(Map<String, Comparable> properties, String key, String value) { if (key != null) { properties.put(key, value); } } /** * Gets the {@link AliasedDiscoveryConfig} from {@code config} by {@code tag}. */ public static AliasedDiscoveryConfig getConfigByTag(JoinConfig config, String tag) { if ("aws".equals(tag)) { return config.getAwsConfig(); } else if ("gcp".equals(tag)) { return config.getGcpConfig(); } else if ("azure".equals(tag)) { return config.getAzureConfig(); } else if ("kubernetes".equals(tag)) { return config.getKubernetesConfig(); } else if ("eureka".equals(tag)) { return config.getEurekaConfig(); } else { throw new IllegalArgumentException(String.format("Invalid tag: '%s'", tag)); } } /** * Gets the {@link AliasedDiscoveryConfig} from {@code config} by {@code tag}. */ public static AliasedDiscoveryConfig getConfigByTag(WanPublisherConfig config, String tag) { if ("aws".equals(tag)) { return config.getAwsConfig(); } else if ("gcp".equals(tag)) { return config.getGcpConfig(); } else if ("azure".equals(tag)) { return config.getAzureConfig(); } else if ("kubernetes".equals(tag)) { return config.getKubernetesConfig(); } else if ("eureka".equals(tag)) { return config.getEurekaConfig(); } else { throw new IllegalArgumentException(String.format("Invalid tag: '%s'", tag)); } } /** * Gets a list of all aliased discovery configs from {@code config}. */ public static List<AliasedDiscoveryConfig<?>> aliasedDiscoveryConfigsFrom(JoinConfig config) { return asList(config.getAwsConfig(), config.getGcpConfig(), config.getAzureConfig(), config.getKubernetesConfig(), config.getEurekaConfig()); } /** * Gets a list of all aliased discovery configs from {@code config}. */ public static List<AliasedDiscoveryConfig<?>> aliasedDiscoveryConfigsFrom(WanPublisherConfig config) { return asList(config.getAwsConfig(), config.getGcpConfig(), config.getAzureConfig(), config.getKubernetesConfig(), config.getEurekaConfig()); } /** * Checks whether all aliased discovery configs have the tag {@literal <use-public-ip>true</use-public-ip}. * <p> * Note that if no config is enabled, then the method returns {@literal false}. */ public static boolean allUsePublicAddress(List<AliasedDiscoveryConfig<?>> configs) { boolean atLeastOneEnabled = false; for (AliasedDiscoveryConfig config : configs) { if (config.isEnabled()) { atLeastOneEnabled = true; if (!config.isUsePublicIp()) { return false; } } } return atLeastOneEnabled; } /** * Creates new {@link AliasedDiscoveryConfig} by the given {@code tag}. */ @SuppressWarnings("unchecked") public static AliasedDiscoveryConfig newConfigFor(String tag) { if ("aws".equals(tag)) { return new AwsConfig(); } else if ("gcp".equals(tag)) { return new GcpConfig(); } else if ("azure".equals(tag)) { return new AzureConfig(); } else if ("kubernetes".equals(tag)) { return new KubernetesConfig(); } else if ("eureka".equals(tag)) { return new EurekaConfig(); } else { throw new IllegalArgumentException(String.format("Invalid tag: '%s'", tag)); } } }
hazelcast/src/main/java/com/hazelcast/config/AliasedDiscoveryConfigUtils.java
/* * Copyright (c) 2008-2018, 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.config; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import static java.util.Arrays.asList; /** * Utility class for Aliased Discovery Configs. */ public final class AliasedDiscoveryConfigUtils { private static final Map<String, String> ALIAS_MAPPINGS = new HashMap<String, String>(); private AliasedDiscoveryConfigUtils() { } static { ALIAS_MAPPINGS.put("aws", "com.hazelcast.aws.AwsDiscoveryStrategy"); ALIAS_MAPPINGS.put("gcp", "com.hazelcast.gcp.GcpDiscoveryStrategy"); ALIAS_MAPPINGS.put("azure", "com.hazelcast.azure.AzureDiscoveryStrategy"); ALIAS_MAPPINGS.put("kubernetes", "com.hazelcast.kubernetes.HazelcastKubernetesDiscoveryStrategy"); ALIAS_MAPPINGS.put("eureka", "com.hazelcast.eureka.one.HazelcastKubernetesDiscoveryStrategy"); } /** * Checks whether the given XML {@code tag} is supported. */ public static boolean supports(String tag) { return ALIAS_MAPPINGS.containsKey(tag); } /** * Returns an XML tag (e.g. {@literal <gcp>}) for the given config. */ public static String tagFor(AliasedDiscoveryConfig config) { return config.getTag(); } /** * Extracts aliased discovery configs from {@code config} and creates a list of {@link DiscoveryStrategyConfig} out of them. */ public static List<DiscoveryStrategyConfig> createDiscoveryStrategyConfigs(JoinConfig config) { return map(aliasedDiscoveryConfigsFrom(config)); } /** * Extracts aliased discovery configs from {@code config} and creates a list of {@link DiscoveryStrategyConfig} out of them. */ public static List<DiscoveryStrategyConfig> createDiscoveryStrategyConfigs(WanPublisherConfig config) { return map(aliasedDiscoveryConfigsFrom(config)); } /** * Maps aliased discovery strategy configs into discovery strategy configs. */ public static List<DiscoveryStrategyConfig> map(List<AliasedDiscoveryConfig<?>> aliasedDiscoveryConfigs) { List<DiscoveryStrategyConfig> result = new ArrayList<DiscoveryStrategyConfig>(); for (AliasedDiscoveryConfig config : aliasedDiscoveryConfigs) { if (config.isEnabled()) { result.add(createDiscoveryStrategyConfig(config)); } } return result; } private static DiscoveryStrategyConfig createDiscoveryStrategyConfig(AliasedDiscoveryConfig<?> config) { validateConfig(config); String className = discoveryStrategyFrom(config); Map<String, Comparable> properties = new HashMap<String, Comparable>(); for (String key : config.getProperties().keySet()) { putIfKeyNotNull(properties, key, config.getProperties().get(key)); } return new DiscoveryStrategyConfig(className, properties); } private static void validateConfig(AliasedDiscoveryConfig config) { if (!ALIAS_MAPPINGS.containsKey(config.getTag())) { throw new InvalidConfigurationException( String.format("Invalid configuration class: '%s'", config.getClass().getName())); } } private static String discoveryStrategyFrom(AliasedDiscoveryConfig config) { return ALIAS_MAPPINGS.get(config.getTag()); } private static void putIfKeyNotNull(Map<String, Comparable> properties, String key, String value) { if (key != null) { properties.put(key, value); } } /** * Gets the {@link AliasedDiscoveryConfig} from {@code config} by {@code tag}. */ public static AliasedDiscoveryConfig getConfigByTag(JoinConfig config, String tag) { if ("aws".equals(tag)) { return config.getAwsConfig(); } else if ("gcp".equals(tag)) { return config.getGcpConfig(); } else if ("azure".equals(tag)) { return config.getAzureConfig(); } else if ("kubernetes".equals(tag)) { return config.getKubernetesConfig(); } else if ("eureka".equals(tag)) { return config.getEurekaConfig(); } else { throw new IllegalArgumentException(String.format("Invalid tag: '%s'", tag)); } } /** * Gets the {@link AliasedDiscoveryConfig} from {@code config} by {@code tag}. */ public static AliasedDiscoveryConfig getConfigByTag(WanPublisherConfig config, String tag) { if ("aws".equals(tag)) { return config.getAwsConfig(); } else if ("gcp".equals(tag)) { return config.getGcpConfig(); } else if ("azure".equals(tag)) { return config.getAzureConfig(); } else if ("kubernetes".equals(tag)) { return config.getKubernetesConfig(); } else if ("eureka".equals(tag)) { return config.getEurekaConfig(); } else { throw new IllegalArgumentException(String.format("Invalid tag: '%s'", tag)); } } /** * Gets a list of all aliased discovery configs from {@code config}. */ public static List<AliasedDiscoveryConfig<?>> aliasedDiscoveryConfigsFrom(JoinConfig config) { return asList(config.getAwsConfig(), config.getGcpConfig(), config.getAzureConfig(), config.getKubernetesConfig(), config.getEurekaConfig()); } /** * Gets a list of all aliased discovery configs from {@code config}. */ public static List<AliasedDiscoveryConfig<?>> aliasedDiscoveryConfigsFrom(WanPublisherConfig config) { return asList(config.getAwsConfig(), config.getGcpConfig(), config.getAzureConfig(), config.getKubernetesConfig(), config.getEurekaConfig()); } /** * Checks whether all aliased discovery configs have the tag {@literal <use-public-ip>trye</use-public-ip}. * <p> * Note that if no config is enabled, then the method returns {@literal false}. */ public static boolean allUsePublicAddress(List<AliasedDiscoveryConfig<?>> configs) { boolean atLeastOneEnabled = false; for (AliasedDiscoveryConfig config : configs) { if (config.isEnabled()) { atLeastOneEnabled = true; if (!config.isUsePublicIp()) { return false; } } } return atLeastOneEnabled; } /** * Creates new {@link AliasedDiscoveryConfig} by the given {@code tag}. */ @SuppressWarnings("unchecked") public static AliasedDiscoveryConfig newConfigFor(String tag) { if ("aws".equals(tag)) { return new AwsConfig(); } else if ("gcp".equals(tag)) { return new GcpConfig(); } else if ("azure".equals(tag)) { return new AzureConfig(); } else if ("kubernetes".equals(tag)) { return new KubernetesConfig(); } else if ("eureka".equals(tag)) { return new EurekaConfig(); } else { throw new IllegalArgumentException(String.format("Invalid tag: '%s'", tag)); } } }
Fix typo
hazelcast/src/main/java/com/hazelcast/config/AliasedDiscoveryConfigUtils.java
Fix typo
<ide><path>azelcast/src/main/java/com/hazelcast/config/AliasedDiscoveryConfigUtils.java <ide> } <ide> <ide> /** <del> * Checks whether all aliased discovery configs have the tag {@literal <use-public-ip>trye</use-public-ip}. <add> * Checks whether all aliased discovery configs have the tag {@literal <use-public-ip>true</use-public-ip}. <ide> * <p> <ide> * Note that if no config is enabled, then the method returns {@literal false}. <ide> */
JavaScript
agpl-3.0
70ae901fa6f67b54b22165f53a86f2dc86ef4d6b
0
ONLYOFFICE/sdkjs,ONLYOFFICE/sdkjs,ONLYOFFICE/sdkjs,ONLYOFFICE/sdkjs,ONLYOFFICE/sdkjs
/* * (c) Copyright Ascensio System SIA 2010-2018 * * This program is a free software product. You can redistribute it and/or * modify it under the terms of the GNU Affero General Public License (AGPL) * version 3 as published by the Free Software Foundation. In accordance with * Section 7(a) of the GNU AGPL its Section 15 shall be amended to the effect * that Ascensio System SIA expressly excludes the warranty of non-infringement * of any third-party rights. * * This program is distributed WITHOUT ANY WARRANTY; without even the implied * warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. For * details, see the GNU AGPL at: http://www.gnu.org/licenses/agpl-3.0.html * * You can contact Ascensio System SIA at Lubanas st. 125a-25, Riga, Latvia, * EU, LV-1021. * * The interactive user interfaces in modified source and object code versions * of the Program must display Appropriate Legal Notices, as required under * Section 5 of the GNU AGPL version 3. * * Pursuant to Section 7(b) of the License you must retain the original Product * logo when distributing the program. Pursuant to Section 7(e) we decline to * grant you any rights under trademark law for use of our trademarks. * * All the Product's GUI elements, including illustrations and icon sets, as * well as technical writing content are licensed under the terms of the * Creative Commons Attribution-ShareAlike 4.0 International. See the License * terms at http://creativecommons.org/licenses/by-sa/4.0/legalcode * */ "use strict"; var GLOBAL_PATH_COUNT = 0; ( /** * @param {Window} window * @param {undefined} undefined */ function (window, undefined) { var MAX_LABELS_COUNT = 300; // Import var oNonSpaceRegExp = new RegExp('' + String.fromCharCode(0x00A0),'g'); var c_oAscChartType = AscCommon.c_oAscChartType; var c_oAscChartSubType = AscCommon.c_oAscChartSubType; var parserHelp = AscCommon.parserHelp; var g_oIdCounter = AscCommon.g_oIdCounter; var g_oTableId = AscCommon.g_oTableId; var oNumFormatCache = AscCommon.oNumFormatCache; var CellAddress = AscCommon.CellAddress; var isRealObject = AscCommon.isRealObject; var History = AscCommon.History; var global_MatrixTransformer = AscCommon.global_MatrixTransformer; var CShape = AscFormat.CShape; var Ax_Counter = AscFormat.Ax_Counter; var checkTxBodyDefFonts = AscFormat.checkTxBodyDefFonts; var c_oAscNumFormatType = Asc.c_oAscNumFormatType; var c_oAscTickLabelsPos = Asc.c_oAscTickLabelsPos; var c_oAscChartLegendShowSettings = Asc.c_oAscChartLegendShowSettings; var c_oAscTickMark = Asc.c_oAscTickMark; var EFFECT_NONE = 0; var EFFECT_SUBTLE = 1; var EFFECT_MODERATE = 2; var EFFECT_INTENSE = 3; var CHART_STYLE_MANAGER = null; var SKIP_LBL_LIMIT = 100; var BAR_SHAPE_CONE = 0; var BAR_SHAPE_CONETOMAX = 1; var BAR_SHAPE_BOX = 2; var BAR_SHAPE_CYLINDER = 3; var BAR_SHAPE_PYRAMID = 4; var BAR_SHAPE_PYRAMIDTOMAX = 5; var DISP_BLANKS_AS_GAP = 0; var DISP_BLANKS_AS_SPAN = 1; var DISP_BLANKS_AS_ZERO = 2; function removePtsFromLit(lit) { var i; var start_idx = Array.isArray(lit.pts) ? lit.pts.length - 1 : -1; for(i = start_idx; i > -1; --i) { lit.removeDPt(i); } } function removeAllSeriesFromChart(chart) { for(var i = chart.series.length-1; i > -1; --i) chart.removeSeries(i); } function checkVerticalTitle(title) { return false; } function GetTextPrFormArrObjects(aObjects, bFirstBreak, bLbl) { var oResultTextPr; for(var i = 0; i < aObjects.length; ++i) { var oContent = aObjects[i]; oContent = bLbl ? oContent.compiledDlb && oContent.compiledDlb.txBody && oContent.compiledDlb.txBody.content : oContent.txBody && oContent.txBody.content; if(!oContent) continue; oContent.Set_ApplyToAll(true); var oTextPr = oContent.GetCalculatedTextPr(); oContent.Set_ApplyToAll(false); if(!oResultTextPr) { oResultTextPr = oTextPr; if(bFirstBreak) { return oResultTextPr; } } else { oResultTextPr.Compare(oTextPr); } } return oResultTextPr; } function checkBlackUnifill(unifill, bLines) { if(unifill && unifill.fill && unifill.fill.color) { var RGBA = unifill.fill.color.RGBA; if(RGBA.R === 0 && RGBA.G === 0 && RGBA.B === 0) { if(bLines) { RGBA.R = 134; RGBA.G = 134; RGBA.B = 134; } else { RGBA.R = 255; RGBA.G = 255; RGBA.B = 255; } } } } function CRect(x, y, w, h){ this.x = x; this.y = y; this.w = w; this.h = h; this.fHorPadding = 0.0; this.fVertPadding = 0.0; } CRect.prototype.copy = function(){ var ret = new CRect(this.x, this.y, this.w, this.h); ret.fHorPadding = this.fHorPadding; ret.fVertPadding = this.fVertPadding; return ret; }; CRect.prototype.intersection = function(oRect){ if(this.x + this.w < oRect.x || oRect.x + oRect.w < this.x || this.y + this.h < oRect.y || oRect.y + oRect.h < this.y){ return false; } var x0, y0, x1, y1; var bResetHorPadding = true, bResetVertPadding = true; if(this.fHorPadding > 0.0 && oRect.fHorPadding > 0.0){ x0 = this.x + oRect.fHorPadding; bResetHorPadding = false; } else{ x0 = Math.max(this.x, oRect.x); } if(this.fVertPadding > 0.0 && oRect.fVertPadding > 0.0){ y0 = this.y + oRect.fVertPadding; bResetVertPadding = false; } else{ y0 = Math.max(this.y, oRect.y); } if(this.fHorPadding < 0.0 && oRect.fHorPadding < 0.0){ x1 = this.x + this.w + oRect.fHorPadding; bResetHorPadding = false; } else{ x1 = Math.min(this.x + this.w, oRect.x + oRect.w); } if(this.fVertPadding < 0.0 && this.fVertPadding < 0.0){ y1 = this.y + this.h + oRect.fVertPadding; bResetVertPadding = false; } else{ y1 = Math.min(this.y + this.h, oRect.y + oRect.h); } if(bResetHorPadding){ this.fHorPadding = 0.0; } if(bResetVertPadding){ this.fVertPadding = 0.0; } this.x = x0; this.y = y0; this.w = x1 - x0; this.h = y1 - y0; return true; }; function BBoxInfo(worksheet, bbox) { this.worksheet = worksheet; if(window["Asc"] && typeof window["Asc"].Range === "function") { this.bbox = window["Asc"].Range(bbox.c1, bbox.r1, bbox.c2, bbox.r2, false); } else { this.bbox = bbox; } } BBoxInfo.prototype = { checkIntersection: function(bboxInfo) { if(this.worksheet !== bboxInfo.worksheet) { return false; } return this.bbox.isIntersect(bboxInfo.bbox); } }; function CreateUnifillSolidFillSchemeColorByIndex(index) { var ret = new AscFormat.CUniFill(); ret.setFill(new AscFormat.CSolidFill()); ret.fill.setColor(new AscFormat.CUniColor()); ret.fill.color.setColor(new AscFormat.CSchemeColor()); ret.fill.color.color.setId(index); return ret; } function CChartStyleManager() { this.styles = []; } CChartStyleManager.prototype = { init: function() { AscFormat.ExecuteNoHistory( function() { var DefaultDataPointPerDataPoint = [ [ CreateUniFillSchemeColorWidthTint(8, 0.885), CreateUniFillSchemeColorWidthTint(8, 0.55), CreateUniFillSchemeColorWidthTint(8, 0.78), CreateUniFillSchemeColorWidthTint(8, 0.925), CreateUniFillSchemeColorWidthTint(8, 0.7), CreateUniFillSchemeColorWidthTint(8, 0.3) ], [ CreateUniFillSchemeColorWidthTint(0, 0), CreateUniFillSchemeColorWidthTint(1, 0), CreateUniFillSchemeColorWidthTint(2, 0), CreateUniFillSchemeColorWidthTint(3, 0), CreateUniFillSchemeColorWidthTint(4, 0), CreateUniFillSchemeColorWidthTint(5, 0) ], [ CreateUniFillSchemeColorWidthTint(0, -0.5), CreateUniFillSchemeColorWidthTint(1, -0.5), CreateUniFillSchemeColorWidthTint(2, -0.5), CreateUniFillSchemeColorWidthTint(3, -0.5), CreateUniFillSchemeColorWidthTint(4, -0.5), CreateUniFillSchemeColorWidthTint(5, -0.5) ], [ CreateUniFillSchemeColorWidthTint(8, 0.05), CreateUniFillSchemeColorWidthTint(8, 0.55), CreateUniFillSchemeColorWidthTint(8, 0.78), CreateUniFillSchemeColorWidthTint(8, 0.15), CreateUniFillSchemeColorWidthTint(8, 0.7), CreateUniFillSchemeColorWidthTint(8, 0.3) ] ]; var s = DefaultDataPointPerDataPoint; var f = CreateUniFillSchemeColorWidthTint; this.styles[0] = new CChartStyle(EFFECT_NONE, EFFECT_SUBTLE, s[0], EFFECT_SUBTLE, EFFECT_NONE, [], 3, s[0], 7); this.styles[1] = new CChartStyle(EFFECT_NONE, EFFECT_SUBTLE, s[1], EFFECT_SUBTLE, EFFECT_NONE, [], 3, s[1], 7); for(var i = 2; i < 8; ++i) { this.styles[i] = new CChartStyle(EFFECT_NONE, EFFECT_SUBTLE, [f(i - 2,0)], EFFECT_SUBTLE, EFFECT_NONE, [], 3, [f(i - 2,0)], 7); } this.styles[8] = new CChartStyle(EFFECT_SUBTLE, EFFECT_SUBTLE, s[0], EFFECT_SUBTLE, EFFECT_SUBTLE, [f(12,0)], 5, s[0], 9); this.styles[9] = new CChartStyle(EFFECT_SUBTLE, EFFECT_SUBTLE, s[1], EFFECT_SUBTLE, EFFECT_SUBTLE, [f(12,0)], 5, s[1], 9); for(i = 10; i < 16; ++i) { this.styles[i] = new CChartStyle(EFFECT_SUBTLE, EFFECT_SUBTLE, [f(i-10,0)], EFFECT_SUBTLE, EFFECT_SUBTLE, [f(12,0)], 5, [f(i-10,0)], 9); } this.styles[16] = new CChartStyle(EFFECT_MODERATE, EFFECT_INTENSE, s[0], EFFECT_SUBTLE, EFFECT_NONE, [], 5, s[0], 9); this.styles[17] = new CChartStyle(EFFECT_MODERATE, EFFECT_INTENSE, s[1], EFFECT_INTENSE, EFFECT_NONE, [], 5, s[1], 9); for(i = 18; i < 24; ++i) { this.styles[i] = new CChartStyle(EFFECT_MODERATE, EFFECT_INTENSE, [f(i-18,0)], EFFECT_SUBTLE, EFFECT_NONE, [], 5, [f(i-18,0)], 9); } this.styles[24] = new CChartStyle(EFFECT_INTENSE, EFFECT_INTENSE, s[0], EFFECT_SUBTLE, EFFECT_NONE, [], 7, s[0], 13); this.styles[25] = new CChartStyle(EFFECT_MODERATE, EFFECT_INTENSE, s[1], EFFECT_SUBTLE, EFFECT_NONE, [], 7, s[1], 13); for(i = 26; i < 32; ++i) { this.styles[i] = new CChartStyle(EFFECT_MODERATE, EFFECT_INTENSE, [f(i-26,0)], EFFECT_SUBTLE, EFFECT_NONE, [], 7, [f(i-26,0)], 13); } this.styles[32] = new CChartStyle(EFFECT_NONE, EFFECT_SUBTLE, s[0], EFFECT_SUBTLE, EFFECT_SUBTLE, [f(8, -0.5)], 5, s[0], 9); this.styles[33] = new CChartStyle(EFFECT_NONE, EFFECT_SUBTLE, s[1], EFFECT_SUBTLE, EFFECT_SUBTLE, s[2], 5, s[1], 9); for(i = 34; i < 40; ++i) { this.styles[i] = new CChartStyle(EFFECT_NONE, EFFECT_SUBTLE, [f(i - 34, 0)], EFFECT_SUBTLE, EFFECT_SUBTLE, [f(i-34, -0.5)], 5, [f(i-34, 0)], 9); } this.styles[40] = new CChartStyle(EFFECT_INTENSE, EFFECT_INTENSE, s[3], EFFECT_SUBTLE, EFFECT_NONE, [], 5, s[3], 9); this.styles[41] = new CChartStyle(EFFECT_INTENSE, EFFECT_INTENSE, s[1], EFFECT_INTENSE, EFFECT_NONE, [], 5, s[1], 9); for(i = 42; i < 48; ++i) { this.styles[i] = new CChartStyle(EFFECT_INTENSE, EFFECT_INTENSE, [f(i-42, 0)], EFFECT_SUBTLE, EFFECT_NONE, [], 5, [f(i-42, 0)], 9); } this.defaultLineStyles = []; this.defaultLineStyles[0] = new ChartLineStyle(f(15, 0.75), f(15, 0.5), f(15, 0.75), f(15, 0), EFFECT_SUBTLE); for(i = 0; i < 32; ++i) { this.defaultLineStyles[i] = this.defaultLineStyles[0]; } this.defaultLineStyles[32] = new ChartLineStyle(f(8, 0.75), f(8, 0.5), f(8, 0.75), f(8, 0), EFFECT_SUBTLE); this.defaultLineStyles[33] = this.defaultLineStyles[32]; this.defaultLineStyles[34] = new ChartLineStyle(f(8, 0.75), f(8, 0.5), f(8, 0.75), f(8, 0), EFFECT_SUBTLE); for(i = 35; i < 40; ++i) { this.defaultLineStyles[i] = this.defaultLineStyles[34]; } this.defaultLineStyles[40] = new ChartLineStyle(f(8, 0.75), f(8, 0.9), f(12, 0), f(12, 0), EFFECT_NONE); for(i = 41; i < 48; ++i) { this.defaultLineStyles[i] = this.defaultLineStyles[40]; } }, this, []); }, getStyleByIndex: function(index) { if(AscFormat.isRealNumber(index)) { return this.styles[(index - 1) % 48]; } return this.styles[1]; }, getDefaultLineStyleByIndex: function(index) { if(AscFormat.isRealNumber(index)) { return this.defaultLineStyles[(index - 1) % 48]; } return this.defaultLineStyles[2]; } }; CHART_STYLE_MANAGER = new CChartStyleManager(); function ChartLineStyle(axisAndMajorGridLines, minorGridlines, chartArea, otherLines, floorChartArea) { this.axisAndMajorGridLines = axisAndMajorGridLines; this.minorGridlines = minorGridlines; this.chartArea = chartArea; this.otherLines = otherLines; this.floorChartArea = floorChartArea; } function CChartStyle(effect, fill1, fill2, fill3, line1, line2, line3, line4, markerSize) { this.effect = effect; this.fill1 = fill1; this.fill2 = fill2; this.fill3 = fill3; this.line1 = line1; this.line2 = line2; this.line3 = line3; this.line4 = line4; this.markerSize = markerSize; } function CreateUniFillSchemeColorWidthTint(schemeColorId, tintVal) { return AscFormat.ExecuteNoHistory( function(schemeColorId, tintVal) { return CreateUniFillSolidFillWidthTintOrShade(CreateUnifillSolidFillSchemeColorByIndex(schemeColorId), tintVal); }, this, [schemeColorId, tintVal]); } function checkFiniteNumber(num) { if(AscFormat.isRealNumber(num) && isFinite(num)) { return num; } return 0; } var G_O_VISITED_HLINK_COLOR = CreateUniFillSolidFillWidthTintOrShade(CreateUnifillSolidFillSchemeColorByIndex(10), 0); var G_O_HLINK_COLOR = CreateUniFillSolidFillWidthTintOrShade(CreateUnifillSolidFillSchemeColorByIndex(11), 0); var G_O_NO_ACTIVE_COMMENT_BRUSH = AscFormat.CreateUniFillByUniColor(AscFormat.CreateUniColorRGB(248, 231, 195)); var G_O_ACTIVE_COMMENT_BRUSH = AscFormat.CreateUniFillByUniColor(AscFormat.CreateUniColorRGB(240, 200, 120)); /*function addPointToMap(map, worksheet, row, col, pt) { if(!Array.isArray(map[worksheet.getId()+""])) { map[worksheet.getId()+""] = []; } if(!Array.isArray(map[worksheet.getId()+""][row])) { map[worksheet.getId()+""][row] = []; } if(!Array.isArray(map[worksheet.getId()+""][row][col])) { map[worksheet.getId()+""][row][col] = []; } map[worksheet.getId()+""][row][col].push(pt); } function checkPointInMap(map, worksheet, row, col) { if(map[worksheet.getId() + ""] && map[worksheet.getId() + ""][row] && map[worksheet.getId() + ""][row][col]) { var cell = worksheet.getCell3(row, col); var pts = map[worksheet.getId() + ""][row][col]; for(var i = 0; i < pts.length; ++i) { pts[i].setVal(cell.getValue()); } return true; } else { return false; } }*/ var CChangesDrawingsBool = AscDFH.CChangesDrawingsBool; var CChangesDrawingsLong = AscDFH.CChangesDrawingsLong; var CChangesDrawingsDouble = AscDFH.CChangesDrawingsDouble; var CChangesDrawingsString = AscDFH.CChangesDrawingsString; var CChangesDrawingsObject = AscDFH.CChangesDrawingsObject; var drawingsChangesMap = window['AscDFH'].drawingsChangesMap; AscDFH.changesFactory[AscDFH.historyitem_ChartSpace_SetNvGrFrProps ] = CChangesDrawingsObject; AscDFH.changesFactory[AscDFH.historyitem_ChartSpace_SetThemeOverride ] = CChangesDrawingsObject; AscDFH.changesFactory[AscDFH.historyitem_ShapeSetBDeleted ] = CChangesDrawingsBool; AscDFH.changesFactory[AscDFH.historyitem_ChartSpace_SetParent ] = CChangesDrawingsObject; AscDFH.changesFactory[AscDFH.historyitem_ChartSpace_SetChart ] = CChangesDrawingsObject; AscDFH.changesFactory[AscDFH.historyitem_ChartSpace_SetClrMapOvr ] = CChangesDrawingsObject; AscDFH.changesFactory[AscDFH.historyitem_ChartSpace_SetDate1904 ] = CChangesDrawingsBool; AscDFH.changesFactory[AscDFH.historyitem_ChartSpace_SetExternalData ] = CChangesDrawingsObject; AscDFH.changesFactory[AscDFH.historyitem_ChartSpace_SetLang ] = CChangesDrawingsString; AscDFH.changesFactory[AscDFH.historyitem_ChartSpace_SetPivotSource ] = CChangesDrawingsObject; AscDFH.changesFactory[AscDFH.historyitem_ChartSpace_SetPrintSettings ] = CChangesDrawingsObject; AscDFH.changesFactory[AscDFH.historyitem_ChartSpace_SetProtection ] = CChangesDrawingsObject; AscDFH.changesFactory[AscDFH.historyitem_ChartSpace_SetRoundedCorners ] = CChangesDrawingsBool; AscDFH.changesFactory[AscDFH.historyitem_ChartSpace_SetSpPr ] = CChangesDrawingsObject; AscDFH.changesFactory[AscDFH.historyitem_ChartSpace_SetStyle ] = CChangesDrawingsLong; AscDFH.changesFactory[AscDFH.historyitem_ChartSpace_SetTxPr ] = CChangesDrawingsObject; AscDFH.changesFactory[AscDFH.historyitem_ChartSpace_SetUserShapes ] = CChangesDrawingsString; AscDFH.changesFactory[AscDFH.historyitem_ChartSpace_SetGroup ] = CChangesDrawingsObject; AscDFH.changesFactory[AscDFH.historyitem_ExternalData_SetAutoUpdate ] = CChangesDrawingsBool; AscDFH.changesFactory[AscDFH.historyitem_ExternalData_SetId ] = CChangesDrawingsString; AscDFH.changesFactory[AscDFH.historyitem_PivotSource_SetFmtId ] = CChangesDrawingsLong; AscDFH.changesFactory[AscDFH.historyitem_PivotSource_SetName ] = CChangesDrawingsString; AscDFH.changesFactory[AscDFH.historyitem_Protection_SetChartObject ] = CChangesDrawingsBool; AscDFH.changesFactory[AscDFH.historyitem_Protection_SetData ] = CChangesDrawingsBool; AscDFH.changesFactory[AscDFH.historyitem_Protection_SetFormatting ] = CChangesDrawingsBool; AscDFH.changesFactory[AscDFH.historyitem_Protection_SetSelection ] = CChangesDrawingsBool; AscDFH.changesFactory[AscDFH.historyitem_Protection_SetUserInterface ] = CChangesDrawingsBool; AscDFH.changesFactory[AscDFH.historyitem_PrintSettingsSetHeaderFooter ] = CChangesDrawingsObject; AscDFH.changesFactory[AscDFH.historyitem_PrintSettingsSetPageMargins ] = CChangesDrawingsObject; AscDFH.changesFactory[AscDFH.historyitem_PrintSettingsSetPageSetup ] = CChangesDrawingsObject; AscDFH.changesFactory[AscDFH.historyitem_HeaderFooterChartSetAlignWithMargins ] = CChangesDrawingsBool; AscDFH.changesFactory[AscDFH.historyitem_HeaderFooterChartSetDifferentFirst ] = CChangesDrawingsBool; AscDFH.changesFactory[AscDFH.historyitem_HeaderFooterChartSetDifferentOddEven ] = CChangesDrawingsBool; AscDFH.changesFactory[AscDFH.historyitem_HeaderFooterChartSetEvenFooter ] = CChangesDrawingsString; AscDFH.changesFactory[AscDFH.historyitem_HeaderFooterChartSetEvenHeader ] = CChangesDrawingsString; AscDFH.changesFactory[AscDFH.historyitem_HeaderFooterChartSetFirstFooter ] = CChangesDrawingsString; AscDFH.changesFactory[AscDFH.historyitem_HeaderFooterChartSetFirstHeader ] = CChangesDrawingsString; AscDFH.changesFactory[AscDFH.historyitem_HeaderFooterChartSetOddFooter ] = CChangesDrawingsString; AscDFH.changesFactory[AscDFH.historyitem_HeaderFooterChartSetOddHeader ] = CChangesDrawingsString; AscDFH.changesFactory[AscDFH.historyitem_PageMarginsSetB ] = CChangesDrawingsDouble; AscDFH.changesFactory[AscDFH.historyitem_PageMarginsSetFooter ] = CChangesDrawingsDouble; AscDFH.changesFactory[AscDFH.historyitem_PageMarginsSetHeader ] = CChangesDrawingsDouble; AscDFH.changesFactory[AscDFH.historyitem_PageMarginsSetL ] = CChangesDrawingsDouble; AscDFH.changesFactory[AscDFH.historyitem_PageMarginsSetR ] = CChangesDrawingsDouble; AscDFH.changesFactory[AscDFH.historyitem_PageMarginsSetT ] = CChangesDrawingsDouble; AscDFH.changesFactory[AscDFH.historyitem_PageSetupSetBlackAndWhite ] = CChangesDrawingsBool; AscDFH.changesFactory[AscDFH.historyitem_PageSetupSetCopies ] = CChangesDrawingsLong; AscDFH.changesFactory[AscDFH.historyitem_PageSetupSetDraft ] = CChangesDrawingsBool; AscDFH.changesFactory[AscDFH.historyitem_PageSetupSetFirstPageNumber ] = CChangesDrawingsLong; AscDFH.changesFactory[AscDFH.historyitem_PageSetupSetHorizontalDpi ] = CChangesDrawingsLong; AscDFH.changesFactory[AscDFH.historyitem_PageSetupSetOrientation ] = CChangesDrawingsLong; AscDFH.changesFactory[AscDFH.historyitem_PageSetupSetPaperHeight ] = CChangesDrawingsDouble; AscDFH.changesFactory[AscDFH.historyitem_PageSetupSetPaperSize ] = CChangesDrawingsLong; AscDFH.changesFactory[AscDFH.historyitem_PageSetupSetPaperWidth ] = CChangesDrawingsDouble; AscDFH.changesFactory[AscDFH.historyitem_PageSetupSetUseFirstPageNumb ] = CChangesDrawingsBool; AscDFH.changesFactory[AscDFH.historyitem_PageSetupSetVerticalDpi ] = CChangesDrawingsLong; function CheckParagraphTextPr(oParagraph, oTextPr) { var oParaPr = oParagraph.Pr.Copy(); var oParaPr2 = new CParaPr(); var oCopyTextPr = oTextPr.Copy(); if(oCopyTextPr.FontFamily) { oCopyTextPr.RFonts.Set_FromObject( { Ascii: { Name: oCopyTextPr.FontFamily.Name, Index: -1 }, EastAsia: { Name: oCopyTextPr.FontFamily.Name, Index: -1 }, HAnsi: { Name: oCopyTextPr.FontFamily.Name, Index: -1 }, CS: { Name: oCopyTextPr.FontFamily.Name, Index: -1 } } ); } oParaPr2.DefaultRunPr = oCopyTextPr; oParaPr.Merge(oParaPr2); oParagraph.Set_Pr(oParaPr); } function CheckObjectTextPr(oElement, oTextPr, oDrawingDocument) { if(oElement) { if(!oElement.txPr) { oElement.setTxPr(AscFormat.CreateTextBodyFromString("", oDrawingDocument, oElement)); } oElement.txPr.content.Content[0].Set_DocumentIndex(0); CheckParagraphTextPr(oElement.txPr.content.Content[0], oTextPr); if(oElement.tx && oElement.tx.rich) { var aContent = oElement.tx.rich.content.Content; for(var i = 0; i < aContent.length; ++i) { CheckParagraphTextPr(aContent[i], oTextPr); } oElement.tx.rich.content.Set_ApplyToAll(true); var oParTextPr = new AscCommonWord.ParaTextPr(oTextPr); oElement.tx.rich.content.AddToParagraph(oParTextPr); oElement.tx.rich.content.Set_ApplyToAll(false); } CheckParagraphTextPr(oElement.txPr.content.Content[0], oTextPr); } } function CheckIncDecFontSize(oElement, bIncrease, oDrawingDocument,nDefaultSize) { if(oElement) { if(!oElement.txPr) { oElement.setTxPr(AscFormat.CreateTextBodyFromString("", oDrawingDocument, oElement)); } var oParaPr = oElement.txPr.content.Content[0].Pr.Copy(); oElement.txPr.content.Content[0].Set_DocumentIndex(0); var oCopyTextPr; if(oParaPr.DefaultRunPr) { oCopyTextPr = oParaPr.DefaultRunPr.Copy(); } else { oCopyTextPr = new CTextPr(); } oCopyTextPr.FontSize = FontSize_IncreaseDecreaseValue( bIncrease, AscFormat.isRealNumber(oCopyTextPr.FontSize) ? oCopyTextPr.FontSize : nDefaultSize); oParaPr.DefaultRunPr = oCopyTextPr; oElement.txPr.content.Content[0].Set_Pr(oParaPr); if(oElement.tx && oElement.tx.rich) { oElement.tx.rich.content.Set_ApplyToAll(true); oElement.tx.rich.content.IncreaseDecreaseFontSize(bIncrease); oElement.tx.rich.content.Set_ApplyToAll(false); } } } function CPathMemory(){ this.size = 1000; this.ArrPathCommand = new Float64Array(this.size); this.curPos = -1; this.path = new AscFormat.Path2(this); } CPathMemory.prototype.AllocPath = function(){ if(this.curPos + 1 >= this.ArrPathCommand.length){ var aNewArray = new Float64Array((((3/2)*(this.curPos + 1)) >> 0) + 1); for(var i = 0; i < this.ArrPathCommand.length; ++i){ aNewArray[i] = this.ArrPathCommand[i]; } this.ArrPathCommand = aNewArray; this.path.ArrPathCommand = aNewArray; } this.path.startPos = ++this.curPos; this.path.curLen = 0; this.ArrPathCommand[this.curPos] = 0; return this.path; }; CPathMemory.prototype.GetPath = function(index){ this.path.startPos = index; this.path.curLen = 0; return this.path; }; drawingsChangesMap[AscDFH.historyitem_ChartSpace_SetNvGrFrProps ] = function(oClass, value){oClass.nvGraphicFramePr = value;}; drawingsChangesMap[AscDFH.historyitem_ChartSpace_SetThemeOverride ] = function(oClass, value){oClass.themeOverride = value;}; drawingsChangesMap[AscDFH.historyitem_ShapeSetBDeleted ] = function(oClass, value){oClass.bDeleted = value;}; drawingsChangesMap[AscDFH.historyitem_ChartSpace_SetParent ] = function(oClass, value){oClass.parent = value;}; drawingsChangesMap[AscDFH.historyitem_ChartSpace_SetChart ] = function(oClass, value){oClass.chart = value;}; drawingsChangesMap[AscDFH.historyitem_ChartSpace_SetClrMapOvr ] = function(oClass, value){oClass.clrMapOvr = value;}; drawingsChangesMap[AscDFH.historyitem_ChartSpace_SetDate1904 ] = function(oClass, value){oClass.date1904 = value;}; drawingsChangesMap[AscDFH.historyitem_ChartSpace_SetExternalData ] = function(oClass, value){oClass.externalData = value;}; drawingsChangesMap[AscDFH.historyitem_ChartSpace_SetLang ] = function(oClass, value){oClass.lang = value;}; drawingsChangesMap[AscDFH.historyitem_ChartSpace_SetPivotSource ] = function(oClass, value){oClass.pivotSource = value;}; drawingsChangesMap[AscDFH.historyitem_ChartSpace_SetPrintSettings ] = function(oClass, value){oClass.printSettings = value;}; drawingsChangesMap[AscDFH.historyitem_ChartSpace_SetProtection ] = function(oClass, value){oClass.protection = value;}; drawingsChangesMap[AscDFH.historyitem_ChartSpace_SetRoundedCorners ] = function(oClass, value){oClass.roundedCorners = value;}; drawingsChangesMap[AscDFH.historyitem_ChartSpace_SetSpPr ] = function(oClass, value){oClass.spPr = value;}; drawingsChangesMap[AscDFH.historyitem_ChartSpace_SetStyle ] = function(oClass, value){oClass.style = value;}; drawingsChangesMap[AscDFH.historyitem_ChartSpace_SetTxPr ] = function(oClass, value){oClass.txPr = value;}; drawingsChangesMap[AscDFH.historyitem_ChartSpace_SetUserShapes ] = function(oClass, value){oClass.userShapes = value;}; drawingsChangesMap[AscDFH.historyitem_ChartSpace_SetGroup ] = function(oClass, value){oClass.group = value;}; drawingsChangesMap[AscDFH.historyitem_ExternalData_SetAutoUpdate ] = function(oClass, value){oClass.autoUpdate = value;}; drawingsChangesMap[AscDFH.historyitem_ExternalData_SetId ] = function(oClass, value){oClass.id = value;}; drawingsChangesMap[AscDFH.historyitem_PivotSource_SetFmtId ] = function(oClass, value){oClass.fmtId = value;}; drawingsChangesMap[AscDFH.historyitem_PivotSource_SetName ] = function(oClass, value){oClass.name = value;}; drawingsChangesMap[AscDFH.historyitem_Protection_SetChartObject ] = function(oClass, value){oClass.chartObject = value;}; drawingsChangesMap[AscDFH.historyitem_Protection_SetData ] = function(oClass, value){oClass.data = value;}; drawingsChangesMap[AscDFH.historyitem_Protection_SetFormatting ] = function(oClass, value){oClass.formatting = value;}; drawingsChangesMap[AscDFH.historyitem_Protection_SetSelection ] = function(oClass, value){oClass.selection = value;}; drawingsChangesMap[AscDFH.historyitem_Protection_SetUserInterface ] = function(oClass, value){oClass.userInterface = value;}; drawingsChangesMap[AscDFH.historyitem_PrintSettingsSetHeaderFooter ] = function(oClass, value){oClass.headerFooter = value;}; drawingsChangesMap[AscDFH.historyitem_PrintSettingsSetPageMargins ] = function(oClass, value){oClass.pageMargins = value;}; drawingsChangesMap[AscDFH.historyitem_PrintSettingsSetPageSetup ] = function(oClass, value){oClass.pageSetup = value;}; drawingsChangesMap[AscDFH.historyitem_HeaderFooterChartSetAlignWithMargins ] = function(oClass, value){oClass.alignWithMargins = value;}; drawingsChangesMap[AscDFH.historyitem_HeaderFooterChartSetDifferentFirst ] = function(oClass, value){oClass.differentFirst = value;}; drawingsChangesMap[AscDFH.historyitem_HeaderFooterChartSetDifferentOddEven ] = function(oClass, value){oClass.differentOddEven = value;}; drawingsChangesMap[AscDFH.historyitem_HeaderFooterChartSetEvenFooter ] = function(oClass, value){oClass.evenFooter = value;}; drawingsChangesMap[AscDFH.historyitem_HeaderFooterChartSetEvenHeader ] = function(oClass, value){oClass.evenHeader = value;}; drawingsChangesMap[AscDFH.historyitem_HeaderFooterChartSetFirstFooter ] = function(oClass, value){oClass.firstFooter = value;}; drawingsChangesMap[AscDFH.historyitem_HeaderFooterChartSetFirstHeader ] = function(oClass, value){oClass.firstHeader = value;}; drawingsChangesMap[AscDFH.historyitem_HeaderFooterChartSetOddFooter ] = function(oClass, value){oClass.oddFooter = value;}; drawingsChangesMap[AscDFH.historyitem_HeaderFooterChartSetOddHeader ] = function(oClass, value){oClass.oddHeader = value;}; drawingsChangesMap[AscDFH.historyitem_PageMarginsSetB ] = function(oClass, value){oClass.b = value;}; drawingsChangesMap[AscDFH.historyitem_PageMarginsSetFooter ] = function(oClass, value){oClass.footer = value;}; drawingsChangesMap[AscDFH.historyitem_PageMarginsSetHeader ] = function(oClass, value){oClass.header = value;}; drawingsChangesMap[AscDFH.historyitem_PageMarginsSetL ] = function(oClass, value){oClass.l = value;}; drawingsChangesMap[AscDFH.historyitem_PageMarginsSetR ] = function(oClass, value){oClass.r = value;}; drawingsChangesMap[AscDFH.historyitem_PageMarginsSetT ] = function(oClass, value){oClass.t = value;}; drawingsChangesMap[AscDFH.historyitem_PageSetupSetBlackAndWhite ] = function(oClass, value){oClass.blackAndWhite = value;}; drawingsChangesMap[AscDFH.historyitem_PageSetupSetCopies ] = function(oClass, value){oClass.copies = value;}; drawingsChangesMap[AscDFH.historyitem_PageSetupSetDraft ] = function(oClass, value){oClass.draft = value;}; drawingsChangesMap[AscDFH.historyitem_PageSetupSetFirstPageNumber ] = function(oClass, value){oClass.firstPageNumber = value;}; drawingsChangesMap[AscDFH.historyitem_PageSetupSetHorizontalDpi ] = function(oClass, value){oClass.horizontalDpi = value;}; drawingsChangesMap[AscDFH.historyitem_PageSetupSetOrientation ] = function(oClass, value){oClass.orientation = value;}; drawingsChangesMap[AscDFH.historyitem_PageSetupSetPaperHeight ] = function(oClass, value){oClass.paperHeight = value;}; drawingsChangesMap[AscDFH.historyitem_PageSetupSetPaperSize ] = function(oClass, value){oClass.paperSize = value;}; drawingsChangesMap[AscDFH.historyitem_PageSetupSetPaperWidth ] = function(oClass, value){oClass.paperWidth = value;}; drawingsChangesMap[AscDFH.historyitem_PageSetupSetUseFirstPageNumb ] = function(oClass, value){oClass.useFirstPageNumb = value;}; drawingsChangesMap[AscDFH.historyitem_PageSetupSetVerticalDpi ] = function(oClass, value){oClass.verticalDpi = value;}; function CLabelsBox(aStrings, oAxis, oChartSpace){ this.x = 0.0; this.y = 0.0; this.extX = 0.0; this.extY = 0.0; this.aLabels = []; this.maxMinWidth = -1.0; this.chartSpace = oChartSpace; this.axis = oAxis; var oStyle = null, oLbl, fMinW; for(var i = 0; i < aStrings.length; ++i){ if(typeof aStrings[i] === "string"){ oLbl = fCreateLabel(aStrings[i], i, oAxis, oChartSpace, oAxis.txPr, oAxis.spPr, oChartSpace.getDrawingDocument()); if(oStyle){ oLbl.lastStyleObject = oStyle; } fMinW = oLbl.tx.rich.content.RecalculateMinMaxContentWidth().Min; if(fMinW > this.maxMinWidth){ this.maxMinWidth = fMinW; } this.aLabels.push(oLbl); if(!oStyle){ oStyle = oLbl.lastStyleObject; } } else{ this.aLabels.push(null); } } } CLabelsBox.prototype.draw = function(graphics){ for(var i = 0; i < this.aLabels.length; ++i) { if(this.aLabels[i]) this.aLabels[i].draw(graphics); } // graphics.p_width(70); // graphics.p_color(0, 0, 0, 255); // graphics._s(); // graphics._m(this.x, this.y); // graphics._l(this.x + this.extX, this.y + 0); // graphics._l(this.x + this.extX, this.y + this.extY); // graphics._l(this.x + 0, this.y + this.extY); // graphics._z(); // graphics.ds(); }; CLabelsBox.prototype.checkMaxMinWidth = function () { if(this.maxMinWidth < 0.0){ var oStyle = null, oLbl, fMinW; for(var i = 0; i < this.aLabels.length; ++i){ oLbl = this.aLabels[i]; if(oLbl){ if(oStyle){ oLbl.lastStyleObject = oStyle; } fMinW = oLbl.tx.rich.content.RecalculateMinMaxContentWidth().Min; if(fMinW > this.maxMinWidth){ this.maxMinWidth = fMinW; } if(!oStyle){ oStyle = oLbl.lastStyleObject; } } } } return this.maxMinWidth >= 0.0 ? this.maxMinWidth : 0.0; }; CLabelsBox.prototype.hit = function(x, y){ var tx, ty; if(this.chartSpace && this.chartSpace.invertTransform) { tx = this.chartSpace.invertTransform.TransformPointX(x, y); ty = this.chartSpace.invertTransform.TransformPointY(x, y); return tx >= this.x && ty >= this.y && tx <= this.x + this.extX && ty <= this.y + this.extY; } return false; }; CLabelsBox.prototype.updatePosition = function(x, y) { // this.posX = x; // this.posY = y; // this.transform = this.localTransform.CreateDublicate(); // global_MatrixTransformer.TranslateAppend(this.transform, x, y); // this.invertTransform = global_MatrixTransformer.Invert(this.transform); for(var i = 0; i < this.aLabels.length; ++i) { if(this.aLabels[i]) this.aLabels[i].updatePosition(x, y); } }; CLabelsBox.prototype.layoutHorNormal = function(fAxisY, fDistance, fXStart, fInterval, bOnTickMark, fForceContentWidth){ var fMaxHeight = 0.0; var fCurX = bOnTickMark ? fXStart - fInterval/2.0 : fXStart; if(fInterval < 0.0){ fCurX += fInterval; } var oFirstLabel = null, fFirstLabelCenterX = null, oLastLabel = null, fLastLabelCenterX = null; var fContentWidth = fForceContentWidth ? fForceContentWidth : Math.abs(fInterval); var fHorShift = Math.abs(fInterval)/2.0 - fContentWidth/2.0; for(var i = 0; i < this.aLabels.length; ++i){ if(this.aLabels[i]){ var oLabel = this.aLabels[i]; var oContent = oLabel.tx.rich.content; oContent.Reset(0, 0, fContentWidth, 20000.0); oContent.Recalculate_Page(0, true); var fCurHeight = oContent.GetSummaryHeight(); if(fCurHeight > fMaxHeight){ fMaxHeight = fCurHeight; } var fX, fY; fX = fCurX + fHorShift; if(fDistance >= 0.0){ fY = fAxisY + fDistance; } else{ fY = fAxisY + fDistance - fCurHeight; } var oTransform = oLabel.transformText; oTransform.Reset(); global_MatrixTransformer.TranslateAppend(oTransform, fX, fY); oTransform = oLabel.localTransformText; oTransform.Reset(); global_MatrixTransformer.TranslateAppend(oTransform, fX, fY); if(oFirstLabel === null){ oFirstLabel = oLabel; fFirstLabelCenterX = fCurX + Math.abs(fInterval)/2.0; } oLastLabel = oLabel; fLastLabelCenterX = fCurX + Math.abs(fInterval)/2.0; } fCurX += fInterval; } var x0, x1; if(bOnTickMark && oFirstLabel && oLastLabel){ var fFirstLabelContentWidth = oFirstLabel.tx.rich.getMaxContentWidth(fContentWidth); var fLastLabelContentWidth = oLastLabel.tx.rich.getMaxContentWidth(fContentWidth); x0 = Math.min(fFirstLabelCenterX - fFirstLabelContentWidth/2.0, fLastLabelCenterX - fLastLabelContentWidth/2.0, fXStart, fXStart + fInterval*(this.aLabels.length - 1)); x1 = Math.max(fFirstLabelCenterX + fFirstLabelContentWidth/2.0, fLastLabelCenterX + fLastLabelContentWidth/2.0, fXStart, fXStart + fInterval*(this.aLabels.length - 1)); } else{ x0 = Math.min(fXStart, fXStart + fInterval*(this.aLabels.length)); x1 = Math.max(fXStart, fXStart + fInterval*(this.aLabels.length)); } this.x = x0; this.extX = x1 - x0; if(fDistance >= 0.0){ this.y = fAxisY; this.extY = fDistance + fMaxHeight; } else{ this.y = fAxisY + fDistance - fMaxHeight; this.extY = fMaxHeight - fDistance; } }; CLabelsBox.prototype.layoutHorRotated = function(fAxisY, fDistance, fXStart, fInterval, bOnTickMark){ var fMaxHeight = 0.0; var fCurX = bOnTickMark ? fXStart : fXStart + fInterval/2.0; var fAngle = Math.PI/4.0, fMultiplier = Math.sin(fAngle); // if(fInterval < 0.0){ // fCurX += fInterval; // } var fMinLeft = null, fMaxRight = null; for(var i = 0; i < this.aLabels.length; ++i){ if(this.aLabels[i]){ var oLabel = this.aLabels[i]; var oContent = oLabel.tx.rich.content; oContent.Set_ApplyToAll(true); oContent.SetParagraphAlign(AscCommon.align_Left); oContent.Set_ApplyToAll(false); var oSize = oLabel.tx.rich.getContentOneStringSizes(); var fBoxW = fMultiplier*(oSize.w + oSize.h); var fBoxH = fBoxW; if(fBoxH > fMaxHeight){ fMaxHeight = fBoxH; } var fX1, fY0, fXC, fYC; fY0 = fAxisY + fDistance; if(fDistance >= 0.0){ fX1 = fCurX + oSize.h*fMultiplier; fXC = fX1 - fBoxW/2.0; fYC = fY0 + fBoxH/2.0; } else{ fX1 = fCurX - oSize.h*fMultiplier; fXC = fX1 + fBoxW/2.0; fYC = fY0 - fBoxH/2.0; } var oTransform = oLabel.localTransformText; oTransform.Reset(); global_MatrixTransformer.TranslateAppend(oTransform, -oSize.w/2.0, -oSize.h/2.0); global_MatrixTransformer.RotateRadAppend(oTransform, fAngle); global_MatrixTransformer.TranslateAppend(oTransform, fXC, fYC); if(null === fMinLeft || (fXC - fBoxW/2.0) < fMinLeft){ fMinLeft = fXC - fBoxW/2.0; } if(null === fMaxRight || (fXC + fBoxW/2.0) > fMaxRight){ fMaxRight = fXC + fBoxW/2.0; } } fCurX += fInterval; } var aPoints = []; aPoints.push(fXStart); var nIntervalCount = bOnTickMark ? this.aLabels.length - 1 : this.aLabels.length; aPoints.push(fXStart + fInterval*nIntervalCount); if(null !== fMinLeft){ aPoints.push(fMinLeft); } if(null !== fMaxRight){ aPoints.push(fMaxRight); } this.x = Math.min.apply(Math, aPoints); this.extX = Math.max.apply(Math, aPoints) - this.x; if(fDistance >= 0.0){ this.y = fAxisY; this.extY = fDistance + fMaxHeight; } else{ this.y = fAxisY + fDistance - fMaxHeight; this.extY = fMaxHeight - fDistance; } }; CLabelsBox.prototype.layoutVertNormal = function(fAxisX, fDistance, fYStart, fInterval, bOnTickMark, fMaxBlockWidth){ var fCurY = bOnTickMark ? fYStart : fYStart + fInterval/2.0; var fDistance_ = Math.abs(fDistance); var oTransform, oContent, oLabel, fMinY = fYStart, fMaxY = fYStart + fInterval*(this.aLabels.length - 1), fY; var fMaxContentWidth = 0.0; for(var i = 0; i < this.aLabels.length; ++i){ if(this.aLabels[i]){ oLabel = this.aLabels[i]; oContent = oLabel.tx.rich.content; oContent.Set_ApplyToAll(true); oContent.SetParagraphAlign(AscCommon.align_Left); oContent.Set_ApplyToAll(false); var oSize = oLabel.tx.rich.getContentOneStringSizes(); if(oSize.w + fDistance_ > fMaxBlockWidth){ break; } if(oSize.w > fMaxContentWidth){ fMaxContentWidth = oSize.w; } oTransform = oLabel.localTransformText; oTransform.Reset(); fY = fCurY - oSize.h/2.0; if(fDistance > 0.0){ global_MatrixTransformer.TranslateAppend(oTransform, fAxisX + fDistance, fY); } else{ global_MatrixTransformer.TranslateAppend(oTransform, fAxisX + fDistance - oSize.w, fY); } if(fY < fMinY){ fMinY = fY; } if(fY + oSize.h > fMaxY){ fMaxY = fY + oSize.h; } } fCurY += fInterval; } if(i < this.aLabels.length){ var fMaxMinWidth = this.checkMaxMinWidth(); fMaxContentWidth = 0.0; for(i = 0; i < this.aLabels.length; ++i){ oLabel = this.aLabels[i]; if(oLabel){ oContent = oLabel.tx.rich.content; oContent.Set_ApplyToAll(true); oContent.SetParagraphAlign(AscCommon.align_Center); oContent.Set_ApplyToAll(false); var fContentWidth; if(fMaxMinWidth + fDistance_ < fMaxBlockWidth) { fContentWidth = oContent.RecalculateMinMaxContentWidth().Min + 0.1; } else{ fContentWidth = fMaxBlockWidth - fDistance_; } if(fContentWidth > fMaxContentWidth){ fMaxContentWidth = fContentWidth; } oContent.Reset(0, 0, fContentWidth, 20000);//выставляем большую ширину чтобы текст расчитался в одну строку. oContent.Recalculate_Page(0, true); var fContentHeight = oContent.GetSummaryHeight(); oTransform = oLabel.localTransformText; oTransform.Reset(); fY = fCurY - fContentHeight/2.0; if(fDistance > 0.0){ global_MatrixTransformer.TranslateAppend(oTransform, fAxisX + fDistance, fY); } else{ fY = fCurY - fContentHeight/2.0; global_MatrixTransformer.TranslateAppend(oTransform, fAxisX + fDistance - fContentWidth, fY); } if(fY < fMinY){ fMinY = fY; } if(fY + fContentHeight > fMaxY){ fMaxY = fY + fContentHeight; } } fCurY += fInterval; } } if(fDistance > 0.0){ this.x = fAxisX; } else{ this.x = fAxisX + fDistance - fMaxContentWidth; } this.extX = fMaxContentWidth + fDistance_; this.y = fMinY; this.extY = fMaxY - fMinY; }; function fCreateLabel(sText, idx, oParent, oChart, oTxPr, oSpPr, oDrawingDocument){ var dlbl = new AscFormat.CDLbl(); dlbl.parent = oParent; dlbl.chart = oChart; dlbl.spPr = oSpPr; dlbl.txPr = oTxPr; dlbl.idx = idx; dlbl.tx = new AscFormat.CChartText(); dlbl.tx.rich = AscFormat.CreateTextBodyFromString(sText, oDrawingDocument, dlbl); var content = dlbl.tx.rich.content; content.Set_ApplyToAll(true); content.SetParagraphAlign(AscCommon.align_Center); content.Set_ApplyToAll(false); dlbl.txBody = dlbl.tx.rich; dlbl.oneStringWidth = -1.0; return dlbl; } function fLayoutHorLabelsBox(oLabelsBox, fY, fXStart, fXEnd, bOnTickMark, fDistance, bForceVertical, bNumbers, fForceContentWidth){ var fAxisLength = fXEnd - fXStart; var nLabelsCount = oLabelsBox.aLabels.length; var bOnTickMark_ = bOnTickMark && nLabelsCount > 1; var nIntervalCount = bOnTickMark_ ? nLabelsCount - 1 : nLabelsCount; var fInterval = fAxisLength/nIntervalCount; if(!bForceVertical || true){//TODO: implement for vertical labels var fMaxMinWidth = oLabelsBox.checkMaxMinWidth(); var fCheckInterval = AscFormat.isRealNumber(fForceContentWidth) ? fForceContentWidth : Math.abs(fInterval); if(fMaxMinWidth <= fCheckInterval){ oLabelsBox.layoutHorNormal(fY, fDistance, fXStart, fInterval, bOnTickMark_, fForceContentWidth); } else{ oLabelsBox.layoutHorRotated(fY, fDistance, fXStart, fInterval, bOnTickMark_); } } } function fLayoutVertLabelsBox(oLabelsBox, fX, fYStart, fYEnd, bOnTickMark, fDistance, bForceVertical){ var fAxisLength = fYEnd - fYStart; var nLabelsCount = oLabelsBox.aLabels.length; var bOnTickMark_ = bOnTickMark && nLabelsCount > 1; var nIntervalCount = bOnTickMark_ ? nLabelsCount - 1 : nLabelsCount; var fInterval = fAxisLength/nIntervalCount; if(!bForceVertical || true){ oLabelsBox.layoutVertNormal(fX, fDistance, fYStart, fInterval, bOnTickMark_); } else{ //TODO: vertical text } } function CAxisGrid(){ this.nType = 0;//0 - horizontal, 1 - vertical, 2 - series axis this.fStart = 0.0; this.fStride = 0.0; this.bOnTickMark = true; this.nCount = 0; this.minVal = 0.0; this.maxVal = 0.0; this.aStrings = []; } function CChartSpace() { AscFormat.CGraphicObjectBase.call(this); this.nvGraphicFramePr = null; this.chart = null; this.clrMapOvr = null; this.date1904 = null; this.externalData = null; this.lang = null; this.pivotSource = null; this.printSettings = null; this.protection = null; this.roundedCorners = null; this.spPr = null; this.style = 2; this.txPr = null; this.userShapes = null; this.themeOverride = null; this.pathMemory = new CPathMemory(); this.bbox = null; this.ptsCount = 0; this.selection = { title: null, legend: null, legendEntry: null, axisLbls: null, dataLbls: null, dataLbl: null, plotArea: null, rotatePlotArea: null, gridLines: null, series: null, datPoint: null, textSelection: null }; this.Id = g_oIdCounter.Get_NewId(); g_oTableId.Add(this, this.Id); } CChartSpace.prototype = Object.create(AscFormat.CGraphicObjectBase.prototype); CChartSpace.prototype.constructor = CChartSpace; CChartSpace.prototype.AllocPath = function(){ return this.pathMemory.AllocPath().startPos; }; CChartSpace.prototype.GetPath = function(index){ return this.pathMemory.GetPath(index); }; CChartSpace.prototype.select = CShape.prototype.select; CChartSpace.prototype.checkDrawingBaseCoords = CShape.prototype.checkDrawingBaseCoords; CChartSpace.prototype.setDrawingBaseCoords = CShape.prototype.setDrawingBaseCoords; CChartSpace.prototype.deleteBFromSerialize = CShape.prototype.deleteBFromSerialize; CChartSpace.prototype.setBFromSerialize = CShape.prototype.setBFromSerialize; CChartSpace.prototype.checkTypeCorrect = function(){ if(!this.chart){ return false; } if(!this.chart.plotArea){ return false } if(this.chart.plotArea.charts.length === 0){ return false; } if(this.chart.plotArea.charts[0].series.length === 0){ return false; } return true; }; CChartSpace.prototype.drawSelect = function(drawingDocument, nPageIndex) { var i; if(this.selectStartPage === nPageIndex) { drawingDocument.DrawTrack(AscFormat.TYPE_TRACK.SHAPE, this.getTransformMatrix(), 0, 0, this.extX, this.extY, false, this.canRotate()); if(window["NATIVE_EDITOR_ENJINE"]){ return; } if(this.selection.textSelection) { drawingDocument.DrawTrack(AscFormat.TYPE_TRACK.CHART_TEXT, this.selection.textSelection.transform, 0, 0, this.selection.textSelection.extX, this.selection.textSelection.extY, false, false, false); } else if(this.selection.title) { drawingDocument.DrawTrack(AscFormat.TYPE_TRACK.CHART_TEXT, this.selection.title.transform, 0, 0, this.selection.title.extX, this.selection.title.extY, false, false, false); } else if(AscFormat.isRealNumber(this.selection.dataLbls)) { var series = this.chart.plotArea.charts[0].series; var ser = series[this.selection.dataLbls]; if(ser) { var pts = AscFormat.getPtsFromSeries(ser); if(!AscFormat.isRealNumber(this.selection.dataLbl)) { for(i = 0; i < pts.length; ++i) { if(pts[i] && pts[i].compiledDlb && !pts[i].compiledDlb.bDelete) { drawingDocument.DrawTrack(AscFormat.TYPE_TRACK.CHART_TEXT, pts[i].compiledDlb.transform, 0, 0, pts[i].compiledDlb.extX, pts[i].compiledDlb.extY, false, false); } } } else { if(pts[this.selection.dataLbl] && pts[this.selection.dataLbl].compiledDlb) { drawingDocument.DrawTrack(AscFormat.TYPE_TRACK.CHART_TEXT, pts[this.selection.dataLbl].compiledDlb.transform, 0, 0, pts[this.selection.dataLbl].compiledDlb.extX, pts[this.selection.dataLbl].compiledDlb.extY, false, false); } } } } else if(this.selection.dataLbl) { drawingDocument.DrawTrack(AscFormat.TYPE_TRACK.CHART_TEXT, this.selection.dataLbl.transform, 0, 0, this.selection.dataLbl.extX, this.selection.dataLbl.extY, false, false); } else if(this.selection.legend) { if(AscFormat.isRealNumber(this.selection.legendEntry)) { var oEntry = this.chart.legend.findCalcEntryByIdx(this.selection.legendEntry); if(oEntry){ drawingDocument.DrawTrack(AscFormat.TYPE_TRACK.CHART_TEXT, oEntry.transformText, 0, 0, oEntry.contentWidth, oEntry.contentHeight, false, false); } } else { drawingDocument.DrawTrack(AscFormat.TYPE_TRACK.CHART_TEXT, this.selection.legend.transform, 0, 0, this.selection.legend.extX, this.selection.legend.extY, false, false); } } else if(this.selection.axisLbls) { var oLabels = this.selection.axisLbls.labels; drawingDocument.DrawTrack(AscFormat.TYPE_TRACK.CHART_TEXT, this.transform, oLabels.x, oLabels.y, oLabels.extX, oLabels.extY, false, false); } else if(this.selection.plotArea) { var oChartSize = this.getChartSizes(true); drawingDocument.DrawTrack(AscFormat.TYPE_TRACK.CHART_TEXT, this.transform, oChartSize.startX, oChartSize.startY, oChartSize.w, oChartSize.h, false, false); /*if(!this.selection.rotatePlotArea) { drawingDocument.DrawTrack(AscFormat.TYPE_TRACK.CHART_TEXT, this.transform, oChartSize.startX, oChartSize.startY, oChartSize.w, oChartSize.h, false, false); } else { var arr = [ {x: oChartSize.startX, y: oChartSize.startY}, {x: oChartSize.startX + oChartSize.w/2, y: oChartSize.startY}, {x: oChartSize.startX + oChartSize.w, y: oChartSize.startY}, {x: oChartSize.startX + oChartSize.w, y: oChartSize.startY + oChartSize.h/2}, {x: oChartSize.startX + oChartSize.w, y: oChartSize.startY + oChartSize.h}, {x: oChartSize.startX + oChartSize.w/2, y: oChartSize.startY + oChartSize.h}, {x: oChartSize.startX, y: oChartSize.startY + oChartSize.h}, {x: oChartSize.startX, y: oChartSize.startY + oChartSize.h/2}, {x: oChartSize.startX, y: oChartSize.startY} ]; drawingDocument.AutoShapesTrack.DrawEditWrapPointsPolygon(arr, this.transform); }*/ } } }; CChartSpace.prototype.recalculateTextPr = function() { if(this.txPr && this.txPr.content) { this.txPr.content.Reset(0, 0, 10, 10); this.txPr.content.Recalculate_Page(0, true); } }; CChartSpace.prototype.getSelectionState = function() { var content_selection = null, content = null; if(this.selection.textSelection) { content = this.selection.textSelection.getDocContent(); if(content) content_selection = content.GetSelectionState(); } return { content: content, title: this.selection.title, legend: this.selection.legend, legendEntry: this.selection.legendEntry, axisLbls: this.selection.axisLbls, dataLbls: this.selection.dataLbls, dataLbl: this.selection.dataLbl, textSelection: this.selection.textSelection, plotArea: this.selection.plotArea, rotatePlotArea: this.selection.rotatePlotArea, contentSelection: content_selection, recalcTitle: this.recalcInfo.recalcTitle, bRecalculatedTitle: this.recalcInfo.bRecalculatedTitle } }; CChartSpace.prototype.setSelectionState = function(state) { this.selection.title = state.title; this.selection.legend = state.legend; this.selection.legendEntry = state.legendEntry; this.selection.axisLbls = state.axisLbls; this.selection.dataLbls = state.dataLbls; this.selection.dataLbl = state.dataLbl; this.selection.rotatePlotArea = state.rotatePlotArea; this.selection.textSelection = state.textSelection; this.selection.plotArea = state.plotArea; if(isRealObject(state.recalcTitle)) { this.recalcInfo.recalcTitle = state.recalcTitle; this.recalcInfo.bRecalculatedTitle = state.bRecalculatedTitle; } if(state.contentSelection) { if(this.selection.textSelection) { var content = this.selection.textSelection.getDocContent(); if(content) content.SetSelectionState(state.contentSelection, state.contentSelection.length - 1); } } }; CChartSpace.prototype.loadDocumentStateAfterLoadChanges = function(state) { this.selection.title = null; this.selection.legend = null; this.selection.legendEntry = null; this.selection.axisLbls = null; this.selection.dataLbls = null; this.selection.dataLbl = null; this.selection.plotArea = null; this.selection.rotatePlotArea = null; this.selection.gridLine = null; this.selection.series = null; this.selection.datPoint = null; this.selection.textSelection = null; var bRet = false; if(state.DrawingsSelectionState){ var chartSelection = state.DrawingsSelectionState.chartSelection; if(chartSelection){ if(this.chart){ if(chartSelection.title){ if(this.chart.title === chartSelection.title){ this.selection.title = this.chart.title; bRet = true; } else{ var plot_area = this.chart.plotArea; if(plot_area){ for(var i = 0; i < plot_area.axId.length; ++i){ var axis = plot_area.axId[i]; if(axis && axis.title === chartSelection.title){ this.selection.title = axis.title; bRet = true; break; } } } } if(this.selection.title){ if(this.selection.title === chartSelection.textSelection){ var oTitleContent = this.selection.title.getDocContent(); if(oTitleContent && oTitleContent === chartSelection.content){ this.selection.textSelection = this.selection.title; if (true === state.DrawingSelection) { oTitleContent.SetContentPosition(state.StartPos, 0, 0); oTitleContent.SetContentSelection(state.StartPos, state.EndPos, 0, 0, 0); } else { oTitleContent.SetContentPosition(state.Pos, 0, 0); } } } } } } } } return bRet; }; CChartSpace.prototype.resetInternalSelection = function(noResetContentSelect) { if(this.selection.title) { this.selection.title.selected = false; } if(this.selection.textSelection) { if(!(noResetContentSelect === true)) { var content = this.selection.textSelection.getDocContent(); content && content.RemoveSelection(); } this.selection.textSelection = null; } }; CChartSpace.prototype.getDocContent = function() { return null; }; CChartSpace.prototype.resetSelection = function(noResetContentSelect) { this.resetInternalSelection(noResetContentSelect); this.selection.title = null; this.selection.legend = null; this.selection.legendEntry = null; this.selection.axisLbls = null; this.selection.dataLbls = null; this.selection.dataLbl = null; this.selection.textSelection = null; this.selection.plotArea = null; this.selection.rotatePlotArea = null; }; CChartSpace.prototype.getStyles = function() { return AscFormat.ExecuteNoHistory(function(){ var styles = new CStyles(false); var style = new CStyle("dataLblStyle", null, null, null, true); var text_pr = new CTextPr(); text_pr.FontSize = 10; text_pr.Unifill = CreateUnfilFromRGB(0,0,0); var parent_objects = this.getParentObjects(); var theme = parent_objects.theme; var para_pr = new CParaPr(); para_pr.Jc = AscCommon.align_Center; para_pr.Spacing.Before = 0.0; para_pr.Spacing.After = 0.0; para_pr.Spacing.Line = 1; para_pr.Spacing.LineRule = Asc.linerule_Auto; style.ParaPr = para_pr; var minor_font = theme.themeElements.fontScheme.minorFont; if(minor_font) { if(typeof minor_font.latin === "string" && minor_font.latin.length > 0) { text_pr.RFonts.Ascii = {Name: minor_font.latin, Index: -1}; } if(typeof minor_font.ea === "string" && minor_font.ea.length > 0) { text_pr.RFonts.EastAsia = {Name: minor_font.ea, Index: -1}; } if(typeof minor_font.cs === "string" && minor_font.cs.length > 0) { text_pr.RFonts.CS = {Name: minor_font.cs, Index: -1}; } if(typeof minor_font.sym === "string" && minor_font.sym.length > 0) { text_pr.RFonts.HAnsi = {Name: minor_font.sym, Index: -1}; } } style.TextPr = text_pr; var chart_text_pr; if(this.txPr && this.txPr.content && this.txPr.content.Content[0] && this.txPr.content.Content[0].Pr) { style.ParaPr.Merge(this.txPr.content.Content[0].Pr); if(this.txPr.content.Content[0].Pr.DefaultRunPr) { chart_text_pr = this.txPr.content.Content[0].Pr.DefaultRunPr; style.TextPr.Merge(chart_text_pr); } } if(this.txPr && this.txPr.content && this.txPr.content.Content[0] && this.txPr.content.Content[0].Pr) { style.ParaPr.Merge(this.txPr.content.Content[0].Pr); if(this.txPr.content.Content[0].Pr.DefaultRunPr) style.TextPr.Merge(this.txPr.content.Content[0].Pr.DefaultRunPr); } styles.Add(style); return {lastId: style.Id, styles: styles}; }, this, []); }; CChartSpace.prototype.getParagraphTextPr = function() { if(this.selection.title && !this.selection.textSelection) { return GetTextPrFormArrObjects([this.selection.title]); } else if(this.selection.legend) { if(!AscFormat.isRealNumber(this.selection.legendEntry)) { if(AscFormat.isRealNumber(this.legendLength)) { var arrForProps = []; for(var i = 0; i < this.legendLength; ++i) { arrForProps.push(this.chart.legend.getCalcEntryByIdx(i, this.getDrawingDocument())) } return GetTextPrFormArrObjects(arrForProps); } return GetTextPrFormArrObjects(this.chart.legend.calcEntryes); } else { var calcLegendEntry = this.chart.legend.getCalcEntryByIdx(this.selection.legendEntry, this.getDrawingDocument()); if(calcLegendEntry) { return GetTextPrFormArrObjects([calcLegendEntry]); } } } else if(this.selection.textSelection) { return this.selection.textSelection.txBody.content.GetCalculatedTextPr(); } else if(this.selection.axisLbls && this.selection.axisLbls.labels) { return GetTextPrFormArrObjects(this.selection.axisLbls.labels.aLabels, true); } else if(AscFormat.isRealNumber(this.selection.dataLbls)) { var ser = this.chart.plotArea.charts[0].series[this.selection.dataLbls]; if(ser) { var pts = AscFormat.getPtsFromSeries(ser); if(!AscFormat.isRealNumber(this.selection.dataLbl)) { return GetTextPrFormArrObjects(pts, undefined , true); } else { var pt = pts[this.selection.dataLbl]; if(pt) { return GetTextPrFormArrObjects([pt], undefined , true); } } } } if(this.txPr && this.txPr.content && this.txPr.content.Content[0] && this.txPr.content.Content[0].Pr.DefaultRunPr) { this.txPr.content.Content[0].Pr.DefaultRunPr.Copy(); } return new AscCommonWord.CTextPr(); }; CChartSpace.prototype.applyLabelsFunction = function(fCallback, value) { if(this.selection.title) { var DefaultFontSize = 18; if(this.selection.title !== this.chart.title) { DefaultFontSize = 10; } fCallback(this.selection.title, value, this.getDrawingDocument(), DefaultFontSize); } else if(this.selection.legend) { if(!AscFormat.isRealNumber(this.selection.legendEntry)) { fCallback(this.selection.legend, value, this.getDrawingDocument(), 10); for(var i = 0; i < this.selection.legend.legendEntryes.length; ++i) { fCallback(this.selection.legend.legendEntryes[i], value, this.getDrawingDocument(), 10); } } else { var entry = this.selection.legend.findLegendEntryByIndex(this.selection.legendEntry); if(!entry) { entry = new AscFormat.CLegendEntry(); entry.setIdx(this.selection.legendEntry); if(this.selection.legend.txPr) { entry.setTxPr(this.selection.legend.txPr.createDuplicate()); } this.selection.legend.addLegendEntry(entry); } if(entry) { fCallback(entry, value, this.getDrawingDocument(), 10); } } } else if(this.selection.axisLbls) { fCallback(this.selection.axisLbls, value, this.getDrawingDocument(), 10); } else if(AscFormat.isRealNumber(this.selection.dataLbls)) { var ser = this.chart.plotArea.charts[0].series[this.selection.dataLbls]; if(ser) { var pts = AscFormat.getPtsFromSeries(ser); if(!ser.dLbls) { var oDlbls; if(this.chart.plotArea.charts[0].dLbls) { oDlbls = this.chart.plotArea.charts[0].dLbls.createDuplicate(); } else { oDlbls = new AscFormat.CDLbls(); } ser.setDLbls(oDlbls); } if(!AscFormat.isRealNumber(this.selection.dataLbl)) { fCallback(ser.dLbls, value, this.getDrawingDocument(), 10); for(var i = 0; i < pts.length; ++i) { var dLbl = ser.dLbls.findDLblByIdx(pts[i].idx); if(dLbl) { if(ser.dLbls.txPr && !dLbl.txPr) { dLbl.setTxPr(ser.dLbls.txPr.createDuplicate()); } fCallback(dLbl, value, this.getDrawingDocument(), 10); } } } else { var pt = pts[this.selection.dataLbl]; if(pt) { var dLbl = ser.dLbls.findDLblByIdx(pt.idx); if(!dLbl) { dLbl = new AscFormat.CDLbl(); dLbl.setIdx(pt.idx); if(ser.dLbls.txPr) { dLbl.merge(ser.dLbls); } ser.dLbls.addDLbl(dLbl); } fCallback(dLbl, value, this.getDrawingDocument(), 10); } } } } }; CChartSpace.prototype.paragraphIncDecFontSize = function(bIncrease) { if(this.selection.textSelection) { this.selection.textSelection.checkDocContent(); var content = this.selection.textSelection.getDocContent(); if(content) { content.IncreaseDecreaseFontSize(bIncrease); } return; } this.applyLabelsFunction(CheckIncDecFontSize, bIncrease); }; CChartSpace.prototype.paragraphAdd = function(paraItem, bRecalculate) { if(paraItem.Type === para_TextPr) { var _paraItem; if(paraItem.Value.Unifill && paraItem.Value.Unifill.checkWordMods()) { _paraItem = paraItem.Copy(); _paraItem.Value.Unifill.convertToPPTXMods(); } else { _paraItem = paraItem; } if(this.selection.textSelection) { this.selection.textSelection.checkDocContent(); this.selection.textSelection.paragraphAdd(paraItem, bRecalculate); return; } /*if(this.selection.title) { this.selection.title.checkDocContent(); CheckObjectTextPr(this.selection.title, _paraItem.Value, this.getDrawingDocument(), 18); if(this.selection.title.tx && this.selection.title.tx.rich && this.selection.title.tx.rich.content) { this.selection.title.tx.rich.content.Set_ApplyToAll(true); this.selection.title.tx.rich.content.AddToParagraph(_paraItem); this.selection.title.tx.rich.content.Set_ApplyToAll(false); } return; }*/ this.applyLabelsFunction(CheckObjectTextPr, _paraItem.Value); } else if(paraItem.Type === para_Text || paraItem.Type === para_Space){ if(this.selection.title){ this.selection.textSelection = this.selection.title; this.selection.textSelection.checkDocContent(); this.selection.textSelection.paragraphAdd(paraItem, bRecalculate); } } }; CChartSpace.prototype.applyTextFunction = function(docContentFunction, tableFunction, args) { if(docContentFunction === CDocumentContent.prototype.AddToParagraph && !this.selection.textSelection) { this.paragraphAdd(args[0], args[1]); return; } if(this.selection.textSelection) { this.selection.textSelection.checkDocContent(); var bTrackRevision = false; if(typeof editor !== "undefined" && editor && editor.WordControl && editor.WordControl.m_oLogicDocument.TrackRevisions === true){ bTrackRevision = true; editor.WordControl.m_oLogicDocument.TrackRevisions = false; } this.selection.textSelection.applyTextFunction(docContentFunction, tableFunction, args); if(bTrackRevision){ editor.WordControl.m_oLogicDocument.TrackRevisions = true; } } }; CChartSpace.prototype.selectTitle = function(title, pageIndex) { title.select(this, pageIndex); this.resetInternalSelection(); this.selection.legend = null; this.selection.legendEntry = null; this.selection.axisLbls = null; this.selection.dataLbls = null; this.selection.dataLbl = null; this.selection.textSelection = null; this.selection.plotArea = null; this.selection.rotatePlotArea = null; }; CChartSpace.prototype.recalculateCurPos = AscFormat.DrawingObjectsController.prototype.recalculateCurPos; CChartSpace.prototype.documentUpdateSelectionState = function() { if(this.selection.textSelection) { this.selection.textSelection.updateSelectionState(); } }; CChartSpace.prototype.getLegend = function() { if(this.chart) { return this.chart.legend; } return null; }; CChartSpace.prototype.getAllTitles = function() { var ret = []; if(this.chart) { if(this.chart.title) { ret.push(this.chart.title); } if(this.chart.plotArea) { if(this.chart.plotArea.catAx && this.chart.plotArea.catAx.title) { ret.push(this.chart.plotArea.catAx.title); } if(this.chart.plotArea.valAx && this.chart.plotArea.valAx.title) { ret.push(this.chart.plotArea.valAx.title); } } } return ret; }; CChartSpace.prototype.getFill = CShape.prototype.getFill; CChartSpace.prototype.changeSize = CShape.prototype.changeSize; CChartSpace.prototype.changeFill = function (unifill) { if(this.recalcInfo.recalculatePenBrush) { this.recalculatePenBrush(); } var unifill2 = AscFormat.CorrectUniFill(unifill, this.brush, this.getEditorType()); unifill2.convertToPPTXMods(); this.spPr.setFill(unifill2); }; CChartSpace.prototype.setFill = function (fill) { this.spPr.setFill(fill); }; CChartSpace.prototype.setNvSpPr = function(pr) { History.Add(new CChangesDrawingsObject(this, AscDFH.historyitem_ChartSpace_SetNvGrFrProps, this.nvGraphicFramePr, pr)); this.nvGraphicFramePr = pr; }; CChartSpace.prototype.changeLine = function (line) { if(this.recalcInfo.recalculatePenBrush) { this.recalculatePenBrush(); } var stroke = AscFormat.CorrectUniStroke(line, this.pen); if(stroke.Fill) { stroke.Fill.convertToPPTXMods(); } this.spPr.setLn(stroke); }; CChartSpace.prototype.parseChartFormula = function(sFormula) { if(this.worksheet && typeof sFormula === "string" && sFormula.length > 0){ return AscCommonExcel.getRangeByRef(sFormula, this.worksheet); } return []; }; CChartSpace.prototype.checkBBoxIntersection = function(bbox1, bbox2) { return !(bbox1.r1 > bbox2.r2 || bbox2.r1 > bbox1.r2 || bbox1.c1 > bbox2.c2 || bbox2.c1 > bbox1.c2) }; CChartSpace.prototype.checkSeriesIntersection = function(val, bbox, worksheet) { if(val && bbox && worksheet) { var parsed_formulas = val.parsedFormulas; for(var i = 0; i < parsed_formulas.length; ++i) { if(parsed_formulas[i].worksheet === worksheet && this.checkBBoxIntersection(parsed_formulas[i].bbox, bbox)) { return true; } } } return false; }; CChartSpace.prototype.checkVal = function(val) { if(val) { if(val.numRef) { val.numRef.parsedFormulas = this.parseChartFormula(val.numRef.f); } if(val.strRef) { val.strRef.parsedFormulas = this.parseChartFormula(val.strRef.f); } } }; CChartSpace.prototype.recalculateSeriesFormulas = function() { this.checkSeriesRefs(this.checkVal); }; CChartSpace.prototype.checkChartIntersection = function(bbox, worksheet) { return this.checkSeriesRefs(this.checkSeriesIntersection, bbox, worksheet); }; CChartSpace.prototype.changeListName = function(val, oldName, newName) { if(val) { if(val.numRef && typeof val.numRef.f === "string") { if(val.numRef.f.indexOf(newName) > -1) return; } if(val.strRef && typeof val.strRef.f === "string") { if(val.strRef.f.indexOf(newName) > -1) return; } if(val.numRef && typeof val.numRef.f === "string" || val.strRef && typeof val.strRef.f === "string") { var checkString = oldName.replace(/[-[\]{}()*+?.,\\^$|#\s]/g, "\\$&"); if(val.numRef && typeof val.numRef.f === "string") { val.numRef.setF(val.numRef.f.replace(new RegExp(checkString,'g'), newName)); } if(val.strRef && typeof val.strRef.f === "string") { val.strRef.setF(val.strRef.f.replace(new RegExp(checkString,'g'), newName)); } } } }; CChartSpace.prototype.checkListName = function(val, oldName) { if(val) { if(val.numRef && typeof val.numRef.f === "string") { if(val.numRef.f.indexOf(oldName) > -1) return true; } if(val.strRef && typeof val.strRef.f === "string") { if(val.strRef.f.indexOf(oldName) > -1) return true; } } return false; }; CChartSpace.prototype.changeChartReferences = function(oldWorksheetName, newWorksheetName) { this.checkSeriesRefs(this.changeListName, oldWorksheetName, newWorksheetName); }; CChartSpace.prototype.checkChartReferences = function(oldWorksheetName) { return this.checkSeriesRefs(this.checkListName, oldWorksheetName); }; CChartSpace.prototype.updateChartReferences = function(oldWorksheetName, newWorksheetName, bNoRebuildCache) { if(this.checkChartReferences(oldWorksheetName)) { if(bNoRebuildCache === true) { this.bNoHandleRecalc = true; } this.changeChartReferences(oldWorksheetName, newWorksheetName); if(!(bNoRebuildCache === true)) { this.rebuildSeries(); } this.bNoHandleRecalc = false; } }; CChartSpace.prototype.updateChartReferences2 = function(oldWorksheetName, newWorksheetName) { if(this.checkChartReferences(oldWorksheetName)) { this.changeChartReferences(oldWorksheetName, newWorksheetName); } }; CChartSpace.prototype.checkSeriesRefs = function(callback, bbox, worksheet) { if(this.chart && this.chart.plotArea) { var charts = this.chart.plotArea.charts, i, j, series, ser; for(i = 0; i < charts.length; ++i) { series = charts[i].series; if(charts[i].getObjectType() === AscDFH.historyitem_type_ScatterChart) { for(j = 0; j < series.length; ++j) { ser = series[j]; if(callback(ser.xVal, bbox, worksheet)) return true; if(callback(ser.yVal, bbox, worksheet)) return true; if(callback(ser.tx, bbox, worksheet)) return true; } } else { for(j = 0; j < series.length; ++j) { ser = series[j]; if(callback(ser.val, bbox, worksheet)) return true; if(callback(ser.cat, bbox, worksheet)) return true; if(callback(ser.tx, bbox, worksheet)) return true; } } } } return false; }; CChartSpace.prototype.clearCacheVal = function(val) { if(!val) return; if(val.numRef) { if(val.numRef.numCache) { removePtsFromLit(val.numRef.numCache); } } if(val.strRef) { if(val.strRef.strCache) { val.strRef.setStrCache(null); } } }; CChartSpace.prototype.checkIntersectionChangedRange = function(data) { if(!data) return true; var i, j; if(this.seriesBBoxes) { for(i = 0; i < this.seriesBBoxes.length; ++i) { for(j = 0; j < data.length; ++j) { if(this.seriesBBoxes[i].checkIntersection(data[j])) return true; } } } if(this.seriesTitlesBBoxes) { for(i = 0; i < this.seriesTitlesBBoxes.length; ++i) { for(j = 0; j < data.length; ++j) { if(this.seriesTitlesBBoxes[i].checkIntersection(data[j])) return true; } } } if(this.catTitlesBBoxes) { for(i = 0; i < this.catTitlesBBoxes.length; ++i) { for(j = 0; j < data.length; ++j) { if(this.catTitlesBBoxes[i].checkIntersection(data[j])) return true; } } } return false; }; CChartSpace.prototype.rebuildSeries = function(data) { if( this.checkIntersectionChangedRange(data)) { AscFormat.ExecuteNoHistory(function(){ this.checkRemoveCache(); this.recalculateReferences(); this.recalcInfo.recalculateReferences = false; // this.recalculate(); }, this, []) } }; CChartSpace.prototype.checkRemoveCache = function() { this.handleUpdateInternalChart(); this.recalcInfo.recalculateReferences = true; this.checkSeriesRefs(this.clearCacheVal); }; CChartSpace.prototype.getTypeSubType = function() { var type = null, subtype = null; if(this.chart && this.chart.plotArea && this.chart.plotArea.charts[0]) { switch (this.chart.plotArea.charts[0].getObjectType()) { case AscDFH.historyitem_type_LineChart: { type = c_oAscChartType.line; break; } case AscDFH.historyitem_type_AreaChart: { type = c_oAscChartType.area; break; } case AscDFH.historyitem_type_DoughnutChart: { type = c_oAscChartType.doughnut; break; } case AscDFH.historyitem_type_PieChart: { type = c_oAscChartType.pie; break; } case AscDFH.historyitem_type_ScatterChart: { type = c_oAscChartType.scatter; break; } case AscDFH.historyitem_type_StockChart: { type = c_oAscChartType.stock; break; } case AscDFH.historyitem_type_BarChart: { if(this.chart.plotArea.charts[0].barDir === AscFormat.BAR_DIR_BAR) type = c_oAscChartType.hbar; else type = c_oAscChartType.bar; break; } } if(AscFormat.isRealNumber(this.chart.plotArea.charts[0].grouping)) { if(!this.chart.plotArea.charts[0].getObjectType() === AscDFH.historyitem_type_BarChart) { switch(this.chart.plotArea.charts[0].grouping) { case AscFormat.GROUPING_STANDARD: { subtype = c_oAscChartSubType.normal; break; } case AscFormat.GROUPING_STACKED: { subtype = c_oAscChartSubType.stacked; break; } case AscFormat.GROUPING_PERCENT_STACKED: { subtype = c_oAscChartSubType.stackedPer; break; } } } else { switch(this.chart.plotArea.charts[0].grouping) { case AscFormat.BAR_GROUPING_CLUSTERED: case AscFormat.BAR_GROUPING_STANDARD: { subtype = c_oAscChartSubType.normal; break; } case AscFormat.BAR_GROUPING_STACKED: { subtype = c_oAscChartSubType.stacked; break; } case AscFormat.BAR_GROUPING_PERCENT_STACKED: { subtype = c_oAscChartSubType.stackedPer; break; } } } } } return {type: type, subtype: subtype}; }; CChartSpace.prototype.clearFormatting = function(bNoClearShapeProps) { if(this.spPr && !(bNoClearShapeProps === true)) { this.spPr.Fill && this.spPr.setFill(null); this.spPr.ln && this.spPr.setLn(null); } if(this.chart) { if(this.chart.plotArea) { if(this.chart.plotArea.spPr) { this.chart.plotArea.spPr.Fill && this.chart.plotArea.spPr.setFill(null); this.chart.plotArea.spPr.ln && this.chart.plotArea.spPr.setLn(null); } var i, j, k, series, pts, chart, ser; for(i = this.chart.plotArea.charts.length-1; i > -1; --i) { chart = this.chart.plotArea.charts[i]; if(chart.upDownBars /*&& chart.getObjectType() !== AscDFH.historyitem_type_StockChart*/) { if(chart.upDownBars.upBars) { if(chart.upDownBars.upBars.Fill) { chart.upDownBars.upBars.setFill(null); } if(chart.upDownBars.upBars.ln) { chart.upDownBars.upBars.setLn(null); } } if(chart.upDownBars.downBars) { if(chart.upDownBars.downBars.Fill) { chart.upDownBars.downBars.setFill(null); } if(chart.upDownBars.downBars.ln) { chart.upDownBars.downBars.setLn(null); } } } series = chart.series; for(j = series.length - 1; j > -1; --j) { ser = series[j]; if(ser.spPr && chart.getObjectType() !== AscDFH.historyitem_type_StockChart) { if(ser.spPr.Fill) { ser.spPr.setFill(null); } if(ser.spPr.ln) { ser.spPr.setLn(null); } } AscFormat.removeDPtsFromSeries(ser) } } } } }; CChartSpace.prototype.remove = function() { if(this.selection.title) { if(this.selection.title.parent) { this.selection.title.parent.setTitle(null); } } else if(this.selection.legend) { if(!AscFormat.isRealNumber(this.selection.legendEntry)) { if(this.selection.legend.parent && this.selection.legend.parent.setLegend) { this.selection.legend.parent.setLegend(null); } } else { var entry = this.selection.legend.findLegendEntryByIndex(this.selection.legendEntry); if(!entry) { entry = new AscFormat.CLegendEntry(); entry.setIdx(this.selection.legendEntry); this.selection.legend.addLegendEntry(entry); } entry.setDelete(true); } } else if(this.selection.axisLbls) { if(this.selection.axisLbls && this.selection.axisLbls.setDelete) { this.selection.axisLbls.setDelete(true); } } else if(AscFormat.isRealNumber(this.selection.dataLbls)) { var ser = this.chart.plotArea.charts[0].series[this.selection.dataLbls]; if(ser) { var oDlbls = ser.dLbls; if(!ser.dLbls) { if(this.chart.plotArea.charts[0].dLbls) { oDlbls = this.chart.plotArea.charts[0].dLbls.createDuplicate(); } else { oDlbls = new AscFormat.CDLbls(); } ser.setDLbls(oDlbls); } if(!AscFormat.isRealNumber(this.selection.dataLbl)) { oDlbls.setDelete(true); } else { var pts = AscFormat.getPtsFromSeries(ser); var pt = pts[this.selection.dataLbl]; if(pt) { var dLbl = ser.dLbls.findDLblByIdx(pt.idx); if(!dLbl) { dLbl = new AscFormat.CDLbl(); dLbl.setIdx(pt.idx); if(ser.dLbls.txPr) { dLbl.merge(ser.dLbls); } ser.dLbls.addDLbl(dLbl); } dLbl.setDelete(true); } } } } this.selection.title = null; this.selection.legend = null; this.selection.legendEntry = null; this.selection.axisLbls = null; this.selection.dataLbls = null; this.selection.dataLbl = null; this.selection.plotArea = null; this.selection.rotatePlotArea = null; this.selection.gridLine = null; this.selection.series = null; this.selection.datPoint = null; this.selection.textSelection = null; }; CChartSpace.prototype.copy = function(drawingDocument) { var copy = new CChartSpace(); if(this.chart) { copy.setChart(this.chart.createDuplicate(drawingDocument)); } if(this.clrMapOvr) { copy.setClrMapOvr(this.clrMapOvr.createDuplicate()); } copy.setDate1904(this.date1904); if(this.externalData) { copy.setExternalData(this.externalData.createDuplicate()); } copy.setLang(this.lang); if(this.pivotSource) { copy.setPivotSource(this.pivotSource.createDuplicate()); } if(this.printSettings) { copy.setPrintSettings(this.printSettings.createDuplicate()); } if(this.protection) { copy.setProtection(this.protection.createDuplicate()); } copy.setRoundedCorners(this.roundedCorners); if(this.spPr) { copy.setSpPr(this.spPr.createDuplicate()); copy.spPr.setParent(copy); } copy.setStyle(this.style); if(this.txPr) { copy.setTxPr(this.txPr.createDuplicate(drawingDocument)) } copy.setUserShapes(this.userShapes); copy.setThemeOverride(this.themeOverride); copy.setBDeleted(this.bDeleted); copy.setLocks(this.locks); copy.cachedImage = this.getBase64Img(); copy.cachedPixH = this.cachedPixH; copy.cachedPixW = this.cachedPixW; if(this.fromSerialize) { copy.setBFromSerialize(true); } return copy; }; CChartSpace.prototype.convertToWord = function(document) { this.setBDeleted(true); var oCopy = this.copy(); oCopy.setBDeleted(false); return oCopy; }; CChartSpace.prototype.convertToPPTX = function(drawingDocument, worksheet) { var copy = this.copy(drawingDocument); copy.setBDeleted(false); copy.setWorksheet(worksheet); copy.setParent(null); return copy; }; CChartSpace.prototype.rebuildSeriesFromAsc = function(asc_chart) { if(this.chart && this.chart.plotArea && this.chart.plotArea.charts[0]) { var asc_series = asc_chart.series; var chart_type = this.chart.plotArea.charts[0]; var first_series = chart_type.series[0] ? chart_type.series[0] : chart_type.getSeriesConstructor(); var bAccent1Background = false; if(this.spPr && this.spPr.Fill && this.spPr.Fill.fill && this.spPr.Fill.fill.color && this.spPr.Fill.fill.color.color && this.spPr.Fill.fill.color.color.type === window['Asc'].c_oAscColor.COLOR_TYPE_SCHEME && this.spPr.Fill.fill.color.color.id === 0){ bAccent1Background = true; } var oFirstSpPrPreset = 0; if(chart_type.getObjectType() === AscDFH.historyitem_type_PieChart || chart_type.getObjectType() === AscDFH.historyitem_type_DoughnutChart){ if(chart_type.series[0].dPt[0] && chart_type.series[0].dPt[0].spPr){ oFirstSpPrPreset = AscFormat.CollectSettingsSpPr(chart_type.series[0].dPt[0].spPr); } } else{ oFirstSpPrPreset = AscFormat.CollectSettingsSpPr(chart_type.series[0].spPr); } if(first_series.spPr){ first_series.spPr.setFill(null); first_series.spPr.setLn(null); } var style = AscFormat.CHART_STYLE_MANAGER.getStyleByIndex(this.style); var base_fills = AscFormat.getArrayFillsFromBase(style.fill2, asc_series.length); if(chart_type.getObjectType() !== AscDFH.historyitem_type_ScatterChart) { if(asc_series.length < chart_type.series.length){ for(var i = chart_type.series.length - 1; i >= asc_series.length; --i){ chart_type.removeSeries(i); } } for(var i = 0; i < asc_series.length; ++i) { var series = null, bNeedAdd = false; if(chart_type.series[i]) { series = chart_type.series[i]; } else { bNeedAdd = true; series = first_series.createDuplicate(); } series.setIdx(i); series.setOrder(i); series.setVal(new AscFormat.CYVal()); FillValNum(series.val, asc_series[i].Val, true, false); if(chart_type.getObjectType() === AscDFH.historyitem_type_PieChart || chart_type.getObjectType() === AscDFH.historyitem_type_DoughnutChart){ if(oFirstSpPrPreset){ var pts = AscFormat.getPtsFromSeries(series); for(var j = 0; j < pts.length; ++j){ var oDPt = new AscFormat.CDPt(); oDPt.setBubble3D(false); oDPt.setIdx(j); AscFormat.ApplySpPr(oFirstSpPrPreset, oDPt, j, base_fills, bAccent1Background); series.series[i].addDPt(oDPt); } } } else{ AscFormat.ApplySpPr(oFirstSpPrPreset, series, i, base_fills, bAccent1Background); } if(asc_series[i].Cat && asc_series[i].Cat.NumCache && typeof asc_series[i].Cat.Formula === "string" && asc_series[i].Cat.Formula.length > 0) { series.setCat(new AscFormat.CCat()); FillCatStr(series.cat, asc_series[i].Cat, true, false); } else { series.setCat(null); } if(asc_series[i].TxCache && typeof asc_series[i].TxCache.Formula === "string" && asc_series[i].TxCache.Formula.length > 0) { FillSeriesTx(series, asc_series[i].TxCache, true, false); } else { series.setTx(null); } if(bNeedAdd) { chart_type.addSer(series); } } } else { for(var i = chart_type.series.length - 1; i > -1; --i){ chart_type.removeSeries(i); } var oXVal; var start_index = 0; var minus = 0; if(asc_series[0].xVal && asc_series[0].xVal.NumCache && typeof asc_series[0].xVal.Formula === "string" && asc_series[0].xVal.Formula.length > 0) { oXVal = new AscFormat.CXVal(); FillCatStr(oXVal, asc_series[0].xVal, true, false); } else if(asc_series[0].Cat && asc_series[0].Cat.NumCache && typeof asc_series[0].Cat.Formula === "string" && asc_series[0].Cat.Formula.length > 0) { oXVal = new AscFormat.CXVal(); FillCatStr(oXVal, asc_series[0].Cat, true, false); } for(var i = start_index; i < asc_series.length; ++i) { var series = new AscFormat.CScatterSeries(); series.setIdx(i - minus); series.setOrder(i - minus); AscFormat.ApplySpPr(oFirstSpPrPreset, series, i, base_fills, bAccent1Background); if(oXVal) { series.setXVal(oXVal.createDuplicate()); } series.setYVal(new AscFormat.CYVal()); FillValNum(series.yVal, asc_series[i].Val, true, false); if(asc_series[i].TxCache && typeof asc_series[i].TxCache.Formula === "string" && asc_series[i].TxCache.Formula.length > 0) { FillSeriesTx(series, asc_series[i].TxCache, true, false); } chart_type.addSer(series); } } this.recalculateReferences(); } }; CChartSpace.prototype.Write_ToBinary2 = function (w) { w.WriteLong(this.getObjectType()); w.WriteString2(this.Id); }; CChartSpace.prototype.Read_FromBinary2 = function (r) { this.Id = r.GetString2(); }; CChartSpace.prototype.handleUpdateType = function() { if(this.bNoHandleRecalc === true) { return; } this.recalcInfo.recalculateChart = true; this.recalcInfo.recalculateSeriesColors = true; this.recalcInfo.recalculateMarkers = true; this.recalcInfo.recalculateGridLines = true; this.recalcInfo.recalculateDLbls = true; this.recalcInfo.recalculateAxisLabels = true; //this.recalcInfo.dataLbls.length = 0; //this.recalcInfo.axisLabels.length = 0; this.recalcInfo.recalculateAxisVal = true; this.recalcInfo.recalculateAxisTickMark = true; this.recalcInfo.recalculateHiLowLines = true; this.recalcInfo.recalculateUpDownBars = true; this.recalcInfo.recalculateLegend = true; this.recalcInfo.recalculateReferences = true; this.recalcInfo.recalculateBBox = true; this.recalcInfo.recalculateFormulas = true; this.chartObj = null; this.addToRecalculate(); }; CChartSpace.prototype.handleUpdateInternalChart = function() { if(this.bNoHandleRecalc === true) { return; } this.recalcInfo.recalculateChart = true; this.recalcInfo.recalculateSeriesColors = true; this.recalcInfo.recalculateDLbls = true; this.recalcInfo.recalculateAxisLabels = true; this.recalcInfo.recalculateMarkers = true; this.recalcInfo.recalculatePlotAreaBrush = true; this.recalcInfo.recalculatePlotAreaPen = true; this.recalcInfo.recalculateAxisTickMark = true; //this.recalcInfo.dataLbls.length = 0; //this.recalcInfo.axisLabels.length = 0; this.recalcInfo.recalculateAxisVal = true; this.recalcInfo.recalculateLegend = true; this.recalcInfo.recalculateBBox = true; this.chartObj = null; this.addToRecalculate(); }; CChartSpace.prototype.handleUpdateGridlines = function() { this.recalcInfo.recalculateGridLines = true; this.addToRecalculate(); }; CChartSpace.prototype.handleUpdateDataLabels = function() { this.recalcInfo.recalculateDLbls = true; this.addToRecalculate(); }; CChartSpace.prototype.updateChildLabelsTransform = function(posX, posY) { if(this.localTransformText) { this.transformText = this.localTransformText.CreateDublicate(); global_MatrixTransformer.TranslateAppend(this.transformText, posX, posY); this.invertTransformText = global_MatrixTransformer.Invert(this.transformText); } if(this.chart) { if(this.chart.plotArea) { var aCharts = this.chart.plotArea.charts; for(var t = 0; t < aCharts.length; ++t){ var oChart = aCharts[t]; var series = oChart.series; for(var i = 0; i < series.length; ++i) { var ser = series[i]; var pts = AscFormat.getPtsFromSeries(ser); for(var j = 0; j < pts.length; ++j) { if(pts[j].compiledDlb) { pts[j].compiledDlb.updatePosition(posX, posY); } } } } var aAxes = this.chart.plotArea.axId; for(var i = 0; i < aAxes.length; ++i){ var oAxis = aAxes[i]; if(oAxis){ if(oAxis.title){ oAxis.title.updatePosition(posX, posY); } if(oAxis.labels){ oAxis.labels.updatePosition(posX, posY); } } } } if(this.chart.title) { this.chart.title.updatePosition(posX, posY); } if(this.chart.legend) { this.chart.legend.updatePosition(posX, posY); } } }; CChartSpace.prototype.recalcTitles = function() { if(this.chart && this.chart.title) { this.chart.title.recalcInfo.recalculateContent = true; this.chart.title.recalcInfo.recalcTransform = true; this.chart.title.recalcInfo.recalcTransformText = true; } if(this.chart && this.chart.plotArea) { var hor_axis = this.chart.plotArea.getHorizontalAxis(); if(hor_axis && hor_axis.title) { hor_axis.title.recalcInfo.recalculateContent = true; hor_axis.title.recalcInfo.recalcTransform = true; hor_axis.title.recalcInfo.recalcTransformText = true; } var vert_axis = this.chart.plotArea.getVerticalAxis(); if(vert_axis && vert_axis.title) { vert_axis.title.recalcInfo.recalculateContent = true; vert_axis.title.recalcInfo.recalcTransform = true; vert_axis.title.recalcInfo.recalcTransformText = true; } } }; CChartSpace.prototype.recalcTitles2 = function() { if(this.chart && this.chart.title) { this.chart.title.recalcInfo.recalculateContent = true; this.chart.title.recalcInfo.recalcTransform = true; this.chart.title.recalcInfo.recalcTransformText = true; this.chart.title.recalcInfo.recalculateTxBody = true; } if(this.chart && this.chart.plotArea) { var hor_axis = this.chart.plotArea.getHorizontalAxis(); if(hor_axis && hor_axis.title) { hor_axis.title.recalcInfo.recalculateContent = true; hor_axis.title.recalcInfo.recalcTransform = true; hor_axis.title.recalcInfo.recalcTransformText = true; hor_axis.title.recalcInfo.recalculateTxBody = true; } var vert_axis = this.chart.plotArea.getVerticalAxis(); if(vert_axis && vert_axis.title) { vert_axis.title.recalcInfo.recalculateContent = true; vert_axis.title.recalcInfo.recalcTransform = true; vert_axis.title.recalcInfo.recalcTransformText = true; vert_axis.title.recalcInfo.recalculateTxBody = true; } } }; CChartSpace.prototype.Refresh_RecalcData2 = function(pageIndex, object) { if(object && object.getObjectType && object.getObjectType() === AscDFH.historyitem_type_Title && this.selection.title === object) { this.recalcInfo.recalcTitle = object; } else { var bOldRecalculateRef = this.recalcInfo.recalculateReferences; this.setRecalculateInfo(); this.recalcInfo.recalculateReferences = bOldRecalculateRef; } this.addToRecalculate(); }; CChartSpace.prototype.Refresh_RecalcData = function(data) { switch(data.Type) { case AscDFH.historyitem_ChartSpace_SetStyle: { this.handleUpdateStyle(); break; } case AscDFH.historyitem_ChartSpace_SetTxPr: { this.recalcInfo.recalculateChart = true; this.recalcInfo.recalculateLegend = true; this.recalcInfo.recalculateDLbls = true; this.recalcInfo.recalculateAxisVal = true; this.recalcInfo.recalculateAxisCat = true; this.recalcInfo.recalculateAxisLabels = true; this.addToRecalculate(); break; } case AscDFH.historyitem_ChartSpace_SetChart: { this.handleUpdateType(); break; } case AscDFH.historyitem_ShapeSetBDeleted:{ if(!this.bDeleted){ this.handleUpdateType(); } break; } } }; CChartSpace.prototype.getObjectType = function() { return AscDFH.historyitem_type_ChartSpace; }; CChartSpace.prototype.getAllRasterImages = function(images) { if(this.spPr) { this.spPr.checkBlipFillRasterImage(images); } var chart = this.chart; if(chart) { chart.backWall && chart.backWall.spPr && chart.backWall.spPr.checkBlipFillRasterImage(images); chart.floor && chart.floor.spPr && chart.floor.spPr.checkBlipFillRasterImage(images); chart.legend && chart.legend.spPr && chart.legend.spPr.checkBlipFillRasterImage(images); chart.sideWall && chart.sideWall.spPr && chart.sideWall.spPr.checkBlipFillRasterImage(images); chart.title && chart.title.spPr && chart.title.spPr.checkBlipFillRasterImage(images); //plotArea var plot_area = this.chart.plotArea; if(plot_area) { plot_area.spPr && plot_area.spPr.checkBlipFillRasterImage(images); var i; for(i = 0; i < plot_area.axId.length; ++i) { var axis = plot_area.axId[i]; if(axis) { axis.spPr && axis.spPr.checkBlipFillRasterImage(images); axis.title && axis.title && axis.title.spPr && axis.title.spPr.checkBlipFillRasterImage(images); } } for(i = 0; i < plot_area.charts.length; ++i) { plot_area.charts[i].getAllRasterImages(images); } } } }; CChartSpace.prototype.getAllContents = function() { }; CChartSpace.prototype.getAllFonts = function (allFonts) { this.documentGetAllFontNames(allFonts); }; CChartSpace.prototype.documentGetAllFontNames = function(allFonts) { allFonts["+mn-lt"] = 1; allFonts["+mn-ea"] = 1; allFonts["+mn-cs"] = 1; checkTxBodyDefFonts(allFonts, this.txPr); var chart = this.chart, i; if(chart) { for(i = 0; i < chart.pivotFmts.length; ++i) { chart.pivotFmts[i] && checkTxBodyDefFonts(allFonts, chart.pivotFmts[i].txPr); } if(chart.legend) { checkTxBodyDefFonts(allFonts, chart.legend.txPr); for(i = 0; i < chart.legend.legendEntryes.length; ++i) { chart.legend.legendEntryes[i] && checkTxBodyDefFonts(allFonts, chart.legend.legendEntryes[i].txPr); } } if(chart.title) { checkTxBodyDefFonts(allFonts, chart.title.txPr); if(chart.title.tx && chart.title.tx.rich) { checkTxBodyDefFonts(allFonts, chart.title.tx.rich); chart.title.tx.rich.content && chart.title.tx.rich.content.Document_Get_AllFontNames(allFonts); } } var plot_area = chart.plotArea; if(plot_area) { for(i = 0; i < plot_area.charts.length; ++i) { plot_area.charts[i] && plot_area.charts[i].documentCreateFontMap(allFonts);/*TODO надо бы этот метод переименовать чтоб название не вводило в заблуждение*/ } var cur_axis; for(i = 0; i < plot_area.axId.length; ++i) { cur_axis = plot_area.axId[i]; checkTxBodyDefFonts(allFonts, cur_axis.txPr); if(cur_axis.title) { checkTxBodyDefFonts(allFonts, cur_axis.title.txPr); if(cur_axis.title.tx && cur_axis.title.tx.rich) { checkTxBodyDefFonts(allFonts, cur_axis.title.tx.rich); cur_axis.title.tx.rich.content && cur_axis.title.tx.rich.content.Document_Get_AllFontNames(allFonts); } } } } } }; CChartSpace.prototype.documentCreateFontMap = function(allFonts) { if(this.chart) { this.chart.title && this.chart.title.txBody && this.chart.title.txBody.content.Document_CreateFontMap(allFonts); var i, j, k; if(this.chart.legend) { var calc_entryes = this.chart.legend.calcEntryes; for(i = 0; i < calc_entryes.length; ++i) { calc_entryes[i].txBody.content.Document_CreateFontMap(allFonts); } } var axis = this.chart.plotArea.axId, cur_axis; for(i = axis.length-1; i > -1 ; --i) { cur_axis = axis[i]; if(cur_axis) { cur_axis && cur_axis.title && cur_axis.title.txBody && cur_axis.title.txBody.content.Document_CreateFontMap(allFonts); if(cur_axis.labels) { for(j = cur_axis.labels.aLabels.length - 1; j > -1; --j) { cur_axis.labels.aLabels[j] && cur_axis.labels.aLabels[j].txBody && cur_axis.labels.aLabels[j].txBody.content.Document_CreateFontMap(allFonts); } } } } var series, pts; for(i = this.chart.plotArea.charts.length-1; i > -1; --i) { series = this.chart.plotArea.charts[i].series; for(j = series.length -1; j > -1; --j) { pts = AscFormat.getPtsFromSeries(series[i]); if(Array.isArray(pts)) { for(k = pts.length - 1; k > -1; --k) { pts[k].compiledDlb && pts[k].compiledDlb.txBody && pts[k].compiledDlb.txBody.content.Document_CreateFontMap(allFonts); } } } } } }; CChartSpace.prototype.setThemeOverride = function(pr) { History.Add(new CChangesDrawingsObject(this, AscDFH.historyitem_ChartSpace_SetThemeOverride, this.themeOverride, pr)); this.themeOverride = pr; }; CChartSpace.prototype.setParent = function (parent) { History.Add(new CChangesDrawingsObject(this, AscDFH.historyitem_ChartSpace_SetParent, this.parent, parent )); this.parent = parent; }; CChartSpace.prototype.setChart = function(chart) { History.Add(new CChangesDrawingsObject(this, AscDFH.historyitem_ChartSpace_SetChart, this.chart, chart)); this.chart = chart; if(chart) { chart.setParent(this); } }; CChartSpace.prototype.setClrMapOvr = function(clrMapOvr) { History.Add(new CChangesDrawingsObject(this, AscDFH.historyitem_ChartSpace_SetClrMapOvr, this.clrMapOvr, clrMapOvr)); this.clrMapOvr = clrMapOvr; }; CChartSpace.prototype.setDate1904 = function(date1904) { History.Add(new CChangesDrawingsBool(this, AscDFH.historyitem_ChartSpace_SetDate1904, this.date1904, date1904)); this.date1904 = date1904; }; CChartSpace.prototype.setExternalData = function(externalData) { History.Add(new CChangesDrawingsObject(this, AscDFH.historyitem_ChartSpace_SetExternalData, this.externalData, externalData)); this.externalData = externalData; }; CChartSpace.prototype.setLang = function(lang) { History.Add(new CChangesDrawingsString(this, AscDFH.historyitem_ChartSpace_SetLang, this.lang, lang)); this.lang = lang; }; CChartSpace.prototype.setPivotSource = function(pivotSource) { History.Add(new CChangesDrawingsObject(this, AscDFH.historyitem_ChartSpace_SetPivotSource, this.pivotSource, pivotSource)); this.pivotSource = pivotSource; }; CChartSpace.prototype.setPrintSettings = function(printSettings) { History.Add(new CChangesDrawingsObject(this, AscDFH.historyitem_ChartSpace_SetPrintSettings, this.printSettings, printSettings)); this.printSettings = printSettings; }; CChartSpace.prototype.setProtection = function(protection) { History.Add(new CChangesDrawingsObject(this, AscDFH.historyitem_ChartSpace_SetProtection, this.protection, protection)); this.protection = protection; }; CChartSpace.prototype.setRoundedCorners = function(roundedCorners) { History.Add(new CChangesDrawingsBool(this, AscDFH.historyitem_ChartSpace_SetRoundedCorners, this.roundedCorners, roundedCorners)); this.roundedCorners = roundedCorners; }; CChartSpace.prototype.setSpPr = function(spPr) { History.Add(new CChangesDrawingsObject(this, AscDFH.historyitem_ChartSpace_SetSpPr, this.spPr, spPr)); this.spPr = spPr; }; CChartSpace.prototype.setStyle = function(style) { History.Add(new CChangesDrawingsLong(this, AscDFH.historyitem_ChartSpace_SetStyle, this.style, style)); this.style = style; this.handleUpdateStyle(); }; CChartSpace.prototype.setTxPr = function(txPr) { History.Add(new CChangesDrawingsObject(this, AscDFH.historyitem_ChartSpace_SetTxPr, this.txPr, txPr)); this.txPr = txPr; if(txPr) { txPr.setParent(this); } }; CChartSpace.prototype.setUserShapes = function(userShapes) { History.Add(new CChangesDrawingsString(this, AscDFH.historyitem_ChartSpace_SetUserShapes, this.userShapes, userShapes)); this.userShapes = userShapes; }; CChartSpace.prototype.getTransformMatrix = function() { return this.transform; }; CChartSpace.prototype.canRotate = function() { return false; }; CChartSpace.prototype.drawAdjustments = function() {}; CChartSpace.prototype.isChart = function() { return true; }; CChartSpace.prototype.isShape = function() { return false; }; CChartSpace.prototype.isImage = function() { return false; }; CChartSpace.prototype.isGroup = function() { return false; }; CChartSpace.prototype.isPlaceholder = CShape.prototype.isPlaceholder; CChartSpace.prototype.setGroup = function (group) { History.Add(new CChangesDrawingsObject(this, AscDFH.historyitem_ChartSpace_SetGroup, this.group, group )); this.group = group; }; CChartSpace.prototype.getBase64Img = CShape.prototype.getBase64Img; CChartSpace.prototype.getRangeObjectStr = function() { if(this.recalcInfo.recalculateBBox) { this.recalculateBBox(); this.recalcInfo.recalculateBBox = false; } var ret = {range: null, bVert: null}; if(this.bbox && this.bbox.seriesBBox) { var r1 = this.bbox.seriesBBox.r1, r2 = this.bbox.seriesBBox.r2, c1 = this.bbox.seriesBBox.c1, c2 = this.bbox.seriesBBox.c2; ret.bVert = this.bbox.seriesBBox.bVert; if(this.bbox.seriesBBox.bVert) { if(this.bbox.catBBox) { if(r1 > 0) { --r1; } } if(this.bbox.serBBox) { if(c1 > 0) { --c1; } } } else { if(this.bbox.catBBox) { if(c1 > 0) { --c1; } } if(this.bbox.serBBox) { if(r1 > 0) { --r1; } } } var startCell = new CellAddress(r1, c1, 0); var endCell = new CellAddress(r2, c2, 0); var sStartCellId, sEndCellId; if (this.bbox.worksheet) { sStartCellId = startCell.getIDAbsolute(); sEndCellId = endCell.getIDAbsolute(); ret.range = parserHelp.get3DRef(this.bbox.worksheet.sName, sStartCellId === sEndCellId ? sStartCellId : sStartCellId + ':' + sEndCellId); } } return ret; }; CChartSpace.prototype.recalculateBBox = function() { this.bbox = null; this.seriesBBoxes = []; this.seriesTitlesBBoxes = []; this.catTitlesBBoxes = []; var series_bboxes = [], cat_bboxes = [], ser_titles_bboxes = []; var series_sheet, cur_bbox, parsed_formulas; if(this.chart && this.chart.plotArea && this.chart.plotArea && this.worksheet) { var series = []; var aCharts = this.chart.plotArea.charts; for(var i = 0; i < aCharts.length; ++i){ series = series.concat(aCharts[i].series); } series.sort(function(a, b){ return a.idx - b.idx; }); if(Array.isArray(series) && series.length > 0) { var series_title_f = [], cat_title_f, series_f = [], i, range1; var ref; var b_vert/*флаг означает, что значения в серии идут по горизонтали, а сами серии по вертикали сверху вниз*/ , b_titles_vert; var first_series_sheet; for(i = 0; i < series.length; ++i) { var numRef = null; if(series[i].val) numRef = series[i].val.numRef; else if(series[i].yVal) numRef = series[i].yVal.numRef; if(numRef) { parsed_formulas = this.parseChartFormula(numRef.f); if(parsed_formulas && parsed_formulas.length > 0 && parsed_formulas[0].worksheet) { series_bboxes = series_bboxes.concat(parsed_formulas); if(series_f !== null && parsed_formulas.length === 1) { series_sheet = parsed_formulas[0].worksheet; if(!first_series_sheet) first_series_sheet = series_sheet; if(series_sheet !== first_series_sheet) series_f = null; if(parsed_formulas[0].bbox) { cur_bbox = parsed_formulas[0].bbox; if(cur_bbox.r1 !== cur_bbox.r2 && cur_bbox.c1 !== cur_bbox.c2) series_f = null; if(series_f && series_f.length > 0) { if(!AscFormat.isRealBool(b_vert)) { if(series_f[0].c1 === cur_bbox.c1 && series_f[0].c2 === cur_bbox.c2) { b_vert = true; } else if(series_f[0].r1 === cur_bbox.r1 && series_f[0].r2 === cur_bbox.r2) { b_vert = false; } else { series_f = null; } } else { if(b_vert) { if(!(series_f[0].c1 === cur_bbox.c1 && series_f[0].c2 === cur_bbox.c2)) { series_f = null; } } else { if(!(series_f[0].r1 === cur_bbox.r1 && series_f[0].r2 === cur_bbox.r2)) { series_f = null; } } } if(series_f) { if(b_vert ) { if(cur_bbox.r1 - series_f[series_f.length-1].r1 !== 1) series_f = null; } else { if(cur_bbox.c1 - series_f[series_f.length-1].c1 !== 1) series_f = null; } } } if(series_f !== null) series_f.push(cur_bbox); } else series_f = null; } } } else series_f = null; if(series[i].tx && series[i].tx.strRef) { parsed_formulas = this.parseChartFormula(series[i].tx.strRef.f); if(parsed_formulas && parsed_formulas.length > 0 && parsed_formulas[0].worksheet) { ser_titles_bboxes = ser_titles_bboxes.concat(parsed_formulas); } if(series_title_f !== null) { if(!parsed_formulas || parsed_formulas.length !== 1 || !parsed_formulas[0].worksheet) { series_title_f = null; continue; } var series_cat_sheet = parsed_formulas[0].worksheet; if(series_cat_sheet !== first_series_sheet) { series_title_f = null; continue; } cur_bbox = parsed_formulas[0].bbox; if(cur_bbox) { if(cur_bbox.r1 !== cur_bbox.r2 || cur_bbox.c1 !== cur_bbox.c2) { series_title_f = null; continue; } if(!AscFormat.isRealBool(b_titles_vert)) { if(series_title_f.length > 0) { if( cur_bbox.r1 - series_title_f[0].r1 === 1) b_titles_vert = true; else if(cur_bbox.c1 - series_title_f[0].c1 === 1) b_titles_vert = false; else { series_title_f = null; continue; } } } else { if(b_titles_vert) { if( cur_bbox.r1 - series_title_f[series_title_f.length-1].r1 !== 1) { series_title_f = null; continue; } } else { if( cur_bbox.c1 - series_title_f[series_title_f.length-1].c1 !== 1) { series_title_f = null; continue; } } } series_title_f.push(cur_bbox); } else { series_title_f = null; continue; } } } else { series_title_f = null; } } if(series[0].cat) { if(series[0].cat.strRef) { ref = series[0].cat.strRef; } else if(series[0].cat.numRef) { ref = series[0].cat.numRef; } } else if(series[0].xVal) { if(series[0].xVal.strRef) { ref = series[0].xVal.strRef; } else if(series[0].xVal.numRef) { ref = series[0].xVal.numRef; } } if(ref) { parsed_formulas = this.parseChartFormula(ref.f); if(parsed_formulas && parsed_formulas.length === 1 && parsed_formulas[0].worksheet) { cat_bboxes = cat_bboxes.concat(parsed_formulas); if(parsed_formulas.length === 1) { var cat_title_sheet = parsed_formulas[0].worksheet; if(cat_title_sheet === first_series_sheet) { if(parsed_formulas[0].bbox) { cat_title_f = parsed_formulas[0].bbox; } } } } } if(series_f !== null && series_f.length === 1) { if(series_f[0].r1 === series_f[0].r2 && series_f[0].c1 !== series_f[0].c2) { b_vert = true; } else if(series_f[0].c1 === series_f[0].c2 && series_f[0].r1 !== series_f[0].r2) { b_vert = false; } if(!AscFormat.isRealBool(b_vert) && Array.isArray(series_title_f) ) { if(series_f[0].r1 === series_f[0].r2 && series_title_f[0].r1 === series_f[0].r1) { b_vert = true; } else if(series_f[0].c1 === series_f[0].c2 && series_title_f[0].c1 === series_f[0].c1) { b_vert = false; } } if(!AscFormat.isRealBool(b_vert)) { if(cat_title_f) { if(series_f[0].r1 === series_f[0].r2 && cat_title_f.c1 === series_f[0].c1 && cat_title_f.c2 === series_f[0].c2) { b_vert = true; } else if(series_f[0].c1 === series_f[0].c2 && cat_title_f.r1 === series_f[0].r1 && cat_title_f.r2 === series_f[0].r2) { b_vert = false; } } if(!AscFormat.isRealBool(b_vert)) { b_vert = true; } } } if(series_f !== null && series_f.length > 0) { this.bbox = { seriesBBox: null, catBBox: null, serBBox: null, worksheet: first_series_sheet }; this.bbox.seriesBBox = { r1: series_f[0].r1, r2: series_f[series_f.length-1].r2, c1: series_f[0].c1, c2: series_f[series_f.length-1].c2, bVert: b_vert }; this.seriesBBoxes.push(new BBoxInfo(first_series_sheet, this.bbox.seriesBBox)); if(cat_title_f) { if(b_vert) { if(cat_title_f.c1 !== this.bbox.seriesBBox.c1 || cat_title_f.c2 !== this.bbox.seriesBBox.c2 || cat_title_f.r1 !== cat_title_f.r1) { cat_title_f = null; } } else { if(cat_title_f.c1 !== cat_title_f.c2 || cat_title_f.r1 !== this.bbox.seriesBBox.r1 || cat_title_f.r2 !== this.bbox.seriesBBox.r2) { cat_title_f = null; } } this.bbox.catBBox = cat_title_f; if(cat_title_f) { this.catTitlesBBoxes.push(new BBoxInfo(first_series_sheet, cat_title_f)); } } if(Array.isArray(series_title_f)) { this.bbox.serBBox = { r1: series_title_f[0].r1, r2: series_title_f[series_title_f.length-1].r2, c1: series_title_f[0].c1, c2: series_title_f[series_title_f.length-1].c2 }; this.seriesTitlesBBoxes.push(new BBoxInfo(first_series_sheet, this.bbox.serBBox)); } } else { for(i = 0; i < series_bboxes.length; ++i) { this.seriesBBoxes.push(new BBoxInfo(series_bboxes[i].worksheet, series_bboxes[i].bbox)); } for(i = 0; i < cat_bboxes.length; ++i) { this.catTitlesBBoxes.push(new BBoxInfo(cat_bboxes[i].worksheet, cat_bboxes[i].bbox)); } for(i = 0; i < ser_titles_bboxes.length; ++i) { this.seriesTitlesBBoxes.push(new BBoxInfo(ser_titles_bboxes[i].worksheet, ser_titles_bboxes[i].bbox)); } } } } }; CChartSpace.prototype.getCommonBBox = function() { if(this.recalcInfo.recalculateBBox) { this.recalculateBBox(); this.recalcInfo.recalculateBBox = false; } var oRet = null; if(this.bbox && this.bbox.seriesBBox && AscFormat.isRealBool(this.bbox.seriesBBox.bVert)) { oRet = {r1: this.bbox.seriesBBox.r1, r2: this.bbox.seriesBBox.r2, c1: this.bbox.seriesBBox.c1, c2: this.bbox.seriesBBox.c2}; if(this.bbox.seriesBBox.bVert) { if(this.bbox.catBBox ) { if(this.bbox.catBBox.r1 === this.bbox.catBBox.r2 && this.bbox.catBBox.r1 === this.bbox.seriesBBox.r1 - 1) { --oRet.r1; } else { oRet = null; } } if(oRet) { if(this.bbox.serBBox) { if(this.bbox.serBBox.c1 === this.bbox.serBBox.c2 && this.bbox.serBBox.c1 === this.bbox.seriesBBox.c1 - 1) { --oRet.c1; } else { oRet = null; } } } } else { if(this.bbox.catBBox ) { if(this.bbox.catBBox.c1 === this.bbox.catBBox.c2 && this.bbox.catBBox.c1 === this.bbox.seriesBBox.c1 - 1) { --oRet.c1; } else { oRet = null; } } if(oRet) { if(this.bbox.serBBox) { if(this.bbox.serBBox.r1 === this.bbox.serBBox.r2 && this.bbox.serBBox.r1 === this.bbox.seriesBBox.r1 - 1) { --oRet.r1; } else { oRet = null; } } } } } return oRet; }; CChartSpace.prototype.checkValByNumRef = function(workbook, ser, val, bVertical) { if(val && val.numRef && typeof val.numRef.f === "string"/*(!val.numRef.numCache || val.numRef.numCache.pts.length === 0)*/) { var aParsedRef = this.parseChartFormula(val.numRef.f); var num_cache; if(!val.numRef.numCache ) { num_cache = new AscFormat.CNumLit(); num_cache.setFormatCode("General"); } else { num_cache = val.numRef.numCache; removePtsFromLit(num_cache); } var lit_format_code = typeof num_cache.formatCode === "string" && num_cache.formatCode.length > 0 ? num_cache.formatCode : "General"; var pt_index = 0, i, j, cell, pt, hidden = true, row_hidden, col_hidden, nPtCount, t; for(i = 0; i < aParsedRef.length; ++i) { var oCurRef = aParsedRef[i]; var source_worksheet = oCurRef.worksheet; if(source_worksheet) { var range = oCurRef.bbox; var nLastNoEmptyIndex = null, dLastNoEmptyVal = null, aSpanPoints = [], nSpliceIndex = null; if(range.r1 === range.r2 || bVertical === true) { row_hidden = source_worksheet.getRowHidden(range.r1); for(j = range.c1; j <= range.c2; ++j) { if(!row_hidden && !source_worksheet.getColHidden(j) || (this.displayHidden === true)) { cell = source_worksheet.getCell3(range.r1, j); var sCellValue = cell.getValue(); var value = cell.getNumberValue(); if(!AscFormat.isRealNumber(value) && (!AscFormat.isRealNumber(this.displayEmptyCellsAs) || this.displayEmptyCellsAs === 1)){ var sVal = cell.getValueForEdit(); if((typeof sVal === "string") && sVal.length > 0){ value = 0; } } if(AscFormat.isRealNumber(value)) { hidden = false; pt = new AscFormat.CNumericPoint(); pt.setIdx(pt_index); pt.setVal(value); if(cell.getNumFormatStr() !== lit_format_code) { pt.setFormatCode(cell.getNumFormatStr()) } num_cache.addPt(pt); if(aSpanPoints.length > 0 ) { if(AscFormat.isRealNumber(nLastNoEmptyIndex)) { var oStartPoint = num_cache.getPtByIndex(nLastNoEmptyIndex); for(t = 0; t < aSpanPoints.length; ++t) { aSpanPoints[t].val = oStartPoint.val + ((pt.val - oStartPoint.val)/(aSpanPoints.length + 1))*(t+1); num_cache.pts.splice(nSpliceIndex + t, 0, aSpanPoints[t]); } } aSpanPoints.length = 0; } nLastNoEmptyIndex = pt_index; nSpliceIndex = num_cache.pts.length; dLastNoEmptyVal = pt.val; } else { if(AscFormat.isRealNumber(this.displayEmptyCellsAs) && this.displayEmptyCellsAs !== 1) { if(this.displayEmptyCellsAs === 2 || ((typeof sCellValue === "string") && sCellValue.length > 0)) { pt = new AscFormat.CNumericPoint(); pt.setIdx(pt_index); pt.setVal(0); num_cache.addPt(pt); if(aSpanPoints.length > 0 ) { if(AscFormat.isRealNumber(nLastNoEmptyIndex)) { var oStartPoint = num_cache.getPtByIndex(nLastNoEmptyIndex); for(t = 0; t < aSpanPoints.length; ++t) { aSpanPoints[t].val = oStartPoint.val + ((pt.val - oStartPoint.val)/(aSpanPoints.length + 1))*(t+1); num_cache.pts.splice(nSpliceIndex + t, 0, aSpanPoints[t]); } } aSpanPoints.length = 0; } nLastNoEmptyIndex = pt_index; nSpliceIndex = num_cache.pts.length; dLastNoEmptyVal = pt.val; } else if(this.displayEmptyCellsAs === 0 && ser.getObjectType() === AscDFH.historyitem_type_LineSeries) { pt = new AscFormat.CNumericPoint(); pt.setIdx(pt_index); pt.setVal(0); aSpanPoints.push(pt); } } } } pt_index++; } } else { col_hidden = source_worksheet.getColHidden(range.c1); for(j = range.r1; j <= range.r2; ++j) { if(!col_hidden && !source_worksheet.getRowHidden(j) || (this.displayHidden === true)) { cell = source_worksheet.getCell3(j, range.c1); var value = cell.getNumberValue(); var sCellValue = cell.getValue(); if(!AscFormat.isRealNumber(value) && !AscFormat.isRealNumber(this.displayEmptyCellsAs)){ var sVal = cell.getValueForEdit(); if((typeof sVal === "string") && sVal.length > 0){ value = 0; } } if(AscFormat.isRealNumber(value)) { hidden = false; pt = new AscFormat.CNumericPoint(); pt.setIdx(pt_index); pt.setVal(value); if(cell.getNumFormatStr() !== lit_format_code) { pt.setFormatCode(cell.getNumFormatStr()); } num_cache.addPt(pt); } else { if(AscFormat.isRealNumber(this.displayEmptyCellsAs) && this.displayEmptyCellsAs !== 1) { if(this.displayEmptyCellsAs === 2 || ((typeof sCellValue === "string") && sCellValue.length > 0)) { pt = new AscFormat.CNumericPoint(); pt.setIdx(pt_index); pt.setVal(0); num_cache.addPt(pt); if(aSpanPoints.length > 0 ) { if(AscFormat.isRealNumber(nLastNoEmptyIndex)) { var oStartPoint = num_cache.getPtByIndex(nLastNoEmptyIndex); for(t = 0; t < aSpanPoints.length; ++t) { aSpanPoints[t].val = oStartPoint.val + ((pt.val - oStartPoint.val)/(aSpanPoints.length + 1))*(t+1); num_cache.pts.splice(nSpliceIndex + t, 0, aSpanPoints[t]); } } aSpanPoints.length = 0; } nLastNoEmptyIndex = pt_index; nSpliceIndex = num_cache.pts.length; dLastNoEmptyVal = pt.val; } else if(this.displayEmptyCellsAs === 0 && ser.getObjectType() === AscDFH.historyitem_type_LineSeries) { pt = new AscFormat.CNumericPoint(); pt.setIdx(pt_index); pt.setVal(0); aSpanPoints.push(pt); } } } } pt_index++; } } } else{ pt_index = 0; var fCollectArray = function(oRef, oNumCache){ if(Array.isArray(oRef)){ for(var i = 0; i < oRef.length; ++i){ if(Array.isArray(oRef[i])){ fCollectArray(oRef[i], oNumCache); } else{ cell = source_worksheet.getCell3(j, range.c1); var value = cell.getNumberValue(); if(AscFormat.isRealNumber(value)) { hidden = false; pt = new AscFormat.CNumericPoint(); pt.setIdx(pt_index); pt.setVal(value); if(cell.getNumFormatStr() !== lit_format_code) { pt.setFormatCode(cell.getNumFormatStr()); } num_cache.addPt(pt); } } } } } for(j = 0; j < oCurRef.length; ++j){ for(var k = 0; k < oCurRef[j].length; ++k){ } } } } num_cache.setPtCount(pt_index); val.numRef.setNumCache(num_cache); if(!(val instanceof AscFormat.CCat)) { ser.isHidden = hidden; ser.isHiddenForLegend = hidden; } } }; CChartSpace.prototype.checkCatByNumRef = function(oThis, ser, cat, bVertical) { if(cat && cat.strRef && typeof cat.strRef.f === "string" /*(!cat.strRef.strCache || cat.strRef.strCache.pt.length === 0)*/) { var aParsedRef = this.parseChartFormula(cat.strRef.f); var str_cache = new AscFormat.CStrCache(); //str_cache.setFormatCode("General"); var pt_index = 0, i, j, cell, pt, value_width_format, row_hidden, col_hidden; var fParseTableDataString = function(oRef, oCache){ if(Array.isArray(oRef)){ for(var i = 0; i < oRef.length; ++i){ if(Array.isArray(oRef[i])){ fParseTableDataString(oRef, oCache); } else{ pt = new AscFormat.CStringPoint(); pt.setIdx(pt_index); pt.setVal(oRef[i].value); str_cache.addPt(pt); ++pt_index; } } } }; for(i = 0; i < aParsedRef.length; ++i) { var oCurRef = aParsedRef[i]; var source_worksheet = oCurRef.worksheet; if(source_worksheet) { var range = oCurRef.bbox; if(range.r1 === range.r2 || bVertical === true) { row_hidden = source_worksheet.getRowHidden(range.r1); for(j = range.c1; j <= range.c2; ++j) { if(!row_hidden && !source_worksheet.getColHidden(j)) { cell = source_worksheet.getCell3(range.r1, j); value_width_format = cell.getValueWithFormat(); if(typeof value_width_format === "string" && value_width_format.length > 0) { pt = new AscFormat.CStringPoint(); pt.setIdx(pt_index); pt.setVal(value_width_format); str_cache.addPt(pt); //addPointToMap(oThis.pointsMap, source_worksheet, range.r1, j, pt); } } pt_index++; } } else { col_hidden = source_worksheet.getColHidden(range.c1); for(j = range.r1; j <= range.r2; ++j) { if(!col_hidden && !source_worksheet.getRowHidden(j)) { cell = source_worksheet.getCell3(j, range.c1); value_width_format = cell.getValueWithFormat(); if(typeof value_width_format === "string" && value_width_format.length > 0) { pt = new AscFormat.CStringPoint(); pt.setIdx(pt_index); pt.setVal(cell.getValueWithFormat()); str_cache.addPt(pt); //addPointToMap(oThis.pointsMap, source_worksheet, j, range.c1, pt); } } pt_index++; } } } else{ fParseTableDataString(oCurRef); } } str_cache.setPtCount(pt_index); cat.strRef.setStrCache(str_cache); } }; CChartSpace.prototype.recalculateReferences = function() { var worksheet = this.worksheet; //this.pointsMap = {}; if(!worksheet) return; if(this.recalcInfo.recalculateBBox) { this.recalculateBBox(); this.recalcInfo.recalculateBBox = false; } var charts, series, i, j, ser; charts = this.chart.plotArea.charts; var bVert = undefined; if(this.bbox && this.bbox.seriesBBox && AscFormat.isRealBool(this.bbox.seriesBBox.bVert)) { bVert = this.bbox.seriesBBox.bVert; } for(i = 0; i < charts.length; ++i) { series = charts[i].series; var bHaveHidden = false, bHaveNoHidden = false; var bCheckFormatCode = false; if(charts[i].getObjectType() !== AscDFH.historyitem_type_ScatterChart) { for(j = 0; j < series.length; ++j) { ser = series[j]; //val this.checkValByNumRef(this.worksheet.workbook, ser, ser.val); //cat this.checkValByNumRef(this.worksheet.workbook, ser, ser.cat, bVert); this.checkCatByNumRef(this, ser, ser.cat, bVert); //tx this.checkCatByNumRef(this, ser, ser.tx, AscFormat.isRealBool(bVert) ? !bVert : undefined); if(ser.isHidden) { bHaveHidden = true; } else { bHaveNoHidden = true; if(!bCheckFormatCode && !((charts[i].getObjectType() === AscDFH.historyitem_type_BarChart && charts[i].grouping === AscFormat.BAR_GROUPING_PERCENT_STACKED) || (charts[i].getObjectType() !== AscDFH.historyitem_type_BarChart && charts[i].grouping === AscFormat.GROUPING_PERCENT_STACKED))){ bCheckFormatCode = true; var aAxId = charts[i].axId; if(aAxId){ for(var s = 0; s < aAxId.length; ++s){ if(aAxId[s].getObjectType() === AscDFH.historyitem_type_ValAx){ if(aAxId[s].numFmt && aAxId[s].numFmt.sourceLinked){ var aPoints = AscFormat.getPtsFromSeries(ser); if(aPoints[0] && typeof aPoints[0].formatCode === "string" && aPoints[0].formatCode.length > 0){ aAxId[s].numFmt.setFormatCode(aPoints[0].formatCode); } else{ aAxId[s].numFmt.setFormatCode("General"); } } } } } } } } } else { for(j = 0; j < series.length; ++j) { ser = series[j]; this.checkValByNumRef(this.worksheet.workbook, ser, ser.xVal, bVert); this.checkValByNumRef(this.worksheet.workbook, ser, ser.yVal); this.checkCatByNumRef(this, ser, ser.tx, AscFormat.isRealBool(bVert) ? !bVert : undefined); if(ser.isHidden) { bHaveHidden = true; } else { bHaveNoHidden = true; if(!bCheckFormatCode){ bCheckFormatCode = true; var aAxId = charts[i].axId; if(aAxId){ for(var s = 0; s < aAxId.length; ++s){ if(aAxId[s].getObjectType() === AscDFH.historyitem_type_ValAx){ if((aAxId[s].axPos === AscFormat.AX_POS_L || aAxId[s].axPos === AscFormat.AX_POS_R) && aAxId[s].numFmt && aAxId[s].numFmt.sourceLinked){ var aPoints = AscFormat.getPtsFromSeries(ser); if(aPoints[0] && typeof aPoints[0].formatCode === "string" && aPoints[0].formatCode.length > 0){ aAxId[s].numFmt.setFormatCode(aPoints[0].formatCode); } else{ aAxId[s].numFmt.setFormatCode("General"); } } } } } } } } } // if(bHaveHidden && bHaveNoHidden) // { // for(j = 0; j < series.length; ++j) // { // series[j].isHidden = false; // } // } } }; CChartSpace.prototype.checkEmptySeries = function() { var chart_type = this.chart.plotArea.charts[0]; var series = chart_type.series; var checkEmptyVal = function(val) { if(val.numRef) { if(!val.numRef.numCache) return true; if(val.numRef.numCache.pts.length === 0) return true; } else if(val.numLit) { if(val.numLit.pts.length === 0) return true; } else { return true; } return false; }; var nChartType = chart_type.getObjectType(); var nSeriesLength = (nChartType === AscDFH.historyitem_type_PieChart || nChartType === AscDFH.historyitem_type_DoughnutChart) ? 1 : series.length; for(var i = 0; i < nSeriesLength; ++i) { var ser = series[i]; if(ser.val) { if(!checkEmptyVal(ser.val)) return false; } if(ser.yVal) { if(!checkEmptyVal(ser.yVal)) return false; } } return true; }; CChartSpace.prototype.getNeedReflect = function() { if(!this.chartObj) { this.chartObj = new AscFormat.CChartsDrawer(); } return this.chartObj.calculatePositionLabelsCatAxFromAngle(this); }; CChartSpace.prototype.isChart3D = function(oChart){ var oOldFirstChart = this.chart.plotArea.charts[0]; this.chart.plotArea.charts[0] = oChart; var ret = AscFormat.CChartsDrawer.prototype._isSwitchCurrent3DChart(this); this.chart.plotArea.charts[0] = oOldFirstChart; return ret; }; CChartSpace.prototype.getAxisCrossType = function(oAxis){ if(oAxis.getObjectType() === AscDFH.historyitem_type_ValAx){ return AscFormat.CROSS_BETWEEN_MID_CAT; } var oCrossAxis = oAxis.crossAx; if(oCrossAxis && oCrossAxis.getObjectType() === AscDFH.historyitem_type_ValAx){ var oChart = this.chart.plotArea.getChartsForAxis(oCrossAxis)[0]; if(oChart){ var nChartType = oChart.getObjectType(); if(nChartType === AscDFH.historyitem_type_ScatterChart){ return null; } else if(nChartType !== AscDFH.historyitem_type_BarChart && (nChartType !== AscDFH.historyitem_type_PieChart && nChartType !== AscDFH.historyitem_type_DoughnutChart) || (nChartType === AscDFH.historyitem_type_BarChart && oChart.barDir !== AscFormat.BAR_DIR_BAR)){ if(oCrossAxis){ if(this.isChart3D(oChart)){ if(nChartType === AscDFH.historyitem_type_AreaChart || nChartType === AscDFH.historyitem_type_SurfaceChart ){ return AscFormat.isRealNumber(oCrossAxis.crossBetween) ? oCrossAxis.crossBetween : AscFormat.CROSS_BETWEEN_MID_CAT; } else if(nChartType === AscDFH.historyitem_type_LineChart){ return AscFormat.isRealNumber(oCrossAxis.crossBetween) ? oCrossAxis.crossBetween : AscFormat.CROSS_BETWEEN_BETWEEN; } else{ return AscFormat.CROSS_BETWEEN_BETWEEN; } } else{ return AscFormat.isRealNumber(oCrossAxis.crossBetween) ? oCrossAxis.crossBetween : ((nChartType === AscDFH.historyitem_type_AreaChart|| nChartType === AscDFH.historyitem_type_SurfaceChart ) ? AscFormat.CROSS_BETWEEN_MID_CAT : AscFormat.CROSS_BETWEEN_BETWEEN); } } } else if(nChartType === AscDFH.historyitem_type_BarChart && oChart.barDir === AscFormat.BAR_DIR_BAR){ return AscFormat.isRealNumber(oCrossAxis.crossBetween) && !this.isChart3D(oChart) ? oCrossAxis.crossBetween : AscFormat.CROSS_BETWEEN_BETWEEN; } } } switch(oAxis.getObjectType()){ case AscDFH.historyitem_type_ValAx:{ return AscFormat.CROSS_BETWEEN_MID_CAT; } case AscDFH.historyitem_type_CatAx: case AscDFH.historyitem_type_DateAx:{ return AscFormat.CROSS_BETWEEN_BETWEEN; } default:{ return AscFormat.CROSS_BETWEEN_BETWEEN; } } return AscFormat.CROSS_BETWEEN_BETWEEN; }; CChartSpace.prototype.getValAxisCrossType = function() { if(this.chart && this.chart.plotArea && this.chart.plotArea.charts[0]){ var chartType = this.chart.plotArea.charts[0].getObjectType(); var valAx = this.chart.plotArea.valAx; if(chartType === AscDFH.historyitem_type_ScatterChart){ return null; } else if(chartType !== AscDFH.historyitem_type_BarChart && (chartType !== AscDFH.historyitem_type_PieChart && chartType !== AscDFH.historyitem_type_DoughnutChart) || (chartType === AscDFH.historyitem_type_BarChart && this.chart.plotArea.charts[0].barDir !== AscFormat.BAR_DIR_BAR)){ if(valAx){ if(AscFormat.CChartsDrawer.prototype._isSwitchCurrent3DChart(this)){ if(chartType === AscDFH.historyitem_type_AreaChart || chartType === AscDFH.historyitem_type_SurfaceChart ){ return AscFormat.isRealNumber(valAx.crossBetween) ? valAx.crossBetween : AscFormat.CROSS_BETWEEN_MID_CAT; } else if(chartType === AscDFH.historyitem_type_LineChart){ return AscFormat.isRealNumber(valAx.crossBetween) ? valAx.crossBetween : AscFormat.CROSS_BETWEEN_BETWEEN; } else{ return AscFormat.CROSS_BETWEEN_BETWEEN; } } else{ return AscFormat.isRealNumber(valAx.crossBetween) ? valAx.crossBetween : ((chartType === AscDFH.historyitem_type_AreaChart|| chartType === AscDFH.historyitem_type_SurfaceChart ) ? AscFormat.CROSS_BETWEEN_MID_CAT : AscFormat.CROSS_BETWEEN_BETWEEN); } } } else if(chartType === AscDFH.historyitem_type_BarChart && this.chart.plotArea.charts[0].barDir === AscFormat.BAR_DIR_BAR){ if(valAx){ return AscFormat.isRealNumber(valAx.crossBetween) && !AscFormat.CChartsDrawer.prototype._isSwitchCurrent3DChart(this) ? valAx.crossBetween : AscFormat.CROSS_BETWEEN_BETWEEN; } } } return null; }; CChartSpace.prototype.calculatePosByLayout = function(fPos, nLayoutMode, fLayoutValue, fSize, fChartSize){ if(!AscFormat.isRealNumber(fLayoutValue)){ return fPos; } var fRetPos = 0; if(nLayoutMode === AscFormat.LAYOUT_MODE_EDGE){ fRetPos = fChartSize*fLayoutValue; } else{ fRetPos = fPos + fChartSize*fLayoutValue; } if(fRetPos < 0){ fRetPos = 0; } return fRetPos; }; CChartSpace.prototype.calculateSizeByLayout = function(fPos, fChartSize, fLayoutSize, fSizeMode ){ if(!AscFormat.isRealNumber(fLayoutSize)){ return -1; } var fRetSize = Math.min(fChartSize*fLayoutSize, fChartSize); if(fSizeMode === AscFormat.LAYOUT_MODE_EDGE){ fRetSize = fRetSize - fPos; } return fRetSize; }; CChartSpace.prototype.calculateLabelsPositions = function(b_recalc_labels, b_recalc_legend) { var layout; for(var i = 0; i < this.recalcInfo.dataLbls.length; ++i) { var series = this.getAllSeries(); if(this.recalcInfo.dataLbls[i].series && this.recalcInfo.dataLbls[i].pt) { var ser_idx = this.recalcInfo.dataLbls[i].series.idx; //сделаем проверку лежит ли серия с индексом this.recalcInfo.dataLbls[i].series.idx в сериях первой диаграммы for(var j = 0; j < series.length; ++j) { if(series[j].idx === this.recalcInfo.dataLbls[i].series.idx) { var bLayout = AscCommon.isRealObject(this.recalcInfo.dataLbls[i].layout) && (AscFormat.isRealNumber(this.recalcInfo.dataLbls[i].layout.x) || AscFormat.isRealNumber(this.recalcInfo.dataLbls[i].layout.y)); var pos = this.chartObj.reCalculatePositionText("dlbl", this, this.recalcInfo.dataLbls[i].series.idx, this.recalcInfo.dataLbls[i].pt.idx, bLayout);// var oLbl = this.recalcInfo.dataLbls[i]; if(oLbl.layout){ layout = oLbl.layout; if(AscFormat.isRealNumber(layout.x)){ pos.x = this.calculatePosByLayout(pos.x, layout.xMode, layout.x, this.recalcInfo.dataLbls[i].extX, this.extX); } if(AscFormat.isRealNumber(layout.y)){ pos.y = this.calculatePosByLayout(pos.y, layout.yMode, layout.y, this.recalcInfo.dataLbls[i].extY, this.extY); } } if(pos.x + oLbl.extX > this.extX){ pos.x -= (pos.x + oLbl.extX - this.extX); } if(pos.y + oLbl.extY > this.extY){ pos.y -= (pos.y + oLbl.extY - this.extY); } if(pos.x < 0){ pos.x = 0; } if(pos.y < 0){ pos.y = 0; } oLbl.setPosition(pos.x, pos.y); break; } } } } this.recalcInfo.dataLbls.length = 0; if(b_recalc_labels) { if(this.chart && this.chart.title) { var pos = this.chartObj.reCalculatePositionText("title", this, this.chart.title); if(this.chart.title.layout){ layout = this.chart.title.layout; if(AscFormat.isRealNumber(layout.x)){ pos.x = this.calculatePosByLayout(pos.x, layout.xMode, layout.x, this.chart.title.extX, this.extX); }if(AscFormat.isRealNumber(layout.y)){ pos.y = this.calculatePosByLayout(pos.y, layout.yMode, layout.y, this.chart.title.extY, this.extY); } } this.chart.title.setPosition(pos.x, pos.y); } if(this.chart && this.chart.plotArea) { var hor_axis = this.chart.plotArea.getHorizontalAxis(); if(hor_axis && hor_axis.title) { var old_cat_ax = this.chart.plotArea.catAx; this.chart.plotArea.catAx = hor_axis; var pos = this.chartObj.reCalculatePositionText("catAx", this, hor_axis.title); if(hor_axis.title.layout){ layout = hor_axis.title.layout; if(AscFormat.isRealNumber(layout.x)){ pos.x = this.calculatePosByLayout(pos.x, layout.xMode, layout.x, hor_axis.title.extX, this.extX); }if(AscFormat.isRealNumber(layout.y)){ pos.y = this.calculatePosByLayout(pos.y, layout.yMode, layout.y, hor_axis.title.extY, this.extY); } } hor_axis.title.setPosition(pos.x, pos.y); this.chart.plotArea.catAx = old_cat_ax; } var vert_axis = this.chart.plotArea.getVerticalAxis(); if(vert_axis && vert_axis.title) { var old_val_ax = this.chart.plotArea.valAx; this.chart.plotArea.valAx = vert_axis; var pos = this.chartObj.reCalculatePositionText("valAx", this, vert_axis.title); if(vert_axis.title.layout){ layout = vert_axis.title.layout; if(AscFormat.isRealNumber(layout.x)){ pos.x = this.calculatePosByLayout(pos.x, layout.xMode, layout.x, vert_axis.title.extX, this.extX); }if(AscFormat.isRealNumber(layout.y)){ pos.y = this.calculatePosByLayout(pos.y, layout.yMode, layout.y, vert_axis.title.extY, this.extY); } } vert_axis.title.setPosition(pos.x, pos.y); this.chart.plotArea.valAx = old_val_ax; } } } if(b_recalc_legend && this.chart && this.chart.legend) { var bResetLegendPos = false; if(!AscFormat.isRealNumber(this.chart.legend.legendPos)) { this.chart.legend.legendPos = Asc.c_oAscChartLegendShowSettings.bottom; bResetLegendPos = true; } var pos = this.chartObj.reCalculatePositionText("legend", this, this.chart.legend); if(this.chart.legend.layout){ layout = this.chart.legend.layout; if(AscFormat.isRealNumber(layout.x)){ pos.x = this.calculatePosByLayout(pos.x, layout.xMode, layout.x, this.chart.legend.extX, this.extX); }if(AscFormat.isRealNumber(layout.y)){ pos.y = this.calculatePosByLayout(pos.y, layout.yMode, layout.y, this.chart.legend.extY, this.extY); } } this.chart.legend.setPosition(pos.x, pos.y); if(bResetLegendPos) { this.chart.legend.legendPos = null; } } }; CChartSpace.prototype.getLabelsForAxis = function(oAxis){ var aStrings = []; var oPlotArea = this.chart.plotArea, i; switch(oAxis.getObjectType()){ case AscDFH.historyitem_type_DateAx: case AscDFH.historyitem_type_CatAx:{ //расчитаем подписи для горизонтальной оси var oSeries = oPlotArea.getSeriesWithSmallestIndexForAxis(oAxis); var nPtsLen = 0; oAxis.scale = []; ; if(oSeries && oSeries.cat) { var oLit; var oCat = oSeries.cat; if(oCat.strRef && oCat.strRef.strCache){ oLit = oCat.strRef.strCache; } else if(oCat.strLit){ oLit = oCat.strLit; } else if(oCat.numRef && oCat.numRef.numCache){ oLit = oCat.numRef.numCache; } else if(oCat.numLit){ oLit = oCat.numLit; } if(oLit){ var oLitFormat = null, oPtFormat = null; if(typeof oLit.formatCode === "string" && oLit.formatCode.length > 0){ oLitFormat = oNumFormatCache.get(oLit.formatCode); } nPtsLen = oLit.ptCount; var bTickSkip = AscFormat.isRealNumber(oAxis.tickLblSkip); var nTickLblSkip = AscFormat.isRealNumber(oAxis.tickLblSkip) ? oAxis.tickLblSkip : (nPtsLen < SKIP_LBL_LIMIT ? 1 : Math.floor(nPtsLen/SKIP_LBL_LIMIT)); for(i = 0; i < nPtsLen; ++i){ oAxis.scale.push(i); if(!bTickSkip || ((i % nTickLblSkip) === 0)){ var oPt = oLit.getPtByIndex(i); if(oPt){ var sPt; if(typeof oPt.formatCode === "string" && oPt.formatCode.length > 0){ oPtFormat = oNumFormatCache.get(oPt.formatCode); if(oPtFormat){ sPt = oPtFormat.formatToChart(oPt.val); } else{ sPt = oPt.val; } } else if(oLitFormat){ sPt = oLitFormat.formatToChart(oPt.val); } else{ sPt = oPt.val; } aStrings.push(sPt); } else{ aStrings.push(""); } } else{ aStrings.push(null); } } } } var nPtsLength = 0; var aChartsForAxis = oPlotArea.getChartsForAxis(oAxis); for(i = 0; i < aChartsForAxis.length; ++i){ var oChart = aChartsForAxis[i]; for(var j = 0; j < oChart.series.length; ++j){ var oCurPts = null; oSeries = oChart.series[j]; if(oSeries.val) { if(oSeries.val.numRef && oSeries.val.numRef.numCache){ oCurPts = oSeries.val.numRef.numCache; } else if(oSeries.val.numLit){ oCurPts = oSeries.val.numLit; } if(oCurPts){ nPtsLength = Math.max(nPtsLength, oCurPts.ptCount); } } } } var nCrossBetween = this.getAxisCrossType(oAxis.crossAx); if(nCrossBetween === AscFormat.CROSS_BETWEEN_MID_CAT && nPtsLength < 2){ nPtsLength = 2; } if(nPtsLength > aStrings.length){ for(i = aStrings.length; i < nPtsLength; ++i){ aStrings.push(i + 1 + ""); oAxis.scale.push(i); } } else{ aStrings.splice(nPtsLength, aStrings.length - nPtsLength); } break; } case AscDFH.historyitem_type_ValAx:{ var aVal = [].concat(oAxis.scale); var fMultiplier; if(oAxis.dispUnits){ fMultiplier = oAxis.dispUnits.getMultiplier(); } else{ fMultiplier = 1.0; } var oNumFmt = oAxis.numFmt; var oNumFormat = null; if(oNumFmt && typeof oNumFmt.formatCode === "string"){ oNumFormat = oNumFormatCache.get(oNumFmt.formatCode); } for(var t = 0; t < aVal.length; ++t){ var fCalcValue = aVal[t]*fMultiplier; var sRichValue; if(oNumFormat){ sRichValue = oNumFormat.formatToChart(fCalcValue); } else{ sRichValue = fCalcValue + ""; } aStrings.push(sRichValue); } break; } case AscDFH.historyitem_type_SerAx:{ break; } } return aStrings; }; CChartSpace.prototype.calculateAxisGrid = function(oAxis, oRect){ if(!oAxis){ return; } var oAxisGrid = new CAxisGrid(); oAxis.grid = oAxisGrid; // oAxis.nType = 0;//0 - horizontal, 1 - vertical, 2 - series axis var nOrientation = oAxis.scaling && AscFormat.isRealNumber(oAxis.scaling.orientation) ? oAxis.scaling.orientation : AscFormat.ORIENTATION_MIN_MAX; var aStrings = this.getLabelsForAxis(oAxis); var nCrossType = this.getAxisCrossType(oAxis); var bOnTickMark = ((nCrossType === AscFormat.CROSS_BETWEEN_MID_CAT) && (aStrings.length > 1)); var nIntervalsCount = bOnTickMark ? (aStrings.length - 1) : (aStrings.length); var fInterval; oAxisGrid.nCount = nIntervalsCount; oAxisGrid.bOnTickMark = bOnTickMark; oAxisGrid.aStrings = aStrings; if(oAxis.axPos === AscFormat.AX_POS_B || oAxis.axPos === AscFormat.AX_POS_T){ oAxisGrid.nType = 0; fInterval = oRect.w/nIntervalsCount; if(nOrientation === AscFormat.ORIENTATION_MIN_MAX){ oAxisGrid.fStart = oRect.x; oAxisGrid.fStride = fInterval; } else{ oAxisGrid.fStart = oRect.x + oRect.w; oAxisGrid.fStride = -fInterval; } } else{ oAxis.yPoints =[]; oAxisGrid.nType = 1; fInterval = oRect.h/nIntervalsCount; if(nOrientation === AscFormat.ORIENTATION_MIN_MAX){ oAxisGrid.fStart = oRect.y + oRect.h; oAxisGrid.fStride = -fInterval; } else{ oAxisGrid.fStart = oRect.y; oAxisGrid.fStride = fInterval; } } }; CChartSpace.prototype.recalculateAxesSet = function (aAxesSet, oRect, oBaseRect, nIndex, fForceContentWidth) { var oCorrectedRect = null; var bWithoutLabels = false; if(this.chart.plotArea.layout && this.chart.plotArea.layout.layoutTarget === AscFormat.LAYOUT_TARGET_INNER){ bWithoutLabels = true; } var bCorrected = false; var fL = oRect.x, fT = oRect.y, fR = oRect.x + oRect.w, fB = oRect.y + oRect.h; var fHorPadding = 0.0; var fVertPadding = 0.0; var fHorInterval = null; var oCalcMap = {}; for(var i = 0; i < aAxesSet.length; ++i){ var oCurAxis = aAxesSet[i]; var oCrossAxis = oCurAxis.crossAx; if(!oCalcMap[oCurAxis.Id]){ this.calculateAxisGrid(oCurAxis, oRect); oCalcMap[oCurAxis.Id] = true; } if(!oCalcMap[oCrossAxis.Id]){ this.calculateAxisGrid(oCrossAxis, oRect); oCalcMap[oCrossAxis.Id] = true; } var fCrossValue; var fAxisPos; if(AscFormat.isRealNumber(oCurAxis.crossesAt) && oCrossAxis.scale[0] <= oCurAxis.crossesAt && oCrossAxis.scale[oCrossAxis.scale.length - 1] >= oCurAxis.crossesAt){ fCrossValue = oCurAxis.crossesAt; } var fDistance = 10.0*(25.4/72);///TODO var nLabelsPos; var bLabelsExtremePosition = false; if(oCurAxis.bDelete){ nLabelsPos = c_oAscTickLabelsPos.TICK_LABEL_POSITION_NONE; } else{ if(null !== oCurAxis.tickLblPos){ nLabelsPos = oCurAxis.tickLblPos; } else{ nLabelsPos = c_oAscTickLabelsPos.TICK_LABEL_POSITION_NEXT_TO; } } switch (oCurAxis.crosses) { case AscFormat.CROSSES_MAX:{ fCrossValue = oCrossAxis.scale[oCrossAxis.scale.length - 1]; if(nLabelsPos === c_oAscTickLabelsPos.TICK_LABEL_POSITION_NEXT_TO){ fDistance = -fDistance; bLabelsExtremePosition = true; } break; } case AscFormat.CROSSES_MIN:{ fCrossValue = oCrossAxis.scale[0]; if(nLabelsPos === c_oAscTickLabelsPos.TICK_LABEL_POSITION_NEXT_TO){ bLabelsExtremePosition = true; } } default:{ //includes AutoZero if(oCrossAxis.scale[0] <=0 && oCrossAxis.scale[oCrossAxis.scale.length - 1] >= 0){ fCrossValue = 0; } else if(oCrossAxis.scale[0] > 0){ fCrossValue = oCrossAxis.scale[0]; } else{ fCrossValue = oCrossAxis.scale[oCrossAxis.scale.length - 1]; } if(AscFormat.fApproxEqual(fCrossValue, oCrossAxis.scale[0]) || AscFormat.fApproxEqual(fCrossValue, oCrossAxis.scale[oCrossAxis.scale.length - 1])){ bLabelsExtremePosition = true; } } } var oCrossGrid = oCrossAxis.grid; var fScale = (oCrossGrid.nCount*oCrossGrid.fStride)/(oCrossAxis.scale[oCrossAxis.scale.length - 1] - oCrossAxis.scale[0]); fAxisPos = oCrossGrid.fStart + (fCrossValue - oCrossAxis.scale[0])*fScale; var nOrientation = isRealObject(oCrossAxis.scaling) && AscFormat.isRealNumber(oCrossAxis.scaling.orientation) ? oCrossAxis.scaling.orientation : AscFormat.ORIENTATION_MIN_MAX; if(nOrientation === AscFormat.ORIENTATION_MAX_MIN){ fDistance = -fDistance; } var oLabelsBox = null, fPos; var fPosStart = oCurAxis.grid.fStart; var fPosEnd = oCurAxis.grid.fStart + oCurAxis.grid.nCount*oCurAxis.grid.fStride; var bOnTickMark = oCurAxis.grid.bOnTickMark; var bForceVertical = false; var bNumbers = false;//TODO if(nLabelsPos !== c_oAscTickLabelsPos.TICK_LABEL_POSITION_NONE){ oLabelsBox = new CLabelsBox(oCurAxis.grid.aStrings, oCurAxis, this); switch(nLabelsPos){ case c_oAscTickLabelsPos.TICK_LABEL_POSITION_NEXT_TO:{ fPos = fAxisPos; break; } case c_oAscTickLabelsPos.TICK_LABEL_POSITION_HIGH:{ fPos = oCrossGrid.fStart + oCrossGrid.nCount*oCrossGrid.fStride; fDistance = - fDistance; break; } case c_oAscTickLabelsPos.TICK_LABEL_POSITION_LOW:{ fPos = oCrossGrid.fStart; break; } } } oCurAxis.labels = oLabelsBox; oCurAxis.posX = null; oCurAxis.posY = null; oCurAxis.xPoints = null; oCurAxis.yPoints = null; var aPoints = null; if(oCurAxis.getObjectType() === AscDFH.historyitem_type_SerAx){ //TODO } else if(oCurAxis.axPos === AscFormat.AX_POS_B || oCurAxis.axPos === AscFormat.AX_POS_T){ oCurAxis.posY = fAxisPos; oCurAxis.xPoints = []; aPoints = oCurAxis.xPoints; if(oLabelsBox){ if(!AscFormat.fApproxEqual(oRect.fVertPadding, 0)){ fPos -= oRect.fVertPadding; if(nLabelsPos === c_oAscTickLabelsPos.TICK_LABEL_POSITION_NEXT_TO){ oCurAxis.posY -= oRect.fVertPadding; } } var bTickSkip = AscFormat.isRealNumber(oCurAxis.tickLblSkip); var nTickLblSkip = AscFormat.isRealNumber(oCurAxis.tickLblSkip) ? oCurAxis.tickLblSkip : 1; var fAxisLength = fPosEnd - fPosStart; var nLabelsCount = oLabelsBox.aLabels.length; var bOnTickMark_ = bOnTickMark && nLabelsCount > 1; var nIntervalCount = bOnTickMark_ ? nLabelsCount - 1 : nLabelsCount; fHorInterval = Math.abs(fAxisLength/nIntervalCount); if(bTickSkip && !AscFormat.isRealNumber(fForceContentWidth)){ fForceContentWidth = Math.abs(fHorInterval) + fHorInterval/nTickLblSkip; } fLayoutHorLabelsBox(oLabelsBox, fPos, fPosStart, fPosEnd, bOnTickMark, fDistance, bForceVertical, bNumbers, fForceContentWidth); if(bLabelsExtremePosition){ if(fDistance > 0){ fVertPadding = -oLabelsBox.extY; } else{ fVertPadding = oLabelsBox.extY; } } } } else{//vertical axis fDistance = -fDistance; oCurAxis.posX = fAxisPos; oCurAxis.yPoints = []; aPoints = oCurAxis.yPoints; if(oLabelsBox){ if(!AscFormat.fApproxEqual(oRect.fHorPadding, 0)){ fPos -= oRect.fHorPadding; if(nLabelsPos === c_oAscTickLabelsPos.TICK_LABEL_POSITION_NEXT_TO){ oCurAxis.posX -= oRect.fHorPadding; } } fLayoutVertLabelsBox(oLabelsBox, fPos, fPosStart, fPosEnd, bOnTickMark, fDistance, bForceVertical); if(bLabelsExtremePosition){ if(fDistance > 0){ fHorPadding = -oLabelsBox.extX; } else{ fHorPadding = oLabelsBox.extX; } } } } if(null !== aPoints){ var fStartSeriesPos = 0.0; if(!bOnTickMark){ fStartSeriesPos = oCurAxis.grid.fStride/2.0; } for(var j = 0; j < oCurAxis.grid.aStrings.length; ++j){ aPoints.push({val: oCurAxis.scale[j], pos: oCurAxis.grid.fStart + j*oCurAxis.grid.fStride + fStartSeriesPos}) } } if(oLabelsBox){ if(oLabelsBox.x < fL){ fL = oLabelsBox.x; } if(oLabelsBox.x + oLabelsBox.extX > fR){ fR = oLabelsBox.x + oLabelsBox.extX; } if(oLabelsBox.y < fT){ fT = oLabelsBox.y; } if(oLabelsBox.y + oLabelsBox.extY > fB){ fB = oLabelsBox.y + oLabelsBox.extY; } } } // function CAxisGrid(){ // this.nType = 0;//0 - horizontal, 1 - vertical, 2 - series axis // this.fStart = 0.0; // this.fStride = 0.0; // this.nCount = 0; // } if(nIndex < 2){ var fDiff; var fPrecision = 0.01; oCorrectedRect = new CRect(oRect.x, oRect.y, oRect.w, oRect.h); if(bWithoutLabels){ fDiff = fL; if(fDiff < 0.0 && !AscFormat.fApproxEqual(fDiff, 0.0, fPrecision)){ oCorrectedRect.x -= fDiff; oCorrectedRect.w += fDiff; bCorrected = true; } fDiff = fR - this.extX; if(fDiff > 0.0 && !AscFormat.fApproxEqual(fDiff, 0.0, fPrecision)){ oCorrectedRect.w -= fDiff; bCorrected = true; } fDiff = fT; if( fDiff < 0.0 && !AscFormat.fApproxEqual(fDiff, 0.0, fPrecision)){ oCorrectedRect.y -= fDiff; oCorrectedRect.h += fDiff; bCorrected = true; } fDiff = fB - this.extY; if( fDiff > 0.0 && !AscFormat.fApproxEqual(fDiff, 0.0, fPrecision)){ oCorrectedRect.h -= (fB - this.extY); bCorrected = true; } } else{ fDiff = oBaseRect.x - fL; if(/*fDiff > 0.0 && */!AscFormat.fApproxEqual(fDiff, 0.0, fPrecision) ){ oCorrectedRect.x += fDiff; oCorrectedRect.w -= fDiff; bCorrected = true; } fDiff = oBaseRect.x + oBaseRect.w - fR; if(/*fDiff < 0.0 && */!AscFormat.fApproxEqual(fDiff, 0.0, fPrecision)){ oCorrectedRect.w += fDiff; bCorrected = true; } fDiff = oBaseRect.y - fT; if(/*fDiff > 0.0 &&*/ !AscFormat.fApproxEqual(fDiff, 0.0, fPrecision)){ oCorrectedRect.y += fDiff; oCorrectedRect.h -= fDiff; bCorrected = true; } fDiff = oBaseRect.y + oBaseRect.h - fB; if(/*fDiff < 0.0 && */!AscFormat.fApproxEqual(fDiff, 0.0, fPrecision)){ oCorrectedRect.h += fDiff; bCorrected = true; } } if(oCorrectedRect && bCorrected){ if(oCorrectedRect.w > oRect.w){ return this.recalculateAxesSet(aAxesSet, oCorrectedRect, oBaseRect, ++nIndex, fHorInterval); } else{ return this.recalculateAxesSet(aAxesSet, oCorrectedRect, oBaseRect, ++nIndex); } } } var _ret = oRect.copy(); _ret.fHorPadding = fHorPadding; _ret.fVertPadding = fVertPadding; return _ret; }; CChartSpace.prototype.recalculateAxes = function(){ this.plotAreaRect = null; if(this.chart && this.chart.plotArea && this.chart.plotArea){ if(!this.chartObj){ this.chartObj = new AscFormat.CChartsDrawer() } this.chartObj.preCalculateData(this); var i, j; var oPlotArea = this.chart.plotArea; var aAxes = [].concat(oPlotArea.axId); var aAllAxes = [];//array of axes sets var oCurAxis, oCurAxis2, aCurAxesSet; while(aAxes.length > 0){ oCurAxis = aAxes.splice(0, 1)[0]; aCurAxesSet = []; aCurAxesSet.push(oCurAxis); for(i = aAxes.length - 1; i > -1; --i){ oCurAxis2 = aAxes[i]; for(j = 0; j < aCurAxesSet.length; ++j){ if(aCurAxesSet[j].crossAx === oCurAxis2 || oCurAxis2.crossAx === aCurAxesSet[j]){ aCurAxesSet.push(oCurAxis2); } } } if(aCurAxesSet.length > 1){ aAllAxes.push(aCurAxesSet); } } for(i = 0; i < oPlotArea.axId.length; ++i){ oCurAxis = oPlotArea.axId[i]; oCurAxis.posY = null; oCurAxis.posX = null; oCurAxis.xPoints = null; oCurAxis.yPoints = null; } var oSize = this.getChartSizes(); var oRect = new CRect(oSize.startX, oSize.startY, oSize.w, oSize.h); var oBaseRect = oRect; var aRects = []; for(i = 0; i < aAllAxes.length; ++i){ aCurAxesSet = aAllAxes[i]; aRects.push(this.recalculateAxesSet(aCurAxesSet, oRect, oBaseRect, 0)); } if(aRects.length > 1){ oRect = aRects[0].copy(); for(i = 1; i < aRects.length; ++i){ if(!oRect.intersection(aRects[i])){ break; } } var fOldHorPadding = 0.0, fOldVertPadding = 0.0; if(i === aRects.length){ var aRects2 = []; for(i = 0; i < aAllAxes.length; ++i){ aCurAxesSet = aAllAxes[i]; if(i === 0){ fOldHorPadding = oRect.fHorPadding; fOldVertPadding = oRect.fVertPadding; oRect.fHorPadding = 0.0; oRect.fVertPadding = 0.0; } aRects2.push(this.recalculateAxesSet(aCurAxesSet, oRect, oBaseRect, 2)); if(i === 0){ oRect.fHorPadding = fOldHorPadding; oRect.fVertPadding = fOldVertPadding; } } var bCheckPaddings = false; for(i = 0; i < aRects.length; ++i){ if(Math.abs(aRects2[i].fVertPadding) > Math.abs(aRects[i].fVertPadding)){ if(aRects2[i].fVertPadding > 0){ aRects[i].y += (aRects2[i].fVertPadding - aRects[i].fVertPadding); aRects[i].h -= (aRects2[i].fVertPadding - aRects[i].fVertPadding); } else{ aRects[i].h -= Math.abs(aRects2[i].fVertPadding - aRects[i].fVertPadding); } aRects[i].fVertPadding = aRects2[i].fVertPadding; bCheckPaddings = true; } if(Math.abs(aRects2[i].fHorPadding) > Math.abs(aRects[i].fHorPadding)){ if(aRects2[i].fHorPadding > 0){ aRects[i].x += (aRects2[i].fHorPadding - aRects[i].fHorPadding); aRects[i].w -= (aRects2[i].fHorPadding - aRects[i].fHorPadding); } else{ aRects[i].w -= Math.abs(aRects2[i].fHorPadding - aRects[i].fHorPadding); } aRects[i].fHorPadding = aRects2[i].fHorPadding; bCheckPaddings = true; } } if(bCheckPaddings){ oRect = aRects[0].copy(); for(i = 1; i < aRects.length; ++i){ if(!oRect.intersection(aRects[i])){ break; } } if(i === aRects.length){ var aRects2 = []; for(i = 0; i < aAllAxes.length; ++i){ aCurAxesSet = aAllAxes[i]; if(i === 0){ fOldHorPadding = oRect.fHorPadding; fOldVertPadding = oRect.fVertPadding; oRect.fHorPadding = 0.0; oRect.fVertPadding = 0.0; } aRects2.push(this.recalculateAxesSet(aCurAxesSet, oRect, oBaseRect, 2)); if(i === 0){ oRect.fHorPadding = fOldHorPadding; oRect.fVertPadding = fOldVertPadding; } } } } } } } }; CChartSpace.prototype.recalculateAxis = function() { if(this.chart && this.chart.plotArea && this.chart.plotArea.charts[0]) { var b_checkEmpty = this.checkEmptySeries(); this.bEmptySeries = b_checkEmpty; var plot_area = this.chart.plotArea; var chart_object = plot_area.chart; var i; var chart_type = chart_object.getObjectType(); var bWithoutLabels = false; if(plot_area.layout && plot_area.layout.layoutTarget === AscFormat.LAYOUT_TARGET_INNER){ bWithoutLabels = true; } this.plotAreaRect = null; var rect; var bCorrectedLayoutRect = false; if(b_checkEmpty) { if(chart_type === AscDFH.historyitem_type_ScatterChart) { var x_ax, y_ax; y_ax = this.chart.plotArea.valAx; x_ax = this.chart.plotArea.catAx; y_ax.labels = null; x_ax.labels = null; y_ax.posX = null; x_ax.posY = null; y_ax.posY = null; x_ax.posX = null; y_ax.xPoints = null; x_ax.yPoints = null; y_ax.yPoints = null; x_ax.xPoints = null; } else if(chart_type !== AscDFH.historyitem_type_BarChart && (chart_type !== AscDFH.historyitem_type_PieChart && chart_type !== AscDFH.historyitem_type_DoughnutChart) || (chart_type === AscDFH.historyitem_type_BarChart && chart_object.barDir !== AscFormat.BAR_DIR_BAR)) { var cat_ax, val_ax; val_ax = this.chart.plotArea.valAx; cat_ax = this.chart.plotArea.catAx; if(val_ax && cat_ax) { val_ax.labels = null; cat_ax.labels = null; val_ax.posX = null; cat_ax.posY = null; val_ax.posY = null; cat_ax.posX = null; val_ax.xPoints = null; cat_ax.yPoints = null; val_ax.yPoints = null; cat_ax.xPoints = null; val_ax.transformYPoints = null; cat_ax.transformXPoints = null; val_ax.transformXPoints = null; cat_ax.transformYPoints = null; } } else if(chart_type === AscDFH.historyitem_type_BarChart && chart_object.barDir === AscFormat.BAR_DIR_BAR) { var cat_ax, val_ax; var axis_by_types = chart_object.getAxisByTypes(); cat_ax = axis_by_types.catAx[0]; val_ax = axis_by_types.valAx[0]; if(cat_ax && val_ax) { val_ax.labels = null; cat_ax.labels = null; val_ax.posX = null; cat_ax.posY = null; val_ax.posY = null; cat_ax.posX = null; val_ax.xPoints = null; cat_ax.yPoints = null; val_ax.yPoints = null; cat_ax.xPoints = null; val_ax.transformYPoints = null; cat_ax.transformXPoints = null; val_ax.transformXPoints = null; cat_ax.transformYPoints = null; } } return; } var bNeedReflect = this.getNeedReflect(); if(chart_type === AscDFH.historyitem_type_ScatterChart) { var x_ax, y_ax; y_ax = this.chart.plotArea.valAx; x_ax = this.chart.plotArea.catAx; if(x_ax && y_ax) { /*new recalc*/ y_ax.labels = null; x_ax.labels = null; y_ax.posX = null; x_ax.posY = null; y_ax.posY = null; x_ax.posX = null; y_ax.xPoints = null; x_ax.yPoints = null; y_ax.yPoints = null; x_ax.xPoints = null; var sizes = this.getChartSizes(); rect = {x: sizes.startX, y:sizes.startY, w:sizes.w, h: sizes.h}; var arr_val = this.getValAxisValues(); var arr_strings = []; var multiplier; if(y_ax.dispUnits) multiplier = y_ax.dispUnits.getMultiplier(); else multiplier = 1; var num_fmt = y_ax.numFmt; if(num_fmt && typeof num_fmt.formatCode === "string" /*&& !(num_fmt.formatCode === "General")*/) { var num_format = oNumFormatCache.get(num_fmt.formatCode); for(i = 0; i < arr_val.length; ++i) { var calc_value = arr_val[i]*multiplier; var rich_value = num_format.formatToChart(calc_value); arr_strings.push(rich_value); } } else { for(i = 0; i < arr_val.length; ++i) { var calc_value = arr_val[i]*multiplier; arr_strings.push(calc_value + ""); } } //расчитаем подписи для вертикальной оси найдем ширину максимальной и возьмем её удвоенную за ширину подписей верт оси var left_align_labels = true; y_ax.labels = new AscFormat.CValAxisLabels(this, y_ax); y_ax.yPoints = []; var max_width = 0; for(i = 0; i < arr_strings.length; ++i) { var dlbl = new AscFormat.CDLbl(); dlbl.parent = y_ax; dlbl.chart = this; dlbl.spPr = y_ax.spPr; dlbl.txPr = y_ax.txPr; dlbl.tx = new AscFormat.CChartText(); dlbl.tx.rich = AscFormat.CreateTextBodyFromString(arr_strings[i], this.getDrawingDocument(), dlbl); if(i > 0) { dlbl.lastStyleObject = y_ax.labels.aLabels[0].lastStyleObject; } var oRecalculateByMaxWord = dlbl.tx.rich.recalculateByMaxWord(); var cur_width = oRecalculateByMaxWord.w; if(i === arr_strings.length-1){ rect.y += oRecalculateByMaxWord.h/2; } if(cur_width > max_width) max_width = cur_width; y_ax.labels.aLabels.push(dlbl); } //пока расстояние между подписями и краем блока с подписями берем размер шрифта. var hor_gap = y_ax.labels.aLabels[0].tx.rich.content.Content[0].CompiledPr.Pr.TextPr.FontSize*(25.4/72); y_ax.labels.extX = max_width + hor_gap; /*расчитаем надписи в блоке для горизонтальной оси*/ var arr_x_val = this.getXValAxisValues(); var num_fmt = x_ax.numFmt; var string_pts = []; if(num_fmt && typeof num_fmt.formatCode === "string" /*&& !(num_fmt.formatCode === "General")*/) { var num_format = oNumFormatCache.get(num_fmt.formatCode); for(i = 0; i < arr_x_val.length; ++i) { var calc_value = arr_x_val[i]*multiplier; var rich_value = num_format.formatToChart(calc_value); string_pts.push({val:rich_value}); } } else { for(i = 0; i < arr_x_val.length; ++i) { var calc_value = arr_x_val[i]*multiplier; string_pts.push({val:calc_value + ""}); } } x_ax.labels = new AscFormat.CValAxisLabels(this, x_ax); var bottom_align_labels = true; var max_height = 0; for(i = 0; i < string_pts.length; ++i) { var dlbl = new AscFormat.CDLbl(); dlbl.parent = x_ax; dlbl.chart = this; dlbl.spPr = x_ax.spPr; dlbl.txPr = x_ax.txPr; dlbl.tx = new AscFormat.CChartText(); dlbl.tx.rich = AscFormat.CreateTextBodyFromString(string_pts[i].val.replace(oNonSpaceRegExp, ' '), this.getDrawingDocument(), dlbl); if(x_ax.labels.aLabels[0]) { dlbl.lastStyleObject = x_ax.labels.aLabels[0].lastStyleObject; } var oWH = dlbl.tx.rich.recalculateByMaxWord(); var cur_height = oWH.h; if(cur_height > max_height) max_height = cur_height; if(i === string_pts.length - 1){ rect.w -= oWH.w/2; } x_ax.labels.aLabels.push(dlbl); } var vert_gap = x_ax.labels.aLabels[0].tx.rich.content.Content[0].CompiledPr.Pr.TextPr.FontSize*(25.4/72); x_ax.labels.extY = max_height + vert_gap; /*расчитаем позицию блока с подпиясями вертикальной оси*/ var x_ax_orientation = isRealObject(x_ax.scaling) && AscFormat.isRealNumber(x_ax.scaling.orientation) ? x_ax.scaling.orientation : AscFormat.ORIENTATION_MIN_MAX; var crosses;//точка на горизонтальной оси где её пересекает вертикальная if(y_ax.crosses === AscFormat.CROSSES_AUTO_ZERO) { if(arr_x_val[0] <=0 && arr_x_val[arr_x_val.length -1] >= 0) crosses = 0; else if(arr_x_val[0] > 0) crosses = arr_x_val[0]; else crosses = arr_x_val[arr_x_val.length-1]; } else if(y_ax.crosses === AscFormat.CROSSES_MAX) crosses = arr_x_val[arr_x_val.length-1]; else if(y_ax.crosses === AscFormat.CROSSES_MIN) crosses = arr_x_val[0]; else if(AscFormat.isRealNumber(y_ax.crossesAt) && arr_val[0] <= y_ax.crossesAt && arr_val[arr_val.length-1] >= y_ax.crossesAt) { crosses = y_ax.crossesAt; } else { //в кайнем случае ведем себя как с AUTO_ZERO if(arr_x_val[0] <=0 && arr_x_val[arr_x_val.length -1] >= 0) crosses = 0; else if(arr_x_val[0] > 0) crosses = arr_x_val[0]; else crosses = arr_x_val[arr_x_val.length-1]; } var hor_interval_width = checkFiniteNumber(rect.w/(arr_x_val[arr_x_val.length-1] - arr_x_val[0])); var vert_interval_height = checkFiniteNumber(rect.h/(arr_val[arr_val.length-1] - arr_val[0])); var arr_x_points = [], arr_y_points = []; var labels_pos = y_ax.tickLblPos; var first_hor_label_half_width = (x_ax.tickLblPos === c_oAscTickLabelsPos.TICK_LABEL_POSITION_NONE || x_ax.bDelete) ? 0 : x_ax.labels.aLabels[0].tx.rich.content.XLimit/2; var last_hor_label_half_width = (x_ax.tickLblPos === c_oAscTickLabelsPos.TICK_LABEL_POSITION_NONE || x_ax.bDelete) ? 0 : x_ax.labels.aLabels[x_ax.labels.aLabels.length-1].tx.rich.content.XLimit/2; var left_gap = 0, right_gap = 0; if(x_ax_orientation === AscFormat.ORIENTATION_MIN_MAX) { switch(labels_pos) { case c_oAscTickLabelsPos.TICK_LABEL_POSITION_HIGH: { left_align_labels = false; if(bNeedReflect) { right_gap = Math.max(last_hor_label_half_width, 0); } else { right_gap = Math.max(last_hor_label_half_width, y_ax.labels.extX); } if(!bWithoutLabels){ hor_interval_width = checkFiniteNumber((rect.w - right_gap - first_hor_label_half_width)/(arr_x_val[arr_x_val.length-1] - arr_x_val[0])); for(i = 0; i < arr_x_val.length; ++i) { arr_x_points[i] = rect.x + first_hor_label_half_width + hor_interval_width*(arr_x_val[i] - arr_x_val[0]); } y_ax.labels.x = rect.x + first_hor_label_half_width + hor_interval_width*(arr_x_val[arr_x_val.length-1] - arr_x_val[0]); y_ax.posX = rect.x + first_hor_label_half_width + (crosses-arr_x_val[0])*hor_interval_width; } else{ hor_interval_width = checkFiniteNumber(rect.w/(arr_x_val[arr_x_val.length-1] - arr_x_val[0])); for(i = 0; i < arr_x_val.length; ++i) { arr_x_points[i] = rect.x + hor_interval_width*(arr_x_val[i] - arr_x_val[0]); } y_ax.labels.x = rect.x + hor_interval_width*(arr_x_val[arr_x_val.length-1] - arr_x_val[0]); y_ax.posX = rect.x + (crosses-arr_x_val[0])*hor_interval_width; if(y_ax.labels.x < 0 && !bNeedReflect){ rect.x -= y_ax.labels.x; rect.w += y_ax.labels.x; bCorrectedLayoutRect = true; } if(y_ax.labels.x + y_ax.labels.extX > this.extX && !bNeedReflect){ rect.w -= (y_ax.labels.x + y_ax.labels.extX - this.extX); bCorrectedLayoutRect = true; } if(bCorrectedLayoutRect){ hor_interval_width = checkFiniteNumber(rect.w/(arr_x_val[arr_x_val.length-1] - arr_x_val[0])); for(i = 0; i < arr_x_val.length; ++i) { arr_x_points[i] = rect.x + hor_interval_width*(arr_x_val[i] - arr_x_val[0]); } y_ax.labels.x = rect.x + hor_interval_width*(arr_x_val[arr_x_val.length-1] - arr_x_val[0]); y_ax.posX = rect.x + (crosses-arr_x_val[0])*hor_interval_width; } } break; } case c_oAscTickLabelsPos.TICK_LABEL_POSITION_LOW: { if(bNeedReflect) { left_gap = Math.max(first_hor_label_half_width, 0); } else { left_gap = Math.max(first_hor_label_half_width, y_ax.labels.extX); } if(!bWithoutLabels){ hor_interval_width = checkFiniteNumber((rect.w-left_gap - last_hor_label_half_width)/(arr_x_val[arr_x_val.length-1] - arr_x_val[0])); for(i = 0; i < arr_x_val.length; ++i) { arr_x_points[i] = rect.x + left_gap + hor_interval_width*(arr_x_val[i] - arr_x_val[0]); } y_ax.labels.x = rect.x - y_ax.labels.extX; y_ax.posX = rect.x + (crosses-arr_x_val[0])*hor_interval_width; } else{ hor_interval_width = checkFiniteNumber(rect.w/(arr_x_val[arr_x_val.length-1] - arr_x_val[0])); for(i = 0; i < arr_x_val.length; ++i) { arr_x_points[i] = rect.x + hor_interval_width*(arr_x_val[i] - arr_x_val[0]); } y_ax.labels.x = rect.x - y_ax.labels.extX; y_ax.posX = rect.x + (crosses-arr_x_val[0])*hor_interval_width; if(y_ax.labels.x < 0 && !bNeedReflect){ rect.x -= y_ax.labels.x; rect.w += y_ax.labels.x; bCorrectedLayoutRect = true; } if(y_ax.labels.x + y_ax.labels.extX > this.extX && !bNeedReflect){ rect.w -= (y_ax.labels.x + y_ax.labels.extX - this.extX); bCorrectedLayoutRect = true; } if(bCorrectedLayoutRect){ hor_interval_width = checkFiniteNumber(rect.w/(arr_x_val[arr_x_val.length-1] - arr_x_val[0])); for(i = 0; i < arr_x_val.length; ++i) { arr_x_points[i] = rect.x + hor_interval_width*(arr_x_val[i] - arr_x_val[0]); } y_ax.labels.x = rect.x - y_ax.labels.extX; y_ax.posX = rect.x + (crosses-arr_x_val[0])*hor_interval_width; } } break; } case c_oAscTickLabelsPos.TICK_LABEL_POSITION_NONE: { if(!bWithoutLabels) { y_ax.labels = null; hor_interval_width = checkFiniteNumber((rect.w - first_hor_label_half_width - last_hor_label_half_width) / (arr_x_val[arr_x_val.length - 1] - arr_x_val[0])); for (i = 0; i < arr_x_val.length; ++i) { arr_x_points[i] = rect.x + first_hor_label_half_width + hor_interval_width * (arr_x_val[i] - arr_x_val[0]); } y_ax.posX = rect.x + first_hor_label_half_width + hor_interval_width * (crosses - arr_x_val[0]); } else{ y_ax.labels = null; hor_interval_width = checkFiniteNumber(rect.w/ (arr_x_val[arr_x_val.length - 1] - arr_x_val[0])); for (i = 0; i < arr_x_val.length; ++i) { arr_x_points[i] = rect.x + first_hor_label_half_width + hor_interval_width * (arr_x_val[i] - arr_x_val[0]); } y_ax.posX = rect.x + hor_interval_width * (crosses - arr_x_val[0]); } break; } default : {//c_oAscTickLabelsPos.TICK_LABEL_POSITION_NEXT_TO рядом с осью if(y_ax.crosses === AscFormat.CROSSES_MAX) { left_align_labels = false; if(bNeedReflect) { right_gap = Math.max(right_gap, 0); } else { right_gap = Math.max(right_gap, y_ax.labels.extX); } if(!bWithoutLabels){ y_ax.labels.x = rect.x + rect.w - right_gap; y_ax.posX = rect.x + rect.w - right_gap; hor_interval_width = checkFiniteNumber((rect.w - right_gap - first_hor_label_half_width)/(arr_x_val[arr_x_val.length-1] - arr_x_val[0])); for(i = 0; i < arr_x_val.length; ++i) { arr_x_points[i] = rect.x + first_hor_label_half_width + hor_interval_width*(arr_x_val[i] - arr_x_val[0]); } } else{ y_ax.labels.x = rect.x + rect.w; y_ax.posX = rect.x + rect.w; hor_interval_width = checkFiniteNumber(rect.w/(arr_x_val[arr_x_val.length-1] - arr_x_val[0])); for(i = 0; i < arr_x_val.length; ++i) { arr_x_points[i] = rect.x + hor_interval_width*(arr_x_val[i] - arr_x_val[0]); } if(y_ax.labels.x < 0 && !bNeedReflect){ rect.x -= y_ax.labels.x; rect.w += y_ax.labels.x; bCorrectedLayoutRect = true; } if(y_ax.labels.x + y_ax.labels.extX > this.extX && !bNeedReflect){ rect.w -= (y_ax.labels.x + y_ax.labels.extX - this.extX); bCorrectedLayoutRect = true; } if(bCorrectedLayoutRect){ y_ax.labels.x = rect.x + rect.w; y_ax.posX = rect.x + rect.w; hor_interval_width = checkFiniteNumber(rect.w/(arr_x_val[arr_x_val.length-1] - arr_x_val[0])); for(i = 0; i < arr_x_val.length; ++i) { arr_x_points[i] = rect.x + hor_interval_width*(arr_x_val[i] - arr_x_val[0]); } } } } else { if(!bWithoutLabels) { hor_interval_width = checkFiniteNumber((rect.w - first_hor_label_half_width - last_hor_label_half_width) / (arr_x_val[arr_x_val.length - 1] - arr_x_val[0])); if (!bNeedReflect && first_hor_label_half_width + (crosses - arr_x_val[0]) * hor_interval_width < y_ax.labels.extX) { hor_interval_width = checkFiniteNumber((rect.w - y_ax.labels.extX - last_hor_label_half_width) / (arr_x_val[arr_x_val.length - 1] - crosses)); } y_ax.posX = rect.x + rect.w - last_hor_label_half_width - (arr_x_val[arr_x_val.length - 1] - crosses) * hor_interval_width; for (i = 0; i < arr_x_val.length; ++i) { arr_x_points[i] = y_ax.posX + (arr_x_val[i] - crosses) * hor_interval_width; } y_ax.labels.x = y_ax.posX - y_ax.labels.extX; } else{ hor_interval_width = checkFiniteNumber(rect.w/ (arr_x_val[arr_x_val.length - 1] - arr_x_val[0])); y_ax.posX = rect.x + rect.w - (arr_x_val[arr_x_val.length - 1] - crosses) * hor_interval_width; for (i = 0; i < arr_x_val.length; ++i) { arr_x_points[i] = y_ax.posX + (arr_x_val[i] - crosses) * hor_interval_width; } y_ax.labels.x = y_ax.posX - y_ax.labels.extX; if(y_ax.labels.x < 0 && !bNeedReflect){ rect.x -= y_ax.labels.x; rect.w += y_ax.labels.x; bCorrectedLayoutRect = true; } if(y_ax.labels.x + y_ax.labels.extX > this.extX && !bNeedReflect){ rect.w -= (y_ax.labels.x + y_ax.labels.extX - this.extX); bCorrectedLayoutRect = true; } if(bCorrectedLayoutRect){ hor_interval_width = checkFiniteNumber(rect.w/ (arr_x_val[arr_x_val.length - 1] - arr_x_val[0])); y_ax.posX = rect.x + rect.w - (arr_x_val[arr_x_val.length - 1] - crosses) * hor_interval_width; for (i = 0; i < arr_x_val.length; ++i) { arr_x_points[i] = y_ax.posX + (arr_x_val[i] - crosses) * hor_interval_width; } y_ax.labels.x = y_ax.posX - y_ax.labels.extX; } } } break; } } } else { switch(labels_pos) { case c_oAscTickLabelsPos.TICK_LABEL_POSITION_HIGH: { if(bNeedReflect) { left_gap = Math.max(0, last_hor_label_half_width); } else { left_gap = Math.max(y_ax.labels.extX, last_hor_label_half_width); } if(!bWithoutLabels){ hor_interval_width = checkFiniteNumber((rect.w - left_gap - first_hor_label_half_width)/(arr_x_val[arr_x_val.length-1] - arr_x_val[0])); y_ax.posX = rect.x + rect.w - (crosses - arr_x_val[0])*hor_interval_width - first_hor_label_half_width; for(i = 0; i < arr_x_val.length; ++i) { arr_x_points[i] = y_ax.posX - (arr_x_val[i]-crosses)*hor_interval_width; } y_ax.labels.x = y_ax.posX - (arr_x_val[arr_x_val.length-1]-crosses)*hor_interval_width - y_ax.labels.extX; } else{ hor_interval_width = checkFiniteNumber(rect.w/(arr_x_val[arr_x_val.length-1] - arr_x_val[0])); y_ax.posX = rect.x + rect.w - (crosses - arr_x_val[0])*hor_interval_width; for(i = 0; i < arr_x_val.length; ++i) { arr_x_points[i] = y_ax.posX - (arr_x_val[i]-crosses)*hor_interval_width; } y_ax.labels.x = y_ax.posX - (arr_x_val[arr_x_val.length-1]-crosses)*hor_interval_width - y_ax.labels.extX; if(y_ax.labels.x < 0 && !bNeedReflect){ rect.x -= y_ax.labels.x; rect.w += y_ax.labels.x; bCorrectedLayoutRect = true; } if(y_ax.labels.x + y_ax.labels.extX > this.extX && !bNeedReflect){ rect.w -= (y_ax.labels.x + y_ax.labels.extX - this.extX); bCorrectedLayoutRect = true; } if(bCorrectedLayoutRect){ hor_interval_width = checkFiniteNumber(rect.w/(arr_x_val[arr_x_val.length-1] - arr_x_val[0])); y_ax.posX = rect.x + rect.w - (crosses - arr_x_val[0])*hor_interval_width; for(i = 0; i < arr_x_val.length; ++i) { arr_x_points[i] = y_ax.posX - (arr_x_val[i]-crosses)*hor_interval_width; } y_ax.labels.x = y_ax.posX - (arr_x_val[arr_x_val.length-1]-crosses)*hor_interval_width - y_ax.labels.extX; } } break; } case c_oAscTickLabelsPos.TICK_LABEL_POSITION_LOW: { left_align_labels = false; if(bNeedReflect) { right_gap = Math.max(0, first_hor_label_half_width); } else { right_gap = Math.max(y_ax.labels.extX, first_hor_label_half_width); } if(!bWithoutLabels){ hor_interval_width = checkFiniteNumber((rect.w - right_gap - last_hor_label_half_width)/(arr_x_val[arr_x_val.length-1] - arr_x_val[0])); y_ax.posX = rect.x + rect.w - right_gap - (crosses - arr_x_val[0])*hor_interval_width; for(i = 0; i < arr_x_val.length; ++i) { arr_x_points[i] = y_ax.posX - (arr_x_val[i]-crosses)*hor_interval_width; } y_ax.labels.x = rect.x + rect.w - right_gap; } else{ hor_interval_width = checkFiniteNumber(rect.w/(arr_x_val[arr_x_val.length-1] - arr_x_val[0])); y_ax.posX = rect.x + rect.w - (crosses - arr_x_val[0])*hor_interval_width; for(i = 0; i < arr_x_val.length; ++i) { arr_x_points[i] = y_ax.posX - (arr_x_val[i]-crosses)*hor_interval_width; } y_ax.labels.x = rect.x + rect.w; if(y_ax.labels.x < 0 && !bNeedReflect){ rect.x -= y_ax.labels.x; rect.w += y_ax.labels.x; bCorrectedLayoutRect = true; } if(y_ax.labels.x + y_ax.labels.extX > this.extX && !bNeedReflect){ rect.w -= (y_ax.labels.x + y_ax.labels.extX - this.extX); bCorrectedLayoutRect = true; } if(bCorrectedLayoutRect){ hor_interval_width = checkFiniteNumber(rect.w/(arr_x_val[arr_x_val.length-1] - arr_x_val[0])); y_ax.posX = rect.x + rect.w - (crosses - arr_x_val[0])*hor_interval_width; for(i = 0; i < arr_x_val.length; ++i) { arr_x_points[i] = y_ax.posX - (arr_x_val[i]-crosses)*hor_interval_width; } y_ax.labels.x = rect.x + rect.w; } } break; } case c_oAscTickLabelsPos.TICK_LABEL_POSITION_NONE: { y_ax.labels = null; if(!bWithoutLabels) { hor_interval_width = checkFiniteNumber((rect.w - first_hor_label_half_width - last_hor_label_half_width) / (arr_x_val[arr_x_val.length - 1] - arr_x_val[0])); y_ax.posX = rect.x + rect.w - first_hor_label_half_width - (crosses - arr_x_val[0]) * hor_interval_width; for (i = 0; i < arr_x_val.length; ++i) { arr_x_points[i] = y_ax.posX - (arr_x_val[i] - crosses) * hor_interval_width; } } else{ hor_interval_width = checkFiniteNumber(rect.w / (arr_x_val[arr_x_val.length - 1] - arr_x_val[0])); y_ax.posX = rect.x + rect.w - (crosses - arr_x_val[0]) * hor_interval_width; for (i = 0; i < arr_x_val.length; ++i) { arr_x_points[i] = y_ax.posX - (arr_x_val[i] - crosses) * hor_interval_width; } } break; } default : {//c_oAscTickLabelsPos.TICK_LABEL_POSITION_NEXT_TO рядом с осью if(y_ax.crosses === AscFormat.CROSSES_MAX) { if(bNeedReflect) { left_gap = Math.max(0, last_hor_label_half_width); } else { left_gap = Math.max(y_ax.labels.extX, last_hor_label_half_width); } if(!bWithoutLabels) { hor_interval_width = checkFiniteNumber((rect.w - left_gap - first_hor_label_half_width) / (arr_x_val[arr_x_val.length - 1] - arr_x_val[0])); y_ax.posX = rect.x + rect.w - first_hor_label_half_width - (crosses - arr_x_val[0]) * hor_interval_width; y_ax.labels.x = y_ax.posX - ((arr_x_val[arr_x_val.length - 1] - crosses) * hor_interval_width) - y_ax.labels.extX; } else{ hor_interval_width = checkFiniteNumber(rect.w/ (arr_x_val[arr_x_val.length - 1] - arr_x_val[0])); y_ax.posX = rect.x + rect.w - (crosses - arr_x_val[0]) * hor_interval_width; y_ax.labels.x = y_ax.posX - ((arr_x_val[arr_x_val.length - 1] - crosses) * hor_interval_width) - y_ax.labels.extX; if(y_ax.labels.x < 0 && !bNeedReflect){ rect.x -= y_ax.labels.x; rect.w += y_ax.labels.x; bCorrectedLayoutRect = true; } if(y_ax.labels.x + y_ax.labels.extX > this.extX && !bNeedReflect){ rect.w -= (y_ax.labels.x + y_ax.labels.extX - this.extX); bCorrectedLayoutRect = true; } if(bCorrectedLayoutRect){ hor_interval_width = checkFiniteNumber(rect.w/ (arr_x_val[arr_x_val.length - 1] - arr_x_val[0])); y_ax.posX = rect.x + rect.w - (crosses - arr_x_val[0]) * hor_interval_width; y_ax.labels.x = y_ax.posX - ((arr_x_val[arr_x_val.length - 1] - crosses) * hor_interval_width) - y_ax.labels.extX; } } } else { left_align_labels = false; if(!bWithoutLabels) { hor_interval_width = checkFiniteNumber((rect.w - first_hor_label_half_width - last_hor_label_half_width) / (arr_x_val[arr_x_val.length - 1] - arr_x_val[0])); if (!bNeedReflect && first_hor_label_half_width + (crosses - arr_x_val[0]) * hor_interval_width < y_ax.labels.extX) { hor_interval_width = checkFiniteNumber((rect.w - y_ax.labels.extX - last_hor_label_half_width) / (arr_x_val[arr_x_val.length - 1] - crosses)); } left_align_labels = false; y_ax.posX = rect.x + last_hor_label_half_width + hor_interval_width * (arr_x_val[arr_x_val.length - 1] - crosses); y_ax.labels.x = y_ax.posX; } else{ hor_interval_width = checkFiniteNumber(rect.w / (arr_x_val[arr_x_val.length - 1] - arr_x_val[0])); left_align_labels = false; y_ax.posX = rect.x + hor_interval_width * (arr_x_val[arr_x_val.length - 1] - crosses); y_ax.labels.x = y_ax.posX; if(y_ax.labels.x < 0 && !bNeedReflect){ rect.x -= y_ax.labels.x; rect.w += y_ax.labels.x; bCorrectedLayoutRect = true; } if(y_ax.labels.x + y_ax.labels.extX > this.extX && !bNeedReflect){ rect.w -= (y_ax.labels.x + y_ax.labels.extX - this.extX); bCorrectedLayoutRect = true; } if(bCorrectedLayoutRect){ hor_interval_width = checkFiniteNumber(rect.w / (arr_x_val[arr_x_val.length - 1] - arr_x_val[0])); left_align_labels = false; y_ax.posX = rect.x + hor_interval_width * (arr_x_val[arr_x_val.length - 1] - crosses); y_ax.labels.x = y_ax.posX; } } } for(i = 0; i < arr_x_val.length; ++i) { arr_x_points[i] = y_ax.posX - (arr_x_val[i] - crosses)*hor_interval_width; } break; } } } x_ax.interval = hor_interval_width; /*рассчитаем позицию блока с подписями горизонтальной оси*/ var y_ax_orientation = isRealObject(y_ax.scaling) && AscFormat.isRealNumber(y_ax.scaling.orientation) ? y_ax.scaling.orientation : AscFormat.ORIENTATION_MIN_MAX; var crosses_x; if(x_ax.crosses === AscFormat.CROSSES_AUTO_ZERO) { if(arr_val[0] <= 0 && arr_val[arr_val.length-1] >=0) { crosses_x = 0; } else if(arr_val[0] > 0) crosses_x = arr_val[0]; else crosses_x = arr_val[arr_val.length-1]; } else if(x_ax.crosses === AscFormat.CROSSES_MAX) { crosses_x = arr_val[arr_val.length-1]; } else if(x_ax.crosses === AscFormat.CROSSES_MIN) { crosses_x = arr_val[0]; } else if(AscFormat.isRealNumber(x_ax.crossesAt) && arr_val[0] <= x_ax.crossesAt && arr_val[arr_val.length-1] >= x_ax.crossesAt) { crosses_x = x_ax.crossesAt; } else { //как с AUTO_ZERO if(arr_val[0] <= 0 && arr_val[arr_val.length-1] >=0) { crosses_x = 0; } else if(arr_val[0] > 0) crosses_x = arr_val[0]; else crosses_x = arr_val[arr_val.length-1]; } var tick_labels_pos_x = x_ax.tickLblPos; var first_vert_label_half_height = 0; //TODO (y_ax.tickLblPos === c_oAscTickLabelsPos.TICK_LABEL_POSITION_NONE || y_ax.bDelete) ? 0 : y_ax.labels.aLabels[0].tx.rich.content.GetSummaryHeight()/2; var last_vert_label_half_height = 0; //(y_ax.tickLblPos === c_oAscTickLabelsPos.TICK_LABEL_POSITION_NONE || y_ax.bDelete) ? 0 : y_ax.labels.aLabels[0].tx.rich.content.GetSummaryHeight()/2; var bottom_gap = 0, top_height = 0; if(y_ax_orientation === AscFormat.ORIENTATION_MIN_MAX) { switch(tick_labels_pos_x) { case c_oAscTickLabelsPos.TICK_LABEL_POSITION_HIGH: { bottom_align_labels = false; var bottom_start_point = rect.y + rect.h - first_vert_label_half_height; top_height = Math.max(x_ax.labels.extY, last_vert_label_half_height); if(!bWithoutLabels){ vert_interval_height = checkFiniteNumber((rect.h - top_height - first_vert_label_half_height)/(arr_val[arr_val.length-1] - arr_val[0])); x_ax.labels.y = bottom_start_point - (arr_val[arr_val.length - 1] - arr_val[0])*vert_interval_height - x_ax.labels.extY; for(i = 0; i < arr_val.length; ++i) { arr_y_points[i] = bottom_start_point - (arr_val[i] - arr_val[0])*vert_interval_height; } x_ax.posY = bottom_start_point - (crosses_x - arr_val[0])*vert_interval_height; } else{ vert_interval_height = checkFiniteNumber(rect.h/(arr_val[arr_val.length-1] - arr_val[0])); x_ax.labels.y = rect.y + rect.h - (arr_val[arr_val.length - 1] - arr_val[0])*vert_interval_height - x_ax.labels.extY; for(i = 0; i < arr_val.length; ++i) { arr_y_points[i] = rect.y + rect.h - (arr_val[i] - arr_val[0])*vert_interval_height; } x_ax.posY = rect.y + rect.h - (crosses_x - arr_val[0])*vert_interval_height; var bCheckXLabels = false; if(x_ax.labels.y < 0){ bCheckXLabels = true; rect.y -= x_ax.labels.y; rect.h -= x_ax.labels.h; } if(x_ax.labels.y + x_ax.labels.extY > this.extY){ bCheckXLabels = true; rect.h -= (x_ax.labels.y + x_ax.labels.extY - this.extY) } if(bCheckXLabels){ vert_interval_height = checkFiniteNumber(rect.h/(arr_val[arr_val.length-1] - arr_val[0])); x_ax.labels.y = rect.y + rect.h - (arr_val[arr_val.length - 1] - arr_val[0])*vert_interval_height - x_ax.labels.extY; for(i = 0; i < arr_val.length; ++i) { arr_y_points[i] = rect.y + rect.h - (arr_val[i] - arr_val[0])*vert_interval_height; } x_ax.posY = rect.y + rect.h - (crosses_x - arr_val[0])*vert_interval_height; } } break; } case c_oAscTickLabelsPos.TICK_LABEL_POSITION_LOW: { bottom_gap = Math.max(x_ax.labels.extY, first_vert_label_half_height); if(!bWithoutLabels){ x_ax.labels.y = rect.y + rect.h - bottom_gap; vert_interval_height = checkFiniteNumber((rect.h - bottom_gap - last_vert_label_half_height)/(arr_val[arr_val.length-1] - arr_val[0])); for(i = 0; i < arr_val.length; ++i) { arr_y_points[i] = rect.y + rect.h - bottom_gap - (arr_val[i] - arr_val[0])*vert_interval_height; } x_ax.posY = rect.y + rect.h - bottom_gap - (crosses_x - arr_val[0])*vert_interval_height; } else{ x_ax.labels.y = rect.y + rect.h; vert_interval_height = checkFiniteNumber(rect.h/(arr_val[arr_val.length-1] - arr_val[0])); for(i = 0; i < arr_val.length; ++i) { arr_y_points[i] = rect.y + rect.h - (arr_val[i] - arr_val[0])*vert_interval_height; } x_ax.posY = rect.y + rect.h - (crosses_x - arr_val[0])*vert_interval_height; var bCheckXLabels = false; if(x_ax.labels.y < 0){ bCheckXLabels = true; rect.y -= x_ax.labels.y; rect.h -= x_ax.labels.h; } if(x_ax.labels.y + x_ax.labels.extY > this.extY){ bCheckXLabels = true; rect.h -= (x_ax.labels.y + x_ax.labels.extY - this.extY) } if(bCheckXLabels){ x_ax.labels.y = rect.y + rect.h; vert_interval_height = checkFiniteNumber(rect.h/(arr_val[arr_val.length-1] - arr_val[0])); for(i = 0; i < arr_val.length; ++i) { arr_y_points[i] = rect.y + rect.h - (arr_val[i] - arr_val[0])*vert_interval_height; } x_ax.posY = rect.y + rect.h - (crosses_x - arr_val[0])*vert_interval_height; } } break; } case c_oAscTickLabelsPos.TICK_LABEL_POSITION_NONE: { x_ax.labels = null; if(!bWithoutLabels){ vert_interval_height = checkFiniteNumber((rect.h - first_vert_label_half_height - last_vert_label_half_height)/(arr_val[arr_val.length-1] - arr_val[0])); for(i = 0; i < arr_val.length; ++i) { arr_y_points[i] = rect.y + rect.h - first_vert_label_half_height - (arr_val[i] - arr_val[0])*vert_interval_height; } x_ax.posY = rect.y + rect.h - first_vert_label_half_height - (crosses_x - arr_val[0])*vert_interval_height; } else{ vert_interval_height = checkFiniteNumber(rect.h/(arr_val[arr_val.length-1] - arr_val[0])); for(i = 0; i < arr_val.length; ++i) { arr_y_points[i] = rect.y + rect.h - (arr_val[i] - arr_val[0])*vert_interval_height; } x_ax.posY = rect.y + rect.h - (crosses_x - arr_val[0])*vert_interval_height; } break; } default : {//c_oAscTickLabelsPos.TICK_LABEL_POSITION_NEXT_TO рядом с осью if(x_ax.crosses === AscFormat.CROSSES_MAX) { bottom_align_labels = false; top_height = Math.max(x_ax.labels.extY, last_vert_label_half_height); if(!bWithoutLabels) { vert_interval_height = checkFiniteNumber((rect.h - top_height - first_vert_label_half_height) / (arr_val[arr_val.length - 1] - arr_val[0])); for (i = 0; i < arr_val.length; ++i) { arr_y_points[i] = rect.y + rect.h - first_vert_label_half_height - (arr_val[i] - arr_val[0]) * vert_interval_height; } x_ax.posY = rect.y + rect.h - first_vert_label_half_height - (arr_val[arr_val.length - 1] - arr_val[0]) * vert_interval_height; x_ax.labels.y = x_ax.posY - x_ax.labels.extY; } else{ vert_interval_height = checkFiniteNumber(rect.h / (arr_val[arr_val.length - 1] - arr_val[0])); for (i = 0; i < arr_val.length; ++i) { arr_y_points[i] = rect.y + rect.h - (arr_val[i] - arr_val[0]) * vert_interval_height; } x_ax.posY = rect.y + rect.h - (arr_val[arr_val.length - 1] - arr_val[0]) * vert_interval_height; x_ax.labels.y = x_ax.posY - x_ax.labels.extY; var bCheckXLabels = false; if(x_ax.labels.y < 0){ bCheckXLabels = true; rect.y -= x_ax.labels.y; rect.h -= x_ax.labels.h; } if(x_ax.labels.y + x_ax.labels.extY > this.extY){ bCheckXLabels = true; rect.h -= (x_ax.labels.y + x_ax.labels.extY - this.extY) } if(bCheckXLabels){ vert_interval_height = checkFiniteNumber(rect.h / (arr_val[arr_val.length - 1] - arr_val[0])); for (i = 0; i < arr_val.length; ++i) { arr_y_points[i] = rect.y + rect.h - (arr_val[i] - arr_val[0]) * vert_interval_height; } x_ax.posY = rect.y + rect.h - (arr_val[arr_val.length - 1] - arr_val[0]) * vert_interval_height; x_ax.labels.y = x_ax.posY - x_ax.labels.extY; } } } else { if(!bWithoutLabels) { vert_interval_height = checkFiniteNumber((rect.h - first_vert_label_half_height - last_vert_label_half_height) / (arr_val[arr_val.length - 1] - arr_val[0])); if (first_vert_label_half_height + (crosses_x - arr_val[0]) * vert_interval_height < x_ax.labels.extY) { vert_interval_height = checkFiniteNumber((rect.h - x_ax.labels.extY - last_vert_label_half_height) / (arr_val[arr_val.length - 1] - crosses_x)); } x_ax.posY = rect.y + last_vert_label_half_height + (arr_val[arr_val.length - 1] - crosses_x) * vert_interval_height; x_ax.labels.y = x_ax.posY; for (i = 0; i < arr_val.length; ++i) { arr_y_points[i] = x_ax.posY - (arr_val[i] - crosses_x) * vert_interval_height; } } else{ vert_interval_height = checkFiniteNumber(rect.h / (arr_val[arr_val.length - 1] - arr_val[0])); x_ax.posY = rect.y + (arr_val[arr_val.length - 1] - crosses_x) * vert_interval_height; x_ax.labels.y = x_ax.posY; for (i = 0; i < arr_val.length; ++i) { arr_y_points[i] = x_ax.posY - (arr_val[i] - crosses_x) * vert_interval_height; } var bCheckXLabels = false; if(x_ax.labels.y < 0){ bCheckXLabels = true; rect.y -= x_ax.labels.y; rect.h -= x_ax.labels.h; } if(x_ax.labels.y + x_ax.labels.extY > this.extY){ bCheckXLabels = true; rect.h -= (x_ax.labels.y + x_ax.labels.extY - this.extY) } if(bCheckXLabels){ vert_interval_height = checkFiniteNumber(rect.h / (arr_val[arr_val.length - 1] - arr_val[0])); x_ax.posY = rect.y + (arr_val[arr_val.length - 1] - crosses_x) * vert_interval_height; x_ax.labels.y = x_ax.posY; for (i = 0; i < arr_val.length; ++i) { arr_y_points[i] = x_ax.posY - (arr_val[i] - crosses_x) * vert_interval_height; } } } } break; } } } else { switch(tick_labels_pos_x) { case c_oAscTickLabelsPos.TICK_LABEL_POSITION_HIGH: { bottom_gap = Math.max(last_vert_label_half_height, x_ax.labels.extY); if(!bWithoutLabels) { vert_interval_height = checkFiniteNumber((rect.h - bottom_gap - first_vert_label_half_height) / (arr_val[arr_val.length - 1] - arr_val[0])); x_ax.posY = rect.y + first_vert_label_half_height + (crosses_x - arr_val[0]) * vert_interval_height; for (i = 0; i < arr_val.length; ++i) { arr_y_points[i] = x_ax.posY + vert_interval_height * (arr_val[i] - crosses_x); } x_ax.labels.y = x_ax.posY + vert_interval_height * (arr_val[arr_val.length - 1] - crosses_x); } else{ vert_interval_height = checkFiniteNumber(rect.h / (arr_val[arr_val.length - 1] - arr_val[0])); x_ax.posY = rect.y + (crosses_x - arr_val[0]) * vert_interval_height; for (i = 0; i < arr_val.length; ++i) { arr_y_points[i] = x_ax.posY + vert_interval_height * (arr_val[i] - crosses_x); } x_ax.labels.y = x_ax.posY + vert_interval_height * (arr_val[arr_val.length - 1] - crosses_x); var bCheckXLabels = false; if(x_ax.labels.y < 0){ bCheckXLabels = true; rect.y -= x_ax.labels.y; rect.h -= x_ax.labels.h; } if(x_ax.labels.y + x_ax.labels.extY > this.extY){ bCheckXLabels = true; rect.h -= (x_ax.labels.y + x_ax.labels.extY - this.extY) } if(bCheckXLabels){ vert_interval_height = checkFiniteNumber(rect.h / (arr_val[arr_val.length - 1] - arr_val[0])); x_ax.posY = rect.y + (crosses_x - arr_val[0]) * vert_interval_height; for (i = 0; i < arr_val.length; ++i) { arr_y_points[i] = x_ax.posY + vert_interval_height * (arr_val[i] - crosses_x); } x_ax.labels.y = x_ax.posY + vert_interval_height * (arr_val[arr_val.length - 1] - crosses_x); } } break; } case c_oAscTickLabelsPos.TICK_LABEL_POSITION_LOW: { top_height = Math.max(x_ax.labels.extY, first_vert_label_half_height); bottom_align_labels = false; if(!bWithoutLabels) { vert_interval_height = checkFiniteNumber((rect.h - top_height - last_vert_label_half_height) / (arr_val[arr_val.length - 1] - arr_val[0])); x_ax.posY = rect.y + top_height + (crosses_x - arr_val[0]) * vert_interval_height; for (i = 0; i < arr_val.length; ++i) { arr_y_points[i] = rect.y + top_height + vert_interval_height * (arr_val[i] - arr_val[0]); } x_ax.labels.y = rect.y + top_height - x_ax.labels.extY; } else{ vert_interval_height = checkFiniteNumber(rect.h / (arr_val[arr_val.length - 1] - arr_val[0])); x_ax.posY = rect.y + (crosses_x - arr_val[0]) * vert_interval_height; for (i = 0; i < arr_val.length; ++i) { arr_y_points[i] = rect.y + vert_interval_height * (arr_val[i] - arr_val[0]); } x_ax.labels.y = rect.y - x_ax.labels.extY; var bCheckXLabels = false; if(x_ax.labels.y < 0){ bCheckXLabels = true; rect.y -= x_ax.labels.y; rect.h -= x_ax.labels.h; } if(x_ax.labels.y + x_ax.labels.extY > this.extY){ bCheckXLabels = true; rect.h -= (x_ax.labels.y + x_ax.labels.extY - this.extY) } if(bCheckXLabels){ vert_interval_height = checkFiniteNumber(rect.h / (arr_val[arr_val.length - 1] - arr_val[0])); x_ax.posY = rect.y + (crosses_x - arr_val[0]) * vert_interval_height; for (i = 0; i < arr_val.length; ++i) { arr_y_points[i] = rect.y + vert_interval_height * (arr_val[i] - arr_val[0]); } x_ax.labels.y = rect.y - x_ax.labels.extY; } } break; } case c_oAscTickLabelsPos.TICK_LABEL_POSITION_NONE: { x_ax.labels = null; if(!bWithoutLabels){ vert_interval_height = checkFiniteNumber((rect.h - first_vert_label_half_height - last_vert_label_half_height)/(arr_val[arr_val.length-1] - arr_val[0])); x_ax.posY = rect.y + first_vert_label_half_height + (crosses_x-arr_val[0])*vert_interval_height; for(i = 0; i < arr_val.length;++i) { arr_y_points[i] = rect.y + first_vert_label_half_height + vert_interval_height*(arr_val[i] - arr_val[0]); } } else{ vert_interval_height = checkFiniteNumber(rect.h/(arr_val[arr_val.length-1] - arr_val[0])); x_ax.posY = rect.y + (crosses_x-arr_val[0])*vert_interval_height; for(i = 0; i < arr_val.length;++i) { arr_y_points[i] = rect.y + vert_interval_height*(arr_val[i] - arr_val[0]); } } break; } default : {//c_oAscTickLabelsPos.TICK_LABEL_POSITION_NEXT_TO рядом с осью if(x_ax.crosses === AscFormat.CROSSES_MAX) { bottom_gap = Math.max(x_ax.labels.extY, last_vert_label_half_height); if(!bWithoutLabels) { vert_interval_height = checkFiniteNumber((rect.h - bottom_gap - first_vert_label_half_height) / (arr_val[arr_val.length - 1] - arr_val[0])); x_ax.posY = rect.y + first_vert_label_half_height + (crosses_x - arr_val[0]) * vert_interval_height; for (i = 0; i < arr_val.length; ++i) { arr_y_points[i] = rect.y + first_vert_label_half_height + vert_interval_height * (arr_val[i] - arr_val[0]); } x_ax.labels.y = rect.y + rect.extY - bottom_gap; } else{ vert_interval_height = checkFiniteNumber(rect.h / (arr_val[arr_val.length - 1] - arr_val[0])); x_ax.posY = rect.y + (crosses_x - arr_val[0]) * vert_interval_height; for (i = 0; i < arr_val.length; ++i) { arr_y_points[i] = rect.y + vert_interval_height * (arr_val[i] - arr_val[0]); } x_ax.labels.y = rect.y + rect.extY; var bCheckXLabels = false; if(x_ax.labels.y < 0){ bCheckXLabels = true; rect.y -= x_ax.labels.y; rect.h -= x_ax.labels.h; } if(x_ax.labels.y + x_ax.labels.extY > this.extY){ bCheckXLabels = true; rect.h -= (x_ax.labels.y + x_ax.labels.extY - this.extY) } if(bCheckXLabels){ vert_interval_height = checkFiniteNumber(rect.h / (arr_val[arr_val.length - 1] - arr_val[0])); x_ax.posY = rect.y + (crosses_x - arr_val[0]) * vert_interval_height; for (i = 0; i < arr_val.length; ++i) { arr_y_points[i] = rect.y + vert_interval_height * (arr_val[i] - arr_val[0]); } x_ax.labels.y = rect.y + rect.extY; } } } else { bottom_align_labels = false; if(!bWithoutLabels) { vert_interval_height = checkFiniteNumber((rect.h - last_vert_label_half_height - first_vert_label_half_height) / (arr_val[arr_val.length - 1] - arr_val[0])); if (first_vert_label_half_height + (crosses_x - arr_val[0]) * vert_interval_height < x_ax.labels.extY) { x_ax.posY = rect.y + x_ax.labels.extY; vert_interval_height = checkFiniteNumber((rect.h - x_ax.labels.extY - last_vert_label_half_height) / (arr_val[arr_val.length - 1] - crosses_x)); } else { x_ax.posY = rect.y + rect.h - vert_interval_height * (arr_val[arr_val.length - 1] - crosses_x) - last_vert_label_half_height; } x_ax.labels.y = x_ax.posY - x_ax.labels.extY; for (i = 0; i < arr_val.length; ++i) { arr_y_points[i] = x_ax.posY + vert_interval_height * (arr_val[i] - crosses_x); } } else{ vert_interval_height = checkFiniteNumber(rect.h / (arr_val[arr_val.length - 1] - arr_val[0])); x_ax.posY = rect.y + rect.h - vert_interval_height * (arr_val[arr_val.length - 1] - crosses_x); x_ax.labels.y = x_ax.posY - x_ax.labels.extY; for (i = 0; i < arr_val.length; ++i) { arr_y_points[i] = x_ax.posY + vert_interval_height * (arr_val[i] - crosses_x); } var bCheckXLabels = false; if(x_ax.labels.y < 0){ bCheckXLabels = true; rect.y -= x_ax.labels.y; rect.h -= x_ax.labels.h; } if(x_ax.labels.y + x_ax.labels.extY > this.extY){ bCheckXLabels = true; rect.h -= (x_ax.labels.y + x_ax.labels.extY - this.extY) } if(bCheckXLabels){ vert_interval_height = checkFiniteNumber(rect.h / (arr_val[arr_val.length - 1] - arr_val[0])); x_ax.posY = rect.y + rect.h - vert_interval_height * (arr_val[arr_val.length - 1] - crosses_x); x_ax.labels.y = x_ax.posY - x_ax.labels.extY; for (i = 0; i < arr_val.length; ++i) { arr_y_points[i] = x_ax.posY + vert_interval_height * (arr_val[i] - crosses_x); } } } } break; } } } y_ax.interval = vert_interval_height; y_ax.yPoints = []; for(i = 0; i < arr_val.length; ++i) { y_ax.yPoints.push({pos: arr_y_points[i], val: arr_val[i]}); } x_ax.xPoints = []; for(i = 0; i < arr_x_val.length; ++i) { x_ax.xPoints.push({pos: arr_x_points[i], val: arr_x_val[i]}); } var arr_labels; var text_transform; var local_text_transform; if(x_ax.bDelete) { x_ax.labels = null; } if(y_ax.bDelete) { y_ax.labels = null; } if(x_ax.labels) { arr_labels = x_ax.labels.aLabels; x_ax.labels.align = bottom_align_labels; if(bottom_align_labels) { var top_line = x_ax.labels.y + vert_gap; for(i = 0; i < arr_labels.length; ++i) { if(arr_labels[i]) { arr_labels[i].txBody = arr_labels[i].tx.rich; text_transform = arr_labels[i].transformText; text_transform.Reset(); global_MatrixTransformer.TranslateAppend(text_transform, arr_x_points[i] - arr_labels[i].tx.rich.content.XLimit/2, top_line); // global_MatrixTransformer.MultiplyAppend(text_transform, this.getTransformMatrix()); local_text_transform = arr_labels[i].localTransformText; local_text_transform.Reset(); global_MatrixTransformer.TranslateAppend(local_text_transform, arr_x_points[i] - arr_labels[i].tx.rich.content.XLimit/2, top_line); } } } else { for(i = 0; i < arr_labels.length; ++i) { if(arr_labels[i]) { arr_labels[i].txBody = arr_labels[i].tx.rich; text_transform = arr_labels[i].transformText; text_transform.Reset(); global_MatrixTransformer.TranslateAppend(text_transform, arr_x_points[i] - arr_labels[i].tx.rich.content.XLimit/2, x_ax.labels.y + x_ax.labels.extY - vert_gap - arr_labels[i].tx.rich.content.GetSummaryHeight()); // global_MatrixTransformer.MultiplyAppend(text_transform, this.getTransformMatrix()); local_text_transform = arr_labels[i].localTransformText; local_text_transform.Reset(); global_MatrixTransformer.TranslateAppend(local_text_transform, arr_x_points[i] - arr_labels[i].tx.rich.content.XLimit/2, x_ax.labels.y + x_ax.labels.extY - vert_gap - arr_labels[i].tx.rich.content.GetSummaryHeight()); } } } } if(y_ax.labels) { if(bNeedReflect) { if(left_align_labels) { left_align_labels = false; y_ax.labels.x += y_ax.labels.extX; } else { left_align_labels = true; y_ax.labels.x -= y_ax.labels.extX; } } y_ax.labels.align = left_align_labels; arr_labels = y_ax.labels.aLabels; if(left_align_labels) { for(i = 0; i < arr_labels.length; ++i) { if(arr_labels[i]) { arr_labels[i].txBody = arr_labels[i].tx.rich; text_transform = arr_labels[i].transformText; text_transform.Reset(); global_MatrixTransformer.TranslateAppend(text_transform, y_ax.labels.x + y_ax.labels.extX - hor_gap - arr_labels[i].tx.rich.content.XLimit, arr_y_points[i] - arr_labels[i].tx.rich.content.GetSummaryHeight()/2); // global_MatrixTransformer.MultiplyAppend(text_transform, this.getTransformMatrix()); local_text_transform = arr_labels[i].localTransformText; local_text_transform.Reset(); global_MatrixTransformer.TranslateAppend(local_text_transform, y_ax.labels.x + y_ax.labels.extX - hor_gap - arr_labels[i].tx.rich.content.XLimit, arr_y_points[i] - arr_labels[i].tx.rich.content.GetSummaryHeight()/2); } } } else { for(i = 0; i < arr_labels.length; ++i) { if(arr_labels[i]) { arr_labels[i].txBody = arr_labels[i].tx.rich; text_transform = arr_labels[i].transformText; text_transform.Reset(); global_MatrixTransformer.TranslateAppend(text_transform, y_ax.labels.x + hor_gap, arr_y_points[i] - arr_labels[i].tx.rich.content.GetSummaryHeight()/2); // global_MatrixTransformer.MultiplyAppend(text_transform, this.getTransformMatrix()); local_text_transform = arr_labels[i].transformText; local_text_transform.Reset(); global_MatrixTransformer.TranslateAppend(local_text_transform, y_ax.labels.x + hor_gap, arr_y_points[i] - arr_labels[i].tx.rich.content.GetSummaryHeight()/2); } } } } if(y_ax.labels) { if(y_ax_orientation === AscFormat.ORIENTATION_MIN_MAX) { var t = y_ax.labels.aLabels[y_ax.labels.aLabels.length-1].tx.rich.content.GetSummaryHeight()/2; y_ax.labels.y = arr_y_points[arr_y_points.length-1] - t; y_ax.labels.extY = arr_y_points[0] - arr_y_points[arr_y_points.length-1] + t + y_ax.labels.aLabels[0].tx.rich.content.GetSummaryHeight()/2; } else { var t = y_ax.labels.aLabels[0].tx.rich.content.GetSummaryHeight()/2; y_ax.labels.y = arr_y_points[0] - t; y_ax.labels.extY = arr_y_points[arr_y_points.length-1] - arr_y_points[0] + t + y_ax.labels.aLabels[y_ax.labels.aLabels.length-1].tx.rich.content.GetSummaryHeight()/2; } } if(x_ax.labels) { if(x_ax_orientation === AscFormat.ORIENTATION_MIN_MAX) { var t = x_ax.labels.aLabels[0].tx.rich.content.XLimit/2; x_ax.labels.x = arr_x_points[0] - t; x_ax.labels.extX = arr_x_points[arr_x_points.length-1] + x_ax.labels.aLabels[x_ax.labels.aLabels.length-1].tx.rich.content.XLimit/2 - x_ax.labels.x; } else { var t = x_ax.labels.aLabels[x_ax.labels.aLabels.length-1].tx.rich.content.XLimit/2; x_ax.labels.x = arr_x_points[arr_x_points.length-1] - t; x_ax.labels.extX = arr_x_points[0] + x_ax.labels.aLabels[0].tx.rich.content.XLimit/2 - x_ax.labels.x; } } /*new recalc*/ } } else if(chart_type !== AscDFH.historyitem_type_BarChart && (chart_type !== AscDFH.historyitem_type_PieChart && chart_type !== AscDFH.historyitem_type_DoughnutChart) || (chart_type === AscDFH.historyitem_type_BarChart && chart_object.barDir !== AscFormat.BAR_DIR_BAR)) { var cat_ax, val_ax, ser_ax; val_ax = this.chart.plotArea.valAx; cat_ax = this.chart.plotArea.catAx; ser_ax = this.chart.plotArea.serAx; if(val_ax && cat_ax) { val_ax.labels = null; cat_ax.labels = null; if(ser_ax){ ser_ax.labels = null; ser_ax.posY = null; ser_ax.posX = null; ser_ax.xPoints = null; ser_ax.yPoints = null; } val_ax.posX = null; cat_ax.posY = null; val_ax.posY = null; cat_ax.posX = null; val_ax.xPoints = null; cat_ax.yPoints = null; val_ax.yPoints = null; cat_ax.xPoints = null; var sizes = this.getChartSizes(); rect = {x: sizes.startX, y:sizes.startY, w:sizes.w, h: sizes.h}; var arr_val = this.getValAxisValues(); //Получим строки для оси значений с учетом формата и единиц var arr_strings = []; var multiplier; if(val_ax.dispUnits) multiplier = val_ax.dispUnits.getMultiplier(); else multiplier = 1; var num_fmt = val_ax.numFmt; if(num_fmt && typeof num_fmt.formatCode === "string" /*&& !(num_fmt.formatCode === "General")*/) { var num_format = oNumFormatCache.get(num_fmt.formatCode); for(i = 0; i < arr_val.length; ++i) { var calc_value = arr_val[i]*multiplier; var rich_value = num_format.formatToChart(calc_value); arr_strings.push(rich_value); } } else { for(i = 0; i < arr_val.length; ++i) { var calc_value = arr_val[i]*multiplier; arr_strings.push(calc_value + ""); } } /*если у нас шкала логарифмическая то будем вместо полученных значений использовать логарифм*/ val_ax.labels = new AscFormat.CValAxisLabels(this, val_ax); var max_width = 0; val_ax.yPoints = []; var max_val_labels_text_height = 0; var lastStyleObject = null; for(i = 0; i < arr_strings.length; ++i) { var dlbl = new AscFormat.CDLbl(); if(lastStyleObject) { dlbl.lastStyleObject = lastStyleObject; } dlbl.parent = val_ax; dlbl.chart = this; dlbl.spPr = val_ax.spPr; dlbl.txPr = val_ax.txPr; dlbl.tx = new AscFormat.CChartText(); dlbl.tx.rich = AscFormat.CreateTextBodyFromString(arr_strings[i], this.getDrawingDocument(), dlbl); var t = dlbl.tx.rich.recalculateByMaxWord(); if(!lastStyleObject) { lastStyleObject = dlbl.lastStyleObject; } var cur_width = t.w; if(cur_width > max_width) max_width = cur_width; if(t.h > max_val_labels_text_height) max_val_labels_text_height = t.h; val_ax.labels.aLabels.push(dlbl); val_ax.yPoints.push({val: arr_val[i], pos: null}); } var val_axis_labels_gap = val_ax.labels.aLabels[0].tx.rich.content.Content[0].CompiledPr.Pr.TextPr.FontSize*25.4/72; val_ax.labels.extX = max_width + val_axis_labels_gap; //расчитаем подписи для горизонтальной оси var ser = chart_object.series[0]; var string_pts = [], pts_len = 0; /*string_pts pts_len*/ if(ser && ser.cat) { var lit, b_num_lit = true; if(ser.cat.strRef && ser.cat.strRef.strCache) { lit = ser.cat.strRef.strCache; } else if(ser.cat.strLit) { lit = ser.cat.strLit; } else if(ser.cat.numRef && ser.cat.numRef.numCache) { lit = ser.cat.numRef.numCache; b_num_lit = true; } else if(ser.cat.numLit) { lit = ser.cat.numLit; b_num_lit = true; } if(lit) { var lit_format = null, pt_format = null; if(b_num_lit && typeof lit.formatCode === "string" && lit.formatCode.length > 0) { lit_format = oNumFormatCache.get(lit.formatCode); } pts_len = lit.ptCount; for(i = 0; i < pts_len; ++i) { var pt = lit.getPtByIndex(i); if(pt) { var str_pt; if(b_num_lit) { if(typeof pt.formatCode === "string" && pt.formatCode.length > 0) { pt_format = oNumFormatCache.get(pt.formatCode); if(pt_format) { str_pt = pt_format.formatToChart(pt.val); } else { str_pt = pt.val; } } else if(lit_format) { str_pt = lit_format.formatToChart(pt.val); } else { str_pt = pt.val; } } else { str_pt = pt.val; } string_pts.push({val: str_pt + ""}); } else { string_pts.push({val: /*i + */""}); } } } } var cross_between = this.getValAxisCrossType(); if(cross_between === null){ cross_between = AscFormat.CROSS_BETWEEN_BETWEEN; } //if(string_pts.length === 0) { pts_len = 0; for(i = 0; i < chart_object.series.length; ++i) { var cur_pts= null; ser = chart_object.series[i]; if(ser.val) { if(ser.val.numRef && ser.val.numRef.numCache) cur_pts = ser.val.numRef.numCache; else if(ser.val.numLit) cur_pts = ser.val.numLit; if(cur_pts) { pts_len = Math.max(pts_len, cur_pts.ptCount); } } } if(cross_between === AscFormat.CROSS_BETWEEN_MID_CAT && pts_len < 2) { pts_len = 2; } if(pts_len > string_pts.length) { for(i = string_pts.length; i < pts_len; ++i) { string_pts.push({val:i+1 + ""}); } } else { string_pts.splice(pts_len, string_pts.length - pts_len); } } /*---------------------расчет позиции блока с подписями вертикальной оси-----------------------------------------------------------------------------*/ //расчитаем ширину интервала без учета горизонтальной оси; var crosses;//номер категории в которой вертикалная ось пересекает горизонтальную; if(val_ax.crosses === AscFormat.CROSSES_AUTO_ZERO || val_ax.crosses === AscFormat.CROSSES_MIN) crosses = 1; else if(val_ax.crosses === AscFormat.CROSSES_MAX) crosses = string_pts.length; else if(AscFormat.isRealNumber(val_ax.crossesAt)) { if(val_ax.crossesAt <= string_pts.length + 1 && val_ax.crossesAt > 0) crosses = val_ax.crossesAt; else if(val_ax.crossesAt <= 0) crosses = 1; else crosses = string_pts.length; } else crosses = 1; cat_ax.maxCatVal = string_pts.length; var cat_ax_orientation = cat_ax.scaling && AscFormat.isRealNumber(cat_ax.scaling.orientation) ? cat_ax.scaling.orientation : AscFormat.ORIENTATION_MIN_MAX; var point_width = rect.w/string_pts.length; var labels_pos = val_ax.tickLblPos; if(val_ax.bDelete) { labels_pos = c_oAscTickLabelsPos.TICK_LABEL_POSITION_NONE; } // if(string_pts.length === 1) // { // cross_between = AscFormat.CROSS_BETWEEN_BETWEEN; // } var left_val_ax_labels_align = true;//приленгание подписей оси значений к левому краю. var intervals_count = cross_between === AscFormat.CROSS_BETWEEN_MID_CAT ? string_pts.length - 1 : string_pts.length; var point_interval = rect.w/intervals_count;//интервал между точками. Зависит от crossBetween, а также будет потом корректироваться в зависимости от подписей вертикальной и горизонтальной оси. if(cross_between === AscFormat.CROSS_BETWEEN_MID_CAT) point_interval = checkFiniteNumber(rect.w/(string_pts.length - 1)); else point_interval = checkFiniteNumber(rect.w/string_pts.length); var left_points_width, right_point_width; var arr_cat_labels_points = [];//массив середин подписей горизонтальной оси; i-й элемент - x-координата центра подписи категории с номером i; if(cat_ax_orientation === AscFormat.ORIENTATION_MIN_MAX) { if(labels_pos === c_oAscTickLabelsPos.TICK_LABEL_POSITION_NEXT_TO || !AscFormat.isRealNumber(labels_pos)) //подписи рядом с осью { if(val_ax.crosses === AscFormat.CROSSES_MAX) { left_val_ax_labels_align = false; if(!bWithoutLabels){ val_ax.labels.x = rect.x + rect.w - val_ax.labels.extX; if(!bNeedReflect) { point_interval = checkFiniteNumber((rect.w - val_ax.labels.extX)/intervals_count); } else { point_interval = checkFiniteNumber(rect.w/intervals_count); } val_ax.posX = val_ax.labels.x; if(cross_between === AscFormat.CROSS_BETWEEN_MID_CAT) { for(i = 0; i < string_pts.length; ++i) arr_cat_labels_points[i] = rect.x + point_interval*i; } else { for(i = 0; i < string_pts.length; ++i) arr_cat_labels_points[i] = point_interval/2 + rect.x + point_interval*i; } } else{ val_ax.labels.x = rect.x + rect.w; if(val_ax.labels.x < 0 && !bNeedReflect){ rect.x -= val_ax.labels.x; rect.w += val_ax.labels.x; val_ax.labels.x = 0; bCorrectedLayoutRect = true; } if(rect.x + rect.w > this.extX){ rect.w -= (rect.x + rect.w - this.extX); bCorrectedLayoutRect = true; } point_interval = checkFiniteNumber(rect.w/intervals_count); val_ax.posX = val_ax.labels.x; if(cross_between === AscFormat.CROSS_BETWEEN_MID_CAT) { for(i = 0; i < string_pts.length; ++i) arr_cat_labels_points[i] = rect.x + point_interval*i; } else { for(i = 0; i < string_pts.length; ++i) arr_cat_labels_points[i] = point_interval/2 + rect.x + point_interval*i; } } } else { left_points_width = point_interval*(crosses-1);//общая ширина левых точек если считать что точки занимают все пространство if(!bWithoutLabels) { if (!bNeedReflect && left_points_width < val_ax.labels.extX)//подписи верт. оси выходят за пределы области построения { var right_intervals_count = intervals_count - (crosses - 1);//количесво интервалов правее вертикальной оси //скорректируем point_interval, поделив расстояние, которое осталось справа от подписей осей на количество интервалов справа point_interval = checkFiniteNumber((rect.w - val_ax.labels.extX) / right_intervals_count); val_ax.labels.x = rect.x; var start_point = val_ax.labels.x + val_ax.labels.extX - (crosses - 1) * point_interval;//x-координата точки, где начинается собственно область диаграммы if (cross_between === AscFormat.CROSS_BETWEEN_MID_CAT) { for (i = 0; i < string_pts.length; ++i) arr_cat_labels_points[i] = start_point + point_interval * i; } else { for (i = 0; i < string_pts.length; ++i) arr_cat_labels_points[i] = point_interval / 2 + start_point + point_interval * i; } } else { val_ax.labels.x = rect.x + left_points_width - val_ax.labels.extX; if (cross_between === AscFormat.CROSS_BETWEEN_MID_CAT) { for (i = 0; i < string_pts.length; ++i) arr_cat_labels_points[i] = rect.x + point_interval * i; } else { for (i = 0; i < string_pts.length; ++i) arr_cat_labels_points[i] = point_interval / 2 + rect.x + point_interval * i; } } val_ax.posX = val_ax.labels.x + val_ax.labels.extX; } else{ val_ax.labels.x = rect.x + left_points_width - val_ax.labels.extX; if(val_ax.labels.x < 0 && !bNeedReflect){ rect.x -= val_ax.labels.x; rect.w += val_ax.labels.x; val_ax.labels.x = 0; bCorrectedLayoutRect = true; } if(rect.x + rect.w > this.extX){ rect.w -= (rect.x + rect.w - this.extX); bCorrectedLayoutRect = true; } point_interval = checkFiniteNumber( rect.w/intervals_count); if (cross_between === AscFormat.CROSS_BETWEEN_MID_CAT) { for (i = 0; i < string_pts.length; ++i) arr_cat_labels_points[i] = rect.x + point_interval * i; } else { for (i = 0; i < string_pts.length; ++i) arr_cat_labels_points[i] = point_interval / 2 + rect.x + point_interval * i; } val_ax.posX = val_ax.labels.x + val_ax.labels.extX; } } } else if(labels_pos === c_oAscTickLabelsPos.TICK_LABEL_POSITION_LOW)//подписи слева от области построения { if(!bNeedReflect) { point_interval = checkFiniteNumber((rect.w - val_ax.labels.extX)/intervals_count); } else { point_interval = checkFiniteNumber( rect.w/intervals_count); } val_ax.labels.x = rect.x; if(cross_between === AscFormat.CROSS_BETWEEN_MID_CAT) { if(!bNeedReflect) { for(i = 0; i < string_pts.length; ++i) arr_cat_labels_points[i] = rect.x + val_ax.labels.extX + point_interval*i; } else { for(i = 0; i < string_pts.length; ++i) arr_cat_labels_points[i] = rect.x + point_interval*i; } } else { if(!bNeedReflect) { for(i = 0; i < string_pts.length; ++i) arr_cat_labels_points[i] = rect.x + val_ax.labels.extX + point_interval/2 + point_interval*i; } else { for(i = 0; i < string_pts.length; ++i) arr_cat_labels_points[i] = rect.x + point_interval/2 + point_interval*i; } } val_ax.posX = val_ax.labels.x + val_ax.labels.extX + point_interval*(crosses-1); } else if(labels_pos === c_oAscTickLabelsPos.TICK_LABEL_POSITION_HIGH)//подписи справа от области построения { if(!bNeedReflect) { point_interval = checkFiniteNumber( (rect.w - val_ax.labels.extX)/intervals_count); } else { point_interval = checkFiniteNumber( rect.w/intervals_count); } val_ax.labels.x = rect.x + rect.w - val_ax.labels.extX; left_val_ax_labels_align = false; if(cross_between === AscFormat.CROSS_BETWEEN_MID_CAT) { for(i = 0; i < string_pts.length; ++i) arr_cat_labels_points[i] = rect.x + point_interval*i; } else { for(i = 0; i < string_pts.length; ++i) arr_cat_labels_points[i] = point_interval/2 + rect.x + point_interval*i; } val_ax.posX = rect.x + point_interval*(crosses-1); } else { val_ax.labels = null; if(cross_between === AscFormat.CROSS_BETWEEN_MID_CAT) { for(i = 0; i < string_pts.length; ++i) arr_cat_labels_points[i] = rect.x + point_interval*i; } else { for(i = 0; i < string_pts.length; ++i) arr_cat_labels_points[i] = point_interval/2 + rect.x + point_interval*i; } val_ax.posX = rect.x + point_interval*(crosses-1); } } else {//то же самое, только зеркально отраженное if(labels_pos === c_oAscTickLabelsPos.TICK_LABEL_POSITION_NEXT_TO || !AscFormat.isRealNumber(labels_pos)) //подписи рядом с осью { if(val_ax.crosses === AscFormat.CROSSES_MAX) { if(!bWithoutLabels){ val_ax.labels.x = rect.x; if(!bNeedReflect) { point_interval = checkFiniteNumber( (rect.w - val_ax.labels.extX)/intervals_count); } else { point_interval = checkFiniteNumber( rect.w/intervals_count); } if(cross_between === AscFormat.CROSS_BETWEEN_MID_CAT) { for(i = 0; i < string_pts.length; ++i) arr_cat_labels_points[i] = rect.x + rect.w - point_interval*i; } else { for(i = 0; i < string_pts.length; ++i) arr_cat_labels_points[i] = rect.x + rect.w - point_interval/2 - point_interval*i; } if(!bNeedReflect) { val_ax.posX = val_ax.labels.x + val_ax.labels.extX; } else { val_ax.posX = val_ax.labels.x; } } else{ val_ax.labels.x = rect.x - val_ax.labels.extX; if(val_ax.labels.x < 0 && !bNeedReflect){ rect.x -= val_ax.labels.x; rect.w += val_ax.labels.x; val_ax.labels.x = 0; bCorrectedLayoutRect = true; } if(rect.x + rect.w > this.extX){ rect.w -= (rect.x + rect.w - this.extX); bCorrectedLayoutRect = true; } point_interval = checkFiniteNumber( rect.w/intervals_count); if(cross_between === AscFormat.CROSS_BETWEEN_MID_CAT) { for(i = 0; i < string_pts.length; ++i) arr_cat_labels_points[i] = rect.x + rect.w - point_interval*i; } else { for(i = 0; i < string_pts.length; ++i) arr_cat_labels_points[i] = rect.x + rect.w - point_interval/2 - point_interval*i; } if(!bNeedReflect) { val_ax.posX = val_ax.labels.x + val_ax.labels.extX; } else { val_ax.posX = val_ax.labels.x; } } } else { left_val_ax_labels_align = false; right_point_width = point_interval*(crosses-1); if(!bNeedReflect && right_point_width < val_ax.labels.extX && !bWithoutLabels) { val_ax.labels.x = rect.x + rect.w - val_ax.labels.extX; var left_points_interval_count = intervals_count - (crosses - 1); point_interval = checkFiniteNumber( checkFiniteNumber( (val_ax.labels.x - rect.x)/left_points_interval_count)); var start_point_right = rect.x + point_interval*intervals_count; if(cross_between === AscFormat.CROSS_BETWEEN_MID_CAT) { for(i = 0; i < string_pts.length; ++i) arr_cat_labels_points[i] = start_point_right - point_interval*i; } else { for(i = 0; i < string_pts.length; ++i) arr_cat_labels_points[i] = start_point_right - point_interval/2 - point_interval*i; } } else { val_ax.labels.x = rect.x + rect.w - right_point_width; if(val_ax.labels.x < 0 && !bNeedReflect){ rect.x -= val_ax.labels.x; rect.w += val_ax.labels.x; val_ax.labels.x = 0; bCorrectedLayoutRect = true; } if(rect.x + rect.w > this.extX){ rect.w -= (rect.x + rect.w - this.extX); bCorrectedLayoutRect = true; } point_interval = checkFiniteNumber( rect.w/intervals_count); if(cross_between === AscFormat.CROSS_BETWEEN_MID_CAT) { for(i = 0; i < string_pts.length; ++i) arr_cat_labels_points[i] = rect.x + rect.w - point_interval*i; } else { for(i = 0; i < string_pts.length; ++i) arr_cat_labels_points[i] = rect.x + rect.w - point_interval/2 - point_interval*i; } } val_ax.posX = val_ax.labels.x; } } else if(labels_pos === c_oAscTickLabelsPos.TICK_LABEL_POSITION_LOW)//подписи справа от области построения { left_val_ax_labels_align = false; if(!bNeedReflect && !bWithoutLabels) { point_interval = checkFiniteNumber( (rect.w - val_ax.labels.extX)/intervals_count); } else { point_interval = checkFiniteNumber( rect.w/intervals_count); } if(!bWithoutLabels){ val_ax.labels.x = rect.x + rect.w - val_ax.labels.extX; if(cross_between === AscFormat.CROSS_BETWEEN_MID_CAT) { for(i = 0; i < string_pts.length; ++i) arr_cat_labels_points[i] = val_ax.labels.x - point_interval*i; } else { for(i = 0; i < string_pts.length; ++i) arr_cat_labels_points[i] = val_ax.labels.x - point_interval/2 - point_interval*i; } if(!bNeedReflect) { val_ax.posX = rect.x + rect.w - point_interval*(crosses-1) - val_ax.labels.extX; } else { val_ax.posX = rect.x + rect.w - point_interval*(crosses-1); } } else{ val_ax.labels.x = rect.x + rect.w; if(val_ax.labels.x < 0 && !bNeedReflect){ rect.x -= val_ax.labels.x; rect.w += val_ax.labels.x; val_ax.labels.x = 0; bCorrectedLayoutRect = true; } if(rect.x + rect.w > this.extX){ rect.w -= (rect.x + rect.w - this.extX); bCorrectedLayoutRect = true; } point_interval = checkFiniteNumber(rect.w/intervals_count); if(cross_between === AscFormat.CROSS_BETWEEN_MID_CAT) { for(i = 0; i < string_pts.length; ++i) arr_cat_labels_points[i] = val_ax.labels.x - point_interval*i; } else { for(i = 0; i < string_pts.length; ++i) arr_cat_labels_points[i] = val_ax.labels.x - point_interval/2 - point_interval*i; } if(!bNeedReflect) { val_ax.posX = rect.x + rect.w - point_interval*(crosses-1) - val_ax.labels.extX; } else { val_ax.posX = rect.x + rect.w - point_interval*(crosses-1); } } } else if(labels_pos === c_oAscTickLabelsPos.TICK_LABEL_POSITION_HIGH)//подписи слева от области построения { if(!bNeedReflect && !bWithoutLabels) { point_interval = checkFiniteNumber((rect.w - val_ax.labels.extX)/intervals_count); } else { point_interval = checkFiniteNumber(rect.w/intervals_count); } if(!bWithoutLabels){ val_ax.labels.x = rect.x; if(cross_between === AscFormat.CROSS_BETWEEN_MID_CAT) { for(i = 0; i < string_pts.length; ++i) arr_cat_labels_points[i] = rect.x + rect.w - point_interval*i; } else { for(i = 0; i < string_pts.length; ++i) arr_cat_labels_points[i] = rect.x + rect.w - point_interval/2 - point_interval*i; } val_ax.posX = rect.x + rect.w - point_interval*(crosses-1); } else{ val_ax.labels.x = rect.x - val_ax.labels.extX; if(val_ax.labels.x < 0 && !bNeedReflect){ rect.x -= val_ax.labels.x; rect.w += val_ax.labels.x; val_ax.labels.x = 0; bCorrectedLayoutRect = true; } if(rect.x + rect.w > this.extX){ rect.w -= (rect.x + rect.w - this.extX); bCorrectedLayoutRect = true; } point_interval = checkFiniteNumber(rect.w/intervals_count); if(cross_between === AscFormat.CROSS_BETWEEN_MID_CAT) { for(i = 0; i < string_pts.length; ++i) arr_cat_labels_points[i] = rect.x + rect.w - point_interval*i; } else { for(i = 0; i < string_pts.length; ++i) arr_cat_labels_points[i] = rect.x + rect.w - point_interval/2 - point_interval*i; } val_ax.posX = rect.x + rect.w - point_interval*(crosses-1); } } else { val_ax.labels = null; if(cross_between === AscFormat.CROSS_BETWEEN_MID_CAT) { for(i = 0; i < string_pts.length; ++i) arr_cat_labels_points[i] = rect.x + rect.w - point_interval*i; } else { for(i = 0; i < string_pts.length; ++i) arr_cat_labels_points[i] = rect.x + rect.w - point_interval/2 - point_interval*i; } val_ax.posX = rect.x + rect.w - point_interval*(crosses-1); } } cat_ax.interval = point_interval; var diagram_width = point_interval*intervals_count;//размер области с самой диаграммой позже будет корректироватся; var bTickSkip = AscFormat.isRealNumber(cat_ax.tickLblSkip); var tick_lbl_skip = AscFormat.isRealNumber(cat_ax.tickLblSkip) ? cat_ax.tickLblSkip : 1; var max_cat_label_width = diagram_width / string_pts.length; // максимальная ширина подписи горизонтальной оси; cat_ax.labels = null; var b_rotated = false;//флаг означает, что водписи не уместились в отведенное для них пространство и их пришлось перевернуть. //проверим умещаются ли подписи горизонтальной оси в point_interval if(c_oAscTickLabelsPos.TICK_LABEL_POSITION_NONE !== cat_ax.tickLblPos && !(cat_ax.bDelete === true)) //будем корректировать вертикальные подписи только если есть горизонтальные { cat_ax.labels = new AscFormat.CValAxisLabels(this, cat_ax); var max_min_width = 0; var max_max_width = 0; var arr_max_contents = []; var fMaxContentStringH = 0; for(i = 0; i < string_pts.length; ++i) { var dlbl = null; if(i%tick_lbl_skip === 0) { dlbl = new AscFormat.CDLbl(); dlbl.parent = cat_ax; dlbl.chart = this; dlbl.spPr = cat_ax.spPr; dlbl.txPr = cat_ax.txPr; dlbl.tx = new AscFormat.CChartText(); dlbl.tx.rich = AscFormat.CreateTextBodyFromString(string_pts[i].val.replace(oNonSpaceRegExp, ' '), this.getDrawingDocument(), dlbl); //dlbl.recalculate(); var content = dlbl.tx.rich.content; content.Set_ApplyToAll(true); content.SetParagraphAlign(AscCommon.align_Center); content.Set_ApplyToAll(false); dlbl.txBody = dlbl.tx.rich; if(cat_ax.labels.aLabels.length > 0) { dlbl.lastStyleObject = cat_ax.labels.aLabels[0].lastStyleObject; } var min_max = dlbl.tx.rich.content.RecalculateMinMaxContentWidth(); var max_min_content_width = min_max.Min; if(max_min_content_width > max_min_width) max_min_width = max_min_content_width; if(min_max.Max > max_max_width) max_max_width = min_max.Max; if(dlbl.tx.rich.content.Content[0].Content[0].TextHeight > fMaxContentStringH){ fMaxContentStringH = dlbl.tx.rich.content.Content[0].Content[0].TextHeight; } } cat_ax.labels.aLabels.push(dlbl); } fMaxContentStringH *= 1; var stake_offset = AscFormat.isRealNumber(cat_ax.lblOffset) ? cat_ax.lblOffset/100 : 1; var labels_offset = cat_ax.labels.aLabels[0].tx.rich.content.Content[0].CompiledPr.Pr.TextPr.FontSize*(25.4/72)*stake_offset; if(max_min_width < max_cat_label_width)//значит текст каждой из точек умещается в point_width { var max_height = 0; for(i = 0; i < cat_ax.labels.aLabels.length; ++i) { if(cat_ax.labels.aLabels[i]) { var content = cat_ax.labels.aLabels[i].tx.rich.content; content.Reset(0, 0, max_cat_label_width, 20000); content.Recalculate_Page(0, true); var cur_height = content.GetSummaryHeight(); if(cur_height > max_height) max_height = cur_height; } } cat_ax.labels.extY = max_height + labels_offset; if(cross_between === AscFormat.CROSS_BETWEEN_MID_CAT) //корректируем позиции центров подписей горизонтальной оси, положение вертикальной оси и её подписей { var left_gap_point, right_gap_point; if(cat_ax_orientation === AscFormat.ORIENTATION_MIN_MAX) { var first_label_left_gap = cat_ax.labels.aLabels[0].tx.rich.getMaxContentWidth(max_cat_label_width)/2;//на сколько вправа выходит первая подпись var last_labels_right_gap = cat_ax.labels.aLabels[cat_ax.labels.aLabels.length - 1] ? cat_ax.labels.aLabels[cat_ax.labels.aLabels.length - 1].tx.rich.getMaxContentWidth(max_cat_label_width)/2 : 0; //смотрим, выходит ли подпись первой категориии выходит за пределы области построения left_gap_point = arr_cat_labels_points[0] - first_label_left_gap; if(rect.x > left_gap_point && !bWithoutLabels) { if(val_ax.labels)//скорректируем позицию подписей вертикальной оси, если они есть { val_ax.labels.x = rect.x + (val_ax.labels.x - left_gap_point)*checkFiniteNumber((rect.w/(rect.x + rect.w - left_gap_point))); } //скорректируем point_interval point_interval *= checkFiniteNumber((rect.w/(rect.x + rect.w - left_gap_point))); //скорректируем arr_cat_labels_points for(i = 0; i < arr_cat_labels_points.length; ++i) { arr_cat_labels_points[i] = rect.x + (arr_cat_labels_points[i] - left_gap_point)*checkFiniteNumber((rect.w/(rect.x + rect.w - left_gap_point))); } //скорректируем позицию вертикальной оси val_ax.posX = rect.x + (val_ax.posX - left_gap_point)*checkFiniteNumber((rect.w/(rect.x + rect.w - left_gap_point))); } //смотри выходит ли подпись последней категории за пределы области построения right_gap_point = arr_cat_labels_points[arr_cat_labels_points.length - 1] + last_labels_right_gap; if(right_gap_point > rect.x + rect.w && !bWithoutLabels) { if(val_ax.labels)//скорректируем позицию подписей вертикальной оси { val_ax.labels.x = rect.x + (val_ax.labels.x - rect.x)*checkFiniteNumber((rect.w/(right_gap_point - rect.x))); } //скорректируем point_interval point_interval *= checkFiniteNumber((rect.w/(right_gap_point - rect.x))); for(i = 0; i < arr_cat_labels_points.length; ++i) { arr_cat_labels_points[i] = rect.x + (arr_cat_labels_points[i] - rect.x)*checkFiniteNumber((rect.w/(right_gap_point - rect.x))); } //скорректируем позицию вертикальной оси val_ax.posX = rect.x + (val_ax.posX - rect.x)*checkFiniteNumber((rect.w/(right_gap_point - rect.x))); } } else { var last_label_left_gap = cat_ax.labels.aLabels[cat_ax.labels.aLabels.length - 1] ? cat_ax.labels.aLabels[cat_ax.labels.aLabels.length - 1].tx.rich.getMaxContentWidth(max_cat_label_width)/2 : 0; var first_label_right_gap = cat_ax.labels.aLabels[0].tx.rich.getMaxContentWidth(max_cat_label_width)/2; left_gap_point = arr_cat_labels_points[arr_cat_labels_points.length - 1] - last_label_left_gap; right_gap_point = arr_cat_labels_points[0] + first_label_right_gap; if(rect.x > left_gap_point && !bWithoutLabels) { if(val_ax.labels)//скорректируем позицию подписей вертикальной оси, если они есть { val_ax.labels.x = rect.x + (val_ax.labels.x - left_gap_point)*checkFiniteNumber((rect.w/(rect.x + rect.w - left_gap_point))); } //скорректируем point_interval point_interval *= checkFiniteNumber((rect.w/(rect.x + rect.w - left_gap_point))); //скорректируем arr_cat_labels_points for(i = 0; i < arr_cat_labels_points.length; ++i) { arr_cat_labels_points[i] = rect.x + (arr_cat_labels_points[i] - left_gap_point)*checkFiniteNumber((rect.w/(rect.x + rect.w - left_gap_point))); } //скорректируем позицию вертикальной оси val_ax.posX = rect.x + (val_ax.posX - left_gap_point)*checkFiniteNumber((rect.w/(rect.x + rect.w - left_gap_point))); } if(right_gap_point > rect.x + rect.w && !bWithoutLabels) { if(val_ax.labels)//скорректируем позицию подписей вертикальной оси { val_ax.labels.x = rect.x + (val_ax.labels.x - rect.x)*checkFiniteNumber((rect.w/(right_gap_point - rect.x))); } //скорректируем point_interval point_interval *= checkFiniteNumber((rect.w/(right_gap_point - rect.x))); for(i = 0; i < arr_cat_labels_points.length; ++i) { arr_cat_labels_points[i] = rect.x + (arr_cat_labels_points[i] - rect.x)*checkFiniteNumber((rect.w/(right_gap_point - rect.x))); } //скорректируем позицию вертикальной оси val_ax.posX = rect.x + (val_ax.posX - rect.x)*checkFiniteNumber((rect.w/(right_gap_point - rect.x))); } } } } else { b_rotated = true; //пока сделаем без обрезки var arr_left_points = []; var arr_right_points = []; var max_rotated_height = 0; cat_ax.labels.bRotated = true; var nMaxCount = 1; var nLblCount = 0; var nCount = 0; var nSkip = 1; if(!bTickSkip && fMaxContentStringH > 0){ nMaxCount = diagram_width/fMaxContentStringH; nSkip = ((cat_ax.labels.aLabels.length/nMaxCount + 1) >> 0); } else{ bTickSkip = true; } //смотрим на сколько подписи горизонтальной оси выходят влево за пределы области построения for(i = 0; i < cat_ax.labels.aLabels.length; ++i) { if(cat_ax.labels.aLabels[i]) { if(i%nSkip !== 0){ cat_ax.labels.aLabels[i] = null; arr_left_points[i] = arr_cat_labels_points[i]; arr_right_points[i] = arr_cat_labels_points[i]; nCount++; continue; } //сначала расчитаем высоту и ширину подписи так чтобы она умещалась в одну строку var wh = cat_ax.labels.aLabels[i].tx.rich.getContentOneStringSizes(); arr_left_points[i] = arr_cat_labels_points[i] - (wh.w*Math.cos(Math.PI/4) + wh.h*Math.sin(Math.PI/4) - wh.h*Math.sin(Math.PI/4)/2);//вычитаем из точки привязки ширину получившейся подписи arr_right_points[i] = arr_cat_labels_points[i] + wh.h*Math.sin(Math.PI/4)/2; var h2 = wh.w*Math.sin(Math.PI/4) + wh.h*Math.cos(Math.PI/4); if(h2 > max_rotated_height) max_rotated_height = h2; nLblCount++; nCount++; cat_ax.labels.aLabels[i].widthForTransform = wh.w; } else {//подписи нет arr_left_points[i] = arr_cat_labels_points[i]; arr_right_points[i] = arr_cat_labels_points[i]; } } cat_ax.labels.extY = max_rotated_height + labels_offset; // left_gap_point = Math.max(0, Math.min.apply(Math, arr_left_points)); right_gap_point = Math.max(0, Math.max.apply(Math, arr_right_points)); if(!bWithoutLabels){ if(AscFormat.ORIENTATION_MIN_MAX === cat_ax_orientation) { if(rect.x > left_gap_point) { if(val_ax.labels)//скорректируем позицию подписей вертикальной оси, если они есть { val_ax.labels.x = rect.x + (val_ax.labels.x - left_gap_point)*checkFiniteNumber((rect.w/(rect.x + rect.w - left_gap_point))); } //скорректируем point_interval point_interval *= checkFiniteNumber(rect.w/(rect.x + rect.w - left_gap_point)); //скорректируем arr_cat_labels_points for(i = 0; i < arr_cat_labels_points.length; ++i) { arr_cat_labels_points[i] = rect.x + (arr_cat_labels_points[i] - left_gap_point)*checkFiniteNumber((rect.w/(rect.x + rect.w - left_gap_point))); } //скорректируем позицию вертикальной оси val_ax.posX = rect.x + (val_ax.posX - left_gap_point)*checkFiniteNumber((rect.w/(rect.x + rect.w - left_gap_point))); } //смотри выходит ли подпись последней категории за пределы области построения if(right_gap_point > rect.x + rect.w) { if(val_ax.labels)//скорректируем позицию подписей вертикальной оси { val_ax.labels.x = rect.x + (val_ax.labels.x - rect.x)*checkFiniteNumber((rect.w/(right_gap_point - rect.x))); } //скорректируем point_interval point_interval *= checkFiniteNumber((right_gap_point - rect.x)/(rect.x + rect.w - rect.x)); for(i = 0; i < arr_cat_labels_points.length; ++i) { arr_cat_labels_points[i] = rect.x + (arr_cat_labels_points[i] - rect.x)*checkFiniteNumber((rect.w/(right_gap_point - rect.x))); } //скорректируем позицию вертикальной оси val_ax.posX = rect.x + (val_ax.posX - rect.x)*checkFiniteNumber((rect.w/(right_gap_point - rect.x))); } } else { if(rect.x > left_gap_point) { if(val_ax.labels)//скорректируем позицию подписей вертикальной оси, если они есть { val_ax.labels.x = rect.x + (val_ax.labels.x - left_gap_point)*checkFiniteNumber((rect.w/(rect.x + rect.w - left_gap_point))); } //скорректируем point_interval point_interval *= (rect.w)/checkFiniteNumber((rect.x + rect.w - left_gap_point)); //скорректируем arr_cat_labels_points for(i = 0; i < arr_cat_labels_points.length; ++i) { arr_cat_labels_points[i] = rect.x + (arr_cat_labels_points[i] - left_gap_point)*checkFiniteNumber((rect.w/(rect.x + rect.w - left_gap_point))); } //скорректируем позицию вертикальной оси val_ax.posX = rect.x + (val_ax.posX - left_gap_point)*checkFiniteNumber((rect.w/(rect.x + rect.w - left_gap_point))); } if(right_gap_point > rect.x + rect.w) { if(val_ax.labels)//скорректируем позицию подписей вертикальной оси { val_ax.labels.x = rect.x + (val_ax.labels.x - rect.x)*checkFiniteNumber((rect.w/(right_gap_point - rect.x))); } //скорректируем point_interval point_interval *= checkFiniteNumber((right_gap_point - rect.x)/(rect.x + rect.w - rect.x)); for(i = 0; i < arr_cat_labels_points.length; ++i) { arr_cat_labels_points[i] = rect.x + (arr_cat_labels_points[i] - rect.x)*checkFiniteNumber((rect.w/(right_gap_point - rect.x))); } //скорректируем позицию вертикальной оси val_ax.posX = rect.x + (val_ax.posX - rect.x)*checkFiniteNumber((rect.w/(right_gap_point - rect.x))); } } } } } //series axis if(ser_ax){ if(c_oAscTickLabelsPos.TICK_LABEL_POSITION_NONE !== ser_ax.tickLblPos && !(ser_ax.bDelete === true)){ var arr_series_labels_str = []; var aSeries = chart_object.series; for(var i = 0; i < aSeries.length; ++i){ if(aSeries[i].getSeriesName){ arr_series_labels_str.push(aSeries[i].getSeriesName()); } else{ arr_series_labels_str.push('Series ' + (i+1)); } } ser_ax.labels = new AscFormat.CValAxisLabels(this, ser_ax); tick_lbl_skip = AscFormat.isRealNumber(ser_ax.tickLblSkip) ? ser_ax.tickLblSkip : 1; var lastStyleObject = null; max_val_labels_text_height = 0; max_width = 0; for(i = 0; i < arr_series_labels_str.length; ++i) { var dlbl = null; if(i%tick_lbl_skip === 0) { var dlbl = new AscFormat.CDLbl(); if(lastStyleObject) { dlbl.lastStyleObject = lastStyleObject; } dlbl.parent = val_ax; dlbl.chart = this; dlbl.spPr = val_ax.spPr; dlbl.txPr = val_ax.txPr; dlbl.tx = new AscFormat.CChartText(); dlbl.tx.rich = AscFormat.CreateTextBodyFromString(arr_series_labels_str[i], this.getDrawingDocument(), dlbl); var t = dlbl.tx.rich.recalculateByMaxWord(); if(!lastStyleObject) { lastStyleObject = dlbl.lastStyleObject; } var cur_width = t.w; if(cur_width > max_width) max_width = cur_width; if(t.h > max_val_labels_text_height) max_val_labels_text_height = t.h; ser_ax.labels.aLabels.push(dlbl); } } var ser_axis_labels_gap = ser_ax.labels.aLabels[0].tx.rich.content.Content[0].CompiledPr.Pr.TextPr.FontSize*25.4/72; ser_ax.labels.extX = max_width + ser_axis_labels_gap; ser_ax.labels.extY = max_val_labels_text_height; } else{ ser_ax.labels = null; } } //расчет позиции блока с подписями горизонтальной оси var cat_labels_align_bottom = true; /*-----------------------------------------------------------------------*/ var crosses_val_ax;//значение на ветикальной оси в котором её пересекает горизонтальная if(cat_ax.crosses === AscFormat.CROSSES_AUTO_ZERO) { if(arr_val[0] <=0 && arr_val[arr_val.length-1] >= 0) crosses_val_ax = 0; else if(arr_val[arr_val.length-1] < 0) crosses_val_ax = arr_val[arr_val.length-1]; else crosses_val_ax = arr_val[0]; } else if(cat_ax.crosses === AscFormat.CROSSES_MIN) { crosses_val_ax = arr_val[0]; } else if(cat_ax.crosses === AscFormat.CROSSES_MAX) { crosses_val_ax = arr_val[arr_val.length - 1]; } else if(AscFormat.isRealNumber(cat_ax.crossesAt) && cat_ax.crossesAt >= arr_val[0] && cat_ax.crossesAt <= arr_val[arr_val.length - 1]) { //сделаем провеку на попадание в интервал if(cat_ax.crossesAt >= arr_val[0] && cat_ax.crossesAt <= arr_val[arr_val.length - 1]) crosses_val_ax = cat_ax.crossesAt; } else { //ведем себя как в случае (cat_ax.crosses === AscFormat.CROSSES_AUTO_ZERO) if(arr_val[0] <=0 && arr_val[arr_val.length-1] >= 0) crosses_val_ax = 0; else if(arr_val[arr_val.length-1] < 0) crosses_val_ax = arr_val[arr_val.length-1]; else crosses_val_ax = arr_val[0]; } var val_ax_orientation = val_ax.scaling && AscFormat.isRealNumber(val_ax.scaling.orientation) ? val_ax.scaling.orientation : AscFormat.ORIENTATION_MIN_MAX; var hor_labels_pos = cat_ax.tickLblPos; var arr_val_labels_points = [];//массив середин подписей вертикальной оси; i-й элемент - y-координата центра подписи i-огто значения; var top_val_axis_gap, bottom_val_axis_gap; var first_val_axis_label_half_height = 0; //TODO (val_ax.bDelete || val_ax.tickLblPos ===c_oAscTickLabelsPos.TICK_LABEL_POSITION_NONE) ? 0 :val_ax.labels.aLabels[0].tx.rich.content.GetSummaryHeight()/2; var last_val_axis_label_half_height = 0; //TODO (val_ax.bDelete || val_ax.tickLblPos ===c_oAscTickLabelsPos.TICK_LABEL_POSITION_NONE) ? 0 : val_ax.labels.aLabels[val_ax.labels.aLabels.length-1].tx.rich.content.GetSummaryHeight()/2; var unit_height; if(!bWithoutLabels){ unit_height = checkFiniteNumber((rect.h - first_val_axis_label_half_height - last_val_axis_label_half_height)/(arr_val[arr_val.length - 1] - arr_val[0]));//высота единицы измерения на вертикальной оси } else{ unit_height = checkFiniteNumber(rect.h/(arr_val[arr_val.length - 1] - arr_val[0])); } var cat_ax_ext_y = cat_ax.labels ? cat_ax.labels.extY : 0; if(val_ax_orientation === AscFormat.ORIENTATION_MIN_MAX) { if(hor_labels_pos === c_oAscTickLabelsPos.TICK_LABEL_POSITION_NEXT_TO || !AscFormat.isRealNumber(hor_labels_pos)) { if(cat_ax.crosses === AscFormat.CROSSES_MAX) { cat_labels_align_bottom = false; top_val_axis_gap = Math.max(last_val_axis_label_half_height, cat_ax_ext_y); if(!bWithoutLabels){ unit_height = checkFiniteNumber((rect.h - top_val_axis_gap - first_val_axis_label_half_height)/(arr_val[arr_val.length - 1] - arr_val[0])); cat_labels_align_bottom = false;//в данном случае подписи будут выравниваться по верхнему краю блока с подписями cat_ax.posY = rect.y + rect.h - first_val_axis_label_half_height - (crosses_val_ax - arr_val[0])*unit_height; if(cat_ax.labels) cat_ax.labels.y = cat_ax.posY - cat_ax_ext_y; } else{ unit_height = checkFiniteNumber(rect.h/(arr_val[arr_val.length - 1] - arr_val[0])); cat_labels_align_bottom = false;//в данном случае подписи будут выравниваться по верхнему краю блока с подписями cat_ax.posY = rect.y + rect.h - (crosses_val_ax - arr_val[0])*unit_height; if(cat_ax.labels){ cat_ax.labels.y = cat_ax.posY - cat_ax_ext_y; if(true){ var bCorrectedCat = false; if(cat_ax.labels.y < 0){ rect.y -= cat_ax.labels.y; rect.h += cat_ax.labels.y; cat_ax.labels.y = 0; bCorrectedCat = true; } if(cat_ax.labels.y + cat_ax.labels.extY > this.extY){ rect.h -= (cat_ax.labels.y + cat_ax.labels.extY - this.extY); bCorrectedCat = true; } if(bCorrectedCat){ unit_height = checkFiniteNumber(rect.h/(arr_val[arr_val.length - 1] - arr_val[0])); cat_labels_align_bottom = false;//в данном случае подписи будут выравниваться по верхнему краю блока с подписями cat_ax.posY = rect.y + rect.h - (crosses_val_ax - arr_val[0])*unit_height; } } } } } else { if(!bWithoutLabels){ var bottom_points_height = first_val_axis_label_half_height + (crosses_val_ax - arr_val[0])*unit_height;//высота области под горизонтальной осью if(bottom_points_height < cat_ax_ext_y) { unit_height = checkFiniteNumber((rect.h - last_val_axis_label_half_height - cat_ax_ext_y)/(arr_val[arr_val.length-1] - crosses_val_ax)); } cat_ax.posY = rect.y + last_val_axis_label_half_height + (arr_val[arr_val.length-1] - crosses_val_ax)*unit_height; if(cat_ax.labels) cat_ax.labels.y = cat_ax.posY; } else{ cat_ax.posY = rect.y + (arr_val[arr_val.length-1] - crosses_val_ax)*unit_height; if(cat_ax.labels){ cat_ax.labels.y = cat_ax.posY; if(true){ var bCorrectedCat = false; if(cat_ax.labels.y < 0){ rect.y -= cat_ax.labels.y; rect.h += cat_ax.labels.y; cat_ax.labels.y = 0; bCorrectedCat = true; } if(cat_ax.labels.y + cat_ax.labels.extY > this.extY){ rect.h -= (cat_ax.labels.y + cat_ax.labels.extY - this.extY); bCorrectedCat = true; } if(bCorrectedCat){ unit_height = checkFiniteNumber(rect.h/(arr_val[arr_val.length - 1] - arr_val[0])); cat_ax.posY = rect.y + (arr_val[arr_val.length-1] - crosses_val_ax)*unit_height; cat_ax.labels.y = cat_ax.posY; } } } } } for(i = 0; i < arr_val.length; ++i) arr_val_labels_points[i] = cat_ax.posY - (arr_val[i] - crosses_val_ax)*unit_height; } else if(hor_labels_pos === c_oAscTickLabelsPos.TICK_LABEL_POSITION_LOW) { if(!bWithoutLabels){ bottom_val_axis_gap = Math.max(cat_ax_ext_y, first_val_axis_label_half_height); unit_height = checkFiniteNumber((rect.h - bottom_val_axis_gap - last_val_axis_label_half_height)/(arr_val[arr_val.length - 1] - arr_val[0])); cat_ax.posY = rect.y + last_val_axis_label_half_height + (arr_val[arr_val.length-1] - crosses_val_ax)*unit_height; if(cat_ax.labels) cat_ax.labels.y = rect.y + rect.h - bottom_val_axis_gap; for(i = 0; i < arr_val.length; ++i) arr_val_labels_points[i] = cat_ax.posY - (arr_val[i] - crosses_val_ax)*unit_height; } else{ unit_height = checkFiniteNumber(rect.h/(arr_val[arr_val.length - 1] - arr_val[0])); cat_ax.posY = rect.y + (arr_val[arr_val.length-1] - crosses_val_ax)*unit_height; if(cat_ax.labels){ cat_ax.labels.y = rect.y + rect.h; if(true){ var bCorrectedCat = false; if(cat_ax.labels.y < 0){ rect.y -= cat_ax.labels.y; rect.h += cat_ax.labels.y; cat_ax.labels.y = 0; bCorrectedCat = true; } if(cat_ax.labels.y + cat_ax.labels.extY > this.extY){ rect.h -= (cat_ax.labels.y + cat_ax.labels.extY - this.extY); bCorrectedCat = true; } if(bCorrectedCat){ unit_height = checkFiniteNumber(rect.h/(arr_val[arr_val.length - 1] - arr_val[0])); cat_ax.posY = rect.y + (arr_val[arr_val.length-1] - crosses_val_ax)*unit_height; cat_ax.labels.y = rect.y + rect.h; } } } for(i = 0; i < arr_val.length; ++i) arr_val_labels_points[i] = cat_ax.posY - (arr_val[i] - crosses_val_ax)*unit_height; } } else if(hor_labels_pos === c_oAscTickLabelsPos.TICK_LABEL_POSITION_HIGH) { if(!bWithoutLabels){ top_val_axis_gap = Math.max(last_val_axis_label_half_height, cat_ax_ext_y); unit_height = checkFiniteNumber((rect.h - top_val_axis_gap - first_val_axis_label_half_height)/(arr_val[arr_val.length - 1] - arr_val[0])); cat_labels_align_bottom = false;//в данном случае подписи будут выравниваться по верхнему краю блока с подписями cat_ax.posY = rect.y + rect.h - first_val_axis_label_half_height - (crosses_val_ax - arr_val[0])*unit_height; if(cat_ax.labels) cat_ax.labels.y = rect.y + top_val_axis_gap - cat_ax_ext_y; for(i = 0; i < arr_val.length; ++i) arr_val_labels_points[i] = cat_ax.posY - (arr_val[i] - crosses_val_ax)*unit_height; } else{ unit_height = checkFiniteNumber(rect.h/(arr_val[arr_val.length - 1] - arr_val[0])); cat_labels_align_bottom = false;//в данном случае подписи будут выравниваться по верхнему краю блока с подписями cat_ax.posY = rect.y + rect.h - (crosses_val_ax - arr_val[0])*unit_height; if(cat_ax.labels){ cat_ax.labels.y = rect.y - cat_ax_ext_y; if(true){ var bCorrectedCat = false; if(cat_ax.labels.y < 0){ rect.y -= cat_ax.labels.y; rect.h += cat_ax.labels.y; cat_ax.labels.y = 0; bCorrectedCat = true; } if(cat_ax.labels.y + cat_ax.labels.extY > this.extY){ rect.h -= (cat_ax.labels.y + cat_ax.labels.extY - this.extY); bCorrectedCat = true; } if(bCorrectedCat){ unit_height = checkFiniteNumber(rect.h/(arr_val[arr_val.length - 1] - arr_val[0])); cat_ax.posY = rect.y + rect.h - (crosses_val_ax - arr_val[0])*unit_height; cat_ax.labels.y = rect.y - cat_ax_ext_y; } } } for(i = 0; i < arr_val.length; ++i) arr_val_labels_points[i] = cat_ax.posY - (arr_val[i] - crosses_val_ax)*unit_height; } } else { //подписей осей нет cat_ax.labels = null; if(!bWithoutLabels){ for(i = 0; i < arr_val.length; ++i) arr_val_labels_points[i] = rect.y + rect.h - first_val_axis_label_half_height - (arr_val[i] - arr_val[0])*unit_height; cat_ax.posY = rect.y + rect.h - first_val_axis_label_half_height - (crosses_val_ax - arr_val[0])*unit_height; } else{ for(i = 0; i < arr_val.length; ++i) arr_val_labels_points[i] = rect.y + rect.h - (arr_val[i] - arr_val[0])*unit_height; cat_ax.posY = rect.y + rect.h - (crosses_val_ax - arr_val[0])*unit_height; } } } else {//зеркально отражаем if(hor_labels_pos === c_oAscTickLabelsPos.TICK_LABEL_POSITION_NEXT_TO || !AscFormat.isRealNumber(hor_labels_pos)) { if(cat_ax.crosses === AscFormat.CROSSES_MAX) { if(!bWithoutLabels){ bottom_val_axis_gap = Math.max(cat_ax_ext_y, last_val_axis_label_half_height); unit_height = checkFiniteNumber((rect.h - bottom_val_axis_gap - first_val_axis_label_half_height)/(arr_val[arr_val.length - 1] - arr_val[0])); cat_ax.posY = rect.y + first_val_axis_label_half_height + (crosses_val_ax - arr_val[0])*unit_height; if(cat_ax.labels) cat_ax.labels.y = rect.y + rect.h - bottom_val_axis_gap; } else{ unit_height = checkFiniteNumber(rect.h/(arr_val[arr_val.length - 1] - arr_val[0])); cat_ax.posY = rect.y + (crosses_val_ax - arr_val[0])*unit_height; if(cat_ax.labels){ cat_ax.labels.y = rect.y + rect.h; if(true){ var bCorrectedCat = false; if(cat_ax.labels.y < 0){ rect.y -= cat_ax.labels.y; rect.h += cat_ax.labels.y; cat_ax.labels.y = 0; bCorrectedCat = true; } if(cat_ax.labels.y + cat_ax.labels.extY > this.extY){ rect.h -= (cat_ax.labels.y + cat_ax.labels.extY - this.extY); bCorrectedCat = true; } if(bCorrectedCat){ unit_height = checkFiniteNumber(rect.h/(arr_val[arr_val.length - 1] - arr_val[0])); cat_ax.posY = rect.y + (crosses_val_ax - arr_val[0])*unit_height; cat_ax.labels.y = rect.y + rect.h; } } } } } else { cat_labels_align_bottom = false; if(!bWithoutLabels){ var top_points_height = first_val_axis_label_half_height + (crosses_val_ax - arr_val[0])*unit_height; if(top_points_height < cat_ax_ext_y) { unit_height = checkFiniteNumber((rect.h - cat_ax_ext_y - last_val_axis_label_half_height)/(arr_val[arr_val.length-1] - crosses_val_ax)); } cat_ax.posY = rect.y + rect.h - last_val_axis_label_half_height - (arr_val[arr_val.length-1] - crosses_val_ax)*unit_height; if(cat_ax.labels) cat_ax.labels.y = cat_ax.posY - cat_ax_ext_y; } else{ cat_ax.posY = rect.y + rect.h - (arr_val[arr_val.length-1] - crosses_val_ax)*unit_height; if(cat_ax.labels){ cat_ax.labels.y = cat_ax.posY - cat_ax_ext_y; if(true){ var bCorrectedCat = false; if(cat_ax.labels.y < 0){ rect.y -= cat_ax.labels.y; rect.h += cat_ax.labels.y; cat_ax.labels.y = 0; bCorrectedCat = true; } if(cat_ax.labels.y + cat_ax.labels.extY > this.extY){ rect.h -= (cat_ax.labels.y + cat_ax.labels.extY - this.extY); bCorrectedCat = true; } if(bCorrectedCat){ unit_height = checkFiniteNumber(rect.h/(arr_val[arr_val.length - 1] - arr_val[0])); cat_ax.posY = rect.y + rect.h - (arr_val[arr_val.length-1] - crosses_val_ax)*unit_height; cat_ax.labels.y = cat_ax.posY - cat_ax_ext_y; } } } } } for(i = 0; i < arr_val.length; ++i) arr_val_labels_points[i] = cat_ax.posY + (arr_val[i] - crosses_val_ax)*unit_height; } else if(hor_labels_pos === c_oAscTickLabelsPos.TICK_LABEL_POSITION_LOW) { cat_labels_align_bottom = false; if(!bWithoutLabels){ top_val_axis_gap = Math.max(first_val_axis_label_half_height, cat_ax_ext_y); unit_height = checkFiniteNumber((rect.h - top_val_axis_gap - last_val_axis_label_half_height)/(arr_val[arr_val.length-1] - arr_val[0])); cat_ax.posY = rect.y + rect.h - last_val_axis_label_half_height - (arr_val[arr_val.length-1] - crosses_val_ax)*unit_height; for(i = 0; i < arr_val.length; ++i) arr_val_labels_points[i] = cat_ax.posY + (arr_val[i] - crosses_val_ax)*unit_height; if(cat_ax.labels) cat_ax.labels.y = cat_ax.posY + (arr_val[0] - crosses_val_ax)*unit_height - cat_ax_ext_y; } else{ unit_height = checkFiniteNumber(rect.h/(arr_val[arr_val.length-1] - arr_val[0])); cat_ax.posY = rect.y + rect.h - (arr_val[arr_val.length-1] - crosses_val_ax)*unit_height; for(i = 0; i < arr_val.length; ++i) arr_val_labels_points[i] = cat_ax.posY + (arr_val[i] - crosses_val_ax)*unit_height; if(cat_ax.labels) { cat_ax.labels.y = cat_ax.posY + (arr_val[0] - crosses_val_ax)*unit_height - cat_ax_ext_y; if(true){ var bCorrectedCat = false; if(cat_ax.labels.y < 0){ rect.y -= cat_ax.labels.y; rect.h += cat_ax.labels.y; cat_ax.labels.y = 0; bCorrectedCat = true; } if(cat_ax.labels.y + cat_ax.labels.extY > this.extY){ rect.h -= (cat_ax.labels.y + cat_ax.labels.extY - this.extY); bCorrectedCat = true; } if(bCorrectedCat){ unit_height = checkFiniteNumber(rect.h/(arr_val[arr_val.length-1] - arr_val[0])); cat_ax.posY = rect.y + rect.h - (arr_val[arr_val.length-1] - crosses_val_ax)*unit_height; for(i = 0; i < arr_val.length; ++i) arr_val_labels_points[i] = cat_ax.posY + (arr_val[i] - crosses_val_ax)*unit_height; cat_ax.labels.y = cat_ax.posY + (arr_val[0] - crosses_val_ax)*unit_height - cat_ax_ext_y; } } } } } else if(hor_labels_pos === c_oAscTickLabelsPos.TICK_LABEL_POSITION_HIGH) { if(!bWithoutLabels){ bottom_val_axis_gap = Math.max(cat_ax_ext_y, last_val_axis_label_half_height); unit_height = checkFiniteNumber((rect.h - bottom_val_axis_gap - first_val_axis_label_half_height)/(arr_val[arr_val.length-1] - arr_val[0])); cat_ax.posY = rect.y + first_val_axis_label_half_height + (crosses_val_ax - arr_val[0])*unit_height; for(i = 0; i < arr_val.length; ++i) arr_val_labels_points[i] = cat_ax.posY + (arr_val[i] - crosses_val_ax)*unit_height; if(cat_ax.labels) cat_ax.labels.y = rect.y + rect.h - bottom_val_axis_gap; } else{ unit_height = checkFiniteNumber(rect.h/(arr_val[arr_val.length-1] - arr_val[0])); cat_ax.posY = rect.y + (crosses_val_ax - arr_val[0])*unit_height; for(i = 0; i < arr_val.length; ++i) arr_val_labels_points[i] = cat_ax.posY + (arr_val[i] - crosses_val_ax)*unit_height; if(cat_ax.labels){ cat_ax.labels.y = rect.y + rect.h; if(true){ var bCorrectedCat = false; if(cat_ax.labels.y < 0){ rect.y -= cat_ax.labels.y; rect.h += cat_ax.labels.y; cat_ax.labels.y = 0; bCorrectedCat = true; } if(cat_ax.labels.y + cat_ax.labels.extY > this.extY){ rect.h -= (cat_ax.labels.y + cat_ax.labels.extY - this.extY); bCorrectedCat = true; } if(bCorrectedCat){ unit_height = checkFiniteNumber(rect.h/(arr_val[arr_val.length-1] - arr_val[0])); cat_ax.posY = rect.y + (crosses_val_ax - arr_val[0])*unit_height; for(i = 0; i < arr_val.length; ++i) arr_val_labels_points[i] = cat_ax.posY + (arr_val[i] - crosses_val_ax)*unit_height; cat_ax.labels.y = rect.y + rect.h; } } } } } else {//подписей осей нет cat_ax.labels = null; if(!bWithoutLabels){ unit_height = checkFiniteNumber((rect.h - last_val_axis_label_half_height - first_val_axis_label_half_height)/(arr_val[arr_val.length-1] - arr_val[0])); for(i = 0; i < arr_val.length; ++i) arr_val_labels_points[i] = rect.y + first_val_axis_label_half_height + (arr_val[i] - arr_val[0])*unit_height; } else{ unit_height = checkFiniteNumber(rect.h/(arr_val[arr_val.length-1] - arr_val[0])); for(i = 0; i < arr_val.length; ++i) arr_val_labels_points[i] = rect.y + (arr_val[i] - arr_val[0])*unit_height; } } } cat_ax.interval = unit_height; //запишем в оси необходимую информацию для отрисовщика plotArea и выставим окончательные позиции для подписей var arr_labels, transform_text, local_text_transform; if(val_ax.labels) { if(bNeedReflect) { if(left_val_ax_labels_align) { left_val_ax_labels_align = false; val_ax.labels.x += val_ax.labels.extX; } else { left_val_ax_labels_align = true; val_ax.labels.x -= val_ax.labels.extX; } } val_ax.labels.align = left_val_ax_labels_align; val_ax.labels.y = Math.min.apply(Math, arr_val_labels_points) - max_val_labels_text_height/2; val_ax.labels.extY = Math.max.apply(Math, arr_val_labels_points) - Math.min.apply(Math, arr_val_labels_points) + max_val_labels_text_height; arr_labels = val_ax.labels.aLabels; if(left_val_ax_labels_align) { for(i = 0; i < arr_labels.length; ++i) { arr_labels[i].txBody = arr_labels[i].tx.rich; transform_text = arr_labels[i].transformText; transform_text.Reset(); global_MatrixTransformer.TranslateAppend(transform_text, val_ax.labels.x + val_ax.labels.extX - val_axis_labels_gap - arr_labels[i].tx.rich.content.XLimit, arr_val_labels_points[i] - val_ax.labels.aLabels[i].tx.rich.content.GetSummaryHeight()/2); // global_MatrixTransformer.MultiplyAppend(transform_text, this.getTransformMatrix()); local_text_transform = arr_labels[i].localTransformText; local_text_transform.Reset(); global_MatrixTransformer.TranslateAppend(local_text_transform, val_ax.labels.x + val_ax.labels.extX - val_axis_labels_gap - arr_labels[i].tx.rich.content.XLimit, arr_val_labels_points[i] - val_ax.labels.aLabels[i].tx.rich.content.GetSummaryHeight()/2); } } else { var left_line = val_ax.labels.x + val_axis_labels_gap; for(i = 0; i < arr_labels.length; ++i) { arr_labels[i].txBody = arr_labels[i].tx.rich; transform_text = arr_labels[i].transformText; transform_text.Reset(); global_MatrixTransformer.TranslateAppend(transform_text, left_line, arr_val_labels_points[i] - val_ax.labels.aLabels[i].tx.rich.content.GetSummaryHeight()/2); // global_MatrixTransformer.MultiplyAppend(transform_text, this.getTransformMatrix()); local_text_transform = arr_labels[i].localTransformText; local_text_transform.Reset(); global_MatrixTransformer.TranslateAppend(local_text_transform, left_line, arr_val_labels_points[i] - val_ax.labels.aLabels[i].tx.rich.content.GetSummaryHeight()/2); } } } val_ax.yPoints = []; for(i = 0; i < arr_val_labels_points.length; ++i) { val_ax.yPoints[i] = {val:arr_val[i], pos: arr_val_labels_points[i]}; } cat_ax.xPoints = []; for(i = 0; i <arr_cat_labels_points.length; ++i) { cat_ax.xPoints[i] = {val: i, pos: arr_cat_labels_points[i]}; } if(cat_ax.labels) { cat_ax.labels.align = cat_labels_align_bottom; if(!b_rotated)//подписи не повернутые { if(cat_ax_orientation === AscFormat.ORIENTATION_MIN_MAX) { cat_ax.labels.x = arr_cat_labels_points[0] - max_cat_label_width/2; } else { cat_ax.labels.x = arr_cat_labels_points[arr_cat_labels_points.length-1] - max_cat_label_width/2; } cat_ax.labels.extX = arr_cat_labels_points[arr_cat_labels_points.length-1] + max_cat_label_width/2 - cat_ax.labels.x; if(cat_labels_align_bottom) { for(i = 0; i < cat_ax.labels.aLabels.length; ++i) { if(cat_ax.labels.aLabels[i]) { var label_text_transform = cat_ax.labels.aLabels[i].transformText; label_text_transform.Reset(); global_MatrixTransformer.TranslateAppend(label_text_transform, arr_cat_labels_points[i] - max_cat_label_width/2, cat_ax.labels.y + labels_offset); // global_MatrixTransformer.MultiplyAppend(label_text_transform, this.getTransformMatrix()); local_text_transform = cat_ax.labels.aLabels[i].localTransformText; local_text_transform.Reset(); global_MatrixTransformer.TranslateAppend(local_text_transform, arr_cat_labels_points[i] - max_cat_label_width/2, cat_ax.labels.y + labels_offset); } } } else { for(i = 0; i < cat_ax.labels.aLabels.length; ++i) { if(cat_ax.labels.aLabels[i]) { var label_text_transform = cat_ax.labels.aLabels[i].transformText; label_text_transform.Reset(); global_MatrixTransformer.TranslateAppend(label_text_transform, arr_cat_labels_points[i] - max_cat_label_width/2, cat_ax.labels.y + cat_ax.labels.extY - labels_offset - cat_ax.labels.aLabels[i].tx.rich.content.GetSummaryHeight()); // global_MatrixTransformer.MultiplyAppend(label_text_transform, this.getTransformMatrix()); local_text_transform = cat_ax.labels.aLabels[i].localTransformText; local_text_transform.Reset(); global_MatrixTransformer.TranslateAppend(local_text_transform, arr_cat_labels_points[i] - max_cat_label_width/2, cat_ax.labels.y + cat_ax.labels.extY - labels_offset - cat_ax.labels.aLabels[i].tx.rich.content.GetSummaryHeight()); } } } } else { var left_x, right_x; var w2, h2, x1, xc, yc, y0; if(cat_labels_align_bottom) { for(i = 0; i < cat_ax.labels.aLabels.length; ++i) { if(cat_ax.labels.aLabels[i]) { var label_text_transform = cat_ax.labels.aLabels[i].transformText; cat_ax.labels.aLabels[i].tx.rich.content.Set_ApplyToAll(true); cat_ax.labels.aLabels[i].tx.rich.content.SetParagraphAlign(AscCommon.align_Left); cat_ax.labels.aLabels[i].tx.rich.content.Set_ApplyToAll(false); var wh = cat_ax.labels.aLabels[i].tx.rich.getContentOneStringSizes();//Todo: не расчитывать больше контент w2 = wh.w*Math.cos(Math.PI/4) + wh.h*Math.sin(Math.PI/4); h2 = wh.w*Math.sin(Math.PI/4) + wh.h*Math.cos(Math.PI/4); x1 = arr_cat_labels_points[i] + wh.h*Math.sin(Math.PI/4); y0 = cat_ax.labels.y + labels_offset; xc = x1 - w2/2; yc = y0 + h2/2; label_text_transform.Reset(); global_MatrixTransformer.TranslateAppend(label_text_transform, -wh.w/2, -wh.h/2); global_MatrixTransformer.RotateRadAppend(label_text_transform, Math.PI/4);//TODO global_MatrixTransformer.TranslateAppend(label_text_transform, xc, yc); global_MatrixTransformer.MultiplyAppend(label_text_transform,this.transform); if(!AscFormat.isRealNumber(left_x)) { left_x = xc - w2/2; right_x = xc + w2/2; } else { if(xc - w2/2 < left_x) left_x = xc - w2/2; if(xc + w2/2 > right_x) right_x = xc + w2/2; } local_text_transform = cat_ax.labels.aLabels[i].localTransformText; local_text_transform.Reset(); global_MatrixTransformer.TranslateAppend(local_text_transform, -wh.w/2, -wh.h/2); global_MatrixTransformer.RotateRadAppend(local_text_transform, Math.PI/4);//TODO global_MatrixTransformer.TranslateAppend(local_text_transform, xc, yc); } } } else { for(i = 0; i < cat_ax.labels.aLabels.length; ++i) { if(cat_ax.labels.aLabels[i]) { var label_text_transform = cat_ax.labels.aLabels[i].transformText; cat_ax.labels.aLabels[i].tx.rich.content.Set_ApplyToAll(true); cat_ax.labels.aLabels[i].tx.rich.content.SetParagraphAlign(AscCommon.align_Left); cat_ax.labels.aLabels[i].tx.rich.content.Set_ApplyToAll(false); var wh = cat_ax.labels.aLabels[i].tx.rich.getContentOneStringSizes();//Todo: не расчитывать больше контент w2 = wh.w*Math.cos(Math.PI/4) + wh.h*Math.sin(Math.PI/4); h2 = wh.w*Math.sin(Math.PI/4) + wh.h*Math.cos(Math.PI/4); x1 = arr_cat_labels_points[i] - wh.h*Math.sin(Math.PI/4); y0 = cat_ax.labels.y + cat_ax.labels.extY - labels_offset; xc = x1 + w2/2; yc = y0 - h2/2; label_text_transform.Reset(); global_MatrixTransformer.TranslateAppend(label_text_transform, -wh.w/2, -wh.h/2); global_MatrixTransformer.RotateRadAppend(label_text_transform, Math.PI/4);//TODO global_MatrixTransformer.TranslateAppend(label_text_transform, xc, yc); global_MatrixTransformer.MultiplyAppend(label_text_transform,this.transform); if(!AscFormat.isRealNumber(left_x)) { left_x = xc - w2/2; right_x = xc + w2/2; } else { if(xc - w2/2 < left_x) left_x = xc - w2/2; if(xc + w2/2 > right_x) right_x = xc + w2/2; } local_text_transform = cat_ax.labels.aLabels[i].localTransformText; local_text_transform.Reset(); global_MatrixTransformer.TranslateAppend(local_text_transform, -wh.w/2, -wh.h/2); global_MatrixTransformer.RotateRadAppend(local_text_transform, Math.PI/4);//TODO global_MatrixTransformer.TranslateAppend(local_text_transform, xc, yc); } } } cat_ax.labels.x = left_x; cat_ax.labels.extX = right_x - left_x; } } cat_ax.xPoints.sort(function(a, b){return a.val - b.val}); val_ax.yPoints.sort(function(a, b){return a.val - b.val}); } else{ this.bEmptySeries = true; } } else if(chart_type === AscDFH.historyitem_type_BarChart && chart_object.barDir === AscFormat.BAR_DIR_BAR) { var cat_ax, val_ax; var axis_by_types = chart_object.getAxisByTypes(); cat_ax = axis_by_types.catAx[0]; val_ax = axis_by_types.valAx[0]; if(cat_ax && val_ax) { /*---------------------new version---------------------------------------*/ val_ax.labels = null; cat_ax.labels = null; val_ax.posX = null; cat_ax.posY = null; val_ax.posY = null; cat_ax.posX = null; val_ax.xPoints = null; cat_ax.yPoints = null; val_ax.yPoints = null; cat_ax.xPoints = null; val_ax.transformYPoints = null; cat_ax.transformXPoints = null; val_ax.transformXPoints = null; cat_ax.transformYPoints = null; var sizes = this.getChartSizes(); rect = {x: sizes.startX, y:sizes.startY, w:sizes.w, h: sizes.h}; var arr_val = this.getValAxisValues(); //Получим строки для оси значений с учетом формата и единиц var arr_strings = []; var multiplier; if(val_ax.dispUnits) multiplier = val_ax.dispUnits.getMultiplier(); else multiplier = 1; var num_fmt = val_ax.numFmt; if(num_fmt && typeof num_fmt.formatCode === "string" /*&& !(num_fmt.formatCode === "General")*/) { var num_format = oNumFormatCache.get(num_fmt.formatCode); for(i = 0; i < arr_val.length; ++i) { var calc_value = arr_val[i]*multiplier; var rich_value = num_format.formatToChart(calc_value); arr_strings.push(rich_value); } } else { for(i = 0; i < arr_val.length; ++i) { var calc_value = arr_val[i]*multiplier; arr_strings.push(calc_value + ""); } } //расчитаем подписи горизонтальной оси значений val_ax.labels = new AscFormat.CValAxisLabels(this, val_ax); var max_height = 0; val_ax.xPoints = []; var max_val_ax_label_width = 0; for(i = 0; i < arr_strings.length; ++i) { var dlbl = new AscFormat.CDLbl(); dlbl.parent = val_ax; dlbl.chart = this; dlbl.spPr = val_ax.spPr; dlbl.txPr = val_ax.txPr; dlbl.tx = new AscFormat.CChartText(); dlbl.tx.rich = AscFormat.CreateTextBodyFromString(arr_strings[i], this.getDrawingDocument(), dlbl); dlbl.txBody = dlbl.tx.rich; if(val_ax.labels.aLabels[0]) { dlbl.lastStyleObject = val_ax.labels.aLabels[0].lastStyleObject; } var t = dlbl.tx.rich.recalculateByMaxWord(); var h = t.h; if(t.w > max_val_ax_label_width) max_val_ax_label_width = t.w; if(h > max_height) max_height = h; val_ax.labels.aLabels.push(dlbl); val_ax.xPoints.push({val: arr_val[i], pos: null}); } var val_axis_labels_gap = val_ax.labels.aLabels[0].tx.rich.content.Content[0].CompiledPr.Pr.TextPr.FontSize*25.4/72; val_ax.labels.extY = max_height + val_axis_labels_gap; //расчитаем подписи для горизонтальной оси var ser = chart_object.series[0]; var string_pts = [], pts_len = 0; /*string_pts pts_len*/ if(ser && ser.cat) { var lit, b_num_lit = true; if(ser.cat.strRef && ser.cat.strRef.strCache) { lit = ser.cat.strRef.strCache; } else if(ser.cat.strLit) { lit = ser.cat.strLit; } else if(ser.cat.numRef && ser.cat.numRef.numCache) { lit = ser.cat.numRef.numCache; b_num_lit = true; } else if(ser.cat.numLit) { lit = ser.cat.numLit; b_num_lit = true; } if(lit) { var lit_format = null, pt_format = null; if(b_num_lit && typeof lit.formatCode === "string" && lit.formatCode.length > 0) { lit_format = oNumFormatCache.get(lit.formatCode); } pts_len = lit.ptCount; for(i = 0; i < pts_len; ++i) { var pt = lit.getPtByIndex(i); if(pt) { var str_pt; if(b_num_lit) { if(typeof pt.formatCode === "string" && pt.formatCode.length > 0) { pt_format = oNumFormatCache.get(pt.formatCode); if(pt_format) { str_pt = pt_format.formatToChart(pt.val); } else { str_pt = pt.val; } } else if(lit_format) { str_pt = lit_format.formatToChart(pt.val); } else { str_pt = pt.val; } } else { str_pt = pt.val; } string_pts.push({val: str_pt + ""}); } else { string_pts.push({val: i + ""}); } } } } //if(string_pts.length === 0) { pts_len = 0; for(i = 0; i < chart_object.series.length; ++i) { var cur_pts= null; ser = chart_object.series[i]; if(ser.val) { if(ser.val.numRef && ser.val.numRef.numCache) cur_pts = ser.val.numRef.numCache; else if(ser.val.numLit) cur_pts = ser.val.numLit; if(cur_pts) { pts_len = Math.max(pts_len, cur_pts.ptCount); } } } if(pts_len > string_pts.length) { for(i = string_pts.length; i < pts_len; ++i) { string_pts.push({val:i+1 + ""}); } } else { string_pts.splice(pts_len, string_pts.length - pts_len); } } /*---------------------расчет позиции блока с подписями вертикальной оси-----------------------------------------------------------------------------*/ //расчитаем ширину интервала без учета горизонтальной оси; var crosses;//номер категории в которой вертикалная ось пересекает горизонтальную; if(val_ax.crosses === AscFormat.CROSSES_AUTO_ZERO || val_ax.crosses === AscFormat.CROSSES_MIN) crosses = 1; else if(val_ax.crosses === AscFormat.CROSSES_MAX) crosses = string_pts.length; else if(AscFormat.isRealNumber(val_ax.crossesAt)) { if(val_ax.crossesAt <= string_pts.length + 1 && val_ax.crossesAt > 0) crosses = val_ax.crossesAt; else if(val_ax.crossesAt <= 0) crosses = 1; else crosses = string_pts.length; } else crosses = 1; cat_ax.maxCatVal = string_pts.length; var cat_ax_orientation = cat_ax.scaling && AscFormat.isRealNumber(cat_ax.scaling.orientation) ? cat_ax.scaling.orientation : AscFormat.ORIENTATION_MIN_MAX; var labels_pos = val_ax.tickLblPos; var cross_between = this.getValAxisCrossType(); if(cross_between === null){ cross_between = AscFormat.CROSS_BETWEEN_BETWEEN; } var bottom_val_ax_labels_align = true;//приленгание подписей оси значений к левому краю. var intervals_count = cross_between === AscFormat.CROSS_BETWEEN_MID_CAT ? string_pts.length - 1 : string_pts.length; var point_interval = rect.h/intervals_count;//интервал между точками. Зависит от crossBetween, а также будет потом корректироваться в зависимости от подписей вертикальной и горизонтальной оси. var bottom_points_height, top_point_height; var arr_cat_labels_points = [];//массив середин подписей горизонтальной оси; i-й элемент - x-координата центра подписи категории с номером i; if(cat_ax_orientation === AscFormat.ORIENTATION_MIN_MAX) { if(labels_pos === c_oAscTickLabelsPos.TICK_LABEL_POSITION_NONE || val_ax.bDelete === true) { val_ax.labels = null; if(cross_between === AscFormat.CROSS_BETWEEN_MID_CAT) { for(i = 0; i < string_pts.length; ++i) arr_cat_labels_points[i] = rect.y + rect.h - point_interval*i; } else { for(i = 0; i < string_pts.length; ++i) arr_cat_labels_points[i] = rect.y + rect.h - (point_interval/2 + point_interval*i); } val_ax.posY = rect.y + rect.h - point_interval*(crosses-1); } else if(labels_pos === c_oAscTickLabelsPos.TICK_LABEL_POSITION_NEXT_TO || !AscFormat.isRealNumber(labels_pos)) //подписи рядом с осью { if(val_ax.crosses === AscFormat.CROSSES_MAX) { if(!bWithoutLabels){ val_ax.labels.y = rect.y; point_interval = checkFiniteNumber((rect.h - val_ax.labels.extY)/intervals_count); } else{ val_ax.labels.y = rect.y - val_ax.labels.extY; } bottom_val_ax_labels_align = false; val_ax.posY = val_ax.labels.y + val_ax.labels.extY; if(cross_between === AscFormat.CROSS_BETWEEN_MID_CAT) { for(i = 0; i < string_pts.length; ++i) arr_cat_labels_points[i] = rect.y + rect.h - point_interval*i; } else { for(i = 0; i < string_pts.length; ++i) arr_cat_labels_points[i] = point_interval/2 + rect.y + rect.h - point_interval*i; } } else { bottom_points_height = point_interval*(crosses-1);//общая ширина левых точек если считать что точки занимают все пространство if(bottom_points_height < val_ax.labels.extY && !bWithoutLabels)//подписи верт. оси выходят за пределы области построения { var top_intervals_count = intervals_count - (crosses - 1);//количесво интервалов выше горизонтальной оси //скорректируем point_interval, поделив расстояние, которое осталось справа от подписей осей на количество интервалов справа point_interval = checkFiniteNumber((rect.h - val_ax.labels.extY)/top_intervals_count); val_ax.labels.y = rect.y + rect.h - val_ax.labels.extY; var start_point = val_ax.labels.y + (crosses-1)*point_interval;//y-координата точки низа области постоения if(cross_between === AscFormat.CROSS_BETWEEN_MID_CAT) { for(i = 0; i < string_pts.length; ++i) arr_cat_labels_points[i] = start_point - point_interval*i; } else { for(i = 0; i < string_pts.length; ++i) arr_cat_labels_points[i] = start_point - point_interval/2 - point_interval*i; } } else { val_ax.labels.y = rect.y + rect.h - bottom_points_height; if(cross_between === AscFormat.CROSS_BETWEEN_MID_CAT) { for(i = 0; i < string_pts.length; ++i) arr_cat_labels_points[i] = rect.y + rect.h - point_interval*i; } else { for(i = 0; i < string_pts.length; ++i) arr_cat_labels_points[i] = rect.y + rect.h - (point_interval/2 + point_interval*i); } } val_ax.posY = val_ax.labels.y; } } else if(labels_pos === c_oAscTickLabelsPos.TICK_LABEL_POSITION_LOW)//подписи снизу от области построения { if(!bWithoutLabels){ point_interval = checkFiniteNumber((rect.h - val_ax.labels.extY)/intervals_count); val_ax.labels.y = rect.y + rect.h - val_ax.labels.extY; } else{ val_ax.labels.y = rect.y + rect.h; } if(cross_between === AscFormat.CROSS_BETWEEN_MID_CAT) { for(i = 0; i < string_pts.length; ++i) arr_cat_labels_points[i] = val_ax.labels.y - point_interval*i; } else { for(i = 0; i < string_pts.length; ++i) arr_cat_labels_points[i] = rect.y + rect.h - val_ax.labels.extY - point_interval/2 - point_interval*i; } val_ax.posY = val_ax.labels.y - point_interval*(crosses-1); } else if(labels_pos === c_oAscTickLabelsPos.TICK_LABEL_POSITION_HIGH)//подписи сверху от области построения { if(!bWithoutLabels){ point_interval = checkFiniteNumber((rect.h - val_ax.labels.extY)/intervals_count); val_ax.labels.y = rect.y; } else{ val_ax.labels.y = rect.y - val_ax.labels.extY; } point_interval = checkFiniteNumber((rect.h - val_ax.labels.extY)/intervals_count); val_ax.labels.y = rect.y; bottom_val_ax_labels_align = false; if(cross_between === AscFormat.CROSS_BETWEEN_MID_CAT) { for(i = 0; i < string_pts.length; ++i) arr_cat_labels_points[i] = rect.y + rect.h - point_interval*i; } else { for(i = 0; i < string_pts.length; ++i) arr_cat_labels_points[i] =rect.y + rect.h - (point_interval/2 + point_interval*i); } val_ax.posY = rect.y + rect.h - point_interval*(crosses-1); } else { val_ax.labels = null; if(cross_between === AscFormat.CROSS_BETWEEN_MID_CAT) { for(i = 0; i < string_pts.length; ++i) arr_cat_labels_points[i] = rect.y + rect.h - point_interval*i; } else { for(i = 0; i < string_pts.length; ++i) arr_cat_labels_points[i] = rect.y + rect.h - (point_interval/2 + point_interval*i); } val_ax.posY = rect.y + rect.h - point_interval*(crosses-1); } } else {//то же самое, только зеркально отраженное if(labels_pos === c_oAscTickLabelsPos.TICK_LABEL_POSITION_NONE || val_ax.bDelete === true) { val_ax.labels = null; if(cross_between === AscFormat.CROSS_BETWEEN_MID_CAT) { for(i = 0; i < string_pts.length; ++i) arr_cat_labels_points[i] = rect.y + point_interval*i; } else { for(i = 0; i < string_pts.length; ++i) arr_cat_labels_points[i] = rect.y + point_interval/2 + point_interval*i; } val_ax.posY = rect.y + point_interval*(crosses-1); } else if(labels_pos === c_oAscTickLabelsPos.TICK_LABEL_POSITION_NEXT_TO || !AscFormat.isRealNumber(labels_pos)) //подписи рядом с осью { if(val_ax.crosses === AscFormat.CROSSES_MAX) { if(!bWithoutLabels){ val_ax.labels.y = rect.y + rect.h - val_ax.labels.extY; point_interval = checkFiniteNumber((rect.h - val_ax.labels.extY)/intervals_count); } else{ val_ax.labels.y = rect.y + rect.h; } if(cross_between === AscFormat.CROSS_BETWEEN_MID_CAT) { for(i = 0; i < string_pts.length; ++i) arr_cat_labels_points[i] = rect.y + point_interval*i; } else { for(i = 0; i < string_pts.length; ++i) arr_cat_labels_points[i] = rect.y + point_interval/2 + point_interval*i; } val_ax.posY = val_ax.labels.y; } else { bottom_val_ax_labels_align = false; top_point_height = point_interval*(crosses-1); if(top_point_height < val_ax.labels.extY && !bWithoutLabels) { val_ax.labels.y = rect.y; var bottom_points_interval_count = intervals_count - (crosses - 1); point_interval = checkFiniteNumber((rect.h - val_ax.labels.extY)/bottom_points_interval_count); var start_point_bottom = rect.y + rect.h - point_interval*intervals_count; if(cross_between === AscFormat.CROSS_BETWEEN_MID_CAT) { for(i = 0; i < string_pts.length; ++i) arr_cat_labels_points[i] = start_point_bottom + point_interval*i; } else { for(i = 0; i < string_pts.length; ++i) arr_cat_labels_points[i] = start_point_bottom + point_interval/2 + point_interval*i; } } else { val_ax.labels.y = rect.y + point_interval*(crosses-1) - val_ax.labels.extY; if(cross_between === AscFormat.CROSS_BETWEEN_MID_CAT) { for(i = 0; i < string_pts.length; ++i) arr_cat_labels_points[i] = rect.y + point_interval*i; } else { for(i = 0; i < string_pts.length; ++i) arr_cat_labels_points[i] = rect.y + point_interval/2 + point_interval*i; } } val_ax.posY = val_ax.labels.y + val_ax.labels.extY; } } else if(labels_pos === c_oAscTickLabelsPos.TICK_LABEL_POSITION_LOW)//подписи сверху от области построения { bottom_val_ax_labels_align = false; if(!bWithoutLabels){ point_interval = checkFiniteNumber((rect.h - val_ax.labels.extY)/intervals_count); val_ax.labels.y = rect.y; } else{ val_ax.labels.y = rect.y - val_ax.labels.extY; } if(cross_between === AscFormat.CROSS_BETWEEN_MID_CAT) { for(i = 0; i < string_pts.length; ++i) arr_cat_labels_points[i] = val_ax.labels.y + val_ax.labels.extY + point_interval*i; } else { for(i = 0; i < string_pts.length; ++i) arr_cat_labels_points[i] = val_ax.labels.y + val_ax.labels.extY + point_interval/2 + point_interval*i; } val_ax.posY = rect.y + val_ax.labels.extY + point_interval*(crosses-1); } else if(labels_pos === c_oAscTickLabelsPos.TICK_LABEL_POSITION_HIGH)//подписи снизу от области построения { if(!bWithoutLabels){ point_interval = checkFiniteNumber((rect.h - val_ax.labels.extY)/intervals_count); val_ax.labels.y = rect.y + rect.h - val_ax.labels.extY; } else{ val_ax.labels.y = rect.y + rect.h; } if(cross_between === AscFormat.CROSS_BETWEEN_MID_CAT) { for(i = 0; i < string_pts.length; ++i) arr_cat_labels_points[i] = rect.y + point_interval*i; } else { for(i = 0; i < string_pts.length; ++i) arr_cat_labels_points[i] = rect.y + point_interval/2 + point_interval*i; } val_ax.posY = rect.y + point_interval*(crosses-1); } else { val_ax.labels = null; if(cross_between === AscFormat.CROSS_BETWEEN_MID_CAT) { for(i = 0; i < string_pts.length; ++i) arr_cat_labels_points[i] = rect.y + point_interval*i; } else { for(i = 0; i < string_pts.length; ++i) arr_cat_labels_points[i] = rect.y + point_interval/2 + point_interval*i; } val_ax.posY = rect.y + point_interval*(crosses-1); } } cat_ax.interval = point_interval; var diagram_height = point_interval*intervals_count;//размер области с самой диаграммой позже будет корректироватся; var max_cat_label_height = diagram_height / string_pts.length; // максимальная высота подписи горизонтальной оси; cat_ax.labels = null; var max_cat_labels_block_width = rect.w/2; if(c_oAscTickLabelsPos.TICK_LABEL_POSITION_NONE !== cat_ax.tickLblPos && !(cat_ax.bDelete === true)) //будем корректировать вертикальные подписи только если есть горизонтальные { cat_ax.labels = new AscFormat.CValAxisLabels(this, cat_ax); var tick_lbl_skip = AscFormat.isRealNumber(cat_ax.tickLblSkip) ? cat_ax.tickLblSkip : (string_pts.length < SKIP_LBL_LIMIT ? 1 : Math.floor(string_pts.length/SKIP_LBL_LIMIT)); var max_min_width = 0; var max_max_width = 0; var max_content_width = 0; var arr_min_max_min = []; for(i = 0; i < string_pts.length; ++i) { var dlbl = null; if(i%tick_lbl_skip === 0) { dlbl = new AscFormat.CDLbl(); dlbl.parent = cat_ax; dlbl.chart = this; dlbl.spPr = cat_ax.spPr; dlbl.txPr = cat_ax.txPr; dlbl.tx = new AscFormat.CChartText(); dlbl.tx.rich = AscFormat.CreateTextBodyFromString(string_pts[i].val.replace(oNonSpaceRegExp, ' '), this.getDrawingDocument(), dlbl); if(cat_ax.labels.aLabels[0]) { dlbl.lastStyleObject = cat_ax.labels.aLabels[0].lastStyleObject; } dlbl.tx.rich.content.Set_ApplyToAll(true); dlbl.tx.rich.content.SetParagraphAlign(AscCommon.align_Center); dlbl.tx.rich.content.Set_ApplyToAll(false); var min_max = dlbl.tx.rich.content.RecalculateMinMaxContentWidth(); var max_min_content_width = min_max.Min; if(min_max.Max > max_max_width) max_max_width = min_max.Max; if(min_max.Min > max_min_width) max_min_width = min_max.Min; arr_min_max_min[i] = min_max.Min; dlbl.getMaxWidth = function(){return 20000}; dlbl.recalcInfo.recalculatePen = false; dlbl.recalcInfo.recalculateBrush = false; dlbl.recalculate(); delete dlbl.getMaxWidth; if(dlbl.tx.rich.content.XLimit > max_content_width) max_content_width = dlbl.tx.rich.content.XLimit; } cat_ax.labels.aLabels.push(dlbl); } var stake_offset = AscFormat.isRealNumber(cat_ax.lblOffset) ? cat_ax.lblOffset/100 : 1; var labels_offset = cat_ax.labels.aLabels[0].tx.rich.content.Content[0].CompiledPr.Pr.TextPr.FontSize*(25.4/72)*stake_offset; //сначала посмотрим убираются ли в максимальную допустимую ширину подписей подписи расчитанные в одну строку var width_flag; if(max_content_width + labels_offset < max_cat_labels_block_width) { width_flag = 0; cat_ax.labels.extX = max_content_width + labels_offset; } else if(max_min_width + labels_offset < max_cat_labels_block_width)//ситуация, когда возможно разместить подписи без переноса слов { width_flag = 1; cat_ax.labels.extX = max_min_width + labels_offset; } else //выставляем максимально возможную ширину { width_flag = 2; cat_ax.labels.extX = max_cat_labels_block_width; } } var cat_labels_align_left = true;//выравнивание подписей в блоке сподписями по левому краю(т. е. зазор находится справа) /*-----------------------------------------------------------------------*/ var crosses_val_ax;//значение на горизонтальной оси значений в котором её пересекает горизонтальная if(cat_ax.crosses === AscFormat.CROSSES_AUTO_ZERO) { if(arr_val[0] <=0 && arr_val[arr_val.length-1] >= 0) crosses_val_ax = 0; else if(arr_val[arr_val.length-1] < 0) crosses_val_ax = arr_val[arr_val.length-1]; else crosses_val_ax = arr_val[0]; } else if(cat_ax.crosses === AscFormat.CROSSES_MIN) { crosses_val_ax = arr_val[0]; } else if(cat_ax.crosses === AscFormat.CROSSES_MAX) { crosses_val_ax = arr_val[arr_val.length - 1]; } else if(AscFormat.isRealNumber(cat_ax.crossesAt) && cat_ax.crossesAt >= arr_val[0] && cat_ax.crossesAt <= arr_val[arr_val.length - 1]) { //сделаем провеку на попадание в интервал if(cat_ax.crossesAt >= arr_val[0] && cat_ax.crossesAt <= arr_val[arr_val.length - 1]) crosses_val_ax = cat_ax.crossesAt; } else { //ведем себя как в случае (cat_ax.crosses === AscFormat.CROSSES_AUTO_ZERO) if(arr_val[0] <=0 && arr_val[arr_val.length-1] >= 0) crosses_val_ax = 0; else if(arr_val[arr_val.length-1] < 0) crosses_val_ax = arr_val[arr_val.length-1]; else crosses_val_ax = arr_val[0]; } var val_ax_orientation = val_ax.scaling && AscFormat.isRealNumber(val_ax.scaling.orientation) ? val_ax.scaling.orientation : AscFormat.ORIENTATION_MIN_MAX; var hor_labels_pos = cat_ax.tickLblPos; var first_val_lbl_half_width = (val_ax.tickLblPos === c_oAscTickLabelsPos.TICK_LABEL_POSITION_NONE || val_ax.bDelete) ? 0 : val_ax.labels.aLabels[0].tx.rich.content.XLimit/2; var last_val_lbl_half_width = (val_ax.tickLblPos === c_oAscTickLabelsPos.TICK_LABEL_POSITION_NONE || val_ax.bDelete) ? 0 : val_ax.labels.aLabels[val_ax.labels.aLabels.length-1].tx.rich.content.XLimit/2; var right_gap, left_gap; var arr_val_labels_points = [];//массив середин подписей вертикальной оси; i-й элемент - x-координата центра подписи i-огто значения; var unit_width = checkFiniteNumber((rect.w - first_val_lbl_half_width - last_val_lbl_half_width)/(arr_val[arr_val.length - 1] - arr_val[0]));//ширина единицы измерения на вертикальной оси var cat_ax_ext_x = cat_ax.labels && !bWithoutLabels ? cat_ax.labels.extX : 0; if(val_ax_orientation === AscFormat.ORIENTATION_MIN_MAX) { if(hor_labels_pos === c_oAscTickLabelsPos.TICK_LABEL_POSITION_NEXT_TO || !AscFormat.isRealNumber(hor_labels_pos)) { if(cat_ax.crosses === AscFormat.CROSSES_MAX) { if(!bNeedReflect) { right_gap = Math.max(last_val_lbl_half_width, cat_ax_ext_x); } else { right_gap = Math.max(last_val_lbl_half_width, 0); } cat_labels_align_left = false;//в данном случае подписи будут выравниваться по верхнему краю блока с подписями if(cat_ax.labels) cat_ax.labels.x = rect.x + rect.w - right_gap; unit_width = checkFiniteNumber((rect.w - right_gap - first_val_lbl_half_width)/(arr_val[arr_val.length - 1] - arr_val[0])); cat_ax.posX = rect.x + first_val_lbl_half_width + (crosses_val_ax - arr_val[0])*unit_width; } else { if(!bNeedReflect && (crosses_val_ax - arr_val[0])*unit_width + first_val_lbl_half_width < cat_ax_ext_x) { unit_width = checkFiniteNumber((rect.w - cat_ax_ext_x - last_val_lbl_half_width)/(arr_val[arr_val.length-1] - crosses_val_ax)); } cat_ax.posX = rect.x + rect.w - last_val_lbl_half_width - (arr_val[arr_val.length-1] - crosses_val_ax)*unit_width; if(cat_ax.labels) cat_ax.labels.x = cat_ax.posX - cat_ax.labels.extX; } for(i = 0; i < arr_val.length; ++i) arr_val_labels_points[i] = cat_ax.posX + (arr_val[i] - crosses_val_ax)*unit_width; } else if(hor_labels_pos === c_oAscTickLabelsPos.TICK_LABEL_POSITION_LOW) { if(!bNeedReflect) { left_gap = Math.max(first_val_lbl_half_width, cat_ax_ext_x); } else { left_gap = Math.max(first_val_lbl_half_width, 0); } unit_width = checkFiniteNumber((rect.w - left_gap - last_val_lbl_half_width)/(arr_val[arr_val.length - 1] - arr_val[0])); cat_ax.posX = rect.x + rect.w - (arr_val[arr_val.length-1] - crosses_val_ax )*unit_width - last_val_lbl_half_width; for(i = 0; i < arr_val.length; ++i) arr_val_labels_points[i] = cat_ax.posX + (arr_val[i] - crosses_val_ax)*unit_width; if(cat_ax.labels) cat_ax.labels.x = cat_ax.posX + (arr_val[i] - crosses_val_ax)*unit_width - cat_ax.labels.extX; } else if(hor_labels_pos === c_oAscTickLabelsPos.TICK_LABEL_POSITION_HIGH) { cat_labels_align_left = false; if(!bNeedReflect) { right_gap = Math.max(last_val_lbl_half_width, cat_ax_ext_x); } else { right_gap = Math.max(last_val_lbl_half_width, 0); } unit_width = checkFiniteNumber((rect.w - right_gap - first_val_lbl_half_width)/(arr_val[arr_val.length - 1] - arr_val[0])); cat_ax.posX = rect.x + first_val_lbl_half_width + (crosses_val_ax - arr_val[0])*unit_width; for(i = 0; i < arr_val.length; ++i) arr_val_labels_points[i] = cat_ax.posX + (arr_val[i] - crosses_val_ax)*unit_width; } else { //подписей осей нет cat_ax.labels = null; unit_width = checkFiniteNumber((rect.w - last_val_lbl_half_width - first_val_lbl_half_width)/(arr_val[arr_val.length - 1] - arr_val[0])); cat_ax.posX = rect.x + first_val_lbl_half_width + (crosses_val_ax - arr_val[0])*unit_width; for(i = 0; i < arr_val.length; ++i) arr_val_labels_points[i] = cat_ax.posX + (arr_val[i] - crosses_val_ax)*unit_width; } } else {//зеркально отражаем if(hor_labels_pos === c_oAscTickLabelsPos.TICK_LABEL_POSITION_NEXT_TO || !AscFormat.isRealNumber(hor_labels_pos)) { if(cat_ax.crosses === AscFormat.CROSSES_MAX) { if(!bNeedReflect) { left_gap = Math.max(cat_ax_ext_x, last_val_lbl_half_width); } else { left_gap = Math.max(0, last_val_lbl_half_width); } unit_width = checkFiniteNumber((rect.w - left_gap - first_val_lbl_half_width)/(arr_val[arr_val.length - 1] - arr_val[0])); cat_ax.posX = rect.x + rect.w - first_val_lbl_half_width - (crosses_val_ax - arr_val[0])*unit_width; if(cat_ax.labels) cat_ax.labels.x = cat_ax.posX - cat_ax.labels.extX; } else { cat_labels_align_left = false; if(!bNeedReflect && first_val_lbl_half_width < cat_ax_ext_x) { unit_width = checkFiniteNumber((rect.w - cat_ax_ext_x - last_val_lbl_half_width)/(arr_val[arr_val.length - 1] - arr_val[0])); } cat_ax.posX = rect.x + last_val_lbl_half_width + (arr_val[arr_val.length-1] - crosses_val_ax)*unit_width; if(cat_ax.labels) cat_ax.labels.x = cat_ax.posX; } for(i = 0; i < arr_val.length; ++i) arr_val_labels_points[i] = cat_ax.posX - (arr_val[i] - crosses_val_ax)*unit_width; } else if(hor_labels_pos === c_oAscTickLabelsPos.TICK_LABEL_POSITION_LOW) { cat_labels_align_left = false; if(!bNeedReflect) { right_gap = Math.max(first_val_lbl_half_width, cat_ax_ext_x); } else { right_gap = Math.max(first_val_lbl_half_width, 0); } unit_width = checkFiniteNumber((rect.w - last_val_lbl_half_width - right_gap)/(arr_val[arr_val.length-1] - arr_val[0])); cat_ax.posX = rect.x + last_val_lbl_half_width + (arr_val[arr_val.length-1] - crosses_val_ax)*crosses_val_ax; if(cat_ax.labels) cat_ax.labels.x = cat_ax.posX - (arr_val[0] - crosses_val_ax)*unit_width; for(i = 0; i < arr_val.length; ++i) arr_val_labels_points[i] = cat_ax.posX - (arr_val[i] - crosses_val_ax)*unit_width; } else if(hor_labels_pos === c_oAscTickLabelsPos.TICK_LABEL_POSITION_HIGH) { if(!bNeedReflect) { left_gap = Math.max(cat_ax_ext_x, last_val_lbl_half_width); } else { left_gap = Math.max(0, last_val_lbl_half_width); } unit_width = checkFiniteNumber((rect.w - left_gap - first_val_lbl_half_width)/(arr_val[arr_val.length - 1] - arr_val[0])); cat_ax.posX = rect.x + rect.w - first_val_lbl_half_width - (crosses_val_ax - arr_val[0])*unit_width; if(cat_ax.labels) cat_ax.labels.x = cat_ax.posX - (arr_val[arr_val.length-1] - crosses_val_ax)*unit_width - cat_ax.labels.extX; for(i = 0; i < arr_val.length; ++i) arr_val_labels_points[i] = cat_ax.posX - (arr_val[i] - crosses_val_ax)*unit_width; } else {//подписей осей нет cat_ax.labels = null; unit_width = checkFiniteNumber((rect.w - last_val_lbl_half_width - first_val_lbl_half_width)/(arr_val[arr_val.length - 1] - arr_val[0])); cat_ax.posX = rect.x + rect.w - first_val_lbl_half_width - (crosses_val_ax - arr_val[0])*unit_width; for(i = 0; i < arr_val.length; ++i) arr_val_labels_points[i] = cat_ax.posX - (arr_val[i] - crosses_val_ax)*unit_width; } } val_ax.interval = unit_width; //запишем в оси необходимую информацию для отрисовщика plotArea и выставим окончательные позиции для подписей var local_transform_text; if(val_ax.labels) { val_ax.labels.x = Math.min.apply(Math, arr_val_labels_points) - max_val_ax_label_width/2; val_ax.labels.extX = Math.max.apply(Math, arr_val_labels_points) - Math.min.apply(Math, arr_val_labels_points) + max_val_ax_label_width; //val_axis_labels_gap - вертикальный зазор val_ax.labels.align = bottom_val_ax_labels_align; if(bottom_val_ax_labels_align) { var y_pos = val_ax.labels.y + val_axis_labels_gap; for(i = 0; i < val_ax.labels.aLabels.length; ++i) { var text_transform = val_ax.labels.aLabels[i].transformText; text_transform.Reset(); global_MatrixTransformer.TranslateAppend(text_transform, arr_val_labels_points[i] - val_ax.labels.aLabels[i].tx.rich.content.XLimit/2, y_pos); // global_MatrixTransformer.MultiplyAppend(text_transform, this.getTransformMatrix()); var local_transform_text = val_ax.labels.aLabels[i].localTransformText; local_transform_text.Reset(); global_MatrixTransformer.TranslateAppend(local_transform_text, arr_val_labels_points[i] - val_ax.labels.aLabels[i].tx.rich.content.XLimit/2, y_pos); } } else { for(i = 0; i < val_ax.labels.aLabels.length; ++i) { var text_transform = val_ax.labels.aLabels[i].transformText; text_transform.Reset(); global_MatrixTransformer.TranslateAppend(text_transform, arr_val_labels_points[i] - val_ax.labels.aLabels[i].tx.rich.content.XLimit/2, val_ax.labels.y + val_ax.labels.extY - val_axis_labels_gap - val_ax.labels.aLabels[i].tx.rich.content.GetSummaryHeight()); // global_MatrixTransformer.MultiplyAppend(text_transform, this.getTransformMatrix()); var local_transform_text = val_ax.labels.aLabels[i].localTransformText; local_transform_text.Reset(); global_MatrixTransformer.TranslateAppend(local_transform_text, arr_val_labels_points[i] - val_ax.labels.aLabels[i].tx.rich.content.XLimit/2, val_ax.labels.y + val_ax.labels.extY - val_axis_labels_gap - val_ax.labels.aLabels[i].tx.rich.content.GetSummaryHeight()); } } } val_ax.xPoints = []; for(i = 0; i < arr_val_labels_points.length; ++i) { val_ax.xPoints[i] = {val:arr_val[i], pos: arr_val_labels_points[i]}; } cat_ax.yPoints = []; for(i = 0; i <arr_cat_labels_points.length; ++i) { cat_ax.yPoints[i] = {val: i, pos: arr_cat_labels_points[i]}; } if(cat_ax.labels) { cat_ax.labels.y = rect.y; cat_ax.labels.extY = point_interval*intervals_count; if(bNeedReflect) { if(cat_labels_align_left) { cat_labels_align_left = false; cat_ax.labels.x += cat_ax.labels.extX; } else { cat_labels_align_left = true; cat_ax.labels.x -= cat_ax.labels.extX; } } if(cat_labels_align_left) { if(width_flag === 0) { for(i = 0; i < cat_ax.labels.aLabels.length; ++i) { if(cat_ax.labels.aLabels[i]) { var transform_text = cat_ax.labels.aLabels[i].transformText; transform_text.Reset(); global_MatrixTransformer.TranslateAppend(transform_text, cat_ax.labels.x + cat_ax.labels.extX - cat_ax.labels.aLabels[i].tx.rich.content.XLimit - labels_offset, arr_cat_labels_points[i] - cat_ax.labels.aLabels[i].tx.rich.content.GetSummaryHeight()/2); // global_MatrixTransformer.MultiplyAppend(transform_text, this.getTransformMatrix()); local_transform_text = cat_ax.labels.aLabels[i].localTransformText; local_transform_text.Reset(); global_MatrixTransformer.TranslateAppend(local_transform_text, cat_ax.labels.x + cat_ax.labels.extX - cat_ax.labels.aLabels[i].tx.rich.content.XLimit - labels_offset, arr_cat_labels_points[i] - cat_ax.labels.aLabels[i].tx.rich.content.GetSummaryHeight()/2); } } } else if(width_flag === 1) { for(i = 0; i < cat_ax.labels.aLabels.length; ++i) { if(cat_ax.labels.aLabels[i]) { cat_ax.labels.aLabels[i].tx.rich.content.Reset(0, 0, arr_min_max_min[i], 20000); cat_ax.labels.aLabels[i].tx.rich.content.Recalculate_Page(0, true); var transform_text = cat_ax.labels.aLabels[i].transformText; transform_text.Reset(); global_MatrixTransformer.TranslateAppend(transform_text, cat_ax.labels.x + cat_ax.labels.extX - cat_ax.labels.aLabels[i].tx.rich.content.XLimit - labels_offset, arr_cat_labels_points[i] - cat_ax.labels.aLabels[i].tx.rich.content.GetSummaryHeight()/2); // global_MatrixTransformer.MultiplyAppend(transform_text, this.getTransformMatrix()); local_transform_text = cat_ax.labels.aLabels[i].localTransformText; local_transform_text.Reset(); global_MatrixTransformer.TranslateAppend(local_transform_text, cat_ax.labels.x + cat_ax.labels.extX - cat_ax.labels.aLabels[i].tx.rich.content.XLimit - labels_offset, arr_cat_labels_points[i] - cat_ax.labels.aLabels[i].tx.rich.content.GetSummaryHeight()/2); } } } else { for(i = 0; i < cat_ax.labels.aLabels.length; ++i) { if(cat_ax.labels.aLabels[i]) { cat_ax.labels.aLabels[i].tx.rich.content.Reset(0, 0, cat_ax.labels.extX - labels_offset, 20000); cat_ax.labels.aLabels[i].tx.rich.content.Recalculate_Page(0, true); var transform_text = cat_ax.labels.aLabels[i].transformText; transform_text.Reset(); global_MatrixTransformer.TranslateAppend(transform_text, cat_ax.labels.x + cat_ax.labels.extX - cat_ax.labels.aLabels[i].tx.rich.content.XLimit - labels_offset, arr_cat_labels_points[i] - cat_ax.labels.aLabels[i].tx.rich.content.GetSummaryHeight()/2); // global_MatrixTransformer.MultiplyAppend(transform_text, this.getTransformMatrix()); local_text_transform = cat_ax.labels.aLabels[i].localTransformText; local_text_transform.Reset(); global_MatrixTransformer.TranslateAppend(local_text_transform, cat_ax.labels.x + cat_ax.labels.extX - cat_ax.labels.aLabels[i].tx.rich.content.XLimit - labels_offset, arr_cat_labels_points[i] - cat_ax.labels.aLabels[i].tx.rich.content.GetSummaryHeight()/2); } } } /*for(i = 0; i < cat_ax.labels.aLabels.length; ++i) { if(cat_ax.labels.aLabels[i]) { cat_ax.labels.aLabels[i].tx.rich.content.Set_ApplyToAll(true); cat_ax.labels.aLabels[i].tx.rich.content.SetParagraphAlign(align_Center); cat_ax.labels.aLabels[i].tx.rich.content.Set_ApplyToAll(false); cat_ax.labels.aLabels[i].tx.rich.content.Reset(0, 0, cat_ax.labels.extX - labels_offset, 2000); cat_ax.labels.aLabels[i].tx.rich.content.Recalculate_Page(0, true); cat_ax.labels.aLabels[i].setPosition(cat_ax.labels.x, arr_cat_labels_points[i] - cat_ax.labels.aLabels[i].tx.rich.content.GetSummaryHeight()/2); } } */ } else { if(width_flag === 0) { for(i = 0; i < cat_ax.labels.aLabels.length; ++i) { if(cat_ax.labels.aLabels[i]) { var transform_text = cat_ax.labels.aLabels[i].transformText; transform_text.Reset(); global_MatrixTransformer.TranslateAppend(transform_text, cat_ax.labels.x + labels_offset, arr_cat_labels_points[i] - cat_ax.labels.aLabels[i].tx.rich.content.GetSummaryHeight()/2); // global_MatrixTransformer.MultiplyAppend(transform_text, this.getTransformMatrix()); local_text_transform = cat_ax.labels.aLabels[i].localTransformText; local_text_transform.Reset(); global_MatrixTransformer.TranslateAppend(local_text_transform, cat_ax.labels.x + labels_offset, arr_cat_labels_points[i] - cat_ax.labels.aLabels[i].tx.rich.content.GetSummaryHeight()/2); } } } else if(width_flag === 1) { for(i = 0; i < cat_ax.labels.aLabels.length; ++i) { if(cat_ax.labels.aLabels[i]) { cat_ax.labels.aLabels[i].tx.rich.content.Reset(0, 0, arr_min_max_min[i], 20000); cat_ax.labels.aLabels[i].tx.rich.content.Recalculate_Page(0, true); var transform_text = cat_ax.labels.aLabels[i].transformText; transform_text.Reset(); global_MatrixTransformer.TranslateAppend(transform_text, cat_ax.labels.x + labels_offset, arr_cat_labels_points[i] - cat_ax.labels.aLabels[i].tx.rich.content.GetSummaryHeight()/2); // global_MatrixTransformer.MultiplyAppend(transform_text, this.getTransformMatrix()); local_text_transform = cat_ax.labels.aLabels[i].localTransformText; local_text_transform.Reset(); global_MatrixTransformer.TranslateAppend(local_text_transform, cat_ax.labels.x + labels_offset, arr_cat_labels_points[i] - cat_ax.labels.aLabels[i].tx.rich.content.GetSummaryHeight()/2); } } } else { for(i = 0; i < cat_ax.labels.aLabels.length; ++i) { if(cat_ax.labels.aLabels[i]) { cat_ax.labels.aLabels[i].tx.rich.content.Reset(0, 0, cat_ax.labels.extX - labels_offset, 20000); cat_ax.labels.aLabels[i].tx.rich.content.Recalculate_Page(0, true); var transform_text = cat_ax.labels.aLabels[i].transformText; transform_text.Reset(); global_MatrixTransformer.TranslateAppend(transform_text, cat_ax.labels.x + labels_offset, arr_cat_labels_points[i] - cat_ax.labels.aLabels[i].tx.rich.content.GetSummaryHeight()/2); // global_MatrixTransformer.MultiplyAppend(transform_text, this.getTransformMatrix()); local_text_transform = cat_ax.labels.aLabels[i].localTransformText; local_text_transform.Reset(); global_MatrixTransformer.TranslateAppend(local_text_transform, cat_ax.labels.x + labels_offset, arr_cat_labels_points[i] - cat_ax.labels.aLabels[i].tx.rich.content.GetSummaryHeight()/2); } } } } } cat_ax.yPoints.sort(function(a, b){return a.val - b.val}); val_ax.xPoints.sort(function(a, b){return a.val - b.val}); } else{ this.bEmptySeries = true; } } this.plotAreaRect = rect; } }; CChartSpace.prototype.checkAxisLabelsTransform = function() { if(this.chart && this.chart.plotArea && this.chart.plotArea.charts[0] && this.chart.plotArea.charts[0].getAxisByTypes) { var oAxisByTypes = this.chart.plotArea.charts[0].getAxisByTypes(); var oCatAx = oAxisByTypes.catAx[0], oValAx = oAxisByTypes.valAx[0], deltaX, deltaY, i, oAxisLabels, oLabel, oNewPos; var oProcessor3D = this.chartObj && this.chartObj.processor3D; var aXPoints = [], aYPoints = []; if(oCatAx && oValAx && oProcessor3D) { if(( (oCatAx.axPos === AscFormat.AX_POS_B || oCatAx.axPos === AscFormat.AX_POS_T) && oCatAx.xPoints) && ((oValAx.axPos === AscFormat.AX_POS_L || oValAx.axPos === AscFormat.AX_POS_R) && oValAx.yPoints)) { oAxisLabels = oCatAx.labels; if(oAxisLabels) { var dZPositionCatAxis = oProcessor3D.calculateZPositionCatAxis(); var dPosY, dPosY2 if(oAxisLabels.align) { dPosY = oAxisLabels.y*this.chartObj.calcProp.pxToMM; dPosY2 = oAxisLabels.y; } else { dPosY = (oAxisLabels.y + oAxisLabels.extY)*this.chartObj.calcProp.pxToMM; dPosY2 = oAxisLabels.y + oAxisLabels.extY; } var fBottomLabels = -100; if(!oAxisLabels.bRotated) { for(i = 0; i < oAxisLabels.aLabels.length; ++i) { oLabel = oAxisLabels.aLabels[i]; if(oLabel) { var oCPosLabelX; oCPosLabelX = oLabel.localTransformText.TransformPointX(oLabel.txBody.content.XLimit/2, 0); oNewPos = oProcessor3D.convertAndTurnPoint(oCPosLabelX*this.chartObj.calcProp.pxToMM, dPosY, dZPositionCatAxis); oLabel.setPosition2(oNewPos.x/this.chartObj.calcProp.pxToMM + oLabel.localTransformText.tx - oCPosLabelX, oLabel.localTransformText.ty - dPosY2 + oNewPos.y/this.chartObj.calcProp.pxToMM ); var fBottomContent = oLabel.y + oLabel.tx.rich.content.GetSummaryHeight(); if(fBottomContent > fBottomLabels){ fBottomLabels = fBottomContent; } } } } else { if(oAxisLabels.align) { var stake_offset = AscFormat.isRealNumber(oCatAx.lblOffset) ? oCatAx.lblOffset/100 : 1; var labels_offset = oCatAx.labels.aLabels[0].tx.rich.content.Content[0].CompiledPr.Pr.TextPr.FontSize*(25.4/72)*stake_offset; for(i = 0; i < oAxisLabels.aLabels.length; ++i) { if(oAxisLabels.aLabels[i]) { oLabel = oAxisLabels.aLabels[i]; var wh = {w: oLabel.widthForTransform, h: oLabel.tx.rich.content.GetSummaryHeight()}, w2, h2, x1, y0, xc, yc; w2 = wh.w*Math.cos(Math.PI/4) + wh.h*Math.sin(Math.PI/4); h2 = wh.w*Math.sin(Math.PI/4) + wh.h*Math.cos(Math.PI/4); x1 = oCatAx.xPoints[i].pos + wh.h*Math.sin(Math.PI/4); y0 = oAxisLabels.y + labels_offset; var x1t, y0t; var oRes = oProcessor3D.convertAndTurnPoint(x1*this.chartObj.calcProp.pxToMM, y0*this.chartObj.calcProp.pxToMM, dZPositionCatAxis); x1t = oRes.x/this.chartObj.calcProp.pxToMM; y0t = oRes.y/this.chartObj.calcProp.pxToMM; xc = x1t - w2/2; yc = y0t + h2/2; var local_text_transform = oLabel.localTransformText; local_text_transform.Reset(); global_MatrixTransformer.TranslateAppend(local_text_transform, -wh.w/2, -wh.h/2); global_MatrixTransformer.RotateRadAppend(local_text_transform, Math.PI/4); global_MatrixTransformer.TranslateAppend(local_text_transform, xc, yc); var fBottomContent = y0t + h2; if(fBottomContent > fBottomLabels){ fBottomLabels = fBottomContent; } } } } else { var stake_offset = AscFormat.isRealNumber(oCatAx.lblOffset) ? oCatAx.lblOffset/100 : 1; var labels_offset = oCatAx.labels.aLabels[0].tx.rich.content.Content[0].CompiledPr.Pr.TextPr.FontSize*(25.4/72)*stake_offset; for(i = 0; i < oAxisLabels.aLabels.length; ++i) { if(oAxisLabels.aLabels[i]) { oLabel = oAxisLabels.aLabels[i]; var wh = {w: oLabel.widthForTransform, h: oLabel.tx.rich.content.GetSummaryHeight()}, w2, h2, x1, y0, xc, yc; w2 = wh.w*Math.cos(Math.PI/4) + wh.h*Math.sin(Math.PI/4); h2 = wh.w*Math.sin(Math.PI/4) + wh.h*Math.cos(Math.PI/4); x1 = oCatAx.xPoints[i].pos - wh.h*Math.sin(Math.PI/4); y0 = oAxisLabels.y + oAxisLabels.extY - labels_offset; var x1t, y0t; var oRes = oProcessor3D.convertAndTurnPoint(x1*this.chartObj.calcProp.pxToMM, y0*this.chartObj.calcProp.pxToMM, dZPositionCatAxis); x1t = oRes.x/this.chartObj.calcProp.pxToMM; y0t = oRes.y/this.chartObj.calcProp.pxToMM; xc = x1t + w2/2; yc = y0t - h2/2; local_text_transform = oLabel.localTransformText; local_text_transform.Reset(); global_MatrixTransformer.TranslateAppend(local_text_transform, -wh.w/2, -wh.h/2); global_MatrixTransformer.RotateRadAppend(local_text_transform, Math.PI/4);//TODO global_MatrixTransformer.TranslateAppend(local_text_transform, xc, yc); } } } } oNewPos = oProcessor3D.convertAndTurnPoint(oAxisLabels.x*this.chartObj.calcProp.pxToMM, oAxisLabels.y*this.chartObj.calcProp.pxToMM, dZPositionCatAxis); aXPoints.push(oNewPos.x/this.chartObj.calcProp.pxToMM); aYPoints.push(oNewPos.y/this.chartObj.calcProp.pxToMM); oNewPos = oProcessor3D.convertAndTurnPoint((oAxisLabels.x + oAxisLabels.extX)*this.chartObj.calcProp.pxToMM, oAxisLabels.y*this.chartObj.calcProp.pxToMM, dZPositionCatAxis); aXPoints.push(oNewPos.x/this.chartObj.calcProp.pxToMM); aYPoints.push(oNewPos.y/this.chartObj.calcProp.pxToMM); oNewPos = oProcessor3D.convertAndTurnPoint((oAxisLabels.x + oAxisLabels.extX)*this.chartObj.calcProp.pxToMM, (oAxisLabels.y + oAxisLabels.extY)*this.chartObj.calcProp.pxToMM, dZPositionCatAxis); aXPoints.push(oNewPos.x/this.chartObj.calcProp.pxToMM); aYPoints.push(oNewPos.y/this.chartObj.calcProp.pxToMM); oNewPos = oProcessor3D.convertAndTurnPoint((oAxisLabels.x)*this.chartObj.calcProp.pxToMM, (oAxisLabels.y + oAxisLabels.extY)*this.chartObj.calcProp.pxToMM, dZPositionCatAxis); aXPoints.push(oNewPos.x/this.chartObj.calcProp.pxToMM); aYPoints.push(oNewPos.y/this.chartObj.calcProp.pxToMM); oAxisLabels.x = Math.min.apply(Math, aXPoints); oAxisLabels.y = Math.min.apply(Math, aYPoints); oAxisLabels.extX = Math.max.apply(Math, aXPoints) - oAxisLabels.x; oAxisLabels.extY = Math.max(Math.max.apply(Math, aYPoints), fBottomLabels) - oAxisLabels.y; } oAxisLabels = oValAx.labels; if(oAxisLabels) { var dZPositionCatAxis = oProcessor3D.calculateZPositionValAxis(); var dPosX, dPosX2; if(!oAxisLabels.align) { dPosX2 = oAxisLabels.x; dPosX = oAxisLabels.x*this.chartObj.calcProp.pxToMM; } else { dPosX2 = oAxisLabels.x + oAxisLabels.extX; dPosX = (oAxisLabels.x + oAxisLabels.extX)*this.chartObj.calcProp.pxToMM; } aXPoints.length = 0; aYPoints.length = 0; for(i = 0; i < oAxisLabels.aLabels.length; ++i) { oLabel = oAxisLabels.aLabels[i]; if(oLabel) { oNewPos = oProcessor3D.convertAndTurnPoint(dPosX, oLabel.localTransformText.ty*this.chartObj.calcProp.pxToMM, dZPositionCatAxis); oLabel.setPosition2(oLabel.localTransformText.tx - dPosX2 + oNewPos.x/this.chartObj.calcProp.pxToMM, oNewPos.y/this.chartObj.calcProp.pxToMM); aXPoints.push(oLabel.x); aYPoints.push(oLabel.y); aXPoints.push(oLabel.x + oLabel.txBody.content.XLimit); aYPoints.push(oLabel.y + oLabel.txBody.content.GetSummaryHeight()); } } if(aXPoints.length > 0 && aYPoints.length > 0) { oAxisLabels.x = Math.min.apply(Math, aXPoints); oAxisLabels.y = Math.min.apply(Math, aYPoints); oAxisLabels.extX = Math.max.apply(Math, aXPoints) - oAxisLabels.x; oAxisLabels.extY = Math.max.apply(Math, aYPoints) - oAxisLabels.y; } } } else if(((oCatAx.axPos === AscFormat.AX_POS_L || oCatAx.axPos === AscFormat.AX_POS_R) && oCatAx.yPoints) && ((oValAx.axPos === AscFormat.AX_POS_T || oValAx.axPos === AscFormat.AX_POS_B) && oValAx.xPoints)) { oAxisLabels = oValAx.labels; if(oAxisLabels) { var dZPositionValAxis = oProcessor3D.calculateZPositionValAxis(); var dPosY, dPosY2 if(oAxisLabels.align) { dPosY = oAxisLabels.y*this.chartObj.calcProp.pxToMM; dPosY2 = oAxisLabels.y; } else { dPosY = (oAxisLabels.y + oAxisLabels.extY)*this.chartObj.calcProp.pxToMM; dPosY2 = oAxisLabels.y + oAxisLabels.extY; } for(i = 0; i < oAxisLabels.aLabels.length; ++i) { oLabel = oAxisLabels.aLabels[i]; if(oLabel) { var oCPosLabelX = oLabel.localTransformText.TransformPointX(oLabel.txBody.content.XLimit/2, 0); var oCPosLabelY = oLabel.localTransformText.TransformPointY(oLabel.txBody.content.XLimit/2, 0); oNewPos = oProcessor3D.convertAndTurnPoint(oCPosLabelX*this.chartObj.calcProp.pxToMM, dPosY, dZPositionValAxis); oLabel.setPosition2(oNewPos.x/this.chartObj.calcProp.pxToMM + oLabel.localTransformText.tx - oCPosLabelX, oLabel.localTransformText.ty - dPosY2 + oNewPos.y/this.chartObj.calcProp.pxToMM ); //oNewPos = oProcessor3D.convertAndTurnPoint(oLabel.localTransformText.tx*this.chartObj.calcProp.pxToMM, oLabel.localTransformText.ty*this.chartObj.calcProp.pxToMM, dZPositionValAxis);; //oLabel.setPosition2(oNewPos.x/this.chartObj.calcProp.pxToMM, oNewPos.y/this.chartObj.calcProp.pxToMM); } } oNewPos = oProcessor3D.convertAndTurnPoint(oAxisLabels.x*this.chartObj.calcProp.pxToMM, oAxisLabels.y*this.chartObj.calcProp.pxToMM, dZPositionValAxis); aXPoints.push(oNewPos.x/this.chartObj.calcProp.pxToMM); aYPoints.push(oNewPos.y/this.chartObj.calcProp.pxToMM); oNewPos = oProcessor3D.convertAndTurnPoint((oAxisLabels.x + oAxisLabels.extX)*this.chartObj.calcProp.pxToMM, oAxisLabels.y*this.chartObj.calcProp.pxToMM, dZPositionValAxis); aXPoints.push(oNewPos.x/this.chartObj.calcProp.pxToMM); aYPoints.push(oNewPos.y/this.chartObj.calcProp.pxToMM); oNewPos = oProcessor3D.convertAndTurnPoint((oAxisLabels.x + oAxisLabels.extX)*this.chartObj.calcProp.pxToMM, (oAxisLabels.y + oAxisLabels.extY)*this.chartObj.calcProp.pxToMM, dZPositionValAxis); aXPoints.push(oNewPos.x/this.chartObj.calcProp.pxToMM); aYPoints.push(oNewPos.y/this.chartObj.calcProp.pxToMM); oNewPos = oProcessor3D.convertAndTurnPoint((oAxisLabels.x)*this.chartObj.calcProp.pxToMM, (oAxisLabels.y + oAxisLabels.extY)*this.chartObj.calcProp.pxToMM, dZPositionValAxis); aXPoints.push(oNewPos.x/this.chartObj.calcProp.pxToMM); aYPoints.push(oNewPos.y/this.chartObj.calcProp.pxToMM); oAxisLabels.x = Math.min.apply(Math, aXPoints); oAxisLabels.y = Math.min.apply(Math, aYPoints); oAxisLabels.extX = Math.max.apply(Math, aXPoints) - oAxisLabels.x; oAxisLabels.extY = Math.max.apply(Math, aYPoints) - oAxisLabels.y; } oAxisLabels = oCatAx.labels; aXPoints.length = 0; aYPoints.length = 0; if(oAxisLabels) { var dZPositionCatAxis = oProcessor3D.calculateZPositionCatAxis(); var dPosX, dPosX2; if(oAxisLabels.align) { dPosX2 = oAxisLabels.x; dPosX = oAxisLabels.x*this.chartObj.calcProp.pxToMM; } else { dPosX2 = oAxisLabels.x + oAxisLabels.extX; dPosX = (oAxisLabels.x + oAxisLabels.extX)*this.chartObj.calcProp.pxToMM; } for(i = 0; i < oAxisLabels.aLabels.length; ++i) { oLabel = oAxisLabels.aLabels[i]; if(oLabel) { oNewPos = oProcessor3D.convertAndTurnPoint(dPosX, oLabel.localTransformText.ty*this.chartObj.calcProp.pxToMM, dZPositionCatAxis); oLabel.setPosition2(oLabel.localTransformText.tx - dPosX2 + oNewPos.x/this.chartObj.calcProp.pxToMM, oNewPos.y/this.chartObj.calcProp.pxToMM); aXPoints.push(oLabel.x); aYPoints.push(oLabel.y); aXPoints.push(oLabel.x + oLabel.txBody.content.XLimit); aYPoints.push(oLabel.y + oLabel.txBody.content.GetSummaryHeight()); } } if(aXPoints.length > 0 && aYPoints.length > 0) { oAxisLabels.x = Math.min.apply(Math, aXPoints); oAxisLabels.y = Math.min.apply(Math, aYPoints); oAxisLabels.extX = Math.max.apply(Math, aXPoints) - oAxisLabels.x; oAxisLabels.extY = Math.max.apply(Math, aYPoints) - oAxisLabels.y; } } } } } }; CChartSpace.prototype.hitInTextRect = function() { return false; }; CChartSpace.prototype.recalculateLegend = function() { if(this.chart && this.chart.legend) { var aSeries = this.getAllSeries(); var oParents = this.getParentObjects(); var oLegend = this.chart.legend; var parents = this.getParentObjects(); var RGBA = {R:0, G:0, B: 0, A:255}; var legend = this.chart.legend; var arr_str_labels = [], i; var calc_entryes = legend.calcEntryes; calc_entryes.length = 0; var series = this.getAllSeries(); var calc_entry, union_marker, entry; var max_width = 0, cur_width, max_font_size = 0, cur_font_size, ser, b_line_series; var max_word_width = 0; var b_no_line_series = false; this.chart.legend.chart = this; var b_scatter_no_line = false;/*(this.chart.plotArea.charts[0].getObjectType() === AscDFH.historyitem_type_ScatterChart && (this.chart.plotArea.charts[0].scatterStyle === AscFormat.SCATTER_STYLE_MARKER || this.chart.plotArea.charts[0].scatterStyle === AscFormat.SCATTER_STYLE_NONE)); */ this.legendLength = null; if( !(this.chart.plotArea.charts.length === 1 && this.chart.plotArea.charts[0].varyColors) || (this.chart.plotArea.charts[0].getObjectType() !== AscDFH.historyitem_type_PieChart && this.chart.plotArea.charts[0].getObjectType() !== AscDFH.historyitem_type_DoughnutChart) && series.length !== 1 || this.chart.plotArea.charts[0].getObjectType() === AscDFH.historyitem_type_SurfaceChart) { var bSurfaceChart = false; if(this.chart.plotArea.charts[0].getObjectType() === AscDFH.historyitem_type_SurfaceChart){ this.legendLength = this.chart.plotArea.charts[0].compiledBandFormats.length; ser = series[0]; bSurfaceChart = true; } else { this.legendLength = series.length; } for(i = 0; i < this.legendLength; ++i) { if(!bSurfaceChart){ ser = series[i]; if(ser.isHiddenForLegend) continue; entry = legend.findLegendEntryByIndex(i); if(entry && entry.bDelete) continue; arr_str_labels.push(ser.getSeriesName()); } else{ entry = legend.findLegendEntryByIndex(i); if(entry && entry.bDelete) continue; var oBandFmt = this.chart.plotArea.charts[0].compiledBandFormats[i]; arr_str_labels.push(oBandFmt.startValue + "-" + oBandFmt.endValue); } calc_entry = new AscFormat.CalcLegendEntry(legend, this, i); calc_entry.series = ser; calc_entry.txBody = AscFormat.CreateTextBodyFromString(arr_str_labels[arr_str_labels.length - 1], this.getDrawingDocument(), calc_entry); //if(entry) // calc_entry.txPr = entry.txPr; /*if(calc_entryes[0]) { calc_entry.lastStyleObject = calc_entryes[0].lastStyleObject; }*/ calc_entryes.push(calc_entry); cur_width = calc_entry.txBody.getRectWidth(2000); if(cur_width > max_width) max_width = cur_width; cur_font_size = calc_entry.txBody.content.Content[0].CompiledPr.Pr.TextPr.FontSize; if(cur_font_size > max_font_size) max_font_size = cur_font_size; calc_entry.calcMarkerUnion = new AscFormat.CUnionMarker(); union_marker = calc_entry.calcMarkerUnion; var pts = AscFormat.getPtsFromSeries(ser); switch(ser.getObjectType()) { case AscDFH.historyitem_type_BarSeries: case AscDFH.historyitem_type_BubbleSeries: case AscDFH.historyitem_type_AreaSeries: case AscDFH.historyitem_type_PieSeries: { union_marker.marker = AscFormat.CreateMarkerGeometryByType(AscFormat.SYMBOL_SQUARE, null); union_marker.marker.pen = ser.compiledSeriesPen; union_marker.marker.brush = ser.compiledSeriesBrush; break; } case AscDFH.historyitem_type_SurfaceSeries:{ var oBandFmt = this.chart.plotArea.charts[0].compiledBandFormats[i]; union_marker.marker = AscFormat.CreateMarkerGeometryByType(AscFormat.SYMBOL_SQUARE, null); union_marker.marker.pen = oBandFmt.spPr.ln; union_marker.marker.brush = oBandFmt.spPr.Fill; break; } case AscDFH.historyitem_type_LineSeries: case AscDFH.historyitem_type_ScatterSer: case AscDFH.historyitem_type_SurfaceSeries: { if(AscFormat.CChartsDrawer.prototype._isSwitchCurrent3DChart(this)) { union_marker.marker = AscFormat.CreateMarkerGeometryByType(AscFormat.SYMBOL_SQUARE, null); union_marker.marker.pen = ser.compiledSeriesPen; union_marker.marker.brush = ser.compiledSeriesBrush; break; } if(ser.compiledSeriesMarker) { var pts = AscFormat.getPtsFromSeries(ser); union_marker.marker = AscFormat.CreateMarkerGeometryByType(ser.compiledSeriesMarker.symbol, null); if(pts[0] && pts[0].compiledMarker) { union_marker.marker.brush = pts[0].compiledMarker.brush; union_marker.marker.pen = pts[0].compiledMarker.pen; } } if(ser.compiledSeriesPen && !b_scatter_no_line) { union_marker.lineMarker = AscFormat.CreateMarkerGeometryByType(AscFormat.SYMBOL_DASH, null); union_marker.lineMarker.pen = ser.compiledSeriesPen.createDuplicate(); //Копируем, так как потом возможно придется изменять толщину линии; } if(!b_scatter_no_line && !AscFormat.CChartsDrawer.prototype._isSwitchCurrent3DChart(this)) b_line_series = true; break; } } if(union_marker.marker) { union_marker.marker.pen && union_marker.marker.pen.calculate(parents.theme, parents.slide, parents.layout, parents.master, RGBA, this.clrMapOvr); union_marker.marker.brush && union_marker.marker.brush.calculate(parents.theme, parents.slide, parents.layout, parents.master, RGBA, this.clrMapOvr); } union_marker.lineMarker && union_marker.lineMarker.pen && union_marker.lineMarker.pen.calculate(parents.theme, parents.slide, parents.layout, parents.master, RGBA, this.clrMapOvr); } } else { ser = series[0]; i = 1; while(ser && ser.isHiddenForLegend) { ser = series[i]; ++i; } var pts = AscFormat.getPtsFromSeries(ser), pt; var cat_str_lit = getCatStringPointsFromSeries(ser); this.legendLength = pts.length; for(i = 0; i < pts.length; ++i) { entry = legend.findLegendEntryByIndex(i); if(entry && entry.bDelete) continue; pt = pts[i]; var str_pt = cat_str_lit ? cat_str_lit.getPtByIndex(pt.idx) : null; if(str_pt) arr_str_labels.push(str_pt.val); else arr_str_labels.push((pt.idx + 1) + ""); calc_entry = new AscFormat.CalcLegendEntry(legend, this, pt.idx); calc_entry.txBody = AscFormat.CreateTextBodyFromString(arr_str_labels[arr_str_labels.length - 1], this.getDrawingDocument(), calc_entry); //if(entry) // calc_entry.txPr = entry.txPr; //if(calc_entryes[0]) //{ // calc_entry.lastStyleObject = calc_entryes[0].lastStyleObject; //} calc_entryes.push(calc_entry); cur_width = calc_entry.txBody.getRectWidth(2000); if(cur_width > max_width) max_width = cur_width; cur_font_size = calc_entry.txBody.content.Content[0].CompiledPr.Pr.TextPr.FontSize; if(cur_font_size > max_font_size) max_font_size = cur_font_size; calc_entry.calcMarkerUnion = new AscFormat.CUnionMarker(); union_marker = calc_entry.calcMarkerUnion; if(ser.getObjectType() === AscDFH.historyitem_type_LineSeries && !AscFormat.CChartsDrawer.prototype._isSwitchCurrent3DChart(this) || ser.getObjectType() === AscDFH.historyitem_type_ScatterSer) { if(pt.compiledMarker) { union_marker.marker = AscFormat.CreateMarkerGeometryByType(pt.compiledMarker.symbol, null); union_marker.marker.brush = pt.compiledMarker.pen.Fill; union_marker.marker.pen = pt.compiledMarker.pen; } if(pt.pen) { union_marker.lineMarker = AscFormat.CreateMarkerGeometryByType(AscFormat.SYMBOL_DASH, null); union_marker.lineMarker.pen = pt.pen; } if(!b_scatter_no_line && !AscFormat.CChartsDrawer.prototype._isSwitchCurrent3DChart(this)) b_line_series = true; } else { b_no_line_series = false; union_marker.marker = AscFormat.CreateMarkerGeometryByType(AscFormat.SYMBOL_SQUARE, null); union_marker.marker.pen = pt.pen; union_marker.marker.brush = pt.brush; } if(union_marker.marker) { union_marker.marker.pen && union_marker.marker.pen.calculate(parents.theme, parents.slide, parents.layout, parents.master, RGBA, this.clrMapOvr); union_marker.marker.brush && union_marker.marker.brush.calculate(parents.theme, parents.slide, parents.layout, parents.master, RGBA, this.clrMapOvr); } union_marker.lineMarker && union_marker.lineMarker.pen && union_marker.lineMarker.pen.calculate(parents.theme, parents.slide, parents.layout, parents.master, RGBA, this.clrMapOvr); } } var marker_size; var distance_to_text; var line_marker_width; if(b_line_series) { marker_size = 2.5; line_marker_width = 7.7;//Пока так for(i = 0; i < calc_entryes.length; ++i) { calc_entry = calc_entryes[i]; if(calc_entry.calcMarkerUnion.lineMarker) { calc_entry.calcMarkerUnion.lineMarker.spPr.geometry.Recalculate(line_marker_width, 1); /*Excel не дает сделать толщину линии для маркера легенды больше определенной. Считаем, что это толщина равна 133000emu*/ if(calc_entry.calcMarkerUnion.lineMarker.pen && AscFormat.isRealNumber(calc_entry.calcMarkerUnion.lineMarker.pen.w) && calc_entry.calcMarkerUnion.lineMarker.pen.w > 133000) { calc_entry.calcMarkerUnion.lineMarker.pen.w = 133000; } calc_entry.calcMarkerUnion.lineMarker.penWidth = calc_entry.calcMarkerUnion.lineMarker.pen && AscFormat.isRealNumber(calc_entry.calcMarkerUnion.lineMarker.pen.w) ? calc_entry.calcMarkerUnion.lineMarker.pen.w/36000 : 0; } if(calc_entryes[i].calcMarkerUnion.marker) { var marker_width = marker_size; if(calc_entryes[i].series){ if(calc_entryes[i].series.getObjectType() !== AscDFH.historyitem_type_LineSeries && calc_entryes[i].series.getObjectType() !== AscDFH.historyitem_type_ScatterSer){ marker_width = line_marker_width; } } calc_entryes[i].calcMarkerUnion.marker.spPr.geometry.Recalculate(marker_width, marker_size); calc_entryes[i].calcMarkerUnion.marker.extX = marker_width; calc_entryes[i].calcMarkerUnion.marker.extY = marker_size; } } distance_to_text = 0.5; } else { marker_size = 0.2*max_font_size; for(i = 0; i < calc_entryes.length; ++i) { calc_entryes[i].calcMarkerUnion.marker.spPr.geometry.Recalculate(marker_size, marker_size); } distance_to_text = marker_size*0.8; } var left_inset = marker_size + 3*distance_to_text; var legend_pos = c_oAscChartLegendShowSettings.right; if(AscFormat.isRealNumber(legend.legendPos)) { legend_pos = legend.legendPos; } var legend_width, legend_height; var fFixedWidth = null, fFixedHeight = null; var bFixedSize = false; if(legend.layout){ fFixedWidth = this.calculateSizeByLayout(0, this.extX, legend.layout.w, legend.layout.wMode); fFixedHeight = this.calculateSizeByLayout(0, this.extY, legend.layout.h, legend.layout.hMode); bFixedSize = AscFormat.isRealNumber(fFixedWidth) && fFixedWidth > 0 && AscFormat.isRealNumber(fFixedHeight) && fFixedHeight > 0; if(bFixedSize){ var oOldLayout = legend.layout; legend.layout = null; this.recalculateLegend(); legend.naturalWidth = legend.extX; legend.naturalHeight = legend.extY; legend.layout = oOldLayout; } } if(AscFormat.isRealNumber(legend_pos)) { var max_legend_width, max_legend_height; var cut_index; if ((legend_pos === c_oAscChartLegendShowSettings.left || legend_pos === c_oAscChartLegendShowSettings.leftOverlay || legend_pos === c_oAscChartLegendShowSettings.right || legend_pos === c_oAscChartLegendShowSettings.rightOverlay || legend_pos === c_oAscChartLegendShowSettings.topRight) && !bFixedSize) { max_legend_width = this.extX/3;//Считаем, что ширина легенды не больше трети ширины всей диаграммы; var sizes = this.getChartSizes(); max_legend_height = sizes.h; if(b_line_series) { left_inset = line_marker_width + 3*distance_to_text; var content_width = max_legend_width - left_inset; if(content_width <= 0) content_width = 0.01; var cur_content_width, max_content_width = 0; var arr_heights = []; for(i = 0; i < calc_entryes.length; ++i) { calc_entry = calc_entryes[i]; cur_content_width = calc_entry.txBody.getMaxContentWidth(content_width, true); if(cur_content_width > max_content_width) max_content_width = cur_content_width; arr_heights.push(calc_entry.txBody.getSummaryHeight()); } if(max_content_width < max_legend_width - left_inset) { legend_width = max_content_width + left_inset; } else { legend_width = max_legend_width; } var max_entry_height2 = Math.max(0, Math.max.apply(Math, arr_heights)); for(i = 0; i < arr_heights.length; ++i) arr_heights[i] = max_entry_height2; var height_summ = 0; for(i = 0; i < arr_heights.length; ++i) { height_summ+=arr_heights[i]; if(height_summ > max_legend_height) { cut_index = i; break; } } if(AscFormat.isRealNumber(cut_index)) { if(cut_index > 0) { legend_height = height_summ - arr_heights[cut_index]; } else { legend_height = max_legend_height; } } else { cut_index = arr_heights.length; legend_height = height_summ; } legend.x = 0; legend.y = 0; legend.extX = legend_width; legend.extY = legend_height; var summ_h = 0; calc_entryes.splice(cut_index, calc_entryes.length - cut_index); for(i = 0; i < cut_index && i < calc_entryes.length; ++i) { calc_entry = calc_entryes[i]; if(calc_entry.calcMarkerUnion.marker) { calc_entry.calcMarkerUnion.marker.localX = distance_to_text + line_marker_width/2 - calc_entry.calcMarkerUnion.marker.extX/2; calc_entry.calcMarkerUnion.marker.localY = summ_h + (calc_entry.txBody.content.Content[0].Lines[0].Bottom - calc_entry.txBody.content.Content[0].Lines[0].Top)/2 - marker_size/2; calc_entry.localX = calc_entry.calcMarkerUnion.marker.localX + line_marker_width + distance_to_text; } if(calc_entry.calcMarkerUnion.lineMarker) { calc_entry.calcMarkerUnion.lineMarker.localX = distance_to_text; calc_entry.calcMarkerUnion.lineMarker.localY = summ_h + (calc_entry.txBody.content.Content[0].Lines[0].Bottom - calc_entry.txBody.content.Content[0].Lines[0].Top)/2;// - calc_entry.calcMarkerUnion.lineMarker.penWidth/2; calc_entry.localX = calc_entry.calcMarkerUnion.lineMarker.localX + line_marker_width + distance_to_text; } calc_entry.localY = summ_h; summ_h+=arr_heights[i]; } legend.setPosition(0, 0); } else { var content_width = max_legend_width - left_inset; if(content_width <= 0) content_width = 0.01; var cur_content_width, max_content_width = 0; var arr_heights = []; for(i = 0; i < calc_entryes.length; ++i) { calc_entry = calc_entryes[i]; cur_content_width = calc_entry.txBody.getMaxContentWidth(content_width, true); if(cur_content_width > max_content_width) max_content_width = cur_content_width; arr_heights.push(calc_entry.txBody.getSummaryHeight()); } var chart_object; if(this.chart && this.chart.plotArea && this.chart.plotArea.charts[0]) { chart_object = this.chart.plotArea.charts[0]; } var b_reverse_order = false; if(chart_object && chart_object.getObjectType() === AscDFH.historyitem_type_BarChart && chart_object.barDir === AscFormat.BAR_DIR_BAR && (cat_ax && cat_ax.scaling && AscFormat.isRealNumber(cat_ax.scaling.orientation) ? cat_ax.scaling.orientation : AscFormat.ORIENTATION_MIN_MAX) === AscFormat.ORIENTATION_MIN_MAX || chart_object && chart_object.getObjectType() === AscDFH.historyitem_type_SurfaceChart) { b_reverse_order = true; } var max_entry_height2 = Math.max(0, Math.max.apply(Math, arr_heights)); for(i = 0; i < arr_heights.length; ++i) arr_heights[i] = max_entry_height2; if(max_content_width < max_legend_width - left_inset) { legend_width = max_content_width + left_inset; } else { legend_width = max_legend_width; } var height_summ = 0; for(i = 0; i < arr_heights.length; ++i) { height_summ+=arr_heights[i]; if(height_summ > max_legend_height) { cut_index = i; break; } } if(AscFormat.isRealNumber(cut_index)) { if(cut_index > 0) { legend_height = height_summ - arr_heights[cut_index]; } else { legend_height = max_legend_height; } } else { cut_index = arr_heights.length; legend_height = height_summ; } legend.x = 0; legend.y = 0; legend.extX = legend_width; legend.extY = legend_height; var summ_h = 0; var b_reverse_order = false; var chart_object, cat_ax, start_index, end_index; if(this.chart && this.chart.plotArea && this.chart.plotArea.charts[0]) { chart_object = this.chart.plotArea.charts[0]; if(chart_object && chart_object.getAxisByTypes) { var axis_by_types = chart_object.getAxisByTypes(); cat_ax = axis_by_types.catAx[0]; } } if(chart_object && chart_object.getObjectType() === AscDFH.historyitem_type_BarChart && chart_object.barDir === AscFormat.BAR_DIR_BAR && (cat_ax && cat_ax.scaling && AscFormat.isRealNumber(cat_ax.scaling.orientation) ? cat_ax.scaling.orientation : AscFormat.ORIENTATION_MIN_MAX) === AscFormat.ORIENTATION_MIN_MAX) { b_reverse_order = true; } if(!b_reverse_order) { calc_entryes.splice(cut_index, calc_entryes.length - cut_index); for(i = 0; i < cut_index && i < calc_entryes.length; ++i) { calc_entry = calc_entryes[i]; if(calc_entry.calcMarkerUnion.marker) { calc_entry.calcMarkerUnion.marker.localX = distance_to_text; calc_entry.calcMarkerUnion.marker.localY = summ_h + (calc_entry.txBody.content.Content[0].Lines[0].Bottom - calc_entry.txBody.content.Content[0].Lines[0].Top)/2 - marker_size/2; } calc_entry.localX = 2*distance_to_text + marker_size; calc_entry.localY = summ_h; summ_h+=arr_heights[i]; } } else { calc_entryes.splice(0, calc_entryes.length - cut_index); for(i = calc_entryes.length-1; i > -1; --i) { calc_entry = calc_entryes[i]; if(calc_entry.calcMarkerUnion.marker) { calc_entry.calcMarkerUnion.marker.localX = distance_to_text; calc_entry.calcMarkerUnion.marker.localY = summ_h + (calc_entry.txBody.content.Content[0].Lines[0].Bottom - calc_entry.txBody.content.Content[0].Lines[0].Top)/2 - marker_size/2; } calc_entry.localX = 2*distance_to_text + marker_size; calc_entry.localY = summ_h; summ_h+=arr_heights[i]; } } legend.setPosition(0, 0); } } else { /*пока сделаем так: максимальная ширимна 0.9 от ширины дмаграммы без заголовка максимальная высота легенды 0.6 от высоты диаграммы, с заголовком 0.6 от высоты за вычетом высоты заголовка*/ if(bFixedSize){ max_legend_width = fFixedWidth; max_legend_height = fFixedHeight; } else{ max_legend_width = 0.9*this.extX; max_legend_height = (this.extY - (this.chart.title ? this.chart.title.extY : 0))*0.6; } if(b_line_series) { //сначала найдем максимальную ширину записи. ширина записи получается как отступ слева от маркера + ширина маркера + отступ справа от маркера + ширина текста var max_entry_width = 0, cur_entry_width, cur_entry_height; //найдем максимальную ширину надписи var left_width = line_marker_width + 3*distance_to_text; var arr_width = [], arr_height = []; //массив ширин записей var summ_width = 0;//сумма ширин всех подписей for(i = 0; i < calc_entryes.length; ++i) { calc_entry = calc_entryes[i]; cur_entry_width = calc_entry.txBody.getMaxContentWidth(20000/*ставим большое число чтобы текст расчитался в одну строчку*/, true); if(cur_entry_width > max_entry_width) max_entry_width = cur_entry_width; arr_height.push(calc_entry.txBody.getSummaryHeight()); arr_width.push(cur_entry_width+left_width); summ_width+=arr_width[arr_width.length-1]; } var max_entry_height = Math.max(0, Math.max.apply(Math, arr_height)); var cur_left_x = 0; if(summ_width < max_legend_width)//значит все надписи убираются в одну строчку { if(bFixedSize){ cur_left_x = max_legend_width - summ_width; } /*прибавим справа ещё боковой зазаор и посмотрим уберется ли новая ширина в максимальную ширину*/ if(summ_width + distance_to_text < max_legend_width && !bFixedSize) legend_width = summ_width + distance_to_text; else legend_width = max_legend_width; legend_height = max_entry_height; if(bFixedSize){ legend_height = max_legend_height; } for(i = 0; i < calc_entryes.length; ++i) { calc_entry = calc_entryes[i]; if(calc_entry.calcMarkerUnion.marker) calc_entry.calcMarkerUnion.marker.localX = cur_left_x + distance_to_text + line_marker_width/2 - marker_size/2; calc_entry.calcMarkerUnion.lineMarker.localX = cur_left_x + distance_to_text; calc_entry.calcMarkerUnion.lineMarker.localY = Math.max(0, legend_height/2); cur_left_x += arr_width[i]; if(calc_entry.calcMarkerUnion.marker) calc_entry.calcMarkerUnion.marker.localY = Math.max(0, legend_height/2 - marker_size/2); calc_entry.localX = calc_entry.calcMarkerUnion.lineMarker.localX+line_marker_width+distance_to_text; calc_entry.localY = 0; } legend.extX = legend_width; legend.extY = legend_height; legend.setPosition(0, 0); } else if(max_legend_width >= max_entry_width + left_width) { var hor_count = (max_legend_width/(max_entry_width + left_width)) >> 0;//количество записей в одной строке var vert_count;//количество строк var t = calc_entryes.length / hor_count; if(t - (t >> 0) > 0) vert_count = t+1; else vert_count = t; //посмотрим убираются ли все эти строки в максимальную высоту. те которые не убираются обрежем, кроме первой. legend_width = hor_count*(max_legend_width + left_width); if(legend_width + distance_to_text <= max_legend_width && !bFixedSize) legend_width += distance_to_text; else legend_width = max_legend_width; if(bFixedSize){ max_legend_height = fFixedHeight; } var max_line_count = (max_legend_height/max_entry_height)>>0; //максимальное количество строчек в легенде; if(vert_count <= max_line_count) { cut_index = calc_entryes.length; legend_height = vert_count*max_entry_height; } else { if(max_line_count === 0) { cut_index = hor_count + 1; legend_height = max_entry_height; } else { cut_index = max_line_count*hor_count+1; legend_height = max_entry_height*max_line_count; } } var fStartH = 0; if(bFixedSize){ fStartH = Math.max(0, (fFixedHeight - legend_height)/2); legend_height = fFixedHeight; } legend.extX = legend_width; legend.extY = legend_height; calc_entryes.splice(cut_index, calc_entryes.length - cut_index); for(i = 0; i < cut_index && i < calc_entryes.length; ++i) { calc_entry = calc_entryes[i]; calc_entry.calcMarkerUnion.lineMarker.localX = (i - hor_count*((i/hor_count) >> 0))*(max_entry_width + line_marker_width + 2*distance_to_text) + distance_to_text; calc_entry.calcMarkerUnion.lineMarker.localY = fStartH + ((i/hor_count) >> 0)*(max_entry_height) + max_entry_height/2; if(calc_entry.calcMarkerUnion.marker) { calc_entry.calcMarkerUnion.marker.localX = calc_entry.calcMarkerUnion.lineMarker.localX + line_marker_width/2 - marker_size/2; calc_entry.calcMarkerUnion.marker.localY = calc_entry.calcMarkerUnion.lineMarker.localY - marker_size/2; } calc_entry.localX = calc_entry.calcMarkerUnion.lineMarker.localX + line_marker_width + distance_to_text; calc_entry.localY = fStartH + ((i/hor_count) >> 0)*(max_entry_height); } legend.setPosition(0, 0); } else { //значит максималная по ширине надпись не убирается в рект для легенды var content_width = max_legend_width - 2*distance_to_text - marker_size; if(content_width <= 0) content_width = 0.01; var cur_content_width, max_content_width = 0; var arr_heights = []; for(i = 0; i < calc_entryes.length; ++i) { calc_entry = calc_entryes[i]; cur_content_width = calc_entry.txBody.getMaxContentWidth(content_width, true); if(cur_content_width > max_content_width) max_content_width = cur_content_width; arr_heights.push(calc_entry.txBody.getSummaryHeight()); } if(max_content_width < max_legend_width - left_inset && !bFixedSize) { legend_width = max_content_width + left_inset; } else { legend_width = max_legend_width; } var height_summ = 0; for(i = 0; i < arr_heights.length; ++i) { height_summ+=arr_heights[i]; if(height_summ > max_legend_height) { cut_index = i; break; } } if(AscFormat.isRealNumber(cut_index)) { if(cut_index > 0) { legend_height = height_summ - arr_heights[cut_index]; } else { legend_height = max_legend_height; } } else { cut_index = arr_heights.length; legend_height = height_summ; } if(bFixedSize){ legend_height = max_legend_height; } legend.x = 0; legend.y = 0; legend.extX = legend_width; legend.extY = legend_height; var summ_h = 0; if(bFixedSize){ summ_h = (legend_height - height_summ)/2; } calc_entryes.splice(cut_index, calc_entryes.length - cut_index); for(i = 0; i < cut_index && i < calc_entryes.length; ++i) { calc_entry = calc_entryes[i]; calc_entry.calcMarkerUnion.lineMarker.localX = distance_to_text; calc_entry.calcMarkerUnion.lineMarker.localY = summ_h + (calc_entry.txBody.content.Content[0].Lines[0].Bottom - calc_entry.txBody.content.Content[0].Lines[0].Top)/2;// - calc_entry.calcMarkerUnion.lineMarker.penWidth/2; calc_entry.localX = calc_entry.calcMarkerUnion.lineMarker.localX + line_marker_width + distance_to_text; calc_entry.localY = summ_h; if(calc_entry.calcMarkerUnion.marker) { calc_entry.calcMarkerUnion.marker.localX = calc_entry.calcMarkerUnion.lineMarker.localX + line_marker_width/2 - marker_size/2; calc_entry.calcMarkerUnion.marker.localY = calc_entry.calcMarkerUnion.lineMarker.localY - marker_size/2; } //calc_entry.localX = 2*distance_to_text + marker_size; //calc_entry.localY = summ_h; summ_h+=arr_heights[i]; } legend.setPosition(0, 0); } } else { //сначала найдем максимальную ширину записи. ширина записи получается как отступ слева от маркера + ширина маркера + отступ справа от маркера + ширина текста var max_entry_width = 0, cur_entry_width, cur_entry_height; //найдем максимальную ширину надписи var left_width = marker_size + 2*distance_to_text; var arr_width = [], arr_height = []; //массив ширин записей var summ_width = 0;//сумма ширин всех подписей for(i = 0; i < calc_entryes.length; ++i) { calc_entry = calc_entryes[i]; cur_entry_width = calc_entry.txBody.getMaxContentWidth(20000/*ставим большое число чтобы текст расчитался в одну строчку*/, true); if(cur_entry_width > max_entry_width) max_entry_width = cur_entry_width; arr_height.push(calc_entry.txBody.getSummaryHeight()); arr_width.push(cur_entry_width+left_width); summ_width += arr_width[arr_width.length-1]; } var max_entry_height = Math.max(0, Math.max.apply(Math, arr_height)); var cur_left_x = 0; if(summ_width < max_legend_width)//значит все надписи убираются в одну строчку { /*прибавим справа ещё боковой зазаор и посмотрим уберется ли новая ширина в максимальную ширину*/ if(summ_width + distance_to_text < max_legend_width && !bFixedSize) legend_width = summ_width + distance_to_text; else legend_width = max_legend_width; legend_height = max_entry_height; if(bFixedSize){ cur_left_x = (max_legend_width - summ_width)/2; legend_height = max_legend_height; } for(i = 0; i < calc_entryes.length; ++i) { calc_entry = calc_entryes[i]; calc_entry.calcMarkerUnion.marker.localX = cur_left_x + distance_to_text; cur_left_x += arr_width[i]; calc_entry.calcMarkerUnion.marker.localY = legend_height/2 - marker_size/2; calc_entry.localX = calc_entry.calcMarkerUnion.marker.localX+marker_size+distance_to_text; calc_entry.localY = calc_entry.calcMarkerUnion.marker.localY - marker_size/2; } legend.extX = legend_width; legend.extY = legend_height; legend.setPosition(0, 0); } else if(max_legend_width >= max_entry_width + left_width) { var hor_count = (max_legend_width/(max_entry_width + left_width)) >> 0;//количество записей в одной строке var vert_count;//количество строк var t = calc_entryes.length / hor_count; if(t - (t >> 0) > 0) vert_count = (t+1) >> 0; else vert_count = t >> 0; //посмотрим убираются ли все эти строки в максимальную высоту. те которые не убираются обрежем, кроме первой. var fStartHorPos = 0; legend_width = hor_count*(max_entry_width + left_width); if(legend_width + distance_to_text <= max_legend_width && !bFixedSize) legend_width += distance_to_text; else{ if(bFixedSize){ fStartHorPos = (max_legend_width - legend_width)/2; } legend_width = max_legend_width; } var max_line_count = (max_legend_height/max_entry_height)>>0; //максимальное количество строчек в легенде; if(vert_count <= max_line_count) { cut_index = calc_entryes.length; legend_height = vert_count*max_entry_height; } else { if(max_line_count === 0) { cut_index = hor_count + 1; legend_height = max_entry_height; } else { cut_index = max_line_count*hor_count+1; legend_height = max_entry_height*max_line_count; } } var fStartH = 0; var fDistance = 0; if(bFixedSize){ fDistance = Math.max(0,(max_legend_height - max_entry_height*vert_count)/vert_count); fStartH = Math.max(0, fDistance/2); legend_height = max_legend_height; } legend.extX = legend_width; legend.extY = legend_height; calc_entryes.splice(cut_index, calc_entryes.length - cut_index); for(i = 0; i <cut_index && i < calc_entryes.length; ++i) { calc_entry = calc_entryes[i]; calc_entry.calcMarkerUnion.marker.localX = fStartHorPos + (i - hor_count*((i/hor_count) >> 0))*(max_entry_width + marker_size + 2*distance_to_text) + distance_to_text; var nHorCount = (i/hor_count) >> 0; calc_entry.calcMarkerUnion.marker.localY = fStartH + (nHorCount)*(max_entry_height) + max_entry_height/2 - marker_size/2 + nHorCount*fDistance; calc_entry.localX = calc_entry.calcMarkerUnion.marker.localX + marker_size + distance_to_text; calc_entry.localY = fStartH + nHorCount*(max_entry_height) + nHorCount*fDistance; } legend.setPosition(0, 0); } else { //значит максималная по ширине надпись не убирается в рект для легенды var content_width = max_legend_width - 2*distance_to_text - marker_size; if(content_width <= 0) content_width = 0.01; var cur_content_width, max_content_width = 0; var arr_heights = []; for(i = 0; i < calc_entryes.length; ++i) { calc_entry = calc_entryes[i]; cur_content_width = calc_entry.txBody.getMaxContentWidth(content_width, true); if(cur_content_width > max_content_width) max_content_width = cur_content_width; arr_heights.push(calc_entry.txBody.getSummaryHeight()); } max_entry_height = Math.max(0, Math.max.apply(Math, arr_heights)); if(max_content_width < max_legend_width - left_inset && !bFixedSize) { legend_width = max_content_width + left_inset; } else { legend_width = max_legend_width; } var height_summ = 0; for(i = 0; i < arr_heights.length; ++i) { height_summ+=arr_heights[i]; if(height_summ > max_legend_height) { cut_index = i; break; } } if(AscFormat.isRealNumber(cut_index)) { if(cut_index > 0) { legend_height = height_summ - arr_heights[cut_index]; } else { legend_height = max_legend_height; } } else { cut_index = arr_heights.length; legend_height = height_summ; } var fStartH = 0; var fDistance = 0; if(bFixedSize){ fDistance = Math.max(0,(max_legend_height - max_entry_height*cut_index)/cut_index); fStartH = Math.max(0, fDistance/2); legend_height = max_legend_height; } legend.x = 0; legend.y = 0; legend.extX = legend_width; legend.extY = legend_height; calc_entryes.splice(cut_index, calc_entryes.length - cut_index); for(i = 0; i < cut_index && i < calc_entryes.length; ++i) { calc_entry = calc_entryes[i]; calc_entry.localX = 2*distance_to_text + marker_size; calc_entry.localY = fStartH + i*max_entry_height + i*fDistance; calc_entry.calcMarkerUnion.marker.localX = distance_to_text; calc_entry.calcMarkerUnion.marker.localY = calc_entry.localY + (calc_entry.txBody.content.Content[0].Lines[0].Bottom - calc_entry.txBody.content.Content[0].Lines[0].Top)/2 - marker_size/2; } legend.setPosition(0, 0); } } } } else { //TODO } legend.recalcInfo = {recalculateLine: true, recalculateFill: true, recalculateTransparent: true}; legend.recalculatePen(); legend.recalculateBrush(); for(var i = 0; i < calc_entryes.length; ++i) { calc_entryes[i].checkWidhtContent(); } } }; CChartSpace.prototype.internalCalculatePenBrushFloorWall = function(oSide, nSideType) { if(!oSide) { return; } var parent_objects = this.getParentObjects(); if(oSide.spPr && oSide.spPr.ln) { oSide.pen = oSide.spPr.ln.createDuplicate(); } else { var oCompiledPen = null; if(this.style >= 1 && this.style <= 40 && 2 === nSideType) { if(parent_objects.theme && parent_objects.theme.themeElements && parent_objects.theme.themeElements.fmtScheme && parent_objects.theme.themeElements.fmtScheme.lnStyleLst && parent_objects.theme.themeElements.fmtScheme.lnStyleLst[0]) { oCompiledPen = parent_objects.theme.themeElements.fmtScheme.lnStyleLst[0].createDuplicate(); if(this.style >= 1 && this.style <= 32) { oCompiledPen.Fill = CreateUnifillSolidFillSchemeColor(15, 0.75); } else { oCompiledPen.Fill = CreateUnifillSolidFillSchemeColor(8, 0.75); } } } oSide.pen = oCompiledPen; } if(this.style >= 1 && this.style <= 32) { if(oSide.spPr && oSide.spPr.Fill) { oSide.brush = oSide.spPr.Fill.createDuplicate(); if(nSideType === 0 || nSideType === 2) { var cColorMod = new AscFormat.CColorMod; if(nSideType === 2) cColorMod.val = 45000; else cColorMod.val = 35000; cColorMod.name = "shade"; oSide.brush.addColorMod(cColorMod); } } else { oSide.brush = null; } } else { var oSubtleFill; if(parent_objects.theme && parent_objects.theme.themeElements && parent_objects.theme.themeElements.fmtScheme && parent_objects.theme.themeElements.fmtScheme.fillStyleLst) { oSubtleFill = parent_objects.theme.themeElements.fmtScheme.fillStyleLst[0]; } var oDefaultBrush; var tint = 0.20000; if(this.style >=33 && this.style <= 34) oDefaultBrush = CreateUnifillSolidFillSchemeColor(8, 0.20000); else if(this.style >=35 && this.style <=40) oDefaultBrush = CreateUnifillSolidFillSchemeColor(this.style - 35, tint); else oDefaultBrush = CreateUnifillSolidFillSchemeColor(8, 0.95000); if(oSide.spPr) { oDefaultBrush.merge(oSide.spPr.Fill); } if(nSideType === 0 || nSideType === 2) { var cColorMod = new AscFormat.CColorMod; if(nSideType === 0) cColorMod.val = 45000; else cColorMod.val = 35000; cColorMod.name = "shade"; oDefaultBrush.addColorMod(cColorMod); } oSide.brush = oDefaultBrush; } if(oSide.brush) { oSide.brush.calculate(parent_objects.theme, parent_objects.slide, parent_objects.layout, parent_objects.master, {R: 0, G: 0, B: 0, A: 255}, this.clrMapOvr); } if(oSide.pen) { oSide.pen.calculate(parent_objects.theme, parent_objects.slide, parent_objects.layout, parent_objects.master, {R: 0, G: 0, B: 0, A: 255}, this.clrMapOvr); } }; CChartSpace.prototype.recalculateWalls = function() { if(this.chart) { this.internalCalculatePenBrushFloorWall(this.chart.sideWall, 0); this.internalCalculatePenBrushFloorWall(this.chart.backWall, 1); this.internalCalculatePenBrushFloorWall(this.chart.floor, 2); } }; CChartSpace.prototype.recalculateUpDownBars = function() { if(this.chart && this.chart.plotArea) { var aCharts = this.chart.plotArea.charts; for(var t = 0; t < aCharts.length; ++t){ var oChart = aCharts[t]; if(oChart && oChart.upDownBars){ var bars = oChart.upDownBars; var up_bars = bars.upBars; var down_bars = bars.downBars; var parents = this.getParentObjects(); bars.upBarsBrush = null; bars.upBarsPen = null; bars.downBarsBrush = null; bars.downBarsPen = null; if(up_bars || down_bars) { var default_bar_line = new AscFormat.CLn(); if(parents.theme && parents.theme.themeElements && parents.theme.themeElements.fmtScheme && parents.theme.themeElements.fmtScheme.lnStyleLst) { default_bar_line.merge(parents.theme.themeElements.fmtScheme.lnStyleLst[0]); } if(this.style >= 1 && this.style <= 16) default_bar_line.setFill(CreateUnifillSolidFillSchemeColor(15, 0)); else if(this.style >= 17 && this.style <= 32 || this.style >= 41 && this.style <= 48) default_bar_line = CreateNoFillLine(); else if(this.style === 33 || this.style === 34) default_bar_line.setFill(CreateUnifillSolidFillSchemeColor(8, 0)); else if(this.style >= 35 && this.style <= 40) default_bar_line.setFill(CreateUnifillSolidFillSchemeColor(this.style - 35, -0.25000)); } if(up_bars) { var default_up_bars_fill; if(this.style === 1 || this.style === 9 || this.style === 17 || this.style === 25 || this.style === 41) { default_up_bars_fill = CreateUnifillSolidFillSchemeColor(8, 0.25000); } else if(this.style === 2 || this.style === 10 || this.style === 18 || this.style === 26) { default_up_bars_fill = CreateUnifillSolidFillSchemeColor(8, 0.05000); } else if(this.style >= 3 && this.style <= 8) { default_up_bars_fill = CreateUnifillSolidFillSchemeColor(this.style - 3, 0.25000); } else if(this.style >= 11 && this.style <= 16) { default_up_bars_fill = CreateUnifillSolidFillSchemeColor(this.style - 11, 0.25000); } else if(this.style >=19 && this.style <= 24) { default_up_bars_fill = CreateUnifillSolidFillSchemeColor(this.style - 19, 0.25000); } else if(this.style >= 27 && this.style <= 32 ) { default_up_bars_fill = CreateUnifillSolidFillSchemeColor(this.style - 27, 0.25000); } else if(this.style >= 33 && this.style <= 40 || this.style === 42) { default_up_bars_fill = CreateUnifillSolidFillSchemeColor(12, 0); } else { default_up_bars_fill = CreateUnifillSolidFillSchemeColor(this.style - 43, 0.25000); } if(up_bars.Fill) { default_up_bars_fill.merge(up_bars.Fill); } default_up_bars_fill.calculate(parents.theme, parents.slide, parents.layout, parents.master, {R: 0, G: 0, B: 0, A: 255}, this.clrMapOvr); oChart.upDownBars.upBarsBrush = default_up_bars_fill; var up_bars_line = default_bar_line.createDuplicate(); if(up_bars.ln) up_bars_line.merge(up_bars.ln); up_bars_line.calculate(parents.theme, parents.slide, parents.layout, parents.master, {R: 0, G: 0, B: 0, A: 255}, this.clrMapOvr); oChart.upDownBars.upBarsPen = up_bars_line; } if(down_bars) { var default_down_bars_fill; if(this.style === 1 || this.style === 9 || this.style === 17 || this.style === 25 || this.style === 41 || this.style === 33) { default_down_bars_fill = CreateUnifillSolidFillSchemeColor(8, 0.85000); } else if(this.style === 2 || this.style === 10 || this.style === 18 || this.style === 26 || this.style === 34) { default_down_bars_fill = CreateUnifillSolidFillSchemeColor(8, 0.95000); } else if(this.style >= 3 && this.style <= 8) { default_down_bars_fill = CreateUnifillSolidFillSchemeColor(this.style - 3, -0.25000); } else if(this.style >= 11 && this.style <= 16) { default_down_bars_fill = CreateUnifillSolidFillSchemeColor(this.style - 11, -0.25000); } else if(this.style >=19 && this.style <= 24) { default_down_bars_fill = CreateUnifillSolidFillSchemeColor(this.style - 19, -0.25000); } else if(this.style >= 27 && this.style <= 32 ) { default_down_bars_fill = CreateUnifillSolidFillSchemeColor(this.style - 27, -0.25000); } else if(this.style >= 35 && this.style <= 40) { default_down_bars_fill = CreateUnifillSolidFillSchemeColor(this.style - 35, -0.25000); } else if(this.style === 42) { default_down_bars_fill = CreateUnifillSolidFillSchemeColor(8, 0); } else { default_down_bars_fill = CreateUnifillSolidFillSchemeColor(this.style - 43, -0.25000); } if(down_bars.Fill) { default_down_bars_fill.merge(down_bars.Fill); } default_down_bars_fill.calculate(parents.theme, parents.slide, parents.layout, parents.master, {R: 0, G: 0, B: 0, A: 255}, this.clrMapOvr); oChart.upDownBars.downBarsBrush = default_down_bars_fill; var down_bars_line = default_bar_line.createDuplicate(); if(down_bars.ln) down_bars_line.merge(down_bars.ln); down_bars_line.calculate(parents.theme, parents.slide, parents.layout, parents.master, {R: 0, G: 0, B: 0, A: 255}, this.clrMapOvr); oChart.upDownBars.downBarsPen = down_bars_line; } } } } }; CChartSpace.prototype.recalculatePlotAreaChartPen = function() { if(this.chart && this.chart.plotArea) { if(this.chart.plotArea.spPr && this.chart.plotArea.spPr.ln) { this.chart.plotArea.pen = this.chart.plotArea.spPr.ln; var parents = this.getParentObjects(); this.chart.plotArea.pen.calculate(parents.theme, parents.slide, parents.layout, parents.master, {R: 0, G: 0, B: 0, A: 255}, this.clrMapOvr); } else { this.chart.plotArea.pen = null; } } }; CChartSpace.prototype.recalculatePenBrush = function() { var parents = this.getParentObjects(), RGBA = {R: 0, G: 0, B: 0, A: 255}; if(this.brush) { this.brush.calculate(parents.theme, parents.slide, parents.layout, parents.master, RGBA, this.clrMapOvr); } if(this.pen) { this.pen.calculate(parents.theme, parents.slide, parents.layout, parents.master, RGBA, this.clrMapOvr); checkBlackUnifill(this.pen.Fill, true); } if(this.chart) { if(this.chart.title) { if(this.chart.title.brush) { this.chart.title.brush.calculate(parents.theme, parents.slide, parents.layout, parents.master, RGBA, this.clrMapOvr); } if(this.chart.title.pen) { this.chart.title.pen.calculate(parents.theme, parents.slide, parents.layout, parents.master, RGBA, this.clrMapOvr); } } if(this.chart.plotArea) { if(this.chart.plotArea.brush) { this.chart.plotArea.brush.calculate(parents.theme, parents.slide, parents.layout, parents.master, RGBA, this.clrMapOvr); } if(this.chart.plotArea.pen) { this.chart.plotArea.pen.calculate(parents.theme, parents.slide, parents.layout, parents.master, RGBA, this.clrMapOvr); } if(this.chart.plotArea.valAx) { if(this.chart.plotArea.valAx.compiledTickMarkLn) { this.chart.plotArea.valAx.compiledTickMarkLn.calculate(parents.theme, parents.slide, parents.layout, parents.master, RGBA, this.clrMapOvr); checkBlackUnifill(this.chart.plotArea.valAx.compiledTickMarkLn.Fill, true); } if(this.chart.plotArea.valAx.compiledMajorGridLines) { this.chart.plotArea.valAx.compiledMajorGridLines.calculate(parents.theme, parents.slide, parents.layout, parents.master, RGBA, this.clrMapOvr); checkBlackUnifill(this.chart.plotArea.valAx.compiledMajorGridLines.Fill, true); } if(this.chart.plotArea.valAx.compiledMinorGridLines) { this.chart.plotArea.valAx.compiledMinorGridLines.calculate(parents.theme, parents.slide, parents.layout, parents.master, RGBA, this.clrMapOvr); checkBlackUnifill(this.chart.plotArea.valAx.compiledMinorGridLines.Fill, true); } if(this.chart.plotArea.valAx.title) { if(this.chart.plotArea.valAx.title.brush) { this.chart.plotArea.valAx.title.brush.calculate(parents.theme, parents.slide, parents.layout, parents.master, RGBA, this.clrMapOvr); } if(this.chart.plotArea.valAx.title.pen) { this.chart.plotArea.valAx.title.pen.calculate(parents.theme, parents.slide, parents.layout, parents.master, RGBA, this.clrMapOvr); } } } if(this.chart.plotArea.catAx) { if(this.chart.plotArea.catAx.compiledTickMarkLn) { this.chart.plotArea.catAx.compiledTickMarkLn.calculate(parents.theme, parents.slide, parents.layout, parents.master, RGBA, this.clrMapOvr); checkBlackUnifill(this.chart.plotArea.catAx.compiledTickMarkLn.Fill, true); } if(this.chart.plotArea.catAx.compiledMajorGridLines) { this.chart.plotArea.catAx.compiledMajorGridLines.calculate(parents.theme, parents.slide, parents.layout, parents.master, RGBA, this.clrMapOvr); checkBlackUnifill(this.chart.plotArea.catAx.compiledMajorGridLines.Fill, true); } if(this.chart.plotArea.catAx.compiledMinorGridLines) { this.chart.plotArea.catAx.compiledMinorGridLines.calculate(parents.theme, parents.slide, parents.layout, parents.master, RGBA, this.clrMapOvr); checkBlackUnifill(this.chart.plotArea.catAx.compiledMinorGridLines.Fill, true); } if(this.chart.plotArea.catAx.title) { if(this.chart.plotArea.catAx.title.brush) { this.chart.plotArea.catAx.title.brush.calculate(parents.theme, parents.slide, parents.layout, parents.master, RGBA, this.clrMapOvr); } if(this.chart.plotArea.catAx.title.pen) { this.chart.plotArea.catAx.title.pen.calculate(parents.theme, parents.slide, parents.layout, parents.master, RGBA, this.clrMapOvr); } } } if(this.chart.plotArea.charts[0]) { var series = this.chart.plotArea.charts[0].series; for(var i = 0; i < series.length; ++i) { var pts = AscFormat.getPtsFromSeries(series[i]); for(var j = 0; j < pts.length; ++j) { var pt = pts[j]; if(pt.brush) { pt.brush.calculate(parents.theme, parents.slide, parents.layout, parents.master, RGBA, this.clrMapOvr); } if(pt.pen) { pt.pen.calculate(parents.theme, parents.slide, parents.layout, parents.master, RGBA, this.clrMapOvr); } if(pt.compiledMarker) { if(pt.compiledMarker.brush) { pt.compiledMarker.brush.calculate(parents.theme, parents.slide, parents.layout, parents.master, RGBA, this.clrMapOvr); } if(pt.compiledMarker.pen) { pt.compiledMarker.pen.calculate(parents.theme, parents.slide, parents.layout, parents.master, RGBA, this.clrMapOvr); } } if(pt.compiledDlb) { if(pt.compiledDlb.brush) { pt.compiledDlb.brush.calculate(parents.theme, parents.slide, parents.layout, parents.master, RGBA, this.clrMapOvr); } if(pt.compiledDlb.pen) { pt.compiledDlb.pen.calculate(parents.theme, parents.slide, parents.layout, parents.master, RGBA, this.clrMapOvr); } } } } if(this.chart.plotArea.charts[0].calculatedHiLowLines) { this.chart.plotArea.charts[0].calculatedHiLowLines.calculate(parents.theme, parents.slide, parents.layout, parents.master, RGBA, this.clrMapOvr); } if( this.chart.plotArea.charts[0].upDownBars) { if(this.chart.plotArea.charts[0].upDownBars.upBarsBrush) { this.chart.plotArea.charts[0].upDownBars.upBarsBrush.calculate(parents.theme, parents.slide, parents.layout, parents.master, RGBA, this.clrMapOvr); } if(this.chart.plotArea.charts[0].upDownBars.upBarsPen) { this.chart.plotArea.charts[0].upDownBars.upBarsPen.calculate(parents.theme, parents.slide, parents.layout, parents.master, RGBA, this.clrMapOvr); } if(this.chart.plotArea.charts[0].upDownBars.downBarsBrush) { this.chart.plotArea.charts[0].upDownBars.downBarsBrush.calculate(parents.theme, parents.slide, parents.layout, parents.master, RGBA, this.clrMapOvr); } if(this.chart.plotArea.charts[0].upDownBars.downBarsPen) { this.chart.plotArea.charts[0].upDownBars.downBarsPen.calculate(parents.theme, parents.slide, parents.layout, parents.master, RGBA, this.clrMapOvr); } } } } if(this.chart.legend) { if(this.chart.legend.brush) { this.chart.legend.brush.calculate(parents.theme, parents.slide, parents.layout, parents.master, RGBA, this.clrMapOvr); } if(this.chart.legend.pen) { this.chart.legend.pen.calculate(parents.theme, parents.slide, parents.layout, parents.master, RGBA, this.clrMapOvr); } var legend = this.chart.legend; for(var i = 0; i < legend.calcEntryes.length; ++i) { var union_marker = legend.calcEntryes[i].calcMarkerUnion; if(union_marker) { if(union_marker.marker) { if(union_marker.marker.pen) { union_marker.marker.pen.calculate(parents.theme, parents.slide, parents.layout, parents.master, RGBA, this.clrMapOvr); } if(union_marker.marker.brush) { union_marker.marker.brush.calculate(parents.theme, parents.slide, parents.layout, parents.master, RGBA, this.clrMapOvr); } } if(union_marker.lineMarker) { if(union_marker.lineMarker.pen) { union_marker.lineMarker.pen.calculate(parents.theme, parents.slide, parents.layout, parents.master, RGBA, this.clrMapOvr); } if(union_marker.lineMarker.brush) { union_marker.lineMarker.brush.calculate(parents.theme, parents.slide, parents.layout, parents.master, RGBA, this.clrMapOvr); } } } } } if(this.chart.floor) { if(this.chart.floor.brush) { this.chart.floor.brush.calculate(parents.theme, parents.slide, parents.layout, parents.master, RGBA, this.clrMapOvr); } if(this.chart.floor.pen) { this.chart.floor.pen.calculate(parents.theme, parents.slide, parents.layout, parents.master, RGBA, this.clrMapOvr); } } if(this.chart.sideWall) { if(this.chart.sideWall.brush) { this.chart.sideWall.brush.calculate(parents.theme, parents.slide, parents.layout, parents.master, RGBA, this.clrMapOvr); } if(this.chart.sideWall.pen) { this.chart.sideWall.pen.calculate(parents.theme, parents.slide, parents.layout, parents.master, RGBA, this.clrMapOvr); } } if(this.chart.backWall) { if(this.chart.backWall.brush) { this.chart.backWall.brush.calculate(parents.theme, parents.slide, parents.layout, parents.master, RGBA, this.clrMapOvr); } if(this.chart.backWall.pen) { this.chart.backWall.pen.calculate(parents.theme, parents.slide, parents.layout, parents.master, RGBA, this.clrMapOvr); } } } }; function fSaveChartObjectSourceFormatting(oObject, oObjectCopy, oTheme, oColorMap){ if(oObject === oObjectCopy || !oObjectCopy || !oObject){ return; } if(oObject.pen || oObject.brush){ if(oObject.pen || oObject.brush){ if(!oObjectCopy.spPr){ if(oObjectCopy.setSpPr){ oObjectCopy.setSpPr(new AscFormat.CSpPr()); oObjectCopy.spPr.setParent(oObjectCopy); } } if(oObject.brush){ oObjectCopy.spPr.setFill(oObject.brush.saveSourceFormatting()); } if(oObject.pen){ oObjectCopy.spPr.setLn(oObject.pen.createDuplicate(true)); } } } if(oObject.txPr && oObject.txPr.content){ AscFormat.SaveContentSourceFormatting(oObject.txPr.content.Content, oObjectCopy.txPr.content.Content, oTheme, oColorMap); } if(oObject.tx && oObject.tx.rich && oObject.tx.rich.content){ AscFormat.SaveContentSourceFormatting(oObject.tx.rich.content.Content, oObjectCopy.tx.rich.content.Content, oTheme, oColorMap); } } CChartSpace.prototype.getCopyWithSourceFormatting = function(oIdMap) { var oCopy = this.copy(this.getDrawingDocument()); oCopy.updateLinks(); if(oIdMap){ oIdMap[this.Id] = oCopy.Id; } var oTheme = this.Get_Theme(); var oColorMap = this.Get_ColorMap(); fSaveChartObjectSourceFormatting(this, oCopy, oTheme, oColorMap); if(!oCopy.txPr || !oCopy.txPr.content || !oCopy.txPr.content.Content[0] || !oCopy.txPr.content.Content[0].Pr){ oCopy.setTxPr(AscFormat.CreateTextBodyFromString("", this.getDrawingDocument(), oCopy)); } var bMerge = false; var oTextPr = new CTextPr(); if(!oCopy.txPr.content.Content[0].Pr.DefaultRunPr || !oCopy.txPr.content.Content[0].Pr.DefaultRunPr.RFonts || !oCopy.txPr.content.Content[0].Pr.DefaultRunPr.RFonts.Ascii || !oCopy.txPr.content.Content[0].Pr.DefaultRunPr.RFonts.Ascii.Name){ bMerge = true; oTextPr.RFonts.Set_FromObject( { Ascii: { Name: "+mn-lt", Index: -1 }, EastAsia: { Name: "+mn-ea", Index: -1 }, HAnsi: { Name: "+mn-lt", Index: -1 }, CS: { Name: "+mn-lt", Index: -1 } } ); } if(this.txPr.content.Content[0].Pr.DefaultRunPr && this.txPr.content.Content[0].Pr.DefaultRunPr.Unifill){ bMerge = true; var oUnifill = this.txPr.content.Content[0].Pr.DefaultRunPr.Unifill.createDuplicate(); oUnifill.check(this.Get_Theme(), this.Get_ColorMap()); oTextPr.Unifill = oUnifill.saveSourceFormatting(); } else if(!AscFormat.isRealNumber(this.style) || this.style < 33){ bMerge = true; var oUnifill = CreateUnifillSolidFillSchemeColor(15, 0.0); oUnifill.check(this.Get_Theme(), this.Get_ColorMap()); oTextPr.Unifill = oUnifill.saveSourceFormatting(); } else{ bMerge = true; var oUnifill = CreateUnifillSolidFillSchemeColor(6, 0.0); oUnifill.check(this.Get_Theme(), this.Get_ColorMap()); oTextPr.Unifill = oUnifill.saveSourceFormatting(); } if(bMerge){ var oParaPr = oCopy.txPr.content.Content[0].Pr.Copy(); var oParaPr2 = new CParaPr(); var oCopyTextPr = oTextPr.Copy(); oParaPr2.DefaultRunPr = oCopyTextPr; oParaPr.Merge(oParaPr2); oCopy.txPr.content.Content[0].Set_Pr(oParaPr); //CheckObjectTextPr(oCopy, oTextPr, this.getDrawingDocument()); // fSaveChartObjectSourceFormatting(oCopy, oCopy, oTheme, oColorMap); } if(this.chart) { if(this.chart.title) { fSaveChartObjectSourceFormatting(this.chart.title, oCopy.chart.title, oTheme, oColorMap); } if(this.chart.plotArea) { fSaveChartObjectSourceFormatting(this.chart.plotArea, oCopy.chart.plotArea, oTheme, oColorMap); if(oCopy.chart.plotArea.valAx) { fSaveChartObjectSourceFormatting(this.chart.plotArea.valAx, oCopy.chart.plotArea.valAx, oTheme, oColorMap); if(this.chart.plotArea.valAx.compiledLn) { if(!oCopy.chart.plotArea.valAx.spPr){ oCopy.chart.plotArea.valAx.setSpPr(new AscFormat.CSpPr()); } oCopy.chart.plotArea.valAx.spPr.setLn(this.chart.plotArea.valAx.compiledLn.createDuplicate(true)); } if(this.chart.plotArea.valAx.compiledMajorGridLines) { if(!oCopy.chart.plotArea.valAx.majorGridlines){ oCopyi.chart.plotArea.valAx.setMajorGridlines(new AscFormat.CSpPr()); } oCopy.chart.plotArea.valAx.majorGridlines.setLn(this.chart.plotArea.valAx.compiledMajorGridLines.createDuplicate(true)); } if(this.chart.plotArea.valAx.compiledMinorGridLines) { if(!oCopy.chart.plotArea.valAx.minorGridlines){ oCopy.chart.plotArea.valAx.setMinorGridlines(new AscFormat.CSpPr()); } oCopy.chart.plotArea.valAx.minorGridlines.setLn(this.chart.plotArea.valAx.compiledMinorGridLines.createDuplicate(true)); } if(oCopy.chart.plotArea.valAx.title) { fSaveChartObjectSourceFormatting(this.chart.plotArea.valAx.title, oCopy.chart.plotArea.valAx.title, oTheme, oColorMap); } } if(oCopy.chart.plotArea.catAx) { fSaveChartObjectSourceFormatting(this.chart.plotArea.catAx, oCopy.chart.plotArea.catAx, oTheme, oColorMap); if(this.chart.plotArea.catAx.compiledLn) { if(!oCopy.chart.plotArea.catAx.spPr){ oCopy.chart.plotArea.catAx.setSpPr(new AscFormat.CSpPr()); } oCopy.chart.plotArea.catAx.spPr.setLn(this.chart.plotArea.catAx.compiledLn.createDuplicate(true)); } if(this.chart.plotArea.catAx.compiledMajorGridLines) { if(!oCopy.chart.plotArea.catAx.majorGridlines){ oCopy.chart.plotArea.catAx.setMajorGridlines(new AscFormat.CSpPr()); } oCopy.chart.plotArea.catAx.majorGridlines.setLn(this.chart.plotArea.catAx.compiledMajorGridLines.createDuplicate(true)); } if(this.chart.plotArea.catAx.compiledMinorGridLines) { if(!oCopy.chart.plotArea.catAx.minorGridlines){ oCopy.chart.plotArea.catAx.setMinorGridlines(new AscFormat.CSpPr()); } oCopy.chart.plotArea.catAx.minorGridlines.setLn(this.chart.plotArea.catAx.compiledMinorGridLines.createDuplicate(true)); } if(oCopy.chart.plotArea.catAx.title) { fSaveChartObjectSourceFormatting(this.chart.plotArea.catAx.title, oCopy.chart.plotArea.catAx.title, oTheme, oColorMap); } } if(this.chart.plotArea.charts[0]) { var series = this.chart.plotArea.charts[0].series; var seriesCopy = oCopy.chart.plotArea.charts[0].series; var oDataPoint; for(var i = 0; i < series.length; ++i) { series[i].brush = series[i].compiledSeriesBrush; series[i].pen = series[i].compiledSeriesPen; fSaveChartObjectSourceFormatting(series[i], seriesCopy[i], oTheme, oColorMap); var pts = AscFormat.getPtsFromSeries(series[i]); var ptsCopy = AscFormat.getPtsFromSeries(seriesCopy[i]); for(var j = 0; j < pts.length; ++j) { var pt = pts[j]; oDataPoint = null; if(Array.isArray(seriesCopy[i].dPt)) { for(var k = 0; k < seriesCopy[i].dPt.length; ++k) { if(seriesCopy[i].dPt[k].idx === pts[j].idx) { oDataPoint = seriesCopy[i].dPt[k]; break; } } } if(!oDataPoint) { oDataPoint = new AscFormat.CDPt(); oDataPoint.setIdx(pt.idx); seriesCopy[i].addDPt(oDataPoint); } fSaveChartObjectSourceFormatting(pt, oDataPoint, oTheme, oColorMap); if(pt.compiledMarker) { var oMarker = pt.compiledMarker.createDuplicate(); oDataPoint.setMarker(oMarker); fSaveChartObjectSourceFormatting(pt.compiledMarker, oMarker, oTheme, oColorMap); } } } if(oCopy.chart.plotArea.charts[0].calculatedHiLowLines) { if(!oCopy.chart.plotArea.charts[0].hiLowLines) { oCopy.chart.plotArea.charts[0].setHiLowLines(new AscFormat.CSpPr()); } oCopy.chart.plotArea.charts[0].hiLowLines.setLn(this.chart.plotArea.charts[0].calculatedHiLowLines.createDuplicate(true)); } if( oCopy.chart.plotArea.charts[0].upDownBars) { if(oCopy.chart.plotArea.charts[0].upDownBars.upBarsBrush) { if(!oCopy.chart.plotArea.charts[0].upDownBars.upBars) { oCopy.chart.plotArea.charts[0].upDownBars.setUpBars(new AscFormat.CSpPr()); } oCopy.chart.plotArea.charts[0].upDownBars.upBars.setFill(this.chart.plotArea.charts[0].upDownBars.upBarsBrush.saveSourceFormatting()); } if(oCopy.chart.plotArea.charts[0].upDownBars.upBarsPen) { if(!oCopy.chart.plotArea.charts[0].upDownBars.upBars) { oCopy.chart.plotArea.charts[0].upDownBars.setUpBars(new AscFormat.CSpPr()); } oCopy.chart.plotArea.charts[0].upDownBars.upBars.setLn(this.chart.plotArea.charts[0].upDownBars.upBarsPen.createDuplicate(true)); } if(oCopy.chart.plotArea.charts[0].upDownBars.downBarsBrush) { if(!oCopy.chart.plotArea.charts[0].upDownBars.downBars) { oCopy.chart.plotArea.charts[0].upDownBars.setDownBars(new AscFormat.CSpPr()); } oCopy.chart.plotArea.charts[0].upDownBars.downBars.setFill(this.chart.plotArea.charts[0].upDownBars.downBarsBrush.saveSourceFormatting()); } if(oCopy.chart.plotArea.charts[0].upDownBars.downBarsPen) { if(!oCopy.chart.plotArea.charts[0].upDownBars.downBars) { oCopy.chart.plotArea.charts[0].upDownBars.setDownBars(new AscFormat.CSpPr()); } oCopy.chart.plotArea.charts[0].upDownBars.downBars.setLn(this.chart.plotArea.charts[0].upDownBars.downBarsPen.createDuplicate(true)); } } } } if(this.chart.legend) { fSaveChartObjectSourceFormatting(this.chart.legend, oCopy.chart.legend, oTheme, oColorMap); var legend = this.chart.legend; for(var i = 0; i < legend.legendEntryes.length; ++i) { fSaveChartObjectSourceFormatting(legend.legendEntryes[i], oCopy.chart.legend.legendEntryes[i], oTheme, oColorMap); } } if(this.chart.floor) { fSaveChartObjectSourceFormatting(this.chart.floor, oCopy.chart.floor, oTheme, oColorMap); } if(this.chart.sideWall) { fSaveChartObjectSourceFormatting(this.chart.sideWall, oCopy.chart.sideWall, oTheme, oColorMap); } if(this.chart.backWall) { fSaveChartObjectSourceFormatting(this.chart.backWall, oCopy.chart.backWall, oTheme, oColorMap); } } return oCopy; }; CChartSpace.prototype.getChartSizes = function(bNotRecalculate) { if(this.plotAreaRect && !this.recalcInfo.recalculateAxisVal){ return {startX: this.plotAreaRect.x, startY: this.plotAreaRect.y, w : this.plotAreaRect.w, h: this.plotAreaRect.h}; } if(!this.chartObj) this.chartObj = new AscFormat.CChartsDrawer(); var oChartSize = this.chartObj.calculateSizePlotArea(this, bNotRecalculate); var oLayout = this.chart.plotArea.layout; if(oLayout){ oChartSize.startX = this.calculatePosByLayout(oChartSize.startX, oLayout.xMode, oLayout.x, oChartSize.w, this.extX); oChartSize.startY = this.calculatePosByLayout(oChartSize.startY, oLayout.yMode, oLayout.y, oChartSize.h, this.extY); var fSize = this.calculateSizeByLayout(oChartSize.startX, this.extX, oLayout.w, oLayout.wMode ); if(AscFormat.isRealNumber(fSize) && fSize > 0){ var fSize2 = this.calculateSizeByLayout(oChartSize.startY, this.extY, oLayout.h, oLayout.hMode ); if(AscFormat.isRealNumber(fSize2) && fSize2 > 0){ oChartSize.w = fSize; oChartSize.h = fSize2; var aCharts = this.chart.plotArea.charts; for(var i = 0; i < aCharts.length; ++i){ var nChartType = aCharts[i].getObjectType(); if(nChartType === AscDFH.historyitem_type_PieChart || nChartType === AscDFH.historyitem_type_DoughnutChart){ var fCX = oChartSize.startX + oChartSize.w/2.0; var fCY = oChartSize.startY + oChartSize.h/2.0; var fPieSize = Math.min(oChartSize.w, oChartSize.h); oChartSize.startX = fCX - fPieSize/2.0; oChartSize.startY = fCY - fPieSize/2.0; oChartSize.w = fPieSize; oChartSize.h = fPieSize; break; } } } } } if(oChartSize.w <= 0){ oChartSize.w = 1; } if(oChartSize.h <= 0){ oChartSize.h = 1; } return oChartSize; }; CChartSpace.prototype.getAllSeries = function() { var _ret = []; var aCharts = this.chart.plotArea.charts; for(var i = 0; i < aCharts.length; ++i){ _ret = _ret.concat(aCharts[i].series); } return _ret; }; CChartSpace.prototype.recalculatePlotAreaChartBrush = function() { if(this.chart && this.chart.plotArea) { var plot_area = this.chart.plotArea; var default_brush; if(AscFormat.CChartsDrawer.prototype._isSwitchCurrent3DChart(this)) { default_brush = CreateNoFillUniFill(); } else { if(this.chart.plotArea && this.chart.plotArea.charts.length === 1 && this.chart.plotArea.charts[0] && (this.chart.plotArea.charts[0].getObjectType() === AscDFH.historyitem_type_PieChart || this.chart.plotArea.charts[0].getObjectType() === AscDFH.historyitem_type_DoughnutChart)) { default_brush = CreateNoFillUniFill(); } else { var tint = 0.20000; if(this.style >=1 && this.style <=32) default_brush = CreateUnifillSolidFillSchemeColor(6, tint); else if(this.style >=33 && this.style <= 34) default_brush = CreateUnifillSolidFillSchemeColor(8, 0.20000); else if(this.style >=35 && this.style <=40) default_brush = CreateUnifillSolidFillSchemeColor(this.style - 35, tint); else default_brush = CreateUnifillSolidFillSchemeColor(8, 0.95000); } } if(plot_area.spPr && plot_area.spPr.Fill) { default_brush.merge(plot_area.spPr.Fill); } var parents = this.getParentObjects(); default_brush.calculate(parents.theme, parents.slide, parents.layout, parents.master, {R: 0, G: 0, B: 0, A: 255}, this.clrMapOvr); plot_area.brush = default_brush; } }; CChartSpace.prototype.recalculateChartPen = function() { var parent_objects = this.getParentObjects(); var default_line = new AscFormat.CLn(); if(parent_objects.theme && parent_objects.theme.themeElements && parent_objects.theme.themeElements.fmtScheme && parent_objects.theme.themeElements.fmtScheme.lnStyleLst) { default_line.merge(parent_objects.theme.themeElements.fmtScheme.lnStyleLst[0]); } var fill; if(this.style >= 1 && this.style <= 32) fill = CreateUnifillSolidFillSchemeColor(15, 0.75000); else if(this.style >= 33 && this.style <= 40) fill = CreateUnifillSolidFillSchemeColor(8, 0.75000); else fill = CreateUnifillSolidFillSchemeColor(12, 0); default_line.setFill(fill); if(this.spPr && this.spPr.ln) default_line.merge(this.spPr.ln); var parents = this.getParentObjects(); default_line.calculate(parents.theme, parents.slide, parents.layout, parents.master, {R: 0, G: 0, B: 0, A: 255}, this.clrMapOvr); this.pen = default_line; checkBlackUnifill(this.pen.Fill, true); }; CChartSpace.prototype.recalculateChartBrush = function() { var default_brush; if(this.style >=1 && this.style <=32) default_brush = CreateUnifillSolidFillSchemeColor(6, 0); else if(this.style >=33 && this.style <= 40) default_brush = CreateUnifillSolidFillSchemeColor(12, 0); else default_brush = CreateUnifillSolidFillSchemeColor(8, 0); if(this.spPr && this.spPr.Fill) { default_brush.merge(this.spPr.Fill); } var parents = this.getParentObjects(); default_brush.calculate(parents.theme, parents.slide, parents.layout, parents.master, {R: 0, G: 0, B: 0, A: 255}, this.clrMapOvr); this.brush = default_brush; }; CChartSpace.prototype.recalculateAxisTickMark = function() { if(this.chart && this.chart.plotArea) { var oThis = this; var calcMajorMinorGridLines = function (axis, defaultStyle, subtleLine, parents) { function calcGridLine(defaultStyle, spPr, subtleLine, parents) { var compiled_grid_lines = new AscFormat.CLn(); compiled_grid_lines.merge(subtleLine); // if(compiled_grid_lines.Fill && compiled_grid_lines.Fill.fill && compiled_grid_lines.Fill.fill.color && compiled_grid_lines.Fill.fill.color.Mods) // { // compiled_grid_lines.Fill.fill.color.Mods.Mods.length = 0; // } if(!compiled_grid_lines.Fill) { compiled_grid_lines.setFill(new AscFormat.CUniFill()); } //if(compiled_grid_lines.Fill && compiled_grid_lines.Fill.fill && compiled_grid_lines.Fill.fill.color && compiled_grid_lines.Fill.fill.color.Mods) //{ // compiled_grid_lines.Fill.fill.color.Mods.Mods.length = 0; //} compiled_grid_lines.Fill.merge(defaultStyle); if(subtleLine && subtleLine.Fill && subtleLine.Fill.fill && subtleLine.Fill.fill.color && subtleLine.Fill.fill.color.Mods && compiled_grid_lines.Fill && compiled_grid_lines.Fill.fill && compiled_grid_lines.Fill.fill.color) { compiled_grid_lines.Fill.fill.color.Mods = subtleLine.Fill.fill.color.Mods.createDuplicate(); } compiled_grid_lines.calculate(parents.theme, parents.slide, parents.layout, parents.master, {R: 0, G: 0, B: 0, A: 255}, oThis.clrMapOvr); checkBlackUnifill(compiled_grid_lines.Fill, true); if(spPr && spPr.ln) { compiled_grid_lines.merge(spPr.ln); compiled_grid_lines.calculate(parents.theme, parents.slide, parents.layout, parents.master, {R: 0, G: 0, B: 0, A: 255}, oThis.clrMapOvr); } return compiled_grid_lines; } axis.compiledLn = calcGridLine(defaultStyle.axisAndMajorGridLines, axis.spPr, subtleLine, parents); axis.compiledTickMarkLn = axis.compiledLn.createDuplicate(); if(AscFormat.isRealNumber(axis.compiledTickMarkLn.w)) axis.compiledTickMarkLn.w/=2; axis.compiledTickMarkLn.calculate(parents.theme, parents.slide, parents.layout, parents.master, {R: 0, G: 0, B: 0, A: 255}, oThis.clrMapOvr) }; var default_style = CHART_STYLE_MANAGER.getDefaultLineStyleByIndex(this.style); var parent_objects = this.getParentObjects(); var subtle_line; if(parent_objects.theme && parent_objects.theme.themeElements && parent_objects.theme.themeElements.fmtScheme && parent_objects.theme.themeElements.fmtScheme.lnStyleLst) { subtle_line = parent_objects.theme.themeElements.fmtScheme.lnStyleLst[0]; } var aAxes = this.chart.plotArea.axId; for(var i = 0; i < aAxes.length; ++i){ calcMajorMinorGridLines(aAxes[i], default_style, subtle_line, parent_objects); } } }; CChartSpace.prototype.getXValAxisValues = function() { if(!this.chartObj) { this.chartObj = new AscFormat.CChartsDrawer() } this.chartObj.preCalculateData(this); return [].concat(this.chart.plotArea.catAx.scale) }; CChartSpace.prototype.getValAxisValues = function() { if(!this.chartObj) { this.chartObj = new AscFormat.CChartsDrawer() } this.chartObj.preCalculateData(this); return [].concat(this.chart.plotArea.valAx.scale); }; CChartSpace.prototype.getCalcProps = function() { if(!this.chartObj) { this.chartObj = new AscFormat.CChartsDrawer() } this.chartObj.preCalculateData(this); return this.chartObj.calcProp; }; CChartSpace.prototype.recalculateDLbls = function() { if(this.chart && this.chart.plotArea) { var aCharts = this.chart.plotArea.charts; for(var t = 0; t < aCharts.length; ++t){ var series = aCharts[t].series; var nDefaultPosition; if(this.chart.plotArea.charts[0].getDefaultDataLabelsPosition) { nDefaultPosition = this.chart.plotArea.charts[0].getDefaultDataLabelsPosition(); } var default_lbl = new AscFormat.CDLbl(); default_lbl.initDefault(nDefaultPosition); var bSkip = false; if(this.ptsCount > MAX_LABELS_COUNT){ bSkip = true; } var nCount = 0; var nLblCount = 0; for(var i = 0; i < series.length; ++i) { var ser = series[i]; var pts = AscFormat.getPtsFromSeries(ser); for(var j = 0; j < pts.length; ++j) { var pt = pts[j]; if(bSkip){ if(nLblCount > (MAX_LABELS_COUNT*(nCount/this.ptsCount))){ pt.compiledDlb = null; nCount++; continue; } } var compiled_dlb = new AscFormat.CDLbl(); compiled_dlb.merge(default_lbl); compiled_dlb.merge(this.chart.plotArea.charts[0].dLbls); if(this.chart.plotArea.charts[0].dLbls) compiled_dlb.merge(this.chart.plotArea.charts[0].dLbls.findDLblByIdx(pt.idx), false); compiled_dlb.merge(ser.dLbls); if(ser.dLbls) compiled_dlb.merge(ser.dLbls.findDLblByIdx(pt.idx)); if(compiled_dlb.checkNoLbl()) { pt.compiledDlb = null; } else { pt.compiledDlb = compiled_dlb; pt.compiledDlb.chart = this; pt.compiledDlb.series = ser; pt.compiledDlb.pt = pt; pt.compiledDlb.recalculate(); nLblCount++; } ++nCount; } } } } }; CChartSpace.prototype.recalculateHiLowLines = function() { if(this.chart && this.chart.plotArea){ var aCharts = this.chart.plotArea.charts; var parents = this.getParentObjects(); for(var i = 0; i < aCharts.length; ++i){ var oCurChart = aCharts[i]; if((oCurChart instanceof AscFormat.CStockChart || oCurChart instanceof AscFormat.CLineChart) && oCurChart.hiLowLines){ var default_line = parents.theme.themeElements.fmtScheme.lnStyleLst[0].createDuplicate(); if(this.style >=1 && this.style <= 32) default_line.setFill(CreateUnifillSolidFillSchemeColor(15, 0)); else if(this.style >= 33 && this.style <= 34) default_line.setFill(CreateUnifillSolidFillSchemeColor(8, 0)); else if(this.style >= 35 && this.style <= 40) default_line.setFill(CreateUnifillSolidFillSchemeColor(8, -0.25000)); else default_line.setFill(CreateUnifillSolidFillSchemeColor(12, 0)); default_line.merge(oCurChart.hiLowLines.ln); oCurChart.calculatedHiLowLines = default_line; default_line.calculate(parents.theme, parents.slide, parents.layout, parents.master, {R:0, G:0, B:0, A:255}, this.clrMapOvr); } else{ oCurChart.calculatedHiLowLines = null; } } } }; CChartSpace.prototype.recalculateSeriesColors = function() { this.ptsCount = 0; if(this.chart && this.chart.plotArea) { var style = CHART_STYLE_MANAGER.getStyleByIndex(this.style); var parents = this.getParentObjects(); var RGBA = {R: 0, G: 0, B: 0, A: 255}; var aCharts = this.chart.plotArea.charts; var aAllSeries = []; for(var t = 0; t < aCharts.length; ++t){ aAllSeries = aAllSeries.concat(aCharts[t].series); } var nMaxSeriesIdx = getMaxIdx(aAllSeries); for(t = 0; t < aCharts.length; ++t){ var oChart = aCharts[t]; var series = oChart.series; if(oChart.varyColors && (series.length === 1 || oChart.getObjectType() === AscDFH.historyitem_type_PieChart || oChart.getObjectType() === AscDFH.historyitem_type_DoughnutChart)) { for(var ii = 0; ii < series.length; ++ ii) { var ser = series[ii]; var pts = AscFormat.getPtsFromSeries(ser); this.ptsCount += pts.length; if(!(oChart.getObjectType() === AscDFH.historyitem_type_LineChart || oChart.getObjectType() === AscDFH.historyitem_type_ScatterChart)) { var base_fills = getArrayFillsFromBase(style.fill2, getMaxIdx(pts)); for(var i = 0; i < pts.length; ++i) { var compiled_brush = new AscFormat.CUniFill(); compiled_brush.merge(base_fills[pts[i].idx]); if(ser.spPr && ser.spPr.Fill) { compiled_brush.merge(ser.spPr.Fill); } if(Array.isArray(ser.dPt)) { for(var j = 0; j < ser.dPt.length; ++j) { if(ser.dPt[j].idx === pts[i].idx) { if(ser.dPt[j].spPr) { compiled_brush.merge(ser.dPt[j].spPr.Fill); } break; } } } pts[i].brush = compiled_brush; pts[i].brush.calculate(parents.theme, parents.slide, parents.layout, parents.master, RGBA, this.clrMapOvr); } default_line = new AscFormat.CLn(); if(style.line1 === EFFECT_NONE) { default_line.w = 0; } else if(style.line1 === EFFECT_SUBTLE) { default_line.merge(parents.theme.themeElements.fmtScheme.lnStyleLst[0]); } else if(style.line1 === EFFECT_MODERATE) { default_line.merge(parents.theme.themeElements.fmtScheme.lnStyleLst[1]); } else if(style.line1 === EFFECT_INTENSE) { default_line.merge(parents.theme.themeElements.fmtScheme.lnStyleLst[2]); } var base_line_fills; if(this.style === 34) base_line_fills = getArrayFillsFromBase(style.line2, getMaxIdx(pts)); for(i = 0; i < pts.length; ++i) { var compiled_line = new AscFormat.CLn(); compiled_line.merge(default_line); compiled_line.Fill = new AscFormat.CUniFill(); if(this.style !== 34) { compiled_line.Fill.merge(style.line2[0]); } else { compiled_line.Fill.merge(base_line_fills[pts[i].idx]); } if(ser.spPr && ser.spPr.ln) compiled_line.merge(ser.spPr.ln); if(Array.isArray(ser.dPt) && !(ser.getObjectType && ser.getObjectType() === AscDFH.historyitem_type_AreaSeries)) { for(var j = 0; j < ser.dPt.length; ++j) { if(ser.dPt[j].idx === pts[i].idx) { if(ser.dPt[j].spPr) { compiled_line.merge(ser.dPt[j].spPr.ln); } break; } } } pts[i].pen = compiled_line; pts[i].pen.calculate(parents.theme, parents.slide, parents.layout, parents.master, RGBA, this.clrMapOvr); } } else { var default_line; if(oChart.getObjectType() === AscDFH.historyitem_type_ScatterChart && oChart.scatterStyle === AscFormat.SCATTER_STYLE_MARKER || oChart.scatterStyle === AscFormat.SCATTER_STYLE_NONE) { default_line = new AscFormat.CLn(); default_line.setFill(new AscFormat.CUniFill()); default_line.Fill.setFill(new AscFormat.CNoFill()); } else { default_line = parents.theme.themeElements.fmtScheme.lnStyleLst[0]; } var base_line_fills = getArrayFillsFromBase(style.line4, getMaxIdx(pts)); for(var i = 0; i < pts.length; ++i) { var compiled_line = new AscFormat.CLn(); compiled_line.merge(default_line); if(!(oChart.getObjectType() === AscDFH.historyitem_type_ScatterChart && oChart.scatterStyle === AscFormat.SCATTER_STYLE_MARKER || oChart.scatterStyle === AscFormat.SCATTER_STYLE_NONE)) compiled_line.Fill.merge(base_line_fills[pts[i].idx]); compiled_line.w *= style.line3; if(ser.spPr && ser.spPr.ln) { compiled_line.merge(ser.spPr.ln); } if(Array.isArray(ser.dPt)) { for(var j = 0; j < ser.dPt.length; ++j) { if(ser.dPt[j].idx === pts[i].idx) { if(ser.dPt[j].spPr) { compiled_line.merge(ser.dPt[j].spPr.ln); } break; } } } pts[i].brush = null; pts[i].pen = compiled_line; pts[i].pen.calculate(parents.theme, parents.slide, parents.layout, parents.master, RGBA, this.clrMapOvr); } } for(var j = 0; j < pts.length; ++j) { if(pts[j].compiledMarker) { pts[j].compiledMarker.pen && pts[j].compiledMarker.pen.calculate(parents.theme, parents.slide, parents.layout, parents.master, RGBA, this.clrMapOvr); pts[j].compiledMarker.brush && pts[j].compiledMarker.brush.calculate(parents.theme, parents.slide, parents.layout, parents.master, RGBA, this.clrMapOvr); } } } } else { switch(oChart.getObjectType()) { case AscDFH.historyitem_type_LineChart: case AscDFH.historyitem_type_RadarChart: { var base_line_fills = getArrayFillsFromBase(style.line4, nMaxSeriesIdx); if(!AscFormat.CChartsDrawer.prototype._isSwitchCurrent3DChart(this)) { for(var i = 0; i < series.length; ++i) { var default_line = parents.theme.themeElements.fmtScheme.lnStyleLst[0]; var ser = series[i]; var pts = AscFormat.getPtsFromSeries(ser); this.ptsCount += pts.length; var compiled_line = new AscFormat.CLn(); compiled_line.merge(default_line); compiled_line.Fill && compiled_line.Fill.merge(base_line_fills[ser.idx]); compiled_line.w *= style.line3; if(ser.spPr && ser.spPr.ln) compiled_line.merge(ser.spPr.ln); ser.compiledSeriesPen = compiled_line.createDuplicate(); for(var j = 0; j < pts.length; ++j) { var compiled_line = new AscFormat.CLn(); compiled_line.merge(default_line); compiled_line.Fill && compiled_line.Fill.merge(base_line_fills[ser.idx]); compiled_line.w *= style.line3; if(ser.spPr && ser.spPr.ln) compiled_line.merge(ser.spPr.ln); if(Array.isArray(ser.dPt)) { for(var k = 0; k < ser.dPt.length; ++k) { if(ser.dPt[k].idx === pts[j].idx) { if(ser.dPt[k].spPr) { compiled_line.merge(ser.dPt[k].spPr.ln); } break; } } } pts[j].brush = null; pts[j].pen = compiled_line; pts[j].pen.calculate(parents.theme, parents.slide, parents.layout, parents.master, RGBA, this.clrMapOvr); if(pts[j].compiledMarker) { pts[j].compiledMarker.pen && pts[j].compiledMarker.pen.calculate(parents.theme, parents.slide, parents.layout, parents.master, RGBA, this.clrMapOvr); pts[j].compiledMarker.brush && pts[j].compiledMarker.brush.calculate(parents.theme, parents.slide, parents.layout, parents.master, RGBA, this.clrMapOvr); } } } } else { var base_fills = getArrayFillsFromBase(style.fill2, nMaxSeriesIdx); var base_line_fills = null; if(style.line1 === EFFECT_SUBTLE && this.style === 34) base_line_fills = getArrayFillsFromBase(style.line2, nMaxSeriesIdx); for(var i = 0; i < series.length; ++i) { var ser = series[i]; var compiled_brush = new AscFormat.CUniFill(); compiled_brush.merge(base_fills[ser.idx]); if(ser.spPr && ser.spPr.Fill) { compiled_brush.merge(ser.spPr.Fill); } ser.compiledSeriesBrush = compiled_brush.createDuplicate(); var pts = AscFormat.getPtsFromSeries(ser); for(var j = 0; j < pts.length; ++j) { var compiled_brush = new AscFormat.CUniFill(); compiled_brush.merge(base_fills[ser.idx]); if(ser.spPr && ser.spPr.Fill) { compiled_brush.merge(ser.spPr.Fill); } if(Array.isArray(ser.dPt) && !(ser.getObjectType && ser.getObjectType() === AscDFH.historyitem_type_AreaSeries)) { for(var k = 0; k < ser.dPt.length; ++k) { if(ser.dPt[k].idx === pts[j].idx) { if(ser.dPt[k].spPr) { compiled_brush.merge(ser.dPt[k].spPr.Fill); } break; } } } pts[j].brush = compiled_brush; pts[j].brush.calculate(parents.theme, parents.slide, parents.layout, parents.master, RGBA, this.clrMapOvr); } // { default_line = new AscFormat.CLn(); if(style.line1 === EFFECT_NONE) { default_line.w = 0; } else if(style.line1 === EFFECT_SUBTLE) { default_line.merge(parents.theme.themeElements.fmtScheme.lnStyleLst[0]); } else if(style.line1 === EFFECT_MODERATE) { default_line.merge(parents.theme.themeElements.fmtScheme.lnStyleLst[1]); } else if(style.line1 === EFFECT_INTENSE) { default_line.merge(parents.theme.themeElements.fmtScheme.lnStyleLst[2]); } var base_line_fills; if(this.style === 34) base_line_fills = getArrayFillsFromBase(style.line2, getMaxIdx(pts)); var compiled_line = new AscFormat.CLn(); compiled_line.merge(default_line); compiled_line.Fill = new AscFormat.CUniFill(); if(this.style !== 34) compiled_line.Fill.merge(style.line2[0]); else compiled_line.Fill.merge(base_line_fills[ser.idx]); if(ser.spPr && ser.spPr.ln) { compiled_line.merge(ser.spPr.ln); } ser.compiledSeriesPen = compiled_line.createDuplicate(); for(var j = 0; j < pts.length; ++j) { var compiled_line = new AscFormat.CLn(); compiled_line.merge(default_line); compiled_line.Fill = new AscFormat.CUniFill(); if(this.style !== 34) compiled_line.Fill.merge(style.line2[0]); else compiled_line.Fill.merge(base_line_fills[ser.idx]); if(ser.spPr && ser.spPr.ln) { compiled_line.merge(ser.spPr.ln); } if(Array.isArray(ser.dPt) && !(ser.getObjectType && ser.getObjectType() === AscDFH.historyitem_type_AreaSeries)) { for(var k = 0; k < ser.dPt.length; ++k) { if(ser.dPt[k].idx === pts[j].idx) { if(ser.dPt[k].spPr) { compiled_line.merge(ser.dPt[k].spPr.ln); } break; } } } pts[j].pen = compiled_line; pts[j].pen.calculate(parents.theme, parents.slide, parents.layout, parents.master, RGBA, this.clrMapOvr); if(pts[j].compiledMarker) { pts[j].compiledMarker.pen && pts[j].compiledMarker.pen.calculate(parents.theme, parents.slide, parents.layout, parents.master, RGBA, this.clrMapOvr); pts[j].compiledMarker.brush && pts[j].compiledMarker.brush.calculate(parents.theme, parents.slide, parents.layout, parents.master, RGBA, this.clrMapOvr); } } } } } break; } case AscDFH.historyitem_type_ScatterChart: { var base_line_fills = getArrayFillsFromBase(style.line4, nMaxSeriesIdx); for(var i = 0; i < series.length; ++i) { var default_line = parents.theme.themeElements.fmtScheme.lnStyleLst[0]; var ser = series[i]; var pts = AscFormat.getPtsFromSeries(ser); this.ptsCount += pts.length; if(oChart.scatterStyle === AscFormat.SCATTER_STYLE_SMOOTH || oChart.scatterStyle === AscFormat.SCATTER_STYLE_SMOOTH_MARKER) { if(!AscFormat.isRealBool(ser.smooth)) { ser.smooth = true; } } if(oChart.scatterStyle === AscFormat.SCATTER_STYLE_MARKER || oChart.scatterStyle === AscFormat.SCATTER_STYLE_NONE) { default_line = new AscFormat.CLn(); default_line.setFill(new AscFormat.CUniFill()); default_line.Fill.setFill(new AscFormat.CNoFill()); } var compiled_line = new AscFormat.CLn(); compiled_line.merge(default_line); if(!(oChart.scatterStyle === AscFormat.SCATTER_STYLE_MARKER || oChart.scatterStyle === AscFormat.SCATTER_STYLE_NONE)) { compiled_line.Fill && compiled_line.Fill.merge(base_line_fills[ser.idx]); } compiled_line.w *= style.line3; if(ser.spPr && ser.spPr.ln) compiled_line.merge(ser.spPr.ln); ser.compiledSeriesPen = compiled_line.createDuplicate(); for(var j = 0; j < pts.length; ++j) { var compiled_line = new AscFormat.CLn(); compiled_line.merge(default_line); if(!(oChart.scatterStyle === AscFormat.SCATTER_STYLE_MARKER || oChart.scatterStyle === AscFormat.SCATTER_STYLE_NONE)) { compiled_line.Fill && compiled_line.Fill.merge(base_line_fills[ser.idx]); } compiled_line.w *= style.line3; if(ser.spPr && ser.spPr.ln) compiled_line.merge(ser.spPr.ln); if(Array.isArray(ser.dPt)) { for(var k = 0; k < ser.dPt.length; ++k) { if(ser.dPt[k].idx === pts[j].idx) { if(ser.dPt[k].spPr) { compiled_line.merge(ser.dPt[k].spPr.ln); } break; } } } pts[j].brush = null; pts[j].pen = compiled_line; pts[j].pen.calculate(parents.theme, parents.slide, parents.layout, parents.master, RGBA, this.clrMapOvr); if(pts[j].compiledMarker) { pts[j].compiledMarker.pen && pts[j].compiledMarker.pen.calculate(parents.theme, parents.slide, parents.layout, parents.master, RGBA, this.clrMapOvr); pts[j].compiledMarker.brush && pts[j].compiledMarker.brush.calculate(parents.theme, parents.slide, parents.layout, parents.master, RGBA, this.clrMapOvr); } } } break; } case AscDFH.historyitem_type_SurfaceChart: { var oSurfaceChart = oChart; var aValAxArray = this.getValAxisValues(); var nFmtsCount = aValAxArray.length - 1; var oSpPr, oBandFmt, oCompiledBandFmt; oSurfaceChart.compiledBandFormats.length = 0; var multiplier; var axis_by_types = oSurfaceChart.getAxisByTypes(); var val_ax = axis_by_types.valAx[0]; if(val_ax.dispUnits) multiplier = val_ax.dispUnits.getMultiplier(); else multiplier = 1; var num_fmt = val_ax.numFmt, num_format = null, calc_value, rich_value; if(num_fmt && typeof num_fmt.formatCode === "string" /*&& !(num_fmt.formatCode === "General")*/) { num_format = oNumFormatCache.get(num_fmt.formatCode); } var oParentObjects = this.getParentObjects(); var RGBA = {R: 255, G: 255, B: 255, A: 255}; if(oSurfaceChart.isWireframe()){ var base_line_fills = getArrayFillsFromBase(style.line4, nFmtsCount); var default_line = parents.theme.themeElements.fmtScheme.lnStyleLst[0]; for(var i = 0; i < nFmtsCount; ++i) { oBandFmt = oSurfaceChart.getBandFmtByIndex(i); oSpPr = new AscFormat.CSpPr(); oSpPr.setFill(AscFormat.CreateNoFillUniFill()); var compiled_line = new AscFormat.CLn(); compiled_line.merge(default_line); compiled_line.Fill.merge(base_line_fills[i]); //compiled_line.w *= style.line3; compiled_line.Join = new AscFormat.LineJoin(); compiled_line.Join.type = AscFormat.LineJoinType.Bevel; if(oBandFmt && oBandFmt.spPr){ compiled_line.merge(oBandFmt.spPr.ln); } compiled_line.calculate(oParentObjects.theme, oParentObjects.slide, oParentObjects.layout, oParentObjects.master, RGBA, this.clrMapOvr); oSpPr.setLn(compiled_line); oCompiledBandFmt = new AscFormat.CBandFmt(); oCompiledBandFmt.setIdx(i); oCompiledBandFmt.setSpPr(oSpPr); if(num_format){ oCompiledBandFmt.startValue = num_format.formatToChart(aValAxArray[i]*multiplier); oCompiledBandFmt.endValue = num_format.formatToChart(aValAxArray[i+1]*multiplier); } else{ oCompiledBandFmt.startValue = '' + (aValAxArray[i]*multiplier); oCompiledBandFmt.endValue = '' + (aValAxArray[i+1]*multiplier); } oCompiledBandFmt.setSpPr(oSpPr); oSurfaceChart.compiledBandFormats.push(oCompiledBandFmt); } } else{ var base_fills = getArrayFillsFromBase(style.fill2, nFmtsCount); var base_line_fills = null; if(style.line1 === EFFECT_SUBTLE && this.style === 34) base_line_fills = getArrayFillsFromBase(style.line2, nFmtsCount); var default_line = new AscFormat.CLn(); if(style.line1 === EFFECT_NONE) { default_line.w = 0; } else if(style.line1 === EFFECT_SUBTLE) { default_line.merge(parents.theme.themeElements.fmtScheme.lnStyleLst[0]); } else if(style.line1 === EFFECT_MODERATE) { default_line.merge(parents.theme.themeElements.fmtScheme.lnStyleLst[1]); } else if(style.line1 === EFFECT_INTENSE) { default_line.merge(parents.theme.themeElements.fmtScheme.lnStyleLst[2]); } for(var i = 0; i < nFmtsCount; ++i) { oBandFmt = oSurfaceChart.getBandFmtByIndex(i); var compiled_brush = new AscFormat.CUniFill(); oSpPr = new AscFormat.CSpPr(); compiled_brush.merge(base_fills[i]); if (oBandFmt && oBandFmt.spPr) { compiled_brush.merge(oBandFmt.spPr.Fill); } oSpPr.setFill(compiled_brush); var compiled_line = new AscFormat.CLn(); compiled_line.merge(default_line); compiled_line.Fill = new AscFormat.CUniFill(); if(this.style !== 34) compiled_line.Fill.merge(style.line2[0]); else compiled_line.Fill.merge(base_line_fills[i]); if(oBandFmt && oBandFmt.spPr && oBandFmt.spPr.ln) { compiled_line.merge(oBandFmt.spPr.ln); } oSpPr.setLn(compiled_line); compiled_line.calculate(oParentObjects.theme, oParentObjects.slide, oParentObjects.layout, oParentObjects.master, RGBA, this.clrMapOvr); compiled_brush.calculate(oParentObjects.theme, oParentObjects.slide, oParentObjects.layout, oParentObjects.master, RGBA, this.clrMapOvr); oCompiledBandFmt = new AscFormat.CBandFmt(); oCompiledBandFmt.setIdx(i); oCompiledBandFmt.setSpPr(oSpPr); if(num_format){ oCompiledBandFmt.startValue = num_format.formatToChart(aValAxArray[i]*multiplier); oCompiledBandFmt.endValue = num_format.formatToChart(aValAxArray[i+1]*multiplier); } else{ oCompiledBandFmt.startValue = '' + (aValAxArray[i]*multiplier); oCompiledBandFmt.endValue = '' + (aValAxArray[i+1]*multiplier); } oSurfaceChart.compiledBandFormats.push(oCompiledBandFmt); } } break; } default : { var base_fills = getArrayFillsFromBase(style.fill2, nMaxSeriesIdx); var base_line_fills = null; if(style.line1 === EFFECT_SUBTLE && this.style === 34) base_line_fills = getArrayFillsFromBase(style.line2, nMaxSeriesIdx); for(var i = 0; i < series.length; ++i) { var ser = series[i]; var compiled_brush = new AscFormat.CUniFill(); compiled_brush.merge(base_fills[ser.idx]); if(ser.spPr && ser.spPr.Fill) { compiled_brush.merge(ser.spPr.Fill); } ser.compiledSeriesBrush = compiled_brush.createDuplicate(); var pts = AscFormat.getPtsFromSeries(ser); this.ptsCount += pts.length; for(var j = 0; j < pts.length; ++j) { var compiled_brush = new AscFormat.CUniFill(); compiled_brush.merge(base_fills[ser.idx]); if(ser.spPr && ser.spPr.Fill) { compiled_brush.merge(ser.spPr.Fill); } if(Array.isArray(ser.dPt) && !(ser.getObjectType && ser.getObjectType() === AscDFH.historyitem_type_AreaSeries)) { for(var k = 0; k < ser.dPt.length; ++k) { if(ser.dPt[k].idx === pts[j].idx) { if(ser.dPt[k].spPr) { compiled_brush.merge(ser.dPt[k].spPr.Fill); } break; } } } pts[j].brush = compiled_brush; pts[j].brush.calculate(parents.theme, parents.slide, parents.layout, parents.master, RGBA, this.clrMapOvr); } // { default_line = new AscFormat.CLn(); if(style.line1 === EFFECT_NONE) { default_line.w = 0; } else if(style.line1 === EFFECT_SUBTLE) { default_line.merge(parents.theme.themeElements.fmtScheme.lnStyleLst[0]); } else if(style.line1 === EFFECT_MODERATE) { default_line.merge(parents.theme.themeElements.fmtScheme.lnStyleLst[1]); } else if(style.line1 === EFFECT_INTENSE) { default_line.merge(parents.theme.themeElements.fmtScheme.lnStyleLst[2]); } var base_line_fills; if(this.style === 34) base_line_fills = getArrayFillsFromBase(style.line2, getMaxIdx(pts)); var compiled_line = new AscFormat.CLn(); compiled_line.merge(default_line); compiled_line.Fill = new AscFormat.CUniFill(); if(this.style !== 34) compiled_line.Fill.merge(style.line2[0]); else compiled_line.Fill.merge(base_line_fills[ser.idx]); if(ser.spPr && ser.spPr.ln) { compiled_line.merge(ser.spPr.ln); } ser.compiledSeriesPen = compiled_line.createDuplicate(); for(var j = 0; j < pts.length; ++j) { var compiled_line = new AscFormat.CLn(); compiled_line.merge(default_line); compiled_line.Fill = new AscFormat.CUniFill(); if(this.style !== 34) compiled_line.Fill.merge(style.line2[0]); else compiled_line.Fill.merge(base_line_fills[ser.idx]); if(ser.spPr && ser.spPr.ln) { compiled_line.merge(ser.spPr.ln); } if(Array.isArray(ser.dPt) && !(ser.getObjectType && ser.getObjectType() === AscDFH.historyitem_type_AreaSeries)) { for(var k = 0; k < ser.dPt.length; ++k) { if(ser.dPt[k].idx === pts[j].idx) { if(ser.dPt[k].spPr) { compiled_line.merge(ser.dPt[k].spPr.ln); } break; } } } pts[j].pen = compiled_line; pts[j].pen.calculate(parents.theme, parents.slide, parents.layout, parents.master, RGBA, this.clrMapOvr); if(pts[j].compiledMarker) { pts[j].compiledMarker.pen && pts[j].compiledMarker.pen.calculate(parents.theme, parents.slide, parents.layout, parents.master, RGBA, this.clrMapOvr); pts[j].compiledMarker.brush && pts[j].compiledMarker.brush.calculate(parents.theme, parents.slide, parents.layout, parents.master, RGBA, this.clrMapOvr); } } } } break; } } } } } }; CChartSpace.prototype.recalculateChartTitleEditMode = function(bWord) { var old_pos_x, old_pos_y, old_pos_cx, old_pos_cy; var pos_x, pos_y; old_pos_x = this.recalcInfo.recalcTitle.x; old_pos_y = this.recalcInfo.recalcTitle.y; old_pos_cx = this.recalcInfo.recalcTitle.x + this.recalcInfo.recalcTitle.extX/2; old_pos_cy = this.recalcInfo.recalcTitle.y + this.recalcInfo.recalcTitle.extY/2; this.recalculateAxisLabels(); if(checkVerticalTitle(this.recalcInfo.recalcTitle)) { pos_x = old_pos_x; pos_y = old_pos_cy - this.recalcInfo.recalcTitle.extY/2; } else { pos_x = old_pos_cx - this.recalcInfo.recalcTitle.extX/2; pos_y = old_pos_y; } this.recalcInfo.recalcTitle.setPosition(pos_x, pos_y); if(bWord) { this.recalcInfo.recalcTitle.updatePosition(this.posX, this.posY); } }; CChartSpace.prototype.recalculateMarkers = function() { if(this.chart && this.chart.plotArea) { var aCharts = this.chart.plotArea.charts; var oCurChart; var aAllsSeries = []; for(var t = 0; t < aCharts.length; ++t){ oCurChart = aCharts[t]; var series = oCurChart.series, pts; aAllsSeries = aAllsSeries.concat(series); for(var i = 0; i < series.length; ++i) { var ser = series[i]; ser.compiledSeriesMarker = null; pts = AscFormat.getPtsFromSeries(ser); for(var j = 0; j < pts.length; ++j) { pts[j].compiledMarker = null; } } var oThis = this; var recalculateMarkers2 = function() { var chart_style = CHART_STYLE_MANAGER.getStyleByIndex(oThis.style); var effect_fill = chart_style.fill1; var fill = chart_style.fill2; var line = chart_style.line4; var masrker_default_size = AscFormat.isRealNumber(oThis.style) ? chart_style.markerSize : 5; var default_marker = new AscFormat.CMarker(); default_marker.setSize(masrker_default_size); var parent_objects = oThis.getParentObjects(); if(parent_objects.theme && parent_objects.theme.themeElements && parent_objects.theme.themeElements.fmtScheme && parent_objects.theme.themeElements.fmtScheme.lnStyleLst) { default_marker.setSpPr(new AscFormat.CSpPr()); default_marker.spPr.setLn(new AscFormat.CLn()); default_marker.spPr.ln.merge(parent_objects.theme.themeElements.fmtScheme.lnStyleLst[0]); } var RGBA = {R:0, G:0, B:0, A: 255}; if(oCurChart.varyColors && (oCurChart.series.length === 1 || oCurChart.getObjectType() === AscDFH.historyitem_type_PieChart || oCurChart.getObjectType() === AscDFH.historyitem_type_DoughnutChart)) { var ser = oCurChart.series[0], pts; if(ser.marker && ser.marker.symbol === AscFormat.SYMBOL_NONE && (!Array.isArray(ser.dPt) || ser.dPt.length === 0)) return; pts = AscFormat.getPtsFromSeries(ser); var series_marker = ser.marker; var brushes = getArrayFillsFromBase(fill, getMaxIdx(pts)); var pens_fills = getArrayFillsFromBase(line, getMaxIdx(pts)); var compiled_markers = []; for(var i = 0; i < pts.length; ++i) { var compiled_marker = new AscFormat.CMarker(); compiled_marker.merge(default_marker); if(!compiled_marker.spPr) { compiled_marker.setSpPr(new AscFormat.CSpPr()); } compiled_marker.spPr.setFill(brushes[pts[i].idx]); compiled_marker.spPr.Fill.merge(pts[i].brush); if(!compiled_marker.spPr.ln) compiled_marker.spPr.setLn(new AscFormat.CLn()); compiled_marker.spPr.ln.merge(pts[i].pen); compiled_marker.setSymbol(GetTypeMarkerByIndex(i)); compiled_marker.merge(ser.marker); if(Array.isArray(ser.dPt)) { for(var j = 0; j < ser.dPt.length; ++j) { if(ser.dPt[j].idx === pts[i].idx) { var d_pt = ser.dPt[j]; if(d_pt.spPr && (d_pt.spPr.Fill || d_pt.spPr.ln)) { if(!compiled_marker.spPr) { compiled_marker.setSpPr(new AscFormat.CSpPr()); } if(d_pt.spPr.Fill) { compiled_marker.spPr.setFill(d_pt.spPr.Fill.createDuplicate()); } if(d_pt.spPr.ln) { if(!compiled_marker.spPr.ln) { compiled_marker.spPr.setLn(new AscFormat.CLn()); } compiled_marker.spPr.ln.merge(d_pt.spPr.ln); } } compiled_marker.merge(ser.dPt[j].marker); break; } } } pts[i].compiledMarker = compiled_marker; pts[i].compiledMarker.pen = compiled_marker.spPr.ln; pts[i].compiledMarker.brush = compiled_marker.spPr.Fill; pts[i].compiledMarker.brush.calculate(parent_objects.theme, parent_objects.slide, parent_objects.layout, parent_objects.master, RGBA, oThis.clrMapOvr); pts[i].compiledMarker.pen.calculate(parent_objects.theme, parent_objects.slide, parent_objects.layout, parent_objects.master, RGBA, oThis.clrMapOvr); } } else { var series = oCurChart.series; var brushes = getArrayFillsFromBase(fill, getMaxIdx(aAllsSeries)); var pens_fills = getArrayFillsFromBase(line, getMaxIdx(aAllsSeries)); for(var i = 0; i < series.length; ++i) { var ser = series[i]; if(ser.marker && ser.marker.symbol === AscFormat.SYMBOL_NONE && (!Array.isArray(ser.dPt) || ser.dPt.length === 0)) continue; pts = AscFormat.getPtsFromSeries(ser); for(var j = 0; j < pts.length; ++j) { var compiled_marker = new AscFormat.CMarker(); compiled_marker.merge(default_marker); if(!compiled_marker.spPr) { compiled_marker.setSpPr(new AscFormat.CSpPr()); } compiled_marker.spPr.setFill(brushes[series[i].idx]); if(!compiled_marker.spPr.ln) compiled_marker.spPr.setLn(new AscFormat.CLn()); compiled_marker.spPr.ln.setFill(pens_fills[series[i].idx]); compiled_marker.setSymbol(GetTypeMarkerByIndex(series[i].idx)); compiled_marker.merge(ser.marker); if(j === 0) ser.compiledSeriesMarker = compiled_marker.createDuplicate(); if(Array.isArray(ser.dPt)) { for(var k = 0; k < ser.dPt.length; ++k) { if(ser.dPt[k].idx === pts[j].idx) { compiled_marker.merge(ser.dPt[k].marker); break; } } } pts[j].compiledMarker = compiled_marker; pts[j].compiledMarker.pen = compiled_marker.spPr.ln; pts[j].compiledMarker.brush = compiled_marker.spPr.Fill; pts[j].compiledMarker.brush.calculate(parent_objects.theme, parent_objects.slide, parent_objects.layout, parent_objects.master, RGBA, oThis.clrMapOvr); pts[j].compiledMarker.pen.calculate(parent_objects.theme, parent_objects.slide, parent_objects.layout, parent_objects.master, RGBA, oThis.clrMapOvr); } } } }; switch (oCurChart.getObjectType()) { case AscDFH.historyitem_type_LineChart: case AscDFH.historyitem_type_RadarChart: { if(oCurChart.marker !== false) { recalculateMarkers2(); } break; } case AscDFH.historyitem_type_ScatterChart: { if(oCurChart.scatterStyle === AscFormat.SCATTER_STYLE_MARKER || oCurChart.scatterStyle === AscFormat.SCATTER_STYLE_LINE_MARKER || oCurChart.scatterStyle === AscFormat.SCATTER_STYLE_SMOOTH_MARKER) { recalculateMarkers2(); } break; } default: { recalculateMarkers2(); break; } } } } }; CChartSpace.prototype.calcGridLine = function(defaultStyle, spPr, subtleLine, parents) { if(spPr) { var compiled_grid_lines = new AscFormat.CLn(); compiled_grid_lines.merge(subtleLine); // if(compiled_grid_lines.Fill && compiled_grid_lines.Fill.fill && compiled_grid_lines.Fill.fill.color && compiled_grid_lines.Fill.fill.color.Mods) // { // compiled_grid_lines.Fill.fill.color.Mods.Mods.length = 0; // } if(!compiled_grid_lines.Fill) { compiled_grid_lines.setFill(new AscFormat.CUniFill()); } //if(compiled_grid_lines.Fill && compiled_grid_lines.Fill.fill && compiled_grid_lines.Fill.fill.color && compiled_grid_lines.Fill.fill.color.Mods) //{ // compiled_grid_lines.Fill.fill.color.Mods.Mods.length = 0; //} compiled_grid_lines.Fill.merge(defaultStyle); if(subtleLine && subtleLine.Fill && subtleLine.Fill.fill && subtleLine.Fill.fill.color && subtleLine.Fill.fill.color.Mods && compiled_grid_lines.Fill && compiled_grid_lines.Fill.fill && compiled_grid_lines.Fill.fill.color) { compiled_grid_lines.Fill.fill.color.Mods = subtleLine.Fill.fill.color.Mods.createDuplicate(); } compiled_grid_lines.merge(spPr.ln); compiled_grid_lines.calculate(parents.theme, parents.slide, parents.layout, parents.master, {R: 0, G: 0, B: 0, A: 255}, this.clrMapOvr); checkBlackUnifill(compiled_grid_lines.Fill, true); return compiled_grid_lines; } return null; }; CChartSpace.prototype.calcMajorMinorGridLines = function (axis, defaultStyle, subtleLine, parents) { if(!axis) return; axis.compiledMajorGridLines = this.calcGridLine(defaultStyle.axisAndMajorGridLines, axis.majorGridlines, subtleLine, parents); axis.compiledMinorGridLines = this.calcGridLine(defaultStyle.minorGridlines, axis.minorGridlines, subtleLine, parents); }; CChartSpace.prototype.handleTitlesAfterChangeTheme = function() { if(this.chart && this.chart.title) { this.chart.title.checkAfterChangeTheme(); } if(this.chart && this.chart.plotArea) { var hor_axis = this.chart.plotArea.getHorizontalAxis(); if(hor_axis && hor_axis.title) { hor_axis.title.checkAfterChangeTheme(); } var vert_axis = this.chart.plotArea.getVerticalAxis(); if(vert_axis && vert_axis.title) { vert_axis.title.checkAfterChangeTheme(); } } }; CChartSpace.prototype.recalculateGridLines = function() { if(this.chart && this.chart.plotArea) { var default_style = CHART_STYLE_MANAGER.getDefaultLineStyleByIndex(this.style); var parent_objects = this.getParentObjects(); var subtle_line; if(parent_objects.theme && parent_objects.theme.themeElements && parent_objects.theme.themeElements.fmtScheme && parent_objects.theme.themeElements.fmtScheme.lnStyleLst) { subtle_line = parent_objects.theme.themeElements.fmtScheme.lnStyleLst[0]; } var aAxes = this.chart.plotArea.axId; for(var i = 0; i < aAxes.length; ++i){ var oCurAxis = aAxes[i]; this.calcMajorMinorGridLines(oCurAxis, default_style, subtle_line, parent_objects); this.calcMajorMinorGridLines(oCurAxis, default_style, subtle_line, parent_objects); } } }; CChartSpace.prototype.hitToAdjustment = function() { return {hit: false}; }; CChartSpace.prototype.recalculateAxisLabels = function() { if(this.chart && this.chart.title) { var title = this.chart.title; //title.parent = this.chart; title.chart = this; title.recalculate(); } if(this.chart && this.chart.plotArea) { var hor_axis = this.chart.plotArea.getHorizontalAxis(); if(hor_axis && hor_axis.title) { var title = hor_axis.title; //title.parent = hor_axis; title.chart = this; title.recalculate(); } var vert_axis = this.chart.plotArea.getVerticalAxis(); if(vert_axis && vert_axis.title) { var title = vert_axis.title; //title.parent = vert_axis; title.chart = this; title.recalculate(); } } }; CChartSpace.prototype.updateLinks = function() { //Этот метод нужен, т. к. мы не полностью поддерживаем формат в котором в одном plotArea может быть несколько разных диаграмм(конкретных типов). // Здесь мы берем первую из диаграмм лежащих в массиве plotArea.charts, а также выставляем ссылки для осей ; if(this.chart && this.chart.plotArea) { var oCheckChart; var oPlotArea = this.chart.plotArea; var aCharts = oPlotArea.charts; this.chart.plotArea.chart = aCharts[0]; for(var i = 0; i < aCharts.length; ++i){ if(aCharts[i].getObjectType() !== AscDFH.historyitem_type_PieChart && aCharts[i].getObjectType() !== AscDFH.historyitem_type_DoughnutChart){ oCheckChart = aCharts[i]; break; } } if(oCheckChart){ this.chart.plotArea.chart = oCheckChart; this.chart.plotArea.serAx = null; if(oCheckChart.getAxisByTypes) { var axis_by_types = oCheckChart.getAxisByTypes(); if(axis_by_types.valAx.length > 0 && axis_by_types.catAx.length > 0) { for(var i = 0; i < axis_by_types.valAx.length; ++i) { if(axis_by_types.valAx[i].crossAx) { for(var j = 0; j < axis_by_types.catAx.length; ++j) { if(axis_by_types.catAx[j] === axis_by_types.valAx[i].crossAx) { this.chart.plotArea.valAx = axis_by_types.valAx[i]; this.chart.plotArea.catAx = axis_by_types.catAx[j]; break; } } if(j < axis_by_types.catAx.length) { break; } } } if(i === axis_by_types.valAx.length) { this.chart.plotArea.valAx = axis_by_types.valAx[0]; this.chart.plotArea.catAx = axis_by_types.catAx[0]; } if(this.chart.plotArea.valAx && this.chart.plotArea.catAx) { for(i = 0; i < axis_by_types.serAx.length; ++i) { if(axis_by_types.serAx[i].crossAx === this.chart.plotArea.valAx) { this.chart.plotArea.serAx = axis_by_types.serAx[i]; break; } } } } else { if(axis_by_types.valAx.length > 1) {//TODO: выставлять оси исходя из настроек this.chart.plotArea.valAx = axis_by_types.valAx[1]; this.chart.plotArea.catAx = axis_by_types.valAx[0]; } } } else { this.chart.plotArea.valAx = null; this.chart.plotArea.catAx = null; } } } }; CChartSpace.prototype.draw = function(graphics) { if(this.checkNeedRecalculate && this.checkNeedRecalculate()){ return; } if(graphics.IsSlideBoundsCheckerType) { graphics.transform3(this.transform); graphics._s(); graphics._m(0, 0); graphics._l(this.extX, 0); graphics._l(this.extX, this.extY); graphics._l(0, this.extY); graphics._e(); return; } if(graphics.updatedRect) { var rect = graphics.updatedRect; var bounds = this.bounds; if(bounds.x > rect.x + rect.w || bounds.y > rect.y + rect.h || bounds.x + bounds.w < rect.x || bounds.y + bounds.h < rect.y) return; } graphics.SaveGrState(); graphics.SetIntegerGrid(false); graphics.transform3(this.transform, false); var ln_width; if(this.pen && AscFormat.isRealNumber(this.pen.w)) { ln_width = this.pen.w/36000; } else { ln_width = 0; } graphics.AddClipRect(-ln_width, -ln_width, this.extX+2*ln_width, this.extY+2*ln_width); if(this.chartObj) { this.chartObj.draw(this, graphics); } if(this.chart && !this.bEmptySeries) { if(this.chart.plotArea) { // var oChartSize = this.getChartSizes(); // graphics.p_width(70); // graphics.p_color(0, 0, 0, 255); // graphics._s(); // graphics._m(oChartSize.startX, oChartSize.startY); // graphics._l(oChartSize.startX + oChartSize.w, oChartSize.startY + 0); // graphics._l(oChartSize.startX + oChartSize.w, oChartSize.startY + oChartSize.h); // graphics._l(oChartSize.startX + 0, oChartSize.startY + oChartSize.h); // graphics._z(); // graphics.ds(); var aCharts = this.chart.plotArea.charts; for(var t = 0; t < aCharts.length; ++t){ var oChart = aCharts[t]; if(oChart && oChart.series) { var series = oChart.series; var _len = oChart.getObjectType() === AscDFH.historyitem_type_PieChart ? 1 : series.length; for(var i = 0; i < _len; ++i) { var ser = series[i]; var pts = AscFormat.getPtsFromSeries(ser); for(var j = 0; j < pts.length; ++j) { if(pts[j].compiledDlb) pts[j].compiledDlb.draw(graphics); } } } } for(var i = 0; i < this.chart.plotArea.axId.length; ++i){ var oAxis = this.chart.plotArea.axId[i]; if(oAxis.title){ oAxis.title.draw(graphics); } if(oAxis.labels){ oAxis.labels.draw(graphics); } } } if(this.chart.title) { this.chart.title.draw(graphics); } if(this.chart.legend) { this.chart.legend.draw(graphics); } } graphics.RestoreGrState(); if(this.drawLocks(this.transform, graphics)){ graphics.RestoreGrState(); } }; CChartSpace.prototype.addToSetPosition = function(dLbl) { if(dLbl instanceof AscFormat.CDLbl) this.recalcInfo.dataLbls.push(dLbl); else if(dLbl instanceof AscFormat.CTitle) this.recalcInfo.axisLabels.push(dLbl); }; CChartSpace.prototype.recalculateChart = function() { this.pathMemory.curPos = -1; if(this.chartObj == null) this.chartObj = new AscFormat.CChartsDrawer(); this.chartObj.recalculate(this); }; CChartSpace.prototype.GetRevisionsChangeParagraph = function(SearchEngine){ var titles = this.getAllTitles(), i; if(titles.length === 0){ return; } var oSelectedTitle = this.selection.title || this.selection.textSelection; if(oSelectedTitle){ for(i = 0; i < titles.length; ++i){ if(oSelectedTitle === titles[i]){ break; } } if(i === titles.length){ return; } } else{ if(SearchEngine.Get_Direction() > 0){ i = 0; } else{ i = titles.length - 1; } } while(!SearchEngine.Is_Found()){ titles[i].GetRevisionsChangeParagraph(SearchEngine); if(SearchEngine.Get_Direction() > 0){ if(i === titles.length - 1){ break; } ++i; } else{ if(i === 0){ break; } --i; } } }; CChartSpace.prototype.Search = function(Str, Props, SearchEngine, Type) { var titles = this.getAllTitles(); for(var i = 0; i < titles.length; ++i) { titles[i].Search(Str, Props, SearchEngine, Type) } }; CChartSpace.prototype.Search_GetId = function(bNext, bCurrent) { var Current = -1; var titles = this.getAllTitles(); var Len = titles.length; var Id = null; if ( true === bCurrent ) { for(var i = 0; i < Len; ++i) { if(titles[i] === this.selection.textSelection) { Current = i; break; } } } if ( true === bNext ) { var Start = ( -1 !== Current ? Current : 0 ); for ( var i = Start; i < Len; i++ ) { if ( titles[i].Search_GetId ) { Id = titles[i].Search_GetId(true, i === Current ? true : false); if ( null !== Id ) return Id; } } } else { var Start = ( -1 !== Current ? Current : Len - 1 ); for ( var i = Start; i >= 0; i-- ) { if (titles[i].Search_GetId ) { Id = titles[i].Search_GetId(false, i === Current ? true : false); if ( null !== Id ) return Id; } } } return null; }; function getPtsFromSeries(ser) { if(ser) { if(ser.val) { if(ser.val.numRef && ser.val.numRef.numCache) return ser.val.numRef.numCache.pts; else if(ser.val.numLit) return ser.val.numLit.pts; } else if(ser.yVal) { if(ser.yVal.numRef && ser.yVal.numRef.numCache) return ser.yVal.numRef.numCache.pts; else if(ser.yVal.numLit) return ser.yVal.numLit.pts; } } return []; } function getCatStringPointsFromSeries(ser) { if(ser && ser.cat) { if(ser.cat.strRef && ser.cat.strRef.strCache) { return ser.cat.strRef.strCache; } else if(ser.cat.strLit) { return ser.cat.strLit; } } return null; } function getMaxIdx(arr) { var max_idx = 0; for(var i = 0; i < arr.length;++i) arr[i].idx > max_idx && (max_idx = arr[i].idx); return max_idx+1; } function getArrayFillsFromBase(arrBaseFills, needFillsCount) { var ret = []; var nMaxCycleIdx = parseInt((needFillsCount - 1)/arrBaseFills.length); for(var i = 0; i < needFillsCount; ++i) { var nCycleIdx = ( i / arrBaseFills.length ) >> 0; var fShadeTint = ( nCycleIdx + 1 ) / (nMaxCycleIdx + 2) * 1.4 - 0.7; if(fShadeTint < 0) { fShadeTint = -(1 + fShadeTint); } else { fShadeTint = (1 - fShadeTint); } var color = CreateUniFillSolidFillWidthTintOrShade(arrBaseFills[i % arrBaseFills.length], fShadeTint); ret.push(color); } return ret; } function GetTypeMarkerByIndex(index) { return AscFormat.MARKER_SYMBOL_TYPE[index % 9]; } function CreateUnfilFromRGB(r, g, b) { var ret = new AscFormat.CUniFill(); ret.setFill(new AscFormat.CSolidFill()); ret.fill.setColor(new AscFormat.CUniColor()); ret.fill.color.setColor(new AscFormat.CRGBColor()); ret.fill.color.color.setColor(r, g, b); return ret; } function CreateColorMapByIndex(index) { var ret = []; switch(index) { case 1: { ret.push(CreateUnfilFromRGB(85, 85, 85)); ret.push(CreateUnfilFromRGB(158, 158, 158)); ret.push(CreateUnfilFromRGB(114, 114, 114)); ret.push(CreateUnfilFromRGB(70, 70, 70)); ret.push(CreateUnfilFromRGB(131, 131, 131)); ret.push(CreateUnfilFromRGB(193, 193, 193)); break; } case 2: { for(var i = 0; i < 6; ++i) { ret.push(CreateUnifillSolidFillSchemeColorByIndex(i)); } break; } default: { ret.push(CreateUnifillSolidFillSchemeColorByIndex(index - 3)); break; } } return ret; } function CreateUniFillSolidFillWidthTintOrShade(unifill, effectVal) { var ret = unifill.createDuplicate(); var unicolor = ret.fill.color; if(effectVal !== 0) { effectVal*=100000.0; if(!unicolor.Mods) unicolor.setMods(new AscFormat.CColorModifiers()); var mod = new AscFormat.CColorMod(); if(effectVal > 0) { mod.setName("tint"); mod.setVal(effectVal); } else { mod.setName("shade"); mod.setVal(Math.abs(effectVal)); } unicolor.Mods.addMod(mod); } return ret; } function CreateUnifillSolidFillSchemeColor(colorId, tintOrShade) { var unifill = new AscFormat.CUniFill(); unifill.setFill(new AscFormat.CSolidFill()); unifill.fill.setColor(new AscFormat.CUniColor()); unifill.fill.color.setColor(new AscFormat.CSchemeColor()); unifill.fill.color.color.setId(colorId); return CreateUniFillSolidFillWidthTintOrShade(unifill, tintOrShade); } function CreateNoFillLine() { var ret = new AscFormat.CLn(); ret.setFill(CreateNoFillUniFill()); return ret; } function CreateNoFillUniFill() { var ret = new AscFormat.CUniFill(); ret.setFill(new AscFormat.CNoFill()); return ret; } function CExternalData() { this.autoUpdate = null; this.id = null; this.Id = g_oIdCounter.Get_NewId(); g_oTableId.Add(this, this.Id); } CExternalData.prototype = { Get_Id: function() { return this.Id; }, Refresh_RecalcData: function() {}, getObjectType: function() { return AscDFH.historyitem_type_ExternalData; }, setAutoUpdate: function(pr) { History.Add(new CChangesDrawingsBool(this, AscDFH.historyitem_ExternalData_SetAutoUpdate, this.autoUpdate, pr)); this.autoUpdate = pr; }, setId: function(pr) { History.Add(new CChangesDrawingsString(this, AscDFH.historyitem_ExternalData_SetId, this.id, pr)); this.id = pr; } }; function CPivotSource() { this.fmtId = null; this.name = null; this.Id = g_oIdCounter.Get_NewId(); g_oTableId.Add(this, this.Id); } CPivotSource.prototype = { Get_Id: function() { return this.Id; }, Refresh_RecalcData: function() {}, getObjectType: function() { return AscDFH.historyitem_type_PivotSource; }, Write_ToBinary2: function (w) { w.WriteLong(this.getObjectType()); w.WriteString2(this.Id); }, Read_FromBinary2: function (r) { this.Id = r.GetString2(); }, setFmtId: function(pr) { History.Add(new CChangesDrawingsLong(this, AscDFH.historyitem_PivotSource_SetFmtId, this.fmtId, pr)); this.fmtId = pr; }, setName: function(pr) { History.Add(new CChangesDrawingsString(this, AscDFH.historyitem_PivotSource_SetName, this.name, pr)); this.name = pr; }, createDuplicate: function() { var copy = new CPivotSource(); if(AscFormat.isRealNumber(this.fmtId)) { copy.setFmtId(this.fmtId); } if(typeof this.name === "string") { copy.setName(this.name); } return copy; } }; function CProtection() { this.chartObject = null; this.data = null; this.formatting = null; this.selection = null; this.userInterface = null; this.Id = g_oIdCounter.Get_NewId(); g_oTableId.Add(this, this.Id); } CProtection.prototype = { Get_Id: function() { return this.Id; }, Refresh_RecalcData: function() {}, getObjectType: function() { return AscDFH.historyitem_type_Protection; }, Write_ToBinary2: function (w) { w.WriteLong(this.getObjectType()); w.WriteString2(this.Id); }, Read_FromBinary2: function (r) { this.Id = r.GetString2(); }, setChartObject: function(pr) { History.Add(new CChangesDrawingsBool(this, AscDFH.historyitem_Protection_SetChartObject, this.chartObject, pr)); this.chartObject = pr; }, setData: function(pr) { History.Add(new CChangesDrawingsBool(this, AscDFH.historyitem_Protection_SetData, this.data, pr)); this.data = pr; }, setFormatting: function(pr) { History.Add(new CChangesDrawingsBool(this, AscDFH.historyitem_Protection_SetFormatting, this.formatting, pr)); this.formatting = pr; }, setSelection: function(pr) { History.Add(new CChangesDrawingsBool(this, AscDFH.historyitem_Protection_SetSelection, this.selection, pr)); this.selection = pr; }, setUserInterface: function(pr) { History.Add(new CChangesDrawingsBool(this, AscDFH.historyitem_Protection_SetUserInterface, this.userInterface, pr)); this.userInterface = pr; }, createDuplicate: function() { var c = new CProtection(); if(this.chartObject !== null) c.setChartObject(this.chartObject); if(this.data !== null) c.setData(this.data); if(this.formatting !== null) c.setFormatting(this.formatting); if(this.selection !== null) c.setSelection(this.selection); if(this.userInterface !== null) c.setUserInterface(this.userInterface); return c; } }; function CPrintSettings() { this.headerFooter = null; this.pageMargins = null; this.pageSetup = null; this.Id = g_oIdCounter.Get_NewId(); g_oTableId.Add(this, this.Id); } CPrintSettings.prototype = { Get_Id: function() { return this.Id; }, createDuplicate : function() { var oPS = new CPrintSettings(); if ( this.headerFooter ) oPS.setHeaderFooter(this.headerFooter.createDuplicate()); if ( this.pageMargins ) oPS.setPageMargins(this.pageMargins.createDuplicate()); if ( this.pageSetup ) oPS.setPageSetup(this.pageSetup.createDuplicate()); return oPS; }, Refresh_RecalcData: function() {}, getObjectType: function() { return AscDFH.historyitem_type_PrintSettings; }, Write_ToBinary2: function (w) { w.WriteLong(this.getObjectType()); w.WriteString2(this.Id); }, Read_FromBinary2: function (r) { this.Id = r.GetString2(); }, setHeaderFooter: function(pr) { History.Add(new CChangesDrawingsObject(this, AscDFH.historyitem_PrintSettingsSetHeaderFooter, this.headerFooter, pr)); this.headerFooter = pr; }, setPageMargins: function(pr) { History.Add(new CChangesDrawingsObject(this, AscDFH.historyitem_PrintSettingsSetPageMargins, this.pageMargins, pr)); this.pageMargins = pr; }, setPageSetup: function(pr) { History.Add(new CChangesDrawingsObject(this, AscDFH.historyitem_PrintSettingsSetPageSetup, this.pageSetup, pr)); this.pageSetup = pr; } }; function CHeaderFooterChart() { this.alignWithMargins = null; this.differentFirst = null; this.differentOddEven = null; this.evenFooter = null; this.evenHeader = null; this.firstFooter = null; this.firstHeader = null; this.oddFooter = null; this.oddHeader = null; this.Id = g_oIdCounter.Get_NewId(); g_oTableId.Add(this, this.Id); } CHeaderFooterChart.prototype = { Get_Id: function() { return this.Id; }, createDuplicate : function() { var oHFC = new CHeaderFooterChart(); if(this.alignWithMargins !== null) oHFC.setAlignWithMargins(this.alignWithMargins); if(this.differentFirst !== null) oHFC.setDifferentFirst(this.differentFirst); if(this.differentOddEven !== null) oHFC.setDifferentOddEven(this.differentOddEven); if ( this.evenFooter !== null ) oHFC.setEvenFooter(this.evenFooter); if ( this.evenHeader !== null) oHFC.setEvenHeader(this.evenHeader); if ( this.firstFooter !== null) oHFC.setFirstFooter(this.firstFooter); if ( this.firstHeader !== null) oHFC.setFirstHeader(this.firstHeader); if ( this.oddFooter !== null) oHFC.setOddFooter(this.oddFooter); if ( this.oddHeader !== null) oHFC.setOddHeader(this.oddHeader); return oHFC; }, Refresh_RecalcData: function() {}, Write_ToBinary2: function (w) { w.WriteLong(this.getObjectType()); w.WriteString2(this.Id); }, Read_FromBinary2: function (r) { this.Id = r.GetString2(); }, getObjectType: function() { return AscDFH.historyitem_type_HeaderFooterChart; }, setAlignWithMargins: function(pr) { History.Add(new CChangesDrawingsBool(this, AscDFH.historyitem_HeaderFooterChartSetAlignWithMargins, this.alignWithMargins, pr)); this.alignWithMargins = pr; }, setDifferentFirst: function(pr) { History.Add(new CChangesDrawingsBool(this, AscDFH.historyitem_HeaderFooterChartSetDifferentFirst, this.differentFirst, pr)); this.differentFirst = pr; }, setDifferentOddEven: function(pr) { History.Add(new CChangesDrawingsBool(this, AscDFH.historyitem_HeaderFooterChartSetDifferentOddEven, this.differentOddEven, pr)); this.differentOddEven = pr; }, setEvenFooter: function(pr) { History.Add(new CChangesDrawingsString(this, AscDFH.historyitem_HeaderFooterChartSetEvenFooter, this.evenFooter, pr)); this.evenFooter = pr; }, setEvenHeader: function(pr) { History.Add(new CChangesDrawingsString(this, AscDFH.historyitem_HeaderFooterChartSetEvenHeader, this.evenHeader, pr)); this.evenHeader = pr; }, setFirstFooter: function(pr) { History.Add(new CChangesDrawingsString(this, AscDFH.historyitem_HeaderFooterChartSetFirstFooter, this.firstFooter, pr)); this.firstFooter = pr; }, setFirstHeader: function(pr) { History.Add(new CChangesDrawingsString(this, AscDFH.historyitem_HeaderFooterChartSetFirstHeader, this.firstHeader, pr)); this.firstHeader = pr; }, setOddFooter: function(pr) { History.Add(new CChangesDrawingsString(this, AscDFH.historyitem_HeaderFooterChartSetOddFooter, this.oddFooter, pr)); this.oddFooter = pr; }, setOddHeader: function(pr) { History.Add(new CChangesDrawingsString(this, AscDFH.historyitem_HeaderFooterChartSetOddHeader, this.oddHeader, pr)); this.oddHeader = pr; } }; function CPageMarginsChart() { this.b = null; this.footer = null; this.header = null; this.l = null; this.r = null; this.t = null; this.Id = g_oIdCounter.Get_NewId(); g_oTableId.Add(this, this.Id); } CPageMarginsChart.prototype = { Get_Id: function() { return this.Id; }, createDuplicate : function() { var oPMC = new CPageMarginsChart(); if(this.b !== null) oPMC.setB(this.b); if(this.footer !== null) oPMC.setFooter(this.footer); if(this.header !== null) oPMC.setHeader(this.header); if(this.l !== null) oPMC.setL(this.l); if(this.r !== null) oPMC.setR(this.r); if(this.t !== null) oPMC.setT(this.t); return oPMC; }, Refresh_RecalcData: function() {}, Write_ToBinary2: function (w) { w.WriteLong(this.getObjectType()); w.WriteString2(this.Id); }, Read_FromBinary2: function (r) { this.Id = r.GetString2(); }, getObjectType: function() { return AscDFH.historyitem_type_PageMarginsChart; }, setB: function(pr) { History.Add(new CChangesDrawingsDouble(this, AscDFH.historyitem_PageMarginsSetB, this.b, pr)); this.b = pr; }, setFooter: function(pr) { History.Add(new CChangesDrawingsDouble(this, AscDFH.historyitem_PageMarginsSetFooter, this.footer, pr)); this.footer = pr; }, setHeader: function(pr) { History.Add(new CChangesDrawingsDouble(this, AscDFH.historyitem_PageMarginsSetHeader, this.header, pr)); this.header = pr; }, setL: function(pr) { History.Add(new CChangesDrawingsDouble(this, AscDFH.historyitem_PageMarginsSetL, this.l, pr)); this.l = pr; }, setR: function(pr) { History.Add(new CChangesDrawingsDouble(this, AscDFH.historyitem_PageMarginsSetR, this.r, pr)); this.r = pr; }, setT: function(pr) { History.Add(new CChangesDrawingsDouble(this, AscDFH.historyitem_PageMarginsSetT, this.t, pr)); this.t = pr; } }; function CPageSetup() { this.blackAndWhite = null; this.copies = null; this.draft = null; this.firstPageNumber = null; this.horizontalDpi = null; this.orientation = null; this.paperHeight = null; this.paperSize = null; this.paperWidth = null; this.useFirstPageNumb = null; this.verticalDpi = null; this.Id = g_oIdCounter.Get_NewId(); g_oTableId.Add(this, this.Id); } CPageSetup.prototype = { Get_Id: function() { return this.Id; }, createDuplicate : function() { var oPS = new CPageSetup(); if(this.blackAndWhite !== null) oPS.setBlackAndWhite(this.blackAndWhite); if(this.copies !== null) oPS.setCopies(this.copies); if(this.draft !== null) oPS.setDraft(this.draft); if(this.firstPageNumber !== null) oPS.setFirstPageNumber(this.firstPageNumber); if(this.horizontalDpi !== null) oPS.setHorizontalDpi(this.horizontalDpi); if(this.orientation !== null) oPS.setOrientation(this.orientation); if(this.paperHeight !== null) oPS.setPaperHeight(this.paperHeight); if(this.paperSize !== null) oPS.setPaperSize(this.paperSize); if(this.paperWidth !== null) oPS.setPaperWidth(this.paperWidth); if(this.useFirstPageNumb !== null) oPS.setUseFirstPageNumb(this.useFirstPageNumb); if(this.verticalDpi !== null) oPS.setVerticalDpi(this.verticalDpi); return oPS; }, Refresh_RecalcData: function() {}, Write_ToBinary2: function (w) { w.WriteLong(this.getObjectType()); w.WriteString2(this.Id); }, Read_FromBinary2: function (r) { this.Id = r.GetString2(); }, getObjectType: function() { return AscDFH.historyitem_type_PageSetup; }, setBlackAndWhite: function(pr) { History.Add(new CChangesDrawingsBool(this, AscDFH.historyitem_PageSetupSetBlackAndWhite, this.blackAndWhite, pr)); this.blackAndWhite = pr; }, setCopies: function(pr) { History.Add(new CChangesDrawingsLong(this, AscDFH.historyitem_PageSetupSetCopies, this.copies, pr)); this.copies = pr; }, setDraft: function(pr) { History.Add(new CChangesDrawingsBool(this, AscDFH.historyitem_PageSetupSetDraft, this.draft, pr)); this.draft = pr; }, setFirstPageNumber: function(pr) { History.Add(new CChangesDrawingsLong(this, AscDFH.historyitem_PageSetupSetFirstPageNumber, this.firstPageNumber, pr)); this.firstPageNumber = pr; }, setHorizontalDpi: function(pr) { History.Add(new CChangesDrawingsLong(this, AscDFH.historyitem_PageSetupSetHorizontalDpi, this.horizontalDpi, pr)); this.horizontalDpi = pr; }, setOrientation: function(pr) { History.Add(new CChangesDrawingsLong(this, AscDFH.historyitem_PageSetupSetOrientation, this.orientation, pr)); this.orientation = pr; }, setPaperHeight: function(pr) { History.Add(new CChangesDrawingsDouble(this, AscDFH.historyitem_PageSetupSetPaperHeight, this.paperHeight, pr)); this.paperHeight = pr; }, setPaperSize: function(pr) { History.Add(new CChangesDrawingsLong(this, AscDFH.historyitem_PageSetupSetPaperSize, this.paperSize, pr)); this.paperSize = pr; }, setPaperWidth: function(pr) { History.Add(new CChangesDrawingsDouble(this, AscDFH.historyitem_PageSetupSetPaperWidth, this.paperWidth, pr)); this.paperWidth = pr; }, setUseFirstPageNumb: function(pr) { History.Add(new CChangesDrawingsBool(this, AscDFH.historyitem_PageSetupSetUseFirstPageNumb, this.useFirstPageNumb, pr)); this.useFirstPageNumb = pr; }, setVerticalDpi: function(pr) { History.Add(new CChangesDrawingsLong(this, AscDFH.historyitem_PageSetupSetVerticalDpi, this.verticalDpi, pr)); this.verticalDpi = pr; } }; function CreateView3d(nRotX, nRotY, bRAngAx, nDepthPercent) { var oView3d = new AscFormat.CView3d(); AscFormat.isRealNumber(nRotX) && oView3d.setRotX(nRotX); AscFormat.isRealNumber(nRotY) && oView3d.setRotY(nRotY); AscFormat.isRealBool(bRAngAx) && oView3d.setRAngAx(bRAngAx); AscFormat.isRealNumber(nDepthPercent) && oView3d.setDepthPercent(nDepthPercent); return oView3d; } function GetNumFormatFromSeries(aAscSeries){ if(aAscSeries && aAscSeries[0] && aAscSeries[0].Val && aAscSeries[0].Val.NumCache && aAscSeries[0].Val.NumCache[0]){ if(typeof (aAscSeries[0].Val.NumCache[0].numFormatStr) === "string" && aAscSeries[0].Val.NumCache[0].numFormatStr.length > 0){ return aAscSeries[0].Val.NumCache[0].numFormatStr; } } return "General"; } function FillCatAxNumFormat(oCatAxis, aAscSeries){ if(!oCatAxis){ return; } var sFormatCode = null; if(aAscSeries && aAscSeries[0] && aAscSeries[0].Cat && aAscSeries[0].Cat.NumCache && aAscSeries[0].Cat.NumCache[0]){ if(typeof (aAscSeries[0].Cat.NumCache[0].numFormatStr) === "string" && aAscSeries[0].Cat.NumCache[0].numFormatStr.length > 0){ sFormatCode = aAscSeries[0].Cat.NumCache[0].numFormatStr; } } if(sFormatCode){ oCatAxis.setNumFmt(new AscFormat.CNumFmt()); oCatAxis.numFmt.setFormatCode(sFormatCode ? sFormatCode : "General"); oCatAxis.numFmt.setSourceLinked(true); } } function CreateLineChart(chartSeries, type, bUseCache, oOptions, b3D) { var asc_series = chartSeries.series; var chart_space = new CChartSpace(); chart_space.setDate1904(false); chart_space.setLang("en-US"); chart_space.setRoundedCorners(false); chart_space.setChart(new AscFormat.CChart()); chart_space.setPrintSettings(new CPrintSettings()); var chart = chart_space.chart; if(b3D) { chart.setView3D(CreateView3d(15, 20, true, 100)); chart.setDefaultWalls(); } chart.setAutoTitleDeleted(false); chart.setPlotArea(new AscFormat.CPlotArea()); chart.setPlotVisOnly(true); var disp_blanks_as; if(type === AscFormat.GROUPING_STANDARD) { disp_blanks_as = DISP_BLANKS_AS_GAP; } else { disp_blanks_as = DISP_BLANKS_AS_ZERO; } chart.setDispBlanksAs(disp_blanks_as); chart.setShowDLblsOverMax(false); var plot_area = chart.plotArea; plot_area.setLayout(new AscFormat.CLayout()); plot_area.addChart(new AscFormat.CLineChart()); var cat_ax = new AscFormat.CCatAx(); var val_ax = new AscFormat.CValAx(); cat_ax.setAxId(++Ax_Counter.GLOBAL_AX_ID_COUNTER); val_ax.setAxId(++Ax_Counter.GLOBAL_AX_ID_COUNTER); cat_ax.setCrossAx(val_ax); val_ax.setCrossAx(cat_ax); plot_area.addAxis(cat_ax); plot_area.addAxis(val_ax); var line_chart = plot_area.charts[0]; line_chart.setGrouping(type); line_chart.setVaryColors(false); line_chart.setMarker(true); line_chart.setSmooth(false); line_chart.addAxId(cat_ax); line_chart.addAxId(val_ax); val_ax.setCrosses(2); var parsedHeaders = chartSeries.parsedHeaders; var bInCols; if(isRealObject(oOptions)) { bInCols = oOptions.inColumns === true; } else { bInCols = false; } for(var i = 0; i < asc_series.length; ++i) { var series = new AscFormat.CLineSeries(); series.setIdx(i); series.setOrder(i); series.setMarker(new AscFormat.CMarker()); series.marker.setSymbol(AscFormat.SYMBOL_NONE); series.setSmooth(false); series.setVal(new AscFormat.CYVal()); FillValNum(series.val, asc_series[i].Val, bUseCache); if(parsedHeaders.bTop && !bInCols || bInCols && parsedHeaders.bLeft) { series.setCat(new AscFormat.CCat()); FillCatStr(series.cat, asc_series[i].Cat, bUseCache); } if((parsedHeaders.bLeft && !bInCols || bInCols && parsedHeaders.bTop) && asc_series[i].TxCache && typeof asc_series[i].TxCache.Formula === "string" && asc_series[i].TxCache.Formula.length > 0) { FillSeriesTx(series, asc_series[i].TxCache, bUseCache); } line_chart.addSer(series); } cat_ax.setScaling(new AscFormat.CScaling()); cat_ax.setDelete(false); cat_ax.setAxPos(AscFormat.AX_POS_B); cat_ax.setMajorTickMark(c_oAscTickMark.TICK_MARK_OUT); cat_ax.setMinorTickMark(c_oAscTickMark.TICK_MARK_OUT); cat_ax.setTickLblPos(c_oAscTickLabelsPos.TICK_LABEL_POSITION_NEXT_TO); cat_ax.setCrosses(AscFormat.CROSSES_AUTO_ZERO); cat_ax.setAuto(true); cat_ax.setLblAlgn(AscFormat.LBL_ALG_CTR); cat_ax.setLblOffset(100); cat_ax.setNoMultiLvlLbl(false); var scaling = cat_ax.scaling; scaling.setOrientation(AscFormat.ORIENTATION_MIN_MAX); FillCatAxNumFormat(cat_ax, asc_series); val_ax.setScaling(new AscFormat.CScaling()); val_ax.setDelete(false); val_ax.setAxPos(AscFormat.AX_POS_L); val_ax.setMajorGridlines(new AscFormat.CSpPr()); val_ax.setNumFmt(new AscFormat.CNumFmt()); val_ax.setMajorTickMark(c_oAscTickMark.TICK_MARK_OUT); val_ax.setMinorTickMark(c_oAscTickMark.TICK_MARK_NONE); val_ax.setTickLblPos(c_oAscTickLabelsPos.TICK_LABEL_POSITION_NEXT_TO); val_ax.setCrosses(AscFormat.CROSSES_AUTO_ZERO); val_ax.setCrossBetween(AscFormat.CROSS_BETWEEN_BETWEEN); scaling = val_ax.scaling; scaling.setOrientation(AscFormat.ORIENTATION_MIN_MAX); var num_fmt = val_ax.numFmt; var format_code; if(type === AscFormat.GROUPING_PERCENT_STACKED) { format_code = "0%"; } else { format_code = GetNumFormatFromSeries(asc_series); } num_fmt.setFormatCode(format_code); num_fmt.setSourceLinked(true); if(asc_series.length > 1) { chart.setLegend(new AscFormat.CLegend()); var legend = chart.legend; legend.setLegendPos(c_oAscChartLegendShowSettings.right); legend.setLayout(new AscFormat.CLayout()); legend.setOverlay(false); } var print_settings = chart_space.printSettings; print_settings.setHeaderFooter(new CHeaderFooterChart()); print_settings.setPageMargins(new CPageMarginsChart()); print_settings.setPageSetup(new CPageSetup()); var page_margins = print_settings.pageMargins; page_margins.setB(0.75); page_margins.setL(0.7); page_margins.setR(0.7); page_margins.setT(0.75); page_margins.setHeader(0.3); page_margins.setFooter(0.3); return chart_space; } function CreateBarChart(chartSeries, type, bUseCache, oOptions, b3D, bDepth) { var asc_series = chartSeries.series; var chart_space = new CChartSpace(); chart_space.setDate1904(false); chart_space.setLang("en-US"); chart_space.setRoundedCorners(false); chart_space.setChart(new AscFormat.CChart()); chart_space.setPrintSettings(new CPrintSettings()); var chart = chart_space.chart; chart.setAutoTitleDeleted(false); if(b3D) { chart.setView3D(CreateView3d(15, 20, true, bDepth ? 100 : undefined)); chart.setDefaultWalls(); } chart.setPlotArea(new AscFormat.CPlotArea()); chart.setPlotVisOnly(true); chart.setDispBlanksAs(DISP_BLANKS_AS_GAP); chart.setShowDLblsOverMax(false); var plot_area = chart.plotArea; plot_area.setLayout(new AscFormat.CLayout()); plot_area.addChart(new AscFormat.CBarChart()); var bInCols; if(isRealObject(oOptions)) { bInCols = oOptions.inColumns === true; } else { bInCols = false; } var cat_ax = new AscFormat.CCatAx(); var val_ax = new AscFormat.CValAx(); cat_ax.setAxId(++Ax_Counter.GLOBAL_AX_ID_COUNTER); val_ax.setAxId(++Ax_Counter.GLOBAL_AX_ID_COUNTER); cat_ax.setCrossAx(val_ax); val_ax.setCrossAx(cat_ax); plot_area.addAxis(cat_ax); plot_area.addAxis(val_ax); var bar_chart = plot_area.charts[0]; if(b3D) { bar_chart.set3D(true); } bar_chart.setBarDir(AscFormat.BAR_DIR_COL); bar_chart.setGrouping(type); bar_chart.setVaryColors(false); var parsedHeaders = chartSeries.parsedHeaders; for(var i = 0; i < asc_series.length; ++i) { var series = new AscFormat.CBarSeries(); series.setIdx(i); series.setOrder(i); series.setInvertIfNegative(false); series.setVal(new AscFormat.CYVal()); FillValNum(series.val, asc_series[i].Val, bUseCache); if(parsedHeaders.bTop && !bInCols || bInCols && parsedHeaders.bLeft) { series.setCat(new AscFormat.CCat()); FillCatStr(series.cat, asc_series[i].Cat, bUseCache); } if((parsedHeaders.bLeft && !bInCols || bInCols && parsedHeaders.bTop) && asc_series[i].TxCache && typeof asc_series[i].TxCache.Formula === "string" && asc_series[i].TxCache.Formula.length > 0) { FillSeriesTx(series, asc_series[i].TxCache, bUseCache); } bar_chart.addSer(series); } bar_chart.setGapWidth(150); if(AscFormat.BAR_GROUPING_PERCENT_STACKED === type || AscFormat.BAR_GROUPING_STACKED === type) bar_chart.setOverlap(100); if(b3D) { bar_chart.setShape(BAR_SHAPE_BOX); } bar_chart.addAxId(cat_ax); bar_chart.addAxId(val_ax); cat_ax.setScaling(new AscFormat.CScaling()); cat_ax.setDelete(false); cat_ax.setAxPos(AscFormat.AX_POS_B); cat_ax.setMajorTickMark(c_oAscTickMark.TICK_MARK_OUT); cat_ax.setMinorTickMark(c_oAscTickMark.TICK_MARK_NONE); cat_ax.setCrosses(AscFormat.CROSSES_AUTO_ZERO); cat_ax.setAuto(true); cat_ax.setLblAlgn(AscFormat.LBL_ALG_CTR); cat_ax.setLblOffset(100); cat_ax.setNoMultiLvlLbl(false); var scaling = cat_ax.scaling; scaling.setOrientation(AscFormat.ORIENTATION_MIN_MAX); FillCatAxNumFormat(cat_ax, asc_series); val_ax.setScaling(new AscFormat.CScaling()); val_ax.setDelete(false); val_ax.setAxPos(AscFormat.AX_POS_L); val_ax.setMajorGridlines(new AscFormat.CSpPr()); val_ax.setNumFmt(new AscFormat.CNumFmt()); var num_fmt = val_ax.numFmt; var format_code; if(type === AscFormat.BAR_GROUPING_PERCENT_STACKED) { format_code = "0%"; } else { format_code = GetNumFormatFromSeries(asc_series); } num_fmt.setFormatCode(format_code); num_fmt.setSourceLinked(true); val_ax.setMajorTickMark(c_oAscTickMark.TICK_MARK_OUT); val_ax.setMinorTickMark(c_oAscTickMark.TICK_MARK_NONE); val_ax.setTickLblPos(c_oAscTickLabelsPos.TICK_LABEL_POSITION_NEXT_TO); val_ax.setCrosses(AscFormat.CROSSES_AUTO_ZERO); val_ax.setCrossBetween(AscFormat.CROSS_BETWEEN_BETWEEN); scaling = val_ax.scaling; scaling.setOrientation(AscFormat.ORIENTATION_MIN_MAX); if(asc_series.length > 1) { chart.setLegend(new AscFormat.CLegend()); var legend = chart.legend; legend.setLegendPos(c_oAscChartLegendShowSettings.right); legend.setLayout(new AscFormat.CLayout()); legend.setOverlay(false); } var print_settings = chart_space.printSettings; print_settings.setHeaderFooter(new CHeaderFooterChart()); print_settings.setPageMargins(new CPageMarginsChart()); print_settings.setPageSetup(new CPageSetup()); var page_margins = print_settings.pageMargins; page_margins.setB(0.75); page_margins.setL(0.7); page_margins.setR(0.7); page_margins.setT(0.75); page_margins.setHeader(0.3); page_margins.setFooter(0.3); return chart_space; } function CreateHBarChart(chartSeries, type, bUseCache, oOptions, b3D) { var asc_series = chartSeries.series; var chart_space = new CChartSpace(); chart_space.setDate1904(false); chart_space.setLang("en-US"); chart_space.setRoundedCorners(false); chart_space.setChart(new AscFormat.CChart()); chart_space.setPrintSettings(new CPrintSettings()); var chart = chart_space.chart; chart.setAutoTitleDeleted(false); if(b3D) { chart.setView3D(CreateView3d(15, 20, true, undefined)); chart.setDefaultWalls(); } chart.setPlotArea(new AscFormat.CPlotArea()); chart.setPlotVisOnly(true); chart.setDispBlanksAs(DISP_BLANKS_AS_GAP); chart.setShowDLblsOverMax(false); var plot_area = chart.plotArea; plot_area.setLayout(new AscFormat.CLayout()); plot_area.addChart(new AscFormat.CBarChart()); var cat_ax = new AscFormat.CCatAx(); var val_ax = new AscFormat.CValAx(); cat_ax.setAxId(++Ax_Counter.GLOBAL_AX_ID_COUNTER); val_ax.setAxId(++Ax_Counter.GLOBAL_AX_ID_COUNTER); cat_ax.setCrossAx(val_ax); val_ax.setCrossAx(cat_ax); plot_area.addAxis(cat_ax); plot_area.addAxis(val_ax); var bar_chart = plot_area.charts[0]; bar_chart.setBarDir(AscFormat.BAR_DIR_BAR); bar_chart.setGrouping(type); bar_chart.setVaryColors(false); var parsedHeaders = chartSeries.parsedHeaders; var bInCols; if(isRealObject(oOptions)) { bInCols = oOptions.inColumns === true; } else { bInCols = false; } for(var i = 0; i < asc_series.length; ++i) { var series = new AscFormat.CBarSeries(); series.setIdx(i); series.setOrder(i); series.setInvertIfNegative(false); series.setVal(new AscFormat.CYVal()); FillValNum(series.val, asc_series[i].Val, bUseCache); if((parsedHeaders.bTop && !bInCols || bInCols && parsedHeaders.bLeft)) { series.setCat(new AscFormat.CCat()); FillCatStr(series.cat, asc_series[i].Cat, bUseCache); } if((parsedHeaders.bLeft && !bInCols || bInCols && parsedHeaders.bTop) && asc_series[i].TxCache && typeof asc_series[i].TxCache.Formula === "string" && asc_series[i].TxCache.Formula.length > 0) { FillSeriesTx(series, asc_series[i].TxCache, bUseCache); } bar_chart.addSer(series); if(b3D) { bar_chart.setShape(BAR_SHAPE_BOX); } } //bar_chart.setDLbls(new CDLbls()); //var d_lbls = bar_chart.dLbls; //d_lbls.setShowLegendKey(false); //d_lbls.setShowVal(true); bar_chart.setGapWidth(150); if(AscFormat.BAR_GROUPING_PERCENT_STACKED === type || AscFormat.BAR_GROUPING_STACKED === type) bar_chart.setOverlap(100); bar_chart.addAxId(cat_ax); bar_chart.addAxId(val_ax); cat_ax.setScaling(new AscFormat.CScaling()); cat_ax.setDelete(false); cat_ax.setAxPos(AscFormat.AX_POS_L); cat_ax.setMajorTickMark(c_oAscTickMark.TICK_MARK_OUT); cat_ax.setMinorTickMark(c_oAscTickMark.TICK_MARK_NONE); cat_ax.setTickLblPos(c_oAscTickLabelsPos.TICK_LABEL_POSITION_NEXT_TO); cat_ax.setCrosses(AscFormat.CROSSES_AUTO_ZERO); cat_ax.setAuto(true); cat_ax.setLblAlgn(AscFormat.LBL_ALG_CTR); cat_ax.setLblOffset(100); cat_ax.setNoMultiLvlLbl(false); var scaling = cat_ax.scaling; scaling.setOrientation(AscFormat.ORIENTATION_MIN_MAX); FillCatAxNumFormat(cat_ax, asc_series); val_ax.setScaling(new AscFormat.CScaling()); val_ax.setDelete(false); val_ax.setAxPos(AscFormat.AX_POS_B); val_ax.setMajorGridlines(new AscFormat.CSpPr()); val_ax.setNumFmt(new AscFormat.CNumFmt()); val_ax.setMajorTickMark(c_oAscTickMark.TICK_MARK_OUT); val_ax.setMinorTickMark(c_oAscTickMark.TICK_MARK_NONE); val_ax.setTickLblPos(c_oAscTickLabelsPos.TICK_LABEL_POSITION_NEXT_TO); val_ax.setCrosses(AscFormat.CROSSES_AUTO_ZERO); val_ax.setCrossBetween(AscFormat.CROSS_BETWEEN_BETWEEN); scaling = val_ax.scaling; scaling.setOrientation(AscFormat.ORIENTATION_MIN_MAX); var num_fmt = val_ax.numFmt; var format_code; /*if(type === GROUPING_PERCENT_STACKED) { format_code = "0%"; } else */ { format_code = GetNumFormatFromSeries(asc_series); } num_fmt.setFormatCode(format_code); num_fmt.setSourceLinked(true); if(asc_series.length > 1) { chart.setLegend(new AscFormat.CLegend()); var legend = chart.legend; legend.setLegendPos(c_oAscChartLegendShowSettings.right); legend.setLayout(new AscFormat.CLayout()); legend.setOverlay(false); } var print_settings = chart_space.printSettings; print_settings.setHeaderFooter(new CHeaderFooterChart()); print_settings.setPageMargins(new CPageMarginsChart()); print_settings.setPageSetup(new CPageSetup()); var page_margins = print_settings.pageMargins; page_margins.setB(0.75); page_margins.setL(0.7); page_margins.setR(0.7); page_margins.setT(0.75); page_margins.setHeader(0.3); page_margins.setFooter(0.3); return chart_space; } function CreateAreaChart(chartSeries, type, bUseCache, oOptions) { var asc_series = chartSeries.series; var chart_space = new CChartSpace(); chart_space.setDate1904(false); chart_space.setLang("en-US"); chart_space.setRoundedCorners(false); chart_space.setChart(new AscFormat.CChart()); chart_space.setPrintSettings(new CPrintSettings()); var chart = chart_space.chart; chart.setAutoTitleDeleted(false); chart.setPlotArea(new AscFormat.CPlotArea()); chart.setPlotVisOnly(true); chart.setDispBlanksAs(DISP_BLANKS_AS_ZERO); chart.setShowDLblsOverMax(false); var plot_area = chart.plotArea; plot_area.setLayout(new AscFormat.CLayout()); plot_area.addChart(new AscFormat.CAreaChart()); var cat_ax = new AscFormat.CCatAx(); var val_ax = new AscFormat.CValAx(); cat_ax.setAxId(++Ax_Counter.GLOBAL_AX_ID_COUNTER); val_ax.setAxId(++Ax_Counter.GLOBAL_AX_ID_COUNTER); cat_ax.setCrossAx(val_ax); val_ax.setCrossAx(cat_ax); plot_area.addAxis(cat_ax); plot_area.addAxis(val_ax); var bInCols; if(isRealObject(oOptions)) { bInCols = oOptions.inColumns === true; } else { bInCols = false; } var area_chart = plot_area.charts[0]; area_chart.setGrouping(type); area_chart.setVaryColors(false); var parsedHeaders = chartSeries.parsedHeaders; for(var i = 0; i < asc_series.length; ++i) { var series = new AscFormat.CAreaSeries(); series.setIdx(i); series.setOrder(i); series.setVal(new AscFormat.CYVal()); FillValNum(series.val, asc_series[i].Val, bUseCache); if(parsedHeaders.bTop && !bInCols || bInCols && parsedHeaders.bLeft) { series.setCat(new AscFormat.CCat()); FillCatStr(series.cat, asc_series[i].Cat, bUseCache); } if((parsedHeaders.bLeft && !bInCols || bInCols && parsedHeaders.bTop) && asc_series[i].TxCache && typeof asc_series[i].TxCache.Formula === "string" && asc_series[i].TxCache.Formula.length > 0) { FillSeriesTx(series, asc_series[i].TxCache, bUseCache); } area_chart.addSer(series); } //area_chart.setDLbls(new CDLbls()); area_chart.addAxId(cat_ax); area_chart.addAxId(val_ax); //var d_lbls = area_chart.dLbls; //d_lbls.setShowLegendKey(false); //d_lbls.setShowVal(true); cat_ax.setScaling(new AscFormat.CScaling()); cat_ax.setDelete(false); cat_ax.setAxPos(AscFormat.AX_POS_B); cat_ax.setMajorTickMark(c_oAscTickMark.TICK_MARK_OUT); cat_ax.setMinorTickMark(c_oAscTickMark.TICK_MARK_NONE); cat_ax.setTickLblPos(c_oAscTickLabelsPos.TICK_LABEL_POSITION_NEXT_TO); cat_ax.setCrosses(AscFormat.CROSSES_AUTO_ZERO); cat_ax.setAuto(true); cat_ax.setLblAlgn(AscFormat.LBL_ALG_CTR); cat_ax.setLblOffset(100); cat_ax.setNoMultiLvlLbl(false); cat_ax.scaling.setOrientation(AscFormat.ORIENTATION_MIN_MAX); FillCatAxNumFormat(cat_ax, asc_series); val_ax.setScaling(new AscFormat.CScaling()); val_ax.setDelete(false); val_ax.setAxPos(AscFormat.AX_POS_L); val_ax.setMajorGridlines(new AscFormat.CSpPr()); val_ax.setNumFmt(new AscFormat.CNumFmt()); val_ax.setMajorTickMark(c_oAscTickMark.TICK_MARK_OUT); val_ax.setMinorTickMark(c_oAscTickMark.TICK_MARK_NONE); val_ax.setTickLblPos(c_oAscTickLabelsPos.TICK_LABEL_POSITION_NEXT_TO); val_ax.setCrosses(AscFormat.CROSSES_AUTO_ZERO); val_ax.setCrossBetween(AscFormat.CROSS_BETWEEN_MID_CAT); var scaling = val_ax.scaling; scaling.setOrientation(AscFormat.ORIENTATION_MIN_MAX); var num_fmt = val_ax.numFmt; var format_code; if(type === AscFormat.GROUPING_PERCENT_STACKED) { format_code = "0%"; } else { format_code = GetNumFormatFromSeries(asc_series); } num_fmt.setFormatCode(format_code); num_fmt.setSourceLinked(true); if(asc_series.length > 1) { chart.setLegend(new AscFormat.CLegend()); var legend = chart.legend; legend.setLegendPos(c_oAscChartLegendShowSettings.right); legend.setLayout(new AscFormat.CLayout()); legend.setOverlay(false); } var print_settings = chart_space.printSettings; print_settings.setHeaderFooter(new CHeaderFooterChart()); print_settings.setPageMargins(new CPageMarginsChart()); print_settings.setPageSetup(new CPageSetup()); var page_margins = print_settings.pageMargins; page_margins.setB(0.75); page_margins.setL(0.7); page_margins.setR(0.7); page_margins.setT(0.75); page_margins.setHeader(0.3); page_margins.setFooter(0.3); return chart_space; } function CreatePieChart(chartSeries, bDoughnut, bUseCache, oOptions, b3D) { var asc_series = chartSeries.series; var chart_space = new CChartSpace(); chart_space.setDate1904(false); chart_space.setLang("en-US"); chart_space.setRoundedCorners(false); chart_space.setStyle(2); chart_space.setChart(new AscFormat.CChart()); var chart = chart_space.chart; chart.setAutoTitleDeleted(false); if(b3D) { chart.setView3D(CreateView3d(30, 0, true, 100)); chart.setDefaultWalls(); } chart.setPlotArea(new AscFormat.CPlotArea()); var plot_area = chart.plotArea; plot_area.setLayout(new AscFormat.CLayout()); plot_area.addChart(bDoughnut ? new AscFormat.CDoughnutChart() : new AscFormat.CPieChart()); var pie_chart = plot_area.charts[0]; pie_chart.setVaryColors(true); var parsedHeaders = chartSeries.parsedHeaders; var bInCols; if(isRealObject(oOptions)) { bInCols = oOptions.inColumns === true; } else { bInCols = false; } for(var i = 0; i < asc_series.length; ++i) { var series = new AscFormat.CPieSeries(); series.setIdx(i); series.setOrder(i); series.setVal(new AscFormat.CYVal()); var val = series.val; FillValNum(series.val, asc_series[i].Val, bUseCache); if(parsedHeaders.bTop && !bInCols || bInCols && parsedHeaders.bLeft) { series.setCat(new AscFormat.CCat()); FillCatStr(series.cat, asc_series[i].Cat, bUseCache); } if((parsedHeaders.bLeft && !bInCols || bInCols && parsedHeaders.bTop) && asc_series[i].TxCache && typeof asc_series[i].TxCache.Formula === "string" && asc_series[i].TxCache.Formula.length > 0) { FillSeriesTx(series, asc_series[i].TxCache, bUseCache); } pie_chart.addSer(series); } pie_chart.setFirstSliceAng(0); if(bDoughnut) pie_chart.setHoleSize(50); chart.setLegend(new AscFormat.CLegend()); var legend = chart.legend; legend.setLegendPos(c_oAscChartLegendShowSettings.right); legend.setLayout(new AscFormat.CLayout()); legend.setOverlay(false); chart.setPlotVisOnly(true); chart.setDispBlanksAs(DISP_BLANKS_AS_GAP); chart.setShowDLblsOverMax(false); chart_space.setPrintSettings(new CPrintSettings()); var print_settings = chart_space.printSettings; print_settings.setHeaderFooter(new CHeaderFooterChart()); print_settings.setPageMargins(new CPageMarginsChart()); print_settings.setPageSetup(new CPageSetup()); var page_margins = print_settings.pageMargins; page_margins.setB(0.75); page_margins.setL(0.7); page_margins.setR(0.7); page_margins.setT(0.75); page_margins.setHeader(0.3); page_margins.setFooter(0.3); return chart_space; } function FillCatStr(oCat, oCatCache, bUseCache, bFillCache) { oCat.setStrRef(new AscFormat.CStrRef()); var str_ref = oCat.strRef; str_ref.setF(oCatCache.Formula); if(bUseCache) { str_ref.setStrCache(new AscFormat.CStrCache()); var str_cache = str_ref.strCache; var cat_num_cache = oCatCache.NumCache; str_cache.setPtCount(cat_num_cache.length); if(!(bFillCache === false)) { for(var j = 0; j < cat_num_cache.length; ++j) { var string_pt = new AscFormat.CStringPoint(); string_pt.setIdx(j); string_pt.setVal(cat_num_cache[j].val); str_cache.addPt(string_pt); } } } } function FillValNum(oVal, oValCache, bUseCache, bFillCache) { oVal.setNumRef(new AscFormat.CNumRef()); var num_ref = oVal.numRef; num_ref.setF(oValCache.Formula); if(bUseCache) { num_ref.setNumCache(new AscFormat.CNumLit()); var num_cache = num_ref.numCache; num_cache.setPtCount(oValCache.NumCache.length); if(!(bFillCache === false)) { for(var j = 0; j < oValCache.NumCache.length; ++j) { var pt = new AscFormat.CNumericPoint(); pt.setIdx(j); pt.setFormatCode(oValCache.NumCache[j].numFormatStr); pt.setVal(oValCache.NumCache[j].val); num_cache.addPt(pt); } } } } function FillSeriesTx(oSeries, oTxCache, bUseCache, bFillCache) { oSeries.setTx(new AscFormat.CTx()); var tx= oSeries.tx; tx.setStrRef(new AscFormat.CStrRef()); var str_ref = tx.strRef; str_ref.setF(oTxCache.Formula); if(bUseCache) { str_ref.setStrCache(new AscFormat.CStrCache()); var str_cache = str_ref.strCache; str_cache.setPtCount(1); if(!(bFillCache === false)) { str_cache.addPt(new AscFormat.CStringPoint()); var pt = str_cache.pts[0]; pt.setIdx(0); pt.setVal(oTxCache.Tx); } } } function CreateScatterChart(chartSeries, bUseCache, oOptions) { var asc_series = chartSeries.series; var chart_space = new CChartSpace(); chart_space.setDate1904(false); chart_space.setLang("en-US"); chart_space.setRoundedCorners(false); chart_space.setStyle(2); chart_space.setChart(new AscFormat.CChart()); var chart = chart_space.chart; chart.setAutoTitleDeleted(false); chart.setPlotArea(new AscFormat.CPlotArea()); var plot_area = chart.plotArea; plot_area.setLayout(new AscFormat.CLayout()); plot_area.addChart(new AscFormat.CScatterChart()); var scatter_chart = plot_area.charts[0]; scatter_chart.setScatterStyle(AscFormat.SCATTER_STYLE_MARKER); scatter_chart.setVaryColors(false); var bInCols; if(isRealObject(oOptions)) { bInCols = oOptions.inColumns === true; } else { bInCols = false; } var parsedHeaders = chartSeries.parsedHeaders; var cat_ax = new AscFormat.CValAx(); var val_ax = new AscFormat.CValAx(); cat_ax.setAxId(++Ax_Counter.GLOBAL_AX_ID_COUNTER); val_ax.setAxId(++Ax_Counter.GLOBAL_AX_ID_COUNTER); cat_ax.setCrossAx(val_ax); val_ax.setCrossAx(cat_ax); plot_area.addAxis(cat_ax); plot_area.addAxis(val_ax); var oXVal; var first_series = null; var start_index = 0; var minus = 0; if(parsedHeaders.bTop && !bInCols || bInCols && parsedHeaders.bLeft) { oXVal = new AscFormat.CXVal(); FillCatStr(oXVal, asc_series[0].xVal, bUseCache); } else { first_series = asc_series.length > 1 ? asc_series[0] : null; start_index = asc_series.length > 1 ? 1 : 0; minus = start_index === 1 ? 1 : 0; if(first_series) { oXVal = new AscFormat.CXVal(); FillValNum(oXVal, first_series.Val, bUseCache); } } for(var i = start_index; i < asc_series.length; ++i) { var series = new AscFormat.CScatterSeries(); series.setIdx(i - minus); series.setOrder(i - minus); if(oXVal) { series.setXVal(oXVal.createDuplicate()); } series.setYVal(new AscFormat.CYVal()); FillValNum(series.yVal, asc_series[i].Val, bUseCache); if((parsedHeaders.bLeft && !bInCols || bInCols && parsedHeaders.bTop) && asc_series[i].TxCache && typeof asc_series[i].TxCache.Formula === "string" && asc_series[i].TxCache.Formula.length > 0) { FillSeriesTx(series, asc_series[i].TxCache, bUseCache) } scatter_chart.addSer(series); } scatter_chart.addAxId(cat_ax); scatter_chart.addAxId(val_ax); cat_ax.setScaling(new AscFormat.CScaling()); cat_ax.setDelete(false); cat_ax.setAxPos(AscFormat.AX_POS_B); cat_ax.setMajorTickMark(c_oAscTickMark.TICK_MARK_OUT); cat_ax.setMinorTickMark(c_oAscTickMark.TICK_MARK_NONE); cat_ax.setTickLblPos(c_oAscTickLabelsPos.TICK_LABEL_POSITION_NEXT_TO); cat_ax.setCrosses(AscFormat.CROSSES_AUTO_ZERO); cat_ax.scaling.setOrientation(AscFormat.ORIENTATION_MIN_MAX); val_ax.setScaling(new AscFormat.CScaling()); val_ax.setDelete(false); val_ax.setAxPos(AscFormat.AX_POS_L); val_ax.setMajorGridlines(new AscFormat.CSpPr()); val_ax.setNumFmt(new AscFormat.CNumFmt()); val_ax.setMajorTickMark(c_oAscTickMark.TICK_MARK_OUT); val_ax.setMinorTickMark(c_oAscTickMark.TICK_MARK_NONE); val_ax.setTickLblPos(c_oAscTickLabelsPos.TICK_LABEL_POSITION_NEXT_TO); val_ax.setCrosses(AscFormat.CROSSES_AUTO_ZERO); val_ax.setCrossBetween(AscFormat.CROSS_BETWEEN_BETWEEN); var scaling = val_ax.scaling; scaling.setOrientation(AscFormat.ORIENTATION_MIN_MAX); var num_fmt = val_ax.numFmt; var format_code = GetNumFormatFromSeries(asc_series); num_fmt.setFormatCode(format_code); num_fmt.setSourceLinked(true); if(scatter_chart.series.length > 1) { chart.setLegend(new AscFormat.CLegend()); var legend = chart.legend; legend.setLegendPos(c_oAscChartLegendShowSettings.right); legend.setLayout(new AscFormat.CLayout()); legend.setOverlay(false); } chart_space.setPrintSettings(new CPrintSettings()); var print_settings = chart_space.printSettings; print_settings.setHeaderFooter(new CHeaderFooterChart()); print_settings.setPageMargins(new CPageMarginsChart()); print_settings.setPageSetup(new CPageSetup()); var page_margins = print_settings.pageMargins; page_margins.setB(0.75); page_margins.setL(0.7); page_margins.setR(0.7); page_margins.setT(0.75); page_margins.setHeader(0.3); page_margins.setFooter(0.3); return chart_space; } function CreateStockChart(chartSeries, bUseCache, oOptions) { var asc_series = chartSeries.series; var chart_space = new CChartSpace(); chart_space.setDate1904(false); chart_space.setLang("en-US"); chart_space.setRoundedCorners(false); chart_space.setChart(new AscFormat.CChart()); chart_space.setPrintSettings(new CPrintSettings()); var chart = chart_space.chart; chart.setAutoTitleDeleted(false); chart.setPlotArea(new AscFormat.CPlotArea()); chart.setLegend(new AscFormat.CLegend()); chart.setPlotVisOnly(true); var disp_blanks_as; disp_blanks_as = DISP_BLANKS_AS_GAP; chart.setDispBlanksAs(disp_blanks_as); chart.setShowDLblsOverMax(false); var plot_area = chart.plotArea; plot_area.setLayout(new AscFormat.CLayout()); plot_area.addChart(new AscFormat.CStockChart()); var bInCols; if(isRealObject(oOptions)) { bInCols = oOptions.inColumns === true; } else { bInCols = false; } var cat_ax = new AscFormat.CCatAx(); var val_ax = new AscFormat.CValAx(); cat_ax.setAxId(++Ax_Counter.GLOBAL_AX_ID_COUNTER); val_ax.setAxId(++Ax_Counter.GLOBAL_AX_ID_COUNTER); cat_ax.setCrossAx(val_ax); val_ax.setCrossAx(cat_ax); plot_area.addAxis(cat_ax); plot_area.addAxis(val_ax); var line_chart = plot_area.charts[0]; line_chart.addAxId(cat_ax); line_chart.addAxId(val_ax); line_chart.setHiLowLines(new AscFormat.CSpPr()); line_chart.setUpDownBars(new AscFormat.CUpDownBars()); line_chart.upDownBars.setGapWidth(150); line_chart.upDownBars.setUpBars(new AscFormat.CSpPr()); line_chart.upDownBars.setDownBars(new AscFormat.CSpPr()); var parsedHeaders = chartSeries.parsedHeaders; for(var i = 0; i < asc_series.length; ++i) { var series = new AscFormat.CLineSeries(); series.setIdx(i); series.setOrder(i); series.setMarker(new AscFormat.CMarker()); series.setSpPr(new AscFormat.CSpPr()); series.spPr.setLn(new AscFormat.CLn()); series.spPr.ln.setW(28575); series.spPr.ln.setFill(CreateNoFillUniFill()); series.marker.setSymbol(AscFormat.SYMBOL_NONE); series.setSmooth(false); series.setVal(new AscFormat.CYVal()); var val = series.val; FillValNum(val, asc_series[i].Val, bUseCache); if((parsedHeaders.bTop && !bInCols || bInCols && parsedHeaders.bLeft)) { series.setCat(new AscFormat.CCat()); var cat = series.cat; if(typeof asc_series[i].Cat.formatCode === "string" && asc_series[i].Cat.formatCode.length > 0) { cat.setNumRef(new AscFormat.CNumRef()); var num_ref = cat.numRef; num_ref.setF(asc_series[i].Cat.Formula); if(bUseCache) { num_ref.setNumCache(new AscFormat.CNumLit()); var num_cache = num_ref.numCache; var cat_num_cache = asc_series[i].Cat.NumCache; num_cache.setPtCount(cat_num_cache.length); num_cache.setFormatCode(asc_series[i].Cat.formatCode); for(var j= 0; j < cat_num_cache.length; ++j) { var pt = new AscFormat.CNumericPoint(); pt.setIdx(j); pt.setVal(cat_num_cache[j].val); if(cat_num_cache[j].numFormatStr !== asc_series[i].Cat.formatCode) { pt.setFormatCode(cat_num_cache[j].numFormatStr); } num_cache.addPt(pt); } } } else { FillCatStr(cat, asc_series[i].Cat, bUseCache); } } if((parsedHeaders.bLeft && !bInCols || bInCols && parsedHeaders.bTop) && asc_series[i].TxCache && typeof asc_series[i].TxCache.Formula === "string" && asc_series[i].TxCache.Formula.length > 0) { FillSeriesTx(series, asc_series[i].TxCache, bUseCache); } line_chart.addSer(series); } cat_ax.setScaling(new AscFormat.CScaling()); cat_ax.setDelete(false); cat_ax.setAxPos(AscFormat.AX_POS_B); cat_ax.setMajorTickMark(c_oAscTickMark.TICK_MARK_OUT); cat_ax.setMinorTickMark(c_oAscTickMark.TICK_MARK_OUT); cat_ax.setTickLblPos(c_oAscTickLabelsPos.TICK_LABEL_POSITION_NEXT_TO); cat_ax.setCrosses(AscFormat.CROSSES_AUTO_ZERO); cat_ax.setAuto(true); cat_ax.setLblAlgn(AscFormat.LBL_ALG_CTR); cat_ax.setLblOffset(100); cat_ax.setNoMultiLvlLbl(false); var scaling = cat_ax.scaling; scaling.setOrientation(AscFormat.ORIENTATION_MIN_MAX); val_ax.setScaling(new AscFormat.CScaling()); val_ax.setDelete(false); val_ax.setAxPos(AscFormat.AX_POS_L); val_ax.setMajorGridlines(new AscFormat.CSpPr()); val_ax.setNumFmt(new AscFormat.CNumFmt()); val_ax.setMajorTickMark(c_oAscTickMark.TICK_MARK_OUT); val_ax.setMinorTickMark(c_oAscTickMark.TICK_MARK_NONE); val_ax.setTickLblPos(c_oAscTickLabelsPos.TICK_LABEL_POSITION_NEXT_TO); val_ax.setCrosses(AscFormat.CROSSES_AUTO_ZERO); val_ax.setCrossBetween(AscFormat.CROSS_BETWEEN_BETWEEN); scaling = val_ax.scaling; scaling.setOrientation(AscFormat.ORIENTATION_MIN_MAX); var num_fmt = val_ax.numFmt; var format_code; format_code = GetNumFormatFromSeries(asc_series); num_fmt.setFormatCode(format_code); num_fmt.setSourceLinked(true); var legend = chart.legend; legend.setLegendPos(c_oAscChartLegendShowSettings.right); legend.setLayout(new AscFormat.CLayout()); legend.setOverlay(false); var print_settings = chart_space.printSettings; print_settings.setHeaderFooter(new CHeaderFooterChart()); print_settings.setPageMargins(new CPageMarginsChart()); print_settings.setPageSetup(new CPageSetup()); var page_margins = print_settings.pageMargins; page_margins.setB(0.75); page_margins.setL(0.7); page_margins.setR(0.7); page_margins.setT(0.75); page_margins.setHeader(0.3); page_margins.setFooter(0.3); return chart_space; } function CreateSurfaceChart(chartSeries, bUseCache, oOptions, bContour, bWireFrame){ var asc_series = chartSeries.series; var oChartSpace = new AscFormat.CChartSpace(); oChartSpace.setDate1904(false); oChartSpace.setLang("en-Us"); oChartSpace.setRoundedCorners(false); oChartSpace.setStyle(2); oChartSpace.setChart(new AscFormat.CChart()); var oChart = oChartSpace.chart; oChart.setAutoTitleDeleted(false); var oView3D = new AscFormat.CView3d(); oChart.setView3D(oView3D); if(!bContour){ oView3D.setRotX(15); oView3D.setRotY(20); oView3D.setRAngAx(false); oView3D.setPerspective(30); } else{ oView3D.setRotX(90); oView3D.setRotY(0); oView3D.setRAngAx(false); oView3D.setPerspective(0); } oChart.setFloor(new AscFormat.CChartWall()); oChart.floor.setThickness(0); oChart.setSideWall(new AscFormat.CChartWall()); oChart.sideWall.setThickness(0); oChart.setBackWall(new AscFormat.CChartWall()); oChart.backWall.setThickness(0); oChart.setPlotArea(new AscFormat.CPlotArea()); oChart.plotArea.setLayout(new AscFormat.CLayout()); var oSurfaceChart; //if(bContour){ oSurfaceChart = new AscFormat.CSurfaceChart(); //} if(bWireFrame){ oSurfaceChart.setWireframe(true); } else{ oSurfaceChart.setWireframe(false); } oChart.plotArea.addChart(oSurfaceChart); var bInCols; if(isRealObject(oOptions)) { bInCols = oOptions.inColumns === true; } else { bInCols = false; } var parsedHeaders = chartSeries.parsedHeaders; for(var i = 0; i < asc_series.length; ++i) { var series = new AscFormat.CSurfaceSeries(); series.setIdx(i); series.setOrder(i); series.setVal(new AscFormat.CYVal()); FillValNum(series.val, asc_series[i].Val, bUseCache); if(parsedHeaders.bTop && !bInCols || bInCols && parsedHeaders.bLeft) { series.setCat(new AscFormat.CCat()); FillCatStr(series.cat, asc_series[i].Cat, bUseCache); } if((parsedHeaders.bLeft && !bInCols || bInCols && parsedHeaders.bTop) && asc_series[i].TxCache && typeof asc_series[i].TxCache.Formula === "string" && asc_series[i].TxCache.Formula.length > 0) { FillSeriesTx(series, asc_series[i].TxCache, bUseCache); } oSurfaceChart.addSer(series); } var oCatAx = new AscFormat.CCatAx(); oCatAx.setAxId(++AscFormat.Ax_Counter.GLOBAL_AX_ID_COUNTER); var oScaling = new AscFormat.CScaling(); oScaling.setOrientation(AscFormat.ORIENTATION_MIN_MAX); oCatAx.setScaling(oScaling); oCatAx.setDelete(false); oCatAx.setAxPos(AscFormat.AX_POS_B); oCatAx.setMajorTickMark(c_oAscTickMark.TICK_MARK_OUT); oCatAx.setMinorTickMark(c_oAscTickMark.TICK_MARK_NONE); oCatAx.setTickLblPos(c_oAscTickLabelsPos.TICK_LABEL_POSITION_NEXT_TO); oCatAx.setCrosses(AscFormat.CROSSES_AUTO_ZERO); oCatAx.setAuto(true); oCatAx.setLblAlgn(AscFormat.LBL_ALG_CTR); oCatAx.setLblOffset(100); oCatAx.setNoMultiLvlLbl(false); var oValAx = new AscFormat.CValAx(); oValAx.setAxId(++AscFormat.Ax_Counter.GLOBAL_AX_ID_COUNTER); var oValScaling = new AscFormat.CScaling(); oValScaling.setOrientation(AscFormat.ORIENTATION_MIN_MAX); oValAx.setScaling(oValScaling); oValAx.setDelete(false); oValAx.setAxPos(AscFormat.AX_POS_L); oValAx.setMajorGridlines(new AscFormat.CSpPr()); var oNumFmt = new AscFormat.CNumFmt(); oNumFmt.setFormatCode(GetNumFormatFromSeries(asc_series)); oNumFmt.setSourceLinked(true); oValAx.setNumFmt(oNumFmt); oValAx.setMajorTickMark(c_oAscTickMark.TICK_MARK_OUT); oValAx.setMinorTickMark(c_oAscTickMark.TICK_MARK_NONE); oValAx.setTickLblPos(c_oAscTickLabelsPos.TICK_LABEL_POSITION_NEXT_TO); oCatAx.setCrossAx(oValAx); oValAx.setCrossAx(oCatAx); oValAx.setCrosses(AscFormat.CROSSES_AUTO_ZERO); oValAx.setCrossBetween(AscFormat.CROSS_BETWEEN_MID_CAT); var oSerAx = new AscFormat.CSerAx(); oSerAx.setAxId(++AscFormat.Ax_Counter.GLOBAL_AX_ID_COUNTER); var oSerScaling = new AscFormat.CScaling(); oSerScaling.setOrientation(AscFormat.ORIENTATION_MIN_MAX); oSerAx.setScaling(oSerScaling); oSerAx.setDelete(false); oSerAx.setAxPos(AscFormat.AX_POS_B); oSerAx.setMajorTickMark(c_oAscTickMark.TICK_MARK_OUT); oSerAx.setMinorTickMark(c_oAscTickMark.TICK_MARK_NONE); oSerAx.setTickLblPos(c_oAscTickLabelsPos.TICK_LABEL_POSITION_NEXT_TO); oSerAx.setCrossAx(oCatAx); oSerAx.setCrosses(AscFormat.CROSSES_AUTO_ZERO); oChart.plotArea.addAxis(oCatAx); oChart.plotArea.addAxis(oValAx); oChart.plotArea.addAxis(oSerAx); oSurfaceChart.addAxId(oCatAx); oSurfaceChart.addAxId(oValAx); oSurfaceChart.addAxId(oSerAx); var oLegend = new AscFormat.CLegend(); oLegend.setLegendPos(c_oAscChartLegendShowSettings.right); oLegend.setLayout(new AscFormat.CLayout()); oLegend.setOverlay(false); //oLegend.setTxPr(AscFormat.CreateTextBodyFromString("", oDrawingDocument, oElement)); oChart.setLegend(oLegend); oChart.setPlotVisOnly(true); oChart.setDispBlanksAs(DISP_BLANKS_AS_ZERO); oChart.setShowDLblsOverMax(false); var oPrintSettings = new AscFormat.CPrintSettings(); oPrintSettings.setHeaderFooter(new AscFormat.CHeaderFooterChart()); var oPageMargins = new AscFormat.CPageMarginsChart(); oPageMargins.setB(0.75); oPageMargins.setL(0.7); oPageMargins.setR(0.7); oPageMargins.setT(0.75); oPageMargins.setHeader(0.3); oPageMargins.setFooter(0.3); oPrintSettings.setPageMargins(oPageMargins); oPrintSettings.setPageSetup(new AscFormat.CPageSetup()); oChartSpace.setPrintSettings(oPrintSettings); return oChartSpace; } function CreateDefaultAxises(valFormatCode) { var cat_ax = new AscFormat.CCatAx(); var val_ax = new AscFormat.CValAx(); cat_ax.setAxId(++Ax_Counter.GLOBAL_AX_ID_COUNTER); val_ax.setAxId(++Ax_Counter.GLOBAL_AX_ID_COUNTER); cat_ax.setCrossAx(val_ax); val_ax.setCrossAx(cat_ax); cat_ax.setScaling(new AscFormat.CScaling()); cat_ax.setDelete(false); cat_ax.setAxPos(AscFormat.AX_POS_B); cat_ax.setMajorTickMark(c_oAscTickMark.TICK_MARK_OUT); cat_ax.setMinorTickMark(c_oAscTickMark.TICK_MARK_NONE); cat_ax.setCrosses(AscFormat.CROSSES_AUTO_ZERO); cat_ax.setAuto(true); cat_ax.setLblAlgn(AscFormat.LBL_ALG_CTR); cat_ax.setLblOffset(100); cat_ax.setNoMultiLvlLbl(false); var scaling = cat_ax.scaling; scaling.setOrientation(AscFormat.ORIENTATION_MIN_MAX); val_ax.setScaling(new AscFormat.CScaling()); val_ax.setDelete(false); val_ax.setAxPos(AscFormat.AX_POS_L); val_ax.setMajorGridlines(new AscFormat.CSpPr()); val_ax.setNumFmt(new AscFormat.CNumFmt()); var num_fmt = val_ax.numFmt; num_fmt.setFormatCode(valFormatCode); num_fmt.setSourceLinked(true); val_ax.setMajorTickMark(c_oAscTickMark.TICK_MARK_OUT); val_ax.setMinorTickMark(c_oAscTickMark.TICK_MARK_NONE); val_ax.setTickLblPos(c_oAscTickLabelsPos.TICK_LABEL_POSITION_NEXT_TO); val_ax.setCrosses(AscFormat.CROSSES_AUTO_ZERO); val_ax.setCrossBetween(AscFormat.CROSS_BETWEEN_BETWEEN); scaling = val_ax.scaling; scaling.setOrientation(AscFormat.ORIENTATION_MIN_MAX); //cat_ax.setTitle(new CTitle()); //val_ax.setTitle(new CTitle()); // var title = val_ax.title; // title.setTxPr(new CTextBody()); // title.txPr.setBodyPr(new AscFormat.CBodyPr()); // title.txPr.bodyPr.setVert(AscFormat.nVertTTvert); return {valAx: val_ax, catAx: cat_ax}; } function CreateScatterAxis() { var cat_ax = new AscFormat.CValAx(); var val_ax = new AscFormat.CValAx(); cat_ax.setAxId(++Ax_Counter.GLOBAL_AX_ID_COUNTER); val_ax.setAxId(++Ax_Counter.GLOBAL_AX_ID_COUNTER); cat_ax.setCrossAx(val_ax); val_ax.setCrossAx(cat_ax); cat_ax.setScaling(new AscFormat.CScaling()); cat_ax.setDelete(false); cat_ax.setAxPos(AscFormat.AX_POS_B); cat_ax.setMajorTickMark(c_oAscTickMark.TICK_MARK_OUT); cat_ax.setMinorTickMark(c_oAscTickMark.TICK_MARK_NONE); cat_ax.setTickLblPos(c_oAscTickLabelsPos.TICK_LABEL_POSITION_NEXT_TO); cat_ax.setCrosses(AscFormat.CROSSES_AUTO_ZERO); cat_ax.scaling.setOrientation(AscFormat.ORIENTATION_MIN_MAX); val_ax.setScaling(new AscFormat.CScaling()); val_ax.setDelete(false); val_ax.setAxPos(AscFormat.AX_POS_L); val_ax.setMajorGridlines(new AscFormat.CSpPr()); val_ax.setNumFmt(new AscFormat.CNumFmt()); val_ax.setMajorTickMark(c_oAscTickMark.TICK_MARK_OUT); val_ax.setMinorTickMark(c_oAscTickMark.TICK_MARK_NONE); val_ax.setTickLblPos(c_oAscTickLabelsPos.TICK_LABEL_POSITION_NEXT_TO); val_ax.setCrosses(AscFormat.CROSSES_AUTO_ZERO); val_ax.setCrossBetween(AscFormat.CROSS_BETWEEN_BETWEEN); var scaling = val_ax.scaling; scaling.setOrientation(AscFormat.ORIENTATION_MIN_MAX); var num_fmt = val_ax.numFmt; var format_code = "General"; num_fmt.setFormatCode(format_code); num_fmt.setSourceLinked(true); return {valAx: val_ax, catAx: cat_ax}; } function fCheckNumFormatType(numFormatType){ return (numFormatType === c_oAscNumFormatType.Time || numFormatType === c_oAscNumFormatType.Date || numFormatType === c_oAscNumFormatType.Percent) } function parseSeriesHeaders (ws, rangeBBox) { var cntLeft = 0, cntTop = 0; var headers = { bLeft: false, bTop: false }; var i, cell, value, numFormatType, j; var bLeftOnlyDateTime = true, bTopOnlyDateTime = true; var nStartIndex; if (rangeBBox) { if (rangeBBox.c2 - rangeBBox.c1 > 0) { var nStartIndex = (rangeBBox.r1 === rangeBBox.r2) ? rangeBBox.r1 : (rangeBBox.r1 + 1); for (i = nStartIndex; i <= rangeBBox.r2; i++) { cell = ws.getCell3(i, rangeBBox.c1); value = cell.getValue(); numFormatType = cell.getNumFormatType(); if(!AscCommon.isNumber(value) && (value != "")) { bLeftOnlyDateTime = false; headers.bLeft = true; } else if(fCheckNumFormatType(numFormatType)) { headers.bLeft = true; } } } if (rangeBBox.r2 - rangeBBox.r1 > 0) { var nStartIndex = (rangeBBox.c1 === rangeBBox.c2) ? rangeBBox.c1 : (rangeBBox.c1 + 1); for (i = nStartIndex; i <= rangeBBox.c2; i++) { cell = ws.getCell3(rangeBBox.r1, i); value = cell.getValue(); numFormatType= cell.getNumFormatType(); if(!AscCommon.isNumber(value) && value != "") { bTopOnlyDateTime = false; headers.bTop = true; } else if(fCheckNumFormatType(numFormatType) ) { headers.bTop = true; } } } if(headers.bTop || headers.bLeft) { var nRowStart = headers.bTop ? rangeBBox.r1 + 1 : rangeBBox.r1, nColStart = headers.bLeft ? rangeBBox.c1 + 1 : rangeBBox.c1; for(i = nRowStart; i <= rangeBBox.r2; ++i) { for(j = nColStart; j <= rangeBBox.c2; ++j) { cell = ws.getCell3(i, j); value = cell.getValue(); numFormatType= cell.getNumFormatType(); if (!fCheckNumFormatType(numFormatType) && value !== "") { break; } } if(j <= rangeBBox.c2) { break; } } if(i === rangeBBox.r2 + 1) { if(headers.bLeft && bLeftOnlyDateTime) { headers.bLeft = false; } if(headers.bTop && bTopOnlyDateTime) { headers.bTop = false; } } } } else headers = { bLeft: true, bTop: true }; return headers; } function getChartSeries (worksheet, options, catHeadersBBox, serHeadersBBox) { var api = window["Asc"]["editor"]; var ws = null; var range = null; var result = parserHelp.parse3DRef(options.range); if (null !== result) { ws = worksheet.workbook.getWorksheetByName(result.sheet); if (ws) range = ws.getRange2(result.range); } if (null === range) return null; var bbox = range.getBBox0(); var nameIndex = 1; var i, series = []; function getNumCache(c1, c2, r1, r2) { // (c1 == c2) || (r1 == r2) var cache = [], cell, item; if ( c1 == c2 ) { // vertical cache for (var row = r1; row <= r2; row++) { cell = ws.getCell3(row, c1); item = {}; item.numFormatStr = cell.getNumFormatStr(); item.isDateTimeFormat = cell.getNumFormat().isDateTimeFormat(); item.val = cell.getValue(); item.isHidden = ws.getColHidden(c1) || ws.getRowHidden(row); cache.push(item); } } else /*r1 == r2*/ { // horizontal cache for (var col = c1; col <= c2; col++) { cell = ws.getCell3(r1, col, 0); item = {}; item.numFormatStr = cell.getNumFormatStr(); item.isDateTimeFormat = cell.getNumFormat().isDateTimeFormat(); item.val = cell.getValue(); item.isHidden = ws.getColHidden(col) || ws.getRowHidden(r1); cache.push(item); } } return cache; } var parsedHeaders = parseSeriesHeaders(ws, bbox); var data_bbox = {r1: bbox.r1, r2: bbox.r2, c1: bbox.c1, c2: bbox.c2}; if(parsedHeaders.bTop) { ++data_bbox.r1; } else { if(!options.getInColumns()) { if(catHeadersBBox && catHeadersBBox.c1 === data_bbox.c1 && catHeadersBBox.c2 === data_bbox.c2 && catHeadersBBox.r1 === catHeadersBBox.r2 && catHeadersBBox.r1 === data_bbox.r1) { ++data_bbox.r1; } } else { if(serHeadersBBox && serHeadersBBox.c1 === data_bbox.c1 && serHeadersBBox.c2 === data_bbox.c2 && serHeadersBBox.r1 === serHeadersBBox.r2 && serHeadersBBox.r1 === data_bbox.r1) { ++data_bbox.r1; } } } if(parsedHeaders.bLeft) { ++data_bbox.c1; } else { if(!options.getInColumns()) { if(serHeadersBBox && serHeadersBBox.c1 === serHeadersBBox.c2 && serHeadersBBox.r1 === data_bbox.r1 && serHeadersBBox.r2 === data_bbox.r2 && serHeadersBBox.c1 === data_bbox.c1) { ++data_bbox.c1; } } else { if(catHeadersBBox && catHeadersBBox.c1 === catHeadersBBox.c2 && catHeadersBBox.r1 === data_bbox.r1 && catHeadersBBox.r2 === data_bbox.r2 && catHeadersBBox.c1 === data_bbox.c1) { ++data_bbox.c1; } } } var bIsScatter = (Asc.c_oAscChartTypeSettings.scatter <= options.type && options.type <= Asc.c_oAscChartTypeSettings.scatterSmoothMarker); var top_header_bbox, left_header_bbox, ser, startCell, endCell, formulaCell, start, end, formula, numCache, sStartCellId, sEndCellId; if (!options.getInColumns()) { if(parsedHeaders.bTop) top_header_bbox = {r1: bbox.r1, c1: data_bbox.c1, r2: bbox.r1, c2: data_bbox.c2}; else if(catHeadersBBox && catHeadersBBox.c1 === data_bbox.c1 && catHeadersBBox.c2 === data_bbox.c2 && catHeadersBBox.r1 === catHeadersBBox.r2) top_header_bbox = {r1: catHeadersBBox.r1, c1: catHeadersBBox.c1, r2: catHeadersBBox.r1, c2:catHeadersBBox.c2}; if(parsedHeaders.bLeft) left_header_bbox = {r1: data_bbox.r1, r2: data_bbox.r2, c1: bbox.c1, c2: bbox.c1}; else if(serHeadersBBox && serHeadersBBox.c1 === serHeadersBBox.c2 && serHeadersBBox.r1 === data_bbox.r1 && serHeadersBBox.r2 === data_bbox.r2) left_header_bbox = {r1: serHeadersBBox.r1, c1: serHeadersBBox.c1, r2: serHeadersBBox.r1, c2: serHeadersBBox.c2}; for (i = data_bbox.r1; i <= data_bbox.r2; ++i) { ser = new AscFormat.asc_CChartSeria(); startCell = new CellAddress(i, data_bbox.c1, 0); endCell = new CellAddress(i, data_bbox.c2, 0); ser.isHidden = !!ws.getRowHidden(i); // Val sStartCellId = startCell.getIDAbsolute(); sEndCellId = endCell.getIDAbsolute(); ser.Val.Formula = parserHelp.get3DRef(ws.sName, sStartCellId === sEndCellId ? sStartCellId : sStartCellId + ':' + sEndCellId); ser.Val.NumCache = getNumCache(data_bbox.c1, data_bbox.c2, i, i); if(left_header_bbox) { formulaCell = new CellAddress( i, left_header_bbox.c1, 0 ); ser.TxCache.Formula = parserHelp.get3DRef(ws.sName, formulaCell.getIDAbsolute()); } // xVal if(top_header_bbox) { start = new CellAddress(top_header_bbox.r1, top_header_bbox.c1, 0); end = new CellAddress(top_header_bbox.r1, top_header_bbox.c2, 0); formula = parserHelp.get3DRef(ws.sName, start.getIDAbsolute() + ':' + end.getIDAbsolute()); numCache = getNumCache(top_header_bbox.c1, top_header_bbox.c2, top_header_bbox.r1, top_header_bbox.r1 ); if (bIsScatter) { ser.xVal.Formula = formula; ser.xVal.NumCache = numCache; } else { ser.Cat.Formula = formula; ser.Cat.NumCache = numCache; } } ser.TxCache.Tx = left_header_bbox ? (ws.getCell3(i, left_header_bbox.c1).getValue()) : (AscCommon.translateManager.getValue('Series') + " " + nameIndex); series.push(ser); nameIndex++; } } else { if(parsedHeaders.bTop) top_header_bbox = {r1: bbox.r1, c1: data_bbox.c1, r2: bbox.r1, c2: data_bbox.c2}; else if(serHeadersBBox && serHeadersBBox.r1 === serHeadersBBox.r2 && serHeadersBBox.c1 === data_bbox.c1 && serHeadersBBox.c2 === data_bbox.c2) top_header_bbox = {r1: serHeadersBBox.r1, c1: serHeadersBBox.c1, r2: serHeadersBBox.r2, c2: serHeadersBBox.c2}; if(parsedHeaders.bLeft) left_header_bbox = {r1: data_bbox.r1, c1: bbox.c1, r2: data_bbox.r2, c2: bbox.c1}; else if(catHeadersBBox && catHeadersBBox.c1 === catHeadersBBox.c2 && catHeadersBBox.r1 === data_bbox.r1 && catHeadersBBox.r2 === data_bbox.r2) left_header_bbox = {r1: catHeadersBBox.r1, c1: catHeadersBBox.c1, r2: catHeadersBBox.r2, c2: catHeadersBBox.c2}; for (i = data_bbox.c1; i <= data_bbox.c2; i++) { ser = new AscFormat.asc_CChartSeria(); startCell = new CellAddress(data_bbox.r1, i, 0); endCell = new CellAddress(data_bbox.r2, i, 0); ser.isHidden = !!ws.getColHidden(i); // Val sStartCellId = startCell.getIDAbsolute(); sEndCellId = endCell.getIDAbsolute(); if (sStartCellId == sEndCellId) ser.Val.Formula = parserHelp.get3DRef(ws.sName, sStartCellId); else ser.Val.Formula = parserHelp.get3DRef(ws.sName, sStartCellId + ':' + sEndCellId); ser.Val.NumCache = getNumCache(i, i, data_bbox.r1, bbox.r2); if ( left_header_bbox ) { start = new CellAddress(left_header_bbox.r1, left_header_bbox.c1, 0); end = new CellAddress(left_header_bbox.r2, left_header_bbox.c1, 0); formula = parserHelp.get3DRef(ws.sName, start.getIDAbsolute() + ':' + end.getIDAbsolute()); numCache = getNumCache( left_header_bbox.c1, left_header_bbox.c1, left_header_bbox.r1, left_header_bbox.r2 ); if (bIsScatter) { ser.xVal.Formula = formula; ser.xVal.NumCache = numCache; } else { ser.Cat.Formula = formula; ser.Cat.NumCache = numCache; } } if (top_header_bbox) { formulaCell = new CellAddress( top_header_bbox.r1, i, 0 ); ser.TxCache.Formula = parserHelp.get3DRef(ws.sName, formulaCell.getIDAbsolute()); } ser.TxCache.Tx = top_header_bbox ? (ws.getCell3(top_header_bbox.r1, i).getValue()) : (AscCommon.translateManager.getValue('Series') + " " + nameIndex); series.push(ser); nameIndex++; } } return {series: series, parsedHeaders: parsedHeaders}; } function checkSpPrRasterImages(spPr) { if(spPr && spPr.Fill && spPr.Fill && spPr.Fill.fill && spPr.Fill.fill.type === Asc.c_oAscFill.FILL_TYPE_BLIP) { var copyBlipFill = spPr.Fill.createDuplicate(); copyBlipFill.fill.setRasterImageId(spPr.Fill.fill.RasterImageId); spPr.setFill(copyBlipFill); } } function checkBlipFillRasterImages(sp) { switch (sp.getObjectType()) { case AscDFH.historyitem_type_Shape: { checkSpPrRasterImages(sp.spPr); break; } case AscDFH.historyitem_type_ImageShape: case AscDFH.historyitem_type_OleObject: { if(sp.blipFill) { var newBlipFill = sp.blipFill.createDuplicate(); newBlipFill.setRasterImageId(sp.blipFill.RasterImageId); sp.setBlipFill(newBlipFill); } break; } case AscDFH.historyitem_type_ChartSpace: { checkSpPrRasterImages(sp.spPr); var chart = sp.chart; if(chart) { chart.backWall && checkSpPrRasterImages(chart.backWall.spPr); chart.floor && checkSpPrRasterImages(chart.floor.spPr); chart.legend && checkSpPrRasterImages(chart.legend.spPr); chart.sideWall && checkSpPrRasterImages(chart.sideWall.spPr); chart.title && checkSpPrRasterImages(chart.title.spPr); //plotArea var plot_area = sp.chart.plotArea; if(plot_area) { checkSpPrRasterImages(plot_area.spPr); for(var j = 0; j < plot_area.axId.length; ++j) { var axis = plot_area.axId[j]; if(axis) { checkSpPrRasterImages(axis.spPr); axis.title && axis.title && checkSpPrRasterImages(axis.title.spPr); } } for(j = 0; j < plot_area.charts.length; ++j) { plot_area.charts[j].checkSpPrRasterImages(); } } } break; } case AscDFH.historyitem_type_GroupShape: { for(var i = 0; i < sp.spTree.length; ++i) { checkBlipFillRasterImages(sp.spTree[i]); } break; } case AscDFH.historyitem_type_GraphicFrame: { break; } } } function initStyleManager() { CHART_STYLE_MANAGER.init(); } //--------------------------------------------------------export---------------------------------------------------- window['AscFormat'] = window['AscFormat'] || {}; window['AscFormat'].BAR_SHAPE_CONE = BAR_SHAPE_CONE; window['AscFormat'].BAR_SHAPE_CONETOMAX = BAR_SHAPE_CONETOMAX; window['AscFormat'].BAR_SHAPE_BOX = BAR_SHAPE_BOX; window['AscFormat'].BAR_SHAPE_CYLINDER = BAR_SHAPE_CYLINDER; window['AscFormat'].BAR_SHAPE_PYRAMID = BAR_SHAPE_PYRAMID; window['AscFormat'].BAR_SHAPE_PYRAMIDTOMAX = BAR_SHAPE_PYRAMIDTOMAX; window['AscFormat'].DISP_BLANKS_AS_GAP = DISP_BLANKS_AS_GAP; window['AscFormat'].DISP_BLANKS_AS_SPAN = DISP_BLANKS_AS_SPAN; window['AscFormat'].DISP_BLANKS_AS_ZERO = DISP_BLANKS_AS_ZERO; window['AscFormat'].checkBlackUnifill = checkBlackUnifill; window['AscFormat'].BBoxInfo = BBoxInfo; window['AscFormat'].CreateUnifillSolidFillSchemeColorByIndex = CreateUnifillSolidFillSchemeColorByIndex; window['AscFormat'].CreateUniFillSchemeColorWidthTint = CreateUniFillSchemeColorWidthTint; window['AscFormat'].G_O_VISITED_HLINK_COLOR = G_O_VISITED_HLINK_COLOR; window['AscFormat'].G_O_HLINK_COLOR = G_O_HLINK_COLOR; window['AscFormat'].G_O_NO_ACTIVE_COMMENT_BRUSH = G_O_NO_ACTIVE_COMMENT_BRUSH; window['AscFormat'].G_O_ACTIVE_COMMENT_BRUSH = G_O_ACTIVE_COMMENT_BRUSH; window['AscFormat'].CChartSpace = CChartSpace; window['AscFormat'].getPtsFromSeries = getPtsFromSeries; window['AscFormat'].CreateUnfilFromRGB = CreateUnfilFromRGB; window['AscFormat'].CreateUniFillSolidFillWidthTintOrShade = CreateUniFillSolidFillWidthTintOrShade; window['AscFormat'].CreateUnifillSolidFillSchemeColor = CreateUnifillSolidFillSchemeColor; window['AscFormat'].CreateNoFillLine = CreateNoFillLine; window['AscFormat'].CreateNoFillUniFill = CreateNoFillUniFill; window['AscFormat'].CExternalData = CExternalData; window['AscFormat'].CPivotSource = CPivotSource; window['AscFormat'].CProtection = CProtection; window['AscFormat'].CPrintSettings = CPrintSettings; window['AscFormat'].CHeaderFooterChart = CHeaderFooterChart; window['AscFormat'].CPageMarginsChart = CPageMarginsChart; window['AscFormat'].CPageSetup = CPageSetup; window['AscFormat'].CreateView3d = CreateView3d; window['AscFormat'].CreateLineChart = CreateLineChart; window['AscFormat'].CreateBarChart = CreateBarChart; window['AscFormat'].CreateHBarChart = CreateHBarChart; window['AscFormat'].CreateAreaChart = CreateAreaChart; window['AscFormat'].CreatePieChart = CreatePieChart; window['AscFormat'].CreateScatterChart = CreateScatterChart; window['AscFormat'].CreateStockChart = CreateStockChart; window['AscFormat'].CreateDefaultAxises = CreateDefaultAxises; window['AscFormat'].CreateScatterAxis = CreateScatterAxis; window['AscFormat'].getChartSeries = getChartSeries; window['AscFormat'].checkSpPrRasterImages = checkSpPrRasterImages; window['AscFormat'].checkBlipFillRasterImages = checkBlipFillRasterImages; window['AscFormat'].PAGE_SETUP_ORIENTATION_DEFAULT = 0; window['AscFormat'].PAGE_SETUP_ORIENTATION_LANDSCAPE = 1; window['AscFormat'].PAGE_SETUP_ORIENTATION_PORTRAIT = 2; window['AscFormat'].initStyleManager = initStyleManager; window['AscFormat'].CHART_STYLE_MANAGER = CHART_STYLE_MANAGER; window['AscFormat'].CheckParagraphTextPr = CheckParagraphTextPr; window['AscFormat'].CheckObjectTextPr = CheckObjectTextPr; window['AscFormat'].CreateColorMapByIndex = CreateColorMapByIndex; window['AscFormat'].getArrayFillsFromBase = getArrayFillsFromBase; window['AscFormat'].getMaxIdx = getMaxIdx; window['AscFormat'].CreateSurfaceChart = CreateSurfaceChart; })(window);
common/Drawings/Format/ChartSpace.js
/* * (c) Copyright Ascensio System SIA 2010-2018 * * This program is a free software product. You can redistribute it and/or * modify it under the terms of the GNU Affero General Public License (AGPL) * version 3 as published by the Free Software Foundation. In accordance with * Section 7(a) of the GNU AGPL its Section 15 shall be amended to the effect * that Ascensio System SIA expressly excludes the warranty of non-infringement * of any third-party rights. * * This program is distributed WITHOUT ANY WARRANTY; without even the implied * warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. For * details, see the GNU AGPL at: http://www.gnu.org/licenses/agpl-3.0.html * * You can contact Ascensio System SIA at Lubanas st. 125a-25, Riga, Latvia, * EU, LV-1021. * * The interactive user interfaces in modified source and object code versions * of the Program must display Appropriate Legal Notices, as required under * Section 5 of the GNU AGPL version 3. * * Pursuant to Section 7(b) of the License you must retain the original Product * logo when distributing the program. Pursuant to Section 7(e) we decline to * grant you any rights under trademark law for use of our trademarks. * * All the Product's GUI elements, including illustrations and icon sets, as * well as technical writing content are licensed under the terms of the * Creative Commons Attribution-ShareAlike 4.0 International. See the License * terms at http://creativecommons.org/licenses/by-sa/4.0/legalcode * */ "use strict"; var GLOBAL_PATH_COUNT = 0; ( /** * @param {Window} window * @param {undefined} undefined */ function (window, undefined) { var MAX_LABELS_COUNT = 300; // Import var oNonSpaceRegExp = new RegExp('' + String.fromCharCode(0x00A0),'g'); var c_oAscChartType = AscCommon.c_oAscChartType; var c_oAscChartSubType = AscCommon.c_oAscChartSubType; var parserHelp = AscCommon.parserHelp; var g_oIdCounter = AscCommon.g_oIdCounter; var g_oTableId = AscCommon.g_oTableId; var oNumFormatCache = AscCommon.oNumFormatCache; var CellAddress = AscCommon.CellAddress; var isRealObject = AscCommon.isRealObject; var History = AscCommon.History; var global_MatrixTransformer = AscCommon.global_MatrixTransformer; var CShape = AscFormat.CShape; var Ax_Counter = AscFormat.Ax_Counter; var checkTxBodyDefFonts = AscFormat.checkTxBodyDefFonts; var c_oAscNumFormatType = Asc.c_oAscNumFormatType; var c_oAscTickLabelsPos = Asc.c_oAscTickLabelsPos; var c_oAscChartLegendShowSettings = Asc.c_oAscChartLegendShowSettings; var c_oAscTickMark = Asc.c_oAscTickMark; var EFFECT_NONE = 0; var EFFECT_SUBTLE = 1; var EFFECT_MODERATE = 2; var EFFECT_INTENSE = 3; var CHART_STYLE_MANAGER = null; var SKIP_LBL_LIMIT = 100; var BAR_SHAPE_CONE = 0; var BAR_SHAPE_CONETOMAX = 1; var BAR_SHAPE_BOX = 2; var BAR_SHAPE_CYLINDER = 3; var BAR_SHAPE_PYRAMID = 4; var BAR_SHAPE_PYRAMIDTOMAX = 5; var DISP_BLANKS_AS_GAP = 0; var DISP_BLANKS_AS_SPAN = 1; var DISP_BLANKS_AS_ZERO = 2; function removePtsFromLit(lit) { var i; var start_idx = Array.isArray(lit.pts) ? lit.pts.length - 1 : -1; for(i = start_idx; i > -1; --i) { lit.removeDPt(i); } } function removeAllSeriesFromChart(chart) { for(var i = chart.series.length-1; i > -1; --i) chart.removeSeries(i); } function checkVerticalTitle(title) { return false; } function GetTextPrFormArrObjects(aObjects, bFirstBreak, bLbl) { var oResultTextPr; for(var i = 0; i < aObjects.length; ++i) { var oContent = aObjects[i]; oContent = bLbl ? oContent.compiledDlb && oContent.compiledDlb.txBody && oContent.compiledDlb.txBody.content : oContent.txBody && oContent.txBody.content; if(!oContent) continue; oContent.Set_ApplyToAll(true); var oTextPr = oContent.GetCalculatedTextPr(); oContent.Set_ApplyToAll(false); if(!oResultTextPr) { oResultTextPr = oTextPr; if(bFirstBreak) { return oResultTextPr; } } else { oResultTextPr.Compare(oTextPr); } } return oResultTextPr; } function checkBlackUnifill(unifill, bLines) { if(unifill && unifill.fill && unifill.fill.color) { var RGBA = unifill.fill.color.RGBA; if(RGBA.R === 0 && RGBA.G === 0 && RGBA.B === 0) { if(bLines) { RGBA.R = 134; RGBA.G = 134; RGBA.B = 134; } else { RGBA.R = 255; RGBA.G = 255; RGBA.B = 255; } } } } function CRect(x, y, w, h){ this.x = x; this.y = y; this.w = w; this.h = h; this.fHorPadding = 0.0; this.fVertPadding = 0.0; } CRect.prototype.copy = function(){ var ret = new CRect(this.x, this.y, this.w, this.h); ret.fHorPadding = this.fHorPadding; ret.fVertPadding = this.fVertPadding; return ret; }; CRect.prototype.intersection = function(oRect){ if(this.x + this.w < oRect.x || oRect.x + oRect.w < this.x || this.y + this.h < oRect.y || oRect.y + oRect.h < this.y){ return false; } var x0, y0, x1, y1; var bResetHorPadding = true, bResetVertPadding = true; if(this.fHorPadding > 0.0 && oRect.fHorPadding > 0.0){ x0 = this.x + oRect.fHorPadding; bResetHorPadding = false; } else{ x0 = Math.max(this.x, oRect.x); } if(this.fVertPadding > 0.0 && oRect.fVertPadding > 0.0){ y0 = this.y + oRect.fVertPadding; bResetVertPadding = false; } else{ y0 = Math.max(this.y, oRect.y); } if(this.fHorPadding < 0.0 && oRect.fHorPadding < 0.0){ x1 = this.x + this.w + oRect.fHorPadding; bResetHorPadding = false; } else{ x1 = Math.min(this.x + this.w, oRect.x + oRect.w); } if(this.fVertPadding < 0.0 && this.fVertPadding < 0.0){ y1 = this.y + this.h + oRect.fVertPadding; bResetVertPadding = false; } else{ y1 = Math.min(this.y + this.h, oRect.y + oRect.h); } if(bResetHorPadding){ this.fHorPadding = 0.0; } if(bResetVertPadding){ this.fVertPadding = 0.0; } this.x = x0; this.y = y0; this.w = x1 - x0; this.h = y1 - y0; return true; }; function BBoxInfo(worksheet, bbox) { this.worksheet = worksheet; if(window["Asc"] && typeof window["Asc"].Range === "function") { this.bbox = window["Asc"].Range(bbox.c1, bbox.r1, bbox.c2, bbox.r2, false); } else { this.bbox = bbox; } } BBoxInfo.prototype = { checkIntersection: function(bboxInfo) { if(this.worksheet !== bboxInfo.worksheet) { return false; } return this.bbox.isIntersect(bboxInfo.bbox); } }; function CreateUnifillSolidFillSchemeColorByIndex(index) { var ret = new AscFormat.CUniFill(); ret.setFill(new AscFormat.CSolidFill()); ret.fill.setColor(new AscFormat.CUniColor()); ret.fill.color.setColor(new AscFormat.CSchemeColor()); ret.fill.color.color.setId(index); return ret; } function CChartStyleManager() { this.styles = []; } CChartStyleManager.prototype = { init: function() { AscFormat.ExecuteNoHistory( function() { var DefaultDataPointPerDataPoint = [ [ CreateUniFillSchemeColorWidthTint(8, 0.885), CreateUniFillSchemeColorWidthTint(8, 0.55), CreateUniFillSchemeColorWidthTint(8, 0.78), CreateUniFillSchemeColorWidthTint(8, 0.925), CreateUniFillSchemeColorWidthTint(8, 0.7), CreateUniFillSchemeColorWidthTint(8, 0.3) ], [ CreateUniFillSchemeColorWidthTint(0, 0), CreateUniFillSchemeColorWidthTint(1, 0), CreateUniFillSchemeColorWidthTint(2, 0), CreateUniFillSchemeColorWidthTint(3, 0), CreateUniFillSchemeColorWidthTint(4, 0), CreateUniFillSchemeColorWidthTint(5, 0) ], [ CreateUniFillSchemeColorWidthTint(0, -0.5), CreateUniFillSchemeColorWidthTint(1, -0.5), CreateUniFillSchemeColorWidthTint(2, -0.5), CreateUniFillSchemeColorWidthTint(3, -0.5), CreateUniFillSchemeColorWidthTint(4, -0.5), CreateUniFillSchemeColorWidthTint(5, -0.5) ], [ CreateUniFillSchemeColorWidthTint(8, 0.05), CreateUniFillSchemeColorWidthTint(8, 0.55), CreateUniFillSchemeColorWidthTint(8, 0.78), CreateUniFillSchemeColorWidthTint(8, 0.15), CreateUniFillSchemeColorWidthTint(8, 0.7), CreateUniFillSchemeColorWidthTint(8, 0.3) ] ]; var s = DefaultDataPointPerDataPoint; var f = CreateUniFillSchemeColorWidthTint; this.styles[0] = new CChartStyle(EFFECT_NONE, EFFECT_SUBTLE, s[0], EFFECT_SUBTLE, EFFECT_NONE, [], 3, s[0], 7); this.styles[1] = new CChartStyle(EFFECT_NONE, EFFECT_SUBTLE, s[1], EFFECT_SUBTLE, EFFECT_NONE, [], 3, s[1], 7); for(var i = 2; i < 8; ++i) { this.styles[i] = new CChartStyle(EFFECT_NONE, EFFECT_SUBTLE, [f(i - 2,0)], EFFECT_SUBTLE, EFFECT_NONE, [], 3, [f(i - 2,0)], 7); } this.styles[8] = new CChartStyle(EFFECT_SUBTLE, EFFECT_SUBTLE, s[0], EFFECT_SUBTLE, EFFECT_SUBTLE, [f(12,0)], 5, s[0], 9); this.styles[9] = new CChartStyle(EFFECT_SUBTLE, EFFECT_SUBTLE, s[1], EFFECT_SUBTLE, EFFECT_SUBTLE, [f(12,0)], 5, s[1], 9); for(i = 10; i < 16; ++i) { this.styles[i] = new CChartStyle(EFFECT_SUBTLE, EFFECT_SUBTLE, [f(i-10,0)], EFFECT_SUBTLE, EFFECT_SUBTLE, [f(12,0)], 5, [f(i-10,0)], 9); } this.styles[16] = new CChartStyle(EFFECT_MODERATE, EFFECT_INTENSE, s[0], EFFECT_SUBTLE, EFFECT_NONE, [], 5, s[0], 9); this.styles[17] = new CChartStyle(EFFECT_MODERATE, EFFECT_INTENSE, s[1], EFFECT_INTENSE, EFFECT_NONE, [], 5, s[1], 9); for(i = 18; i < 24; ++i) { this.styles[i] = new CChartStyle(EFFECT_MODERATE, EFFECT_INTENSE, [f(i-18,0)], EFFECT_SUBTLE, EFFECT_NONE, [], 5, [f(i-18,0)], 9); } this.styles[24] = new CChartStyle(EFFECT_INTENSE, EFFECT_INTENSE, s[0], EFFECT_SUBTLE, EFFECT_NONE, [], 7, s[0], 13); this.styles[25] = new CChartStyle(EFFECT_MODERATE, EFFECT_INTENSE, s[1], EFFECT_SUBTLE, EFFECT_NONE, [], 7, s[1], 13); for(i = 26; i < 32; ++i) { this.styles[i] = new CChartStyle(EFFECT_MODERATE, EFFECT_INTENSE, [f(i-26,0)], EFFECT_SUBTLE, EFFECT_NONE, [], 7, [f(i-26,0)], 13); } this.styles[32] = new CChartStyle(EFFECT_NONE, EFFECT_SUBTLE, s[0], EFFECT_SUBTLE, EFFECT_SUBTLE, [f(8, -0.5)], 5, s[0], 9); this.styles[33] = new CChartStyle(EFFECT_NONE, EFFECT_SUBTLE, s[1], EFFECT_SUBTLE, EFFECT_SUBTLE, s[2], 5, s[1], 9); for(i = 34; i < 40; ++i) { this.styles[i] = new CChartStyle(EFFECT_NONE, EFFECT_SUBTLE, [f(i - 34, 0)], EFFECT_SUBTLE, EFFECT_SUBTLE, [f(i-34, -0.5)], 5, [f(i-34, 0)], 9); } this.styles[40] = new CChartStyle(EFFECT_INTENSE, EFFECT_INTENSE, s[3], EFFECT_SUBTLE, EFFECT_NONE, [], 5, s[3], 9); this.styles[41] = new CChartStyle(EFFECT_INTENSE, EFFECT_INTENSE, s[1], EFFECT_INTENSE, EFFECT_NONE, [], 5, s[1], 9); for(i = 42; i < 48; ++i) { this.styles[i] = new CChartStyle(EFFECT_INTENSE, EFFECT_INTENSE, [f(i-42, 0)], EFFECT_SUBTLE, EFFECT_NONE, [], 5, [f(i-42, 0)], 9); } this.defaultLineStyles = []; this.defaultLineStyles[0] = new ChartLineStyle(f(15, 0.75), f(15, 0.5), f(15, 0.75), f(15, 0), EFFECT_SUBTLE); for(i = 0; i < 32; ++i) { this.defaultLineStyles[i] = this.defaultLineStyles[0]; } this.defaultLineStyles[32] = new ChartLineStyle(f(8, 0.75), f(8, 0.5), f(8, 0.75), f(8, 0), EFFECT_SUBTLE); this.defaultLineStyles[33] = this.defaultLineStyles[32]; this.defaultLineStyles[34] = new ChartLineStyle(f(8, 0.75), f(8, 0.5), f(8, 0.75), f(8, 0), EFFECT_SUBTLE); for(i = 35; i < 40; ++i) { this.defaultLineStyles[i] = this.defaultLineStyles[34]; } this.defaultLineStyles[40] = new ChartLineStyle(f(8, 0.75), f(8, 0.9), f(12, 0), f(12, 0), EFFECT_NONE); for(i = 41; i < 48; ++i) { this.defaultLineStyles[i] = this.defaultLineStyles[40]; } }, this, []); }, getStyleByIndex: function(index) { if(AscFormat.isRealNumber(index)) { return this.styles[(index - 1) % 48]; } return this.styles[1]; }, getDefaultLineStyleByIndex: function(index) { if(AscFormat.isRealNumber(index)) { return this.defaultLineStyles[(index - 1) % 48]; } return this.defaultLineStyles[2]; } }; CHART_STYLE_MANAGER = new CChartStyleManager(); function ChartLineStyle(axisAndMajorGridLines, minorGridlines, chartArea, otherLines, floorChartArea) { this.axisAndMajorGridLines = axisAndMajorGridLines; this.minorGridlines = minorGridlines; this.chartArea = chartArea; this.otherLines = otherLines; this.floorChartArea = floorChartArea; } function CChartStyle(effect, fill1, fill2, fill3, line1, line2, line3, line4, markerSize) { this.effect = effect; this.fill1 = fill1; this.fill2 = fill2; this.fill3 = fill3; this.line1 = line1; this.line2 = line2; this.line3 = line3; this.line4 = line4; this.markerSize = markerSize; } function CreateUniFillSchemeColorWidthTint(schemeColorId, tintVal) { return AscFormat.ExecuteNoHistory( function(schemeColorId, tintVal) { return CreateUniFillSolidFillWidthTintOrShade(CreateUnifillSolidFillSchemeColorByIndex(schemeColorId), tintVal); }, this, [schemeColorId, tintVal]); } function checkFiniteNumber(num) { if(AscFormat.isRealNumber(num) && isFinite(num)) { return num; } return 0; } var G_O_VISITED_HLINK_COLOR = CreateUniFillSolidFillWidthTintOrShade(CreateUnifillSolidFillSchemeColorByIndex(10), 0); var G_O_HLINK_COLOR = CreateUniFillSolidFillWidthTintOrShade(CreateUnifillSolidFillSchemeColorByIndex(11), 0); var G_O_NO_ACTIVE_COMMENT_BRUSH = AscFormat.CreateUniFillByUniColor(AscFormat.CreateUniColorRGB(248, 231, 195)); var G_O_ACTIVE_COMMENT_BRUSH = AscFormat.CreateUniFillByUniColor(AscFormat.CreateUniColorRGB(240, 200, 120)); /*function addPointToMap(map, worksheet, row, col, pt) { if(!Array.isArray(map[worksheet.getId()+""])) { map[worksheet.getId()+""] = []; } if(!Array.isArray(map[worksheet.getId()+""][row])) { map[worksheet.getId()+""][row] = []; } if(!Array.isArray(map[worksheet.getId()+""][row][col])) { map[worksheet.getId()+""][row][col] = []; } map[worksheet.getId()+""][row][col].push(pt); } function checkPointInMap(map, worksheet, row, col) { if(map[worksheet.getId() + ""] && map[worksheet.getId() + ""][row] && map[worksheet.getId() + ""][row][col]) { var cell = worksheet.getCell3(row, col); var pts = map[worksheet.getId() + ""][row][col]; for(var i = 0; i < pts.length; ++i) { pts[i].setVal(cell.getValue()); } return true; } else { return false; } }*/ var CChangesDrawingsBool = AscDFH.CChangesDrawingsBool; var CChangesDrawingsLong = AscDFH.CChangesDrawingsLong; var CChangesDrawingsDouble = AscDFH.CChangesDrawingsDouble; var CChangesDrawingsString = AscDFH.CChangesDrawingsString; var CChangesDrawingsObject = AscDFH.CChangesDrawingsObject; var drawingsChangesMap = window['AscDFH'].drawingsChangesMap; AscDFH.changesFactory[AscDFH.historyitem_ChartSpace_SetNvGrFrProps ] = CChangesDrawingsObject; AscDFH.changesFactory[AscDFH.historyitem_ChartSpace_SetThemeOverride ] = CChangesDrawingsObject; AscDFH.changesFactory[AscDFH.historyitem_ShapeSetBDeleted ] = CChangesDrawingsBool; AscDFH.changesFactory[AscDFH.historyitem_ChartSpace_SetParent ] = CChangesDrawingsObject; AscDFH.changesFactory[AscDFH.historyitem_ChartSpace_SetChart ] = CChangesDrawingsObject; AscDFH.changesFactory[AscDFH.historyitem_ChartSpace_SetClrMapOvr ] = CChangesDrawingsObject; AscDFH.changesFactory[AscDFH.historyitem_ChartSpace_SetDate1904 ] = CChangesDrawingsBool; AscDFH.changesFactory[AscDFH.historyitem_ChartSpace_SetExternalData ] = CChangesDrawingsObject; AscDFH.changesFactory[AscDFH.historyitem_ChartSpace_SetLang ] = CChangesDrawingsString; AscDFH.changesFactory[AscDFH.historyitem_ChartSpace_SetPivotSource ] = CChangesDrawingsObject; AscDFH.changesFactory[AscDFH.historyitem_ChartSpace_SetPrintSettings ] = CChangesDrawingsObject; AscDFH.changesFactory[AscDFH.historyitem_ChartSpace_SetProtection ] = CChangesDrawingsObject; AscDFH.changesFactory[AscDFH.historyitem_ChartSpace_SetRoundedCorners ] = CChangesDrawingsBool; AscDFH.changesFactory[AscDFH.historyitem_ChartSpace_SetSpPr ] = CChangesDrawingsObject; AscDFH.changesFactory[AscDFH.historyitem_ChartSpace_SetStyle ] = CChangesDrawingsLong; AscDFH.changesFactory[AscDFH.historyitem_ChartSpace_SetTxPr ] = CChangesDrawingsObject; AscDFH.changesFactory[AscDFH.historyitem_ChartSpace_SetUserShapes ] = CChangesDrawingsString; AscDFH.changesFactory[AscDFH.historyitem_ChartSpace_SetGroup ] = CChangesDrawingsObject; AscDFH.changesFactory[AscDFH.historyitem_ExternalData_SetAutoUpdate ] = CChangesDrawingsBool; AscDFH.changesFactory[AscDFH.historyitem_ExternalData_SetId ] = CChangesDrawingsString; AscDFH.changesFactory[AscDFH.historyitem_PivotSource_SetFmtId ] = CChangesDrawingsLong; AscDFH.changesFactory[AscDFH.historyitem_PivotSource_SetName ] = CChangesDrawingsString; AscDFH.changesFactory[AscDFH.historyitem_Protection_SetChartObject ] = CChangesDrawingsBool; AscDFH.changesFactory[AscDFH.historyitem_Protection_SetData ] = CChangesDrawingsBool; AscDFH.changesFactory[AscDFH.historyitem_Protection_SetFormatting ] = CChangesDrawingsBool; AscDFH.changesFactory[AscDFH.historyitem_Protection_SetSelection ] = CChangesDrawingsBool; AscDFH.changesFactory[AscDFH.historyitem_Protection_SetUserInterface ] = CChangesDrawingsBool; AscDFH.changesFactory[AscDFH.historyitem_PrintSettingsSetHeaderFooter ] = CChangesDrawingsObject; AscDFH.changesFactory[AscDFH.historyitem_PrintSettingsSetPageMargins ] = CChangesDrawingsObject; AscDFH.changesFactory[AscDFH.historyitem_PrintSettingsSetPageSetup ] = CChangesDrawingsObject; AscDFH.changesFactory[AscDFH.historyitem_HeaderFooterChartSetAlignWithMargins ] = CChangesDrawingsBool; AscDFH.changesFactory[AscDFH.historyitem_HeaderFooterChartSetDifferentFirst ] = CChangesDrawingsBool; AscDFH.changesFactory[AscDFH.historyitem_HeaderFooterChartSetDifferentOddEven ] = CChangesDrawingsBool; AscDFH.changesFactory[AscDFH.historyitem_HeaderFooterChartSetEvenFooter ] = CChangesDrawingsString; AscDFH.changesFactory[AscDFH.historyitem_HeaderFooterChartSetEvenHeader ] = CChangesDrawingsString; AscDFH.changesFactory[AscDFH.historyitem_HeaderFooterChartSetFirstFooter ] = CChangesDrawingsString; AscDFH.changesFactory[AscDFH.historyitem_HeaderFooterChartSetFirstHeader ] = CChangesDrawingsString; AscDFH.changesFactory[AscDFH.historyitem_HeaderFooterChartSetOddFooter ] = CChangesDrawingsString; AscDFH.changesFactory[AscDFH.historyitem_HeaderFooterChartSetOddHeader ] = CChangesDrawingsString; AscDFH.changesFactory[AscDFH.historyitem_PageMarginsSetB ] = CChangesDrawingsDouble; AscDFH.changesFactory[AscDFH.historyitem_PageMarginsSetFooter ] = CChangesDrawingsDouble; AscDFH.changesFactory[AscDFH.historyitem_PageMarginsSetHeader ] = CChangesDrawingsDouble; AscDFH.changesFactory[AscDFH.historyitem_PageMarginsSetL ] = CChangesDrawingsDouble; AscDFH.changesFactory[AscDFH.historyitem_PageMarginsSetR ] = CChangesDrawingsDouble; AscDFH.changesFactory[AscDFH.historyitem_PageMarginsSetT ] = CChangesDrawingsDouble; AscDFH.changesFactory[AscDFH.historyitem_PageSetupSetBlackAndWhite ] = CChangesDrawingsBool; AscDFH.changesFactory[AscDFH.historyitem_PageSetupSetCopies ] = CChangesDrawingsLong; AscDFH.changesFactory[AscDFH.historyitem_PageSetupSetDraft ] = CChangesDrawingsBool; AscDFH.changesFactory[AscDFH.historyitem_PageSetupSetFirstPageNumber ] = CChangesDrawingsLong; AscDFH.changesFactory[AscDFH.historyitem_PageSetupSetHorizontalDpi ] = CChangesDrawingsLong; AscDFH.changesFactory[AscDFH.historyitem_PageSetupSetOrientation ] = CChangesDrawingsLong; AscDFH.changesFactory[AscDFH.historyitem_PageSetupSetPaperHeight ] = CChangesDrawingsDouble; AscDFH.changesFactory[AscDFH.historyitem_PageSetupSetPaperSize ] = CChangesDrawingsLong; AscDFH.changesFactory[AscDFH.historyitem_PageSetupSetPaperWidth ] = CChangesDrawingsDouble; AscDFH.changesFactory[AscDFH.historyitem_PageSetupSetUseFirstPageNumb ] = CChangesDrawingsBool; AscDFH.changesFactory[AscDFH.historyitem_PageSetupSetVerticalDpi ] = CChangesDrawingsLong; function CheckParagraphTextPr(oParagraph, oTextPr) { var oParaPr = oParagraph.Pr.Copy(); var oParaPr2 = new CParaPr(); var oCopyTextPr = oTextPr.Copy(); if(oCopyTextPr.FontFamily) { oCopyTextPr.RFonts.Set_FromObject( { Ascii: { Name: oCopyTextPr.FontFamily.Name, Index: -1 }, EastAsia: { Name: oCopyTextPr.FontFamily.Name, Index: -1 }, HAnsi: { Name: oCopyTextPr.FontFamily.Name, Index: -1 }, CS: { Name: oCopyTextPr.FontFamily.Name, Index: -1 } } ); } oParaPr2.DefaultRunPr = oCopyTextPr; oParaPr.Merge(oParaPr2); oParagraph.Set_Pr(oParaPr); } function CheckObjectTextPr(oElement, oTextPr, oDrawingDocument) { if(oElement) { if(!oElement.txPr) { oElement.setTxPr(AscFormat.CreateTextBodyFromString("", oDrawingDocument, oElement)); } oElement.txPr.content.Content[0].Set_DocumentIndex(0); CheckParagraphTextPr(oElement.txPr.content.Content[0], oTextPr); if(oElement.tx && oElement.tx.rich) { var aContent = oElement.tx.rich.content.Content; for(var i = 0; i < aContent.length; ++i) { CheckParagraphTextPr(aContent[i], oTextPr); } oElement.tx.rich.content.Set_ApplyToAll(true); var oParTextPr = new AscCommonWord.ParaTextPr(oTextPr); oElement.tx.rich.content.AddToParagraph(oParTextPr); oElement.tx.rich.content.Set_ApplyToAll(false); } CheckParagraphTextPr(oElement.txPr.content.Content[0], oTextPr); } } function CheckIncDecFontSize(oElement, bIncrease, oDrawingDocument,nDefaultSize) { if(oElement) { if(!oElement.txPr) { oElement.setTxPr(AscFormat.CreateTextBodyFromString("", oDrawingDocument, oElement)); } var oParaPr = oElement.txPr.content.Content[0].Pr.Copy(); oElement.txPr.content.Content[0].Set_DocumentIndex(0); var oCopyTextPr; if(oParaPr.DefaultRunPr) { oCopyTextPr = oParaPr.DefaultRunPr.Copy(); } else { oCopyTextPr = new CTextPr(); } oCopyTextPr.FontSize = FontSize_IncreaseDecreaseValue( bIncrease, AscFormat.isRealNumber(oCopyTextPr.FontSize) ? oCopyTextPr.FontSize : nDefaultSize); oParaPr.DefaultRunPr = oCopyTextPr; oElement.txPr.content.Content[0].Set_Pr(oParaPr); if(oElement.tx && oElement.tx.rich) { oElement.tx.rich.content.Set_ApplyToAll(true); oElement.tx.rich.content.IncreaseDecreaseFontSize(bIncrease); oElement.tx.rich.content.Set_ApplyToAll(false); } } } function CPathMemory(){ this.size = 1000; this.ArrPathCommand = new Float64Array(this.size); this.curPos = -1; this.path = new AscFormat.Path2(this); } CPathMemory.prototype.AllocPath = function(){ if(this.curPos + 1 >= this.ArrPathCommand.length){ var aNewArray = new Float64Array((((3/2)*(this.curPos + 1)) >> 0) + 1); for(var i = 0; i < this.ArrPathCommand.length; ++i){ aNewArray[i] = this.ArrPathCommand[i]; } this.ArrPathCommand = aNewArray; this.path.ArrPathCommand = aNewArray; } this.path.startPos = ++this.curPos; this.path.curLen = 0; this.ArrPathCommand[this.curPos] = 0; return this.path; }; CPathMemory.prototype.GetPath = function(index){ this.path.startPos = index; this.path.curLen = 0; return this.path; }; drawingsChangesMap[AscDFH.historyitem_ChartSpace_SetNvGrFrProps ] = function(oClass, value){oClass.nvGraphicFramePr = value;}; drawingsChangesMap[AscDFH.historyitem_ChartSpace_SetThemeOverride ] = function(oClass, value){oClass.themeOverride = value;}; drawingsChangesMap[AscDFH.historyitem_ShapeSetBDeleted ] = function(oClass, value){oClass.bDeleted = value;}; drawingsChangesMap[AscDFH.historyitem_ChartSpace_SetParent ] = function(oClass, value){oClass.parent = value;}; drawingsChangesMap[AscDFH.historyitem_ChartSpace_SetChart ] = function(oClass, value){oClass.chart = value;}; drawingsChangesMap[AscDFH.historyitem_ChartSpace_SetClrMapOvr ] = function(oClass, value){oClass.clrMapOvr = value;}; drawingsChangesMap[AscDFH.historyitem_ChartSpace_SetDate1904 ] = function(oClass, value){oClass.date1904 = value;}; drawingsChangesMap[AscDFH.historyitem_ChartSpace_SetExternalData ] = function(oClass, value){oClass.externalData = value;}; drawingsChangesMap[AscDFH.historyitem_ChartSpace_SetLang ] = function(oClass, value){oClass.lang = value;}; drawingsChangesMap[AscDFH.historyitem_ChartSpace_SetPivotSource ] = function(oClass, value){oClass.pivotSource = value;}; drawingsChangesMap[AscDFH.historyitem_ChartSpace_SetPrintSettings ] = function(oClass, value){oClass.printSettings = value;}; drawingsChangesMap[AscDFH.historyitem_ChartSpace_SetProtection ] = function(oClass, value){oClass.protection = value;}; drawingsChangesMap[AscDFH.historyitem_ChartSpace_SetRoundedCorners ] = function(oClass, value){oClass.roundedCorners = value;}; drawingsChangesMap[AscDFH.historyitem_ChartSpace_SetSpPr ] = function(oClass, value){oClass.spPr = value;}; drawingsChangesMap[AscDFH.historyitem_ChartSpace_SetStyle ] = function(oClass, value){oClass.style = value;}; drawingsChangesMap[AscDFH.historyitem_ChartSpace_SetTxPr ] = function(oClass, value){oClass.txPr = value;}; drawingsChangesMap[AscDFH.historyitem_ChartSpace_SetUserShapes ] = function(oClass, value){oClass.userShapes = value;}; drawingsChangesMap[AscDFH.historyitem_ChartSpace_SetGroup ] = function(oClass, value){oClass.group = value;}; drawingsChangesMap[AscDFH.historyitem_ExternalData_SetAutoUpdate ] = function(oClass, value){oClass.autoUpdate = value;}; drawingsChangesMap[AscDFH.historyitem_ExternalData_SetId ] = function(oClass, value){oClass.id = value;}; drawingsChangesMap[AscDFH.historyitem_PivotSource_SetFmtId ] = function(oClass, value){oClass.fmtId = value;}; drawingsChangesMap[AscDFH.historyitem_PivotSource_SetName ] = function(oClass, value){oClass.name = value;}; drawingsChangesMap[AscDFH.historyitem_Protection_SetChartObject ] = function(oClass, value){oClass.chartObject = value;}; drawingsChangesMap[AscDFH.historyitem_Protection_SetData ] = function(oClass, value){oClass.data = value;}; drawingsChangesMap[AscDFH.historyitem_Protection_SetFormatting ] = function(oClass, value){oClass.formatting = value;}; drawingsChangesMap[AscDFH.historyitem_Protection_SetSelection ] = function(oClass, value){oClass.selection = value;}; drawingsChangesMap[AscDFH.historyitem_Protection_SetUserInterface ] = function(oClass, value){oClass.userInterface = value;}; drawingsChangesMap[AscDFH.historyitem_PrintSettingsSetHeaderFooter ] = function(oClass, value){oClass.headerFooter = value;}; drawingsChangesMap[AscDFH.historyitem_PrintSettingsSetPageMargins ] = function(oClass, value){oClass.pageMargins = value;}; drawingsChangesMap[AscDFH.historyitem_PrintSettingsSetPageSetup ] = function(oClass, value){oClass.pageSetup = value;}; drawingsChangesMap[AscDFH.historyitem_HeaderFooterChartSetAlignWithMargins ] = function(oClass, value){oClass.alignWithMargins = value;}; drawingsChangesMap[AscDFH.historyitem_HeaderFooterChartSetDifferentFirst ] = function(oClass, value){oClass.differentFirst = value;}; drawingsChangesMap[AscDFH.historyitem_HeaderFooterChartSetDifferentOddEven ] = function(oClass, value){oClass.differentOddEven = value;}; drawingsChangesMap[AscDFH.historyitem_HeaderFooterChartSetEvenFooter ] = function(oClass, value){oClass.evenFooter = value;}; drawingsChangesMap[AscDFH.historyitem_HeaderFooterChartSetEvenHeader ] = function(oClass, value){oClass.evenHeader = value;}; drawingsChangesMap[AscDFH.historyitem_HeaderFooterChartSetFirstFooter ] = function(oClass, value){oClass.firstFooter = value;}; drawingsChangesMap[AscDFH.historyitem_HeaderFooterChartSetFirstHeader ] = function(oClass, value){oClass.firstHeader = value;}; drawingsChangesMap[AscDFH.historyitem_HeaderFooterChartSetOddFooter ] = function(oClass, value){oClass.oddFooter = value;}; drawingsChangesMap[AscDFH.historyitem_HeaderFooterChartSetOddHeader ] = function(oClass, value){oClass.oddHeader = value;}; drawingsChangesMap[AscDFH.historyitem_PageMarginsSetB ] = function(oClass, value){oClass.b = value;}; drawingsChangesMap[AscDFH.historyitem_PageMarginsSetFooter ] = function(oClass, value){oClass.footer = value;}; drawingsChangesMap[AscDFH.historyitem_PageMarginsSetHeader ] = function(oClass, value){oClass.header = value;}; drawingsChangesMap[AscDFH.historyitem_PageMarginsSetL ] = function(oClass, value){oClass.l = value;}; drawingsChangesMap[AscDFH.historyitem_PageMarginsSetR ] = function(oClass, value){oClass.r = value;}; drawingsChangesMap[AscDFH.historyitem_PageMarginsSetT ] = function(oClass, value){oClass.t = value;}; drawingsChangesMap[AscDFH.historyitem_PageSetupSetBlackAndWhite ] = function(oClass, value){oClass.blackAndWhite = value;}; drawingsChangesMap[AscDFH.historyitem_PageSetupSetCopies ] = function(oClass, value){oClass.copies = value;}; drawingsChangesMap[AscDFH.historyitem_PageSetupSetDraft ] = function(oClass, value){oClass.draft = value;}; drawingsChangesMap[AscDFH.historyitem_PageSetupSetFirstPageNumber ] = function(oClass, value){oClass.firstPageNumber = value;}; drawingsChangesMap[AscDFH.historyitem_PageSetupSetHorizontalDpi ] = function(oClass, value){oClass.horizontalDpi = value;}; drawingsChangesMap[AscDFH.historyitem_PageSetupSetOrientation ] = function(oClass, value){oClass.orientation = value;}; drawingsChangesMap[AscDFH.historyitem_PageSetupSetPaperHeight ] = function(oClass, value){oClass.paperHeight = value;}; drawingsChangesMap[AscDFH.historyitem_PageSetupSetPaperSize ] = function(oClass, value){oClass.paperSize = value;}; drawingsChangesMap[AscDFH.historyitem_PageSetupSetPaperWidth ] = function(oClass, value){oClass.paperWidth = value;}; drawingsChangesMap[AscDFH.historyitem_PageSetupSetUseFirstPageNumb ] = function(oClass, value){oClass.useFirstPageNumb = value;}; drawingsChangesMap[AscDFH.historyitem_PageSetupSetVerticalDpi ] = function(oClass, value){oClass.verticalDpi = value;}; function CLabelsBox(aStrings, oAxis, oChartSpace){ this.x = 0.0; this.y = 0.0; this.extX = 0.0; this.extY = 0.0; this.aLabels = []; this.maxMinWidth = -1.0; this.chartSpace = oChartSpace; this.axis = oAxis; var oStyle = null, oLbl, fMinW; for(var i = 0; i < aStrings.length; ++i){ if(typeof aStrings[i] === "string"){ oLbl = fCreateLabel(aStrings[i], i, oAxis, oChartSpace, oAxis.txPr, oAxis.spPr, oChartSpace.getDrawingDocument()); if(oStyle){ oLbl.lastStyleObject = oStyle; } fMinW = oLbl.tx.rich.content.RecalculateMinMaxContentWidth().Min; if(fMinW > this.maxMinWidth){ this.maxMinWidth = fMinW; } this.aLabels.push(oLbl); if(!oStyle){ oStyle = oLbl.lastStyleObject; } } else{ this.aLabels.push(null); } } } CLabelsBox.prototype.draw = function(graphics){ for(var i = 0; i < this.aLabels.length; ++i) { if(this.aLabels[i]) this.aLabels[i].draw(graphics); } // graphics.p_width(70); // graphics.p_color(0, 0, 0, 255); // graphics._s(); // graphics._m(this.x, this.y); // graphics._l(this.x + this.extX, this.y + 0); // graphics._l(this.x + this.extX, this.y + this.extY); // graphics._l(this.x + 0, this.y + this.extY); // graphics._z(); // graphics.ds(); }; CLabelsBox.prototype.checkMaxMinWidth = function () { if(this.maxMinWidth < 0.0){ var oStyle = null, oLbl, fMinW; for(var i = 0; i < this.aLabels.length; ++i){ oLbl = this.aLabels[i]; if(oLbl){ if(oStyle){ oLbl.lastStyleObject = oStyle; } fMinW = oLbl.tx.rich.content.RecalculateMinMaxContentWidth().Min; if(fMinW > this.maxMinWidth){ this.maxMinWidth = fMinW; } if(!oStyle){ oStyle = oLbl.lastStyleObject; } } } } return this.maxMinWidth >= 0.0 ? this.maxMinWidth : 0.0; }; CLabelsBox.prototype.hit = function(x, y){ var tx, ty; if(this.chartSpace && this.chartSpace.invertTransform) { tx = this.chartSpace.invertTransform.TransformPointX(x, y); ty = this.chartSpace.invertTransform.TransformPointY(x, y); return tx >= this.x && ty >= this.y && tx <= this.x + this.extX && ty <= this.y + this.extY; } return false; }; CLabelsBox.prototype.updatePosition = function(x, y) { // this.posX = x; // this.posY = y; // this.transform = this.localTransform.CreateDublicate(); // global_MatrixTransformer.TranslateAppend(this.transform, x, y); // this.invertTransform = global_MatrixTransformer.Invert(this.transform); for(var i = 0; i < this.aLabels.length; ++i) { if(this.aLabels[i]) this.aLabels[i].updatePosition(x, y); } }; CLabelsBox.prototype.layoutHorNormal = function(fAxisY, fDistance, fXStart, fInterval, bOnTickMark, fForceContentWidth){ var fMaxHeight = 0.0; var fCurX = bOnTickMark ? fXStart - fInterval/2.0 : fXStart; if(fInterval < 0.0){ fCurX += fInterval; } var oFirstLabel = null, fFirstLabelCenterX = null, oLastLabel = null, fLastLabelCenterX = null; var fContentWidth = fForceContentWidth ? fForceContentWidth : Math.abs(fInterval); var fHorShift = Math.abs(fInterval)/2.0 - fContentWidth/2.0; for(var i = 0; i < this.aLabels.length; ++i){ if(this.aLabels[i]){ var oLabel = this.aLabels[i]; var oContent = oLabel.tx.rich.content; oContent.Reset(0, 0, fContentWidth, 20000.0); oContent.Recalculate_Page(0, true); var fCurHeight = oContent.GetSummaryHeight(); if(fCurHeight > fMaxHeight){ fMaxHeight = fCurHeight; } var fX, fY; fX = fCurX + fHorShift; if(fDistance >= 0.0){ fY = fAxisY + fDistance; } else{ fY = fAxisY + fDistance - fCurHeight; } var oTransform = oLabel.transformText; oTransform.Reset(); global_MatrixTransformer.TranslateAppend(oTransform, fX, fY); oTransform = oLabel.localTransformText; oTransform.Reset(); global_MatrixTransformer.TranslateAppend(oTransform, fX, fY); if(oFirstLabel === null){ oFirstLabel = oLabel; fFirstLabelCenterX = fCurX + Math.abs(fInterval)/2.0; } oLastLabel = oLabel; fLastLabelCenterX = fCurX + Math.abs(fInterval)/2.0; } fCurX += fInterval; } var x0, x1; if(bOnTickMark && oFirstLabel && oLastLabel){ var fFirstLabelContentWidth = oFirstLabel.tx.rich.getMaxContentWidth(fContentWidth); var fLastLabelContentWidth = oLastLabel.tx.rich.getMaxContentWidth(fContentWidth); x0 = Math.min(fFirstLabelCenterX - fFirstLabelContentWidth/2.0, fLastLabelCenterX - fLastLabelContentWidth/2.0, fXStart, fXStart + fInterval*(this.aLabels.length - 1)); x1 = Math.max(fFirstLabelCenterX + fFirstLabelContentWidth/2.0, fLastLabelCenterX + fLastLabelContentWidth/2.0, fXStart, fXStart + fInterval*(this.aLabels.length - 1)); } else{ x0 = Math.min(fXStart, fXStart + fInterval*(this.aLabels.length)); x1 = Math.max(fXStart, fXStart + fInterval*(this.aLabels.length)); } this.x = x0; this.extX = x1 - x0; if(fDistance >= 0.0){ this.y = fAxisY; this.extY = fDistance + fMaxHeight; } else{ this.y = fAxisY + fDistance - fMaxHeight; this.extY = fMaxHeight - fDistance; } }; CLabelsBox.prototype.layoutHorRotated = function(fAxisY, fDistance, fXStart, fInterval, bOnTickMark){ var fMaxHeight = 0.0; var fCurX = bOnTickMark ? fXStart : fXStart + fInterval/2.0; var fAngle = Math.PI/4.0, fMultiplier = Math.sin(fAngle); // if(fInterval < 0.0){ // fCurX += fInterval; // } var fMinLeft = null, fMaxRight = null; for(var i = 0; i < this.aLabels.length; ++i){ if(this.aLabels[i]){ var oLabel = this.aLabels[i]; var oContent = oLabel.tx.rich.content; oContent.Set_ApplyToAll(true); oContent.SetParagraphAlign(AscCommon.align_Left); oContent.Set_ApplyToAll(false); var oSize = oLabel.tx.rich.getContentOneStringSizes(); var fBoxW = fMultiplier*(oSize.w + oSize.h); var fBoxH = fBoxW; if(fBoxH > fMaxHeight){ fMaxHeight = fBoxH; } var fX1, fY0, fXC, fYC; fY0 = fAxisY + fDistance; if(fDistance >= 0.0){ fX1 = fCurX + oSize.h*fMultiplier; fXC = fX1 - fBoxW/2.0; fYC = fY0 + fBoxH/2.0; } else{ fX1 = fCurX - oSize.h*fMultiplier; fXC = fX1 + fBoxW/2.0; fYC = fY0 - fBoxH/2.0; } var oTransform = oLabel.localTransformText; oTransform.Reset(); global_MatrixTransformer.TranslateAppend(oTransform, -oSize.w/2.0, -oSize.h/2.0); global_MatrixTransformer.RotateRadAppend(oTransform, fAngle); global_MatrixTransformer.TranslateAppend(oTransform, fXC, fYC); if(null === fMinLeft || (fXC - fBoxW/2.0) < fMinLeft){ fMinLeft = fXC - fBoxW/2.0; } if(null === fMaxRight || (fXC + fBoxW/2.0) > fMaxRight){ fMaxRight = fXC + fBoxW/2.0; } } fCurX += fInterval; } var aPoints = []; aPoints.push(fXStart); var nIntervalCount = bOnTickMark ? this.aLabels.length - 1 : this.aLabels.length; aPoints.push(fXStart + fInterval*nIntervalCount); if(null !== fMinLeft){ aPoints.push(fMinLeft); } if(null !== fMaxRight){ aPoints.push(fMaxRight); } this.x = Math.min.apply(Math, aPoints); this.extX = Math.max.apply(Math, aPoints) - this.x; if(fDistance >= 0.0){ this.y = fAxisY; this.extY = fDistance + fMaxHeight; } else{ this.y = fAxisY + fDistance - fMaxHeight; this.extY = fMaxHeight - fDistance; } }; CLabelsBox.prototype.layoutVertNormal = function(fAxisX, fDistance, fYStart, fInterval, bOnTickMark, fMaxBlockWidth){ var fCurY = bOnTickMark ? fYStart : fYStart + fInterval/2.0; var fDistance_ = Math.abs(fDistance); var oTransform, oContent, oLabel, fMinY = fYStart, fMaxY = fYStart + fInterval*(this.aLabels.length - 1), fY; var fMaxContentWidth = 0.0; for(var i = 0; i < this.aLabels.length; ++i){ if(this.aLabels[i]){ oLabel = this.aLabels[i]; oContent = oLabel.tx.rich.content; oContent.Set_ApplyToAll(true); oContent.SetParagraphAlign(AscCommon.align_Left); oContent.Set_ApplyToAll(false); var oSize = oLabel.tx.rich.getContentOneStringSizes(); if(oSize.w + fDistance_ > fMaxBlockWidth){ break; } if(oSize.w > fMaxContentWidth){ fMaxContentWidth = oSize.w; } oTransform = oLabel.localTransformText; oTransform.Reset(); fY = fCurY - oSize.h/2.0; if(fDistance > 0.0){ global_MatrixTransformer.TranslateAppend(oTransform, fAxisX + fDistance, fY); } else{ global_MatrixTransformer.TranslateAppend(oTransform, fAxisX + fDistance - oSize.w, fY); } if(fY < fMinY){ fMinY = fY; } if(fY + oSize.h > fMaxY){ fMaxY = fY + oSize.h; } } fCurY += fInterval; } if(i < this.aLabels.length){ var fMaxMinWidth = this.checkMaxMinWidth(); fMaxContentWidth = 0.0; for(i = 0; i < this.aLabels.length; ++i){ oLabel = this.aLabels[i]; if(oLabel){ oContent = oLabel.tx.rich.content; oContent.Set_ApplyToAll(true); oContent.SetParagraphAlign(AscCommon.align_Center); oContent.Set_ApplyToAll(false); var fContentWidth; if(fMaxMinWidth + fDistance_ < fMaxBlockWidth) { fContentWidth = oContent.RecalculateMinMaxContentWidth().Min + 0.1; } else{ fContentWidth = fMaxBlockWidth - fDistance_; } if(fContentWidth > fMaxContentWidth){ fMaxContentWidth = fContentWidth; } oContent.Reset(0, 0, fContentWidth, 20000);//выставляем большую ширину чтобы текст расчитался в одну строку. oContent.Recalculate_Page(0, true); var fContentHeight = oContent.GetSummaryHeight(); oTransform = oLabel.localTransformText; oTransform.Reset(); fY = fCurY - fContentHeight/2.0; if(fDistance > 0.0){ global_MatrixTransformer.TranslateAppend(oTransform, fAxisX + fDistance, fY); } else{ fY = fCurY - fContentHeight/2.0; global_MatrixTransformer.TranslateAppend(oTransform, fAxisX + fDistance - fContentWidth, fY); } if(fY < fMinY){ fMinY = fY; } if(fY + fContentHeight > fMaxY){ fMaxY = fY + fContentHeight; } } fCurY += fInterval; } } if(fDistance > 0.0){ this.x = fAxisX; } else{ this.x = fAxisX + fDistance - fMaxContentWidth; } this.extX = fMaxContentWidth + fDistance_; this.y = fMinY; this.extY = fMaxY - fMinY; }; function fCreateLabel(sText, idx, oParent, oChart, oTxPr, oSpPr, oDrawingDocument){ var dlbl = new AscFormat.CDLbl(); dlbl.parent = oParent; dlbl.chart = oChart; dlbl.spPr = oSpPr; dlbl.txPr = oTxPr; dlbl.idx = idx; dlbl.tx = new AscFormat.CChartText(); dlbl.tx.rich = AscFormat.CreateTextBodyFromString(sText, oDrawingDocument, dlbl); var content = dlbl.tx.rich.content; content.Set_ApplyToAll(true); content.SetParagraphAlign(AscCommon.align_Center); content.Set_ApplyToAll(false); dlbl.txBody = dlbl.tx.rich; dlbl.oneStringWidth = -1.0; return dlbl; } function fLayoutHorLabelsBox(oLabelsBox, fY, fXStart, fXEnd, bOnTickMark, fDistance, bForceVertical, bNumbers, fForceContentWidth){ var fAxisLength = fXEnd - fXStart; var nLabelsCount = oLabelsBox.aLabels.length; var bOnTickMark_ = bOnTickMark && nLabelsCount > 1; var nIntervalCount = bOnTickMark_ ? nLabelsCount - 1 : nLabelsCount; var fInterval = fAxisLength/nIntervalCount; if(!bForceVertical || true){//TODO: implement for vertical labels var fMaxMinWidth = oLabelsBox.checkMaxMinWidth(); var fCheckInterval = AscFormat.isRealNumber(fForceContentWidth) ? fForceContentWidth : Math.abs(fInterval); if(fMaxMinWidth <= fCheckInterval){ oLabelsBox.layoutHorNormal(fY, fDistance, fXStart, fInterval, bOnTickMark_, fForceContentWidth); } else{ oLabelsBox.layoutHorRotated(fY, fDistance, fXStart, fInterval, bOnTickMark_); } } } function fLayoutVertLabelsBox(oLabelsBox, fX, fYStart, fYEnd, bOnTickMark, fDistance, bForceVertical){ var fAxisLength = fYEnd - fYStart; var nLabelsCount = oLabelsBox.aLabels.length; var bOnTickMark_ = bOnTickMark && nLabelsCount > 1; var nIntervalCount = bOnTickMark_ ? nLabelsCount - 1 : nLabelsCount; var fInterval = fAxisLength/nIntervalCount; if(!bForceVertical || true){ oLabelsBox.layoutVertNormal(fX, fDistance, fYStart, fInterval, bOnTickMark_); } else{ //TODO: vertical text } } function CAxisGrid(){ this.nType = 0;//0 - horizontal, 1 - vertical, 2 - series axis this.fStart = 0.0; this.fStride = 0.0; this.bOnTickMark = true; this.nCount = 0; this.minVal = 0.0; this.maxVal = 0.0; this.aStrings = []; } function CChartSpace() { AscFormat.CGraphicObjectBase.call(this); this.nvGraphicFramePr = null; this.chart = null; this.clrMapOvr = null; this.date1904 = null; this.externalData = null; this.lang = null; this.pivotSource = null; this.printSettings = null; this.protection = null; this.roundedCorners = null; this.spPr = null; this.style = 2; this.txPr = null; this.userShapes = null; this.themeOverride = null; this.pathMemory = new CPathMemory(); this.bbox = null; this.ptsCount = 0; this.selection = { title: null, legend: null, legendEntry: null, axisLbls: null, dataLbls: null, dataLbl: null, plotArea: null, rotatePlotArea: null, gridLines: null, series: null, datPoint: null, textSelection: null }; this.Id = g_oIdCounter.Get_NewId(); g_oTableId.Add(this, this.Id); } CChartSpace.prototype = Object.create(AscFormat.CGraphicObjectBase.prototype); CChartSpace.prototype.constructor = CChartSpace; CChartSpace.prototype.AllocPath = function(){ return this.pathMemory.AllocPath().startPos; }; CChartSpace.prototype.GetPath = function(index){ return this.pathMemory.GetPath(index); }; CChartSpace.prototype.select = CShape.prototype.select; CChartSpace.prototype.checkDrawingBaseCoords = CShape.prototype.checkDrawingBaseCoords; CChartSpace.prototype.setDrawingBaseCoords = CShape.prototype.setDrawingBaseCoords; CChartSpace.prototype.deleteBFromSerialize = CShape.prototype.deleteBFromSerialize; CChartSpace.prototype.setBFromSerialize = CShape.prototype.setBFromSerialize; CChartSpace.prototype.checkTypeCorrect = function(){ if(!this.chart){ return false; } if(!this.chart.plotArea){ return false } if(this.chart.plotArea.charts.length === 0){ return false; } if(this.chart.plotArea.charts[0].series.length === 0){ return false; } return true; }; CChartSpace.prototype.drawSelect = function(drawingDocument, nPageIndex) { var i; if(this.selectStartPage === nPageIndex) { drawingDocument.DrawTrack(AscFormat.TYPE_TRACK.SHAPE, this.getTransformMatrix(), 0, 0, this.extX, this.extY, false, this.canRotate()); if(window["NATIVE_EDITOR_ENJINE"]){ return; } if(this.selection.textSelection) { drawingDocument.DrawTrack(AscFormat.TYPE_TRACK.CHART_TEXT, this.selection.textSelection.transform, 0, 0, this.selection.textSelection.extX, this.selection.textSelection.extY, false, false, false); } else if(this.selection.title) { drawingDocument.DrawTrack(AscFormat.TYPE_TRACK.CHART_TEXT, this.selection.title.transform, 0, 0, this.selection.title.extX, this.selection.title.extY, false, false, false); } else if(AscFormat.isRealNumber(this.selection.dataLbls)) { var series = this.chart.plotArea.charts[0].series; var ser = series[this.selection.dataLbls]; if(ser) { var pts = AscFormat.getPtsFromSeries(ser); if(!AscFormat.isRealNumber(this.selection.dataLbl)) { for(i = 0; i < pts.length; ++i) { if(pts[i] && pts[i].compiledDlb && !pts[i].compiledDlb.bDelete) { drawingDocument.DrawTrack(AscFormat.TYPE_TRACK.CHART_TEXT, pts[i].compiledDlb.transform, 0, 0, pts[i].compiledDlb.extX, pts[i].compiledDlb.extY, false, false); } } } else { if(pts[this.selection.dataLbl] && pts[this.selection.dataLbl].compiledDlb) { drawingDocument.DrawTrack(AscFormat.TYPE_TRACK.CHART_TEXT, pts[this.selection.dataLbl].compiledDlb.transform, 0, 0, pts[this.selection.dataLbl].compiledDlb.extX, pts[this.selection.dataLbl].compiledDlb.extY, false, false); } } } } else if(this.selection.dataLbl) { drawingDocument.DrawTrack(AscFormat.TYPE_TRACK.CHART_TEXT, this.selection.dataLbl.transform, 0, 0, this.selection.dataLbl.extX, this.selection.dataLbl.extY, false, false); } else if(this.selection.legend) { if(AscFormat.isRealNumber(this.selection.legendEntry)) { var oEntry = this.chart.legend.findCalcEntryByIdx(this.selection.legendEntry); if(oEntry){ drawingDocument.DrawTrack(AscFormat.TYPE_TRACK.CHART_TEXT, oEntry.transformText, 0, 0, oEntry.contentWidth, oEntry.contentHeight, false, false); } } else { drawingDocument.DrawTrack(AscFormat.TYPE_TRACK.CHART_TEXT, this.selection.legend.transform, 0, 0, this.selection.legend.extX, this.selection.legend.extY, false, false); } } else if(this.selection.axisLbls) { var oLabels = this.selection.axisLbls.labels; drawingDocument.DrawTrack(AscFormat.TYPE_TRACK.CHART_TEXT, this.transform, oLabels.x, oLabels.y, oLabels.extX, oLabels.extY, false, false); } else if(this.selection.plotArea) { var oChartSize = this.getChartSizes(true); drawingDocument.DrawTrack(AscFormat.TYPE_TRACK.CHART_TEXT, this.transform, oChartSize.startX, oChartSize.startY, oChartSize.w, oChartSize.h, false, false); /*if(!this.selection.rotatePlotArea) { drawingDocument.DrawTrack(AscFormat.TYPE_TRACK.CHART_TEXT, this.transform, oChartSize.startX, oChartSize.startY, oChartSize.w, oChartSize.h, false, false); } else { var arr = [ {x: oChartSize.startX, y: oChartSize.startY}, {x: oChartSize.startX + oChartSize.w/2, y: oChartSize.startY}, {x: oChartSize.startX + oChartSize.w, y: oChartSize.startY}, {x: oChartSize.startX + oChartSize.w, y: oChartSize.startY + oChartSize.h/2}, {x: oChartSize.startX + oChartSize.w, y: oChartSize.startY + oChartSize.h}, {x: oChartSize.startX + oChartSize.w/2, y: oChartSize.startY + oChartSize.h}, {x: oChartSize.startX, y: oChartSize.startY + oChartSize.h}, {x: oChartSize.startX, y: oChartSize.startY + oChartSize.h/2}, {x: oChartSize.startX, y: oChartSize.startY} ]; drawingDocument.AutoShapesTrack.DrawEditWrapPointsPolygon(arr, this.transform); }*/ } } }; CChartSpace.prototype.recalculateTextPr = function() { if(this.txPr && this.txPr.content) { this.txPr.content.Reset(0, 0, 10, 10); this.txPr.content.Recalculate_Page(0, true); } }; CChartSpace.prototype.getSelectionState = function() { var content_selection = null, content = null; if(this.selection.textSelection) { content = this.selection.textSelection.getDocContent(); if(content) content_selection = content.GetSelectionState(); } return { content: content, title: this.selection.title, legend: this.selection.legend, legendEntry: this.selection.legendEntry, axisLbls: this.selection.axisLbls, dataLbls: this.selection.dataLbls, dataLbl: this.selection.dataLbl, textSelection: this.selection.textSelection, plotArea: this.selection.plotArea, rotatePlotArea: this.selection.rotatePlotArea, contentSelection: content_selection, recalcTitle: this.recalcInfo.recalcTitle, bRecalculatedTitle: this.recalcInfo.bRecalculatedTitle } }; CChartSpace.prototype.setSelectionState = function(state) { this.selection.title = state.title; this.selection.legend = state.legend; this.selection.legendEntry = state.legendEntry; this.selection.axisLbls = state.axisLbls; this.selection.dataLbls = state.dataLbls; this.selection.dataLbl = state.dataLbl; this.selection.rotatePlotArea = state.rotatePlotArea; this.selection.textSelection = state.textSelection; this.selection.plotArea = state.plotArea; if(isRealObject(state.recalcTitle)) { this.recalcInfo.recalcTitle = state.recalcTitle; this.recalcInfo.bRecalculatedTitle = state.bRecalculatedTitle; } if(state.contentSelection) { if(this.selection.textSelection) { var content = this.selection.textSelection.getDocContent(); if(content) content.SetSelectionState(state.contentSelection, state.contentSelection.length - 1); } } }; CChartSpace.prototype.loadDocumentStateAfterLoadChanges = function(state) { this.selection.title = null; this.selection.legend = null; this.selection.legendEntry = null; this.selection.axisLbls = null; this.selection.dataLbls = null; this.selection.dataLbl = null; this.selection.plotArea = null; this.selection.rotatePlotArea = null; this.selection.gridLine = null; this.selection.series = null; this.selection.datPoint = null; this.selection.textSelection = null; var bRet = false; if(state.DrawingsSelectionState){ var chartSelection = state.DrawingsSelectionState.chartSelection; if(chartSelection){ if(this.chart){ if(chartSelection.title){ if(this.chart.title === chartSelection.title){ this.selection.title = this.chart.title; bRet = true; } else{ var plot_area = this.chart.plotArea; if(plot_area){ for(var i = 0; i < plot_area.axId.length; ++i){ var axis = plot_area.axId[i]; if(axis && axis.title === chartSelection.title){ this.selection.title = axis.title; bRet = true; break; } } } } if(this.selection.title){ if(this.selection.title === chartSelection.textSelection){ var oTitleContent = this.selection.title.getDocContent(); if(oTitleContent && oTitleContent === chartSelection.content){ this.selection.textSelection = this.selection.title; if (true === state.DrawingSelection) { oTitleContent.SetContentPosition(state.StartPos, 0, 0); oTitleContent.SetContentSelection(state.StartPos, state.EndPos, 0, 0, 0); } else { oTitleContent.SetContentPosition(state.Pos, 0, 0); } } } } } } } } return bRet; }; CChartSpace.prototype.resetInternalSelection = function(noResetContentSelect) { if(this.selection.title) { this.selection.title.selected = false; } if(this.selection.textSelection) { if(!(noResetContentSelect === true)) { var content = this.selection.textSelection.getDocContent(); content && content.RemoveSelection(); } this.selection.textSelection = null; } }; CChartSpace.prototype.getDocContent = function() { return null; }; CChartSpace.prototype.resetSelection = function(noResetContentSelect) { this.resetInternalSelection(noResetContentSelect); this.selection.title = null; this.selection.legend = null; this.selection.legendEntry = null; this.selection.axisLbls = null; this.selection.dataLbls = null; this.selection.dataLbl = null; this.selection.textSelection = null; this.selection.plotArea = null; this.selection.rotatePlotArea = null; }; CChartSpace.prototype.getStyles = function() { return AscFormat.ExecuteNoHistory(function(){ var styles = new CStyles(false); var style = new CStyle("dataLblStyle", null, null, null, true); var text_pr = new CTextPr(); text_pr.FontSize = 10; text_pr.Unifill = CreateUnfilFromRGB(0,0,0); var parent_objects = this.getParentObjects(); var theme = parent_objects.theme; var para_pr = new CParaPr(); para_pr.Jc = AscCommon.align_Center; para_pr.Spacing.Before = 0.0; para_pr.Spacing.After = 0.0; para_pr.Spacing.Line = 1; para_pr.Spacing.LineRule = Asc.linerule_Auto; style.ParaPr = para_pr; var minor_font = theme.themeElements.fontScheme.minorFont; if(minor_font) { if(typeof minor_font.latin === "string" && minor_font.latin.length > 0) { text_pr.RFonts.Ascii = {Name: minor_font.latin, Index: -1}; } if(typeof minor_font.ea === "string" && minor_font.ea.length > 0) { text_pr.RFonts.EastAsia = {Name: minor_font.ea, Index: -1}; } if(typeof minor_font.cs === "string" && minor_font.cs.length > 0) { text_pr.RFonts.CS = {Name: minor_font.cs, Index: -1}; } if(typeof minor_font.sym === "string" && minor_font.sym.length > 0) { text_pr.RFonts.HAnsi = {Name: minor_font.sym, Index: -1}; } } style.TextPr = text_pr; var chart_text_pr; if(this.txPr && this.txPr.content && this.txPr.content.Content[0] && this.txPr.content.Content[0].Pr) { style.ParaPr.Merge(this.txPr.content.Content[0].Pr); if(this.txPr.content.Content[0].Pr.DefaultRunPr) { chart_text_pr = this.txPr.content.Content[0].Pr.DefaultRunPr; style.TextPr.Merge(chart_text_pr); } } if(this.txPr && this.txPr.content && this.txPr.content.Content[0] && this.txPr.content.Content[0].Pr) { style.ParaPr.Merge(this.txPr.content.Content[0].Pr); if(this.txPr.content.Content[0].Pr.DefaultRunPr) style.TextPr.Merge(this.txPr.content.Content[0].Pr.DefaultRunPr); } styles.Add(style); return {lastId: style.Id, styles: styles}; }, this, []); }; CChartSpace.prototype.getParagraphTextPr = function() { if(this.selection.title && !this.selection.textSelection) { return GetTextPrFormArrObjects([this.selection.title]); } else if(this.selection.legend) { if(!AscFormat.isRealNumber(this.selection.legendEntry)) { if(AscFormat.isRealNumber(this.legendLength)) { var arrForProps = []; for(var i = 0; i < this.legendLength; ++i) { arrForProps.push(this.chart.legend.getCalcEntryByIdx(i, this.getDrawingDocument())) } return GetTextPrFormArrObjects(arrForProps); } return GetTextPrFormArrObjects(this.chart.legend.calcEntryes); } else { var calcLegendEntry = this.chart.legend.getCalcEntryByIdx(this.selection.legendEntry, this.getDrawingDocument()); if(calcLegendEntry) { return GetTextPrFormArrObjects([calcLegendEntry]); } } } else if(this.selection.textSelection) { return this.selection.textSelection.txBody.content.GetCalculatedTextPr(); } else if(this.selection.axisLbls && this.selection.axisLbls.labels) { return GetTextPrFormArrObjects(this.selection.axisLbls.labels.aLabels, true); } else if(AscFormat.isRealNumber(this.selection.dataLbls)) { var ser = this.chart.plotArea.charts[0].series[this.selection.dataLbls]; if(ser) { var pts = AscFormat.getPtsFromSeries(ser); if(!AscFormat.isRealNumber(this.selection.dataLbl)) { return GetTextPrFormArrObjects(pts, undefined , true); } else { var pt = pts[this.selection.dataLbl]; if(pt) { return GetTextPrFormArrObjects([pt], undefined , true); } } } } if(this.txPr && this.txPr.content && this.txPr.content.Content[0] && this.txPr.content.Content[0].Pr.DefaultRunPr) { this.txPr.content.Content[0].Pr.DefaultRunPr.Copy(); } return new AscCommonWord.CTextPr(); }; CChartSpace.prototype.applyLabelsFunction = function(fCallback, value) { if(this.selection.title) { var DefaultFontSize = 18; if(this.selection.title !== this.chart.title) { DefaultFontSize = 10; } fCallback(this.selection.title, value, this.getDrawingDocument(), DefaultFontSize); } else if(this.selection.legend) { if(!AscFormat.isRealNumber(this.selection.legendEntry)) { fCallback(this.selection.legend, value, this.getDrawingDocument(), 10); for(var i = 0; i < this.selection.legend.legendEntryes.length; ++i) { fCallback(this.selection.legend.legendEntryes[i], value, this.getDrawingDocument(), 10); } } else { var entry = this.selection.legend.findLegendEntryByIndex(this.selection.legendEntry); if(!entry) { entry = new AscFormat.CLegendEntry(); entry.setIdx(this.selection.legendEntry); if(this.selection.legend.txPr) { entry.setTxPr(this.selection.legend.txPr.createDuplicate()); } this.selection.legend.addLegendEntry(entry); } if(entry) { fCallback(entry, value, this.getDrawingDocument(), 10); } } } else if(this.selection.axisLbls) { fCallback(this.selection.axisLbls, value, this.getDrawingDocument(), 10); } else if(AscFormat.isRealNumber(this.selection.dataLbls)) { var ser = this.chart.plotArea.charts[0].series[this.selection.dataLbls]; if(ser) { var pts = AscFormat.getPtsFromSeries(ser); if(!ser.dLbls) { var oDlbls; if(this.chart.plotArea.charts[0].dLbls) { oDlbls = this.chart.plotArea.charts[0].dLbls.createDuplicate(); } else { oDlbls = new AscFormat.CDLbls(); } ser.setDLbls(oDlbls); } if(!AscFormat.isRealNumber(this.selection.dataLbl)) { fCallback(ser.dLbls, value, this.getDrawingDocument(), 10); for(var i = 0; i < pts.length; ++i) { var dLbl = ser.dLbls.findDLblByIdx(pts[i].idx); if(dLbl) { if(ser.dLbls.txPr && !dLbl.txPr) { dLbl.setTxPr(ser.dLbls.txPr.createDuplicate()); } fCallback(dLbl, value, this.getDrawingDocument(), 10); } } } else { var pt = pts[this.selection.dataLbl]; if(pt) { var dLbl = ser.dLbls.findDLblByIdx(pt.idx); if(!dLbl) { dLbl = new AscFormat.CDLbl(); dLbl.setIdx(pt.idx); if(ser.dLbls.txPr) { dLbl.merge(ser.dLbls); } ser.dLbls.addDLbl(dLbl); } fCallback(dLbl, value, this.getDrawingDocument(), 10); } } } } }; CChartSpace.prototype.paragraphIncDecFontSize = function(bIncrease) { if(this.selection.textSelection) { this.selection.textSelection.checkDocContent(); var content = this.selection.textSelection.getDocContent(); if(content) { content.IncreaseDecreaseFontSize(bIncrease); } return; } this.applyLabelsFunction(CheckIncDecFontSize, bIncrease); }; CChartSpace.prototype.paragraphAdd = function(paraItem, bRecalculate) { if(paraItem.Type === para_TextPr) { var _paraItem; if(paraItem.Value.Unifill && paraItem.Value.Unifill.checkWordMods()) { _paraItem = paraItem.Copy(); _paraItem.Value.Unifill.convertToPPTXMods(); } else { _paraItem = paraItem; } if(this.selection.textSelection) { this.selection.textSelection.checkDocContent(); this.selection.textSelection.paragraphAdd(paraItem, bRecalculate); return; } /*if(this.selection.title) { this.selection.title.checkDocContent(); CheckObjectTextPr(this.selection.title, _paraItem.Value, this.getDrawingDocument(), 18); if(this.selection.title.tx && this.selection.title.tx.rich && this.selection.title.tx.rich.content) { this.selection.title.tx.rich.content.Set_ApplyToAll(true); this.selection.title.tx.rich.content.AddToParagraph(_paraItem); this.selection.title.tx.rich.content.Set_ApplyToAll(false); } return; }*/ this.applyLabelsFunction(CheckObjectTextPr, _paraItem.Value); } else if(paraItem.Type === para_Text || paraItem.Type === para_Space){ if(this.selection.title){ this.selection.textSelection = this.selection.title; this.selection.textSelection.checkDocContent(); this.selection.textSelection.paragraphAdd(paraItem, bRecalculate); } } }; CChartSpace.prototype.applyTextFunction = function(docContentFunction, tableFunction, args) { if(docContentFunction === CDocumentContent.prototype.AddToParagraph && !this.selection.textSelection) { this.paragraphAdd(args[0], args[1]); return; } if(this.selection.textSelection) { this.selection.textSelection.checkDocContent(); var bTrackRevision = false; if(typeof editor !== "undefined" && editor && editor.WordControl && editor.WordControl.m_oLogicDocument.TrackRevisions === true){ bTrackRevision = true; editor.WordControl.m_oLogicDocument.TrackRevisions = false; } this.selection.textSelection.applyTextFunction(docContentFunction, tableFunction, args); if(bTrackRevision){ editor.WordControl.m_oLogicDocument.TrackRevisions = true; } } }; CChartSpace.prototype.selectTitle = function(title, pageIndex) { title.select(this, pageIndex); this.resetInternalSelection(); this.selection.legend = null; this.selection.legendEntry = null; this.selection.axisLbls = null; this.selection.dataLbls = null; this.selection.dataLbl = null; this.selection.textSelection = null; this.selection.plotArea = null; this.selection.rotatePlotArea = null; }; CChartSpace.prototype.recalculateCurPos = AscFormat.DrawingObjectsController.prototype.recalculateCurPos; CChartSpace.prototype.documentUpdateSelectionState = function() { if(this.selection.textSelection) { this.selection.textSelection.updateSelectionState(); } }; CChartSpace.prototype.getLegend = function() { if(this.chart) { return this.chart.legend; } return null; }; CChartSpace.prototype.getAllTitles = function() { var ret = []; if(this.chart) { if(this.chart.title) { ret.push(this.chart.title); } if(this.chart.plotArea) { if(this.chart.plotArea.catAx && this.chart.plotArea.catAx.title) { ret.push(this.chart.plotArea.catAx.title); } if(this.chart.plotArea.valAx && this.chart.plotArea.valAx.title) { ret.push(this.chart.plotArea.valAx.title); } } } return ret; }; CChartSpace.prototype.getFill = CShape.prototype.getFill; CChartSpace.prototype.changeSize = CShape.prototype.changeSize; CChartSpace.prototype.changeFill = function (unifill) { if(this.recalcInfo.recalculatePenBrush) { this.recalculatePenBrush(); } var unifill2 = AscFormat.CorrectUniFill(unifill, this.brush, this.getEditorType()); unifill2.convertToPPTXMods(); this.spPr.setFill(unifill2); }; CChartSpace.prototype.setFill = function (fill) { this.spPr.setFill(fill); }; CChartSpace.prototype.setNvSpPr = function(pr) { History.Add(new CChangesDrawingsObject(this, AscDFH.historyitem_ChartSpace_SetNvGrFrProps, this.nvGraphicFramePr, pr)); this.nvGraphicFramePr = pr; }; CChartSpace.prototype.changeLine = function (line) { if(this.recalcInfo.recalculatePenBrush) { this.recalculatePenBrush(); } var stroke = AscFormat.CorrectUniStroke(line, this.pen); if(stroke.Fill) { stroke.Fill.convertToPPTXMods(); } this.spPr.setLn(stroke); }; CChartSpace.prototype.parseChartFormula = function(sFormula) { if(this.worksheet && typeof sFormula === "string" && sFormula.length > 0){ return AscCommonExcel.getRangeByRef(sFormula, this.worksheet); } return []; }; CChartSpace.prototype.checkBBoxIntersection = function(bbox1, bbox2) { return !(bbox1.r1 > bbox2.r2 || bbox2.r1 > bbox1.r2 || bbox1.c1 > bbox2.c2 || bbox2.c1 > bbox1.c2) }; CChartSpace.prototype.checkSeriesIntersection = function(val, bbox, worksheet) { if(val && bbox && worksheet) { var parsed_formulas = val.parsedFormulas; for(var i = 0; i < parsed_formulas.length; ++i) { if(parsed_formulas[i].worksheet === worksheet && this.checkBBoxIntersection(parsed_formulas[i].bbox, bbox)) { return true; } } } return false; }; CChartSpace.prototype.checkVal = function(val) { if(val) { if(val.numRef) { val.numRef.parsedFormulas = this.parseChartFormula(val.numRef.f); } if(val.strRef) { val.strRef.parsedFormulas = this.parseChartFormula(val.strRef.f); } } }; CChartSpace.prototype.recalculateSeriesFormulas = function() { this.checkSeriesRefs(this.checkVal); }; CChartSpace.prototype.checkChartIntersection = function(bbox, worksheet) { return this.checkSeriesRefs(this.checkSeriesIntersection, bbox, worksheet); }; CChartSpace.prototype.changeListName = function(val, oldName, newName) { if(val) { if(val.numRef && typeof val.numRef.f === "string") { if(val.numRef.f.indexOf(newName) > -1) return; } if(val.strRef && typeof val.strRef.f === "string") { if(val.strRef.f.indexOf(newName) > -1) return; } if(val.numRef && typeof val.numRef.f === "string" || val.strRef && typeof val.strRef.f === "string") { var checkString = oldName.replace(/[-[\]{}()*+?.,\\^$|#\s]/g, "\\$&"); if(val.numRef && typeof val.numRef.f === "string") { val.numRef.setF(val.numRef.f.replace(new RegExp(checkString,'g'), newName)); } if(val.strRef && typeof val.strRef.f === "string") { val.strRef.setF(val.strRef.f.replace(new RegExp(checkString,'g'), newName)); } } } }; CChartSpace.prototype.checkListName = function(val, oldName) { if(val) { if(val.numRef && typeof val.numRef.f === "string") { if(val.numRef.f.indexOf(oldName) > -1) return true; } if(val.strRef && typeof val.strRef.f === "string") { if(val.strRef.f.indexOf(oldName) > -1) return true; } } return false; }; CChartSpace.prototype.changeChartReferences = function(oldWorksheetName, newWorksheetName) { this.checkSeriesRefs(this.changeListName, oldWorksheetName, newWorksheetName); }; CChartSpace.prototype.checkChartReferences = function(oldWorksheetName) { return this.checkSeriesRefs(this.checkListName, oldWorksheetName); }; CChartSpace.prototype.updateChartReferences = function(oldWorksheetName, newWorksheetName, bNoRebuildCache) { if(this.checkChartReferences(oldWorksheetName)) { if(bNoRebuildCache === true) { this.bNoHandleRecalc = true; } this.changeChartReferences(oldWorksheetName, newWorksheetName); if(!(bNoRebuildCache === true)) { this.rebuildSeries(); } this.bNoHandleRecalc = false; } }; CChartSpace.prototype.updateChartReferences2 = function(oldWorksheetName, newWorksheetName) { if(this.checkChartReferences(oldWorksheetName)) { this.changeChartReferences(oldWorksheetName, newWorksheetName); } }; CChartSpace.prototype.checkSeriesRefs = function(callback, bbox, worksheet) { if(this.chart && this.chart.plotArea) { var charts = this.chart.plotArea.charts, i, j, series, ser; for(i = 0; i < charts.length; ++i) { series = charts[i].series; if(charts[i].getObjectType() === AscDFH.historyitem_type_ScatterChart) { for(j = 0; j < series.length; ++j) { ser = series[j]; if(callback(ser.xVal, bbox, worksheet)) return true; if(callback(ser.yVal, bbox, worksheet)) return true; if(callback(ser.tx, bbox, worksheet)) return true; } } else { for(j = 0; j < series.length; ++j) { ser = series[j]; if(callback(ser.val, bbox, worksheet)) return true; if(callback(ser.cat, bbox, worksheet)) return true; if(callback(ser.tx, bbox, worksheet)) return true; } } } } return false; }; CChartSpace.prototype.clearCacheVal = function(val) { if(!val) return; if(val.numRef) { if(val.numRef.numCache) { removePtsFromLit(val.numRef.numCache); } } if(val.strRef) { if(val.strRef.strCache) { val.strRef.setStrCache(null); } } }; CChartSpace.prototype.checkIntersectionChangedRange = function(data) { if(!data) return true; var i, j; if(this.seriesBBoxes) { for(i = 0; i < this.seriesBBoxes.length; ++i) { for(j = 0; j < data.length; ++j) { if(this.seriesBBoxes[i].checkIntersection(data[j])) return true; } } } if(this.seriesTitlesBBoxes) { for(i = 0; i < this.seriesTitlesBBoxes.length; ++i) { for(j = 0; j < data.length; ++j) { if(this.seriesTitlesBBoxes[i].checkIntersection(data[j])) return true; } } } if(this.catTitlesBBoxes) { for(i = 0; i < this.catTitlesBBoxes.length; ++i) { for(j = 0; j < data.length; ++j) { if(this.catTitlesBBoxes[i].checkIntersection(data[j])) return true; } } } return false; }; CChartSpace.prototype.rebuildSeries = function(data) { if( this.checkIntersectionChangedRange(data)) { AscFormat.ExecuteNoHistory(function(){ this.checkRemoveCache(); this.recalculateReferences(); this.recalcInfo.recalculateReferences = false; // this.recalculate(); }, this, []) } }; CChartSpace.prototype.checkRemoveCache = function() { this.handleUpdateInternalChart(); this.recalcInfo.recalculateReferences = true; this.checkSeriesRefs(this.clearCacheVal); }; CChartSpace.prototype.getTypeSubType = function() { var type = null, subtype = null; if(this.chart && this.chart.plotArea && this.chart.plotArea.charts[0]) { switch (this.chart.plotArea.charts[0].getObjectType()) { case AscDFH.historyitem_type_LineChart: { type = c_oAscChartType.line; break; } case AscDFH.historyitem_type_AreaChart: { type = c_oAscChartType.area; break; } case AscDFH.historyitem_type_DoughnutChart: { type = c_oAscChartType.doughnut; break; } case AscDFH.historyitem_type_PieChart: { type = c_oAscChartType.pie; break; } case AscDFH.historyitem_type_ScatterChart: { type = c_oAscChartType.scatter; break; } case AscDFH.historyitem_type_StockChart: { type = c_oAscChartType.stock; break; } case AscDFH.historyitem_type_BarChart: { if(this.chart.plotArea.charts[0].barDir === AscFormat.BAR_DIR_BAR) type = c_oAscChartType.hbar; else type = c_oAscChartType.bar; break; } } if(AscFormat.isRealNumber(this.chart.plotArea.charts[0].grouping)) { if(!this.chart.plotArea.charts[0].getObjectType() === AscDFH.historyitem_type_BarChart) { switch(this.chart.plotArea.charts[0].grouping) { case AscFormat.GROUPING_STANDARD: { subtype = c_oAscChartSubType.normal; break; } case AscFormat.GROUPING_STACKED: { subtype = c_oAscChartSubType.stacked; break; } case AscFormat.GROUPING_PERCENT_STACKED: { subtype = c_oAscChartSubType.stackedPer; break; } } } else { switch(this.chart.plotArea.charts[0].grouping) { case AscFormat.BAR_GROUPING_CLUSTERED: case AscFormat.BAR_GROUPING_STANDARD: { subtype = c_oAscChartSubType.normal; break; } case AscFormat.BAR_GROUPING_STACKED: { subtype = c_oAscChartSubType.stacked; break; } case AscFormat.BAR_GROUPING_PERCENT_STACKED: { subtype = c_oAscChartSubType.stackedPer; break; } } } } } return {type: type, subtype: subtype}; }; CChartSpace.prototype.clearFormatting = function(bNoClearShapeProps) { if(this.spPr && !(bNoClearShapeProps === true)) { this.spPr.Fill && this.spPr.setFill(null); this.spPr.ln && this.spPr.setLn(null); } if(this.chart) { if(this.chart.plotArea) { if(this.chart.plotArea.spPr) { this.chart.plotArea.spPr.Fill && this.chart.plotArea.spPr.setFill(null); this.chart.plotArea.spPr.ln && this.chart.plotArea.spPr.setLn(null); } var i, j, k, series, pts, chart, ser; for(i = this.chart.plotArea.charts.length-1; i > -1; --i) { chart = this.chart.plotArea.charts[i]; if(chart.upDownBars /*&& chart.getObjectType() !== AscDFH.historyitem_type_StockChart*/) { if(chart.upDownBars.upBars) { if(chart.upDownBars.upBars.Fill) { chart.upDownBars.upBars.setFill(null); } if(chart.upDownBars.upBars.ln) { chart.upDownBars.upBars.setLn(null); } } if(chart.upDownBars.downBars) { if(chart.upDownBars.downBars.Fill) { chart.upDownBars.downBars.setFill(null); } if(chart.upDownBars.downBars.ln) { chart.upDownBars.downBars.setLn(null); } } } series = chart.series; for(j = series.length - 1; j > -1; --j) { ser = series[j]; if(ser.spPr && chart.getObjectType() !== AscDFH.historyitem_type_StockChart) { if(ser.spPr.Fill) { ser.spPr.setFill(null); } if(ser.spPr.ln) { ser.spPr.setLn(null); } } AscFormat.removeDPtsFromSeries(ser) } } } } }; CChartSpace.prototype.remove = function() { if(this.selection.title) { if(this.selection.title.parent) { this.selection.title.parent.setTitle(null); } } else if(this.selection.legend) { if(!AscFormat.isRealNumber(this.selection.legendEntry)) { if(this.selection.legend.parent && this.selection.legend.parent.setLegend) { this.selection.legend.parent.setLegend(null); } } else { var entry = this.selection.legend.findLegendEntryByIndex(this.selection.legendEntry); if(!entry) { entry = new AscFormat.CLegendEntry(); entry.setIdx(this.selection.legendEntry); this.selection.legend.addLegendEntry(entry); } entry.setDelete(true); } } else if(this.selection.axisLbls) { if(this.selection.axisLbls && this.selection.axisLbls.setDelete) { this.selection.axisLbls.setDelete(true); } } else if(AscFormat.isRealNumber(this.selection.dataLbls)) { var ser = this.chart.plotArea.charts[0].series[this.selection.dataLbls]; if(ser) { var oDlbls = ser.dLbls; if(!ser.dLbls) { if(this.chart.plotArea.charts[0].dLbls) { oDlbls = this.chart.plotArea.charts[0].dLbls.createDuplicate(); } else { oDlbls = new AscFormat.CDLbls(); } ser.setDLbls(oDlbls); } if(!AscFormat.isRealNumber(this.selection.dataLbl)) { oDlbls.setDelete(true); } else { var pts = AscFormat.getPtsFromSeries(ser); var pt = pts[this.selection.dataLbl]; if(pt) { var dLbl = ser.dLbls.findDLblByIdx(pt.idx); if(!dLbl) { dLbl = new AscFormat.CDLbl(); dLbl.setIdx(pt.idx); if(ser.dLbls.txPr) { dLbl.merge(ser.dLbls); } ser.dLbls.addDLbl(dLbl); } dLbl.setDelete(true); } } } } this.selection.title = null; this.selection.legend = null; this.selection.legendEntry = null; this.selection.axisLbls = null; this.selection.dataLbls = null; this.selection.dataLbl = null; this.selection.plotArea = null; this.selection.rotatePlotArea = null; this.selection.gridLine = null; this.selection.series = null; this.selection.datPoint = null; this.selection.textSelection = null; }; CChartSpace.prototype.copy = function(drawingDocument) { var copy = new CChartSpace(); if(this.chart) { copy.setChart(this.chart.createDuplicate(drawingDocument)); } if(this.clrMapOvr) { copy.setClrMapOvr(this.clrMapOvr.createDuplicate()); } copy.setDate1904(this.date1904); if(this.externalData) { copy.setExternalData(this.externalData.createDuplicate()); } copy.setLang(this.lang); if(this.pivotSource) { copy.setPivotSource(this.pivotSource.createDuplicate()); } if(this.printSettings) { copy.setPrintSettings(this.printSettings.createDuplicate()); } if(this.protection) { copy.setProtection(this.protection.createDuplicate()); } copy.setRoundedCorners(this.roundedCorners); if(this.spPr) { copy.setSpPr(this.spPr.createDuplicate()); copy.spPr.setParent(copy); } copy.setStyle(this.style); if(this.txPr) { copy.setTxPr(this.txPr.createDuplicate(drawingDocument)) } copy.setUserShapes(this.userShapes); copy.setThemeOverride(this.themeOverride); copy.setBDeleted(this.bDeleted); copy.setLocks(this.locks); copy.cachedImage = this.getBase64Img(); copy.cachedPixH = this.cachedPixH; copy.cachedPixW = this.cachedPixW; if(this.fromSerialize) { copy.setBFromSerialize(true); } return copy; }; CChartSpace.prototype.convertToWord = function(document) { this.setBDeleted(true); var oCopy = this.copy(); oCopy.setBDeleted(false); return oCopy; }; CChartSpace.prototype.convertToPPTX = function(drawingDocument, worksheet) { var copy = this.copy(drawingDocument); copy.setBDeleted(false); copy.setWorksheet(worksheet); copy.setParent(null); return copy; }; CChartSpace.prototype.rebuildSeriesFromAsc = function(asc_chart) { if(this.chart && this.chart.plotArea && this.chart.plotArea.charts[0]) { var asc_series = asc_chart.series; var chart_type = this.chart.plotArea.charts[0]; var first_series = chart_type.series[0] ? chart_type.series[0] : chart_type.getSeriesConstructor(); var bAccent1Background = false; if(this.spPr && this.spPr.Fill && this.spPr.Fill.fill && this.spPr.Fill.fill.color && this.spPr.Fill.fill.color.color && this.spPr.Fill.fill.color.color.type === window['Asc'].c_oAscColor.COLOR_TYPE_SCHEME && this.spPr.Fill.fill.color.color.id === 0){ bAccent1Background = true; } var oFirstSpPrPreset = 0; if(chart_type.getObjectType() === AscDFH.historyitem_type_PieChart || chart_type.getObjectType() === AscDFH.historyitem_type_DoughnutChart){ if(chart_type.series[0].dPt[0] && chart_type.series[0].dPt[0].spPr){ oFirstSpPrPreset = AscFormat.CollectSettingsSpPr(chart_type.series[0].dPt[0].spPr); } } else{ oFirstSpPrPreset = AscFormat.CollectSettingsSpPr(chart_type.series[0].spPr); } if(first_series.spPr){ first_series.spPr.setFill(null); first_series.spPr.setLn(null); } var style = AscFormat.CHART_STYLE_MANAGER.getStyleByIndex(this.style); var base_fills = AscFormat.getArrayFillsFromBase(style.fill2, asc_series.length); if(chart_type.getObjectType() !== AscDFH.historyitem_type_ScatterChart) { if(asc_series.length < chart_type.series.length){ for(var i = chart_type.series.length - 1; i >= asc_series.length; --i){ chart_type.removeSeries(i); } } for(var i = 0; i < asc_series.length; ++i) { var series = null, bNeedAdd = false; if(chart_type.series[i]) { series = chart_type.series[i]; } else { bNeedAdd = true; series = first_series.createDuplicate(); } series.setIdx(i); series.setOrder(i); series.setVal(new AscFormat.CYVal()); FillValNum(series.val, asc_series[i].Val, true, false); if(chart_type.getObjectType() === AscDFH.historyitem_type_PieChart || chart_type.getObjectType() === AscDFH.historyitem_type_DoughnutChart){ if(oFirstSpPrPreset){ var pts = AscFormat.getPtsFromSeries(series); for(var j = 0; j < pts.length; ++j){ var oDPt = new AscFormat.CDPt(); oDPt.setBubble3D(false); oDPt.setIdx(j); AscFormat.ApplySpPr(oFirstSpPrPreset, oDPt, j, base_fills, bAccent1Background); series.series[i].addDPt(oDPt); } } } else{ AscFormat.ApplySpPr(oFirstSpPrPreset, series, i, base_fills, bAccent1Background); } if(asc_series[i].Cat && asc_series[i].Cat.NumCache && typeof asc_series[i].Cat.Formula === "string" && asc_series[i].Cat.Formula.length > 0) { series.setCat(new AscFormat.CCat()); FillCatStr(series.cat, asc_series[i].Cat, true, false); } else { series.setCat(null); } if(asc_series[i].TxCache && typeof asc_series[i].TxCache.Formula === "string" && asc_series[i].TxCache.Formula.length > 0) { FillSeriesTx(series, asc_series[i].TxCache, true, false); } else { series.setTx(null); } if(bNeedAdd) { chart_type.addSer(series); } } } else { for(var i = chart_type.series.length - 1; i > -1; --i){ chart_type.removeSeries(i); } var oXVal; var start_index = 0; var minus = 0; if(asc_series[0].xVal && asc_series[0].xVal.NumCache && typeof asc_series[0].xVal.Formula === "string" && asc_series[0].xVal.Formula.length > 0) { oXVal = new AscFormat.CXVal(); FillCatStr(oXVal, asc_series[0].xVal, true, false); } else if(asc_series[0].Cat && asc_series[0].Cat.NumCache && typeof asc_series[0].Cat.Formula === "string" && asc_series[0].Cat.Formula.length > 0) { oXVal = new AscFormat.CXVal(); FillCatStr(oXVal, asc_series[0].Cat, true, false); } for(var i = start_index; i < asc_series.length; ++i) { var series = new AscFormat.CScatterSeries(); series.setIdx(i - minus); series.setOrder(i - minus); AscFormat.ApplySpPr(oFirstSpPrPreset, series, i, base_fills, bAccent1Background); if(oXVal) { series.setXVal(oXVal.createDuplicate()); } series.setYVal(new AscFormat.CYVal()); FillValNum(series.yVal, asc_series[i].Val, true, false); if(asc_series[i].TxCache && typeof asc_series[i].TxCache.Formula === "string" && asc_series[i].TxCache.Formula.length > 0) { FillSeriesTx(series, asc_series[i].TxCache, true, false); } chart_type.addSer(series); } } this.recalculateReferences(); } }; CChartSpace.prototype.Write_ToBinary2 = function (w) { w.WriteLong(this.getObjectType()); w.WriteString2(this.Id); }; CChartSpace.prototype.Read_FromBinary2 = function (r) { this.Id = r.GetString2(); }; CChartSpace.prototype.handleUpdateType = function() { if(this.bNoHandleRecalc === true) { return; } this.recalcInfo.recalculateChart = true; this.recalcInfo.recalculateSeriesColors = true; this.recalcInfo.recalculateMarkers = true; this.recalcInfo.recalculateGridLines = true; this.recalcInfo.recalculateDLbls = true; this.recalcInfo.recalculateAxisLabels = true; //this.recalcInfo.dataLbls.length = 0; //this.recalcInfo.axisLabels.length = 0; this.recalcInfo.recalculateAxisVal = true; this.recalcInfo.recalculateAxisTickMark = true; this.recalcInfo.recalculateHiLowLines = true; this.recalcInfo.recalculateUpDownBars = true; this.recalcInfo.recalculateLegend = true; this.recalcInfo.recalculateReferences = true; this.recalcInfo.recalculateBBox = true; this.recalcInfo.recalculateFormulas = true; this.chartObj = null; this.addToRecalculate(); }; CChartSpace.prototype.handleUpdateInternalChart = function() { if(this.bNoHandleRecalc === true) { return; } this.recalcInfo.recalculateChart = true; this.recalcInfo.recalculateSeriesColors = true; this.recalcInfo.recalculateDLbls = true; this.recalcInfo.recalculateAxisLabels = true; this.recalcInfo.recalculateMarkers = true; this.recalcInfo.recalculatePlotAreaBrush = true; this.recalcInfo.recalculatePlotAreaPen = true; this.recalcInfo.recalculateAxisTickMark = true; //this.recalcInfo.dataLbls.length = 0; //this.recalcInfo.axisLabels.length = 0; this.recalcInfo.recalculateAxisVal = true; this.recalcInfo.recalculateLegend = true; this.recalcInfo.recalculateBBox = true; this.chartObj = null; this.addToRecalculate(); }; CChartSpace.prototype.handleUpdateGridlines = function() { this.recalcInfo.recalculateGridLines = true; this.addToRecalculate(); }; CChartSpace.prototype.handleUpdateDataLabels = function() { this.recalcInfo.recalculateDLbls = true; this.addToRecalculate(); }; CChartSpace.prototype.updateChildLabelsTransform = function(posX, posY) { if(this.localTransformText) { this.transformText = this.localTransformText.CreateDublicate(); global_MatrixTransformer.TranslateAppend(this.transformText, posX, posY); this.invertTransformText = global_MatrixTransformer.Invert(this.transformText); } if(this.chart) { if(this.chart.plotArea) { var aCharts = this.chart.plotArea.charts; for(var t = 0; t < aCharts.length; ++t){ var oChart = aCharts[t]; var series = oChart.series; for(var i = 0; i < series.length; ++i) { var ser = series[i]; var pts = AscFormat.getPtsFromSeries(ser); for(var j = 0; j < pts.length; ++j) { if(pts[j].compiledDlb) { pts[j].compiledDlb.updatePosition(posX, posY); } } } } var aAxes = this.chart.plotArea.axId; for(var i = 0; i < aAxes.length; ++i){ var oAxis = aAxes[i]; if(oAxis){ if(oAxis.title){ oAxis.title.updatePosition(posX, posY); } if(oAxis.labels){ oAxis.labels.updatePosition(posX, posY); } } } } if(this.chart.title) { this.chart.title.updatePosition(posX, posY); } if(this.chart.legend) { this.chart.legend.updatePosition(posX, posY); } } }; CChartSpace.prototype.recalcTitles = function() { if(this.chart && this.chart.title) { this.chart.title.recalcInfo.recalculateContent = true; this.chart.title.recalcInfo.recalcTransform = true; this.chart.title.recalcInfo.recalcTransformText = true; } if(this.chart && this.chart.plotArea) { var hor_axis = this.chart.plotArea.getHorizontalAxis(); if(hor_axis && hor_axis.title) { hor_axis.title.recalcInfo.recalculateContent = true; hor_axis.title.recalcInfo.recalcTransform = true; hor_axis.title.recalcInfo.recalcTransformText = true; } var vert_axis = this.chart.plotArea.getVerticalAxis(); if(vert_axis && vert_axis.title) { vert_axis.title.recalcInfo.recalculateContent = true; vert_axis.title.recalcInfo.recalcTransform = true; vert_axis.title.recalcInfo.recalcTransformText = true; } } }; CChartSpace.prototype.recalcTitles2 = function() { if(this.chart && this.chart.title) { this.chart.title.recalcInfo.recalculateContent = true; this.chart.title.recalcInfo.recalcTransform = true; this.chart.title.recalcInfo.recalcTransformText = true; this.chart.title.recalcInfo.recalculateTxBody = true; } if(this.chart && this.chart.plotArea) { var hor_axis = this.chart.plotArea.getHorizontalAxis(); if(hor_axis && hor_axis.title) { hor_axis.title.recalcInfo.recalculateContent = true; hor_axis.title.recalcInfo.recalcTransform = true; hor_axis.title.recalcInfo.recalcTransformText = true; hor_axis.title.recalcInfo.recalculateTxBody = true; } var vert_axis = this.chart.plotArea.getVerticalAxis(); if(vert_axis && vert_axis.title) { vert_axis.title.recalcInfo.recalculateContent = true; vert_axis.title.recalcInfo.recalcTransform = true; vert_axis.title.recalcInfo.recalcTransformText = true; vert_axis.title.recalcInfo.recalculateTxBody = true; } } }; CChartSpace.prototype.Refresh_RecalcData2 = function(pageIndex, object) { if(object && object.getObjectType && object.getObjectType() === AscDFH.historyitem_type_Title && this.selection.title === object) { this.recalcInfo.recalcTitle = object; } else { var bOldRecalculateRef = this.recalcInfo.recalculateReferences; this.setRecalculateInfo(); this.recalcInfo.recalculateReferences = bOldRecalculateRef; } this.addToRecalculate(); }; CChartSpace.prototype.Refresh_RecalcData = function(data) { switch(data.Type) { case AscDFH.historyitem_ChartSpace_SetStyle: { this.handleUpdateStyle(); break; } case AscDFH.historyitem_ChartSpace_SetTxPr: { this.recalcInfo.recalculateChart = true; this.recalcInfo.recalculateLegend = true; this.recalcInfo.recalculateDLbls = true; this.recalcInfo.recalculateAxisVal = true; this.recalcInfo.recalculateAxisCat = true; this.recalcInfo.recalculateAxisLabels = true; this.addToRecalculate(); break; } case AscDFH.historyitem_ChartSpace_SetChart: { this.handleUpdateType(); break; } case AscDFH.historyitem_ShapeSetBDeleted:{ if(!this.bDeleted){ this.handleUpdateType(); } break; } } }; CChartSpace.prototype.getObjectType = function() { return AscDFH.historyitem_type_ChartSpace; }; CChartSpace.prototype.getAllRasterImages = function(images) { if(this.spPr) { this.spPr.checkBlipFillRasterImage(images); } var chart = this.chart; if(chart) { chart.backWall && chart.backWall.spPr && chart.backWall.spPr.checkBlipFillRasterImage(images); chart.floor && chart.floor.spPr && chart.floor.spPr.checkBlipFillRasterImage(images); chart.legend && chart.legend.spPr && chart.legend.spPr.checkBlipFillRasterImage(images); chart.sideWall && chart.sideWall.spPr && chart.sideWall.spPr.checkBlipFillRasterImage(images); chart.title && chart.title.spPr && chart.title.spPr.checkBlipFillRasterImage(images); //plotArea var plot_area = this.chart.plotArea; if(plot_area) { plot_area.spPr && plot_area.spPr.checkBlipFillRasterImage(images); var i; for(i = 0; i < plot_area.axId.length; ++i) { var axis = plot_area.axId[i]; if(axis) { axis.spPr && axis.spPr.checkBlipFillRasterImage(images); axis.title && axis.title && axis.title.spPr && axis.title.spPr.checkBlipFillRasterImage(images); } } for(i = 0; i < plot_area.charts.length; ++i) { plot_area.charts[i].getAllRasterImages(images); } } } }; CChartSpace.prototype.getAllContents = function() { }; CChartSpace.prototype.getAllFonts = function (allFonts) { this.documentGetAllFontNames(allFonts); }; CChartSpace.prototype.documentGetAllFontNames = function(allFonts) { allFonts["+mn-lt"] = 1; allFonts["+mn-ea"] = 1; allFonts["+mn-cs"] = 1; checkTxBodyDefFonts(allFonts, this.txPr); var chart = this.chart, i; if(chart) { for(i = 0; i < chart.pivotFmts.length; ++i) { chart.pivotFmts[i] && checkTxBodyDefFonts(allFonts, chart.pivotFmts[i].txPr); } if(chart.legend) { checkTxBodyDefFonts(allFonts, chart.legend.txPr); for(i = 0; i < chart.legend.legendEntryes.length; ++i) { chart.legend.legendEntryes[i] && checkTxBodyDefFonts(allFonts, chart.legend.legendEntryes[i].txPr); } } if(chart.title) { checkTxBodyDefFonts(allFonts, chart.title.txPr); if(chart.title.tx && chart.title.tx.rich) { checkTxBodyDefFonts(allFonts, chart.title.tx.rich); chart.title.tx.rich.content && chart.title.tx.rich.content.Document_Get_AllFontNames(allFonts); } } var plot_area = chart.plotArea; if(plot_area) { for(i = 0; i < plot_area.charts.length; ++i) { plot_area.charts[i] && plot_area.charts[i].documentCreateFontMap(allFonts);/*TODO надо бы этот метод переименовать чтоб название не вводило в заблуждение*/ } var cur_axis; for(i = 0; i < plot_area.axId.length; ++i) { cur_axis = plot_area.axId[i]; checkTxBodyDefFonts(allFonts, cur_axis.txPr); if(cur_axis.title) { checkTxBodyDefFonts(allFonts, cur_axis.title.txPr); if(cur_axis.title.tx && cur_axis.title.tx.rich) { checkTxBodyDefFonts(allFonts, cur_axis.title.tx.rich); cur_axis.title.tx.rich.content && cur_axis.title.tx.rich.content.Document_Get_AllFontNames(allFonts); } } } } } }; CChartSpace.prototype.documentCreateFontMap = function(allFonts) { if(this.chart) { this.chart.title && this.chart.title.txBody && this.chart.title.txBody.content.Document_CreateFontMap(allFonts); var i, j, k; if(this.chart.legend) { var calc_entryes = this.chart.legend.calcEntryes; for(i = 0; i < calc_entryes.length; ++i) { calc_entryes[i].txBody.content.Document_CreateFontMap(allFonts); } } var axis = this.chart.plotArea.axId, cur_axis; for(i = axis.length-1; i > -1 ; --i) { cur_axis = axis[i]; if(cur_axis) { cur_axis && cur_axis.title && cur_axis.title.txBody && cur_axis.title.txBody.content.Document_CreateFontMap(allFonts); if(cur_axis.labels) { for(j = cur_axis.labels.aLabels.length - 1; j > -1; --j) { cur_axis.labels.aLabels[j] && cur_axis.labels.aLabels[j].txBody && cur_axis.labels.aLabels[j].txBody.content.Document_CreateFontMap(allFonts); } } } } var series, pts; for(i = this.chart.plotArea.charts.length-1; i > -1; --i) { series = this.chart.plotArea.charts[i].series; for(j = series.length -1; j > -1; --j) { pts = AscFormat.getPtsFromSeries(series[i]); if(Array.isArray(pts)) { for(k = pts.length - 1; k > -1; --k) { pts[k].compiledDlb && pts[k].compiledDlb.txBody && pts[k].compiledDlb.txBody.content.Document_CreateFontMap(allFonts); } } } } } }; CChartSpace.prototype.setThemeOverride = function(pr) { History.Add(new CChangesDrawingsObject(this, AscDFH.historyitem_ChartSpace_SetThemeOverride, this.themeOverride, pr)); this.themeOverride = pr; }; CChartSpace.prototype.setParent = function (parent) { History.Add(new CChangesDrawingsObject(this, AscDFH.historyitem_ChartSpace_SetParent, this.parent, parent )); this.parent = parent; }; CChartSpace.prototype.setChart = function(chart) { History.Add(new CChangesDrawingsObject(this, AscDFH.historyitem_ChartSpace_SetChart, this.chart, chart)); this.chart = chart; if(chart) { chart.setParent(this); } }; CChartSpace.prototype.setClrMapOvr = function(clrMapOvr) { History.Add(new CChangesDrawingsObject(this, AscDFH.historyitem_ChartSpace_SetClrMapOvr, this.clrMapOvr, clrMapOvr)); this.clrMapOvr = clrMapOvr; }; CChartSpace.prototype.setDate1904 = function(date1904) { History.Add(new CChangesDrawingsBool(this, AscDFH.historyitem_ChartSpace_SetDate1904, this.date1904, date1904)); this.date1904 = date1904; }; CChartSpace.prototype.setExternalData = function(externalData) { History.Add(new CChangesDrawingsObject(this, AscDFH.historyitem_ChartSpace_SetExternalData, this.externalData, externalData)); this.externalData = externalData; }; CChartSpace.prototype.setLang = function(lang) { History.Add(new CChangesDrawingsString(this, AscDFH.historyitem_ChartSpace_SetLang, this.lang, lang)); this.lang = lang; }; CChartSpace.prototype.setPivotSource = function(pivotSource) { History.Add(new CChangesDrawingsObject(this, AscDFH.historyitem_ChartSpace_SetPivotSource, this.pivotSource, pivotSource)); this.pivotSource = pivotSource; }; CChartSpace.prototype.setPrintSettings = function(printSettings) { History.Add(new CChangesDrawingsObject(this, AscDFH.historyitem_ChartSpace_SetPrintSettings, this.printSettings, printSettings)); this.printSettings = printSettings; }; CChartSpace.prototype.setProtection = function(protection) { History.Add(new CChangesDrawingsObject(this, AscDFH.historyitem_ChartSpace_SetProtection, this.protection, protection)); this.protection = protection; }; CChartSpace.prototype.setRoundedCorners = function(roundedCorners) { History.Add(new CChangesDrawingsBool(this, AscDFH.historyitem_ChartSpace_SetRoundedCorners, this.roundedCorners, roundedCorners)); this.roundedCorners = roundedCorners; }; CChartSpace.prototype.setSpPr = function(spPr) { History.Add(new CChangesDrawingsObject(this, AscDFH.historyitem_ChartSpace_SetSpPr, this.spPr, spPr)); this.spPr = spPr; }; CChartSpace.prototype.setStyle = function(style) { History.Add(new CChangesDrawingsLong(this, AscDFH.historyitem_ChartSpace_SetStyle, this.style, style)); this.style = style; this.handleUpdateStyle(); }; CChartSpace.prototype.setTxPr = function(txPr) { History.Add(new CChangesDrawingsObject(this, AscDFH.historyitem_ChartSpace_SetTxPr, this.txPr, txPr)); this.txPr = txPr; if(txPr) { txPr.setParent(this); } }; CChartSpace.prototype.setUserShapes = function(userShapes) { History.Add(new CChangesDrawingsString(this, AscDFH.historyitem_ChartSpace_SetUserShapes, this.userShapes, userShapes)); this.userShapes = userShapes; }; CChartSpace.prototype.getTransformMatrix = function() { return this.transform; }; CChartSpace.prototype.canRotate = function() { return false; }; CChartSpace.prototype.drawAdjustments = function() {}; CChartSpace.prototype.isChart = function() { return true; }; CChartSpace.prototype.isShape = function() { return false; }; CChartSpace.prototype.isImage = function() { return false; }; CChartSpace.prototype.isGroup = function() { return false; }; CChartSpace.prototype.isPlaceholder = CShape.prototype.isPlaceholder; CChartSpace.prototype.setGroup = function (group) { History.Add(new CChangesDrawingsObject(this, AscDFH.historyitem_ChartSpace_SetGroup, this.group, group )); this.group = group; }; CChartSpace.prototype.getBase64Img = CShape.prototype.getBase64Img; CChartSpace.prototype.getRangeObjectStr = function() { if(this.recalcInfo.recalculateBBox) { this.recalculateBBox(); this.recalcInfo.recalculateBBox = false; } var ret = {range: null, bVert: null}; if(this.bbox && this.bbox.seriesBBox) { var r1 = this.bbox.seriesBBox.r1, r2 = this.bbox.seriesBBox.r2, c1 = this.bbox.seriesBBox.c1, c2 = this.bbox.seriesBBox.c2; ret.bVert = this.bbox.seriesBBox.bVert; if(this.bbox.seriesBBox.bVert) { if(this.bbox.catBBox) { if(r1 > 0) { --r1; } } if(this.bbox.serBBox) { if(c1 > 0) { --c1; } } } else { if(this.bbox.catBBox) { if(c1 > 0) { --c1; } } if(this.bbox.serBBox) { if(r1 > 0) { --r1; } } } var startCell = new CellAddress(r1, c1, 0); var endCell = new CellAddress(r2, c2, 0); var sStartCellId, sEndCellId; if (this.bbox.worksheet) { sStartCellId = startCell.getIDAbsolute(); sEndCellId = endCell.getIDAbsolute(); ret.range = parserHelp.get3DRef(this.bbox.worksheet.sName, sStartCellId === sEndCellId ? sStartCellId : sStartCellId + ':' + sEndCellId); } } return ret; }; CChartSpace.prototype.recalculateBBox = function() { this.bbox = null; this.seriesBBoxes = []; this.seriesTitlesBBoxes = []; this.catTitlesBBoxes = []; var series_bboxes = [], cat_bboxes = [], ser_titles_bboxes = []; var series_sheet, cur_bbox, parsed_formulas; if(this.chart && this.chart.plotArea && this.chart.plotArea && this.worksheet) { var series = []; var aCharts = this.chart.plotArea.charts; for(var i = 0; i < aCharts.length; ++i){ series = series.concat(aCharts[i].series); } series.sort(function(a, b){ return a.idx - b.idx; }); if(Array.isArray(series) && series.length > 0) { var series_title_f = [], cat_title_f, series_f = [], i, range1; var ref; var b_vert/*флаг означает, что значения в серии идут по горизонтали, а сами серии по вертикали сверху вниз*/ , b_titles_vert; var first_series_sheet; for(i = 0; i < series.length; ++i) { var numRef = null; if(series[i].val) numRef = series[i].val.numRef; else if(series[i].yVal) numRef = series[i].yVal.numRef; if(numRef) { parsed_formulas = this.parseChartFormula(numRef.f); if(parsed_formulas && parsed_formulas.length > 0 && parsed_formulas[0].worksheet) { series_bboxes = series_bboxes.concat(parsed_formulas); if(series_f !== null && parsed_formulas.length === 1) { series_sheet = parsed_formulas[0].worksheet; if(!first_series_sheet) first_series_sheet = series_sheet; if(series_sheet !== first_series_sheet) series_f = null; if(parsed_formulas[0].bbox) { cur_bbox = parsed_formulas[0].bbox; if(cur_bbox.r1 !== cur_bbox.r2 && cur_bbox.c1 !== cur_bbox.c2) series_f = null; if(series_f && series_f.length > 0) { if(!AscFormat.isRealBool(b_vert)) { if(series_f[0].c1 === cur_bbox.c1 && series_f[0].c2 === cur_bbox.c2) { b_vert = true; } else if(series_f[0].r1 === cur_bbox.r1 && series_f[0].r2 === cur_bbox.r2) { b_vert = false; } else { series_f = null; } } else { if(b_vert) { if(!(series_f[0].c1 === cur_bbox.c1 && series_f[0].c2 === cur_bbox.c2)) { series_f = null; } } else { if(!(series_f[0].r1 === cur_bbox.r1 && series_f[0].r2 === cur_bbox.r2)) { series_f = null; } } } if(series_f) { if(b_vert ) { if(cur_bbox.r1 - series_f[series_f.length-1].r1 !== 1) series_f = null; } else { if(cur_bbox.c1 - series_f[series_f.length-1].c1 !== 1) series_f = null; } } } if(series_f !== null) series_f.push(cur_bbox); } else series_f = null; } } } else series_f = null; if(series[i].tx && series[i].tx.strRef) { parsed_formulas = this.parseChartFormula(series[i].tx.strRef.f); if(parsed_formulas && parsed_formulas.length > 0 && parsed_formulas[0].worksheet) { ser_titles_bboxes = ser_titles_bboxes.concat(parsed_formulas); } if(series_title_f !== null) { if(!parsed_formulas || parsed_formulas.length !== 1 || !parsed_formulas[0].worksheet) { series_title_f = null; continue; } var series_cat_sheet = parsed_formulas[0].worksheet; if(series_cat_sheet !== first_series_sheet) { series_title_f = null; continue; } cur_bbox = parsed_formulas[0].bbox; if(cur_bbox) { if(cur_bbox.r1 !== cur_bbox.r2 || cur_bbox.c1 !== cur_bbox.c2) { series_title_f = null; continue; } if(!AscFormat.isRealBool(b_titles_vert)) { if(series_title_f.length > 0) { if( cur_bbox.r1 - series_title_f[0].r1 === 1) b_titles_vert = true; else if(cur_bbox.c1 - series_title_f[0].c1 === 1) b_titles_vert = false; else { series_title_f = null; continue; } } } else { if(b_titles_vert) { if( cur_bbox.r1 - series_title_f[series_title_f.length-1].r1 !== 1) { series_title_f = null; continue; } } else { if( cur_bbox.c1 - series_title_f[series_title_f.length-1].c1 !== 1) { series_title_f = null; continue; } } } series_title_f.push(cur_bbox); } else { series_title_f = null; continue; } } } else { series_title_f = null; } } if(series[0].cat) { if(series[0].cat.strRef) { ref = series[0].cat.strRef; } else if(series[0].cat.numRef) { ref = series[0].cat.numRef; } } else if(series[0].xVal) { if(series[0].xVal.strRef) { ref = series[0].xVal.strRef; } else if(series[0].xVal.numRef) { ref = series[0].xVal.numRef; } } if(ref) { parsed_formulas = this.parseChartFormula(ref.f); if(parsed_formulas && parsed_formulas.length === 1 && parsed_formulas[0].worksheet) { cat_bboxes = cat_bboxes.concat(parsed_formulas); if(parsed_formulas.length === 1) { var cat_title_sheet = parsed_formulas[0].worksheet; if(cat_title_sheet === first_series_sheet) { if(parsed_formulas[0].bbox) { cat_title_f = parsed_formulas[0].bbox; } } } } } if(series_f !== null && series_f.length === 1) { if(series_f[0].r1 === series_f[0].r2 && series_f[0].c1 !== series_f[0].c2) { b_vert = true; } else if(series_f[0].c1 === series_f[0].c2 && series_f[0].r1 !== series_f[0].r2) { b_vert = false; } if(!AscFormat.isRealBool(b_vert) && Array.isArray(series_title_f) ) { if(series_f[0].r1 === series_f[0].r2 && series_title_f[0].r1 === series_f[0].r1) { b_vert = true; } else if(series_f[0].c1 === series_f[0].c2 && series_title_f[0].c1 === series_f[0].c1) { b_vert = false; } } if(!AscFormat.isRealBool(b_vert)) { if(cat_title_f) { if(series_f[0].r1 === series_f[0].r2 && cat_title_f.c1 === series_f[0].c1 && cat_title_f.c2 === series_f[0].c2) { b_vert = true; } else if(series_f[0].c1 === series_f[0].c2 && cat_title_f.r1 === series_f[0].r1 && cat_title_f.r2 === series_f[0].r2) { b_vert = false; } } if(!AscFormat.isRealBool(b_vert)) { b_vert = true; } } } if(series_f !== null && series_f.length > 0) { this.bbox = { seriesBBox: null, catBBox: null, serBBox: null, worksheet: first_series_sheet }; this.bbox.seriesBBox = { r1: series_f[0].r1, r2: series_f[series_f.length-1].r2, c1: series_f[0].c1, c2: series_f[series_f.length-1].c2, bVert: b_vert }; this.seriesBBoxes.push(new BBoxInfo(first_series_sheet, this.bbox.seriesBBox)); if(cat_title_f) { if(b_vert) { if(cat_title_f.c1 !== this.bbox.seriesBBox.c1 || cat_title_f.c2 !== this.bbox.seriesBBox.c2 || cat_title_f.r1 !== cat_title_f.r1) { cat_title_f = null; } } else { if(cat_title_f.c1 !== cat_title_f.c2 || cat_title_f.r1 !== this.bbox.seriesBBox.r1 || cat_title_f.r2 !== this.bbox.seriesBBox.r2) { cat_title_f = null; } } this.bbox.catBBox = cat_title_f; if(cat_title_f) { this.catTitlesBBoxes.push(new BBoxInfo(first_series_sheet, cat_title_f)); } } if(Array.isArray(series_title_f)) { this.bbox.serBBox = { r1: series_title_f[0].r1, r2: series_title_f[series_title_f.length-1].r2, c1: series_title_f[0].c1, c2: series_title_f[series_title_f.length-1].c2 }; this.seriesTitlesBBoxes.push(new BBoxInfo(first_series_sheet, this.bbox.serBBox)); } } else { for(i = 0; i < series_bboxes.length; ++i) { this.seriesBBoxes.push(new BBoxInfo(series_bboxes[i].worksheet, series_bboxes[i].bbox)); } for(i = 0; i < cat_bboxes.length; ++i) { this.catTitlesBBoxes.push(new BBoxInfo(cat_bboxes[i].worksheet, cat_bboxes[i].bbox)); } for(i = 0; i < ser_titles_bboxes.length; ++i) { this.seriesTitlesBBoxes.push(new BBoxInfo(ser_titles_bboxes[i].worksheet, ser_titles_bboxes[i].bbox)); } } } } }; CChartSpace.prototype.getCommonBBox = function() { if(this.recalcInfo.recalculateBBox) { this.recalculateBBox(); this.recalcInfo.recalculateBBox = false; } var oRet = null; if(this.bbox && this.bbox.seriesBBox && AscFormat.isRealBool(this.bbox.seriesBBox.bVert)) { oRet = {r1: this.bbox.seriesBBox.r1, r2: this.bbox.seriesBBox.r2, c1: this.bbox.seriesBBox.c1, c2: this.bbox.seriesBBox.c2}; if(this.bbox.seriesBBox.bVert) { if(this.bbox.catBBox ) { if(this.bbox.catBBox.r1 === this.bbox.catBBox.r2 && this.bbox.catBBox.r1 === this.bbox.seriesBBox.r1 - 1) { --oRet.r1; } else { oRet = null; } } if(oRet) { if(this.bbox.serBBox) { if(this.bbox.serBBox.c1 === this.bbox.serBBox.c2 && this.bbox.serBBox.c1 === this.bbox.seriesBBox.c1 - 1) { --oRet.c1; } else { oRet = null; } } } } else { if(this.bbox.catBBox ) { if(this.bbox.catBBox.c1 === this.bbox.catBBox.c2 && this.bbox.catBBox.c1 === this.bbox.seriesBBox.c1 - 1) { --oRet.c1; } else { oRet = null; } } if(oRet) { if(this.bbox.serBBox) { if(this.bbox.serBBox.r1 === this.bbox.serBBox.r2 && this.bbox.serBBox.r1 === this.bbox.seriesBBox.r1 - 1) { --oRet.r1; } else { oRet = null; } } } } } return oRet; }; CChartSpace.prototype.checkValByNumRef = function(workbook, ser, val, bVertical) { if(val && val.numRef && typeof val.numRef.f === "string"/*(!val.numRef.numCache || val.numRef.numCache.pts.length === 0)*/) { var aParsedRef = this.parseChartFormula(val.numRef.f); var num_cache; if(!val.numRef.numCache ) { num_cache = new AscFormat.CNumLit(); num_cache.setFormatCode("General"); } else { num_cache = val.numRef.numCache; removePtsFromLit(num_cache); } var lit_format_code = typeof num_cache.formatCode === "string" && num_cache.formatCode.length > 0 ? num_cache.formatCode : "General"; var pt_index = 0, i, j, cell, pt, hidden = true, row_hidden, col_hidden, nPtCount, t; for(i = 0; i < aParsedRef.length; ++i) { var oCurRef = aParsedRef[i]; var source_worksheet = oCurRef.worksheet; if(source_worksheet) { var range = oCurRef.bbox; var nLastNoEmptyIndex = null, dLastNoEmptyVal = null, aSpanPoints = [], nSpliceIndex = null; if(range.r1 === range.r2 || bVertical === true) { row_hidden = source_worksheet.getRowHidden(range.r1); for(j = range.c1; j <= range.c2; ++j) { if(!row_hidden && !source_worksheet.getColHidden(j) || (this.displayHidden === true)) { cell = source_worksheet.getCell3(range.r1, j); var sCellValue = cell.getValue(); var value = cell.getNumberValue(); if(!AscFormat.isRealNumber(value) && (!AscFormat.isRealNumber(this.displayEmptyCellsAs) || this.displayEmptyCellsAs === 1)){ var sVal = cell.getValueForEdit(); if((typeof sVal === "string") && sVal.length > 0){ value = 0; } } if(AscFormat.isRealNumber(value)) { hidden = false; pt = new AscFormat.CNumericPoint(); pt.setIdx(pt_index); pt.setVal(value); if(cell.getNumFormatStr() !== lit_format_code) { pt.setFormatCode(cell.getNumFormatStr()) } num_cache.addPt(pt); if(aSpanPoints.length > 0 ) { if(AscFormat.isRealNumber(nLastNoEmptyIndex)) { var oStartPoint = num_cache.getPtByIndex(nLastNoEmptyIndex); for(t = 0; t < aSpanPoints.length; ++t) { aSpanPoints[t].val = oStartPoint.val + ((pt.val - oStartPoint.val)/(aSpanPoints.length + 1))*(t+1); num_cache.pts.splice(nSpliceIndex + t, 0, aSpanPoints[t]); } } aSpanPoints.length = 0; } nLastNoEmptyIndex = pt_index; nSpliceIndex = num_cache.pts.length; dLastNoEmptyVal = pt.val; } else { if(AscFormat.isRealNumber(this.displayEmptyCellsAs) && this.displayEmptyCellsAs !== 1) { if(this.displayEmptyCellsAs === 2 || ((typeof sCellValue === "string") && sCellValue.length > 0)) { pt = new AscFormat.CNumericPoint(); pt.setIdx(pt_index); pt.setVal(0); num_cache.addPt(pt); if(aSpanPoints.length > 0 ) { if(AscFormat.isRealNumber(nLastNoEmptyIndex)) { var oStartPoint = num_cache.getPtByIndex(nLastNoEmptyIndex); for(t = 0; t < aSpanPoints.length; ++t) { aSpanPoints[t].val = oStartPoint.val + ((pt.val - oStartPoint.val)/(aSpanPoints.length + 1))*(t+1); num_cache.pts.splice(nSpliceIndex + t, 0, aSpanPoints[t]); } } aSpanPoints.length = 0; } nLastNoEmptyIndex = pt_index; nSpliceIndex = num_cache.pts.length; dLastNoEmptyVal = pt.val; } else if(this.displayEmptyCellsAs === 0 && ser.getObjectType() === AscDFH.historyitem_type_LineSeries) { pt = new AscFormat.CNumericPoint(); pt.setIdx(pt_index); pt.setVal(0); aSpanPoints.push(pt); } } } } pt_index++; } } else { col_hidden = source_worksheet.getColHidden(range.c1); for(j = range.r1; j <= range.r2; ++j) { if(!col_hidden && !source_worksheet.getRowHidden(j) || (this.displayHidden === true)) { cell = source_worksheet.getCell3(j, range.c1); var value = cell.getNumberValue(); var sCellValue = cell.getValue(); if(!AscFormat.isRealNumber(value) && !AscFormat.isRealNumber(this.displayEmptyCellsAs)){ var sVal = cell.getValueForEdit(); if((typeof sVal === "string") && sVal.length > 0){ value = 0; } } if(AscFormat.isRealNumber(value)) { hidden = false; pt = new AscFormat.CNumericPoint(); pt.setIdx(pt_index); pt.setVal(value); if(cell.getNumFormatStr() !== lit_format_code) { pt.setFormatCode(cell.getNumFormatStr()); } num_cache.addPt(pt); } else { if(AscFormat.isRealNumber(this.displayEmptyCellsAs) && this.displayEmptyCellsAs !== 1) { if(this.displayEmptyCellsAs === 2 || ((typeof sCellValue === "string") && sCellValue.length > 0)) { pt = new AscFormat.CNumericPoint(); pt.setIdx(pt_index); pt.setVal(0); num_cache.addPt(pt); if(aSpanPoints.length > 0 ) { if(AscFormat.isRealNumber(nLastNoEmptyIndex)) { var oStartPoint = num_cache.getPtByIndex(nLastNoEmptyIndex); for(t = 0; t < aSpanPoints.length; ++t) { aSpanPoints[t].val = oStartPoint.val + ((pt.val - oStartPoint.val)/(aSpanPoints.length + 1))*(t+1); num_cache.pts.splice(nSpliceIndex + t, 0, aSpanPoints[t]); } } aSpanPoints.length = 0; } nLastNoEmptyIndex = pt_index; nSpliceIndex = num_cache.pts.length; dLastNoEmptyVal = pt.val; } else if(this.displayEmptyCellsAs === 0 && ser.getObjectType() === AscDFH.historyitem_type_LineSeries) { pt = new AscFormat.CNumericPoint(); pt.setIdx(pt_index); pt.setVal(0); aSpanPoints.push(pt); } } } } pt_index++; } } } else{ pt_index = 0; var fCollectArray = function(oRef, oNumCache){ if(Array.isArray(oRef)){ for(var i = 0; i < oRef.length; ++i){ if(Array.isArray(oRef[i])){ fCollectArray(oRef[i], oNumCache); } else{ cell = source_worksheet.getCell3(j, range.c1); var value = cell.getNumberValue(); if(AscFormat.isRealNumber(value)) { hidden = false; pt = new AscFormat.CNumericPoint(); pt.setIdx(pt_index); pt.setVal(value); if(cell.getNumFormatStr() !== lit_format_code) { pt.setFormatCode(cell.getNumFormatStr()); } num_cache.addPt(pt); } } } } } for(j = 0; j < oCurRef.length; ++j){ for(var k = 0; k < oCurRef[j].length; ++k){ } } } } num_cache.setPtCount(pt_index); val.numRef.setNumCache(num_cache); if(!(val instanceof AscFormat.CCat)) { ser.isHidden = hidden; ser.isHiddenForLegend = hidden; } } }; CChartSpace.prototype.checkCatByNumRef = function(oThis, ser, cat, bVertical) { if(cat && cat.strRef && typeof cat.strRef.f === "string" /*(!cat.strRef.strCache || cat.strRef.strCache.pt.length === 0)*/) { var aParsedRef = this.parseChartFormula(cat.strRef.f); var str_cache = new AscFormat.CStrCache(); //str_cache.setFormatCode("General"); var pt_index = 0, i, j, cell, pt, value_width_format, row_hidden, col_hidden; var fParseTableDataString = function(oRef, oCache){ if(Array.isArray(oRef)){ for(var i = 0; i < oRef.length; ++i){ if(Array.isArray(oRef[i])){ fParseTableDataString(oRef, oCache); } else{ pt = new AscFormat.CStringPoint(); pt.setIdx(pt_index); pt.setVal(oRef[i].value); str_cache.addPt(pt); ++pt_index; } } } }; for(i = 0; i < aParsedRef.length; ++i) { var oCurRef = aParsedRef[i]; var source_worksheet = oCurRef.worksheet; if(source_worksheet) { var range = oCurRef.bbox; if(range.r1 === range.r2 || bVertical === true) { row_hidden = source_worksheet.getRowHidden(range.r1); for(j = range.c1; j <= range.c2; ++j) { if(!row_hidden && !source_worksheet.getColHidden(j)) { cell = source_worksheet.getCell3(range.r1, j); value_width_format = cell.getValueWithFormat(); if(typeof value_width_format === "string" && value_width_format.length > 0) { pt = new AscFormat.CStringPoint(); pt.setIdx(pt_index); pt.setVal(value_width_format); str_cache.addPt(pt); //addPointToMap(oThis.pointsMap, source_worksheet, range.r1, j, pt); } } pt_index++; } } else { col_hidden = source_worksheet.getColHidden(range.c1); for(j = range.r1; j <= range.r2; ++j) { if(!col_hidden && !source_worksheet.getRowHidden(j)) { cell = source_worksheet.getCell3(j, range.c1); value_width_format = cell.getValueWithFormat(); if(typeof value_width_format === "string" && value_width_format.length > 0) { pt = new AscFormat.CStringPoint(); pt.setIdx(pt_index); pt.setVal(cell.getValueWithFormat()); str_cache.addPt(pt); //addPointToMap(oThis.pointsMap, source_worksheet, j, range.c1, pt); } } pt_index++; } } } else{ fParseTableDataString(oCurRef); } } str_cache.setPtCount(pt_index); cat.strRef.setStrCache(str_cache); } }; CChartSpace.prototype.recalculateReferences = function() { var worksheet = this.worksheet; //this.pointsMap = {}; if(!worksheet) return; if(this.recalcInfo.recalculateBBox) { this.recalculateBBox(); this.recalcInfo.recalculateBBox = false; } var charts, series, i, j, ser; charts = this.chart.plotArea.charts; var bVert = undefined; if(this.bbox && this.bbox.seriesBBox && AscFormat.isRealBool(this.bbox.seriesBBox.bVert)) { bVert = this.bbox.seriesBBox.bVert; } for(i = 0; i < charts.length; ++i) { series = charts[i].series; var bHaveHidden = false, bHaveNoHidden = false; var bCheckFormatCode = false; if(charts[i].getObjectType() !== AscDFH.historyitem_type_ScatterChart) { for(j = 0; j < series.length; ++j) { ser = series[j]; //val this.checkValByNumRef(this.worksheet.workbook, ser, ser.val); //cat this.checkValByNumRef(this.worksheet.workbook, ser, ser.cat, bVert); this.checkCatByNumRef(this, ser, ser.cat, bVert); //tx this.checkCatByNumRef(this, ser, ser.tx, AscFormat.isRealBool(bVert) ? !bVert : undefined); if(ser.isHidden) { bHaveHidden = true; } else { bHaveNoHidden = true; if(!bCheckFormatCode && !((charts[i].getObjectType() === AscDFH.historyitem_type_BarChart && charts[i].grouping === AscFormat.BAR_GROUPING_PERCENT_STACKED) || (charts[i].getObjectType() !== AscDFH.historyitem_type_BarChart && charts[i].grouping === AscFormat.GROUPING_PERCENT_STACKED))){ bCheckFormatCode = true; var aAxId = charts[i].axId; if(aAxId){ for(var s = 0; s < aAxId.length; ++s){ if(aAxId[s].getObjectType() === AscDFH.historyitem_type_ValAx){ if(aAxId[s].numFmt && aAxId[s].numFmt.sourceLinked){ var aPoints = AscFormat.getPtsFromSeries(ser); if(aPoints[0] && typeof aPoints[0].formatCode === "string" && aPoints[0].formatCode.length > 0){ aAxId[s].numFmt.setFormatCode(aPoints[0].formatCode); } else{ aAxId[s].numFmt.setFormatCode("General"); } } } } } } } } } else { for(j = 0; j < series.length; ++j) { ser = series[j]; this.checkValByNumRef(this.worksheet.workbook, ser, ser.xVal, bVert); this.checkValByNumRef(this.worksheet.workbook, ser, ser.yVal); this.checkCatByNumRef(this, ser, ser.tx, AscFormat.isRealBool(bVert) ? !bVert : undefined); if(ser.isHidden) { bHaveHidden = true; } else { bHaveNoHidden = true; if(!bCheckFormatCode){ bCheckFormatCode = true; var aAxId = charts[i].axId; if(aAxId){ for(var s = 0; s < aAxId.length; ++s){ if(aAxId[s].getObjectType() === AscDFH.historyitem_type_ValAx){ if((aAxId[s].axPos === AscFormat.AX_POS_L || aAxId[s].axPos === AscFormat.AX_POS_R) && aAxId[s].numFmt && aAxId[s].numFmt.sourceLinked){ var aPoints = AscFormat.getPtsFromSeries(ser); if(aPoints[0] && typeof aPoints[0].formatCode === "string" && aPoints[0].formatCode.length > 0){ aAxId[s].numFmt.setFormatCode(aPoints[0].formatCode); } else{ aAxId[s].numFmt.setFormatCode("General"); } } } } } } } } } // if(bHaveHidden && bHaveNoHidden) // { // for(j = 0; j < series.length; ++j) // { // series[j].isHidden = false; // } // } } }; CChartSpace.prototype.checkEmptySeries = function() { var chart_type = this.chart.plotArea.charts[0]; var series = chart_type.series; var checkEmptyVal = function(val) { if(val.numRef) { if(!val.numRef.numCache) return true; if(val.numRef.numCache.pts.length === 0) return true; } else if(val.numLit) { if(val.numLit.pts.length === 0) return true; } else { return true; } return false; }; var nChartType = chart_type.getObjectType(); var nSeriesLength = (nChartType === AscDFH.historyitem_type_PieChart || nChartType === AscDFH.historyitem_type_DoughnutChart) ? 1 : series.length; for(var i = 0; i < nSeriesLength; ++i) { var ser = series[i]; if(ser.val) { if(!checkEmptyVal(ser.val)) return false; } if(ser.yVal) { if(!checkEmptyVal(ser.yVal)) return false; } } return true; }; CChartSpace.prototype.getNeedReflect = function() { if(!this.chartObj) { this.chartObj = new AscFormat.CChartsDrawer(); } return this.chartObj.calculatePositionLabelsCatAxFromAngle(this); }; CChartSpace.prototype.isChart3D = function(oChart){ var oOldFirstChart = this.chart.plotArea.charts[0]; this.chart.plotArea.charts[0] = oChart; var ret = AscFormat.CChartsDrawer.prototype._isSwitchCurrent3DChart(this); this.chart.plotArea.charts[0] = oOldFirstChart; return ret; }; CChartSpace.prototype.getAxisCrossType = function(oAxis){ if(oAxis.getObjectType() === AscDFH.historyitem_type_ValAx){ return AscFormat.CROSS_BETWEEN_MID_CAT; } var oCrossAxis = oAxis.crossAx; if(oCrossAxis && oCrossAxis.getObjectType() === AscDFH.historyitem_type_ValAx){ var oChart = this.chart.plotArea.getChartsForAxis(oCrossAxis)[0]; if(oChart){ var nChartType = oChart.getObjectType(); if(nChartType === AscDFH.historyitem_type_ScatterChart){ return null; } else if(nChartType !== AscDFH.historyitem_type_BarChart && (nChartType !== AscDFH.historyitem_type_PieChart && nChartType !== AscDFH.historyitem_type_DoughnutChart) || (nChartType === AscDFH.historyitem_type_BarChart && oChart.barDir !== AscFormat.BAR_DIR_BAR)){ if(oCrossAxis){ if(this.isChart3D(oChart)){ if(nChartType === AscDFH.historyitem_type_AreaChart || nChartType === AscDFH.historyitem_type_SurfaceChart ){ return AscFormat.isRealNumber(oCrossAxis.crossBetween) ? oCrossAxis.crossBetween : AscFormat.CROSS_BETWEEN_MID_CAT; } else if(nChartType === AscDFH.historyitem_type_LineChart){ return AscFormat.isRealNumber(oCrossAxis.crossBetween) ? oCrossAxis.crossBetween : AscFormat.CROSS_BETWEEN_BETWEEN; } else{ return AscFormat.CROSS_BETWEEN_BETWEEN; } } else{ return AscFormat.isRealNumber(oCrossAxis.crossBetween) ? oCrossAxis.crossBetween : ((nChartType === AscDFH.historyitem_type_AreaChart|| nChartType === AscDFH.historyitem_type_SurfaceChart ) ? AscFormat.CROSS_BETWEEN_MID_CAT : AscFormat.CROSS_BETWEEN_BETWEEN); } } } else if(nChartType === AscDFH.historyitem_type_BarChart && oChart.barDir === AscFormat.BAR_DIR_BAR){ return AscFormat.isRealNumber(oCrossAxis.crossBetween) && !this.isChart3D(oChart) ? oCrossAxis.crossBetween : AscFormat.CROSS_BETWEEN_BETWEEN; } } } switch(oAxis.getObjectType()){ case AscDFH.historyitem_type_ValAx:{ return AscFormat.CROSS_BETWEEN_MID_CAT; } case AscDFH.historyitem_type_CatAx: case AscDFH.historyitem_type_DateAx:{ return AscFormat.CROSS_BETWEEN_BETWEEN; } default:{ return AscFormat.CROSS_BETWEEN_BETWEEN; } } return AscFormat.CROSS_BETWEEN_BETWEEN; }; CChartSpace.prototype.getValAxisCrossType = function() { if(this.chart && this.chart.plotArea && this.chart.plotArea.charts[0]){ var chartType = this.chart.plotArea.charts[0].getObjectType(); var valAx = this.chart.plotArea.valAx; if(chartType === AscDFH.historyitem_type_ScatterChart){ return null; } else if(chartType !== AscDFH.historyitem_type_BarChart && (chartType !== AscDFH.historyitem_type_PieChart && chartType !== AscDFH.historyitem_type_DoughnutChart) || (chartType === AscDFH.historyitem_type_BarChart && this.chart.plotArea.charts[0].barDir !== AscFormat.BAR_DIR_BAR)){ if(valAx){ if(AscFormat.CChartsDrawer.prototype._isSwitchCurrent3DChart(this)){ if(chartType === AscDFH.historyitem_type_AreaChart || chartType === AscDFH.historyitem_type_SurfaceChart ){ return AscFormat.isRealNumber(valAx.crossBetween) ? valAx.crossBetween : AscFormat.CROSS_BETWEEN_MID_CAT; } else if(chartType === AscDFH.historyitem_type_LineChart){ return AscFormat.isRealNumber(valAx.crossBetween) ? valAx.crossBetween : AscFormat.CROSS_BETWEEN_BETWEEN; } else{ return AscFormat.CROSS_BETWEEN_BETWEEN; } } else{ return AscFormat.isRealNumber(valAx.crossBetween) ? valAx.crossBetween : ((chartType === AscDFH.historyitem_type_AreaChart|| chartType === AscDFH.historyitem_type_SurfaceChart ) ? AscFormat.CROSS_BETWEEN_MID_CAT : AscFormat.CROSS_BETWEEN_BETWEEN); } } } else if(chartType === AscDFH.historyitem_type_BarChart && this.chart.plotArea.charts[0].barDir === AscFormat.BAR_DIR_BAR){ if(valAx){ return AscFormat.isRealNumber(valAx.crossBetween) && !AscFormat.CChartsDrawer.prototype._isSwitchCurrent3DChart(this) ? valAx.crossBetween : AscFormat.CROSS_BETWEEN_BETWEEN; } } } return null; }; CChartSpace.prototype.calculatePosByLayout = function(fPos, nLayoutMode, fLayoutValue, fSize, fChartSize){ if(!AscFormat.isRealNumber(fLayoutValue)){ return fPos; } var fRetPos = 0; if(nLayoutMode === AscFormat.LAYOUT_MODE_EDGE){ fRetPos = fChartSize*fLayoutValue; } else{ fRetPos = fPos + fChartSize*fLayoutValue; } if(fRetPos < 0){ fRetPos = 0; } return fRetPos; }; CChartSpace.prototype.calculateSizeByLayout = function(fPos, fChartSize, fLayoutSize, fSizeMode ){ if(!AscFormat.isRealNumber(fLayoutSize)){ return -1; } var fRetSize = Math.min(fChartSize*fLayoutSize, fChartSize); if(fSizeMode === AscFormat.LAYOUT_MODE_EDGE){ fRetSize = fRetSize - fPos; } return fRetSize; }; CChartSpace.prototype.calculateLabelsPositions = function(b_recalc_labels, b_recalc_legend) { var layout; for(var i = 0; i < this.recalcInfo.dataLbls.length; ++i) { var series = this.getAllSeries(); if(this.recalcInfo.dataLbls[i].series && this.recalcInfo.dataLbls[i].pt) { var ser_idx = this.recalcInfo.dataLbls[i].series.idx; //сделаем проверку лежит ли серия с индексом this.recalcInfo.dataLbls[i].series.idx в сериях первой диаграммы for(var j = 0; j < series.length; ++j) { if(series[j].idx === this.recalcInfo.dataLbls[i].series.idx) { var bLayout = AscCommon.isRealObject(this.recalcInfo.dataLbls[i].layout) && (AscFormat.isRealNumber(this.recalcInfo.dataLbls[i].layout.x) || AscFormat.isRealNumber(this.recalcInfo.dataLbls[i].layout.y)); var pos = this.chartObj.reCalculatePositionText("dlbl", this, this.recalcInfo.dataLbls[i].series.idx, this.recalcInfo.dataLbls[i].pt.idx, bLayout);// var oLbl = this.recalcInfo.dataLbls[i]; if(oLbl.layout){ layout = oLbl.layout; if(AscFormat.isRealNumber(layout.x)){ pos.x = this.calculatePosByLayout(pos.x, layout.xMode, layout.x, this.recalcInfo.dataLbls[i].extX, this.extX); } if(AscFormat.isRealNumber(layout.y)){ pos.y = this.calculatePosByLayout(pos.y, layout.yMode, layout.y, this.recalcInfo.dataLbls[i].extY, this.extY); } } if(pos.x + oLbl.extX > this.extX){ pos.x -= (pos.x + oLbl.extX - this.extX); } if(pos.y + oLbl.extY > this.extY){ pos.y -= (pos.y + oLbl.extY - this.extY); } if(pos.x < 0){ pos.x = 0; } if(pos.y < 0){ pos.y = 0; } oLbl.setPosition(pos.x, pos.y); break; } } } } this.recalcInfo.dataLbls.length = 0; if(b_recalc_labels) { if(this.chart && this.chart.title) { var pos = this.chartObj.reCalculatePositionText("title", this, this.chart.title); if(this.chart.title.layout){ layout = this.chart.title.layout; if(AscFormat.isRealNumber(layout.x)){ pos.x = this.calculatePosByLayout(pos.x, layout.xMode, layout.x, this.chart.title.extX, this.extX); }if(AscFormat.isRealNumber(layout.y)){ pos.y = this.calculatePosByLayout(pos.y, layout.yMode, layout.y, this.chart.title.extY, this.extY); } } this.chart.title.setPosition(pos.x, pos.y); } if(this.chart && this.chart.plotArea) { var hor_axis = this.chart.plotArea.getHorizontalAxis(); if(hor_axis && hor_axis.title) { var old_cat_ax = this.chart.plotArea.catAx; this.chart.plotArea.catAx = hor_axis; var pos = this.chartObj.reCalculatePositionText("catAx", this, hor_axis.title); if(hor_axis.title.layout){ layout = hor_axis.title.layout; if(AscFormat.isRealNumber(layout.x)){ pos.x = this.calculatePosByLayout(pos.x, layout.xMode, layout.x, hor_axis.title.extX, this.extX); }if(AscFormat.isRealNumber(layout.y)){ pos.y = this.calculatePosByLayout(pos.y, layout.yMode, layout.y, hor_axis.title.extY, this.extY); } } hor_axis.title.setPosition(pos.x, pos.y); this.chart.plotArea.catAx = old_cat_ax; } var vert_axis = this.chart.plotArea.getVerticalAxis(); if(vert_axis && vert_axis.title) { var old_val_ax = this.chart.plotArea.valAx; this.chart.plotArea.valAx = vert_axis; var pos = this.chartObj.reCalculatePositionText("valAx", this, vert_axis.title); if(vert_axis.title.layout){ layout = vert_axis.title.layout; if(AscFormat.isRealNumber(layout.x)){ pos.x = this.calculatePosByLayout(pos.x, layout.xMode, layout.x, vert_axis.title.extX, this.extX); }if(AscFormat.isRealNumber(layout.y)){ pos.y = this.calculatePosByLayout(pos.y, layout.yMode, layout.y, vert_axis.title.extY, this.extY); } } vert_axis.title.setPosition(pos.x, pos.y); this.chart.plotArea.valAx = old_val_ax; } } } if(b_recalc_legend && this.chart && this.chart.legend) { var bResetLegendPos = false; if(!AscFormat.isRealNumber(this.chart.legend.legendPos)) { this.chart.legend.legendPos = Asc.c_oAscChartLegendShowSettings.bottom; bResetLegendPos = true; } var pos = this.chartObj.reCalculatePositionText("legend", this, this.chart.legend); if(this.chart.legend.layout){ layout = this.chart.legend.layout; if(AscFormat.isRealNumber(layout.x)){ pos.x = this.calculatePosByLayout(pos.x, layout.xMode, layout.x, this.chart.legend.extX, this.extX); }if(AscFormat.isRealNumber(layout.y)){ pos.y = this.calculatePosByLayout(pos.y, layout.yMode, layout.y, this.chart.legend.extY, this.extY); } } this.chart.legend.setPosition(pos.x, pos.y); if(bResetLegendPos) { this.chart.legend.legendPos = null; } } }; CChartSpace.prototype.getLabelsForAxis = function(oAxis){ var aStrings = []; var oPlotArea = this.chart.plotArea, i; switch(oAxis.getObjectType()){ case AscDFH.historyitem_type_DateAx: case AscDFH.historyitem_type_CatAx:{ //расчитаем подписи для горизонтальной оси var oSeries = oPlotArea.getSeriesWithSmallestIndexForAxis(oAxis); var nPtsLen = 0; oAxis.scale = []; ; if(oSeries && oSeries.cat) { var oLit; var oCat = oSeries.cat; if(oCat.strRef && oCat.strRef.strCache){ oLit = oCat.strRef.strCache; } else if(oCat.strLit){ oLit = oCat.strLit; } else if(oCat.numRef && oCat.numRef.numCache){ oLit = oCat.numRef.numCache; } else if(oCat.numLit){ oLit = oCat.numLit; } if(oLit){ var oLitFormat = null, oPtFormat = null; if(typeof oLit.formatCode === "string" && oLit.formatCode.length > 0){ oLitFormat = oNumFormatCache.get(oLit.formatCode); } nPtsLen = oLit.ptCount; var bTickSkip = AscFormat.isRealNumber(oAxis.tickLblSkip); var nTickLblSkip = AscFormat.isRealNumber(oAxis.tickLblSkip) ? oAxis.tickLblSkip : (nPtsLen < SKIP_LBL_LIMIT ? 1 : Math.floor(nPtsLen/SKIP_LBL_LIMIT)); for(i = 0; i < nPtsLen; ++i){ oAxis.scale.push(i); if(!bTickSkip || ((i % nTickLblSkip) === 0)){ var oPt = oLit.getPtByIndex(i); if(oPt){ var sPt; if(typeof oPt.formatCode === "string" && oPt.formatCode.length > 0){ oPtFormat = oNumFormatCache.get(oPt.formatCode); if(oPtFormat){ sPt = oPtFormat.formatToChart(oPt.val); } else{ sPt = oPt.val; } } else if(oLitFormat){ sPt = oLitFormat.formatToChart(oPt.val); } else{ sPt = oPt.val; } aStrings.push(sPt); } else{ aStrings.push(""); } } else{ aStrings.push(null); } } } } var nPtsLength = 0; var aChartsForAxis = oPlotArea.getChartsForAxis(oAxis); for(i = 0; i < aChartsForAxis.length; ++i){ var oChart = aChartsForAxis[i]; for(var j = 0; j < oChart.series.length; ++j){ var oCurPts = null; oSeries = oChart.series[j]; if(oSeries.val) { if(oSeries.val.numRef && oSeries.val.numRef.numCache){ oCurPts = oSeries.val.numRef.numCache; } else if(oSeries.val.numLit){ oCurPts = oSeries.val.numLit; } if(oCurPts){ nPtsLength = Math.max(nPtsLength, oCurPts.ptCount); } } } } var nCrossBetween = this.getAxisCrossType(oAxis.crossAx); if(nCrossBetween === AscFormat.CROSS_BETWEEN_MID_CAT && nPtsLength < 2){ nPtsLength = 2; } if(nPtsLength > aStrings.length){ for(i = aStrings.length; i < nPtsLength; ++i){ aStrings.push(i + 1 + ""); oAxis.scale.push(i); } } else{ aStrings.splice(nPtsLength, aStrings.length - nPtsLength); } break; } case AscDFH.historyitem_type_ValAx:{ var aVal = [].concat(oAxis.scale); var fMultiplier; if(oAxis.dispUnits){ fMultiplier = oAxis.dispUnits.getMultiplier(); } else{ fMultiplier = 1.0; } var oNumFmt = oAxis.numFmt; var oNumFormat = null; if(oNumFmt && typeof oNumFmt.formatCode === "string"){ oNumFormat = oNumFormatCache.get(oNumFmt.formatCode); } for(var t = 0; t < aVal.length; ++t){ var fCalcValue = aVal[t]*fMultiplier; var sRichValue; if(oNumFormat){ sRichValue = oNumFormat.formatToChart(fCalcValue); } else{ sRichValue = fCalcValue + ""; } aStrings.push(sRichValue); } break; } case AscDFH.historyitem_type_SerAx:{ break; } } return aStrings; }; CChartSpace.prototype.calculateAxisGrid = function(oAxis, oRect){ if(!oAxis){ return; } var oAxisGrid = new CAxisGrid(); oAxis.grid = oAxisGrid; // oAxis.nType = 0;//0 - horizontal, 1 - vertical, 2 - series axis var nOrientation = oAxis.scaling && AscFormat.isRealNumber(oAxis.scaling.orientation) ? oAxis.scaling.orientation : AscFormat.ORIENTATION_MIN_MAX; var aStrings = this.getLabelsForAxis(oAxis); var nCrossType = this.getAxisCrossType(oAxis); var bOnTickMark = ((nCrossType === AscFormat.CROSS_BETWEEN_MID_CAT) && (aStrings.length > 1)); var nIntervalsCount = bOnTickMark ? (aStrings.length - 1) : (aStrings.length); var fInterval; oAxisGrid.nCount = nIntervalsCount; oAxisGrid.bOnTickMark = bOnTickMark; oAxisGrid.aStrings = aStrings; if(oAxis.axPos === AscFormat.AX_POS_B || oAxis.axPos === AscFormat.AX_POS_T){ oAxisGrid.nType = 0; fInterval = oRect.w/nIntervalsCount; if(nOrientation === AscFormat.ORIENTATION_MIN_MAX){ oAxisGrid.fStart = oRect.x; oAxisGrid.fStride = fInterval; } else{ oAxisGrid.fStart = oRect.x + oRect.w; oAxisGrid.fStride = -fInterval; } } else{ oAxis.yPoints =[]; oAxisGrid.nType = 1; fInterval = oRect.h/nIntervalsCount; if(nOrientation === AscFormat.ORIENTATION_MIN_MAX){ oAxisGrid.fStart = oRect.y + oRect.h; oAxisGrid.fStride = -fInterval; } else{ oAxisGrid.fStart = oRect.y; oAxisGrid.fStride = fInterval; } } }; CChartSpace.prototype.recalculateAxesSet = function (aAxesSet, oRect, oBaseRect, nIndex, fForceContentWidth) { var oCorrectedRect = null; var bWithoutLabels = false; if(this.chart.plotArea.layout && this.chart.plotArea.layout.layoutTarget === AscFormat.LAYOUT_TARGET_INNER){ bWithoutLabels = true; } var bCorrected = false; var fL = oRect.x, fT = oRect.y, fR = oRect.x + oRect.w, fB = oRect.y + oRect.h; var fHorPadding = 0.0; var fVertPadding = 0.0; var fHorInterval = null; var oCalcMap = {}; for(var i = 0; i < aAxesSet.length; ++i){ var oCurAxis = aAxesSet[i]; var oCrossAxis = oCurAxis.crossAx; if(!oCalcMap[oCurAxis.Id]){ this.calculateAxisGrid(oCurAxis, oRect); oCalcMap[oCurAxis.Id] = true; } if(!oCalcMap[oCrossAxis.Id]){ this.calculateAxisGrid(oCrossAxis, oRect); oCalcMap[oCrossAxis.Id] = true; } var fCrossValue; var fAxisPos; if(AscFormat.isRealNumber(oCurAxis.crossesAt) && oCrossAxis.scale[0] <= oCurAxis.crossesAt && oCrossAxis.scale[oCrossAxis.scale.length - 1] >= oCurAxis.crossesAt){ fCrossValue = oCurAxis.crossesAt; } var fDistance = 10.0*(25.4/72);///TODO var nLabelsPos; var bLabelsExtremePosition = false; if(oCurAxis.bDelete){ nLabelsPos = c_oAscTickLabelsPos.TICK_LABEL_POSITION_NONE; } else{ if(null !== oCurAxis.tickLblPos){ nLabelsPos = oCurAxis.tickLblPos; } else{ nLabelsPos = c_oAscTickLabelsPos.TICK_LABEL_POSITION_NEXT_TO; } } switch (oCurAxis.crosses) { case AscFormat.CROSSES_MAX:{ fCrossValue = oCrossAxis.scale[oCrossAxis.scale.length - 1]; if(nLabelsPos === c_oAscTickLabelsPos.TICK_LABEL_POSITION_NEXT_TO){ fDistance = -fDistance; bLabelsExtremePosition = true; } break; } case AscFormat.CROSSES_MIN:{ fCrossValue = oCrossAxis.scale[0]; if(nLabelsPos === c_oAscTickLabelsPos.TICK_LABEL_POSITION_NEXT_TO){ bLabelsExtremePosition = true; } } default:{ //includes AutoZero if(oCrossAxis.scale[0] <=0 && oCrossAxis.scale[oCrossAxis.scale.length - 1] >= 0){ fCrossValue = 0; } else if(oCrossAxis.scale[0] > 0){ fCrossValue = oCrossAxis.scale[0]; } else{ fCrossValue = oCrossAxis.scale[oCrossAxis.scale.length - 1]; } if(AscFormat.fApproxEqual(fCrossValue, oCrossAxis.scale[0]) || AscFormat.fApproxEqual(fCrossValue, oCrossAxis.scale[oCrossAxis.scale.length - 1])){ bLabelsExtremePosition = true; } } } var oCrossGrid = oCrossAxis.grid; var fScale = (oCrossGrid.nCount*oCrossGrid.fStride)/(oCrossAxis.scale[oCrossAxis.scale.length - 1] - oCrossAxis.scale[0]); fAxisPos = oCrossGrid.fStart + (fCrossValue - oCrossAxis.scale[0])*fScale; var nOrientation = isRealObject(oCrossAxis.scaling) && AscFormat.isRealNumber(oCrossAxis.scaling.orientation) ? oCrossAxis.scaling.orientation : AscFormat.ORIENTATION_MIN_MAX; if(nOrientation === AscFormat.ORIENTATION_MAX_MIN){ fDistance = -fDistance; } var oLabelsBox = null, fPos; var fPosStart = oCurAxis.grid.fStart; var fPosEnd = oCurAxis.grid.fStart + oCurAxis.grid.nCount*oCurAxis.grid.fStride; var bOnTickMark = oCurAxis.grid.bOnTickMark; var bForceVertical = false; var bNumbers = false;//TODO if(nLabelsPos !== c_oAscTickLabelsPos.TICK_LABEL_POSITION_NONE){ oLabelsBox = new CLabelsBox(oCurAxis.grid.aStrings, oCurAxis, this); switch(nLabelsPos){ case c_oAscTickLabelsPos.TICK_LABEL_POSITION_NEXT_TO:{ fPos = fAxisPos; break; } case c_oAscTickLabelsPos.TICK_LABEL_POSITION_HIGH:{ fPos = oCrossGrid.fStart + oCrossGrid.nCount*oCrossGrid.fStride; fDistance = - fDistance; break; } case c_oAscTickLabelsPos.TICK_LABEL_POSITION_LOW:{ fPos = oCrossGrid.fStart; break; } } } oCurAxis.labels = oLabelsBox; oCurAxis.posX = null; oCurAxis.posY = null; oCurAxis.xPoints = null; oCurAxis.yPoints = null; var aPoints = null; if(oCurAxis.getObjectType() === AscDFH.historyitem_type_SerAx){ //TODO } else if(oCurAxis.axPos === AscFormat.AX_POS_B || oCurAxis.axPos === AscFormat.AX_POS_T){ oCurAxis.posY = fAxisPos; oCurAxis.xPoints = []; aPoints = oCurAxis.xPoints; if(oLabelsBox){ if(!AscFormat.fApproxEqual(oRect.fVertPadding, 0)){ fPos -= oRect.fVertPadding; if(nLabelsPos === c_oAscTickLabelsPos.TICK_LABEL_POSITION_NEXT_TO){ oCurAxis.posY -= oRect.fVertPadding; } } var bTickSkip = AscFormat.isRealNumber(oCurAxis.tickLblSkip); var nTickLblSkip = AscFormat.isRealNumber(oCurAxis.tickLblSkip) ? oCurAxis.tickLblSkip : 1; var fAxisLength = fPosEnd - fPosStart; var nLabelsCount = oLabelsBox.aLabels.length; var bOnTickMark_ = bOnTickMark && nLabelsCount > 1; var nIntervalCount = bOnTickMark_ ? nLabelsCount - 1 : nLabelsCount; fHorInterval = Math.abs(fAxisLength/nIntervalCount); if(bTickSkip && !AscFormat.isRealNumber(fForceContentWidth)){ fForceContentWidth = Math.abs(fHorInterval) + fHorInterval/nTickLblSkip; } fLayoutHorLabelsBox(oLabelsBox, fPos, fPosStart, fPosEnd, bOnTickMark, fDistance, bForceVertical, bNumbers, fForceContentWidth); if(bLabelsExtremePosition){ if(fDistance > 0){ fVertPadding = -oLabelsBox.extY; } else{ fVertPadding = oLabelsBox.extY; } } } } else{//vertical axis fDistance = -fDistance; oCurAxis.posX = fAxisPos; oCurAxis.yPoints = []; aPoints = oCurAxis.yPoints; if(oLabelsBox){ if(!AscFormat.fApproxEqual(oRect.fHorPadding, 0)){ fPos -= oRect.fHorPadding; if(nLabelsPos === c_oAscTickLabelsPos.TICK_LABEL_POSITION_NEXT_TO){ oCurAxis.posX -= oRect.fHorPadding; } } fLayoutVertLabelsBox(oLabelsBox, fPos, fPosStart, fPosEnd, bOnTickMark, fDistance, bForceVertical); if(bLabelsExtremePosition){ if(fDistance > 0){ fHorPadding = -oLabelsBox.extX; } else{ fHorPadding = oLabelsBox.extX; } } } } if(null !== aPoints){ var fStartSeriesPos = 0.0; if(!bOnTickMark){ fStartSeriesPos = oCurAxis.grid.fStride/2.0; } for(var j = 0; j < oCurAxis.grid.aStrings.length; ++j){ aPoints.push({val: oCurAxis.scale[j], pos: oCurAxis.grid.fStart + j*oCurAxis.grid.fStride + fStartSeriesPos}) } } if(oLabelsBox){ if(oLabelsBox.x < fL){ fL = oLabelsBox.x; } if(oLabelsBox.x + oLabelsBox.extX > fR){ fR = oLabelsBox.x + oLabelsBox.extX; } if(oLabelsBox.y < fT){ fT = oLabelsBox.y; } if(oLabelsBox.y + oLabelsBox.extY > fB){ fB = oLabelsBox.y + oLabelsBox.extY; } } } // function CAxisGrid(){ // this.nType = 0;//0 - horizontal, 1 - vertical, 2 - series axis // this.fStart = 0.0; // this.fStride = 0.0; // this.nCount = 0; // } if(nIndex < 2){ var fDiff; var fPrecision = 0.01; oCorrectedRect = new CRect(oRect.x, oRect.y, oRect.w, oRect.h); if(bWithoutLabels){ fDiff = fL; if(fDiff < 0.0 && !AscFormat.fApproxEqual(fDiff, 0.0, fPrecision)){ oCorrectedRect.x -= fDiff; oCorrectedRect.w += fDiff; bCorrected = true; } fDiff = fR - this.extX; if(fDiff > 0.0 && !AscFormat.fApproxEqual(fDiff, 0.0, fPrecision)){ oCorrectedRect.w -= fDiff; bCorrected = true; } fDiff = fT; if( fDiff < 0.0 && !AscFormat.fApproxEqual(fDiff, 0.0, fPrecision)){ oCorrectedRect.y -= fDiff; oCorrectedRect.h += fDiff; bCorrected = true; } fDiff = fB - this.extY; if( fDiff > 0.0 && !AscFormat.fApproxEqual(fDiff, 0.0, fPrecision)){ oCorrectedRect.h -= (fB - this.extY); bCorrected = true; } } else{ fDiff = oBaseRect.x - fL; if(/*fDiff > 0.0 && */!AscFormat.fApproxEqual(fDiff, 0.0, fPrecision) ){ oCorrectedRect.x += fDiff; oCorrectedRect.w -= fDiff; bCorrected = true; } fDiff = oBaseRect.x + oBaseRect.w - fR; if(/*fDiff < 0.0 && */!AscFormat.fApproxEqual(fDiff, 0.0, fPrecision)){ oCorrectedRect.w += fDiff; bCorrected = true; } fDiff = oBaseRect.y - fT; if(/*fDiff > 0.0 &&*/ !AscFormat.fApproxEqual(fDiff, 0.0, fPrecision)){ oCorrectedRect.y += fDiff; oCorrectedRect.h -= fDiff; bCorrected = true; } fDiff = oBaseRect.y + oBaseRect.h - fB; if(/*fDiff < 0.0 && */!AscFormat.fApproxEqual(fDiff, 0.0, fPrecision)){ oCorrectedRect.h += fDiff; bCorrected = true; } } if(oCorrectedRect && bCorrected){ if(oCorrectedRect.w > oRect.w){ return this.recalculateAxesSet(aAxesSet, oCorrectedRect, oBaseRect, ++nIndex, fHorInterval); } else{ return this.recalculateAxesSet(aAxesSet, oCorrectedRect, oBaseRect, ++nIndex); } } } var _ret = oRect.copy(); _ret.fHorPadding = fHorPadding; _ret.fVertPadding = fVertPadding; return _ret; }; CChartSpace.prototype.recalculateAxes = function(){ this.plotAreaRect = null; if(this.chart && this.chart.plotArea && this.chart.plotArea){ if(!this.chartObj){ this.chartObj = new AscFormat.CChartsDrawer() } this.chartObj.preCalculateData(this); var i, j; var oPlotArea = this.chart.plotArea; var aAxes = [].concat(oPlotArea.axId); var aAllAxes = [];//array of axes sets var oCurAxis, oCurAxis2, aCurAxesSet; while(aAxes.length > 0){ oCurAxis = aAxes.splice(0, 1)[0]; aCurAxesSet = []; aCurAxesSet.push(oCurAxis); for(i = aAxes.length - 1; i > -1; --i){ oCurAxis2 = aAxes[i]; for(j = 0; j < aCurAxesSet.length; ++j){ if(aCurAxesSet[j].crossAx === oCurAxis2 || oCurAxis2.crossAx === aCurAxesSet[j]){ aCurAxesSet.push(oCurAxis2); } } } if(aCurAxesSet.length > 1){ aAllAxes.push(aCurAxesSet); } } for(i = 0; i < oPlotArea.axId.length; ++i){ oCurAxis = oPlotArea.axId[i]; oCurAxis.posY = null; oCurAxis.posX = null; oCurAxis.xPoints = null; oCurAxis.yPoints = null; } var oSize = this.getChartSizes(); var oRect = new CRect(oSize.startX, oSize.startY, oSize.w, oSize.h); var oBaseRect = oRect; var aRects = []; for(i = 0; i < aAllAxes.length; ++i){ aCurAxesSet = aAllAxes[i]; aRects.push(this.recalculateAxesSet(aCurAxesSet, oRect, oBaseRect, 0)); } if(aRects.length > 1){ oRect = aRects[0].copy(); for(i = 1; i < aRects.length; ++i){ if(!oRect.intersection(aRects[i])){ break; } } var fOldHorPadding = 0.0, fOldVertPadding = 0.0; if(i === aRects.length){ var aRects2 = []; for(i = 0; i < aAllAxes.length; ++i){ aCurAxesSet = aAllAxes[i]; if(i === 0){ fOldHorPadding = oRect.fHorPadding; fOldVertPadding = oRect.fVertPadding; oRect.fHorPadding = 0.0; oRect.fVertPadding = 0.0; } aRects2.push(this.recalculateAxesSet(aCurAxesSet, oRect, oBaseRect, 2)); if(i === 0){ oRect.fHorPadding = fOldHorPadding; oRect.fVertPadding = fOldVertPadding; } } var bCheckPaddings = false; for(i = 0; i < aRects.length; ++i){ if(Math.abs(aRects2[i].fVertPadding) > Math.abs(aRects[i].fVertPadding)){ if(aRects2[i].fVertPadding > 0){ aRects[i].y += (aRects2[i].fVertPadding - aRects[i].fVertPadding); aRects[i].h -= (aRects2[i].fVertPadding - aRects[i].fVertPadding); } else{ aRects[i].h -= Math.abs(aRects2[i].fVertPadding - aRects[i].fVertPadding); } aRects[i].fVertPadding = aRects2[i].fVertPadding; bCheckPaddings = true; } if(Math.abs(aRects2[i].fHorPadding) > Math.abs(aRects[i].fHorPadding)){ if(aRects2[i].fHorPadding > 0){ aRects[i].x += (aRects2[i].fHorPadding - aRects[i].fHorPadding); aRects[i].w -= (aRects2[i].fHorPadding - aRects[i].fHorPadding); } else{ aRects[i].w -= Math.abs(aRects2[i].fHorPadding - aRects[i].fHorPadding); } aRects[i].fHorPadding = aRects2[i].fHorPadding; bCheckPaddings = true; } } if(bCheckPaddings){ oRect = aRects[0].copy(); for(i = 1; i < aRects.length; ++i){ if(!oRect.intersection(aRects[i])){ break; } } if(i === aRects.length){ var aRects2 = []; for(i = 0; i < aAllAxes.length; ++i){ aCurAxesSet = aAllAxes[i]; if(i === 0){ fOldHorPadding = oRect.fHorPadding; fOldVertPadding = oRect.fVertPadding; oRect.fHorPadding = 0.0; oRect.fVertPadding = 0.0; } aRects2.push(this.recalculateAxesSet(aCurAxesSet, oRect, oBaseRect, 2)); if(i === 0){ oRect.fHorPadding = fOldHorPadding; oRect.fVertPadding = fOldVertPadding; } } } } } } } }; CChartSpace.prototype.recalculateAxis = function() { if(this.chart && this.chart.plotArea && this.chart.plotArea.charts[0]) { var b_checkEmpty = this.checkEmptySeries(); this.bEmptySeries = b_checkEmpty; var plot_area = this.chart.plotArea; var chart_object = plot_area.chart; var i; var chart_type = chart_object.getObjectType(); var bWithoutLabels = false; if(plot_area.layout && plot_area.layout.layoutTarget === AscFormat.LAYOUT_TARGET_INNER){ bWithoutLabels = true; } this.plotAreaRect = null; var rect; var bCorrectedLayoutRect = false; if(b_checkEmpty) { if(chart_type === AscDFH.historyitem_type_ScatterChart) { var x_ax, y_ax; y_ax = this.chart.plotArea.valAx; x_ax = this.chart.plotArea.catAx; y_ax.labels = null; x_ax.labels = null; y_ax.posX = null; x_ax.posY = null; y_ax.posY = null; x_ax.posX = null; y_ax.xPoints = null; x_ax.yPoints = null; y_ax.yPoints = null; x_ax.xPoints = null; } else if(chart_type !== AscDFH.historyitem_type_BarChart && (chart_type !== AscDFH.historyitem_type_PieChart && chart_type !== AscDFH.historyitem_type_DoughnutChart) || (chart_type === AscDFH.historyitem_type_BarChart && chart_object.barDir !== AscFormat.BAR_DIR_BAR)) { var cat_ax, val_ax; val_ax = this.chart.plotArea.valAx; cat_ax = this.chart.plotArea.catAx; if(val_ax && cat_ax) { val_ax.labels = null; cat_ax.labels = null; val_ax.posX = null; cat_ax.posY = null; val_ax.posY = null; cat_ax.posX = null; val_ax.xPoints = null; cat_ax.yPoints = null; val_ax.yPoints = null; cat_ax.xPoints = null; val_ax.transformYPoints = null; cat_ax.transformXPoints = null; val_ax.transformXPoints = null; cat_ax.transformYPoints = null; } } else if(chart_type === AscDFH.historyitem_type_BarChart && chart_object.barDir === AscFormat.BAR_DIR_BAR) { var cat_ax, val_ax; var axis_by_types = chart_object.getAxisByTypes(); cat_ax = axis_by_types.catAx[0]; val_ax = axis_by_types.valAx[0]; if(cat_ax && val_ax) { val_ax.labels = null; cat_ax.labels = null; val_ax.posX = null; cat_ax.posY = null; val_ax.posY = null; cat_ax.posX = null; val_ax.xPoints = null; cat_ax.yPoints = null; val_ax.yPoints = null; cat_ax.xPoints = null; val_ax.transformYPoints = null; cat_ax.transformXPoints = null; val_ax.transformXPoints = null; cat_ax.transformYPoints = null; } } return; } var bNeedReflect = this.getNeedReflect(); if(chart_type === AscDFH.historyitem_type_ScatterChart) { var x_ax, y_ax; y_ax = this.chart.plotArea.valAx; x_ax = this.chart.plotArea.catAx; if(x_ax && y_ax) { /*new recalc*/ y_ax.labels = null; x_ax.labels = null; y_ax.posX = null; x_ax.posY = null; y_ax.posY = null; x_ax.posX = null; y_ax.xPoints = null; x_ax.yPoints = null; y_ax.yPoints = null; x_ax.xPoints = null; var sizes = this.getChartSizes(); rect = {x: sizes.startX, y:sizes.startY, w:sizes.w, h: sizes.h}; var arr_val = this.getValAxisValues(); var arr_strings = []; var multiplier; if(y_ax.dispUnits) multiplier = y_ax.dispUnits.getMultiplier(); else multiplier = 1; var num_fmt = y_ax.numFmt; if(num_fmt && typeof num_fmt.formatCode === "string" /*&& !(num_fmt.formatCode === "General")*/) { var num_format = oNumFormatCache.get(num_fmt.formatCode); for(i = 0; i < arr_val.length; ++i) { var calc_value = arr_val[i]*multiplier; var rich_value = num_format.formatToChart(calc_value); arr_strings.push(rich_value); } } else { for(i = 0; i < arr_val.length; ++i) { var calc_value = arr_val[i]*multiplier; arr_strings.push(calc_value + ""); } } //расчитаем подписи для вертикальной оси найдем ширину максимальной и возьмем её удвоенную за ширину подписей верт оси var left_align_labels = true; y_ax.labels = new AscFormat.CValAxisLabels(this, y_ax); y_ax.yPoints = []; var max_width = 0; for(i = 0; i < arr_strings.length; ++i) { var dlbl = new AscFormat.CDLbl(); dlbl.parent = y_ax; dlbl.chart = this; dlbl.spPr = y_ax.spPr; dlbl.txPr = y_ax.txPr; dlbl.tx = new AscFormat.CChartText(); dlbl.tx.rich = AscFormat.CreateTextBodyFromString(arr_strings[i], this.getDrawingDocument(), dlbl); if(i > 0) { dlbl.lastStyleObject = y_ax.labels.aLabels[0].lastStyleObject; } var oRecalculateByMaxWord = dlbl.tx.rich.recalculateByMaxWord(); var cur_width = oRecalculateByMaxWord.w; if(i === arr_strings.length-1){ rect.y += oRecalculateByMaxWord.h/2; } if(cur_width > max_width) max_width = cur_width; y_ax.labels.aLabels.push(dlbl); } //пока расстояние между подписями и краем блока с подписями берем размер шрифта. var hor_gap = y_ax.labels.aLabels[0].tx.rich.content.Content[0].CompiledPr.Pr.TextPr.FontSize*(25.4/72); y_ax.labels.extX = max_width + hor_gap; /*расчитаем надписи в блоке для горизонтальной оси*/ var arr_x_val = this.getXValAxisValues(); var num_fmt = x_ax.numFmt; var string_pts = []; if(num_fmt && typeof num_fmt.formatCode === "string" /*&& !(num_fmt.formatCode === "General")*/) { var num_format = oNumFormatCache.get(num_fmt.formatCode); for(i = 0; i < arr_x_val.length; ++i) { var calc_value = arr_x_val[i]*multiplier; var rich_value = num_format.formatToChart(calc_value); string_pts.push({val:rich_value}); } } else { for(i = 0; i < arr_x_val.length; ++i) { var calc_value = arr_x_val[i]*multiplier; string_pts.push({val:calc_value + ""}); } } x_ax.labels = new AscFormat.CValAxisLabels(this, x_ax); var bottom_align_labels = true; var max_height = 0; for(i = 0; i < string_pts.length; ++i) { var dlbl = new AscFormat.CDLbl(); dlbl.parent = x_ax; dlbl.chart = this; dlbl.spPr = x_ax.spPr; dlbl.txPr = x_ax.txPr; dlbl.tx = new AscFormat.CChartText(); dlbl.tx.rich = AscFormat.CreateTextBodyFromString(string_pts[i].val.replace(oNonSpaceRegExp, ' '), this.getDrawingDocument(), dlbl); if(x_ax.labels.aLabels[0]) { dlbl.lastStyleObject = x_ax.labels.aLabels[0].lastStyleObject; } var oWH = dlbl.tx.rich.recalculateByMaxWord(); var cur_height = oWH.h; if(cur_height > max_height) max_height = cur_height; if(i === string_pts.length - 1){ rect.w -= oWH.w/2; } x_ax.labels.aLabels.push(dlbl); } var vert_gap = x_ax.labels.aLabels[0].tx.rich.content.Content[0].CompiledPr.Pr.TextPr.FontSize*(25.4/72); x_ax.labels.extY = max_height + vert_gap; /*расчитаем позицию блока с подпиясями вертикальной оси*/ var x_ax_orientation = isRealObject(x_ax.scaling) && AscFormat.isRealNumber(x_ax.scaling.orientation) ? x_ax.scaling.orientation : AscFormat.ORIENTATION_MIN_MAX; var crosses;//точка на горизонтальной оси где её пересекает вертикальная if(y_ax.crosses === AscFormat.CROSSES_AUTO_ZERO) { if(arr_x_val[0] <=0 && arr_x_val[arr_x_val.length -1] >= 0) crosses = 0; else if(arr_x_val[0] > 0) crosses = arr_x_val[0]; else crosses = arr_x_val[arr_x_val.length-1]; } else if(y_ax.crosses === AscFormat.CROSSES_MAX) crosses = arr_x_val[arr_x_val.length-1]; else if(y_ax.crosses === AscFormat.CROSSES_MIN) crosses = arr_x_val[0]; else if(AscFormat.isRealNumber(y_ax.crossesAt) && arr_val[0] <= y_ax.crossesAt && arr_val[arr_val.length-1] >= y_ax.crossesAt) { crosses = y_ax.crossesAt; } else { //в кайнем случае ведем себя как с AUTO_ZERO if(arr_x_val[0] <=0 && arr_x_val[arr_x_val.length -1] >= 0) crosses = 0; else if(arr_x_val[0] > 0) crosses = arr_x_val[0]; else crosses = arr_x_val[arr_x_val.length-1]; } var hor_interval_width = checkFiniteNumber(rect.w/(arr_x_val[arr_x_val.length-1] - arr_x_val[0])); var vert_interval_height = checkFiniteNumber(rect.h/(arr_val[arr_val.length-1] - arr_val[0])); var arr_x_points = [], arr_y_points = []; var labels_pos = y_ax.tickLblPos; var first_hor_label_half_width = (x_ax.tickLblPos === c_oAscTickLabelsPos.TICK_LABEL_POSITION_NONE || x_ax.bDelete) ? 0 : x_ax.labels.aLabels[0].tx.rich.content.XLimit/2; var last_hor_label_half_width = (x_ax.tickLblPos === c_oAscTickLabelsPos.TICK_LABEL_POSITION_NONE || x_ax.bDelete) ? 0 : x_ax.labels.aLabels[x_ax.labels.aLabels.length-1].tx.rich.content.XLimit/2; var left_gap = 0, right_gap = 0; if(x_ax_orientation === AscFormat.ORIENTATION_MIN_MAX) { switch(labels_pos) { case c_oAscTickLabelsPos.TICK_LABEL_POSITION_HIGH: { left_align_labels = false; if(bNeedReflect) { right_gap = Math.max(last_hor_label_half_width, 0); } else { right_gap = Math.max(last_hor_label_half_width, y_ax.labels.extX); } if(!bWithoutLabels){ hor_interval_width = checkFiniteNumber((rect.w - right_gap - first_hor_label_half_width)/(arr_x_val[arr_x_val.length-1] - arr_x_val[0])); for(i = 0; i < arr_x_val.length; ++i) { arr_x_points[i] = rect.x + first_hor_label_half_width + hor_interval_width*(arr_x_val[i] - arr_x_val[0]); } y_ax.labels.x = rect.x + first_hor_label_half_width + hor_interval_width*(arr_x_val[arr_x_val.length-1] - arr_x_val[0]); y_ax.posX = rect.x + first_hor_label_half_width + (crosses-arr_x_val[0])*hor_interval_width; } else{ hor_interval_width = checkFiniteNumber(rect.w/(arr_x_val[arr_x_val.length-1] - arr_x_val[0])); for(i = 0; i < arr_x_val.length; ++i) { arr_x_points[i] = rect.x + hor_interval_width*(arr_x_val[i] - arr_x_val[0]); } y_ax.labels.x = rect.x + hor_interval_width*(arr_x_val[arr_x_val.length-1] - arr_x_val[0]); y_ax.posX = rect.x + (crosses-arr_x_val[0])*hor_interval_width; if(y_ax.labels.x < 0 && !bNeedReflect){ rect.x -= y_ax.labels.x; rect.w += y_ax.labels.x; bCorrectedLayoutRect = true; } if(y_ax.labels.x + y_ax.labels.extX > this.extX && !bNeedReflect){ rect.w -= (y_ax.labels.x + y_ax.labels.extX - this.extX); bCorrectedLayoutRect = true; } if(bCorrectedLayoutRect){ hor_interval_width = checkFiniteNumber(rect.w/(arr_x_val[arr_x_val.length-1] - arr_x_val[0])); for(i = 0; i < arr_x_val.length; ++i) { arr_x_points[i] = rect.x + hor_interval_width*(arr_x_val[i] - arr_x_val[0]); } y_ax.labels.x = rect.x + hor_interval_width*(arr_x_val[arr_x_val.length-1] - arr_x_val[0]); y_ax.posX = rect.x + (crosses-arr_x_val[0])*hor_interval_width; } } break; } case c_oAscTickLabelsPos.TICK_LABEL_POSITION_LOW: { if(bNeedReflect) { left_gap = Math.max(first_hor_label_half_width, 0); } else { left_gap = Math.max(first_hor_label_half_width, y_ax.labels.extX); } if(!bWithoutLabels){ hor_interval_width = checkFiniteNumber((rect.w-left_gap - last_hor_label_half_width)/(arr_x_val[arr_x_val.length-1] - arr_x_val[0])); for(i = 0; i < arr_x_val.length; ++i) { arr_x_points[i] = rect.x + left_gap + hor_interval_width*(arr_x_val[i] - arr_x_val[0]); } y_ax.labels.x = rect.x - y_ax.labels.extX; y_ax.posX = rect.x + (crosses-arr_x_val[0])*hor_interval_width; } else{ hor_interval_width = checkFiniteNumber(rect.w/(arr_x_val[arr_x_val.length-1] - arr_x_val[0])); for(i = 0; i < arr_x_val.length; ++i) { arr_x_points[i] = rect.x + hor_interval_width*(arr_x_val[i] - arr_x_val[0]); } y_ax.labels.x = rect.x - y_ax.labels.extX; y_ax.posX = rect.x + (crosses-arr_x_val[0])*hor_interval_width; if(y_ax.labels.x < 0 && !bNeedReflect){ rect.x -= y_ax.labels.x; rect.w += y_ax.labels.x; bCorrectedLayoutRect = true; } if(y_ax.labels.x + y_ax.labels.extX > this.extX && !bNeedReflect){ rect.w -= (y_ax.labels.x + y_ax.labels.extX - this.extX); bCorrectedLayoutRect = true; } if(bCorrectedLayoutRect){ hor_interval_width = checkFiniteNumber(rect.w/(arr_x_val[arr_x_val.length-1] - arr_x_val[0])); for(i = 0; i < arr_x_val.length; ++i) { arr_x_points[i] = rect.x + hor_interval_width*(arr_x_val[i] - arr_x_val[0]); } y_ax.labels.x = rect.x - y_ax.labels.extX; y_ax.posX = rect.x + (crosses-arr_x_val[0])*hor_interval_width; } } break; } case c_oAscTickLabelsPos.TICK_LABEL_POSITION_NONE: { if(!bWithoutLabels) { y_ax.labels = null; hor_interval_width = checkFiniteNumber((rect.w - first_hor_label_half_width - last_hor_label_half_width) / (arr_x_val[arr_x_val.length - 1] - arr_x_val[0])); for (i = 0; i < arr_x_val.length; ++i) { arr_x_points[i] = rect.x + first_hor_label_half_width + hor_interval_width * (arr_x_val[i] - arr_x_val[0]); } y_ax.posX = rect.x + first_hor_label_half_width + hor_interval_width * (crosses - arr_x_val[0]); } else{ y_ax.labels = null; hor_interval_width = checkFiniteNumber(rect.w/ (arr_x_val[arr_x_val.length - 1] - arr_x_val[0])); for (i = 0; i < arr_x_val.length; ++i) { arr_x_points[i] = rect.x + first_hor_label_half_width + hor_interval_width * (arr_x_val[i] - arr_x_val[0]); } y_ax.posX = rect.x + hor_interval_width * (crosses - arr_x_val[0]); } break; } default : {//c_oAscTickLabelsPos.TICK_LABEL_POSITION_NEXT_TO рядом с осью if(y_ax.crosses === AscFormat.CROSSES_MAX) { left_align_labels = false; if(bNeedReflect) { right_gap = Math.max(right_gap, 0); } else { right_gap = Math.max(right_gap, y_ax.labels.extX); } if(!bWithoutLabels){ y_ax.labels.x = rect.x + rect.w - right_gap; y_ax.posX = rect.x + rect.w - right_gap; hor_interval_width = checkFiniteNumber((rect.w - right_gap - first_hor_label_half_width)/(arr_x_val[arr_x_val.length-1] - arr_x_val[0])); for(i = 0; i < arr_x_val.length; ++i) { arr_x_points[i] = rect.x + first_hor_label_half_width + hor_interval_width*(arr_x_val[i] - arr_x_val[0]); } } else{ y_ax.labels.x = rect.x + rect.w; y_ax.posX = rect.x + rect.w; hor_interval_width = checkFiniteNumber(rect.w/(arr_x_val[arr_x_val.length-1] - arr_x_val[0])); for(i = 0; i < arr_x_val.length; ++i) { arr_x_points[i] = rect.x + hor_interval_width*(arr_x_val[i] - arr_x_val[0]); } if(y_ax.labels.x < 0 && !bNeedReflect){ rect.x -= y_ax.labels.x; rect.w += y_ax.labels.x; bCorrectedLayoutRect = true; } if(y_ax.labels.x + y_ax.labels.extX > this.extX && !bNeedReflect){ rect.w -= (y_ax.labels.x + y_ax.labels.extX - this.extX); bCorrectedLayoutRect = true; } if(bCorrectedLayoutRect){ y_ax.labels.x = rect.x + rect.w; y_ax.posX = rect.x + rect.w; hor_interval_width = checkFiniteNumber(rect.w/(arr_x_val[arr_x_val.length-1] - arr_x_val[0])); for(i = 0; i < arr_x_val.length; ++i) { arr_x_points[i] = rect.x + hor_interval_width*(arr_x_val[i] - arr_x_val[0]); } } } } else { if(!bWithoutLabels) { hor_interval_width = checkFiniteNumber((rect.w - first_hor_label_half_width - last_hor_label_half_width) / (arr_x_val[arr_x_val.length - 1] - arr_x_val[0])); if (!bNeedReflect && first_hor_label_half_width + (crosses - arr_x_val[0]) * hor_interval_width < y_ax.labels.extX) { hor_interval_width = checkFiniteNumber((rect.w - y_ax.labels.extX - last_hor_label_half_width) / (arr_x_val[arr_x_val.length - 1] - crosses)); } y_ax.posX = rect.x + rect.w - last_hor_label_half_width - (arr_x_val[arr_x_val.length - 1] - crosses) * hor_interval_width; for (i = 0; i < arr_x_val.length; ++i) { arr_x_points[i] = y_ax.posX + (arr_x_val[i] - crosses) * hor_interval_width; } y_ax.labels.x = y_ax.posX - y_ax.labels.extX; } else{ hor_interval_width = checkFiniteNumber(rect.w/ (arr_x_val[arr_x_val.length - 1] - arr_x_val[0])); y_ax.posX = rect.x + rect.w - (arr_x_val[arr_x_val.length - 1] - crosses) * hor_interval_width; for (i = 0; i < arr_x_val.length; ++i) { arr_x_points[i] = y_ax.posX + (arr_x_val[i] - crosses) * hor_interval_width; } y_ax.labels.x = y_ax.posX - y_ax.labels.extX; if(y_ax.labels.x < 0 && !bNeedReflect){ rect.x -= y_ax.labels.x; rect.w += y_ax.labels.x; bCorrectedLayoutRect = true; } if(y_ax.labels.x + y_ax.labels.extX > this.extX && !bNeedReflect){ rect.w -= (y_ax.labels.x + y_ax.labels.extX - this.extX); bCorrectedLayoutRect = true; } if(bCorrectedLayoutRect){ hor_interval_width = checkFiniteNumber(rect.w/ (arr_x_val[arr_x_val.length - 1] - arr_x_val[0])); y_ax.posX = rect.x + rect.w - (arr_x_val[arr_x_val.length - 1] - crosses) * hor_interval_width; for (i = 0; i < arr_x_val.length; ++i) { arr_x_points[i] = y_ax.posX + (arr_x_val[i] - crosses) * hor_interval_width; } y_ax.labels.x = y_ax.posX - y_ax.labels.extX; } } } break; } } } else { switch(labels_pos) { case c_oAscTickLabelsPos.TICK_LABEL_POSITION_HIGH: { if(bNeedReflect) { left_gap = Math.max(0, last_hor_label_half_width); } else { left_gap = Math.max(y_ax.labels.extX, last_hor_label_half_width); } if(!bWithoutLabels){ hor_interval_width = checkFiniteNumber((rect.w - left_gap - first_hor_label_half_width)/(arr_x_val[arr_x_val.length-1] - arr_x_val[0])); y_ax.posX = rect.x + rect.w - (crosses - arr_x_val[0])*hor_interval_width - first_hor_label_half_width; for(i = 0; i < arr_x_val.length; ++i) { arr_x_points[i] = y_ax.posX - (arr_x_val[i]-crosses)*hor_interval_width; } y_ax.labels.x = y_ax.posX - (arr_x_val[arr_x_val.length-1]-crosses)*hor_interval_width - y_ax.labels.extX; } else{ hor_interval_width = checkFiniteNumber(rect.w/(arr_x_val[arr_x_val.length-1] - arr_x_val[0])); y_ax.posX = rect.x + rect.w - (crosses - arr_x_val[0])*hor_interval_width; for(i = 0; i < arr_x_val.length; ++i) { arr_x_points[i] = y_ax.posX - (arr_x_val[i]-crosses)*hor_interval_width; } y_ax.labels.x = y_ax.posX - (arr_x_val[arr_x_val.length-1]-crosses)*hor_interval_width - y_ax.labels.extX; if(y_ax.labels.x < 0 && !bNeedReflect){ rect.x -= y_ax.labels.x; rect.w += y_ax.labels.x; bCorrectedLayoutRect = true; } if(y_ax.labels.x + y_ax.labels.extX > this.extX && !bNeedReflect){ rect.w -= (y_ax.labels.x + y_ax.labels.extX - this.extX); bCorrectedLayoutRect = true; } if(bCorrectedLayoutRect){ hor_interval_width = checkFiniteNumber(rect.w/(arr_x_val[arr_x_val.length-1] - arr_x_val[0])); y_ax.posX = rect.x + rect.w - (crosses - arr_x_val[0])*hor_interval_width; for(i = 0; i < arr_x_val.length; ++i) { arr_x_points[i] = y_ax.posX - (arr_x_val[i]-crosses)*hor_interval_width; } y_ax.labels.x = y_ax.posX - (arr_x_val[arr_x_val.length-1]-crosses)*hor_interval_width - y_ax.labels.extX; } } break; } case c_oAscTickLabelsPos.TICK_LABEL_POSITION_LOW: { left_align_labels = false; if(bNeedReflect) { right_gap = Math.max(0, first_hor_label_half_width); } else { right_gap = Math.max(y_ax.labels.extX, first_hor_label_half_width); } if(!bWithoutLabels){ hor_interval_width = checkFiniteNumber((rect.w - right_gap - last_hor_label_half_width)/(arr_x_val[arr_x_val.length-1] - arr_x_val[0])); y_ax.posX = rect.x + rect.w - right_gap - (crosses - arr_x_val[0])*hor_interval_width; for(i = 0; i < arr_x_val.length; ++i) { arr_x_points[i] = y_ax.posX - (arr_x_val[i]-crosses)*hor_interval_width; } y_ax.labels.x = rect.x + rect.w - right_gap; } else{ hor_interval_width = checkFiniteNumber(rect.w/(arr_x_val[arr_x_val.length-1] - arr_x_val[0])); y_ax.posX = rect.x + rect.w - (crosses - arr_x_val[0])*hor_interval_width; for(i = 0; i < arr_x_val.length; ++i) { arr_x_points[i] = y_ax.posX - (arr_x_val[i]-crosses)*hor_interval_width; } y_ax.labels.x = rect.x + rect.w; if(y_ax.labels.x < 0 && !bNeedReflect){ rect.x -= y_ax.labels.x; rect.w += y_ax.labels.x; bCorrectedLayoutRect = true; } if(y_ax.labels.x + y_ax.labels.extX > this.extX && !bNeedReflect){ rect.w -= (y_ax.labels.x + y_ax.labels.extX - this.extX); bCorrectedLayoutRect = true; } if(bCorrectedLayoutRect){ hor_interval_width = checkFiniteNumber(rect.w/(arr_x_val[arr_x_val.length-1] - arr_x_val[0])); y_ax.posX = rect.x + rect.w - (crosses - arr_x_val[0])*hor_interval_width; for(i = 0; i < arr_x_val.length; ++i) { arr_x_points[i] = y_ax.posX - (arr_x_val[i]-crosses)*hor_interval_width; } y_ax.labels.x = rect.x + rect.w; } } break; } case c_oAscTickLabelsPos.TICK_LABEL_POSITION_NONE: { y_ax.labels = null; if(!bWithoutLabels) { hor_interval_width = checkFiniteNumber((rect.w - first_hor_label_half_width - last_hor_label_half_width) / (arr_x_val[arr_x_val.length - 1] - arr_x_val[0])); y_ax.posX = rect.x + rect.w - first_hor_label_half_width - (crosses - arr_x_val[0]) * hor_interval_width; for (i = 0; i < arr_x_val.length; ++i) { arr_x_points[i] = y_ax.posX - (arr_x_val[i] - crosses) * hor_interval_width; } } else{ hor_interval_width = checkFiniteNumber(rect.w / (arr_x_val[arr_x_val.length - 1] - arr_x_val[0])); y_ax.posX = rect.x + rect.w - (crosses - arr_x_val[0]) * hor_interval_width; for (i = 0; i < arr_x_val.length; ++i) { arr_x_points[i] = y_ax.posX - (arr_x_val[i] - crosses) * hor_interval_width; } } break; } default : {//c_oAscTickLabelsPos.TICK_LABEL_POSITION_NEXT_TO рядом с осью if(y_ax.crosses === AscFormat.CROSSES_MAX) { if(bNeedReflect) { left_gap = Math.max(0, last_hor_label_half_width); } else { left_gap = Math.max(y_ax.labels.extX, last_hor_label_half_width); } if(!bWithoutLabels) { hor_interval_width = checkFiniteNumber((rect.w - left_gap - first_hor_label_half_width) / (arr_x_val[arr_x_val.length - 1] - arr_x_val[0])); y_ax.posX = rect.x + rect.w - first_hor_label_half_width - (crosses - arr_x_val[0]) * hor_interval_width; y_ax.labels.x = y_ax.posX - ((arr_x_val[arr_x_val.length - 1] - crosses) * hor_interval_width) - y_ax.labels.extX; } else{ hor_interval_width = checkFiniteNumber(rect.w/ (arr_x_val[arr_x_val.length - 1] - arr_x_val[0])); y_ax.posX = rect.x + rect.w - (crosses - arr_x_val[0]) * hor_interval_width; y_ax.labels.x = y_ax.posX - ((arr_x_val[arr_x_val.length - 1] - crosses) * hor_interval_width) - y_ax.labels.extX; if(y_ax.labels.x < 0 && !bNeedReflect){ rect.x -= y_ax.labels.x; rect.w += y_ax.labels.x; bCorrectedLayoutRect = true; } if(y_ax.labels.x + y_ax.labels.extX > this.extX && !bNeedReflect){ rect.w -= (y_ax.labels.x + y_ax.labels.extX - this.extX); bCorrectedLayoutRect = true; } if(bCorrectedLayoutRect){ hor_interval_width = checkFiniteNumber(rect.w/ (arr_x_val[arr_x_val.length - 1] - arr_x_val[0])); y_ax.posX = rect.x + rect.w - (crosses - arr_x_val[0]) * hor_interval_width; y_ax.labels.x = y_ax.posX - ((arr_x_val[arr_x_val.length - 1] - crosses) * hor_interval_width) - y_ax.labels.extX; } } } else { left_align_labels = false; if(!bWithoutLabels) { hor_interval_width = checkFiniteNumber((rect.w - first_hor_label_half_width - last_hor_label_half_width) / (arr_x_val[arr_x_val.length - 1] - arr_x_val[0])); if (!bNeedReflect && first_hor_label_half_width + (crosses - arr_x_val[0]) * hor_interval_width < y_ax.labels.extX) { hor_interval_width = checkFiniteNumber((rect.w - y_ax.labels.extX - last_hor_label_half_width) / (arr_x_val[arr_x_val.length - 1] - crosses)); } left_align_labels = false; y_ax.posX = rect.x + last_hor_label_half_width + hor_interval_width * (arr_x_val[arr_x_val.length - 1] - crosses); y_ax.labels.x = y_ax.posX; } else{ hor_interval_width = checkFiniteNumber(rect.w / (arr_x_val[arr_x_val.length - 1] - arr_x_val[0])); left_align_labels = false; y_ax.posX = rect.x + hor_interval_width * (arr_x_val[arr_x_val.length - 1] - crosses); y_ax.labels.x = y_ax.posX; if(y_ax.labels.x < 0 && !bNeedReflect){ rect.x -= y_ax.labels.x; rect.w += y_ax.labels.x; bCorrectedLayoutRect = true; } if(y_ax.labels.x + y_ax.labels.extX > this.extX && !bNeedReflect){ rect.w -= (y_ax.labels.x + y_ax.labels.extX - this.extX); bCorrectedLayoutRect = true; } if(bCorrectedLayoutRect){ hor_interval_width = checkFiniteNumber(rect.w / (arr_x_val[arr_x_val.length - 1] - arr_x_val[0])); left_align_labels = false; y_ax.posX = rect.x + hor_interval_width * (arr_x_val[arr_x_val.length - 1] - crosses); y_ax.labels.x = y_ax.posX; } } } for(i = 0; i < arr_x_val.length; ++i) { arr_x_points[i] = y_ax.posX - (arr_x_val[i] - crosses)*hor_interval_width; } break; } } } x_ax.interval = hor_interval_width; /*рассчитаем позицию блока с подписями горизонтальной оси*/ var y_ax_orientation = isRealObject(y_ax.scaling) && AscFormat.isRealNumber(y_ax.scaling.orientation) ? y_ax.scaling.orientation : AscFormat.ORIENTATION_MIN_MAX; var crosses_x; if(x_ax.crosses === AscFormat.CROSSES_AUTO_ZERO) { if(arr_val[0] <= 0 && arr_val[arr_val.length-1] >=0) { crosses_x = 0; } else if(arr_val[0] > 0) crosses_x = arr_val[0]; else crosses_x = arr_val[arr_val.length-1]; } else if(x_ax.crosses === AscFormat.CROSSES_MAX) { crosses_x = arr_val[arr_val.length-1]; } else if(x_ax.crosses === AscFormat.CROSSES_MIN) { crosses_x = arr_val[0]; } else if(AscFormat.isRealNumber(x_ax.crossesAt) && arr_val[0] <= x_ax.crossesAt && arr_val[arr_val.length-1] >= x_ax.crossesAt) { crosses_x = x_ax.crossesAt; } else { //как с AUTO_ZERO if(arr_val[0] <= 0 && arr_val[arr_val.length-1] >=0) { crosses_x = 0; } else if(arr_val[0] > 0) crosses_x = arr_val[0]; else crosses_x = arr_val[arr_val.length-1]; } var tick_labels_pos_x = x_ax.tickLblPos; var first_vert_label_half_height = 0; //TODO (y_ax.tickLblPos === c_oAscTickLabelsPos.TICK_LABEL_POSITION_NONE || y_ax.bDelete) ? 0 : y_ax.labels.aLabels[0].tx.rich.content.GetSummaryHeight()/2; var last_vert_label_half_height = 0; //(y_ax.tickLblPos === c_oAscTickLabelsPos.TICK_LABEL_POSITION_NONE || y_ax.bDelete) ? 0 : y_ax.labels.aLabels[0].tx.rich.content.GetSummaryHeight()/2; var bottom_gap = 0, top_height = 0; if(y_ax_orientation === AscFormat.ORIENTATION_MIN_MAX) { switch(tick_labels_pos_x) { case c_oAscTickLabelsPos.TICK_LABEL_POSITION_HIGH: { bottom_align_labels = false; var bottom_start_point = rect.y + rect.h - first_vert_label_half_height; top_height = Math.max(x_ax.labels.extY, last_vert_label_half_height); if(!bWithoutLabels){ vert_interval_height = checkFiniteNumber((rect.h - top_height - first_vert_label_half_height)/(arr_val[arr_val.length-1] - arr_val[0])); x_ax.labels.y = bottom_start_point - (arr_val[arr_val.length - 1] - arr_val[0])*vert_interval_height - x_ax.labels.extY; for(i = 0; i < arr_val.length; ++i) { arr_y_points[i] = bottom_start_point - (arr_val[i] - arr_val[0])*vert_interval_height; } x_ax.posY = bottom_start_point - (crosses_x - arr_val[0])*vert_interval_height; } else{ vert_interval_height = checkFiniteNumber(rect.h/(arr_val[arr_val.length-1] - arr_val[0])); x_ax.labels.y = rect.y + rect.h - (arr_val[arr_val.length - 1] - arr_val[0])*vert_interval_height - x_ax.labels.extY; for(i = 0; i < arr_val.length; ++i) { arr_y_points[i] = rect.y + rect.h - (arr_val[i] - arr_val[0])*vert_interval_height; } x_ax.posY = rect.y + rect.h - (crosses_x - arr_val[0])*vert_interval_height; var bCheckXLabels = false; if(x_ax.labels.y < 0){ bCheckXLabels = true; rect.y -= x_ax.labels.y; rect.h -= x_ax.labels.h; } if(x_ax.labels.y + x_ax.labels.extY > this.extY){ bCheckXLabels = true; rect.h -= (x_ax.labels.y + x_ax.labels.extY - this.extY) } if(bCheckXLabels){ vert_interval_height = checkFiniteNumber(rect.h/(arr_val[arr_val.length-1] - arr_val[0])); x_ax.labels.y = rect.y + rect.h - (arr_val[arr_val.length - 1] - arr_val[0])*vert_interval_height - x_ax.labels.extY; for(i = 0; i < arr_val.length; ++i) { arr_y_points[i] = rect.y + rect.h - (arr_val[i] - arr_val[0])*vert_interval_height; } x_ax.posY = rect.y + rect.h - (crosses_x - arr_val[0])*vert_interval_height; } } break; } case c_oAscTickLabelsPos.TICK_LABEL_POSITION_LOW: { bottom_gap = Math.max(x_ax.labels.extY, first_vert_label_half_height); if(!bWithoutLabels){ x_ax.labels.y = rect.y + rect.h - bottom_gap; vert_interval_height = checkFiniteNumber((rect.h - bottom_gap - last_vert_label_half_height)/(arr_val[arr_val.length-1] - arr_val[0])); for(i = 0; i < arr_val.length; ++i) { arr_y_points[i] = rect.y + rect.h - bottom_gap - (arr_val[i] - arr_val[0])*vert_interval_height; } x_ax.posY = rect.y + rect.h - bottom_gap - (crosses_x - arr_val[0])*vert_interval_height; } else{ x_ax.labels.y = rect.y + rect.h; vert_interval_height = checkFiniteNumber(rect.h/(arr_val[arr_val.length-1] - arr_val[0])); for(i = 0; i < arr_val.length; ++i) { arr_y_points[i] = rect.y + rect.h - (arr_val[i] - arr_val[0])*vert_interval_height; } x_ax.posY = rect.y + rect.h - (crosses_x - arr_val[0])*vert_interval_height; var bCheckXLabels = false; if(x_ax.labels.y < 0){ bCheckXLabels = true; rect.y -= x_ax.labels.y; rect.h -= x_ax.labels.h; } if(x_ax.labels.y + x_ax.labels.extY > this.extY){ bCheckXLabels = true; rect.h -= (x_ax.labels.y + x_ax.labels.extY - this.extY) } if(bCheckXLabels){ x_ax.labels.y = rect.y + rect.h; vert_interval_height = checkFiniteNumber(rect.h/(arr_val[arr_val.length-1] - arr_val[0])); for(i = 0; i < arr_val.length; ++i) { arr_y_points[i] = rect.y + rect.h - (arr_val[i] - arr_val[0])*vert_interval_height; } x_ax.posY = rect.y + rect.h - (crosses_x - arr_val[0])*vert_interval_height; } } break; } case c_oAscTickLabelsPos.TICK_LABEL_POSITION_NONE: { x_ax.labels = null; if(!bWithoutLabels){ vert_interval_height = checkFiniteNumber((rect.h - first_vert_label_half_height - last_vert_label_half_height)/(arr_val[arr_val.length-1] - arr_val[0])); for(i = 0; i < arr_val.length; ++i) { arr_y_points[i] = rect.y + rect.h - first_vert_label_half_height - (arr_val[i] - arr_val[0])*vert_interval_height; } x_ax.posY = rect.y + rect.h - first_vert_label_half_height - (crosses_x - arr_val[0])*vert_interval_height; } else{ vert_interval_height = checkFiniteNumber(rect.h/(arr_val[arr_val.length-1] - arr_val[0])); for(i = 0; i < arr_val.length; ++i) { arr_y_points[i] = rect.y + rect.h - (arr_val[i] - arr_val[0])*vert_interval_height; } x_ax.posY = rect.y + rect.h - (crosses_x - arr_val[0])*vert_interval_height; } break; } default : {//c_oAscTickLabelsPos.TICK_LABEL_POSITION_NEXT_TO рядом с осью if(x_ax.crosses === AscFormat.CROSSES_MAX) { bottom_align_labels = false; top_height = Math.max(x_ax.labels.extY, last_vert_label_half_height); if(!bWithoutLabels) { vert_interval_height = checkFiniteNumber((rect.h - top_height - first_vert_label_half_height) / (arr_val[arr_val.length - 1] - arr_val[0])); for (i = 0; i < arr_val.length; ++i) { arr_y_points[i] = rect.y + rect.h - first_vert_label_half_height - (arr_val[i] - arr_val[0]) * vert_interval_height; } x_ax.posY = rect.y + rect.h - first_vert_label_half_height - (arr_val[arr_val.length - 1] - arr_val[0]) * vert_interval_height; x_ax.labels.y = x_ax.posY - x_ax.labels.extY; } else{ vert_interval_height = checkFiniteNumber(rect.h / (arr_val[arr_val.length - 1] - arr_val[0])); for (i = 0; i < arr_val.length; ++i) { arr_y_points[i] = rect.y + rect.h - (arr_val[i] - arr_val[0]) * vert_interval_height; } x_ax.posY = rect.y + rect.h - (arr_val[arr_val.length - 1] - arr_val[0]) * vert_interval_height; x_ax.labels.y = x_ax.posY - x_ax.labels.extY; var bCheckXLabels = false; if(x_ax.labels.y < 0){ bCheckXLabels = true; rect.y -= x_ax.labels.y; rect.h -= x_ax.labels.h; } if(x_ax.labels.y + x_ax.labels.extY > this.extY){ bCheckXLabels = true; rect.h -= (x_ax.labels.y + x_ax.labels.extY - this.extY) } if(bCheckXLabels){ vert_interval_height = checkFiniteNumber(rect.h / (arr_val[arr_val.length - 1] - arr_val[0])); for (i = 0; i < arr_val.length; ++i) { arr_y_points[i] = rect.y + rect.h - (arr_val[i] - arr_val[0]) * vert_interval_height; } x_ax.posY = rect.y + rect.h - (arr_val[arr_val.length - 1] - arr_val[0]) * vert_interval_height; x_ax.labels.y = x_ax.posY - x_ax.labels.extY; } } } else { if(!bWithoutLabels) { vert_interval_height = checkFiniteNumber((rect.h - first_vert_label_half_height - last_vert_label_half_height) / (arr_val[arr_val.length - 1] - arr_val[0])); if (first_vert_label_half_height + (crosses_x - arr_val[0]) * vert_interval_height < x_ax.labels.extY) { vert_interval_height = checkFiniteNumber((rect.h - x_ax.labels.extY - last_vert_label_half_height) / (arr_val[arr_val.length - 1] - crosses_x)); } x_ax.posY = rect.y + last_vert_label_half_height + (arr_val[arr_val.length - 1] - crosses_x) * vert_interval_height; x_ax.labels.y = x_ax.posY; for (i = 0; i < arr_val.length; ++i) { arr_y_points[i] = x_ax.posY - (arr_val[i] - crosses_x) * vert_interval_height; } } else{ vert_interval_height = checkFiniteNumber(rect.h / (arr_val[arr_val.length - 1] - arr_val[0])); x_ax.posY = rect.y + (arr_val[arr_val.length - 1] - crosses_x) * vert_interval_height; x_ax.labels.y = x_ax.posY; for (i = 0; i < arr_val.length; ++i) { arr_y_points[i] = x_ax.posY - (arr_val[i] - crosses_x) * vert_interval_height; } var bCheckXLabels = false; if(x_ax.labels.y < 0){ bCheckXLabels = true; rect.y -= x_ax.labels.y; rect.h -= x_ax.labels.h; } if(x_ax.labels.y + x_ax.labels.extY > this.extY){ bCheckXLabels = true; rect.h -= (x_ax.labels.y + x_ax.labels.extY - this.extY) } if(bCheckXLabels){ vert_interval_height = checkFiniteNumber(rect.h / (arr_val[arr_val.length - 1] - arr_val[0])); x_ax.posY = rect.y + (arr_val[arr_val.length - 1] - crosses_x) * vert_interval_height; x_ax.labels.y = x_ax.posY; for (i = 0; i < arr_val.length; ++i) { arr_y_points[i] = x_ax.posY - (arr_val[i] - crosses_x) * vert_interval_height; } } } } break; } } } else { switch(tick_labels_pos_x) { case c_oAscTickLabelsPos.TICK_LABEL_POSITION_HIGH: { bottom_gap = Math.max(last_vert_label_half_height, x_ax.labels.extY); if(!bWithoutLabels) { vert_interval_height = checkFiniteNumber((rect.h - bottom_gap - first_vert_label_half_height) / (arr_val[arr_val.length - 1] - arr_val[0])); x_ax.posY = rect.y + first_vert_label_half_height + (crosses_x - arr_val[0]) * vert_interval_height; for (i = 0; i < arr_val.length; ++i) { arr_y_points[i] = x_ax.posY + vert_interval_height * (arr_val[i] - crosses_x); } x_ax.labels.y = x_ax.posY + vert_interval_height * (arr_val[arr_val.length - 1] - crosses_x); } else{ vert_interval_height = checkFiniteNumber(rect.h / (arr_val[arr_val.length - 1] - arr_val[0])); x_ax.posY = rect.y + (crosses_x - arr_val[0]) * vert_interval_height; for (i = 0; i < arr_val.length; ++i) { arr_y_points[i] = x_ax.posY + vert_interval_height * (arr_val[i] - crosses_x); } x_ax.labels.y = x_ax.posY + vert_interval_height * (arr_val[arr_val.length - 1] - crosses_x); var bCheckXLabels = false; if(x_ax.labels.y < 0){ bCheckXLabels = true; rect.y -= x_ax.labels.y; rect.h -= x_ax.labels.h; } if(x_ax.labels.y + x_ax.labels.extY > this.extY){ bCheckXLabels = true; rect.h -= (x_ax.labels.y + x_ax.labels.extY - this.extY) } if(bCheckXLabels){ vert_interval_height = checkFiniteNumber(rect.h / (arr_val[arr_val.length - 1] - arr_val[0])); x_ax.posY = rect.y + (crosses_x - arr_val[0]) * vert_interval_height; for (i = 0; i < arr_val.length; ++i) { arr_y_points[i] = x_ax.posY + vert_interval_height * (arr_val[i] - crosses_x); } x_ax.labels.y = x_ax.posY + vert_interval_height * (arr_val[arr_val.length - 1] - crosses_x); } } break; } case c_oAscTickLabelsPos.TICK_LABEL_POSITION_LOW: { top_height = Math.max(x_ax.labels.extY, first_vert_label_half_height); bottom_align_labels = false; if(!bWithoutLabels) { vert_interval_height = checkFiniteNumber((rect.h - top_height - last_vert_label_half_height) / (arr_val[arr_val.length - 1] - arr_val[0])); x_ax.posY = rect.y + top_height + (crosses_x - arr_val[0]) * vert_interval_height; for (i = 0; i < arr_val.length; ++i) { arr_y_points[i] = rect.y + top_height + vert_interval_height * (arr_val[i] - arr_val[0]); } x_ax.labels.y = rect.y + top_height - x_ax.labels.extY; } else{ vert_interval_height = checkFiniteNumber(rect.h / (arr_val[arr_val.length - 1] - arr_val[0])); x_ax.posY = rect.y + (crosses_x - arr_val[0]) * vert_interval_height; for (i = 0; i < arr_val.length; ++i) { arr_y_points[i] = rect.y + vert_interval_height * (arr_val[i] - arr_val[0]); } x_ax.labels.y = rect.y - x_ax.labels.extY; var bCheckXLabels = false; if(x_ax.labels.y < 0){ bCheckXLabels = true; rect.y -= x_ax.labels.y; rect.h -= x_ax.labels.h; } if(x_ax.labels.y + x_ax.labels.extY > this.extY){ bCheckXLabels = true; rect.h -= (x_ax.labels.y + x_ax.labels.extY - this.extY) } if(bCheckXLabels){ vert_interval_height = checkFiniteNumber(rect.h / (arr_val[arr_val.length - 1] - arr_val[0])); x_ax.posY = rect.y + (crosses_x - arr_val[0]) * vert_interval_height; for (i = 0; i < arr_val.length; ++i) { arr_y_points[i] = rect.y + vert_interval_height * (arr_val[i] - arr_val[0]); } x_ax.labels.y = rect.y - x_ax.labels.extY; } } break; } case c_oAscTickLabelsPos.TICK_LABEL_POSITION_NONE: { x_ax.labels = null; if(!bWithoutLabels){ vert_interval_height = checkFiniteNumber((rect.h - first_vert_label_half_height - last_vert_label_half_height)/(arr_val[arr_val.length-1] - arr_val[0])); x_ax.posY = rect.y + first_vert_label_half_height + (crosses_x-arr_val[0])*vert_interval_height; for(i = 0; i < arr_val.length;++i) { arr_y_points[i] = rect.y + first_vert_label_half_height + vert_interval_height*(arr_val[i] - arr_val[0]); } } else{ vert_interval_height = checkFiniteNumber(rect.h/(arr_val[arr_val.length-1] - arr_val[0])); x_ax.posY = rect.y + (crosses_x-arr_val[0])*vert_interval_height; for(i = 0; i < arr_val.length;++i) { arr_y_points[i] = rect.y + vert_interval_height*(arr_val[i] - arr_val[0]); } } break; } default : {//c_oAscTickLabelsPos.TICK_LABEL_POSITION_NEXT_TO рядом с осью if(x_ax.crosses === AscFormat.CROSSES_MAX) { bottom_gap = Math.max(x_ax.labels.extY, last_vert_label_half_height); if(!bWithoutLabels) { vert_interval_height = checkFiniteNumber((rect.h - bottom_gap - first_vert_label_half_height) / (arr_val[arr_val.length - 1] - arr_val[0])); x_ax.posY = rect.y + first_vert_label_half_height + (crosses_x - arr_val[0]) * vert_interval_height; for (i = 0; i < arr_val.length; ++i) { arr_y_points[i] = rect.y + first_vert_label_half_height + vert_interval_height * (arr_val[i] - arr_val[0]); } x_ax.labels.y = rect.y + rect.extY - bottom_gap; } else{ vert_interval_height = checkFiniteNumber(rect.h / (arr_val[arr_val.length - 1] - arr_val[0])); x_ax.posY = rect.y + (crosses_x - arr_val[0]) * vert_interval_height; for (i = 0; i < arr_val.length; ++i) { arr_y_points[i] = rect.y + vert_interval_height * (arr_val[i] - arr_val[0]); } x_ax.labels.y = rect.y + rect.extY; var bCheckXLabels = false; if(x_ax.labels.y < 0){ bCheckXLabels = true; rect.y -= x_ax.labels.y; rect.h -= x_ax.labels.h; } if(x_ax.labels.y + x_ax.labels.extY > this.extY){ bCheckXLabels = true; rect.h -= (x_ax.labels.y + x_ax.labels.extY - this.extY) } if(bCheckXLabels){ vert_interval_height = checkFiniteNumber(rect.h / (arr_val[arr_val.length - 1] - arr_val[0])); x_ax.posY = rect.y + (crosses_x - arr_val[0]) * vert_interval_height; for (i = 0; i < arr_val.length; ++i) { arr_y_points[i] = rect.y + vert_interval_height * (arr_val[i] - arr_val[0]); } x_ax.labels.y = rect.y + rect.extY; } } } else { bottom_align_labels = false; if(!bWithoutLabels) { vert_interval_height = checkFiniteNumber((rect.h - last_vert_label_half_height - first_vert_label_half_height) / (arr_val[arr_val.length - 1] - arr_val[0])); if (first_vert_label_half_height + (crosses_x - arr_val[0]) * vert_interval_height < x_ax.labels.extY) { x_ax.posY = rect.y + x_ax.labels.extY; vert_interval_height = checkFiniteNumber((rect.h - x_ax.labels.extY - last_vert_label_half_height) / (arr_val[arr_val.length - 1] - crosses_x)); } else { x_ax.posY = rect.y + rect.h - vert_interval_height * (arr_val[arr_val.length - 1] - crosses_x) - last_vert_label_half_height; } x_ax.labels.y = x_ax.posY - x_ax.labels.extY; for (i = 0; i < arr_val.length; ++i) { arr_y_points[i] = x_ax.posY + vert_interval_height * (arr_val[i] - crosses_x); } } else{ vert_interval_height = checkFiniteNumber(rect.h / (arr_val[arr_val.length - 1] - arr_val[0])); x_ax.posY = rect.y + rect.h - vert_interval_height * (arr_val[arr_val.length - 1] - crosses_x); x_ax.labels.y = x_ax.posY - x_ax.labels.extY; for (i = 0; i < arr_val.length; ++i) { arr_y_points[i] = x_ax.posY + vert_interval_height * (arr_val[i] - crosses_x); } var bCheckXLabels = false; if(x_ax.labels.y < 0){ bCheckXLabels = true; rect.y -= x_ax.labels.y; rect.h -= x_ax.labels.h; } if(x_ax.labels.y + x_ax.labels.extY > this.extY){ bCheckXLabels = true; rect.h -= (x_ax.labels.y + x_ax.labels.extY - this.extY) } if(bCheckXLabels){ vert_interval_height = checkFiniteNumber(rect.h / (arr_val[arr_val.length - 1] - arr_val[0])); x_ax.posY = rect.y + rect.h - vert_interval_height * (arr_val[arr_val.length - 1] - crosses_x); x_ax.labels.y = x_ax.posY - x_ax.labels.extY; for (i = 0; i < arr_val.length; ++i) { arr_y_points[i] = x_ax.posY + vert_interval_height * (arr_val[i] - crosses_x); } } } } break; } } } y_ax.interval = vert_interval_height; y_ax.yPoints = []; for(i = 0; i < arr_val.length; ++i) { y_ax.yPoints.push({pos: arr_y_points[i], val: arr_val[i]}); } x_ax.xPoints = []; for(i = 0; i < arr_x_val.length; ++i) { x_ax.xPoints.push({pos: arr_x_points[i], val: arr_x_val[i]}); } var arr_labels; var text_transform; var local_text_transform; if(x_ax.bDelete) { x_ax.labels = null; } if(y_ax.bDelete) { y_ax.labels = null; } if(x_ax.labels) { arr_labels = x_ax.labels.aLabels; x_ax.labels.align = bottom_align_labels; if(bottom_align_labels) { var top_line = x_ax.labels.y + vert_gap; for(i = 0; i < arr_labels.length; ++i) { if(arr_labels[i]) { arr_labels[i].txBody = arr_labels[i].tx.rich; text_transform = arr_labels[i].transformText; text_transform.Reset(); global_MatrixTransformer.TranslateAppend(text_transform, arr_x_points[i] - arr_labels[i].tx.rich.content.XLimit/2, top_line); // global_MatrixTransformer.MultiplyAppend(text_transform, this.getTransformMatrix()); local_text_transform = arr_labels[i].localTransformText; local_text_transform.Reset(); global_MatrixTransformer.TranslateAppend(local_text_transform, arr_x_points[i] - arr_labels[i].tx.rich.content.XLimit/2, top_line); } } } else { for(i = 0; i < arr_labels.length; ++i) { if(arr_labels[i]) { arr_labels[i].txBody = arr_labels[i].tx.rich; text_transform = arr_labels[i].transformText; text_transform.Reset(); global_MatrixTransformer.TranslateAppend(text_transform, arr_x_points[i] - arr_labels[i].tx.rich.content.XLimit/2, x_ax.labels.y + x_ax.labels.extY - vert_gap - arr_labels[i].tx.rich.content.GetSummaryHeight()); // global_MatrixTransformer.MultiplyAppend(text_transform, this.getTransformMatrix()); local_text_transform = arr_labels[i].localTransformText; local_text_transform.Reset(); global_MatrixTransformer.TranslateAppend(local_text_transform, arr_x_points[i] - arr_labels[i].tx.rich.content.XLimit/2, x_ax.labels.y + x_ax.labels.extY - vert_gap - arr_labels[i].tx.rich.content.GetSummaryHeight()); } } } } if(y_ax.labels) { if(bNeedReflect) { if(left_align_labels) { left_align_labels = false; y_ax.labels.x += y_ax.labels.extX; } else { left_align_labels = true; y_ax.labels.x -= y_ax.labels.extX; } } y_ax.labels.align = left_align_labels; arr_labels = y_ax.labels.aLabels; if(left_align_labels) { for(i = 0; i < arr_labels.length; ++i) { if(arr_labels[i]) { arr_labels[i].txBody = arr_labels[i].tx.rich; text_transform = arr_labels[i].transformText; text_transform.Reset(); global_MatrixTransformer.TranslateAppend(text_transform, y_ax.labels.x + y_ax.labels.extX - hor_gap - arr_labels[i].tx.rich.content.XLimit, arr_y_points[i] - arr_labels[i].tx.rich.content.GetSummaryHeight()/2); // global_MatrixTransformer.MultiplyAppend(text_transform, this.getTransformMatrix()); local_text_transform = arr_labels[i].localTransformText; local_text_transform.Reset(); global_MatrixTransformer.TranslateAppend(local_text_transform, y_ax.labels.x + y_ax.labels.extX - hor_gap - arr_labels[i].tx.rich.content.XLimit, arr_y_points[i] - arr_labels[i].tx.rich.content.GetSummaryHeight()/2); } } } else { for(i = 0; i < arr_labels.length; ++i) { if(arr_labels[i]) { arr_labels[i].txBody = arr_labels[i].tx.rich; text_transform = arr_labels[i].transformText; text_transform.Reset(); global_MatrixTransformer.TranslateAppend(text_transform, y_ax.labels.x + hor_gap, arr_y_points[i] - arr_labels[i].tx.rich.content.GetSummaryHeight()/2); // global_MatrixTransformer.MultiplyAppend(text_transform, this.getTransformMatrix()); local_text_transform = arr_labels[i].transformText; local_text_transform.Reset(); global_MatrixTransformer.TranslateAppend(local_text_transform, y_ax.labels.x + hor_gap, arr_y_points[i] - arr_labels[i].tx.rich.content.GetSummaryHeight()/2); } } } } if(y_ax.labels) { if(y_ax_orientation === AscFormat.ORIENTATION_MIN_MAX) { var t = y_ax.labels.aLabels[y_ax.labels.aLabels.length-1].tx.rich.content.GetSummaryHeight()/2; y_ax.labels.y = arr_y_points[arr_y_points.length-1] - t; y_ax.labels.extY = arr_y_points[0] - arr_y_points[arr_y_points.length-1] + t + y_ax.labels.aLabels[0].tx.rich.content.GetSummaryHeight()/2; } else { var t = y_ax.labels.aLabels[0].tx.rich.content.GetSummaryHeight()/2; y_ax.labels.y = arr_y_points[0] - t; y_ax.labels.extY = arr_y_points[arr_y_points.length-1] - arr_y_points[0] + t + y_ax.labels.aLabels[y_ax.labels.aLabels.length-1].tx.rich.content.GetSummaryHeight()/2; } } if(x_ax.labels) { if(x_ax_orientation === AscFormat.ORIENTATION_MIN_MAX) { var t = x_ax.labels.aLabels[0].tx.rich.content.XLimit/2; x_ax.labels.x = arr_x_points[0] - t; x_ax.labels.extX = arr_x_points[arr_x_points.length-1] + x_ax.labels.aLabels[x_ax.labels.aLabels.length-1].tx.rich.content.XLimit/2 - x_ax.labels.x; } else { var t = x_ax.labels.aLabels[x_ax.labels.aLabels.length-1].tx.rich.content.XLimit/2; x_ax.labels.x = arr_x_points[arr_x_points.length-1] - t; x_ax.labels.extX = arr_x_points[0] + x_ax.labels.aLabels[0].tx.rich.content.XLimit/2 - x_ax.labels.x; } } /*new recalc*/ } } else if(chart_type !== AscDFH.historyitem_type_BarChart && (chart_type !== AscDFH.historyitem_type_PieChart && chart_type !== AscDFH.historyitem_type_DoughnutChart) || (chart_type === AscDFH.historyitem_type_BarChart && chart_object.barDir !== AscFormat.BAR_DIR_BAR)) { var cat_ax, val_ax, ser_ax; val_ax = this.chart.plotArea.valAx; cat_ax = this.chart.plotArea.catAx; ser_ax = this.chart.plotArea.serAx; if(val_ax && cat_ax) { val_ax.labels = null; cat_ax.labels = null; if(ser_ax){ ser_ax.labels = null; ser_ax.posY = null; ser_ax.posX = null; ser_ax.xPoints = null; ser_ax.yPoints = null; } val_ax.posX = null; cat_ax.posY = null; val_ax.posY = null; cat_ax.posX = null; val_ax.xPoints = null; cat_ax.yPoints = null; val_ax.yPoints = null; cat_ax.xPoints = null; var sizes = this.getChartSizes(); rect = {x: sizes.startX, y:sizes.startY, w:sizes.w, h: sizes.h}; var arr_val = this.getValAxisValues(); //Получим строки для оси значений с учетом формата и единиц var arr_strings = []; var multiplier; if(val_ax.dispUnits) multiplier = val_ax.dispUnits.getMultiplier(); else multiplier = 1; var num_fmt = val_ax.numFmt; if(num_fmt && typeof num_fmt.formatCode === "string" /*&& !(num_fmt.formatCode === "General")*/) { var num_format = oNumFormatCache.get(num_fmt.formatCode); for(i = 0; i < arr_val.length; ++i) { var calc_value = arr_val[i]*multiplier; var rich_value = num_format.formatToChart(calc_value); arr_strings.push(rich_value); } } else { for(i = 0; i < arr_val.length; ++i) { var calc_value = arr_val[i]*multiplier; arr_strings.push(calc_value + ""); } } /*если у нас шкала логарифмическая то будем вместо полученных значений использовать логарифм*/ val_ax.labels = new AscFormat.CValAxisLabels(this, val_ax); var max_width = 0; val_ax.yPoints = []; var max_val_labels_text_height = 0; var lastStyleObject = null; for(i = 0; i < arr_strings.length; ++i) { var dlbl = new AscFormat.CDLbl(); if(lastStyleObject) { dlbl.lastStyleObject = lastStyleObject; } dlbl.parent = val_ax; dlbl.chart = this; dlbl.spPr = val_ax.spPr; dlbl.txPr = val_ax.txPr; dlbl.tx = new AscFormat.CChartText(); dlbl.tx.rich = AscFormat.CreateTextBodyFromString(arr_strings[i], this.getDrawingDocument(), dlbl); var t = dlbl.tx.rich.recalculateByMaxWord(); if(!lastStyleObject) { lastStyleObject = dlbl.lastStyleObject; } var cur_width = t.w; if(cur_width > max_width) max_width = cur_width; if(t.h > max_val_labels_text_height) max_val_labels_text_height = t.h; val_ax.labels.aLabels.push(dlbl); val_ax.yPoints.push({val: arr_val[i], pos: null}); } var val_axis_labels_gap = val_ax.labels.aLabels[0].tx.rich.content.Content[0].CompiledPr.Pr.TextPr.FontSize*25.4/72; val_ax.labels.extX = max_width + val_axis_labels_gap; //расчитаем подписи для горизонтальной оси var ser = chart_object.series[0]; var string_pts = [], pts_len = 0; /*string_pts pts_len*/ if(ser && ser.cat) { var lit, b_num_lit = true; if(ser.cat.strRef && ser.cat.strRef.strCache) { lit = ser.cat.strRef.strCache; } else if(ser.cat.strLit) { lit = ser.cat.strLit; } else if(ser.cat.numRef && ser.cat.numRef.numCache) { lit = ser.cat.numRef.numCache; b_num_lit = true; } else if(ser.cat.numLit) { lit = ser.cat.numLit; b_num_lit = true; } if(lit) { var lit_format = null, pt_format = null; if(b_num_lit && typeof lit.formatCode === "string" && lit.formatCode.length > 0) { lit_format = oNumFormatCache.get(lit.formatCode); } pts_len = lit.ptCount; for(i = 0; i < pts_len; ++i) { var pt = lit.getPtByIndex(i); if(pt) { var str_pt; if(b_num_lit) { if(typeof pt.formatCode === "string" && pt.formatCode.length > 0) { pt_format = oNumFormatCache.get(pt.formatCode); if(pt_format) { str_pt = pt_format.formatToChart(pt.val); } else { str_pt = pt.val; } } else if(lit_format) { str_pt = lit_format.formatToChart(pt.val); } else { str_pt = pt.val; } } else { str_pt = pt.val; } string_pts.push({val: str_pt + ""}); } else { string_pts.push({val: /*i + */""}); } } } } var cross_between = this.getValAxisCrossType(); if(cross_between === null){ cross_between = AscFormat.CROSS_BETWEEN_BETWEEN; } //if(string_pts.length === 0) { pts_len = 0; for(i = 0; i < chart_object.series.length; ++i) { var cur_pts= null; ser = chart_object.series[i]; if(ser.val) { if(ser.val.numRef && ser.val.numRef.numCache) cur_pts = ser.val.numRef.numCache; else if(ser.val.numLit) cur_pts = ser.val.numLit; if(cur_pts) { pts_len = Math.max(pts_len, cur_pts.ptCount); } } } if(cross_between === AscFormat.CROSS_BETWEEN_MID_CAT && pts_len < 2) { pts_len = 2; } if(pts_len > string_pts.length) { for(i = string_pts.length; i < pts_len; ++i) { string_pts.push({val:i+1 + ""}); } } else { string_pts.splice(pts_len, string_pts.length - pts_len); } } /*---------------------расчет позиции блока с подписями вертикальной оси-----------------------------------------------------------------------------*/ //расчитаем ширину интервала без учета горизонтальной оси; var crosses;//номер категории в которой вертикалная ось пересекает горизонтальную; if(val_ax.crosses === AscFormat.CROSSES_AUTO_ZERO || val_ax.crosses === AscFormat.CROSSES_MIN) crosses = 1; else if(val_ax.crosses === AscFormat.CROSSES_MAX) crosses = string_pts.length; else if(AscFormat.isRealNumber(val_ax.crossesAt)) { if(val_ax.crossesAt <= string_pts.length + 1 && val_ax.crossesAt > 0) crosses = val_ax.crossesAt; else if(val_ax.crossesAt <= 0) crosses = 1; else crosses = string_pts.length; } else crosses = 1; cat_ax.maxCatVal = string_pts.length; var cat_ax_orientation = cat_ax.scaling && AscFormat.isRealNumber(cat_ax.scaling.orientation) ? cat_ax.scaling.orientation : AscFormat.ORIENTATION_MIN_MAX; var point_width = rect.w/string_pts.length; var labels_pos = val_ax.tickLblPos; if(val_ax.bDelete) { labels_pos = c_oAscTickLabelsPos.TICK_LABEL_POSITION_NONE; } // if(string_pts.length === 1) // { // cross_between = AscFormat.CROSS_BETWEEN_BETWEEN; // } var left_val_ax_labels_align = true;//приленгание подписей оси значений к левому краю. var intervals_count = cross_between === AscFormat.CROSS_BETWEEN_MID_CAT ? string_pts.length - 1 : string_pts.length; var point_interval = rect.w/intervals_count;//интервал между точками. Зависит от crossBetween, а также будет потом корректироваться в зависимости от подписей вертикальной и горизонтальной оси. if(cross_between === AscFormat.CROSS_BETWEEN_MID_CAT) point_interval = checkFiniteNumber(rect.w/(string_pts.length - 1)); else point_interval = checkFiniteNumber(rect.w/string_pts.length); var left_points_width, right_point_width; var arr_cat_labels_points = [];//массив середин подписей горизонтальной оси; i-й элемент - x-координата центра подписи категории с номером i; if(cat_ax_orientation === AscFormat.ORIENTATION_MIN_MAX) { if(labels_pos === c_oAscTickLabelsPos.TICK_LABEL_POSITION_NEXT_TO || !AscFormat.isRealNumber(labels_pos)) //подписи рядом с осью { if(val_ax.crosses === AscFormat.CROSSES_MAX) { left_val_ax_labels_align = false; if(!bWithoutLabels){ val_ax.labels.x = rect.x + rect.w - val_ax.labels.extX; if(!bNeedReflect) { point_interval = checkFiniteNumber((rect.w - val_ax.labels.extX)/intervals_count); } else { point_interval = checkFiniteNumber(rect.w/intervals_count); } val_ax.posX = val_ax.labels.x; if(cross_between === AscFormat.CROSS_BETWEEN_MID_CAT) { for(i = 0; i < string_pts.length; ++i) arr_cat_labels_points[i] = rect.x + point_interval*i; } else { for(i = 0; i < string_pts.length; ++i) arr_cat_labels_points[i] = point_interval/2 + rect.x + point_interval*i; } } else{ val_ax.labels.x = rect.x + rect.w; if(val_ax.labels.x < 0 && !bNeedReflect){ rect.x -= val_ax.labels.x; rect.w += val_ax.labels.x; val_ax.labels.x = 0; bCorrectedLayoutRect = true; } if(rect.x + rect.w > this.extX){ rect.w -= (rect.x + rect.w - this.extX); bCorrectedLayoutRect = true; } point_interval = checkFiniteNumber(rect.w/intervals_count); val_ax.posX = val_ax.labels.x; if(cross_between === AscFormat.CROSS_BETWEEN_MID_CAT) { for(i = 0; i < string_pts.length; ++i) arr_cat_labels_points[i] = rect.x + point_interval*i; } else { for(i = 0; i < string_pts.length; ++i) arr_cat_labels_points[i] = point_interval/2 + rect.x + point_interval*i; } } } else { left_points_width = point_interval*(crosses-1);//общая ширина левых точек если считать что точки занимают все пространство if(!bWithoutLabels) { if (!bNeedReflect && left_points_width < val_ax.labels.extX)//подписи верт. оси выходят за пределы области построения { var right_intervals_count = intervals_count - (crosses - 1);//количесво интервалов правее вертикальной оси //скорректируем point_interval, поделив расстояние, которое осталось справа от подписей осей на количество интервалов справа point_interval = checkFiniteNumber((rect.w - val_ax.labels.extX) / right_intervals_count); val_ax.labels.x = rect.x; var start_point = val_ax.labels.x + val_ax.labels.extX - (crosses - 1) * point_interval;//x-координата точки, где начинается собственно область диаграммы if (cross_between === AscFormat.CROSS_BETWEEN_MID_CAT) { for (i = 0; i < string_pts.length; ++i) arr_cat_labels_points[i] = start_point + point_interval * i; } else { for (i = 0; i < string_pts.length; ++i) arr_cat_labels_points[i] = point_interval / 2 + start_point + point_interval * i; } } else { val_ax.labels.x = rect.x + left_points_width - val_ax.labels.extX; if (cross_between === AscFormat.CROSS_BETWEEN_MID_CAT) { for (i = 0; i < string_pts.length; ++i) arr_cat_labels_points[i] = rect.x + point_interval * i; } else { for (i = 0; i < string_pts.length; ++i) arr_cat_labels_points[i] = point_interval / 2 + rect.x + point_interval * i; } } val_ax.posX = val_ax.labels.x + val_ax.labels.extX; } else{ val_ax.labels.x = rect.x + left_points_width - val_ax.labels.extX; if(val_ax.labels.x < 0 && !bNeedReflect){ rect.x -= val_ax.labels.x; rect.w += val_ax.labels.x; val_ax.labels.x = 0; bCorrectedLayoutRect = true; } if(rect.x + rect.w > this.extX){ rect.w -= (rect.x + rect.w - this.extX); bCorrectedLayoutRect = true; } point_interval = checkFiniteNumber( rect.w/intervals_count); if (cross_between === AscFormat.CROSS_BETWEEN_MID_CAT) { for (i = 0; i < string_pts.length; ++i) arr_cat_labels_points[i] = rect.x + point_interval * i; } else { for (i = 0; i < string_pts.length; ++i) arr_cat_labels_points[i] = point_interval / 2 + rect.x + point_interval * i; } val_ax.posX = val_ax.labels.x + val_ax.labels.extX; } } } else if(labels_pos === c_oAscTickLabelsPos.TICK_LABEL_POSITION_LOW)//подписи слева от области построения { if(!bNeedReflect) { point_interval = checkFiniteNumber((rect.w - val_ax.labels.extX)/intervals_count); } else { point_interval = checkFiniteNumber( rect.w/intervals_count); } val_ax.labels.x = rect.x; if(cross_between === AscFormat.CROSS_BETWEEN_MID_CAT) { if(!bNeedReflect) { for(i = 0; i < string_pts.length; ++i) arr_cat_labels_points[i] = rect.x + val_ax.labels.extX + point_interval*i; } else { for(i = 0; i < string_pts.length; ++i) arr_cat_labels_points[i] = rect.x + point_interval*i; } } else { if(!bNeedReflect) { for(i = 0; i < string_pts.length; ++i) arr_cat_labels_points[i] = rect.x + val_ax.labels.extX + point_interval/2 + point_interval*i; } else { for(i = 0; i < string_pts.length; ++i) arr_cat_labels_points[i] = rect.x + point_interval/2 + point_interval*i; } } val_ax.posX = val_ax.labels.x + val_ax.labels.extX + point_interval*(crosses-1); } else if(labels_pos === c_oAscTickLabelsPos.TICK_LABEL_POSITION_HIGH)//подписи справа от области построения { if(!bNeedReflect) { point_interval = checkFiniteNumber( (rect.w - val_ax.labels.extX)/intervals_count); } else { point_interval = checkFiniteNumber( rect.w/intervals_count); } val_ax.labels.x = rect.x + rect.w - val_ax.labels.extX; left_val_ax_labels_align = false; if(cross_between === AscFormat.CROSS_BETWEEN_MID_CAT) { for(i = 0; i < string_pts.length; ++i) arr_cat_labels_points[i] = rect.x + point_interval*i; } else { for(i = 0; i < string_pts.length; ++i) arr_cat_labels_points[i] = point_interval/2 + rect.x + point_interval*i; } val_ax.posX = rect.x + point_interval*(crosses-1); } else { val_ax.labels = null; if(cross_between === AscFormat.CROSS_BETWEEN_MID_CAT) { for(i = 0; i < string_pts.length; ++i) arr_cat_labels_points[i] = rect.x + point_interval*i; } else { for(i = 0; i < string_pts.length; ++i) arr_cat_labels_points[i] = point_interval/2 + rect.x + point_interval*i; } val_ax.posX = rect.x + point_interval*(crosses-1); } } else {//то же самое, только зеркально отраженное if(labels_pos === c_oAscTickLabelsPos.TICK_LABEL_POSITION_NEXT_TO || !AscFormat.isRealNumber(labels_pos)) //подписи рядом с осью { if(val_ax.crosses === AscFormat.CROSSES_MAX) { if(!bWithoutLabels){ val_ax.labels.x = rect.x; if(!bNeedReflect) { point_interval = checkFiniteNumber( (rect.w - val_ax.labels.extX)/intervals_count); } else { point_interval = checkFiniteNumber( rect.w/intervals_count); } if(cross_between === AscFormat.CROSS_BETWEEN_MID_CAT) { for(i = 0; i < string_pts.length; ++i) arr_cat_labels_points[i] = rect.x + rect.w - point_interval*i; } else { for(i = 0; i < string_pts.length; ++i) arr_cat_labels_points[i] = rect.x + rect.w - point_interval/2 - point_interval*i; } if(!bNeedReflect) { val_ax.posX = val_ax.labels.x + val_ax.labels.extX; } else { val_ax.posX = val_ax.labels.x; } } else{ val_ax.labels.x = rect.x - val_ax.labels.extX; if(val_ax.labels.x < 0 && !bNeedReflect){ rect.x -= val_ax.labels.x; rect.w += val_ax.labels.x; val_ax.labels.x = 0; bCorrectedLayoutRect = true; } if(rect.x + rect.w > this.extX){ rect.w -= (rect.x + rect.w - this.extX); bCorrectedLayoutRect = true; } point_interval = checkFiniteNumber( rect.w/intervals_count); if(cross_between === AscFormat.CROSS_BETWEEN_MID_CAT) { for(i = 0; i < string_pts.length; ++i) arr_cat_labels_points[i] = rect.x + rect.w - point_interval*i; } else { for(i = 0; i < string_pts.length; ++i) arr_cat_labels_points[i] = rect.x + rect.w - point_interval/2 - point_interval*i; } if(!bNeedReflect) { val_ax.posX = val_ax.labels.x + val_ax.labels.extX; } else { val_ax.posX = val_ax.labels.x; } } } else { left_val_ax_labels_align = false; right_point_width = point_interval*(crosses-1); if(!bNeedReflect && right_point_width < val_ax.labels.extX && !bWithoutLabels) { val_ax.labels.x = rect.x + rect.w - val_ax.labels.extX; var left_points_interval_count = intervals_count - (crosses - 1); point_interval = checkFiniteNumber( checkFiniteNumber( (val_ax.labels.x - rect.x)/left_points_interval_count)); var start_point_right = rect.x + point_interval*intervals_count; if(cross_between === AscFormat.CROSS_BETWEEN_MID_CAT) { for(i = 0; i < string_pts.length; ++i) arr_cat_labels_points[i] = start_point_right - point_interval*i; } else { for(i = 0; i < string_pts.length; ++i) arr_cat_labels_points[i] = start_point_right - point_interval/2 - point_interval*i; } } else { val_ax.labels.x = rect.x + rect.w - right_point_width; if(val_ax.labels.x < 0 && !bNeedReflect){ rect.x -= val_ax.labels.x; rect.w += val_ax.labels.x; val_ax.labels.x = 0; bCorrectedLayoutRect = true; } if(rect.x + rect.w > this.extX){ rect.w -= (rect.x + rect.w - this.extX); bCorrectedLayoutRect = true; } point_interval = checkFiniteNumber( rect.w/intervals_count); if(cross_between === AscFormat.CROSS_BETWEEN_MID_CAT) { for(i = 0; i < string_pts.length; ++i) arr_cat_labels_points[i] = rect.x + rect.w - point_interval*i; } else { for(i = 0; i < string_pts.length; ++i) arr_cat_labels_points[i] = rect.x + rect.w - point_interval/2 - point_interval*i; } } val_ax.posX = val_ax.labels.x; } } else if(labels_pos === c_oAscTickLabelsPos.TICK_LABEL_POSITION_LOW)//подписи справа от области построения { left_val_ax_labels_align = false; if(!bNeedReflect && !bWithoutLabels) { point_interval = checkFiniteNumber( (rect.w - val_ax.labels.extX)/intervals_count); } else { point_interval = checkFiniteNumber( rect.w/intervals_count); } if(!bWithoutLabels){ val_ax.labels.x = rect.x + rect.w - val_ax.labels.extX; if(cross_between === AscFormat.CROSS_BETWEEN_MID_CAT) { for(i = 0; i < string_pts.length; ++i) arr_cat_labels_points[i] = val_ax.labels.x - point_interval*i; } else { for(i = 0; i < string_pts.length; ++i) arr_cat_labels_points[i] = val_ax.labels.x - point_interval/2 - point_interval*i; } if(!bNeedReflect) { val_ax.posX = rect.x + rect.w - point_interval*(crosses-1) - val_ax.labels.extX; } else { val_ax.posX = rect.x + rect.w - point_interval*(crosses-1); } } else{ val_ax.labels.x = rect.x + rect.w; if(val_ax.labels.x < 0 && !bNeedReflect){ rect.x -= val_ax.labels.x; rect.w += val_ax.labels.x; val_ax.labels.x = 0; bCorrectedLayoutRect = true; } if(rect.x + rect.w > this.extX){ rect.w -= (rect.x + rect.w - this.extX); bCorrectedLayoutRect = true; } point_interval = checkFiniteNumber(rect.w/intervals_count); if(cross_between === AscFormat.CROSS_BETWEEN_MID_CAT) { for(i = 0; i < string_pts.length; ++i) arr_cat_labels_points[i] = val_ax.labels.x - point_interval*i; } else { for(i = 0; i < string_pts.length; ++i) arr_cat_labels_points[i] = val_ax.labels.x - point_interval/2 - point_interval*i; } if(!bNeedReflect) { val_ax.posX = rect.x + rect.w - point_interval*(crosses-1) - val_ax.labels.extX; } else { val_ax.posX = rect.x + rect.w - point_interval*(crosses-1); } } } else if(labels_pos === c_oAscTickLabelsPos.TICK_LABEL_POSITION_HIGH)//подписи слева от области построения { if(!bNeedReflect && !bWithoutLabels) { point_interval = checkFiniteNumber((rect.w - val_ax.labels.extX)/intervals_count); } else { point_interval = checkFiniteNumber(rect.w/intervals_count); } if(!bWithoutLabels){ val_ax.labels.x = rect.x; if(cross_between === AscFormat.CROSS_BETWEEN_MID_CAT) { for(i = 0; i < string_pts.length; ++i) arr_cat_labels_points[i] = rect.x + rect.w - point_interval*i; } else { for(i = 0; i < string_pts.length; ++i) arr_cat_labels_points[i] = rect.x + rect.w - point_interval/2 - point_interval*i; } val_ax.posX = rect.x + rect.w - point_interval*(crosses-1); } else{ val_ax.labels.x = rect.x - val_ax.labels.extX; if(val_ax.labels.x < 0 && !bNeedReflect){ rect.x -= val_ax.labels.x; rect.w += val_ax.labels.x; val_ax.labels.x = 0; bCorrectedLayoutRect = true; } if(rect.x + rect.w > this.extX){ rect.w -= (rect.x + rect.w - this.extX); bCorrectedLayoutRect = true; } point_interval = checkFiniteNumber(rect.w/intervals_count); if(cross_between === AscFormat.CROSS_BETWEEN_MID_CAT) { for(i = 0; i < string_pts.length; ++i) arr_cat_labels_points[i] = rect.x + rect.w - point_interval*i; } else { for(i = 0; i < string_pts.length; ++i) arr_cat_labels_points[i] = rect.x + rect.w - point_interval/2 - point_interval*i; } val_ax.posX = rect.x + rect.w - point_interval*(crosses-1); } } else { val_ax.labels = null; if(cross_between === AscFormat.CROSS_BETWEEN_MID_CAT) { for(i = 0; i < string_pts.length; ++i) arr_cat_labels_points[i] = rect.x + rect.w - point_interval*i; } else { for(i = 0; i < string_pts.length; ++i) arr_cat_labels_points[i] = rect.x + rect.w - point_interval/2 - point_interval*i; } val_ax.posX = rect.x + rect.w - point_interval*(crosses-1); } } cat_ax.interval = point_interval; var diagram_width = point_interval*intervals_count;//размер области с самой диаграммой позже будет корректироватся; var bTickSkip = AscFormat.isRealNumber(cat_ax.tickLblSkip); var tick_lbl_skip = AscFormat.isRealNumber(cat_ax.tickLblSkip) ? cat_ax.tickLblSkip : 1; var max_cat_label_width = diagram_width / string_pts.length; // максимальная ширина подписи горизонтальной оси; cat_ax.labels = null; var b_rotated = false;//флаг означает, что водписи не уместились в отведенное для них пространство и их пришлось перевернуть. //проверим умещаются ли подписи горизонтальной оси в point_interval if(c_oAscTickLabelsPos.TICK_LABEL_POSITION_NONE !== cat_ax.tickLblPos && !(cat_ax.bDelete === true)) //будем корректировать вертикальные подписи только если есть горизонтальные { cat_ax.labels = new AscFormat.CValAxisLabels(this, cat_ax); var max_min_width = 0; var max_max_width = 0; var arr_max_contents = []; var fMaxContentStringH = 0; for(i = 0; i < string_pts.length; ++i) { var dlbl = null; if(i%tick_lbl_skip === 0) { dlbl = new AscFormat.CDLbl(); dlbl.parent = cat_ax; dlbl.chart = this; dlbl.spPr = cat_ax.spPr; dlbl.txPr = cat_ax.txPr; dlbl.tx = new AscFormat.CChartText(); dlbl.tx.rich = AscFormat.CreateTextBodyFromString(string_pts[i].val.replace(oNonSpaceRegExp, ' '), this.getDrawingDocument(), dlbl); //dlbl.recalculate(); var content = dlbl.tx.rich.content; content.Set_ApplyToAll(true); content.SetParagraphAlign(AscCommon.align_Center); content.Set_ApplyToAll(false); dlbl.txBody = dlbl.tx.rich; if(cat_ax.labels.aLabels.length > 0) { dlbl.lastStyleObject = cat_ax.labels.aLabels[0].lastStyleObject; } var min_max = dlbl.tx.rich.content.RecalculateMinMaxContentWidth(); var max_min_content_width = min_max.Min; if(max_min_content_width > max_min_width) max_min_width = max_min_content_width; if(min_max.Max > max_max_width) max_max_width = min_max.Max; if(dlbl.tx.rich.content.Content[0].Content[0].TextHeight > fMaxContentStringH){ fMaxContentStringH = dlbl.tx.rich.content.Content[0].Content[0].TextHeight; } } cat_ax.labels.aLabels.push(dlbl); } fMaxContentStringH *= 1; var stake_offset = AscFormat.isRealNumber(cat_ax.lblOffset) ? cat_ax.lblOffset/100 : 1; var labels_offset = cat_ax.labels.aLabels[0].tx.rich.content.Content[0].CompiledPr.Pr.TextPr.FontSize*(25.4/72)*stake_offset; if(max_min_width < max_cat_label_width)//значит текст каждой из точек умещается в point_width { var max_height = 0; for(i = 0; i < cat_ax.labels.aLabels.length; ++i) { if(cat_ax.labels.aLabels[i]) { var content = cat_ax.labels.aLabels[i].tx.rich.content; content.Reset(0, 0, max_cat_label_width, 20000); content.Recalculate_Page(0, true); var cur_height = content.GetSummaryHeight(); if(cur_height > max_height) max_height = cur_height; } } cat_ax.labels.extY = max_height + labels_offset; if(cross_between === AscFormat.CROSS_BETWEEN_MID_CAT) //корректируем позиции центров подписей горизонтальной оси, положение вертикальной оси и её подписей { var left_gap_point, right_gap_point; if(cat_ax_orientation === AscFormat.ORIENTATION_MIN_MAX) { var first_label_left_gap = cat_ax.labels.aLabels[0].tx.rich.getMaxContentWidth(max_cat_label_width)/2;//на сколько вправа выходит первая подпись var last_labels_right_gap = cat_ax.labels.aLabels[cat_ax.labels.aLabels.length - 1] ? cat_ax.labels.aLabels[cat_ax.labels.aLabels.length - 1].tx.rich.getMaxContentWidth(max_cat_label_width)/2 : 0; //смотрим, выходит ли подпись первой категориии выходит за пределы области построения left_gap_point = arr_cat_labels_points[0] - first_label_left_gap; if(rect.x > left_gap_point && !bWithoutLabels) { if(val_ax.labels)//скорректируем позицию подписей вертикальной оси, если они есть { val_ax.labels.x = rect.x + (val_ax.labels.x - left_gap_point)*checkFiniteNumber((rect.w/(rect.x + rect.w - left_gap_point))); } //скорректируем point_interval point_interval *= checkFiniteNumber((rect.w/(rect.x + rect.w - left_gap_point))); //скорректируем arr_cat_labels_points for(i = 0; i < arr_cat_labels_points.length; ++i) { arr_cat_labels_points[i] = rect.x + (arr_cat_labels_points[i] - left_gap_point)*checkFiniteNumber((rect.w/(rect.x + rect.w - left_gap_point))); } //скорректируем позицию вертикальной оси val_ax.posX = rect.x + (val_ax.posX - left_gap_point)*checkFiniteNumber((rect.w/(rect.x + rect.w - left_gap_point))); } //смотри выходит ли подпись последней категории за пределы области построения right_gap_point = arr_cat_labels_points[arr_cat_labels_points.length - 1] + last_labels_right_gap; if(right_gap_point > rect.x + rect.w && !bWithoutLabels) { if(val_ax.labels)//скорректируем позицию подписей вертикальной оси { val_ax.labels.x = rect.x + (val_ax.labels.x - rect.x)*checkFiniteNumber((rect.w/(right_gap_point - rect.x))); } //скорректируем point_interval point_interval *= checkFiniteNumber((rect.w/(right_gap_point - rect.x))); for(i = 0; i < arr_cat_labels_points.length; ++i) { arr_cat_labels_points[i] = rect.x + (arr_cat_labels_points[i] - rect.x)*checkFiniteNumber((rect.w/(right_gap_point - rect.x))); } //скорректируем позицию вертикальной оси val_ax.posX = rect.x + (val_ax.posX - rect.x)*checkFiniteNumber((rect.w/(right_gap_point - rect.x))); } } else { var last_label_left_gap = cat_ax.labels.aLabels[cat_ax.labels.aLabels.length - 1] ? cat_ax.labels.aLabels[cat_ax.labels.aLabels.length - 1].tx.rich.getMaxContentWidth(max_cat_label_width)/2 : 0; var first_label_right_gap = cat_ax.labels.aLabels[0].tx.rich.getMaxContentWidth(max_cat_label_width)/2; left_gap_point = arr_cat_labels_points[arr_cat_labels_points.length - 1] - last_label_left_gap; right_gap_point = arr_cat_labels_points[0] + first_label_right_gap; if(rect.x > left_gap_point && !bWithoutLabels) { if(val_ax.labels)//скорректируем позицию подписей вертикальной оси, если они есть { val_ax.labels.x = rect.x + (val_ax.labels.x - left_gap_point)*checkFiniteNumber((rect.w/(rect.x + rect.w - left_gap_point))); } //скорректируем point_interval point_interval *= checkFiniteNumber((rect.w/(rect.x + rect.w - left_gap_point))); //скорректируем arr_cat_labels_points for(i = 0; i < arr_cat_labels_points.length; ++i) { arr_cat_labels_points[i] = rect.x + (arr_cat_labels_points[i] - left_gap_point)*checkFiniteNumber((rect.w/(rect.x + rect.w - left_gap_point))); } //скорректируем позицию вертикальной оси val_ax.posX = rect.x + (val_ax.posX - left_gap_point)*checkFiniteNumber((rect.w/(rect.x + rect.w - left_gap_point))); } if(right_gap_point > rect.x + rect.w && !bWithoutLabels) { if(val_ax.labels)//скорректируем позицию подписей вертикальной оси { val_ax.labels.x = rect.x + (val_ax.labels.x - rect.x)*checkFiniteNumber((rect.w/(right_gap_point - rect.x))); } //скорректируем point_interval point_interval *= checkFiniteNumber((rect.w/(right_gap_point - rect.x))); for(i = 0; i < arr_cat_labels_points.length; ++i) { arr_cat_labels_points[i] = rect.x + (arr_cat_labels_points[i] - rect.x)*checkFiniteNumber((rect.w/(right_gap_point - rect.x))); } //скорректируем позицию вертикальной оси val_ax.posX = rect.x + (val_ax.posX - rect.x)*checkFiniteNumber((rect.w/(right_gap_point - rect.x))); } } } } else { b_rotated = true; //пока сделаем без обрезки var arr_left_points = []; var arr_right_points = []; var max_rotated_height = 0; cat_ax.labels.bRotated = true; var nMaxCount = 1; var nLblCount = 0; var nCount = 0; var nSkip = 1; if(!bTickSkip && fMaxContentStringH > 0){ nMaxCount = diagram_width/fMaxContentStringH; nSkip = ((cat_ax.labels.aLabels.length/nMaxCount + 1) >> 0); } else{ bTickSkip = true; } //смотрим на сколько подписи горизонтальной оси выходят влево за пределы области построения for(i = 0; i < cat_ax.labels.aLabels.length; ++i) { if(cat_ax.labels.aLabels[i]) { if(i%nSkip !== 0){ cat_ax.labels.aLabels[i] = null; arr_left_points[i] = arr_cat_labels_points[i]; arr_right_points[i] = arr_cat_labels_points[i]; nCount++; continue; } //сначала расчитаем высоту и ширину подписи так чтобы она умещалась в одну строку var wh = cat_ax.labels.aLabels[i].tx.rich.getContentOneStringSizes(); arr_left_points[i] = arr_cat_labels_points[i] - (wh.w*Math.cos(Math.PI/4) + wh.h*Math.sin(Math.PI/4) - wh.h*Math.sin(Math.PI/4)/2);//вычитаем из точки привязки ширину получившейся подписи arr_right_points[i] = arr_cat_labels_points[i] + wh.h*Math.sin(Math.PI/4)/2; var h2 = wh.w*Math.sin(Math.PI/4) + wh.h*Math.cos(Math.PI/4); if(h2 > max_rotated_height) max_rotated_height = h2; nLblCount++; nCount++; cat_ax.labels.aLabels[i].widthForTransform = wh.w; } else {//подписи нет arr_left_points[i] = arr_cat_labels_points[i]; arr_right_points[i] = arr_cat_labels_points[i]; } } cat_ax.labels.extY = max_rotated_height + labels_offset; // left_gap_point = Math.max(0, Math.min.apply(Math, arr_left_points)); right_gap_point = Math.max(0, Math.max.apply(Math, arr_right_points)); if(!bWithoutLabels){ if(AscFormat.ORIENTATION_MIN_MAX === cat_ax_orientation) { if(rect.x > left_gap_point) { if(val_ax.labels)//скорректируем позицию подписей вертикальной оси, если они есть { val_ax.labels.x = rect.x + (val_ax.labels.x - left_gap_point)*checkFiniteNumber((rect.w/(rect.x + rect.w - left_gap_point))); } //скорректируем point_interval point_interval *= checkFiniteNumber(rect.w/(rect.x + rect.w - left_gap_point)); //скорректируем arr_cat_labels_points for(i = 0; i < arr_cat_labels_points.length; ++i) { arr_cat_labels_points[i] = rect.x + (arr_cat_labels_points[i] - left_gap_point)*checkFiniteNumber((rect.w/(rect.x + rect.w - left_gap_point))); } //скорректируем позицию вертикальной оси val_ax.posX = rect.x + (val_ax.posX - left_gap_point)*checkFiniteNumber((rect.w/(rect.x + rect.w - left_gap_point))); } //смотри выходит ли подпись последней категории за пределы области построения if(right_gap_point > rect.x + rect.w) { if(val_ax.labels)//скорректируем позицию подписей вертикальной оси { val_ax.labels.x = rect.x + (val_ax.labels.x - rect.x)*checkFiniteNumber((rect.w/(right_gap_point - rect.x))); } //скорректируем point_interval point_interval *= checkFiniteNumber((right_gap_point - rect.x)/(rect.x + rect.w - rect.x)); for(i = 0; i < arr_cat_labels_points.length; ++i) { arr_cat_labels_points[i] = rect.x + (arr_cat_labels_points[i] - rect.x)*checkFiniteNumber((rect.w/(right_gap_point - rect.x))); } //скорректируем позицию вертикальной оси val_ax.posX = rect.x + (val_ax.posX - rect.x)*checkFiniteNumber((rect.w/(right_gap_point - rect.x))); } } else { if(rect.x > left_gap_point) { if(val_ax.labels)//скорректируем позицию подписей вертикальной оси, если они есть { val_ax.labels.x = rect.x + (val_ax.labels.x - left_gap_point)*checkFiniteNumber((rect.w/(rect.x + rect.w - left_gap_point))); } //скорректируем point_interval point_interval *= (rect.w)/checkFiniteNumber((rect.x + rect.w - left_gap_point)); //скорректируем arr_cat_labels_points for(i = 0; i < arr_cat_labels_points.length; ++i) { arr_cat_labels_points[i] = rect.x + (arr_cat_labels_points[i] - left_gap_point)*checkFiniteNumber((rect.w/(rect.x + rect.w - left_gap_point))); } //скорректируем позицию вертикальной оси val_ax.posX = rect.x + (val_ax.posX - left_gap_point)*checkFiniteNumber((rect.w/(rect.x + rect.w - left_gap_point))); } if(right_gap_point > rect.x + rect.w) { if(val_ax.labels)//скорректируем позицию подписей вертикальной оси { val_ax.labels.x = rect.x + (val_ax.labels.x - rect.x)*checkFiniteNumber((rect.w/(right_gap_point - rect.x))); } //скорректируем point_interval point_interval *= checkFiniteNumber((right_gap_point - rect.x)/(rect.x + rect.w - rect.x)); for(i = 0; i < arr_cat_labels_points.length; ++i) { arr_cat_labels_points[i] = rect.x + (arr_cat_labels_points[i] - rect.x)*checkFiniteNumber((rect.w/(right_gap_point - rect.x))); } //скорректируем позицию вертикальной оси val_ax.posX = rect.x + (val_ax.posX - rect.x)*checkFiniteNumber((rect.w/(right_gap_point - rect.x))); } } } } } //series axis if(ser_ax){ if(c_oAscTickLabelsPos.TICK_LABEL_POSITION_NONE !== ser_ax.tickLblPos && !(ser_ax.bDelete === true)){ var arr_series_labels_str = []; var aSeries = chart_object.series; for(var i = 0; i < aSeries.length; ++i){ if(aSeries[i].getSeriesName){ arr_series_labels_str.push(aSeries[i].getSeriesName()); } else{ arr_series_labels_str.push('Series ' + (i+1)); } } ser_ax.labels = new AscFormat.CValAxisLabels(this, ser_ax); tick_lbl_skip = AscFormat.isRealNumber(ser_ax.tickLblSkip) ? ser_ax.tickLblSkip : 1; var lastStyleObject = null; max_val_labels_text_height = 0; max_width = 0; for(i = 0; i < arr_series_labels_str.length; ++i) { var dlbl = null; if(i%tick_lbl_skip === 0) { var dlbl = new AscFormat.CDLbl(); if(lastStyleObject) { dlbl.lastStyleObject = lastStyleObject; } dlbl.parent = val_ax; dlbl.chart = this; dlbl.spPr = val_ax.spPr; dlbl.txPr = val_ax.txPr; dlbl.tx = new AscFormat.CChartText(); dlbl.tx.rich = AscFormat.CreateTextBodyFromString(arr_series_labels_str[i], this.getDrawingDocument(), dlbl); var t = dlbl.tx.rich.recalculateByMaxWord(); if(!lastStyleObject) { lastStyleObject = dlbl.lastStyleObject; } var cur_width = t.w; if(cur_width > max_width) max_width = cur_width; if(t.h > max_val_labels_text_height) max_val_labels_text_height = t.h; ser_ax.labels.aLabels.push(dlbl); } } var ser_axis_labels_gap = ser_ax.labels.aLabels[0].tx.rich.content.Content[0].CompiledPr.Pr.TextPr.FontSize*25.4/72; ser_ax.labels.extX = max_width + ser_axis_labels_gap; ser_ax.labels.extY = max_val_labels_text_height; } else{ ser_ax.labels = null; } } //расчет позиции блока с подписями горизонтальной оси var cat_labels_align_bottom = true; /*-----------------------------------------------------------------------*/ var crosses_val_ax;//значение на ветикальной оси в котором её пересекает горизонтальная if(cat_ax.crosses === AscFormat.CROSSES_AUTO_ZERO) { if(arr_val[0] <=0 && arr_val[arr_val.length-1] >= 0) crosses_val_ax = 0; else if(arr_val[arr_val.length-1] < 0) crosses_val_ax = arr_val[arr_val.length-1]; else crosses_val_ax = arr_val[0]; } else if(cat_ax.crosses === AscFormat.CROSSES_MIN) { crosses_val_ax = arr_val[0]; } else if(cat_ax.crosses === AscFormat.CROSSES_MAX) { crosses_val_ax = arr_val[arr_val.length - 1]; } else if(AscFormat.isRealNumber(cat_ax.crossesAt) && cat_ax.crossesAt >= arr_val[0] && cat_ax.crossesAt <= arr_val[arr_val.length - 1]) { //сделаем провеку на попадание в интервал if(cat_ax.crossesAt >= arr_val[0] && cat_ax.crossesAt <= arr_val[arr_val.length - 1]) crosses_val_ax = cat_ax.crossesAt; } else { //ведем себя как в случае (cat_ax.crosses === AscFormat.CROSSES_AUTO_ZERO) if(arr_val[0] <=0 && arr_val[arr_val.length-1] >= 0) crosses_val_ax = 0; else if(arr_val[arr_val.length-1] < 0) crosses_val_ax = arr_val[arr_val.length-1]; else crosses_val_ax = arr_val[0]; } var val_ax_orientation = val_ax.scaling && AscFormat.isRealNumber(val_ax.scaling.orientation) ? val_ax.scaling.orientation : AscFormat.ORIENTATION_MIN_MAX; var hor_labels_pos = cat_ax.tickLblPos; var arr_val_labels_points = [];//массив середин подписей вертикальной оси; i-й элемент - y-координата центра подписи i-огто значения; var top_val_axis_gap, bottom_val_axis_gap; var first_val_axis_label_half_height = 0; //TODO (val_ax.bDelete || val_ax.tickLblPos ===c_oAscTickLabelsPos.TICK_LABEL_POSITION_NONE) ? 0 :val_ax.labels.aLabels[0].tx.rich.content.GetSummaryHeight()/2; var last_val_axis_label_half_height = 0; //TODO (val_ax.bDelete || val_ax.tickLblPos ===c_oAscTickLabelsPos.TICK_LABEL_POSITION_NONE) ? 0 : val_ax.labels.aLabels[val_ax.labels.aLabels.length-1].tx.rich.content.GetSummaryHeight()/2; var unit_height; if(!bWithoutLabels){ unit_height = checkFiniteNumber((rect.h - first_val_axis_label_half_height - last_val_axis_label_half_height)/(arr_val[arr_val.length - 1] - arr_val[0]));//высота единицы измерения на вертикальной оси } else{ unit_height = checkFiniteNumber(rect.h/(arr_val[arr_val.length - 1] - arr_val[0])); } var cat_ax_ext_y = cat_ax.labels ? cat_ax.labels.extY : 0; if(val_ax_orientation === AscFormat.ORIENTATION_MIN_MAX) { if(hor_labels_pos === c_oAscTickLabelsPos.TICK_LABEL_POSITION_NEXT_TO || !AscFormat.isRealNumber(hor_labels_pos)) { if(cat_ax.crosses === AscFormat.CROSSES_MAX) { cat_labels_align_bottom = false; top_val_axis_gap = Math.max(last_val_axis_label_half_height, cat_ax_ext_y); if(!bWithoutLabels){ unit_height = checkFiniteNumber((rect.h - top_val_axis_gap - first_val_axis_label_half_height)/(arr_val[arr_val.length - 1] - arr_val[0])); cat_labels_align_bottom = false;//в данном случае подписи будут выравниваться по верхнему краю блока с подписями cat_ax.posY = rect.y + rect.h - first_val_axis_label_half_height - (crosses_val_ax - arr_val[0])*unit_height; if(cat_ax.labels) cat_ax.labels.y = cat_ax.posY - cat_ax_ext_y; } else{ unit_height = checkFiniteNumber(rect.h/(arr_val[arr_val.length - 1] - arr_val[0])); cat_labels_align_bottom = false;//в данном случае подписи будут выравниваться по верхнему краю блока с подписями cat_ax.posY = rect.y + rect.h - (crosses_val_ax - arr_val[0])*unit_height; if(cat_ax.labels){ cat_ax.labels.y = cat_ax.posY - cat_ax_ext_y; if(true){ var bCorrectedCat = false; if(cat_ax.labels.y < 0){ rect.y -= cat_ax.labels.y; rect.h += cat_ax.labels.y; cat_ax.labels.y = 0; bCorrectedCat = true; } if(cat_ax.labels.y + cat_ax.labels.extY > this.extY){ rect.h -= (cat_ax.labels.y + cat_ax.labels.extY - this.extY); bCorrectedCat = true; } if(bCorrectedCat){ unit_height = checkFiniteNumber(rect.h/(arr_val[arr_val.length - 1] - arr_val[0])); cat_labels_align_bottom = false;//в данном случае подписи будут выравниваться по верхнему краю блока с подписями cat_ax.posY = rect.y + rect.h - (crosses_val_ax - arr_val[0])*unit_height; } } } } } else { if(!bWithoutLabels){ var bottom_points_height = first_val_axis_label_half_height + (crosses_val_ax - arr_val[0])*unit_height;//высота области под горизонтальной осью if(bottom_points_height < cat_ax_ext_y) { unit_height = checkFiniteNumber((rect.h - last_val_axis_label_half_height - cat_ax_ext_y)/(arr_val[arr_val.length-1] - crosses_val_ax)); } cat_ax.posY = rect.y + last_val_axis_label_half_height + (arr_val[arr_val.length-1] - crosses_val_ax)*unit_height; if(cat_ax.labels) cat_ax.labels.y = cat_ax.posY; } else{ cat_ax.posY = rect.y + (arr_val[arr_val.length-1] - crosses_val_ax)*unit_height; if(cat_ax.labels){ cat_ax.labels.y = cat_ax.posY; if(true){ var bCorrectedCat = false; if(cat_ax.labels.y < 0){ rect.y -= cat_ax.labels.y; rect.h += cat_ax.labels.y; cat_ax.labels.y = 0; bCorrectedCat = true; } if(cat_ax.labels.y + cat_ax.labels.extY > this.extY){ rect.h -= (cat_ax.labels.y + cat_ax.labels.extY - this.extY); bCorrectedCat = true; } if(bCorrectedCat){ unit_height = checkFiniteNumber(rect.h/(arr_val[arr_val.length - 1] - arr_val[0])); cat_ax.posY = rect.y + (arr_val[arr_val.length-1] - crosses_val_ax)*unit_height; cat_ax.labels.y = cat_ax.posY; } } } } } for(i = 0; i < arr_val.length; ++i) arr_val_labels_points[i] = cat_ax.posY - (arr_val[i] - crosses_val_ax)*unit_height; } else if(hor_labels_pos === c_oAscTickLabelsPos.TICK_LABEL_POSITION_LOW) { if(!bWithoutLabels){ bottom_val_axis_gap = Math.max(cat_ax_ext_y, first_val_axis_label_half_height); unit_height = checkFiniteNumber((rect.h - bottom_val_axis_gap - last_val_axis_label_half_height)/(arr_val[arr_val.length - 1] - arr_val[0])); cat_ax.posY = rect.y + last_val_axis_label_half_height + (arr_val[arr_val.length-1] - crosses_val_ax)*unit_height; if(cat_ax.labels) cat_ax.labels.y = rect.y + rect.h - bottom_val_axis_gap; for(i = 0; i < arr_val.length; ++i) arr_val_labels_points[i] = cat_ax.posY - (arr_val[i] - crosses_val_ax)*unit_height; } else{ unit_height = checkFiniteNumber(rect.h/(arr_val[arr_val.length - 1] - arr_val[0])); cat_ax.posY = rect.y + (arr_val[arr_val.length-1] - crosses_val_ax)*unit_height; if(cat_ax.labels){ cat_ax.labels.y = rect.y + rect.h; if(true){ var bCorrectedCat = false; if(cat_ax.labels.y < 0){ rect.y -= cat_ax.labels.y; rect.h += cat_ax.labels.y; cat_ax.labels.y = 0; bCorrectedCat = true; } if(cat_ax.labels.y + cat_ax.labels.extY > this.extY){ rect.h -= (cat_ax.labels.y + cat_ax.labels.extY - this.extY); bCorrectedCat = true; } if(bCorrectedCat){ unit_height = checkFiniteNumber(rect.h/(arr_val[arr_val.length - 1] - arr_val[0])); cat_ax.posY = rect.y + (arr_val[arr_val.length-1] - crosses_val_ax)*unit_height; cat_ax.labels.y = rect.y + rect.h; } } } for(i = 0; i < arr_val.length; ++i) arr_val_labels_points[i] = cat_ax.posY - (arr_val[i] - crosses_val_ax)*unit_height; } } else if(hor_labels_pos === c_oAscTickLabelsPos.TICK_LABEL_POSITION_HIGH) { if(!bWithoutLabels){ top_val_axis_gap = Math.max(last_val_axis_label_half_height, cat_ax_ext_y); unit_height = checkFiniteNumber((rect.h - top_val_axis_gap - first_val_axis_label_half_height)/(arr_val[arr_val.length - 1] - arr_val[0])); cat_labels_align_bottom = false;//в данном случае подписи будут выравниваться по верхнему краю блока с подписями cat_ax.posY = rect.y + rect.h - first_val_axis_label_half_height - (crosses_val_ax - arr_val[0])*unit_height; if(cat_ax.labels) cat_ax.labels.y = rect.y + top_val_axis_gap - cat_ax_ext_y; for(i = 0; i < arr_val.length; ++i) arr_val_labels_points[i] = cat_ax.posY - (arr_val[i] - crosses_val_ax)*unit_height; } else{ unit_height = checkFiniteNumber(rect.h/(arr_val[arr_val.length - 1] - arr_val[0])); cat_labels_align_bottom = false;//в данном случае подписи будут выравниваться по верхнему краю блока с подписями cat_ax.posY = rect.y + rect.h - (crosses_val_ax - arr_val[0])*unit_height; if(cat_ax.labels){ cat_ax.labels.y = rect.y - cat_ax_ext_y; if(true){ var bCorrectedCat = false; if(cat_ax.labels.y < 0){ rect.y -= cat_ax.labels.y; rect.h += cat_ax.labels.y; cat_ax.labels.y = 0; bCorrectedCat = true; } if(cat_ax.labels.y + cat_ax.labels.extY > this.extY){ rect.h -= (cat_ax.labels.y + cat_ax.labels.extY - this.extY); bCorrectedCat = true; } if(bCorrectedCat){ unit_height = checkFiniteNumber(rect.h/(arr_val[arr_val.length - 1] - arr_val[0])); cat_ax.posY = rect.y + rect.h - (crosses_val_ax - arr_val[0])*unit_height; cat_ax.labels.y = rect.y - cat_ax_ext_y; } } } for(i = 0; i < arr_val.length; ++i) arr_val_labels_points[i] = cat_ax.posY - (arr_val[i] - crosses_val_ax)*unit_height; } } else { //подписей осей нет cat_ax.labels = null; if(!bWithoutLabels){ for(i = 0; i < arr_val.length; ++i) arr_val_labels_points[i] = rect.y + rect.h - first_val_axis_label_half_height - (arr_val[i] - arr_val[0])*unit_height; cat_ax.posY = rect.y + rect.h - first_val_axis_label_half_height - (crosses_val_ax - arr_val[0])*unit_height; } else{ for(i = 0; i < arr_val.length; ++i) arr_val_labels_points[i] = rect.y + rect.h - (arr_val[i] - arr_val[0])*unit_height; cat_ax.posY = rect.y + rect.h - (crosses_val_ax - arr_val[0])*unit_height; } } } else {//зеркально отражаем if(hor_labels_pos === c_oAscTickLabelsPos.TICK_LABEL_POSITION_NEXT_TO || !AscFormat.isRealNumber(hor_labels_pos)) { if(cat_ax.crosses === AscFormat.CROSSES_MAX) { if(!bWithoutLabels){ bottom_val_axis_gap = Math.max(cat_ax_ext_y, last_val_axis_label_half_height); unit_height = checkFiniteNumber((rect.h - bottom_val_axis_gap - first_val_axis_label_half_height)/(arr_val[arr_val.length - 1] - arr_val[0])); cat_ax.posY = rect.y + first_val_axis_label_half_height + (crosses_val_ax - arr_val[0])*unit_height; if(cat_ax.labels) cat_ax.labels.y = rect.y + rect.h - bottom_val_axis_gap; } else{ unit_height = checkFiniteNumber(rect.h/(arr_val[arr_val.length - 1] - arr_val[0])); cat_ax.posY = rect.y + (crosses_val_ax - arr_val[0])*unit_height; if(cat_ax.labels){ cat_ax.labels.y = rect.y + rect.h; if(true){ var bCorrectedCat = false; if(cat_ax.labels.y < 0){ rect.y -= cat_ax.labels.y; rect.h += cat_ax.labels.y; cat_ax.labels.y = 0; bCorrectedCat = true; } if(cat_ax.labels.y + cat_ax.labels.extY > this.extY){ rect.h -= (cat_ax.labels.y + cat_ax.labels.extY - this.extY); bCorrectedCat = true; } if(bCorrectedCat){ unit_height = checkFiniteNumber(rect.h/(arr_val[arr_val.length - 1] - arr_val[0])); cat_ax.posY = rect.y + (crosses_val_ax - arr_val[0])*unit_height; cat_ax.labels.y = rect.y + rect.h; } } } } } else { cat_labels_align_bottom = false; if(!bWithoutLabels){ var top_points_height = first_val_axis_label_half_height + (crosses_val_ax - arr_val[0])*unit_height; if(top_points_height < cat_ax_ext_y) { unit_height = checkFiniteNumber((rect.h - cat_ax_ext_y - last_val_axis_label_half_height)/(arr_val[arr_val.length-1] - crosses_val_ax)); } cat_ax.posY = rect.y + rect.h - last_val_axis_label_half_height - (arr_val[arr_val.length-1] - crosses_val_ax)*unit_height; if(cat_ax.labels) cat_ax.labels.y = cat_ax.posY - cat_ax_ext_y; } else{ cat_ax.posY = rect.y + rect.h - (arr_val[arr_val.length-1] - crosses_val_ax)*unit_height; if(cat_ax.labels){ cat_ax.labels.y = cat_ax.posY - cat_ax_ext_y; if(true){ var bCorrectedCat = false; if(cat_ax.labels.y < 0){ rect.y -= cat_ax.labels.y; rect.h += cat_ax.labels.y; cat_ax.labels.y = 0; bCorrectedCat = true; } if(cat_ax.labels.y + cat_ax.labels.extY > this.extY){ rect.h -= (cat_ax.labels.y + cat_ax.labels.extY - this.extY); bCorrectedCat = true; } if(bCorrectedCat){ unit_height = checkFiniteNumber(rect.h/(arr_val[arr_val.length - 1] - arr_val[0])); cat_ax.posY = rect.y + rect.h - (arr_val[arr_val.length-1] - crosses_val_ax)*unit_height; cat_ax.labels.y = cat_ax.posY - cat_ax_ext_y; } } } } } for(i = 0; i < arr_val.length; ++i) arr_val_labels_points[i] = cat_ax.posY + (arr_val[i] - crosses_val_ax)*unit_height; } else if(hor_labels_pos === c_oAscTickLabelsPos.TICK_LABEL_POSITION_LOW) { cat_labels_align_bottom = false; if(!bWithoutLabels){ top_val_axis_gap = Math.max(first_val_axis_label_half_height, cat_ax_ext_y); unit_height = checkFiniteNumber((rect.h - top_val_axis_gap - last_val_axis_label_half_height)/(arr_val[arr_val.length-1] - arr_val[0])); cat_ax.posY = rect.y + rect.h - last_val_axis_label_half_height - (arr_val[arr_val.length-1] - crosses_val_ax)*unit_height; for(i = 0; i < arr_val.length; ++i) arr_val_labels_points[i] = cat_ax.posY + (arr_val[i] - crosses_val_ax)*unit_height; if(cat_ax.labels) cat_ax.labels.y = cat_ax.posY + (arr_val[0] - crosses_val_ax)*unit_height - cat_ax_ext_y; } else{ unit_height = checkFiniteNumber(rect.h/(arr_val[arr_val.length-1] - arr_val[0])); cat_ax.posY = rect.y + rect.h - (arr_val[arr_val.length-1] - crosses_val_ax)*unit_height; for(i = 0; i < arr_val.length; ++i) arr_val_labels_points[i] = cat_ax.posY + (arr_val[i] - crosses_val_ax)*unit_height; if(cat_ax.labels) { cat_ax.labels.y = cat_ax.posY + (arr_val[0] - crosses_val_ax)*unit_height - cat_ax_ext_y; if(true){ var bCorrectedCat = false; if(cat_ax.labels.y < 0){ rect.y -= cat_ax.labels.y; rect.h += cat_ax.labels.y; cat_ax.labels.y = 0; bCorrectedCat = true; } if(cat_ax.labels.y + cat_ax.labels.extY > this.extY){ rect.h -= (cat_ax.labels.y + cat_ax.labels.extY - this.extY); bCorrectedCat = true; } if(bCorrectedCat){ unit_height = checkFiniteNumber(rect.h/(arr_val[arr_val.length-1] - arr_val[0])); cat_ax.posY = rect.y + rect.h - (arr_val[arr_val.length-1] - crosses_val_ax)*unit_height; for(i = 0; i < arr_val.length; ++i) arr_val_labels_points[i] = cat_ax.posY + (arr_val[i] - crosses_val_ax)*unit_height; cat_ax.labels.y = cat_ax.posY + (arr_val[0] - crosses_val_ax)*unit_height - cat_ax_ext_y; } } } } } else if(hor_labels_pos === c_oAscTickLabelsPos.TICK_LABEL_POSITION_HIGH) { if(!bWithoutLabels){ bottom_val_axis_gap = Math.max(cat_ax_ext_y, last_val_axis_label_half_height); unit_height = checkFiniteNumber((rect.h - bottom_val_axis_gap - first_val_axis_label_half_height)/(arr_val[arr_val.length-1] - arr_val[0])); cat_ax.posY = rect.y + first_val_axis_label_half_height + (crosses_val_ax - arr_val[0])*unit_height; for(i = 0; i < arr_val.length; ++i) arr_val_labels_points[i] = cat_ax.posY + (arr_val[i] - crosses_val_ax)*unit_height; if(cat_ax.labels) cat_ax.labels.y = rect.y + rect.h - bottom_val_axis_gap; } else{ unit_height = checkFiniteNumber(rect.h/(arr_val[arr_val.length-1] - arr_val[0])); cat_ax.posY = rect.y + (crosses_val_ax - arr_val[0])*unit_height; for(i = 0; i < arr_val.length; ++i) arr_val_labels_points[i] = cat_ax.posY + (arr_val[i] - crosses_val_ax)*unit_height; if(cat_ax.labels){ cat_ax.labels.y = rect.y + rect.h; if(true){ var bCorrectedCat = false; if(cat_ax.labels.y < 0){ rect.y -= cat_ax.labels.y; rect.h += cat_ax.labels.y; cat_ax.labels.y = 0; bCorrectedCat = true; } if(cat_ax.labels.y + cat_ax.labels.extY > this.extY){ rect.h -= (cat_ax.labels.y + cat_ax.labels.extY - this.extY); bCorrectedCat = true; } if(bCorrectedCat){ unit_height = checkFiniteNumber(rect.h/(arr_val[arr_val.length-1] - arr_val[0])); cat_ax.posY = rect.y + (crosses_val_ax - arr_val[0])*unit_height; for(i = 0; i < arr_val.length; ++i) arr_val_labels_points[i] = cat_ax.posY + (arr_val[i] - crosses_val_ax)*unit_height; cat_ax.labels.y = rect.y + rect.h; } } } } } else {//подписей осей нет cat_ax.labels = null; if(!bWithoutLabels){ unit_height = checkFiniteNumber((rect.h - last_val_axis_label_half_height - first_val_axis_label_half_height)/(arr_val[arr_val.length-1] - arr_val[0])); for(i = 0; i < arr_val.length; ++i) arr_val_labels_points[i] = rect.y + first_val_axis_label_half_height + (arr_val[i] - arr_val[0])*unit_height; } else{ unit_height = checkFiniteNumber(rect.h/(arr_val[arr_val.length-1] - arr_val[0])); for(i = 0; i < arr_val.length; ++i) arr_val_labels_points[i] = rect.y + (arr_val[i] - arr_val[0])*unit_height; } } } cat_ax.interval = unit_height; //запишем в оси необходимую информацию для отрисовщика plotArea и выставим окончательные позиции для подписей var arr_labels, transform_text, local_text_transform; if(val_ax.labels) { if(bNeedReflect) { if(left_val_ax_labels_align) { left_val_ax_labels_align = false; val_ax.labels.x += val_ax.labels.extX; } else { left_val_ax_labels_align = true; val_ax.labels.x -= val_ax.labels.extX; } } val_ax.labels.align = left_val_ax_labels_align; val_ax.labels.y = Math.min.apply(Math, arr_val_labels_points) - max_val_labels_text_height/2; val_ax.labels.extY = Math.max.apply(Math, arr_val_labels_points) - Math.min.apply(Math, arr_val_labels_points) + max_val_labels_text_height; arr_labels = val_ax.labels.aLabels; if(left_val_ax_labels_align) { for(i = 0; i < arr_labels.length; ++i) { arr_labels[i].txBody = arr_labels[i].tx.rich; transform_text = arr_labels[i].transformText; transform_text.Reset(); global_MatrixTransformer.TranslateAppend(transform_text, val_ax.labels.x + val_ax.labels.extX - val_axis_labels_gap - arr_labels[i].tx.rich.content.XLimit, arr_val_labels_points[i] - val_ax.labels.aLabels[i].tx.rich.content.GetSummaryHeight()/2); // global_MatrixTransformer.MultiplyAppend(transform_text, this.getTransformMatrix()); local_text_transform = arr_labels[i].localTransformText; local_text_transform.Reset(); global_MatrixTransformer.TranslateAppend(local_text_transform, val_ax.labels.x + val_ax.labels.extX - val_axis_labels_gap - arr_labels[i].tx.rich.content.XLimit, arr_val_labels_points[i] - val_ax.labels.aLabels[i].tx.rich.content.GetSummaryHeight()/2); } } else { var left_line = val_ax.labels.x + val_axis_labels_gap; for(i = 0; i < arr_labels.length; ++i) { arr_labels[i].txBody = arr_labels[i].tx.rich; transform_text = arr_labels[i].transformText; transform_text.Reset(); global_MatrixTransformer.TranslateAppend(transform_text, left_line, arr_val_labels_points[i] - val_ax.labels.aLabels[i].tx.rich.content.GetSummaryHeight()/2); // global_MatrixTransformer.MultiplyAppend(transform_text, this.getTransformMatrix()); local_text_transform = arr_labels[i].localTransformText; local_text_transform.Reset(); global_MatrixTransformer.TranslateAppend(local_text_transform, left_line, arr_val_labels_points[i] - val_ax.labels.aLabels[i].tx.rich.content.GetSummaryHeight()/2); } } } val_ax.yPoints = []; for(i = 0; i < arr_val_labels_points.length; ++i) { val_ax.yPoints[i] = {val:arr_val[i], pos: arr_val_labels_points[i]}; } cat_ax.xPoints = []; for(i = 0; i <arr_cat_labels_points.length; ++i) { cat_ax.xPoints[i] = {val: i, pos: arr_cat_labels_points[i]}; } if(cat_ax.labels) { cat_ax.labels.align = cat_labels_align_bottom; if(!b_rotated)//подписи не повернутые { if(cat_ax_orientation === AscFormat.ORIENTATION_MIN_MAX) { cat_ax.labels.x = arr_cat_labels_points[0] - max_cat_label_width/2; } else { cat_ax.labels.x = arr_cat_labels_points[arr_cat_labels_points.length-1] - max_cat_label_width/2; } cat_ax.labels.extX = arr_cat_labels_points[arr_cat_labels_points.length-1] + max_cat_label_width/2 - cat_ax.labels.x; if(cat_labels_align_bottom) { for(i = 0; i < cat_ax.labels.aLabels.length; ++i) { if(cat_ax.labels.aLabels[i]) { var label_text_transform = cat_ax.labels.aLabels[i].transformText; label_text_transform.Reset(); global_MatrixTransformer.TranslateAppend(label_text_transform, arr_cat_labels_points[i] - max_cat_label_width/2, cat_ax.labels.y + labels_offset); // global_MatrixTransformer.MultiplyAppend(label_text_transform, this.getTransformMatrix()); local_text_transform = cat_ax.labels.aLabels[i].localTransformText; local_text_transform.Reset(); global_MatrixTransformer.TranslateAppend(local_text_transform, arr_cat_labels_points[i] - max_cat_label_width/2, cat_ax.labels.y + labels_offset); } } } else { for(i = 0; i < cat_ax.labels.aLabels.length; ++i) { if(cat_ax.labels.aLabels[i]) { var label_text_transform = cat_ax.labels.aLabels[i].transformText; label_text_transform.Reset(); global_MatrixTransformer.TranslateAppend(label_text_transform, arr_cat_labels_points[i] - max_cat_label_width/2, cat_ax.labels.y + cat_ax.labels.extY - labels_offset - cat_ax.labels.aLabels[i].tx.rich.content.GetSummaryHeight()); // global_MatrixTransformer.MultiplyAppend(label_text_transform, this.getTransformMatrix()); local_text_transform = cat_ax.labels.aLabels[i].localTransformText; local_text_transform.Reset(); global_MatrixTransformer.TranslateAppend(local_text_transform, arr_cat_labels_points[i] - max_cat_label_width/2, cat_ax.labels.y + cat_ax.labels.extY - labels_offset - cat_ax.labels.aLabels[i].tx.rich.content.GetSummaryHeight()); } } } } else { var left_x, right_x; var w2, h2, x1, xc, yc, y0; if(cat_labels_align_bottom) { for(i = 0; i < cat_ax.labels.aLabels.length; ++i) { if(cat_ax.labels.aLabels[i]) { var label_text_transform = cat_ax.labels.aLabels[i].transformText; cat_ax.labels.aLabels[i].tx.rich.content.Set_ApplyToAll(true); cat_ax.labels.aLabels[i].tx.rich.content.SetParagraphAlign(AscCommon.align_Left); cat_ax.labels.aLabels[i].tx.rich.content.Set_ApplyToAll(false); var wh = cat_ax.labels.aLabels[i].tx.rich.getContentOneStringSizes();//Todo: не расчитывать больше контент w2 = wh.w*Math.cos(Math.PI/4) + wh.h*Math.sin(Math.PI/4); h2 = wh.w*Math.sin(Math.PI/4) + wh.h*Math.cos(Math.PI/4); x1 = arr_cat_labels_points[i] + wh.h*Math.sin(Math.PI/4); y0 = cat_ax.labels.y + labels_offset; xc = x1 - w2/2; yc = y0 + h2/2; label_text_transform.Reset(); global_MatrixTransformer.TranslateAppend(label_text_transform, -wh.w/2, -wh.h/2); global_MatrixTransformer.RotateRadAppend(label_text_transform, Math.PI/4);//TODO global_MatrixTransformer.TranslateAppend(label_text_transform, xc, yc); global_MatrixTransformer.MultiplyAppend(label_text_transform,this.transform); if(!AscFormat.isRealNumber(left_x)) { left_x = xc - w2/2; right_x = xc + w2/2; } else { if(xc - w2/2 < left_x) left_x = xc - w2/2; if(xc + w2/2 > right_x) right_x = xc + w2/2; } local_text_transform = cat_ax.labels.aLabels[i].localTransformText; local_text_transform.Reset(); global_MatrixTransformer.TranslateAppend(local_text_transform, -wh.w/2, -wh.h/2); global_MatrixTransformer.RotateRadAppend(local_text_transform, Math.PI/4);//TODO global_MatrixTransformer.TranslateAppend(local_text_transform, xc, yc); } } } else { for(i = 0; i < cat_ax.labels.aLabels.length; ++i) { if(cat_ax.labels.aLabels[i]) { var label_text_transform = cat_ax.labels.aLabels[i].transformText; cat_ax.labels.aLabels[i].tx.rich.content.Set_ApplyToAll(true); cat_ax.labels.aLabels[i].tx.rich.content.SetParagraphAlign(AscCommon.align_Left); cat_ax.labels.aLabels[i].tx.rich.content.Set_ApplyToAll(false); var wh = cat_ax.labels.aLabels[i].tx.rich.getContentOneStringSizes();//Todo: не расчитывать больше контент w2 = wh.w*Math.cos(Math.PI/4) + wh.h*Math.sin(Math.PI/4); h2 = wh.w*Math.sin(Math.PI/4) + wh.h*Math.cos(Math.PI/4); x1 = arr_cat_labels_points[i] - wh.h*Math.sin(Math.PI/4); y0 = cat_ax.labels.y + cat_ax.labels.extY - labels_offset; xc = x1 + w2/2; yc = y0 - h2/2; label_text_transform.Reset(); global_MatrixTransformer.TranslateAppend(label_text_transform, -wh.w/2, -wh.h/2); global_MatrixTransformer.RotateRadAppend(label_text_transform, Math.PI/4);//TODO global_MatrixTransformer.TranslateAppend(label_text_transform, xc, yc); global_MatrixTransformer.MultiplyAppend(label_text_transform,this.transform); if(!AscFormat.isRealNumber(left_x)) { left_x = xc - w2/2; right_x = xc + w2/2; } else { if(xc - w2/2 < left_x) left_x = xc - w2/2; if(xc + w2/2 > right_x) right_x = xc + w2/2; } local_text_transform = cat_ax.labels.aLabels[i].localTransformText; local_text_transform.Reset(); global_MatrixTransformer.TranslateAppend(local_text_transform, -wh.w/2, -wh.h/2); global_MatrixTransformer.RotateRadAppend(local_text_transform, Math.PI/4);//TODO global_MatrixTransformer.TranslateAppend(local_text_transform, xc, yc); } } } cat_ax.labels.x = left_x; cat_ax.labels.extX = right_x - left_x; } } cat_ax.xPoints.sort(function(a, b){return a.val - b.val}); val_ax.yPoints.sort(function(a, b){return a.val - b.val}); } else{ this.bEmptySeries = true; } } else if(chart_type === AscDFH.historyitem_type_BarChart && chart_object.barDir === AscFormat.BAR_DIR_BAR) { var cat_ax, val_ax; var axis_by_types = chart_object.getAxisByTypes(); cat_ax = axis_by_types.catAx[0]; val_ax = axis_by_types.valAx[0]; if(cat_ax && val_ax) { /*---------------------new version---------------------------------------*/ val_ax.labels = null; cat_ax.labels = null; val_ax.posX = null; cat_ax.posY = null; val_ax.posY = null; cat_ax.posX = null; val_ax.xPoints = null; cat_ax.yPoints = null; val_ax.yPoints = null; cat_ax.xPoints = null; val_ax.transformYPoints = null; cat_ax.transformXPoints = null; val_ax.transformXPoints = null; cat_ax.transformYPoints = null; var sizes = this.getChartSizes(); rect = {x: sizes.startX, y:sizes.startY, w:sizes.w, h: sizes.h}; var arr_val = this.getValAxisValues(); //Получим строки для оси значений с учетом формата и единиц var arr_strings = []; var multiplier; if(val_ax.dispUnits) multiplier = val_ax.dispUnits.getMultiplier(); else multiplier = 1; var num_fmt = val_ax.numFmt; if(num_fmt && typeof num_fmt.formatCode === "string" /*&& !(num_fmt.formatCode === "General")*/) { var num_format = oNumFormatCache.get(num_fmt.formatCode); for(i = 0; i < arr_val.length; ++i) { var calc_value = arr_val[i]*multiplier; var rich_value = num_format.formatToChart(calc_value); arr_strings.push(rich_value); } } else { for(i = 0; i < arr_val.length; ++i) { var calc_value = arr_val[i]*multiplier; arr_strings.push(calc_value + ""); } } //расчитаем подписи горизонтальной оси значений val_ax.labels = new AscFormat.CValAxisLabels(this, val_ax); var max_height = 0; val_ax.xPoints = []; var max_val_ax_label_width = 0; for(i = 0; i < arr_strings.length; ++i) { var dlbl = new AscFormat.CDLbl(); dlbl.parent = val_ax; dlbl.chart = this; dlbl.spPr = val_ax.spPr; dlbl.txPr = val_ax.txPr; dlbl.tx = new AscFormat.CChartText(); dlbl.tx.rich = AscFormat.CreateTextBodyFromString(arr_strings[i], this.getDrawingDocument(), dlbl); dlbl.txBody = dlbl.tx.rich; if(val_ax.labels.aLabels[0]) { dlbl.lastStyleObject = val_ax.labels.aLabels[0].lastStyleObject; } var t = dlbl.tx.rich.recalculateByMaxWord(); var h = t.h; if(t.w > max_val_ax_label_width) max_val_ax_label_width = t.w; if(h > max_height) max_height = h; val_ax.labels.aLabels.push(dlbl); val_ax.xPoints.push({val: arr_val[i], pos: null}); } var val_axis_labels_gap = val_ax.labels.aLabels[0].tx.rich.content.Content[0].CompiledPr.Pr.TextPr.FontSize*25.4/72; val_ax.labels.extY = max_height + val_axis_labels_gap; //расчитаем подписи для горизонтальной оси var ser = chart_object.series[0]; var string_pts = [], pts_len = 0; /*string_pts pts_len*/ if(ser && ser.cat) { var lit, b_num_lit = true; if(ser.cat.strRef && ser.cat.strRef.strCache) { lit = ser.cat.strRef.strCache; } else if(ser.cat.strLit) { lit = ser.cat.strLit; } else if(ser.cat.numRef && ser.cat.numRef.numCache) { lit = ser.cat.numRef.numCache; b_num_lit = true; } else if(ser.cat.numLit) { lit = ser.cat.numLit; b_num_lit = true; } if(lit) { var lit_format = null, pt_format = null; if(b_num_lit && typeof lit.formatCode === "string" && lit.formatCode.length > 0) { lit_format = oNumFormatCache.get(lit.formatCode); } pts_len = lit.ptCount; for(i = 0; i < pts_len; ++i) { var pt = lit.getPtByIndex(i); if(pt) { var str_pt; if(b_num_lit) { if(typeof pt.formatCode === "string" && pt.formatCode.length > 0) { pt_format = oNumFormatCache.get(pt.formatCode); if(pt_format) { str_pt = pt_format.formatToChart(pt.val); } else { str_pt = pt.val; } } else if(lit_format) { str_pt = lit_format.formatToChart(pt.val); } else { str_pt = pt.val; } } else { str_pt = pt.val; } string_pts.push({val: str_pt + ""}); } else { string_pts.push({val: i + ""}); } } } } //if(string_pts.length === 0) { pts_len = 0; for(i = 0; i < chart_object.series.length; ++i) { var cur_pts= null; ser = chart_object.series[i]; if(ser.val) { if(ser.val.numRef && ser.val.numRef.numCache) cur_pts = ser.val.numRef.numCache; else if(ser.val.numLit) cur_pts = ser.val.numLit; if(cur_pts) { pts_len = Math.max(pts_len, cur_pts.ptCount); } } } if(pts_len > string_pts.length) { for(i = string_pts.length; i < pts_len; ++i) { string_pts.push({val:i+1 + ""}); } } else { string_pts.splice(pts_len, string_pts.length - pts_len); } } /*---------------------расчет позиции блока с подписями вертикальной оси-----------------------------------------------------------------------------*/ //расчитаем ширину интервала без учета горизонтальной оси; var crosses;//номер категории в которой вертикалная ось пересекает горизонтальную; if(val_ax.crosses === AscFormat.CROSSES_AUTO_ZERO || val_ax.crosses === AscFormat.CROSSES_MIN) crosses = 1; else if(val_ax.crosses === AscFormat.CROSSES_MAX) crosses = string_pts.length; else if(AscFormat.isRealNumber(val_ax.crossesAt)) { if(val_ax.crossesAt <= string_pts.length + 1 && val_ax.crossesAt > 0) crosses = val_ax.crossesAt; else if(val_ax.crossesAt <= 0) crosses = 1; else crosses = string_pts.length; } else crosses = 1; cat_ax.maxCatVal = string_pts.length; var cat_ax_orientation = cat_ax.scaling && AscFormat.isRealNumber(cat_ax.scaling.orientation) ? cat_ax.scaling.orientation : AscFormat.ORIENTATION_MIN_MAX; var labels_pos = val_ax.tickLblPos; var cross_between = this.getValAxisCrossType(); if(cross_between === null){ cross_between = AscFormat.CROSS_BETWEEN_BETWEEN; } var bottom_val_ax_labels_align = true;//приленгание подписей оси значений к левому краю. var intervals_count = cross_between === AscFormat.CROSS_BETWEEN_MID_CAT ? string_pts.length - 1 : string_pts.length; var point_interval = rect.h/intervals_count;//интервал между точками. Зависит от crossBetween, а также будет потом корректироваться в зависимости от подписей вертикальной и горизонтальной оси. var bottom_points_height, top_point_height; var arr_cat_labels_points = [];//массив середин подписей горизонтальной оси; i-й элемент - x-координата центра подписи категории с номером i; if(cat_ax_orientation === AscFormat.ORIENTATION_MIN_MAX) { if(labels_pos === c_oAscTickLabelsPos.TICK_LABEL_POSITION_NONE || val_ax.bDelete === true) { val_ax.labels = null; if(cross_between === AscFormat.CROSS_BETWEEN_MID_CAT) { for(i = 0; i < string_pts.length; ++i) arr_cat_labels_points[i] = rect.y + rect.h - point_interval*i; } else { for(i = 0; i < string_pts.length; ++i) arr_cat_labels_points[i] = rect.y + rect.h - (point_interval/2 + point_interval*i); } val_ax.posY = rect.y + rect.h - point_interval*(crosses-1); } else if(labels_pos === c_oAscTickLabelsPos.TICK_LABEL_POSITION_NEXT_TO || !AscFormat.isRealNumber(labels_pos)) //подписи рядом с осью { if(val_ax.crosses === AscFormat.CROSSES_MAX) { if(!bWithoutLabels){ val_ax.labels.y = rect.y; point_interval = checkFiniteNumber((rect.h - val_ax.labels.extY)/intervals_count); } else{ val_ax.labels.y = rect.y - val_ax.labels.extY; } bottom_val_ax_labels_align = false; val_ax.posY = val_ax.labels.y + val_ax.labels.extY; if(cross_between === AscFormat.CROSS_BETWEEN_MID_CAT) { for(i = 0; i < string_pts.length; ++i) arr_cat_labels_points[i] = rect.y + rect.h - point_interval*i; } else { for(i = 0; i < string_pts.length; ++i) arr_cat_labels_points[i] = point_interval/2 + rect.y + rect.h - point_interval*i; } } else { bottom_points_height = point_interval*(crosses-1);//общая ширина левых точек если считать что точки занимают все пространство if(bottom_points_height < val_ax.labels.extY && !bWithoutLabels)//подписи верт. оси выходят за пределы области построения { var top_intervals_count = intervals_count - (crosses - 1);//количесво интервалов выше горизонтальной оси //скорректируем point_interval, поделив расстояние, которое осталось справа от подписей осей на количество интервалов справа point_interval = checkFiniteNumber((rect.h - val_ax.labels.extY)/top_intervals_count); val_ax.labels.y = rect.y + rect.h - val_ax.labels.extY; var start_point = val_ax.labels.y + (crosses-1)*point_interval;//y-координата точки низа области постоения if(cross_between === AscFormat.CROSS_BETWEEN_MID_CAT) { for(i = 0; i < string_pts.length; ++i) arr_cat_labels_points[i] = start_point - point_interval*i; } else { for(i = 0; i < string_pts.length; ++i) arr_cat_labels_points[i] = start_point - point_interval/2 - point_interval*i; } } else { val_ax.labels.y = rect.y + rect.h - bottom_points_height; if(cross_between === AscFormat.CROSS_BETWEEN_MID_CAT) { for(i = 0; i < string_pts.length; ++i) arr_cat_labels_points[i] = rect.y + rect.h - point_interval*i; } else { for(i = 0; i < string_pts.length; ++i) arr_cat_labels_points[i] = rect.y + rect.h - (point_interval/2 + point_interval*i); } } val_ax.posY = val_ax.labels.y; } } else if(labels_pos === c_oAscTickLabelsPos.TICK_LABEL_POSITION_LOW)//подписи снизу от области построения { if(!bWithoutLabels){ point_interval = checkFiniteNumber((rect.h - val_ax.labels.extY)/intervals_count); val_ax.labels.y = rect.y + rect.h - val_ax.labels.extY; } else{ val_ax.labels.y = rect.y + rect.h; } if(cross_between === AscFormat.CROSS_BETWEEN_MID_CAT) { for(i = 0; i < string_pts.length; ++i) arr_cat_labels_points[i] = val_ax.labels.y - point_interval*i; } else { for(i = 0; i < string_pts.length; ++i) arr_cat_labels_points[i] = rect.y + rect.h - val_ax.labels.extY - point_interval/2 - point_interval*i; } val_ax.posY = val_ax.labels.y - point_interval*(crosses-1); } else if(labels_pos === c_oAscTickLabelsPos.TICK_LABEL_POSITION_HIGH)//подписи сверху от области построения { if(!bWithoutLabels){ point_interval = checkFiniteNumber((rect.h - val_ax.labels.extY)/intervals_count); val_ax.labels.y = rect.y; } else{ val_ax.labels.y = rect.y - val_ax.labels.extY; } point_interval = checkFiniteNumber((rect.h - val_ax.labels.extY)/intervals_count); val_ax.labels.y = rect.y; bottom_val_ax_labels_align = false; if(cross_between === AscFormat.CROSS_BETWEEN_MID_CAT) { for(i = 0; i < string_pts.length; ++i) arr_cat_labels_points[i] = rect.y + rect.h - point_interval*i; } else { for(i = 0; i < string_pts.length; ++i) arr_cat_labels_points[i] =rect.y + rect.h - (point_interval/2 + point_interval*i); } val_ax.posY = rect.y + rect.h - point_interval*(crosses-1); } else { val_ax.labels = null; if(cross_between === AscFormat.CROSS_BETWEEN_MID_CAT) { for(i = 0; i < string_pts.length; ++i) arr_cat_labels_points[i] = rect.y + rect.h - point_interval*i; } else { for(i = 0; i < string_pts.length; ++i) arr_cat_labels_points[i] = rect.y + rect.h - (point_interval/2 + point_interval*i); } val_ax.posY = rect.y + rect.h - point_interval*(crosses-1); } } else {//то же самое, только зеркально отраженное if(labels_pos === c_oAscTickLabelsPos.TICK_LABEL_POSITION_NONE || val_ax.bDelete === true) { val_ax.labels = null; if(cross_between === AscFormat.CROSS_BETWEEN_MID_CAT) { for(i = 0; i < string_pts.length; ++i) arr_cat_labels_points[i] = rect.y + point_interval*i; } else { for(i = 0; i < string_pts.length; ++i) arr_cat_labels_points[i] = rect.y + point_interval/2 + point_interval*i; } val_ax.posY = rect.y + point_interval*(crosses-1); } else if(labels_pos === c_oAscTickLabelsPos.TICK_LABEL_POSITION_NEXT_TO || !AscFormat.isRealNumber(labels_pos)) //подписи рядом с осью { if(val_ax.crosses === AscFormat.CROSSES_MAX) { if(!bWithoutLabels){ val_ax.labels.y = rect.y + rect.h - val_ax.labels.extY; point_interval = checkFiniteNumber((rect.h - val_ax.labels.extY)/intervals_count); } else{ val_ax.labels.y = rect.y + rect.h; } if(cross_between === AscFormat.CROSS_BETWEEN_MID_CAT) { for(i = 0; i < string_pts.length; ++i) arr_cat_labels_points[i] = rect.y + point_interval*i; } else { for(i = 0; i < string_pts.length; ++i) arr_cat_labels_points[i] = rect.y + point_interval/2 + point_interval*i; } val_ax.posY = val_ax.labels.y; } else { bottom_val_ax_labels_align = false; top_point_height = point_interval*(crosses-1); if(top_point_height < val_ax.labels.extY && !bWithoutLabels) { val_ax.labels.y = rect.y; var bottom_points_interval_count = intervals_count - (crosses - 1); point_interval = checkFiniteNumber((rect.h - val_ax.labels.extY)/bottom_points_interval_count); var start_point_bottom = rect.y + rect.h - point_interval*intervals_count; if(cross_between === AscFormat.CROSS_BETWEEN_MID_CAT) { for(i = 0; i < string_pts.length; ++i) arr_cat_labels_points[i] = start_point_bottom + point_interval*i; } else { for(i = 0; i < string_pts.length; ++i) arr_cat_labels_points[i] = start_point_bottom + point_interval/2 + point_interval*i; } } else { val_ax.labels.y = rect.y + point_interval*(crosses-1) - val_ax.labels.extY; if(cross_between === AscFormat.CROSS_BETWEEN_MID_CAT) { for(i = 0; i < string_pts.length; ++i) arr_cat_labels_points[i] = rect.y + point_interval*i; } else { for(i = 0; i < string_pts.length; ++i) arr_cat_labels_points[i] = rect.y + point_interval/2 + point_interval*i; } } val_ax.posY = val_ax.labels.y + val_ax.labels.extY; } } else if(labels_pos === c_oAscTickLabelsPos.TICK_LABEL_POSITION_LOW)//подписи сверху от области построения { bottom_val_ax_labels_align = false; if(!bWithoutLabels){ point_interval = checkFiniteNumber((rect.h - val_ax.labels.extY)/intervals_count); val_ax.labels.y = rect.y; } else{ val_ax.labels.y = rect.y - val_ax.labels.extY; } if(cross_between === AscFormat.CROSS_BETWEEN_MID_CAT) { for(i = 0; i < string_pts.length; ++i) arr_cat_labels_points[i] = val_ax.labels.y + val_ax.labels.extY + point_interval*i; } else { for(i = 0; i < string_pts.length; ++i) arr_cat_labels_points[i] = val_ax.labels.y + val_ax.labels.extY + point_interval/2 + point_interval*i; } val_ax.posY = rect.y + val_ax.labels.extY + point_interval*(crosses-1); } else if(labels_pos === c_oAscTickLabelsPos.TICK_LABEL_POSITION_HIGH)//подписи снизу от области построения { if(!bWithoutLabels){ point_interval = checkFiniteNumber((rect.h - val_ax.labels.extY)/intervals_count); val_ax.labels.y = rect.y + rect.h - val_ax.labels.extY; } else{ val_ax.labels.y = rect.y + rect.h; } if(cross_between === AscFormat.CROSS_BETWEEN_MID_CAT) { for(i = 0; i < string_pts.length; ++i) arr_cat_labels_points[i] = rect.y + point_interval*i; } else { for(i = 0; i < string_pts.length; ++i) arr_cat_labels_points[i] = rect.y + point_interval/2 + point_interval*i; } val_ax.posY = rect.y + point_interval*(crosses-1); } else { val_ax.labels = null; if(cross_between === AscFormat.CROSS_BETWEEN_MID_CAT) { for(i = 0; i < string_pts.length; ++i) arr_cat_labels_points[i] = rect.y + point_interval*i; } else { for(i = 0; i < string_pts.length; ++i) arr_cat_labels_points[i] = rect.y + point_interval/2 + point_interval*i; } val_ax.posY = rect.y + point_interval*(crosses-1); } } cat_ax.interval = point_interval; var diagram_height = point_interval*intervals_count;//размер области с самой диаграммой позже будет корректироватся; var max_cat_label_height = diagram_height / string_pts.length; // максимальная высота подписи горизонтальной оси; cat_ax.labels = null; var max_cat_labels_block_width = rect.w/2; if(c_oAscTickLabelsPos.TICK_LABEL_POSITION_NONE !== cat_ax.tickLblPos && !(cat_ax.bDelete === true)) //будем корректировать вертикальные подписи только если есть горизонтальные { cat_ax.labels = new AscFormat.CValAxisLabels(this, cat_ax); var tick_lbl_skip = AscFormat.isRealNumber(cat_ax.tickLblSkip) ? cat_ax.tickLblSkip : (string_pts.length < SKIP_LBL_LIMIT ? 1 : Math.floor(string_pts.length/SKIP_LBL_LIMIT)); var max_min_width = 0; var max_max_width = 0; var max_content_width = 0; var arr_min_max_min = []; for(i = 0; i < string_pts.length; ++i) { var dlbl = null; if(i%tick_lbl_skip === 0) { dlbl = new AscFormat.CDLbl(); dlbl.parent = cat_ax; dlbl.chart = this; dlbl.spPr = cat_ax.spPr; dlbl.txPr = cat_ax.txPr; dlbl.tx = new AscFormat.CChartText(); dlbl.tx.rich = AscFormat.CreateTextBodyFromString(string_pts[i].val.replace(oNonSpaceRegExp, ' '), this.getDrawingDocument(), dlbl); if(cat_ax.labels.aLabels[0]) { dlbl.lastStyleObject = cat_ax.labels.aLabels[0].lastStyleObject; } dlbl.tx.rich.content.Set_ApplyToAll(true); dlbl.tx.rich.content.SetParagraphAlign(AscCommon.align_Center); dlbl.tx.rich.content.Set_ApplyToAll(false); var min_max = dlbl.tx.rich.content.RecalculateMinMaxContentWidth(); var max_min_content_width = min_max.Min; if(min_max.Max > max_max_width) max_max_width = min_max.Max; if(min_max.Min > max_min_width) max_min_width = min_max.Min; arr_min_max_min[i] = min_max.Min; dlbl.getMaxWidth = function(){return 20000}; dlbl.recalcInfo.recalculatePen = false; dlbl.recalcInfo.recalculateBrush = false; dlbl.recalculate(); delete dlbl.getMaxWidth; if(dlbl.tx.rich.content.XLimit > max_content_width) max_content_width = dlbl.tx.rich.content.XLimit; } cat_ax.labels.aLabels.push(dlbl); } var stake_offset = AscFormat.isRealNumber(cat_ax.lblOffset) ? cat_ax.lblOffset/100 : 1; var labels_offset = cat_ax.labels.aLabels[0].tx.rich.content.Content[0].CompiledPr.Pr.TextPr.FontSize*(25.4/72)*stake_offset; //сначала посмотрим убираются ли в максимальную допустимую ширину подписей подписи расчитанные в одну строку var width_flag; if(max_content_width + labels_offset < max_cat_labels_block_width) { width_flag = 0; cat_ax.labels.extX = max_content_width + labels_offset; } else if(max_min_width + labels_offset < max_cat_labels_block_width)//ситуация, когда возможно разместить подписи без переноса слов { width_flag = 1; cat_ax.labels.extX = max_min_width + labels_offset; } else //выставляем максимально возможную ширину { width_flag = 2; cat_ax.labels.extX = max_cat_labels_block_width; } } var cat_labels_align_left = true;//выравнивание подписей в блоке сподписями по левому краю(т. е. зазор находится справа) /*-----------------------------------------------------------------------*/ var crosses_val_ax;//значение на горизонтальной оси значений в котором её пересекает горизонтальная if(cat_ax.crosses === AscFormat.CROSSES_AUTO_ZERO) { if(arr_val[0] <=0 && arr_val[arr_val.length-1] >= 0) crosses_val_ax = 0; else if(arr_val[arr_val.length-1] < 0) crosses_val_ax = arr_val[arr_val.length-1]; else crosses_val_ax = arr_val[0]; } else if(cat_ax.crosses === AscFormat.CROSSES_MIN) { crosses_val_ax = arr_val[0]; } else if(cat_ax.crosses === AscFormat.CROSSES_MAX) { crosses_val_ax = arr_val[arr_val.length - 1]; } else if(AscFormat.isRealNumber(cat_ax.crossesAt) && cat_ax.crossesAt >= arr_val[0] && cat_ax.crossesAt <= arr_val[arr_val.length - 1]) { //сделаем провеку на попадание в интервал if(cat_ax.crossesAt >= arr_val[0] && cat_ax.crossesAt <= arr_val[arr_val.length - 1]) crosses_val_ax = cat_ax.crossesAt; } else { //ведем себя как в случае (cat_ax.crosses === AscFormat.CROSSES_AUTO_ZERO) if(arr_val[0] <=0 && arr_val[arr_val.length-1] >= 0) crosses_val_ax = 0; else if(arr_val[arr_val.length-1] < 0) crosses_val_ax = arr_val[arr_val.length-1]; else crosses_val_ax = arr_val[0]; } var val_ax_orientation = val_ax.scaling && AscFormat.isRealNumber(val_ax.scaling.orientation) ? val_ax.scaling.orientation : AscFormat.ORIENTATION_MIN_MAX; var hor_labels_pos = cat_ax.tickLblPos; var first_val_lbl_half_width = (val_ax.tickLblPos === c_oAscTickLabelsPos.TICK_LABEL_POSITION_NONE || val_ax.bDelete) ? 0 : val_ax.labels.aLabels[0].tx.rich.content.XLimit/2; var last_val_lbl_half_width = (val_ax.tickLblPos === c_oAscTickLabelsPos.TICK_LABEL_POSITION_NONE || val_ax.bDelete) ? 0 : val_ax.labels.aLabels[val_ax.labels.aLabels.length-1].tx.rich.content.XLimit/2; var right_gap, left_gap; var arr_val_labels_points = [];//массив середин подписей вертикальной оси; i-й элемент - x-координата центра подписи i-огто значения; var unit_width = checkFiniteNumber((rect.w - first_val_lbl_half_width - last_val_lbl_half_width)/(arr_val[arr_val.length - 1] - arr_val[0]));//ширина единицы измерения на вертикальной оси var cat_ax_ext_x = cat_ax.labels && !bWithoutLabels ? cat_ax.labels.extX : 0; if(val_ax_orientation === AscFormat.ORIENTATION_MIN_MAX) { if(hor_labels_pos === c_oAscTickLabelsPos.TICK_LABEL_POSITION_NEXT_TO || !AscFormat.isRealNumber(hor_labels_pos)) { if(cat_ax.crosses === AscFormat.CROSSES_MAX) { if(!bNeedReflect) { right_gap = Math.max(last_val_lbl_half_width, cat_ax_ext_x); } else { right_gap = Math.max(last_val_lbl_half_width, 0); } cat_labels_align_left = false;//в данном случае подписи будут выравниваться по верхнему краю блока с подписями if(cat_ax.labels) cat_ax.labels.x = rect.x + rect.w - right_gap; unit_width = checkFiniteNumber((rect.w - right_gap - first_val_lbl_half_width)/(arr_val[arr_val.length - 1] - arr_val[0])); cat_ax.posX = rect.x + first_val_lbl_half_width + (crosses_val_ax - arr_val[0])*unit_width; } else { if(!bNeedReflect && (crosses_val_ax - arr_val[0])*unit_width + first_val_lbl_half_width < cat_ax_ext_x) { unit_width = checkFiniteNumber((rect.w - cat_ax_ext_x - last_val_lbl_half_width)/(arr_val[arr_val.length-1] - crosses_val_ax)); } cat_ax.posX = rect.x + rect.w - last_val_lbl_half_width - (arr_val[arr_val.length-1] - crosses_val_ax)*unit_width; if(cat_ax.labels) cat_ax.labels.x = cat_ax.posX - cat_ax.labels.extX; } for(i = 0; i < arr_val.length; ++i) arr_val_labels_points[i] = cat_ax.posX + (arr_val[i] - crosses_val_ax)*unit_width; } else if(hor_labels_pos === c_oAscTickLabelsPos.TICK_LABEL_POSITION_LOW) { if(!bNeedReflect) { left_gap = Math.max(first_val_lbl_half_width, cat_ax_ext_x); } else { left_gap = Math.max(first_val_lbl_half_width, 0); } unit_width = checkFiniteNumber((rect.w - left_gap - last_val_lbl_half_width)/(arr_val[arr_val.length - 1] - arr_val[0])); cat_ax.posX = rect.x + rect.w - (arr_val[arr_val.length-1] - crosses_val_ax )*unit_width - last_val_lbl_half_width; for(i = 0; i < arr_val.length; ++i) arr_val_labels_points[i] = cat_ax.posX + (arr_val[i] - crosses_val_ax)*unit_width; if(cat_ax.labels) cat_ax.labels.x = cat_ax.posX + (arr_val[i] - crosses_val_ax)*unit_width - cat_ax.labels.extX; } else if(hor_labels_pos === c_oAscTickLabelsPos.TICK_LABEL_POSITION_HIGH) { cat_labels_align_left = false; if(!bNeedReflect) { right_gap = Math.max(last_val_lbl_half_width, cat_ax_ext_x); } else { right_gap = Math.max(last_val_lbl_half_width, 0); } unit_width = checkFiniteNumber((rect.w - right_gap - first_val_lbl_half_width)/(arr_val[arr_val.length - 1] - arr_val[0])); cat_ax.posX = rect.x + first_val_lbl_half_width + (crosses_val_ax - arr_val[0])*unit_width; for(i = 0; i < arr_val.length; ++i) arr_val_labels_points[i] = cat_ax.posX + (arr_val[i] - crosses_val_ax)*unit_width; } else { //подписей осей нет cat_ax.labels = null; unit_width = checkFiniteNumber((rect.w - last_val_lbl_half_width - first_val_lbl_half_width)/(arr_val[arr_val.length - 1] - arr_val[0])); cat_ax.posX = rect.x + first_val_lbl_half_width + (crosses_val_ax - arr_val[0])*unit_width; for(i = 0; i < arr_val.length; ++i) arr_val_labels_points[i] = cat_ax.posX + (arr_val[i] - crosses_val_ax)*unit_width; } } else {//зеркально отражаем if(hor_labels_pos === c_oAscTickLabelsPos.TICK_LABEL_POSITION_NEXT_TO || !AscFormat.isRealNumber(hor_labels_pos)) { if(cat_ax.crosses === AscFormat.CROSSES_MAX) { if(!bNeedReflect) { left_gap = Math.max(cat_ax_ext_x, last_val_lbl_half_width); } else { left_gap = Math.max(0, last_val_lbl_half_width); } unit_width = checkFiniteNumber((rect.w - left_gap - first_val_lbl_half_width)/(arr_val[arr_val.length - 1] - arr_val[0])); cat_ax.posX = rect.x + rect.w - first_val_lbl_half_width - (crosses_val_ax - arr_val[0])*unit_width; if(cat_ax.labels) cat_ax.labels.x = cat_ax.posX - cat_ax.labels.extX; } else { cat_labels_align_left = false; if(!bNeedReflect && first_val_lbl_half_width < cat_ax_ext_x) { unit_width = checkFiniteNumber((rect.w - cat_ax_ext_x - last_val_lbl_half_width)/(arr_val[arr_val.length - 1] - arr_val[0])); } cat_ax.posX = rect.x + last_val_lbl_half_width + (arr_val[arr_val.length-1] - crosses_val_ax)*unit_width; if(cat_ax.labels) cat_ax.labels.x = cat_ax.posX; } for(i = 0; i < arr_val.length; ++i) arr_val_labels_points[i] = cat_ax.posX - (arr_val[i] - crosses_val_ax)*unit_width; } else if(hor_labels_pos === c_oAscTickLabelsPos.TICK_LABEL_POSITION_LOW) { cat_labels_align_left = false; if(!bNeedReflect) { right_gap = Math.max(first_val_lbl_half_width, cat_ax_ext_x); } else { right_gap = Math.max(first_val_lbl_half_width, 0); } unit_width = checkFiniteNumber((rect.w - last_val_lbl_half_width - right_gap)/(arr_val[arr_val.length-1] - arr_val[0])); cat_ax.posX = rect.x + last_val_lbl_half_width + (arr_val[arr_val.length-1] - crosses_val_ax)*crosses_val_ax; if(cat_ax.labels) cat_ax.labels.x = cat_ax.posX - (arr_val[0] - crosses_val_ax)*unit_width; for(i = 0; i < arr_val.length; ++i) arr_val_labels_points[i] = cat_ax.posX - (arr_val[i] - crosses_val_ax)*unit_width; } else if(hor_labels_pos === c_oAscTickLabelsPos.TICK_LABEL_POSITION_HIGH) { if(!bNeedReflect) { left_gap = Math.max(cat_ax_ext_x, last_val_lbl_half_width); } else { left_gap = Math.max(0, last_val_lbl_half_width); } unit_width = checkFiniteNumber((rect.w - left_gap - first_val_lbl_half_width)/(arr_val[arr_val.length - 1] - arr_val[0])); cat_ax.posX = rect.x + rect.w - first_val_lbl_half_width - (crosses_val_ax - arr_val[0])*unit_width; if(cat_ax.labels) cat_ax.labels.x = cat_ax.posX - (arr_val[arr_val.length-1] - crosses_val_ax)*unit_width - cat_ax.labels.extX; for(i = 0; i < arr_val.length; ++i) arr_val_labels_points[i] = cat_ax.posX - (arr_val[i] - crosses_val_ax)*unit_width; } else {//подписей осей нет cat_ax.labels = null; unit_width = checkFiniteNumber((rect.w - last_val_lbl_half_width - first_val_lbl_half_width)/(arr_val[arr_val.length - 1] - arr_val[0])); cat_ax.posX = rect.x + rect.w - first_val_lbl_half_width - (crosses_val_ax - arr_val[0])*unit_width; for(i = 0; i < arr_val.length; ++i) arr_val_labels_points[i] = cat_ax.posX - (arr_val[i] - crosses_val_ax)*unit_width; } } val_ax.interval = unit_width; //запишем в оси необходимую информацию для отрисовщика plotArea и выставим окончательные позиции для подписей var local_transform_text; if(val_ax.labels) { val_ax.labels.x = Math.min.apply(Math, arr_val_labels_points) - max_val_ax_label_width/2; val_ax.labels.extX = Math.max.apply(Math, arr_val_labels_points) - Math.min.apply(Math, arr_val_labels_points) + max_val_ax_label_width; //val_axis_labels_gap - вертикальный зазор val_ax.labels.align = bottom_val_ax_labels_align; if(bottom_val_ax_labels_align) { var y_pos = val_ax.labels.y + val_axis_labels_gap; for(i = 0; i < val_ax.labels.aLabels.length; ++i) { var text_transform = val_ax.labels.aLabels[i].transformText; text_transform.Reset(); global_MatrixTransformer.TranslateAppend(text_transform, arr_val_labels_points[i] - val_ax.labels.aLabels[i].tx.rich.content.XLimit/2, y_pos); // global_MatrixTransformer.MultiplyAppend(text_transform, this.getTransformMatrix()); var local_transform_text = val_ax.labels.aLabels[i].localTransformText; local_transform_text.Reset(); global_MatrixTransformer.TranslateAppend(local_transform_text, arr_val_labels_points[i] - val_ax.labels.aLabels[i].tx.rich.content.XLimit/2, y_pos); } } else { for(i = 0; i < val_ax.labels.aLabels.length; ++i) { var text_transform = val_ax.labels.aLabels[i].transformText; text_transform.Reset(); global_MatrixTransformer.TranslateAppend(text_transform, arr_val_labels_points[i] - val_ax.labels.aLabels[i].tx.rich.content.XLimit/2, val_ax.labels.y + val_ax.labels.extY - val_axis_labels_gap - val_ax.labels.aLabels[i].tx.rich.content.GetSummaryHeight()); // global_MatrixTransformer.MultiplyAppend(text_transform, this.getTransformMatrix()); var local_transform_text = val_ax.labels.aLabels[i].localTransformText; local_transform_text.Reset(); global_MatrixTransformer.TranslateAppend(local_transform_text, arr_val_labels_points[i] - val_ax.labels.aLabels[i].tx.rich.content.XLimit/2, val_ax.labels.y + val_ax.labels.extY - val_axis_labels_gap - val_ax.labels.aLabels[i].tx.rich.content.GetSummaryHeight()); } } } val_ax.xPoints = []; for(i = 0; i < arr_val_labels_points.length; ++i) { val_ax.xPoints[i] = {val:arr_val[i], pos: arr_val_labels_points[i]}; } cat_ax.yPoints = []; for(i = 0; i <arr_cat_labels_points.length; ++i) { cat_ax.yPoints[i] = {val: i, pos: arr_cat_labels_points[i]}; } if(cat_ax.labels) { cat_ax.labels.y = rect.y; cat_ax.labels.extY = point_interval*intervals_count; if(bNeedReflect) { if(cat_labels_align_left) { cat_labels_align_left = false; cat_ax.labels.x += cat_ax.labels.extX; } else { cat_labels_align_left = true; cat_ax.labels.x -= cat_ax.labels.extX; } } if(cat_labels_align_left) { if(width_flag === 0) { for(i = 0; i < cat_ax.labels.aLabels.length; ++i) { if(cat_ax.labels.aLabels[i]) { var transform_text = cat_ax.labels.aLabels[i].transformText; transform_text.Reset(); global_MatrixTransformer.TranslateAppend(transform_text, cat_ax.labels.x + cat_ax.labels.extX - cat_ax.labels.aLabels[i].tx.rich.content.XLimit - labels_offset, arr_cat_labels_points[i] - cat_ax.labels.aLabels[i].tx.rich.content.GetSummaryHeight()/2); // global_MatrixTransformer.MultiplyAppend(transform_text, this.getTransformMatrix()); local_transform_text = cat_ax.labels.aLabels[i].localTransformText; local_transform_text.Reset(); global_MatrixTransformer.TranslateAppend(local_transform_text, cat_ax.labels.x + cat_ax.labels.extX - cat_ax.labels.aLabels[i].tx.rich.content.XLimit - labels_offset, arr_cat_labels_points[i] - cat_ax.labels.aLabels[i].tx.rich.content.GetSummaryHeight()/2); } } } else if(width_flag === 1) { for(i = 0; i < cat_ax.labels.aLabels.length; ++i) { if(cat_ax.labels.aLabels[i]) { cat_ax.labels.aLabels[i].tx.rich.content.Reset(0, 0, arr_min_max_min[i], 20000); cat_ax.labels.aLabels[i].tx.rich.content.Recalculate_Page(0, true); var transform_text = cat_ax.labels.aLabels[i].transformText; transform_text.Reset(); global_MatrixTransformer.TranslateAppend(transform_text, cat_ax.labels.x + cat_ax.labels.extX - cat_ax.labels.aLabels[i].tx.rich.content.XLimit - labels_offset, arr_cat_labels_points[i] - cat_ax.labels.aLabels[i].tx.rich.content.GetSummaryHeight()/2); // global_MatrixTransformer.MultiplyAppend(transform_text, this.getTransformMatrix()); local_transform_text = cat_ax.labels.aLabels[i].localTransformText; local_transform_text.Reset(); global_MatrixTransformer.TranslateAppend(local_transform_text, cat_ax.labels.x + cat_ax.labels.extX - cat_ax.labels.aLabels[i].tx.rich.content.XLimit - labels_offset, arr_cat_labels_points[i] - cat_ax.labels.aLabels[i].tx.rich.content.GetSummaryHeight()/2); } } } else { for(i = 0; i < cat_ax.labels.aLabels.length; ++i) { if(cat_ax.labels.aLabels[i]) { cat_ax.labels.aLabels[i].tx.rich.content.Reset(0, 0, cat_ax.labels.extX - labels_offset, 20000); cat_ax.labels.aLabels[i].tx.rich.content.Recalculate_Page(0, true); var transform_text = cat_ax.labels.aLabels[i].transformText; transform_text.Reset(); global_MatrixTransformer.TranslateAppend(transform_text, cat_ax.labels.x + cat_ax.labels.extX - cat_ax.labels.aLabels[i].tx.rich.content.XLimit - labels_offset, arr_cat_labels_points[i] - cat_ax.labels.aLabels[i].tx.rich.content.GetSummaryHeight()/2); // global_MatrixTransformer.MultiplyAppend(transform_text, this.getTransformMatrix()); local_text_transform = cat_ax.labels.aLabels[i].localTransformText; local_text_transform.Reset(); global_MatrixTransformer.TranslateAppend(local_text_transform, cat_ax.labels.x + cat_ax.labels.extX - cat_ax.labels.aLabels[i].tx.rich.content.XLimit - labels_offset, arr_cat_labels_points[i] - cat_ax.labels.aLabels[i].tx.rich.content.GetSummaryHeight()/2); } } } /*for(i = 0; i < cat_ax.labels.aLabels.length; ++i) { if(cat_ax.labels.aLabels[i]) { cat_ax.labels.aLabels[i].tx.rich.content.Set_ApplyToAll(true); cat_ax.labels.aLabels[i].tx.rich.content.SetParagraphAlign(align_Center); cat_ax.labels.aLabels[i].tx.rich.content.Set_ApplyToAll(false); cat_ax.labels.aLabels[i].tx.rich.content.Reset(0, 0, cat_ax.labels.extX - labels_offset, 2000); cat_ax.labels.aLabels[i].tx.rich.content.Recalculate_Page(0, true); cat_ax.labels.aLabels[i].setPosition(cat_ax.labels.x, arr_cat_labels_points[i] - cat_ax.labels.aLabels[i].tx.rich.content.GetSummaryHeight()/2); } } */ } else { if(width_flag === 0) { for(i = 0; i < cat_ax.labels.aLabels.length; ++i) { if(cat_ax.labels.aLabels[i]) { var transform_text = cat_ax.labels.aLabels[i].transformText; transform_text.Reset(); global_MatrixTransformer.TranslateAppend(transform_text, cat_ax.labels.x + labels_offset, arr_cat_labels_points[i] - cat_ax.labels.aLabels[i].tx.rich.content.GetSummaryHeight()/2); // global_MatrixTransformer.MultiplyAppend(transform_text, this.getTransformMatrix()); local_text_transform = cat_ax.labels.aLabels[i].localTransformText; local_text_transform.Reset(); global_MatrixTransformer.TranslateAppend(local_text_transform, cat_ax.labels.x + labels_offset, arr_cat_labels_points[i] - cat_ax.labels.aLabels[i].tx.rich.content.GetSummaryHeight()/2); } } } else if(width_flag === 1) { for(i = 0; i < cat_ax.labels.aLabels.length; ++i) { if(cat_ax.labels.aLabels[i]) { cat_ax.labels.aLabels[i].tx.rich.content.Reset(0, 0, arr_min_max_min[i], 20000); cat_ax.labels.aLabels[i].tx.rich.content.Recalculate_Page(0, true); var transform_text = cat_ax.labels.aLabels[i].transformText; transform_text.Reset(); global_MatrixTransformer.TranslateAppend(transform_text, cat_ax.labels.x + labels_offset, arr_cat_labels_points[i] - cat_ax.labels.aLabels[i].tx.rich.content.GetSummaryHeight()/2); // global_MatrixTransformer.MultiplyAppend(transform_text, this.getTransformMatrix()); local_text_transform = cat_ax.labels.aLabels[i].localTransformText; local_text_transform.Reset(); global_MatrixTransformer.TranslateAppend(local_text_transform, cat_ax.labels.x + labels_offset, arr_cat_labels_points[i] - cat_ax.labels.aLabels[i].tx.rich.content.GetSummaryHeight()/2); } } } else { for(i = 0; i < cat_ax.labels.aLabels.length; ++i) { if(cat_ax.labels.aLabels[i]) { cat_ax.labels.aLabels[i].tx.rich.content.Reset(0, 0, cat_ax.labels.extX - labels_offset, 20000); cat_ax.labels.aLabels[i].tx.rich.content.Recalculate_Page(0, true); var transform_text = cat_ax.labels.aLabels[i].transformText; transform_text.Reset(); global_MatrixTransformer.TranslateAppend(transform_text, cat_ax.labels.x + labels_offset, arr_cat_labels_points[i] - cat_ax.labels.aLabels[i].tx.rich.content.GetSummaryHeight()/2); // global_MatrixTransformer.MultiplyAppend(transform_text, this.getTransformMatrix()); local_text_transform = cat_ax.labels.aLabels[i].localTransformText; local_text_transform.Reset(); global_MatrixTransformer.TranslateAppend(local_text_transform, cat_ax.labels.x + labels_offset, arr_cat_labels_points[i] - cat_ax.labels.aLabels[i].tx.rich.content.GetSummaryHeight()/2); } } } } } cat_ax.yPoints.sort(function(a, b){return a.val - b.val}); val_ax.xPoints.sort(function(a, b){return a.val - b.val}); } else{ this.bEmptySeries = true; } } this.plotAreaRect = rect; } }; CChartSpace.prototype.checkAxisLabelsTransform = function() { if(this.chart && this.chart.plotArea && this.chart.plotArea.charts[0] && this.chart.plotArea.charts[0].getAxisByTypes) { var oAxisByTypes = this.chart.plotArea.charts[0].getAxisByTypes(); var oCatAx = oAxisByTypes.catAx[0], oValAx = oAxisByTypes.valAx[0], deltaX, deltaY, i, oAxisLabels, oLabel, oNewPos; var oProcessor3D = this.chartObj && this.chartObj.processor3D; var aXPoints = [], aYPoints = []; if(oCatAx && oValAx && oProcessor3D) { if(( (oCatAx.axPos === AscFormat.AX_POS_B || oCatAx.axPos === AscFormat.AX_POS_T) && oCatAx.xPoints) && ((oValAx.axPos === AscFormat.AX_POS_L || oValAx.axPos === AscFormat.AX_POS_R) && oValAx.yPoints)) { oAxisLabels = oCatAx.labels; if(oAxisLabels) { var dZPositionCatAxis = oProcessor3D.calculateZPositionCatAxis(); var dPosY, dPosY2 if(oAxisLabels.align) { dPosY = oAxisLabels.y*this.chartObj.calcProp.pxToMM; dPosY2 = oAxisLabels.y; } else { dPosY = (oAxisLabels.y + oAxisLabels.extY)*this.chartObj.calcProp.pxToMM; dPosY2 = oAxisLabels.y + oAxisLabels.extY; } var fBottomLabels = -100; if(!oAxisLabels.bRotated) { for(i = 0; i < oAxisLabels.aLabels.length; ++i) { oLabel = oAxisLabels.aLabels[i]; if(oLabel) { var oCPosLabelX; oCPosLabelX = oLabel.localTransformText.TransformPointX(oLabel.txBody.content.XLimit/2, 0); oNewPos = oProcessor3D.convertAndTurnPoint(oCPosLabelX*this.chartObj.calcProp.pxToMM, dPosY, dZPositionCatAxis); oLabel.setPosition2(oNewPos.x/this.chartObj.calcProp.pxToMM + oLabel.localTransformText.tx - oCPosLabelX, oLabel.localTransformText.ty - dPosY2 + oNewPos.y/this.chartObj.calcProp.pxToMM ); var fBottomContent = oLabel.y + oLabel.tx.rich.content.GetSummaryHeight(); if(fBottomContent > fBottomLabels){ fBottomLabels = fBottomContent; } } } } else { if(oAxisLabels.align) { var stake_offset = AscFormat.isRealNumber(oCatAx.lblOffset) ? oCatAx.lblOffset/100 : 1; var labels_offset = oCatAx.labels.aLabels[0].tx.rich.content.Content[0].CompiledPr.Pr.TextPr.FontSize*(25.4/72)*stake_offset; for(i = 0; i < oAxisLabels.aLabels.length; ++i) { if(oAxisLabels.aLabels[i]) { oLabel = oAxisLabels.aLabels[i]; var wh = {w: oLabel.widthForTransform, h: oLabel.tx.rich.content.GetSummaryHeight()}, w2, h2, x1, y0, xc, yc; w2 = wh.w*Math.cos(Math.PI/4) + wh.h*Math.sin(Math.PI/4); h2 = wh.w*Math.sin(Math.PI/4) + wh.h*Math.cos(Math.PI/4); x1 = oCatAx.xPoints[i].pos + wh.h*Math.sin(Math.PI/4); y0 = oAxisLabels.y + labels_offset; var x1t, y0t; var oRes = oProcessor3D.convertAndTurnPoint(x1*this.chartObj.calcProp.pxToMM, y0*this.chartObj.calcProp.pxToMM, dZPositionCatAxis); x1t = oRes.x/this.chartObj.calcProp.pxToMM; y0t = oRes.y/this.chartObj.calcProp.pxToMM; xc = x1t - w2/2; yc = y0t + h2/2; var local_text_transform = oLabel.localTransformText; local_text_transform.Reset(); global_MatrixTransformer.TranslateAppend(local_text_transform, -wh.w/2, -wh.h/2); global_MatrixTransformer.RotateRadAppend(local_text_transform, Math.PI/4); global_MatrixTransformer.TranslateAppend(local_text_transform, xc, yc); var fBottomContent = y0t + h2; if(fBottomContent > fBottomLabels){ fBottomLabels = fBottomContent; } } } } else { var stake_offset = AscFormat.isRealNumber(oCatAx.lblOffset) ? oCatAx.lblOffset/100 : 1; var labels_offset = oCatAx.labels.aLabels[0].tx.rich.content.Content[0].CompiledPr.Pr.TextPr.FontSize*(25.4/72)*stake_offset; for(i = 0; i < oAxisLabels.aLabels.length; ++i) { if(oAxisLabels.aLabels[i]) { oLabel = oAxisLabels.aLabels[i]; var wh = {w: oLabel.widthForTransform, h: oLabel.tx.rich.content.GetSummaryHeight()}, w2, h2, x1, y0, xc, yc; w2 = wh.w*Math.cos(Math.PI/4) + wh.h*Math.sin(Math.PI/4); h2 = wh.w*Math.sin(Math.PI/4) + wh.h*Math.cos(Math.PI/4); x1 = oCatAx.xPoints[i].pos - wh.h*Math.sin(Math.PI/4); y0 = oAxisLabels.y + oAxisLabels.extY - labels_offset; var x1t, y0t; var oRes = oProcessor3D.convertAndTurnPoint(x1*this.chartObj.calcProp.pxToMM, y0*this.chartObj.calcProp.pxToMM, dZPositionCatAxis); x1t = oRes.x/this.chartObj.calcProp.pxToMM; y0t = oRes.y/this.chartObj.calcProp.pxToMM; xc = x1t + w2/2; yc = y0t - h2/2; local_text_transform = oLabel.localTransformText; local_text_transform.Reset(); global_MatrixTransformer.TranslateAppend(local_text_transform, -wh.w/2, -wh.h/2); global_MatrixTransformer.RotateRadAppend(local_text_transform, Math.PI/4);//TODO global_MatrixTransformer.TranslateAppend(local_text_transform, xc, yc); } } } } oNewPos = oProcessor3D.convertAndTurnPoint(oAxisLabels.x*this.chartObj.calcProp.pxToMM, oAxisLabels.y*this.chartObj.calcProp.pxToMM, dZPositionCatAxis); aXPoints.push(oNewPos.x/this.chartObj.calcProp.pxToMM); aYPoints.push(oNewPos.y/this.chartObj.calcProp.pxToMM); oNewPos = oProcessor3D.convertAndTurnPoint((oAxisLabels.x + oAxisLabels.extX)*this.chartObj.calcProp.pxToMM, oAxisLabels.y*this.chartObj.calcProp.pxToMM, dZPositionCatAxis); aXPoints.push(oNewPos.x/this.chartObj.calcProp.pxToMM); aYPoints.push(oNewPos.y/this.chartObj.calcProp.pxToMM); oNewPos = oProcessor3D.convertAndTurnPoint((oAxisLabels.x + oAxisLabels.extX)*this.chartObj.calcProp.pxToMM, (oAxisLabels.y + oAxisLabels.extY)*this.chartObj.calcProp.pxToMM, dZPositionCatAxis); aXPoints.push(oNewPos.x/this.chartObj.calcProp.pxToMM); aYPoints.push(oNewPos.y/this.chartObj.calcProp.pxToMM); oNewPos = oProcessor3D.convertAndTurnPoint((oAxisLabels.x)*this.chartObj.calcProp.pxToMM, (oAxisLabels.y + oAxisLabels.extY)*this.chartObj.calcProp.pxToMM, dZPositionCatAxis); aXPoints.push(oNewPos.x/this.chartObj.calcProp.pxToMM); aYPoints.push(oNewPos.y/this.chartObj.calcProp.pxToMM); oAxisLabels.x = Math.min.apply(Math, aXPoints); oAxisLabels.y = Math.min.apply(Math, aYPoints); oAxisLabels.extX = Math.max.apply(Math, aXPoints) - oAxisLabels.x; oAxisLabels.extY = Math.max(Math.max.apply(Math, aYPoints), fBottomLabels) - oAxisLabels.y; } oAxisLabels = oValAx.labels; if(oAxisLabels) { var dZPositionCatAxis = oProcessor3D.calculateZPositionValAxis(); var dPosX, dPosX2; if(!oAxisLabels.align) { dPosX2 = oAxisLabels.x; dPosX = oAxisLabels.x*this.chartObj.calcProp.pxToMM; } else { dPosX2 = oAxisLabels.x + oAxisLabels.extX; dPosX = (oAxisLabels.x + oAxisLabels.extX)*this.chartObj.calcProp.pxToMM; } aXPoints.length = 0; aYPoints.length = 0; for(i = 0; i < oAxisLabels.aLabels.length; ++i) { oLabel = oAxisLabels.aLabels[i]; if(oLabel) { oNewPos = oProcessor3D.convertAndTurnPoint(dPosX, oLabel.localTransformText.ty*this.chartObj.calcProp.pxToMM, dZPositionCatAxis); oLabel.setPosition2(oLabel.localTransformText.tx - dPosX2 + oNewPos.x/this.chartObj.calcProp.pxToMM, oNewPos.y/this.chartObj.calcProp.pxToMM); aXPoints.push(oLabel.x); aYPoints.push(oLabel.y); aXPoints.push(oLabel.x + oLabel.txBody.content.XLimit); aYPoints.push(oLabel.y + oLabel.txBody.content.GetSummaryHeight()); } } if(aXPoints.length > 0 && aYPoints.length > 0) { oAxisLabels.x = Math.min.apply(Math, aXPoints); oAxisLabels.y = Math.min.apply(Math, aYPoints); oAxisLabels.extX = Math.max.apply(Math, aXPoints) - oAxisLabels.x; oAxisLabels.extY = Math.max.apply(Math, aYPoints) - oAxisLabels.y; } } } else if(((oCatAx.axPos === AscFormat.AX_POS_L || oCatAx.axPos === AscFormat.AX_POS_R) && oCatAx.yPoints) && ((oValAx.axPos === AscFormat.AX_POS_T || oValAx.axPos === AscFormat.AX_POS_B) && oValAx.xPoints)) { oAxisLabels = oValAx.labels; if(oAxisLabels) { var dZPositionValAxis = oProcessor3D.calculateZPositionValAxis(); var dPosY, dPosY2 if(oAxisLabels.align) { dPosY = oAxisLabels.y*this.chartObj.calcProp.pxToMM; dPosY2 = oAxisLabels.y; } else { dPosY = (oAxisLabels.y + oAxisLabels.extY)*this.chartObj.calcProp.pxToMM; dPosY2 = oAxisLabels.y + oAxisLabels.extY; } for(i = 0; i < oAxisLabels.aLabels.length; ++i) { oLabel = oAxisLabels.aLabels[i]; if(oLabel) { var oCPosLabelX = oLabel.localTransformText.TransformPointX(oLabel.txBody.content.XLimit/2, 0); var oCPosLabelY = oLabel.localTransformText.TransformPointY(oLabel.txBody.content.XLimit/2, 0); oNewPos = oProcessor3D.convertAndTurnPoint(oCPosLabelX*this.chartObj.calcProp.pxToMM, dPosY, dZPositionValAxis); oLabel.setPosition2(oNewPos.x/this.chartObj.calcProp.pxToMM + oLabel.localTransformText.tx - oCPosLabelX, oLabel.localTransformText.ty - dPosY2 + oNewPos.y/this.chartObj.calcProp.pxToMM ); //oNewPos = oProcessor3D.convertAndTurnPoint(oLabel.localTransformText.tx*this.chartObj.calcProp.pxToMM, oLabel.localTransformText.ty*this.chartObj.calcProp.pxToMM, dZPositionValAxis);; //oLabel.setPosition2(oNewPos.x/this.chartObj.calcProp.pxToMM, oNewPos.y/this.chartObj.calcProp.pxToMM); } } oNewPos = oProcessor3D.convertAndTurnPoint(oAxisLabels.x*this.chartObj.calcProp.pxToMM, oAxisLabels.y*this.chartObj.calcProp.pxToMM, dZPositionValAxis); aXPoints.push(oNewPos.x/this.chartObj.calcProp.pxToMM); aYPoints.push(oNewPos.y/this.chartObj.calcProp.pxToMM); oNewPos = oProcessor3D.convertAndTurnPoint((oAxisLabels.x + oAxisLabels.extX)*this.chartObj.calcProp.pxToMM, oAxisLabels.y*this.chartObj.calcProp.pxToMM, dZPositionValAxis); aXPoints.push(oNewPos.x/this.chartObj.calcProp.pxToMM); aYPoints.push(oNewPos.y/this.chartObj.calcProp.pxToMM); oNewPos = oProcessor3D.convertAndTurnPoint((oAxisLabels.x + oAxisLabels.extX)*this.chartObj.calcProp.pxToMM, (oAxisLabels.y + oAxisLabels.extY)*this.chartObj.calcProp.pxToMM, dZPositionValAxis); aXPoints.push(oNewPos.x/this.chartObj.calcProp.pxToMM); aYPoints.push(oNewPos.y/this.chartObj.calcProp.pxToMM); oNewPos = oProcessor3D.convertAndTurnPoint((oAxisLabels.x)*this.chartObj.calcProp.pxToMM, (oAxisLabels.y + oAxisLabels.extY)*this.chartObj.calcProp.pxToMM, dZPositionValAxis); aXPoints.push(oNewPos.x/this.chartObj.calcProp.pxToMM); aYPoints.push(oNewPos.y/this.chartObj.calcProp.pxToMM); oAxisLabels.x = Math.min.apply(Math, aXPoints); oAxisLabels.y = Math.min.apply(Math, aYPoints); oAxisLabels.extX = Math.max.apply(Math, aXPoints) - oAxisLabels.x; oAxisLabels.extY = Math.max.apply(Math, aYPoints) - oAxisLabels.y; } oAxisLabels = oCatAx.labels; aXPoints.length = 0; aYPoints.length = 0; if(oAxisLabels) { var dZPositionCatAxis = oProcessor3D.calculateZPositionCatAxis(); var dPosX, dPosX2; if(oAxisLabels.align) { dPosX2 = oAxisLabels.x; dPosX = oAxisLabels.x*this.chartObj.calcProp.pxToMM; } else { dPosX2 = oAxisLabels.x + oAxisLabels.extX; dPosX = (oAxisLabels.x + oAxisLabels.extX)*this.chartObj.calcProp.pxToMM; } for(i = 0; i < oAxisLabels.aLabels.length; ++i) { oLabel = oAxisLabels.aLabels[i]; if(oLabel) { oNewPos = oProcessor3D.convertAndTurnPoint(dPosX, oLabel.localTransformText.ty*this.chartObj.calcProp.pxToMM, dZPositionCatAxis); oLabel.setPosition2(oLabel.localTransformText.tx - dPosX2 + oNewPos.x/this.chartObj.calcProp.pxToMM, oNewPos.y/this.chartObj.calcProp.pxToMM); aXPoints.push(oLabel.x); aYPoints.push(oLabel.y); aXPoints.push(oLabel.x + oLabel.txBody.content.XLimit); aYPoints.push(oLabel.y + oLabel.txBody.content.GetSummaryHeight()); } } if(aXPoints.length > 0 && aYPoints.length > 0) { oAxisLabels.x = Math.min.apply(Math, aXPoints); oAxisLabels.y = Math.min.apply(Math, aYPoints); oAxisLabels.extX = Math.max.apply(Math, aXPoints) - oAxisLabels.x; oAxisLabels.extY = Math.max.apply(Math, aYPoints) - oAxisLabels.y; } } } } } }; CChartSpace.prototype.hitInTextRect = function() { return false; }; CChartSpace.prototype.recalculateLegend = function() { if(this.chart && this.chart.legend) { var aSeries = this.getAllSeries(); var oParents = this.getParentObjects(); var oLegend = this.chart.legend; var parents = this.getParentObjects(); var RGBA = {R:0, G:0, B: 0, A:255}; var legend = this.chart.legend; var arr_str_labels = [], i; var calc_entryes = legend.calcEntryes; calc_entryes.length = 0; var series = this.getAllSeries(); var calc_entry, union_marker, entry; var max_width = 0, cur_width, max_font_size = 0, cur_font_size, ser, b_line_series; var max_word_width = 0; var b_no_line_series = false; this.chart.legend.chart = this; var b_scatter_no_line = false;/*(this.chart.plotArea.charts[0].getObjectType() === AscDFH.historyitem_type_ScatterChart && (this.chart.plotArea.charts[0].scatterStyle === AscFormat.SCATTER_STYLE_MARKER || this.chart.plotArea.charts[0].scatterStyle === AscFormat.SCATTER_STYLE_NONE)); */ this.legendLength = null; if( !(this.chart.plotArea.charts.length === 1 && this.chart.plotArea.charts[0].varyColors) || (this.chart.plotArea.charts[0].getObjectType() !== AscDFH.historyitem_type_PieChart && this.chart.plotArea.charts[0].getObjectType() !== AscDFH.historyitem_type_DoughnutChart) && series.length !== 1 || this.chart.plotArea.charts[0].getObjectType() === AscDFH.historyitem_type_SurfaceChart) { var bSurfaceChart = false; if(this.chart.plotArea.charts[0].getObjectType() === AscDFH.historyitem_type_SurfaceChart){ this.legendLength = this.chart.plotArea.charts[0].compiledBandFormats.length; ser = series[0]; bSurfaceChart = true; } else { this.legendLength = series.length; } for(i = 0; i < this.legendLength; ++i) { if(!bSurfaceChart){ ser = series[i]; if(ser.isHiddenForLegend) continue; entry = legend.findLegendEntryByIndex(i); if(entry && entry.bDelete) continue; arr_str_labels.push(ser.getSeriesName()); } else{ entry = legend.findLegendEntryByIndex(i); if(entry && entry.bDelete) continue; var oBandFmt = this.chart.plotArea.charts[0].compiledBandFormats[i]; arr_str_labels.push(oBandFmt.startValue + "-" + oBandFmt.endValue); } calc_entry = new AscFormat.CalcLegendEntry(legend, this, i); calc_entry.series = ser; calc_entry.txBody = AscFormat.CreateTextBodyFromString(arr_str_labels[arr_str_labels.length - 1], this.getDrawingDocument(), calc_entry); //if(entry) // calc_entry.txPr = entry.txPr; /*if(calc_entryes[0]) { calc_entry.lastStyleObject = calc_entryes[0].lastStyleObject; }*/ calc_entryes.push(calc_entry); cur_width = calc_entry.txBody.getRectWidth(2000); if(cur_width > max_width) max_width = cur_width; cur_font_size = calc_entry.txBody.content.Content[0].CompiledPr.Pr.TextPr.FontSize; if(cur_font_size > max_font_size) max_font_size = cur_font_size; calc_entry.calcMarkerUnion = new AscFormat.CUnionMarker(); union_marker = calc_entry.calcMarkerUnion; var pts = AscFormat.getPtsFromSeries(ser); switch(ser.getObjectType()) { case AscDFH.historyitem_type_BarSeries: case AscDFH.historyitem_type_BubbleSeries: case AscDFH.historyitem_type_AreaSeries: case AscDFH.historyitem_type_PieSeries: { union_marker.marker = AscFormat.CreateMarkerGeometryByType(AscFormat.SYMBOL_SQUARE, null); union_marker.marker.pen = ser.compiledSeriesPen; union_marker.marker.brush = ser.compiledSeriesBrush; break; } case AscDFH.historyitem_type_SurfaceSeries:{ var oBandFmt = this.chart.plotArea.charts[0].compiledBandFormats[i]; union_marker.marker = AscFormat.CreateMarkerGeometryByType(AscFormat.SYMBOL_SQUARE, null); union_marker.marker.pen = oBandFmt.spPr.ln; union_marker.marker.brush = oBandFmt.spPr.Fill; break; } case AscDFH.historyitem_type_LineSeries: case AscDFH.historyitem_type_ScatterSer: case AscDFH.historyitem_type_SurfaceSeries: { if(AscFormat.CChartsDrawer.prototype._isSwitchCurrent3DChart(this)) { union_marker.marker = AscFormat.CreateMarkerGeometryByType(AscFormat.SYMBOL_SQUARE, null); union_marker.marker.pen = ser.compiledSeriesPen; union_marker.marker.brush = ser.compiledSeriesBrush; break; } if(ser.compiledSeriesMarker) { var pts = AscFormat.getPtsFromSeries(ser); union_marker.marker = AscFormat.CreateMarkerGeometryByType(ser.compiledSeriesMarker.symbol, null); if(pts[0] && pts[0].compiledMarker) { union_marker.marker.brush = pts[0].compiledMarker.brush; union_marker.marker.pen = pts[0].compiledMarker.pen; } } if(ser.compiledSeriesPen && !b_scatter_no_line) { union_marker.lineMarker = AscFormat.CreateMarkerGeometryByType(AscFormat.SYMBOL_DASH, null); union_marker.lineMarker.pen = ser.compiledSeriesPen.createDuplicate(); //Копируем, так как потом возможно придется изменять толщину линии; } if(!b_scatter_no_line && !AscFormat.CChartsDrawer.prototype._isSwitchCurrent3DChart(this)) b_line_series = true; break; } } if(union_marker.marker) { union_marker.marker.pen && union_marker.marker.pen.calculate(parents.theme, parents.slide, parents.layout, parents.master, RGBA, this.clrMapOvr); union_marker.marker.brush && union_marker.marker.brush.calculate(parents.theme, parents.slide, parents.layout, parents.master, RGBA, this.clrMapOvr); } union_marker.lineMarker && union_marker.lineMarker.pen && union_marker.lineMarker.pen.calculate(parents.theme, parents.slide, parents.layout, parents.master, RGBA, this.clrMapOvr); } } else { ser = series[0]; i = 1; while(ser && ser.isHiddenForLegend) { ser = series[i]; ++i; } var pts = AscFormat.getPtsFromSeries(ser), pt; var cat_str_lit = getCatStringPointsFromSeries(ser); this.legendLength = pts.length; for(i = 0; i < pts.length; ++i) { entry = legend.findLegendEntryByIndex(i); if(entry && entry.bDelete) continue; pt = pts[i]; var str_pt = cat_str_lit ? cat_str_lit.getPtByIndex(pt.idx) : null; if(str_pt) arr_str_labels.push(str_pt.val); else arr_str_labels.push((pt.idx + 1) + ""); calc_entry = new AscFormat.CalcLegendEntry(legend, this, pt.idx); calc_entry.txBody = AscFormat.CreateTextBodyFromString(arr_str_labels[arr_str_labels.length - 1], this.getDrawingDocument(), calc_entry); //if(entry) // calc_entry.txPr = entry.txPr; //if(calc_entryes[0]) //{ // calc_entry.lastStyleObject = calc_entryes[0].lastStyleObject; //} calc_entryes.push(calc_entry); cur_width = calc_entry.txBody.getRectWidth(2000); if(cur_width > max_width) max_width = cur_width; cur_font_size = calc_entry.txBody.content.Content[0].CompiledPr.Pr.TextPr.FontSize; if(cur_font_size > max_font_size) max_font_size = cur_font_size; calc_entry.calcMarkerUnion = new AscFormat.CUnionMarker(); union_marker = calc_entry.calcMarkerUnion; if(ser.getObjectType() === AscDFH.historyitem_type_LineSeries && !AscFormat.CChartsDrawer.prototype._isSwitchCurrent3DChart(this) || ser.getObjectType() === AscDFH.historyitem_type_ScatterSer) { if(pt.compiledMarker) { union_marker.marker = AscFormat.CreateMarkerGeometryByType(pt.compiledMarker.symbol, null); union_marker.marker.brush = pt.compiledMarker.pen.Fill; union_marker.marker.pen = pt.compiledMarker.pen; } if(pt.pen) { union_marker.lineMarker = AscFormat.CreateMarkerGeometryByType(AscFormat.SYMBOL_DASH, null); union_marker.lineMarker.pen = pt.pen; } if(!b_scatter_no_line && !AscFormat.CChartsDrawer.prototype._isSwitchCurrent3DChart(this)) b_line_series = true; } else { b_no_line_series = false; union_marker.marker = AscFormat.CreateMarkerGeometryByType(AscFormat.SYMBOL_SQUARE, null); union_marker.marker.pen = pt.pen; union_marker.marker.brush = pt.brush; } if(union_marker.marker) { union_marker.marker.pen && union_marker.marker.pen.calculate(parents.theme, parents.slide, parents.layout, parents.master, RGBA, this.clrMapOvr); union_marker.marker.brush && union_marker.marker.brush.calculate(parents.theme, parents.slide, parents.layout, parents.master, RGBA, this.clrMapOvr); } union_marker.lineMarker && union_marker.lineMarker.pen && union_marker.lineMarker.pen.calculate(parents.theme, parents.slide, parents.layout, parents.master, RGBA, this.clrMapOvr); } } var marker_size; var distance_to_text; var line_marker_width; if(b_line_series) { marker_size = 2.5; line_marker_width = 7.7;//Пока так for(i = 0; i < calc_entryes.length; ++i) { calc_entry = calc_entryes[i]; if(calc_entry.calcMarkerUnion.lineMarker) { calc_entry.calcMarkerUnion.lineMarker.spPr.geometry.Recalculate(line_marker_width, 1); /*Excel не дает сделать толщину линии для маркера легенды больше определенной. Считаем, что это толщина равна 133000emu*/ if(calc_entry.calcMarkerUnion.lineMarker.pen && AscFormat.isRealNumber(calc_entry.calcMarkerUnion.lineMarker.pen.w) && calc_entry.calcMarkerUnion.lineMarker.pen.w > 133000) { calc_entry.calcMarkerUnion.lineMarker.pen.w = 133000; } calc_entry.calcMarkerUnion.lineMarker.penWidth = calc_entry.calcMarkerUnion.lineMarker.pen && AscFormat.isRealNumber(calc_entry.calcMarkerUnion.lineMarker.pen.w) ? calc_entry.calcMarkerUnion.lineMarker.pen.w/36000 : 0; } if(calc_entryes[i].calcMarkerUnion.marker) { var marker_width = marker_size; if(calc_entryes[i].series){ if(calc_entryes[i].series.getObjectType() !== AscDFH.historyitem_type_LineSeries && calc_entryes[i].series.getObjectType() !== AscDFH.historyitem_type_ScatterSer){ marker_width = line_marker_width; } } calc_entryes[i].calcMarkerUnion.marker.spPr.geometry.Recalculate(marker_width, marker_size); calc_entryes[i].calcMarkerUnion.marker.extX = marker_width; calc_entryes[i].calcMarkerUnion.marker.extY = marker_size; } } distance_to_text = 0.5; } else { marker_size = 0.2*max_font_size; for(i = 0; i < calc_entryes.length; ++i) { calc_entryes[i].calcMarkerUnion.marker.spPr.geometry.Recalculate(marker_size, marker_size); } distance_to_text = marker_size*0.8; } var left_inset = marker_size + 3*distance_to_text; var legend_pos = c_oAscChartLegendShowSettings.right; if(AscFormat.isRealNumber(legend.legendPos)) { legend_pos = legend.legendPos; } var legend_width, legend_height; var fFixedWidth = null, fFixedHeight = null; var bFixedSize = false; if(legend.layout){ fFixedWidth = this.calculateSizeByLayout(0, this.extX, legend.layout.w, legend.layout.wMode); fFixedHeight = this.calculateSizeByLayout(0, this.extY, legend.layout.h, legend.layout.hMode); bFixedSize = AscFormat.isRealNumber(fFixedWidth) && fFixedWidth > 0 && AscFormat.isRealNumber(fFixedHeight) && fFixedHeight > 0; if(bFixedSize){ var oOldLayout = legend.layout; legend.layout = null; this.recalculateLegend(); legend.naturalWidth = legend.extX; legend.naturalHeight = legend.extY; legend.layout = oOldLayout; } } if(AscFormat.isRealNumber(legend_pos)) { var max_legend_width, max_legend_height; var cut_index; if ((legend_pos === c_oAscChartLegendShowSettings.left || legend_pos === c_oAscChartLegendShowSettings.leftOverlay || legend_pos === c_oAscChartLegendShowSettings.right || legend_pos === c_oAscChartLegendShowSettings.rightOverlay || legend_pos === c_oAscChartLegendShowSettings.topRight) && !bFixedSize) { max_legend_width = this.extX/3;//Считаем, что ширина легенды не больше трети ширины всей диаграммы; var sizes = this.getChartSizes(); max_legend_height = sizes.h; if(b_line_series) { left_inset = line_marker_width + 3*distance_to_text; var content_width = max_legend_width - left_inset; if(content_width <= 0) content_width = 0.01; var cur_content_width, max_content_width = 0; var arr_heights = []; for(i = 0; i < calc_entryes.length; ++i) { calc_entry = calc_entryes[i]; cur_content_width = calc_entry.txBody.getMaxContentWidth(content_width, true); if(cur_content_width > max_content_width) max_content_width = cur_content_width; arr_heights.push(calc_entry.txBody.getSummaryHeight()); } if(max_content_width < max_legend_width - left_inset) { legend_width = max_content_width + left_inset; } else { legend_width = max_legend_width; } var max_entry_height2 = Math.max(0, Math.max.apply(Math, arr_heights)); for(i = 0; i < arr_heights.length; ++i) arr_heights[i] = max_entry_height2; var height_summ = 0; for(i = 0; i < arr_heights.length; ++i) { height_summ+=arr_heights[i]; if(height_summ > max_legend_height) { cut_index = i; break; } } if(AscFormat.isRealNumber(cut_index)) { if(cut_index > 0) { legend_height = height_summ - arr_heights[cut_index]; } else { legend_height = max_legend_height; } } else { cut_index = arr_heights.length; legend_height = height_summ; } legend.x = 0; legend.y = 0; legend.extX = legend_width; legend.extY = legend_height; var summ_h = 0; calc_entryes.splice(cut_index, calc_entryes.length - cut_index); for(i = 0; i < cut_index && i < calc_entryes.length; ++i) { calc_entry = calc_entryes[i]; if(calc_entry.calcMarkerUnion.marker) { calc_entry.calcMarkerUnion.marker.localX = distance_to_text + line_marker_width/2 - calc_entry.calcMarkerUnion.marker.extX/2; calc_entry.calcMarkerUnion.marker.localY = summ_h + (calc_entry.txBody.content.Content[0].Lines[0].Bottom - calc_entry.txBody.content.Content[0].Lines[0].Top)/2 - marker_size/2; calc_entry.localX = calc_entry.calcMarkerUnion.marker.localX + line_marker_width + distance_to_text; } if(calc_entry.calcMarkerUnion.lineMarker) { calc_entry.calcMarkerUnion.lineMarker.localX = distance_to_text; calc_entry.calcMarkerUnion.lineMarker.localY = summ_h + (calc_entry.txBody.content.Content[0].Lines[0].Bottom - calc_entry.txBody.content.Content[0].Lines[0].Top)/2;// - calc_entry.calcMarkerUnion.lineMarker.penWidth/2; calc_entry.localX = calc_entry.calcMarkerUnion.lineMarker.localX + line_marker_width + distance_to_text; } calc_entry.localY = summ_h; summ_h+=arr_heights[i]; } legend.setPosition(0, 0); } else { var content_width = max_legend_width - left_inset; if(content_width <= 0) content_width = 0.01; var cur_content_width, max_content_width = 0; var arr_heights = []; for(i = 0; i < calc_entryes.length; ++i) { calc_entry = calc_entryes[i]; cur_content_width = calc_entry.txBody.getMaxContentWidth(content_width, true); if(cur_content_width > max_content_width) max_content_width = cur_content_width; arr_heights.push(calc_entry.txBody.getSummaryHeight()); } var chart_object; if(this.chart && this.chart.plotArea && this.chart.plotArea.charts[0]) { chart_object = this.chart.plotArea.charts[0]; } var b_reverse_order = false; if(chart_object && chart_object.getObjectType() === AscDFH.historyitem_type_BarChart && chart_object.barDir === AscFormat.BAR_DIR_BAR && (cat_ax && cat_ax.scaling && AscFormat.isRealNumber(cat_ax.scaling.orientation) ? cat_ax.scaling.orientation : AscFormat.ORIENTATION_MIN_MAX) === AscFormat.ORIENTATION_MIN_MAX || chart_object && chart_object.getObjectType() === AscDFH.historyitem_type_SurfaceChart) { b_reverse_order = true; } var max_entry_height2 = Math.max(0, Math.max.apply(Math, arr_heights)); for(i = 0; i < arr_heights.length; ++i) arr_heights[i] = max_entry_height2; if(max_content_width < max_legend_width - left_inset) { legend_width = max_content_width + left_inset; } else { legend_width = max_legend_width; } var height_summ = 0; for(i = 0; i < arr_heights.length; ++i) { height_summ+=arr_heights[i]; if(height_summ > max_legend_height) { cut_index = i; break; } } if(AscFormat.isRealNumber(cut_index)) { if(cut_index > 0) { legend_height = height_summ - arr_heights[cut_index]; } else { legend_height = max_legend_height; } } else { cut_index = arr_heights.length; legend_height = height_summ; } legend.x = 0; legend.y = 0; legend.extX = legend_width; legend.extY = legend_height; var summ_h = 0; var b_reverse_order = false; var chart_object, cat_ax, start_index, end_index; if(this.chart && this.chart.plotArea && this.chart.plotArea.charts[0]) { chart_object = this.chart.plotArea.charts[0]; if(chart_object && chart_object.getAxisByTypes) { var axis_by_types = chart_object.getAxisByTypes(); cat_ax = axis_by_types.catAx[0]; } } if(chart_object && chart_object.getObjectType() === AscDFH.historyitem_type_BarChart && chart_object.barDir === AscFormat.BAR_DIR_BAR && (cat_ax && cat_ax.scaling && AscFormat.isRealNumber(cat_ax.scaling.orientation) ? cat_ax.scaling.orientation : AscFormat.ORIENTATION_MIN_MAX) === AscFormat.ORIENTATION_MIN_MAX) { b_reverse_order = true; } if(!b_reverse_order) { calc_entryes.splice(cut_index, calc_entryes.length - cut_index); for(i = 0; i < cut_index && i < calc_entryes.length; ++i) { calc_entry = calc_entryes[i]; if(calc_entry.calcMarkerUnion.marker) { calc_entry.calcMarkerUnion.marker.localX = distance_to_text; calc_entry.calcMarkerUnion.marker.localY = summ_h + (calc_entry.txBody.content.Content[0].Lines[0].Bottom - calc_entry.txBody.content.Content[0].Lines[0].Top)/2 - marker_size/2; } calc_entry.localX = 2*distance_to_text + marker_size; calc_entry.localY = summ_h; summ_h+=arr_heights[i]; } } else { calc_entryes.splice(0, calc_entryes.length - cut_index); for(i = calc_entryes.length-1; i > -1; --i) { calc_entry = calc_entryes[i]; if(calc_entry.calcMarkerUnion.marker) { calc_entry.calcMarkerUnion.marker.localX = distance_to_text; calc_entry.calcMarkerUnion.marker.localY = summ_h + (calc_entry.txBody.content.Content[0].Lines[0].Bottom - calc_entry.txBody.content.Content[0].Lines[0].Top)/2 - marker_size/2; } calc_entry.localX = 2*distance_to_text + marker_size; calc_entry.localY = summ_h; summ_h+=arr_heights[i]; } } legend.setPosition(0, 0); } } else { /*пока сделаем так: максимальная ширимна 0.9 от ширины дмаграммы без заголовка максимальная высота легенды 0.6 от высоты диаграммы, с заголовком 0.6 от высоты за вычетом высоты заголовка*/ if(bFixedSize){ max_legend_width = fFixedWidth; max_legend_height = fFixedHeight; } else{ max_legend_width = 0.9*this.extX; max_legend_height = (this.extY - (this.chart.title ? this.chart.title.extY : 0))*0.6; } if(b_line_series) { //сначала найдем максимальную ширину записи. ширина записи получается как отступ слева от маркера + ширина маркера + отступ справа от маркера + ширина текста var max_entry_width = 0, cur_entry_width, cur_entry_height; //найдем максимальную ширину надписи var left_width = line_marker_width + 3*distance_to_text; var arr_width = [], arr_height = []; //массив ширин записей var summ_width = 0;//сумма ширин всех подписей for(i = 0; i < calc_entryes.length; ++i) { calc_entry = calc_entryes[i]; cur_entry_width = calc_entry.txBody.getMaxContentWidth(20000/*ставим большое число чтобы текст расчитался в одну строчку*/, true); if(cur_entry_width > max_entry_width) max_entry_width = cur_entry_width; arr_height.push(calc_entry.txBody.getSummaryHeight()); arr_width.push(cur_entry_width+left_width); summ_width+=arr_width[arr_width.length-1]; } var max_entry_height = Math.max(0, Math.max.apply(Math, arr_height)); var cur_left_x = 0; if(summ_width < max_legend_width)//значит все надписи убираются в одну строчку { if(bFixedSize){ cur_left_x = max_legend_width - summ_width; } /*прибавим справа ещё боковой зазаор и посмотрим уберется ли новая ширина в максимальную ширину*/ if(summ_width + distance_to_text < max_legend_width && !bFixedSize) legend_width = summ_width + distance_to_text; else legend_width = max_legend_width; legend_height = max_entry_height; if(bFixedSize){ legend_height = max_legend_height; } for(i = 0; i < calc_entryes.length; ++i) { calc_entry = calc_entryes[i]; if(calc_entry.calcMarkerUnion.marker) calc_entry.calcMarkerUnion.marker.localX = cur_left_x + distance_to_text + line_marker_width/2 - marker_size/2; calc_entry.calcMarkerUnion.lineMarker.localX = cur_left_x + distance_to_text; calc_entry.calcMarkerUnion.lineMarker.localY = Math.max(0, legend_height/2); cur_left_x += arr_width[i]; if(calc_entry.calcMarkerUnion.marker) calc_entry.calcMarkerUnion.marker.localY = Math.max(0, legend_height/2 - marker_size/2); calc_entry.localX = calc_entry.calcMarkerUnion.lineMarker.localX+line_marker_width+distance_to_text; calc_entry.localY = 0; } legend.extX = legend_width; legend.extY = legend_height; legend.setPosition(0, 0); } else if(max_legend_width >= max_entry_width + left_width) { var hor_count = (max_legend_width/(max_entry_width + left_width)) >> 0;//количество записей в одной строке var vert_count;//количество строк var t = calc_entryes.length / hor_count; if(t - (t >> 0) > 0) vert_count = t+1; else vert_count = t; //посмотрим убираются ли все эти строки в максимальную высоту. те которые не убираются обрежем, кроме первой. legend_width = hor_count*(max_legend_width + left_width); if(legend_width + distance_to_text <= max_legend_width && !bFixedSize) legend_width += distance_to_text; else legend_width = max_legend_width; if(bFixedSize){ max_legend_height = fFixedHeight; } var max_line_count = (max_legend_height/max_entry_height)>>0; //максимальное количество строчек в легенде; if(vert_count <= max_line_count) { cut_index = calc_entryes.length; legend_height = vert_count*max_entry_height; } else { if(max_line_count === 0) { cut_index = hor_count + 1; legend_height = max_entry_height; } else { cut_index = max_line_count*hor_count+1; legend_height = max_entry_height*max_line_count; } } var fStartH = 0; if(bFixedSize){ fStartH = Math.max(0, (fFixedHeight - legend_height)/2); legend_height = fFixedHeight; } legend.extX = legend_width; legend.extY = legend_height; calc_entryes.splice(cut_index, calc_entryes.length - cut_index); for(i = 0; i < cut_index && i < calc_entryes.length; ++i) { calc_entry = calc_entryes[i]; calc_entry.calcMarkerUnion.lineMarker.localX = (i - hor_count*((i/hor_count) >> 0))*(max_entry_width + line_marker_width + 2*distance_to_text) + distance_to_text; calc_entry.calcMarkerUnion.lineMarker.localY = fStartH + ((i/hor_count) >> 0)*(max_entry_height) + max_entry_height/2; if(calc_entry.calcMarkerUnion.marker) { calc_entry.calcMarkerUnion.marker.localX = calc_entry.calcMarkerUnion.lineMarker.localX + line_marker_width/2 - marker_size/2; calc_entry.calcMarkerUnion.marker.localY = calc_entry.calcMarkerUnion.lineMarker.localY - marker_size/2; } calc_entry.localX = calc_entry.calcMarkerUnion.lineMarker.localX + line_marker_width + distance_to_text; calc_entry.localY = fStartH + ((i/hor_count) >> 0)*(max_entry_height); } legend.setPosition(0, 0); } else { //значит максималная по ширине надпись не убирается в рект для легенды var content_width = max_legend_width - 2*distance_to_text - marker_size; if(content_width <= 0) content_width = 0.01; var cur_content_width, max_content_width = 0; var arr_heights = []; for(i = 0; i < calc_entryes.length; ++i) { calc_entry = calc_entryes[i]; cur_content_width = calc_entry.txBody.getMaxContentWidth(content_width, true); if(cur_content_width > max_content_width) max_content_width = cur_content_width; arr_heights.push(calc_entry.txBody.getSummaryHeight()); } if(max_content_width < max_legend_width - left_inset && !bFixedSize) { legend_width = max_content_width + left_inset; } else { legend_width = max_legend_width; } var height_summ = 0; for(i = 0; i < arr_heights.length; ++i) { height_summ+=arr_heights[i]; if(height_summ > max_legend_height) { cut_index = i; break; } } if(AscFormat.isRealNumber(cut_index)) { if(cut_index > 0) { legend_height = height_summ - arr_heights[cut_index]; } else { legend_height = max_legend_height; } } else { cut_index = arr_heights.length; legend_height = height_summ; } if(bFixedSize){ legend_height = max_legend_height; } legend.x = 0; legend.y = 0; legend.extX = legend_width; legend.extY = legend_height; var summ_h = 0; if(bFixedSize){ summ_h = (legend_height - height_summ)/2; } calc_entryes.splice(cut_index, calc_entryes.length - cut_index); for(i = 0; i < cut_index && i < calc_entryes.length; ++i) { calc_entry = calc_entryes[i]; calc_entry.calcMarkerUnion.lineMarker.localX = distance_to_text; calc_entry.calcMarkerUnion.lineMarker.localY = summ_h + (calc_entry.txBody.content.Content[0].Lines[0].Bottom - calc_entry.txBody.content.Content[0].Lines[0].Top)/2;// - calc_entry.calcMarkerUnion.lineMarker.penWidth/2; calc_entry.localX = calc_entry.calcMarkerUnion.lineMarker.localX + line_marker_width + distance_to_text; calc_entry.localY = summ_h; if(calc_entry.calcMarkerUnion.marker) { calc_entry.calcMarkerUnion.marker.localX = calc_entry.calcMarkerUnion.lineMarker.localX + line_marker_width/2 - marker_size/2; calc_entry.calcMarkerUnion.marker.localY = calc_entry.calcMarkerUnion.lineMarker.localY - marker_size/2; } //calc_entry.localX = 2*distance_to_text + marker_size; //calc_entry.localY = summ_h; summ_h+=arr_heights[i]; } legend.setPosition(0, 0); } } else { //сначала найдем максимальную ширину записи. ширина записи получается как отступ слева от маркера + ширина маркера + отступ справа от маркера + ширина текста var max_entry_width = 0, cur_entry_width, cur_entry_height; //найдем максимальную ширину надписи var left_width = marker_size + 2*distance_to_text; var arr_width = [], arr_height = []; //массив ширин записей var summ_width = 0;//сумма ширин всех подписей for(i = 0; i < calc_entryes.length; ++i) { calc_entry = calc_entryes[i]; cur_entry_width = calc_entry.txBody.getMaxContentWidth(20000/*ставим большое число чтобы текст расчитался в одну строчку*/, true); if(cur_entry_width > max_entry_width) max_entry_width = cur_entry_width; arr_height.push(calc_entry.txBody.getSummaryHeight()); arr_width.push(cur_entry_width+left_width); summ_width += arr_width[arr_width.length-1]; } var max_entry_height = Math.max(0, Math.max.apply(Math, arr_height)); var cur_left_x = 0; if(summ_width < max_legend_width)//значит все надписи убираются в одну строчку { /*прибавим справа ещё боковой зазаор и посмотрим уберется ли новая ширина в максимальную ширину*/ if(summ_width + distance_to_text < max_legend_width && !bFixedSize) legend_width = summ_width + distance_to_text; else legend_width = max_legend_width; legend_height = max_entry_height; if(bFixedSize){ cur_left_x = (max_legend_width - summ_width)/2; legend_height = max_legend_height; } for(i = 0; i < calc_entryes.length; ++i) { calc_entry = calc_entryes[i]; calc_entry.calcMarkerUnion.marker.localX = cur_left_x + distance_to_text; cur_left_x += arr_width[i]; calc_entry.calcMarkerUnion.marker.localY = legend_height/2 - marker_size/2; calc_entry.localX = calc_entry.calcMarkerUnion.marker.localX+marker_size+distance_to_text; calc_entry.localY = calc_entry.calcMarkerUnion.marker.localY - marker_size/2; } legend.extX = legend_width; legend.extY = legend_height; legend.setPosition(0, 0); } else if(max_legend_width >= max_entry_width + left_width) { var hor_count = (max_legend_width/(max_entry_width + left_width)) >> 0;//количество записей в одной строке var vert_count;//количество строк var t = calc_entryes.length / hor_count; if(t - (t >> 0) > 0) vert_count = (t+1) >> 0; else vert_count = t >> 0; //посмотрим убираются ли все эти строки в максимальную высоту. те которые не убираются обрежем, кроме первой. var fStartHorPos = 0; legend_width = hor_count*(max_entry_width + left_width); if(legend_width + distance_to_text <= max_legend_width && !bFixedSize) legend_width += distance_to_text; else{ if(bFixedSize){ fStartHorPos = (max_legend_width - legend_width)/2; } legend_width = max_legend_width; } var max_line_count = (max_legend_height/max_entry_height)>>0; //максимальное количество строчек в легенде; if(vert_count <= max_line_count) { cut_index = calc_entryes.length; legend_height = vert_count*max_entry_height; } else { if(max_line_count === 0) { cut_index = hor_count + 1; legend_height = max_entry_height; } else { cut_index = max_line_count*hor_count+1; legend_height = max_entry_height*max_line_count; } } var fStartH = 0; var fDistance = 0; if(bFixedSize){ fDistance = Math.max(0,(max_legend_height - max_entry_height*vert_count)/vert_count); fStartH = Math.max(0, fDistance/2); legend_height = max_legend_height; } legend.extX = legend_width; legend.extY = legend_height; calc_entryes.splice(cut_index, calc_entryes.length - cut_index); for(i = 0; i <cut_index && i < calc_entryes.length; ++i) { calc_entry = calc_entryes[i]; calc_entry.calcMarkerUnion.marker.localX = fStartHorPos + (i - hor_count*((i/hor_count) >> 0))*(max_entry_width + marker_size + 2*distance_to_text) + distance_to_text; var nHorCount = (i/hor_count) >> 0; calc_entry.calcMarkerUnion.marker.localY = fStartH + (nHorCount)*(max_entry_height) + max_entry_height/2 - marker_size/2 + nHorCount*fDistance; calc_entry.localX = calc_entry.calcMarkerUnion.marker.localX + marker_size + distance_to_text; calc_entry.localY = fStartH + nHorCount*(max_entry_height) + nHorCount*fDistance; } legend.setPosition(0, 0); } else { //значит максималная по ширине надпись не убирается в рект для легенды var content_width = max_legend_width - 2*distance_to_text - marker_size; if(content_width <= 0) content_width = 0.01; var cur_content_width, max_content_width = 0; var arr_heights = []; for(i = 0; i < calc_entryes.length; ++i) { calc_entry = calc_entryes[i]; cur_content_width = calc_entry.txBody.getMaxContentWidth(content_width, true); if(cur_content_width > max_content_width) max_content_width = cur_content_width; arr_heights.push(calc_entry.txBody.getSummaryHeight()); } max_entry_height = Math.max(0, Math.max.apply(Math, arr_heights)); if(max_content_width < max_legend_width - left_inset && !bFixedSize) { legend_width = max_content_width + left_inset; } else { legend_width = max_legend_width; } var height_summ = 0; for(i = 0; i < arr_heights.length; ++i) { height_summ+=arr_heights[i]; if(height_summ > max_legend_height) { cut_index = i; break; } } if(AscFormat.isRealNumber(cut_index)) { if(cut_index > 0) { legend_height = height_summ - arr_heights[cut_index]; } else { legend_height = max_legend_height; } } else { cut_index = arr_heights.length; legend_height = height_summ; } var fStartH = 0; var fDistance = 0; if(bFixedSize){ fDistance = Math.max(0,(max_legend_height - max_entry_height*cut_index)/cut_index); fStartH = Math.max(0, fDistance/2); legend_height = max_legend_height; } legend.x = 0; legend.y = 0; legend.extX = legend_width; legend.extY = legend_height; calc_entryes.splice(cut_index, calc_entryes.length - cut_index); for(i = 0; i < cut_index && i < calc_entryes.length; ++i) { calc_entry = calc_entryes[i]; calc_entry.localX = 2*distance_to_text + marker_size; calc_entry.localY = fStartH + i*max_entry_height + i*fDistance; calc_entry.calcMarkerUnion.marker.localX = distance_to_text; calc_entry.calcMarkerUnion.marker.localY = calc_entry.localY + (calc_entry.txBody.content.Content[0].Lines[0].Bottom - calc_entry.txBody.content.Content[0].Lines[0].Top)/2 - marker_size/2; } legend.setPosition(0, 0); } } } } else { //TODO } legend.recalcInfo = {recalculateLine: true, recalculateFill: true, recalculateTransparent: true}; legend.recalculatePen(); legend.recalculateBrush(); for(var i = 0; i < calc_entryes.length; ++i) { calc_entryes[i].checkWidhtContent(); } } }; CChartSpace.prototype.internalCalculatePenBrushFloorWall = function(oSide, nSideType) { if(!oSide) { return; } var parent_objects = this.getParentObjects(); if(oSide.spPr && oSide.spPr.ln) { oSide.pen = oSide.spPr.ln.createDuplicate(); } else { var oCompiledPen = null; if(this.style >= 1 && this.style <= 40 && 2 === nSideType) { if(parent_objects.theme && parent_objects.theme.themeElements && parent_objects.theme.themeElements.fmtScheme && parent_objects.theme.themeElements.fmtScheme.lnStyleLst && parent_objects.theme.themeElements.fmtScheme.lnStyleLst[0]) { oCompiledPen = parent_objects.theme.themeElements.fmtScheme.lnStyleLst[0].createDuplicate(); if(this.style >= 1 && this.style <= 32) { oCompiledPen.Fill = CreateUnifillSolidFillSchemeColor(15, 0.75); } else { oCompiledPen.Fill = CreateUnifillSolidFillSchemeColor(8, 0.75); } } } oSide.pen = oCompiledPen; } if(this.style >= 1 && this.style <= 32) { if(oSide.spPr && oSide.spPr.Fill) { oSide.brush = oSide.spPr.Fill.createDuplicate(); if(nSideType === 0 || nSideType === 2) { var cColorMod = new AscFormat.CColorMod; if(nSideType === 2) cColorMod.val = 45000; else cColorMod.val = 35000; cColorMod.name = "shade"; oSide.brush.addColorMod(cColorMod); } } else { oSide.brush = null; } } else { var oSubtleFill; if(parent_objects.theme && parent_objects.theme.themeElements && parent_objects.theme.themeElements.fmtScheme && parent_objects.theme.themeElements.fmtScheme.fillStyleLst) { oSubtleFill = parent_objects.theme.themeElements.fmtScheme.fillStyleLst[0]; } var oDefaultBrush; var tint = 0.20000; if(this.style >=33 && this.style <= 34) oDefaultBrush = CreateUnifillSolidFillSchemeColor(8, 0.20000); else if(this.style >=35 && this.style <=40) oDefaultBrush = CreateUnifillSolidFillSchemeColor(this.style - 35, tint); else oDefaultBrush = CreateUnifillSolidFillSchemeColor(8, 0.95000); if(oSide.spPr) { oDefaultBrush.merge(oSide.spPr.Fill); } if(nSideType === 0 || nSideType === 2) { var cColorMod = new AscFormat.CColorMod; if(nSideType === 0) cColorMod.val = 45000; else cColorMod.val = 35000; cColorMod.name = "shade"; oDefaultBrush.addColorMod(cColorMod); } oSide.brush = oDefaultBrush; } if(oSide.brush) { oSide.brush.calculate(parent_objects.theme, parent_objects.slide, parent_objects.layout, parent_objects.master, {R: 0, G: 0, B: 0, A: 255}, this.clrMapOvr); } if(oSide.pen) { oSide.pen.calculate(parent_objects.theme, parent_objects.slide, parent_objects.layout, parent_objects.master, {R: 0, G: 0, B: 0, A: 255}, this.clrMapOvr); } }; CChartSpace.prototype.recalculateWalls = function() { if(this.chart) { this.internalCalculatePenBrushFloorWall(this.chart.sideWall, 0); this.internalCalculatePenBrushFloorWall(this.chart.backWall, 1); this.internalCalculatePenBrushFloorWall(this.chart.floor, 2); } }; CChartSpace.prototype.recalculateUpDownBars = function() { if(this.chart && this.chart.plotArea) { var aCharts = this.chart.plotArea.charts; for(var t = 0; t < aCharts.length; ++t){ var oChart = aCharts[t]; if(oChart && oChart.upDownBars){ var bars = oChart.upDownBars; var up_bars = bars.upBars; var down_bars = bars.downBars; var parents = this.getParentObjects(); bars.upBarsBrush = null; bars.upBarsPen = null; bars.downBarsBrush = null; bars.downBarsPen = null; if(up_bars || down_bars) { var default_bar_line = new AscFormat.CLn(); if(parents.theme && parents.theme.themeElements && parents.theme.themeElements.fmtScheme && parents.theme.themeElements.fmtScheme.lnStyleLst) { default_bar_line.merge(parents.theme.themeElements.fmtScheme.lnStyleLst[0]); } if(this.style >= 1 && this.style <= 16) default_bar_line.setFill(CreateUnifillSolidFillSchemeColor(15, 0)); else if(this.style >= 17 && this.style <= 32 || this.style >= 41 && this.style <= 48) default_bar_line = CreateNoFillLine(); else if(this.style === 33 || this.style === 34) default_bar_line.setFill(CreateUnifillSolidFillSchemeColor(8, 0)); else if(this.style >= 35 && this.style <= 40) default_bar_line.setFill(CreateUnifillSolidFillSchemeColor(this.style - 35, -0.25000)); } if(up_bars) { var default_up_bars_fill; if(this.style === 1 || this.style === 9 || this.style === 17 || this.style === 25 || this.style === 41) { default_up_bars_fill = CreateUnifillSolidFillSchemeColor(8, 0.25000); } else if(this.style === 2 || this.style === 10 || this.style === 18 || this.style === 26) { default_up_bars_fill = CreateUnifillSolidFillSchemeColor(8, 0.05000); } else if(this.style >= 3 && this.style <= 8) { default_up_bars_fill = CreateUnifillSolidFillSchemeColor(this.style - 3, 0.25000); } else if(this.style >= 11 && this.style <= 16) { default_up_bars_fill = CreateUnifillSolidFillSchemeColor(this.style - 11, 0.25000); } else if(this.style >=19 && this.style <= 24) { default_up_bars_fill = CreateUnifillSolidFillSchemeColor(this.style - 19, 0.25000); } else if(this.style >= 27 && this.style <= 32 ) { default_up_bars_fill = CreateUnifillSolidFillSchemeColor(this.style - 27, 0.25000); } else if(this.style >= 33 && this.style <= 40 || this.style === 42) { default_up_bars_fill = CreateUnifillSolidFillSchemeColor(12, 0); } else { default_up_bars_fill = CreateUnifillSolidFillSchemeColor(this.style - 43, 0.25000); } if(up_bars.Fill) { default_up_bars_fill.merge(up_bars.Fill); } default_up_bars_fill.calculate(parents.theme, parents.slide, parents.layout, parents.master, {R: 0, G: 0, B: 0, A: 255}, this.clrMapOvr); oChart.upDownBars.upBarsBrush = default_up_bars_fill; var up_bars_line = default_bar_line.createDuplicate(); if(up_bars.ln) up_bars_line.merge(up_bars.ln); up_bars_line.calculate(parents.theme, parents.slide, parents.layout, parents.master, {R: 0, G: 0, B: 0, A: 255}, this.clrMapOvr); oChart.upDownBars.upBarsPen = up_bars_line; } if(down_bars) { var default_down_bars_fill; if(this.style === 1 || this.style === 9 || this.style === 17 || this.style === 25 || this.style === 41 || this.style === 33) { default_down_bars_fill = CreateUnifillSolidFillSchemeColor(8, 0.85000); } else if(this.style === 2 || this.style === 10 || this.style === 18 || this.style === 26 || this.style === 34) { default_down_bars_fill = CreateUnifillSolidFillSchemeColor(8, 0.95000); } else if(this.style >= 3 && this.style <= 8) { default_down_bars_fill = CreateUnifillSolidFillSchemeColor(this.style - 3, -0.25000); } else if(this.style >= 11 && this.style <= 16) { default_down_bars_fill = CreateUnifillSolidFillSchemeColor(this.style - 11, -0.25000); } else if(this.style >=19 && this.style <= 24) { default_down_bars_fill = CreateUnifillSolidFillSchemeColor(this.style - 19, -0.25000); } else if(this.style >= 27 && this.style <= 32 ) { default_down_bars_fill = CreateUnifillSolidFillSchemeColor(this.style - 27, -0.25000); } else if(this.style >= 35 && this.style <= 40) { default_down_bars_fill = CreateUnifillSolidFillSchemeColor(this.style - 35, -0.25000); } else if(this.style === 42) { default_down_bars_fill = CreateUnifillSolidFillSchemeColor(8, 0); } else { default_down_bars_fill = CreateUnifillSolidFillSchemeColor(this.style - 43, -0.25000); } if(down_bars.Fill) { default_down_bars_fill.merge(down_bars.Fill); } default_down_bars_fill.calculate(parents.theme, parents.slide, parents.layout, parents.master, {R: 0, G: 0, B: 0, A: 255}, this.clrMapOvr); oChart.upDownBars.downBarsBrush = default_down_bars_fill; var down_bars_line = default_bar_line.createDuplicate(); if(down_bars.ln) down_bars_line.merge(down_bars.ln); down_bars_line.calculate(parents.theme, parents.slide, parents.layout, parents.master, {R: 0, G: 0, B: 0, A: 255}, this.clrMapOvr); oChart.upDownBars.downBarsPen = down_bars_line; } } } } }; CChartSpace.prototype.recalculatePlotAreaChartPen = function() { if(this.chart && this.chart.plotArea) { if(this.chart.plotArea.spPr && this.chart.plotArea.spPr.ln) { this.chart.plotArea.pen = this.chart.plotArea.spPr.ln; var parents = this.getParentObjects(); this.chart.plotArea.pen.calculate(parents.theme, parents.slide, parents.layout, parents.master, {R: 0, G: 0, B: 0, A: 255}, this.clrMapOvr); } else { this.chart.plotArea.pen = null; } } }; CChartSpace.prototype.recalculatePenBrush = function() { var parents = this.getParentObjects(), RGBA = {R: 0, G: 0, B: 0, A: 255}; if(this.brush) { this.brush.calculate(parents.theme, parents.slide, parents.layout, parents.master, RGBA, this.clrMapOvr); } if(this.pen) { this.pen.calculate(parents.theme, parents.slide, parents.layout, parents.master, RGBA, this.clrMapOvr); checkBlackUnifill(this.pen.Fill, true); } if(this.chart) { if(this.chart.title) { if(this.chart.title.brush) { this.chart.title.brush.calculate(parents.theme, parents.slide, parents.layout, parents.master, RGBA, this.clrMapOvr); } if(this.chart.title.pen) { this.chart.title.pen.calculate(parents.theme, parents.slide, parents.layout, parents.master, RGBA, this.clrMapOvr); } } if(this.chart.plotArea) { if(this.chart.plotArea.brush) { this.chart.plotArea.brush.calculate(parents.theme, parents.slide, parents.layout, parents.master, RGBA, this.clrMapOvr); } if(this.chart.plotArea.pen) { this.chart.plotArea.pen.calculate(parents.theme, parents.slide, parents.layout, parents.master, RGBA, this.clrMapOvr); } if(this.chart.plotArea.valAx) { if(this.chart.plotArea.valAx.compiledTickMarkLn) { this.chart.plotArea.valAx.compiledTickMarkLn.calculate(parents.theme, parents.slide, parents.layout, parents.master, RGBA, this.clrMapOvr); checkBlackUnifill(this.chart.plotArea.valAx.compiledTickMarkLn.Fill, true); } if(this.chart.plotArea.valAx.compiledMajorGridLines) { this.chart.plotArea.valAx.compiledMajorGridLines.calculate(parents.theme, parents.slide, parents.layout, parents.master, RGBA, this.clrMapOvr); checkBlackUnifill(this.chart.plotArea.valAx.compiledMajorGridLines.Fill, true); } if(this.chart.plotArea.valAx.compiledMinorGridLines) { this.chart.plotArea.valAx.compiledMinorGridLines.calculate(parents.theme, parents.slide, parents.layout, parents.master, RGBA, this.clrMapOvr); checkBlackUnifill(this.chart.plotArea.valAx.compiledMinorGridLines.Fill, true); } if(this.chart.plotArea.valAx.title) { if(this.chart.plotArea.valAx.title.brush) { this.chart.plotArea.valAx.title.brush.calculate(parents.theme, parents.slide, parents.layout, parents.master, RGBA, this.clrMapOvr); } if(this.chart.plotArea.valAx.title.pen) { this.chart.plotArea.valAx.title.pen.calculate(parents.theme, parents.slide, parents.layout, parents.master, RGBA, this.clrMapOvr); } } } if(this.chart.plotArea.catAx) { if(this.chart.plotArea.catAx.compiledTickMarkLn) { this.chart.plotArea.catAx.compiledTickMarkLn.calculate(parents.theme, parents.slide, parents.layout, parents.master, RGBA, this.clrMapOvr); checkBlackUnifill(this.chart.plotArea.catAx.compiledTickMarkLn.Fill, true); } if(this.chart.plotArea.catAx.compiledMajorGridLines) { this.chart.plotArea.catAx.compiledMajorGridLines.calculate(parents.theme, parents.slide, parents.layout, parents.master, RGBA, this.clrMapOvr); checkBlackUnifill(this.chart.plotArea.catAx.compiledMajorGridLines.Fill, true); } if(this.chart.plotArea.catAx.compiledMinorGridLines) { this.chart.plotArea.catAx.compiledMinorGridLines.calculate(parents.theme, parents.slide, parents.layout, parents.master, RGBA, this.clrMapOvr); checkBlackUnifill(this.chart.plotArea.catAx.compiledMinorGridLines.Fill, true); } if(this.chart.plotArea.catAx.title) { if(this.chart.plotArea.catAx.title.brush) { this.chart.plotArea.catAx.title.brush.calculate(parents.theme, parents.slide, parents.layout, parents.master, RGBA, this.clrMapOvr); } if(this.chart.plotArea.catAx.title.pen) { this.chart.plotArea.catAx.title.pen.calculate(parents.theme, parents.slide, parents.layout, parents.master, RGBA, this.clrMapOvr); } } } if(this.chart.plotArea.charts[0]) { var series = this.chart.plotArea.charts[0].series; for(var i = 0; i < series.length; ++i) { var pts = AscFormat.getPtsFromSeries(series[i]); for(var j = 0; j < pts.length; ++j) { var pt = pts[j]; if(pt.brush) { pt.brush.calculate(parents.theme, parents.slide, parents.layout, parents.master, RGBA, this.clrMapOvr); } if(pt.pen) { pt.pen.calculate(parents.theme, parents.slide, parents.layout, parents.master, RGBA, this.clrMapOvr); } if(pt.compiledMarker) { if(pt.compiledMarker.brush) { pt.compiledMarker.brush.calculate(parents.theme, parents.slide, parents.layout, parents.master, RGBA, this.clrMapOvr); } if(pt.compiledMarker.pen) { pt.compiledMarker.pen.calculate(parents.theme, parents.slide, parents.layout, parents.master, RGBA, this.clrMapOvr); } } if(pt.compiledDlb) { if(pt.compiledDlb.brush) { pt.compiledDlb.brush.calculate(parents.theme, parents.slide, parents.layout, parents.master, RGBA, this.clrMapOvr); } if(pt.compiledDlb.pen) { pt.compiledDlb.pen.calculate(parents.theme, parents.slide, parents.layout, parents.master, RGBA, this.clrMapOvr); } } } } if(this.chart.plotArea.charts[0].calculatedHiLowLines) { this.chart.plotArea.charts[0].calculatedHiLowLines.calculate(parents.theme, parents.slide, parents.layout, parents.master, RGBA, this.clrMapOvr); } if( this.chart.plotArea.charts[0].upDownBars) { if(this.chart.plotArea.charts[0].upDownBars.upBarsBrush) { this.chart.plotArea.charts[0].upDownBars.upBarsBrush.calculate(parents.theme, parents.slide, parents.layout, parents.master, RGBA, this.clrMapOvr); } if(this.chart.plotArea.charts[0].upDownBars.upBarsPen) { this.chart.plotArea.charts[0].upDownBars.upBarsPen.calculate(parents.theme, parents.slide, parents.layout, parents.master, RGBA, this.clrMapOvr); } if(this.chart.plotArea.charts[0].upDownBars.downBarsBrush) { this.chart.plotArea.charts[0].upDownBars.downBarsBrush.calculate(parents.theme, parents.slide, parents.layout, parents.master, RGBA, this.clrMapOvr); } if(this.chart.plotArea.charts[0].upDownBars.downBarsPen) { this.chart.plotArea.charts[0].upDownBars.downBarsPen.calculate(parents.theme, parents.slide, parents.layout, parents.master, RGBA, this.clrMapOvr); } } } } if(this.chart.legend) { if(this.chart.legend.brush) { this.chart.legend.brush.calculate(parents.theme, parents.slide, parents.layout, parents.master, RGBA, this.clrMapOvr); } if(this.chart.legend.pen) { this.chart.legend.pen.calculate(parents.theme, parents.slide, parents.layout, parents.master, RGBA, this.clrMapOvr); } var legend = this.chart.legend; for(var i = 0; i < legend.calcEntryes.length; ++i) { var union_marker = legend.calcEntryes[i].calcMarkerUnion; if(union_marker) { if(union_marker.marker) { if(union_marker.marker.pen) { union_marker.marker.pen.calculate(parents.theme, parents.slide, parents.layout, parents.master, RGBA, this.clrMapOvr); } if(union_marker.marker.brush) { union_marker.marker.brush.calculate(parents.theme, parents.slide, parents.layout, parents.master, RGBA, this.clrMapOvr); } } if(union_marker.lineMarker) { if(union_marker.lineMarker.pen) { union_marker.lineMarker.pen.calculate(parents.theme, parents.slide, parents.layout, parents.master, RGBA, this.clrMapOvr); } if(union_marker.lineMarker.brush) { union_marker.lineMarker.brush.calculate(parents.theme, parents.slide, parents.layout, parents.master, RGBA, this.clrMapOvr); } } } } } if(this.chart.floor) { if(this.chart.floor.brush) { this.chart.floor.brush.calculate(parents.theme, parents.slide, parents.layout, parents.master, RGBA, this.clrMapOvr); } if(this.chart.floor.pen) { this.chart.floor.pen.calculate(parents.theme, parents.slide, parents.layout, parents.master, RGBA, this.clrMapOvr); } } if(this.chart.sideWall) { if(this.chart.sideWall.brush) { this.chart.sideWall.brush.calculate(parents.theme, parents.slide, parents.layout, parents.master, RGBA, this.clrMapOvr); } if(this.chart.sideWall.pen) { this.chart.sideWall.pen.calculate(parents.theme, parents.slide, parents.layout, parents.master, RGBA, this.clrMapOvr); } } if(this.chart.backWall) { if(this.chart.backWall.brush) { this.chart.backWall.brush.calculate(parents.theme, parents.slide, parents.layout, parents.master, RGBA, this.clrMapOvr); } if(this.chart.backWall.pen) { this.chart.backWall.pen.calculate(parents.theme, parents.slide, parents.layout, parents.master, RGBA, this.clrMapOvr); } } } }; function fSaveChartObjectSourceFormatting(oObject, oObjectCopy, oTheme, oColorMap){ if(oObject === oObjectCopy || !oObjectCopy || !oObject){ return; } if(oObject.pen || oObject.brush){ if(oObject.pen || oObject.brush){ if(!oObjectCopy.spPr){ if(oObjectCopy.setSpPr){ oObjectCopy.setSpPr(new AscFormat.CSpPr()); oObjectCopy.spPr.setParent(oObjectCopy); } } if(oObject.brush){ oObjectCopy.spPr.setFill(oObject.brush.saveSourceFormatting()); } if(oObject.pen){ oObjectCopy.spPr.setLn(oObject.pen.createDuplicate(true)); } } } if(oObject.txPr && oObject.txPr.content){ AscFormat.SaveContentSourceFormatting(oObject.txPr.content.Content, oObjectCopy.txPr.content.Content, oTheme, oColorMap); } if(oObject.tx && oObject.tx.rich && oObject.tx.rich.content){ AscFormat.SaveContentSourceFormatting(oObject.tx.rich.content.Content, oObjectCopy.tx.rich.content.Content, oTheme, oColorMap); } } CChartSpace.prototype.getCopyWithSourceFormatting = function(oIdMap) { var oCopy = this.copy(this.getDrawingDocument()); oCopy.updateLinks(); if(oIdMap){ oIdMap[this.Id] = oCopy.Id; } var oTheme = this.Get_Theme(); var oColorMap = this.Get_ColorMap(); fSaveChartObjectSourceFormatting(this, oCopy, oTheme, oColorMap); if(!oCopy.txPr || !oCopy.txPr.content || !oCopy.txPr.content.Content[0] || !oCopy.txPr.content.Content[0].Pr){ oCopy.setTxPr(AscFormat.CreateTextBodyFromString("", this.getDrawingDocument(), oCopy)); } var bMerge = false; var oTextPr = new CTextPr(); if(!oCopy.txPr.content.Content[0].Pr.DefaultRunPr || !oCopy.txPr.content.Content[0].Pr.DefaultRunPr.RFonts || !oCopy.txPr.content.Content[0].Pr.DefaultRunPr.RFonts.Ascii || !oCopy.txPr.content.Content[0].Pr.DefaultRunPr.RFonts.Ascii.Name){ bMerge = true; oTextPr.RFonts.Set_FromObject( { Ascii: { Name: "+mn-lt", Index: -1 }, EastAsia: { Name: "+mn-ea", Index: -1 }, HAnsi: { Name: "+mn-lt", Index: -1 }, CS: { Name: "+mn-lt", Index: -1 } } ); } if(this.txPr.content.Content[0].Pr.DefaultRunPr && this.txPr.content.Content[0].Pr.DefaultRunPr.Unifill){ bMerge = true; var oUnifill = this.txPr.content.Content[0].Pr.DefaultRunPr.Unifill.createDuplicate(); oUnifill.check(this.Get_Theme(), this.Get_ColorMap()); oTextPr.Unifill = oUnifill.saveSourceFormatting(); } else if(!AscFormat.isRealNumber(this.style) || this.style < 33){ bMerge = true; var oUnifill = CreateUnifillSolidFillSchemeColor(15, 0.0); oUnifill.check(this.Get_Theme(), this.Get_ColorMap()); oTextPr.Unifill = oUnifill.saveSourceFormatting(); } else{ bMerge = true; var oUnifill = CreateUnifillSolidFillSchemeColor(6, 0.0); oUnifill.check(this.Get_Theme(), this.Get_ColorMap()); oTextPr.Unifill = oUnifill.saveSourceFormatting(); } if(bMerge){ var oParaPr = oCopy.txPr.content.Content[0].Pr.Copy(); var oParaPr2 = new CParaPr(); var oCopyTextPr = oTextPr.Copy(); oParaPr2.DefaultRunPr = oCopyTextPr; oParaPr.Merge(oParaPr2); oCopy.txPr.content.Content[0].Set_Pr(oParaPr); //CheckObjectTextPr(oCopy, oTextPr, this.getDrawingDocument()); // fSaveChartObjectSourceFormatting(oCopy, oCopy, oTheme, oColorMap); } if(this.chart) { if(this.chart.title) { fSaveChartObjectSourceFormatting(this.chart.title, oCopy.chart.title, oTheme, oColorMap); } if(this.chart.plotArea) { fSaveChartObjectSourceFormatting(this.chart.plotArea, oCopy.chart.plotArea, oTheme, oColorMap); if(oCopy.chart.plotArea.valAx) { fSaveChartObjectSourceFormatting(this.chart.plotArea.valAx, oCopy.chart.plotArea.valAx, oTheme, oColorMap); if(this.chart.plotArea.valAx.compiledLn) { if(!oCopy.chart.plotArea.valAx.spPr){ oCopy.chart.plotArea.valAx.setSpPr(new AscFormat.CSpPr()); } oCopy.chart.plotArea.valAx.spPr.setLn(this.chart.plotArea.valAx.compiledLn.createDuplicate(true)); } if(this.chart.plotArea.valAx.compiledMajorGridLines) { if(!oCopy.chart.plotArea.valAx.majorGridlines){ oCopyi.chart.plotArea.valAx.setMajorGridlines(new AscFormat.CSpPr()); } oCopy.chart.plotArea.valAx.majorGridlines.setLn(this.chart.plotArea.valAx.compiledMajorGridLines.createDuplicate(true)); } if(this.chart.plotArea.valAx.compiledMinorGridLines) { if(!oCopy.chart.plotArea.valAx.minorGridlines){ oCopy.chart.plotArea.valAx.setMinorGridlines(new AscFormat.CSpPr()); } oCopy.chart.plotArea.valAx.minorGridlines.setLn(this.chart.plotArea.valAx.compiledMinorGridLines.createDuplicate(true)); } if(oCopy.chart.plotArea.valAx.title) { fSaveChartObjectSourceFormatting(this.chart.plotArea.valAx.title, oCopy.chart.plotArea.valAx.title, oTheme, oColorMap); } } if(oCopy.chart.plotArea.catAx) { fSaveChartObjectSourceFormatting(this.chart.plotArea.catAx, oCopy.chart.plotArea.catAx, oTheme, oColorMap); if(this.chart.plotArea.catAx.compiledLn) { if(!oCopy.chart.plotArea.catAx.spPr){ oCopy.chart.plotArea.catAx.setSpPr(new AscFormat.CSpPr()); } oCopy.chart.plotArea.catAx.spPr.setLn(this.chart.plotArea.catAx.compiledLn.createDuplicate(true)); } if(this.chart.plotArea.catAx.compiledMajorGridLines) { if(!oCopy.chart.plotArea.catAx.majorGridlines){ oCopy.chart.plotArea.catAx.setMajorGridlines(new AscFormat.CSpPr()); } oCopy.chart.plotArea.catAx.majorGridlines.setLn(this.chart.plotArea.catAx.compiledMajorGridLines.createDuplicate(true)); } if(this.chart.plotArea.catAx.compiledMinorGridLines) { if(!oCopy.chart.plotArea.catAx.minorGridlines){ oCopy.chart.plotArea.catAx.setMinorGridlines(new AscFormat.CSpPr()); } oCopy.chart.plotArea.catAx.minorGridlines.setLn(this.chart.plotArea.catAx.compiledMinorGridLines.createDuplicate(true)); } if(oCopy.chart.plotArea.catAx.title) { fSaveChartObjectSourceFormatting(this.chart.plotArea.catAx.title, oCopy.chart.plotArea.catAx.title, oTheme, oColorMap); } } if(this.chart.plotArea.charts[0]) { var series = this.chart.plotArea.charts[0].series; var seriesCopy = oCopy.chart.plotArea.charts[0].series; var oDataPoint; for(var i = 0; i < series.length; ++i) { series[i].brush = series[i].compiledSeriesBrush; series[i].pen = series[i].compiledSeriesPen; fSaveChartObjectSourceFormatting(series[i], seriesCopy[i], oTheme, oColorMap); var pts = AscFormat.getPtsFromSeries(series[i]); var ptsCopy = AscFormat.getPtsFromSeries(seriesCopy[i]); for(var j = 0; j < pts.length; ++j) { var pt = pts[j]; oDataPoint = null; if(Array.isArray(seriesCopy[i].dPt)) { for(var k = 0; k < seriesCopy[i].dPt.length; ++k) { if(seriesCopy[i].dPt[k].idx === pts[j].idx) { oDataPoint = seriesCopy[i].dPt[k]; break; } } } if(!oDataPoint) { oDataPoint = new AscFormat.CDPt(); oDataPoint.setIdx(pt.idx); seriesCopy[i].addDPt(oDataPoint); } fSaveChartObjectSourceFormatting(pt, oDataPoint, oTheme, oColorMap); if(pt.compiledMarker) { var oMarker = pt.compiledMarker.createDuplicate(); oDataPoint.setMarker(oMarker); fSaveChartObjectSourceFormatting(pt.compiledMarker, oMarker, oTheme, oColorMap); } } } if(oCopy.chart.plotArea.charts[0].calculatedHiLowLines) { if(!oCopy.chart.plotArea.charts[0].hiLowLines) { oCopy.chart.plotArea.charts[0].setHiLowLines(new AscFormat.CSpPr()); } oCopy.chart.plotArea.charts[0].hiLowLines.setLn(this.chart.plotArea.charts[0].calculatedHiLowLines.createDuplicate(true)); } if( oCopy.chart.plotArea.charts[0].upDownBars) { if(oCopy.chart.plotArea.charts[0].upDownBars.upBarsBrush) { if(!oCopy.chart.plotArea.charts[0].upDownBars.upBars) { oCopy.chart.plotArea.charts[0].upDownBars.setUpBars(new AscFormat.CSpPr()); } oCopy.chart.plotArea.charts[0].upDownBars.upBars.setFill(this.chart.plotArea.charts[0].upDownBars.upBarsBrush.saveSourceFormatting()); } if(oCopy.chart.plotArea.charts[0].upDownBars.upBarsPen) { if(!oCopy.chart.plotArea.charts[0].upDownBars.upBars) { oCopy.chart.plotArea.charts[0].upDownBars.setUpBars(new AscFormat.CSpPr()); } oCopy.chart.plotArea.charts[0].upDownBars.upBars.setLn(this.chart.plotArea.charts[0].upDownBars.upBarsPen.createDuplicate(true)); } if(oCopy.chart.plotArea.charts[0].upDownBars.downBarsBrush) { if(!oCopy.chart.plotArea.charts[0].upDownBars.downBars) { oCopy.chart.plotArea.charts[0].upDownBars.setDownBars(new AscFormat.CSpPr()); } oCopy.chart.plotArea.charts[0].upDownBars.downBars.setFill(this.chart.plotArea.charts[0].upDownBars.downBarsBrush.saveSourceFormatting()); } if(oCopy.chart.plotArea.charts[0].upDownBars.downBarsPen) { if(!oCopy.chart.plotArea.charts[0].upDownBars.downBars) { oCopy.chart.plotArea.charts[0].upDownBars.setDownBars(new AscFormat.CSpPr()); } oCopy.chart.plotArea.charts[0].upDownBars.downBars.setLn(this.chart.plotArea.charts[0].upDownBars.downBarsPen.createDuplicate(true)); } } } } if(this.chart.legend) { fSaveChartObjectSourceFormatting(this.chart.legend, oCopy.chart.legend, oTheme, oColorMap); var legend = this.chart.legend; for(var i = 0; i < legend.legendEntryes.length; ++i) { fSaveChartObjectSourceFormatting(legend.legendEntryes[i], oCopy.chart.legend.legendEntryes[i], oTheme, oColorMap); } } if(this.chart.floor) { fSaveChartObjectSourceFormatting(this.chart.floor, oCopy.chart.floor, oTheme, oColorMap); } if(this.chart.sideWall) { fSaveChartObjectSourceFormatting(this.chart.sideWall, oCopy.chart.sideWall, oTheme, oColorMap); } if(this.chart.backWall) { fSaveChartObjectSourceFormatting(this.chart.backWall, oCopy.chart.backWall, oTheme, oColorMap); } } return oCopy; }; CChartSpace.prototype.getChartSizes = function(bNotRecalculate) { if(this.plotAreaRect && !this.recalcInfo.recalculateAxisVal){ return {startX: this.plotAreaRect.x, startY: this.plotAreaRect.y, w : this.plotAreaRect.w, h: this.plotAreaRect.h}; } if(!this.chartObj) this.chartObj = new AscFormat.CChartsDrawer(); var oChartSize = this.chartObj.calculateSizePlotArea(this); var oLayout = this.chart.plotArea.layout; if(oLayout){ oChartSize.startX = this.calculatePosByLayout(oChartSize.startX, oLayout.xMode, oLayout.x, oChartSize.w, this.extX); oChartSize.startY = this.calculatePosByLayout(oChartSize.startY, oLayout.yMode, oLayout.y, oChartSize.h, this.extY); var fSize = this.calculateSizeByLayout(oChartSize.startX, this.extX, oLayout.w, oLayout.wMode ); if(AscFormat.isRealNumber(fSize) && fSize > 0){ var fSize2 = this.calculateSizeByLayout(oChartSize.startY, this.extY, oLayout.h, oLayout.hMode ); if(AscFormat.isRealNumber(fSize2) && fSize2 > 0){ oChartSize.w = fSize; oChartSize.h = fSize2; var aCharts = this.chart.plotArea.charts; for(var i = 0; i < aCharts.length; ++i){ var nChartType = aCharts[i].getObjectType(); if(nChartType === AscDFH.historyitem_type_PieChart || nChartType === AscDFH.historyitem_type_DoughnutChart){ var fCX = oChartSize.startX + oChartSize.w/2.0; var fCY = oChartSize.startY + oChartSize.h/2.0; var fPieSize = Math.min(oChartSize.w, oChartSize.h); oChartSize.startX = fCX - fPieSize/2.0; oChartSize.startY = fCY - fPieSize/2.0; oChartSize.w = fPieSize; oChartSize.h = fPieSize; break; } } } } } if(oChartSize.w <= 0){ oChartSize.w = 1; } if(oChartSize.h <= 0){ oChartSize.h = 1; } return oChartSize; }; CChartSpace.prototype.getAllSeries = function() { var _ret = []; var aCharts = this.chart.plotArea.charts; for(var i = 0; i < aCharts.length; ++i){ _ret = _ret.concat(aCharts[i].series); } return _ret; }; CChartSpace.prototype.recalculatePlotAreaChartBrush = function() { if(this.chart && this.chart.plotArea) { var plot_area = this.chart.plotArea; var default_brush; if(AscFormat.CChartsDrawer.prototype._isSwitchCurrent3DChart(this)) { default_brush = CreateNoFillUniFill(); } else { if(this.chart.plotArea && this.chart.plotArea.charts.length === 1 && this.chart.plotArea.charts[0] && (this.chart.plotArea.charts[0].getObjectType() === AscDFH.historyitem_type_PieChart || this.chart.plotArea.charts[0].getObjectType() === AscDFH.historyitem_type_DoughnutChart)) { default_brush = CreateNoFillUniFill(); } else { var tint = 0.20000; if(this.style >=1 && this.style <=32) default_brush = CreateUnifillSolidFillSchemeColor(6, tint); else if(this.style >=33 && this.style <= 34) default_brush = CreateUnifillSolidFillSchemeColor(8, 0.20000); else if(this.style >=35 && this.style <=40) default_brush = CreateUnifillSolidFillSchemeColor(this.style - 35, tint); else default_brush = CreateUnifillSolidFillSchemeColor(8, 0.95000); } } if(plot_area.spPr && plot_area.spPr.Fill) { default_brush.merge(plot_area.spPr.Fill); } var parents = this.getParentObjects(); default_brush.calculate(parents.theme, parents.slide, parents.layout, parents.master, {R: 0, G: 0, B: 0, A: 255}, this.clrMapOvr); plot_area.brush = default_brush; } }; CChartSpace.prototype.recalculateChartPen = function() { var parent_objects = this.getParentObjects(); var default_line = new AscFormat.CLn(); if(parent_objects.theme && parent_objects.theme.themeElements && parent_objects.theme.themeElements.fmtScheme && parent_objects.theme.themeElements.fmtScheme.lnStyleLst) { default_line.merge(parent_objects.theme.themeElements.fmtScheme.lnStyleLst[0]); } var fill; if(this.style >= 1 && this.style <= 32) fill = CreateUnifillSolidFillSchemeColor(15, 0.75000); else if(this.style >= 33 && this.style <= 40) fill = CreateUnifillSolidFillSchemeColor(8, 0.75000); else fill = CreateUnifillSolidFillSchemeColor(12, 0); default_line.setFill(fill); if(this.spPr && this.spPr.ln) default_line.merge(this.spPr.ln); var parents = this.getParentObjects(); default_line.calculate(parents.theme, parents.slide, parents.layout, parents.master, {R: 0, G: 0, B: 0, A: 255}, this.clrMapOvr); this.pen = default_line; checkBlackUnifill(this.pen.Fill, true); }; CChartSpace.prototype.recalculateChartBrush = function() { var default_brush; if(this.style >=1 && this.style <=32) default_brush = CreateUnifillSolidFillSchemeColor(6, 0); else if(this.style >=33 && this.style <= 40) default_brush = CreateUnifillSolidFillSchemeColor(12, 0); else default_brush = CreateUnifillSolidFillSchemeColor(8, 0); if(this.spPr && this.spPr.Fill) { default_brush.merge(this.spPr.Fill); } var parents = this.getParentObjects(); default_brush.calculate(parents.theme, parents.slide, parents.layout, parents.master, {R: 0, G: 0, B: 0, A: 255}, this.clrMapOvr); this.brush = default_brush; }; CChartSpace.prototype.recalculateAxisTickMark = function() { if(this.chart && this.chart.plotArea) { var oThis = this; var calcMajorMinorGridLines = function (axis, defaultStyle, subtleLine, parents) { function calcGridLine(defaultStyle, spPr, subtleLine, parents) { var compiled_grid_lines = new AscFormat.CLn(); compiled_grid_lines.merge(subtleLine); // if(compiled_grid_lines.Fill && compiled_grid_lines.Fill.fill && compiled_grid_lines.Fill.fill.color && compiled_grid_lines.Fill.fill.color.Mods) // { // compiled_grid_lines.Fill.fill.color.Mods.Mods.length = 0; // } if(!compiled_grid_lines.Fill) { compiled_grid_lines.setFill(new AscFormat.CUniFill()); } //if(compiled_grid_lines.Fill && compiled_grid_lines.Fill.fill && compiled_grid_lines.Fill.fill.color && compiled_grid_lines.Fill.fill.color.Mods) //{ // compiled_grid_lines.Fill.fill.color.Mods.Mods.length = 0; //} compiled_grid_lines.Fill.merge(defaultStyle); if(subtleLine && subtleLine.Fill && subtleLine.Fill.fill && subtleLine.Fill.fill.color && subtleLine.Fill.fill.color.Mods && compiled_grid_lines.Fill && compiled_grid_lines.Fill.fill && compiled_grid_lines.Fill.fill.color) { compiled_grid_lines.Fill.fill.color.Mods = subtleLine.Fill.fill.color.Mods.createDuplicate(); } compiled_grid_lines.calculate(parents.theme, parents.slide, parents.layout, parents.master, {R: 0, G: 0, B: 0, A: 255}, oThis.clrMapOvr); checkBlackUnifill(compiled_grid_lines.Fill, true); if(spPr && spPr.ln) { compiled_grid_lines.merge(spPr.ln); compiled_grid_lines.calculate(parents.theme, parents.slide, parents.layout, parents.master, {R: 0, G: 0, B: 0, A: 255}, oThis.clrMapOvr); } return compiled_grid_lines; } axis.compiledLn = calcGridLine(defaultStyle.axisAndMajorGridLines, axis.spPr, subtleLine, parents); axis.compiledTickMarkLn = axis.compiledLn.createDuplicate(); if(AscFormat.isRealNumber(axis.compiledTickMarkLn.w)) axis.compiledTickMarkLn.w/=2; axis.compiledTickMarkLn.calculate(parents.theme, parents.slide, parents.layout, parents.master, {R: 0, G: 0, B: 0, A: 255}, oThis.clrMapOvr) }; var default_style = CHART_STYLE_MANAGER.getDefaultLineStyleByIndex(this.style); var parent_objects = this.getParentObjects(); var subtle_line; if(parent_objects.theme && parent_objects.theme.themeElements && parent_objects.theme.themeElements.fmtScheme && parent_objects.theme.themeElements.fmtScheme.lnStyleLst) { subtle_line = parent_objects.theme.themeElements.fmtScheme.lnStyleLst[0]; } var aAxes = this.chart.plotArea.axId; for(var i = 0; i < aAxes.length; ++i){ calcMajorMinorGridLines(aAxes[i], default_style, subtle_line, parent_objects); } } }; CChartSpace.prototype.getXValAxisValues = function() { if(!this.chartObj) { this.chartObj = new AscFormat.CChartsDrawer() } this.chartObj.preCalculateData(this); return [].concat(this.chart.plotArea.catAx.scale) }; CChartSpace.prototype.getValAxisValues = function() { if(!this.chartObj) { this.chartObj = new AscFormat.CChartsDrawer() } this.chartObj.preCalculateData(this); return [].concat(this.chart.plotArea.valAx.scale); }; CChartSpace.prototype.getCalcProps = function() { if(!this.chartObj) { this.chartObj = new AscFormat.CChartsDrawer() } this.chartObj.preCalculateData(this); return this.chartObj.calcProp; }; CChartSpace.prototype.recalculateDLbls = function() { if(this.chart && this.chart.plotArea) { var aCharts = this.chart.plotArea.charts; for(var t = 0; t < aCharts.length; ++t){ var series = aCharts[t].series; var nDefaultPosition; if(this.chart.plotArea.charts[0].getDefaultDataLabelsPosition) { nDefaultPosition = this.chart.plotArea.charts[0].getDefaultDataLabelsPosition(); } var default_lbl = new AscFormat.CDLbl(); default_lbl.initDefault(nDefaultPosition); var bSkip = false; if(this.ptsCount > MAX_LABELS_COUNT){ bSkip = true; } var nCount = 0; var nLblCount = 0; for(var i = 0; i < series.length; ++i) { var ser = series[i]; var pts = AscFormat.getPtsFromSeries(ser); for(var j = 0; j < pts.length; ++j) { var pt = pts[j]; if(bSkip){ if(nLblCount > (MAX_LABELS_COUNT*(nCount/this.ptsCount))){ pt.compiledDlb = null; nCount++; continue; } } var compiled_dlb = new AscFormat.CDLbl(); compiled_dlb.merge(default_lbl); compiled_dlb.merge(this.chart.plotArea.charts[0].dLbls); if(this.chart.plotArea.charts[0].dLbls) compiled_dlb.merge(this.chart.plotArea.charts[0].dLbls.findDLblByIdx(pt.idx), false); compiled_dlb.merge(ser.dLbls); if(ser.dLbls) compiled_dlb.merge(ser.dLbls.findDLblByIdx(pt.idx)); if(compiled_dlb.checkNoLbl()) { pt.compiledDlb = null; } else { pt.compiledDlb = compiled_dlb; pt.compiledDlb.chart = this; pt.compiledDlb.series = ser; pt.compiledDlb.pt = pt; pt.compiledDlb.recalculate(); nLblCount++; } ++nCount; } } } } }; CChartSpace.prototype.recalculateHiLowLines = function() { if(this.chart && this.chart.plotArea){ var aCharts = this.chart.plotArea.charts; var parents = this.getParentObjects(); for(var i = 0; i < aCharts.length; ++i){ var oCurChart = aCharts[i]; if((oCurChart instanceof AscFormat.CStockChart || oCurChart instanceof AscFormat.CLineChart) && oCurChart.hiLowLines){ var default_line = parents.theme.themeElements.fmtScheme.lnStyleLst[0].createDuplicate(); if(this.style >=1 && this.style <= 32) default_line.setFill(CreateUnifillSolidFillSchemeColor(15, 0)); else if(this.style >= 33 && this.style <= 34) default_line.setFill(CreateUnifillSolidFillSchemeColor(8, 0)); else if(this.style >= 35 && this.style <= 40) default_line.setFill(CreateUnifillSolidFillSchemeColor(8, -0.25000)); else default_line.setFill(CreateUnifillSolidFillSchemeColor(12, 0)); default_line.merge(oCurChart.hiLowLines.ln); oCurChart.calculatedHiLowLines = default_line; default_line.calculate(parents.theme, parents.slide, parents.layout, parents.master, {R:0, G:0, B:0, A:255}, this.clrMapOvr); } else{ oCurChart.calculatedHiLowLines = null; } } } }; CChartSpace.prototype.recalculateSeriesColors = function() { this.ptsCount = 0; if(this.chart && this.chart.plotArea) { var style = CHART_STYLE_MANAGER.getStyleByIndex(this.style); var parents = this.getParentObjects(); var RGBA = {R: 0, G: 0, B: 0, A: 255}; var aCharts = this.chart.plotArea.charts; var aAllSeries = []; for(var t = 0; t < aCharts.length; ++t){ aAllSeries = aAllSeries.concat(aCharts[t].series); } var nMaxSeriesIdx = getMaxIdx(aAllSeries); for(t = 0; t < aCharts.length; ++t){ var oChart = aCharts[t]; var series = oChart.series; if(oChart.varyColors && (series.length === 1 || oChart.getObjectType() === AscDFH.historyitem_type_PieChart || oChart.getObjectType() === AscDFH.historyitem_type_DoughnutChart)) { for(var ii = 0; ii < series.length; ++ ii) { var ser = series[ii]; var pts = AscFormat.getPtsFromSeries(ser); this.ptsCount += pts.length; if(!(oChart.getObjectType() === AscDFH.historyitem_type_LineChart || oChart.getObjectType() === AscDFH.historyitem_type_ScatterChart)) { var base_fills = getArrayFillsFromBase(style.fill2, getMaxIdx(pts)); for(var i = 0; i < pts.length; ++i) { var compiled_brush = new AscFormat.CUniFill(); compiled_brush.merge(base_fills[pts[i].idx]); if(ser.spPr && ser.spPr.Fill) { compiled_brush.merge(ser.spPr.Fill); } if(Array.isArray(ser.dPt)) { for(var j = 0; j < ser.dPt.length; ++j) { if(ser.dPt[j].idx === pts[i].idx) { if(ser.dPt[j].spPr) { compiled_brush.merge(ser.dPt[j].spPr.Fill); } break; } } } pts[i].brush = compiled_brush; pts[i].brush.calculate(parents.theme, parents.slide, parents.layout, parents.master, RGBA, this.clrMapOvr); } default_line = new AscFormat.CLn(); if(style.line1 === EFFECT_NONE) { default_line.w = 0; } else if(style.line1 === EFFECT_SUBTLE) { default_line.merge(parents.theme.themeElements.fmtScheme.lnStyleLst[0]); } else if(style.line1 === EFFECT_MODERATE) { default_line.merge(parents.theme.themeElements.fmtScheme.lnStyleLst[1]); } else if(style.line1 === EFFECT_INTENSE) { default_line.merge(parents.theme.themeElements.fmtScheme.lnStyleLst[2]); } var base_line_fills; if(this.style === 34) base_line_fills = getArrayFillsFromBase(style.line2, getMaxIdx(pts)); for(i = 0; i < pts.length; ++i) { var compiled_line = new AscFormat.CLn(); compiled_line.merge(default_line); compiled_line.Fill = new AscFormat.CUniFill(); if(this.style !== 34) { compiled_line.Fill.merge(style.line2[0]); } else { compiled_line.Fill.merge(base_line_fills[pts[i].idx]); } if(ser.spPr && ser.spPr.ln) compiled_line.merge(ser.spPr.ln); if(Array.isArray(ser.dPt) && !(ser.getObjectType && ser.getObjectType() === AscDFH.historyitem_type_AreaSeries)) { for(var j = 0; j < ser.dPt.length; ++j) { if(ser.dPt[j].idx === pts[i].idx) { if(ser.dPt[j].spPr) { compiled_line.merge(ser.dPt[j].spPr.ln); } break; } } } pts[i].pen = compiled_line; pts[i].pen.calculate(parents.theme, parents.slide, parents.layout, parents.master, RGBA, this.clrMapOvr); } } else { var default_line; if(oChart.getObjectType() === AscDFH.historyitem_type_ScatterChart && oChart.scatterStyle === AscFormat.SCATTER_STYLE_MARKER || oChart.scatterStyle === AscFormat.SCATTER_STYLE_NONE) { default_line = new AscFormat.CLn(); default_line.setFill(new AscFormat.CUniFill()); default_line.Fill.setFill(new AscFormat.CNoFill()); } else { default_line = parents.theme.themeElements.fmtScheme.lnStyleLst[0]; } var base_line_fills = getArrayFillsFromBase(style.line4, getMaxIdx(pts)); for(var i = 0; i < pts.length; ++i) { var compiled_line = new AscFormat.CLn(); compiled_line.merge(default_line); if(!(oChart.getObjectType() === AscDFH.historyitem_type_ScatterChart && oChart.scatterStyle === AscFormat.SCATTER_STYLE_MARKER || oChart.scatterStyle === AscFormat.SCATTER_STYLE_NONE)) compiled_line.Fill.merge(base_line_fills[pts[i].idx]); compiled_line.w *= style.line3; if(ser.spPr && ser.spPr.ln) { compiled_line.merge(ser.spPr.ln); } if(Array.isArray(ser.dPt)) { for(var j = 0; j < ser.dPt.length; ++j) { if(ser.dPt[j].idx === pts[i].idx) { if(ser.dPt[j].spPr) { compiled_line.merge(ser.dPt[j].spPr.ln); } break; } } } pts[i].brush = null; pts[i].pen = compiled_line; pts[i].pen.calculate(parents.theme, parents.slide, parents.layout, parents.master, RGBA, this.clrMapOvr); } } for(var j = 0; j < pts.length; ++j) { if(pts[j].compiledMarker) { pts[j].compiledMarker.pen && pts[j].compiledMarker.pen.calculate(parents.theme, parents.slide, parents.layout, parents.master, RGBA, this.clrMapOvr); pts[j].compiledMarker.brush && pts[j].compiledMarker.brush.calculate(parents.theme, parents.slide, parents.layout, parents.master, RGBA, this.clrMapOvr); } } } } else { switch(oChart.getObjectType()) { case AscDFH.historyitem_type_LineChart: case AscDFH.historyitem_type_RadarChart: { var base_line_fills = getArrayFillsFromBase(style.line4, nMaxSeriesIdx); if(!AscFormat.CChartsDrawer.prototype._isSwitchCurrent3DChart(this)) { for(var i = 0; i < series.length; ++i) { var default_line = parents.theme.themeElements.fmtScheme.lnStyleLst[0]; var ser = series[i]; var pts = AscFormat.getPtsFromSeries(ser); this.ptsCount += pts.length; var compiled_line = new AscFormat.CLn(); compiled_line.merge(default_line); compiled_line.Fill && compiled_line.Fill.merge(base_line_fills[ser.idx]); compiled_line.w *= style.line3; if(ser.spPr && ser.spPr.ln) compiled_line.merge(ser.spPr.ln); ser.compiledSeriesPen = compiled_line.createDuplicate(); for(var j = 0; j < pts.length; ++j) { var compiled_line = new AscFormat.CLn(); compiled_line.merge(default_line); compiled_line.Fill && compiled_line.Fill.merge(base_line_fills[ser.idx]); compiled_line.w *= style.line3; if(ser.spPr && ser.spPr.ln) compiled_line.merge(ser.spPr.ln); if(Array.isArray(ser.dPt)) { for(var k = 0; k < ser.dPt.length; ++k) { if(ser.dPt[k].idx === pts[j].idx) { if(ser.dPt[k].spPr) { compiled_line.merge(ser.dPt[k].spPr.ln); } break; } } } pts[j].brush = null; pts[j].pen = compiled_line; pts[j].pen.calculate(parents.theme, parents.slide, parents.layout, parents.master, RGBA, this.clrMapOvr); if(pts[j].compiledMarker) { pts[j].compiledMarker.pen && pts[j].compiledMarker.pen.calculate(parents.theme, parents.slide, parents.layout, parents.master, RGBA, this.clrMapOvr); pts[j].compiledMarker.brush && pts[j].compiledMarker.brush.calculate(parents.theme, parents.slide, parents.layout, parents.master, RGBA, this.clrMapOvr); } } } } else { var base_fills = getArrayFillsFromBase(style.fill2, nMaxSeriesIdx); var base_line_fills = null; if(style.line1 === EFFECT_SUBTLE && this.style === 34) base_line_fills = getArrayFillsFromBase(style.line2, nMaxSeriesIdx); for(var i = 0; i < series.length; ++i) { var ser = series[i]; var compiled_brush = new AscFormat.CUniFill(); compiled_brush.merge(base_fills[ser.idx]); if(ser.spPr && ser.spPr.Fill) { compiled_brush.merge(ser.spPr.Fill); } ser.compiledSeriesBrush = compiled_brush.createDuplicate(); var pts = AscFormat.getPtsFromSeries(ser); for(var j = 0; j < pts.length; ++j) { var compiled_brush = new AscFormat.CUniFill(); compiled_brush.merge(base_fills[ser.idx]); if(ser.spPr && ser.spPr.Fill) { compiled_brush.merge(ser.spPr.Fill); } if(Array.isArray(ser.dPt) && !(ser.getObjectType && ser.getObjectType() === AscDFH.historyitem_type_AreaSeries)) { for(var k = 0; k < ser.dPt.length; ++k) { if(ser.dPt[k].idx === pts[j].idx) { if(ser.dPt[k].spPr) { compiled_brush.merge(ser.dPt[k].spPr.Fill); } break; } } } pts[j].brush = compiled_brush; pts[j].brush.calculate(parents.theme, parents.slide, parents.layout, parents.master, RGBA, this.clrMapOvr); } // { default_line = new AscFormat.CLn(); if(style.line1 === EFFECT_NONE) { default_line.w = 0; } else if(style.line1 === EFFECT_SUBTLE) { default_line.merge(parents.theme.themeElements.fmtScheme.lnStyleLst[0]); } else if(style.line1 === EFFECT_MODERATE) { default_line.merge(parents.theme.themeElements.fmtScheme.lnStyleLst[1]); } else if(style.line1 === EFFECT_INTENSE) { default_line.merge(parents.theme.themeElements.fmtScheme.lnStyleLst[2]); } var base_line_fills; if(this.style === 34) base_line_fills = getArrayFillsFromBase(style.line2, getMaxIdx(pts)); var compiled_line = new AscFormat.CLn(); compiled_line.merge(default_line); compiled_line.Fill = new AscFormat.CUniFill(); if(this.style !== 34) compiled_line.Fill.merge(style.line2[0]); else compiled_line.Fill.merge(base_line_fills[ser.idx]); if(ser.spPr && ser.spPr.ln) { compiled_line.merge(ser.spPr.ln); } ser.compiledSeriesPen = compiled_line.createDuplicate(); for(var j = 0; j < pts.length; ++j) { var compiled_line = new AscFormat.CLn(); compiled_line.merge(default_line); compiled_line.Fill = new AscFormat.CUniFill(); if(this.style !== 34) compiled_line.Fill.merge(style.line2[0]); else compiled_line.Fill.merge(base_line_fills[ser.idx]); if(ser.spPr && ser.spPr.ln) { compiled_line.merge(ser.spPr.ln); } if(Array.isArray(ser.dPt) && !(ser.getObjectType && ser.getObjectType() === AscDFH.historyitem_type_AreaSeries)) { for(var k = 0; k < ser.dPt.length; ++k) { if(ser.dPt[k].idx === pts[j].idx) { if(ser.dPt[k].spPr) { compiled_line.merge(ser.dPt[k].spPr.ln); } break; } } } pts[j].pen = compiled_line; pts[j].pen.calculate(parents.theme, parents.slide, parents.layout, parents.master, RGBA, this.clrMapOvr); if(pts[j].compiledMarker) { pts[j].compiledMarker.pen && pts[j].compiledMarker.pen.calculate(parents.theme, parents.slide, parents.layout, parents.master, RGBA, this.clrMapOvr); pts[j].compiledMarker.brush && pts[j].compiledMarker.brush.calculate(parents.theme, parents.slide, parents.layout, parents.master, RGBA, this.clrMapOvr); } } } } } break; } case AscDFH.historyitem_type_ScatterChart: { var base_line_fills = getArrayFillsFromBase(style.line4, nMaxSeriesIdx); for(var i = 0; i < series.length; ++i) { var default_line = parents.theme.themeElements.fmtScheme.lnStyleLst[0]; var ser = series[i]; var pts = AscFormat.getPtsFromSeries(ser); this.ptsCount += pts.length; if(oChart.scatterStyle === AscFormat.SCATTER_STYLE_SMOOTH || oChart.scatterStyle === AscFormat.SCATTER_STYLE_SMOOTH_MARKER) { if(!AscFormat.isRealBool(ser.smooth)) { ser.smooth = true; } } if(oChart.scatterStyle === AscFormat.SCATTER_STYLE_MARKER || oChart.scatterStyle === AscFormat.SCATTER_STYLE_NONE) { default_line = new AscFormat.CLn(); default_line.setFill(new AscFormat.CUniFill()); default_line.Fill.setFill(new AscFormat.CNoFill()); } var compiled_line = new AscFormat.CLn(); compiled_line.merge(default_line); if(!(oChart.scatterStyle === AscFormat.SCATTER_STYLE_MARKER || oChart.scatterStyle === AscFormat.SCATTER_STYLE_NONE)) { compiled_line.Fill && compiled_line.Fill.merge(base_line_fills[ser.idx]); } compiled_line.w *= style.line3; if(ser.spPr && ser.spPr.ln) compiled_line.merge(ser.spPr.ln); ser.compiledSeriesPen = compiled_line.createDuplicate(); for(var j = 0; j < pts.length; ++j) { var compiled_line = new AscFormat.CLn(); compiled_line.merge(default_line); if(!(oChart.scatterStyle === AscFormat.SCATTER_STYLE_MARKER || oChart.scatterStyle === AscFormat.SCATTER_STYLE_NONE)) { compiled_line.Fill && compiled_line.Fill.merge(base_line_fills[ser.idx]); } compiled_line.w *= style.line3; if(ser.spPr && ser.spPr.ln) compiled_line.merge(ser.spPr.ln); if(Array.isArray(ser.dPt)) { for(var k = 0; k < ser.dPt.length; ++k) { if(ser.dPt[k].idx === pts[j].idx) { if(ser.dPt[k].spPr) { compiled_line.merge(ser.dPt[k].spPr.ln); } break; } } } pts[j].brush = null; pts[j].pen = compiled_line; pts[j].pen.calculate(parents.theme, parents.slide, parents.layout, parents.master, RGBA, this.clrMapOvr); if(pts[j].compiledMarker) { pts[j].compiledMarker.pen && pts[j].compiledMarker.pen.calculate(parents.theme, parents.slide, parents.layout, parents.master, RGBA, this.clrMapOvr); pts[j].compiledMarker.brush && pts[j].compiledMarker.brush.calculate(parents.theme, parents.slide, parents.layout, parents.master, RGBA, this.clrMapOvr); } } } break; } case AscDFH.historyitem_type_SurfaceChart: { var oSurfaceChart = oChart; var aValAxArray = this.getValAxisValues(); var nFmtsCount = aValAxArray.length - 1; var oSpPr, oBandFmt, oCompiledBandFmt; oSurfaceChart.compiledBandFormats.length = 0; var multiplier; var axis_by_types = oSurfaceChart.getAxisByTypes(); var val_ax = axis_by_types.valAx[0]; if(val_ax.dispUnits) multiplier = val_ax.dispUnits.getMultiplier(); else multiplier = 1; var num_fmt = val_ax.numFmt, num_format = null, calc_value, rich_value; if(num_fmt && typeof num_fmt.formatCode === "string" /*&& !(num_fmt.formatCode === "General")*/) { num_format = oNumFormatCache.get(num_fmt.formatCode); } var oParentObjects = this.getParentObjects(); var RGBA = {R: 255, G: 255, B: 255, A: 255}; if(oSurfaceChart.isWireframe()){ var base_line_fills = getArrayFillsFromBase(style.line4, nFmtsCount); var default_line = parents.theme.themeElements.fmtScheme.lnStyleLst[0]; for(var i = 0; i < nFmtsCount; ++i) { oBandFmt = oSurfaceChart.getBandFmtByIndex(i); oSpPr = new AscFormat.CSpPr(); oSpPr.setFill(AscFormat.CreateNoFillUniFill()); var compiled_line = new AscFormat.CLn(); compiled_line.merge(default_line); compiled_line.Fill.merge(base_line_fills[i]); //compiled_line.w *= style.line3; compiled_line.Join = new AscFormat.LineJoin(); compiled_line.Join.type = AscFormat.LineJoinType.Bevel; if(oBandFmt && oBandFmt.spPr){ compiled_line.merge(oBandFmt.spPr.ln); } compiled_line.calculate(oParentObjects.theme, oParentObjects.slide, oParentObjects.layout, oParentObjects.master, RGBA, this.clrMapOvr); oSpPr.setLn(compiled_line); oCompiledBandFmt = new AscFormat.CBandFmt(); oCompiledBandFmt.setIdx(i); oCompiledBandFmt.setSpPr(oSpPr); if(num_format){ oCompiledBandFmt.startValue = num_format.formatToChart(aValAxArray[i]*multiplier); oCompiledBandFmt.endValue = num_format.formatToChart(aValAxArray[i+1]*multiplier); } else{ oCompiledBandFmt.startValue = '' + (aValAxArray[i]*multiplier); oCompiledBandFmt.endValue = '' + (aValAxArray[i+1]*multiplier); } oCompiledBandFmt.setSpPr(oSpPr); oSurfaceChart.compiledBandFormats.push(oCompiledBandFmt); } } else{ var base_fills = getArrayFillsFromBase(style.fill2, nFmtsCount); var base_line_fills = null; if(style.line1 === EFFECT_SUBTLE && this.style === 34) base_line_fills = getArrayFillsFromBase(style.line2, nFmtsCount); var default_line = new AscFormat.CLn(); if(style.line1 === EFFECT_NONE) { default_line.w = 0; } else if(style.line1 === EFFECT_SUBTLE) { default_line.merge(parents.theme.themeElements.fmtScheme.lnStyleLst[0]); } else if(style.line1 === EFFECT_MODERATE) { default_line.merge(parents.theme.themeElements.fmtScheme.lnStyleLst[1]); } else if(style.line1 === EFFECT_INTENSE) { default_line.merge(parents.theme.themeElements.fmtScheme.lnStyleLst[2]); } for(var i = 0; i < nFmtsCount; ++i) { oBandFmt = oSurfaceChart.getBandFmtByIndex(i); var compiled_brush = new AscFormat.CUniFill(); oSpPr = new AscFormat.CSpPr(); compiled_brush.merge(base_fills[i]); if (oBandFmt && oBandFmt.spPr) { compiled_brush.merge(oBandFmt.spPr.Fill); } oSpPr.setFill(compiled_brush); var compiled_line = new AscFormat.CLn(); compiled_line.merge(default_line); compiled_line.Fill = new AscFormat.CUniFill(); if(this.style !== 34) compiled_line.Fill.merge(style.line2[0]); else compiled_line.Fill.merge(base_line_fills[i]); if(oBandFmt && oBandFmt.spPr && oBandFmt.spPr.ln) { compiled_line.merge(oBandFmt.spPr.ln); } oSpPr.setLn(compiled_line); compiled_line.calculate(oParentObjects.theme, oParentObjects.slide, oParentObjects.layout, oParentObjects.master, RGBA, this.clrMapOvr); compiled_brush.calculate(oParentObjects.theme, oParentObjects.slide, oParentObjects.layout, oParentObjects.master, RGBA, this.clrMapOvr); oCompiledBandFmt = new AscFormat.CBandFmt(); oCompiledBandFmt.setIdx(i); oCompiledBandFmt.setSpPr(oSpPr); if(num_format){ oCompiledBandFmt.startValue = num_format.formatToChart(aValAxArray[i]*multiplier); oCompiledBandFmt.endValue = num_format.formatToChart(aValAxArray[i+1]*multiplier); } else{ oCompiledBandFmt.startValue = '' + (aValAxArray[i]*multiplier); oCompiledBandFmt.endValue = '' + (aValAxArray[i+1]*multiplier); } oSurfaceChart.compiledBandFormats.push(oCompiledBandFmt); } } break; } default : { var base_fills = getArrayFillsFromBase(style.fill2, nMaxSeriesIdx); var base_line_fills = null; if(style.line1 === EFFECT_SUBTLE && this.style === 34) base_line_fills = getArrayFillsFromBase(style.line2, nMaxSeriesIdx); for(var i = 0; i < series.length; ++i) { var ser = series[i]; var compiled_brush = new AscFormat.CUniFill(); compiled_brush.merge(base_fills[ser.idx]); if(ser.spPr && ser.spPr.Fill) { compiled_brush.merge(ser.spPr.Fill); } ser.compiledSeriesBrush = compiled_brush.createDuplicate(); var pts = AscFormat.getPtsFromSeries(ser); this.ptsCount += pts.length; for(var j = 0; j < pts.length; ++j) { var compiled_brush = new AscFormat.CUniFill(); compiled_brush.merge(base_fills[ser.idx]); if(ser.spPr && ser.spPr.Fill) { compiled_brush.merge(ser.spPr.Fill); } if(Array.isArray(ser.dPt) && !(ser.getObjectType && ser.getObjectType() === AscDFH.historyitem_type_AreaSeries)) { for(var k = 0; k < ser.dPt.length; ++k) { if(ser.dPt[k].idx === pts[j].idx) { if(ser.dPt[k].spPr) { compiled_brush.merge(ser.dPt[k].spPr.Fill); } break; } } } pts[j].brush = compiled_brush; pts[j].brush.calculate(parents.theme, parents.slide, parents.layout, parents.master, RGBA, this.clrMapOvr); } // { default_line = new AscFormat.CLn(); if(style.line1 === EFFECT_NONE) { default_line.w = 0; } else if(style.line1 === EFFECT_SUBTLE) { default_line.merge(parents.theme.themeElements.fmtScheme.lnStyleLst[0]); } else if(style.line1 === EFFECT_MODERATE) { default_line.merge(parents.theme.themeElements.fmtScheme.lnStyleLst[1]); } else if(style.line1 === EFFECT_INTENSE) { default_line.merge(parents.theme.themeElements.fmtScheme.lnStyleLst[2]); } var base_line_fills; if(this.style === 34) base_line_fills = getArrayFillsFromBase(style.line2, getMaxIdx(pts)); var compiled_line = new AscFormat.CLn(); compiled_line.merge(default_line); compiled_line.Fill = new AscFormat.CUniFill(); if(this.style !== 34) compiled_line.Fill.merge(style.line2[0]); else compiled_line.Fill.merge(base_line_fills[ser.idx]); if(ser.spPr && ser.spPr.ln) { compiled_line.merge(ser.spPr.ln); } ser.compiledSeriesPen = compiled_line.createDuplicate(); for(var j = 0; j < pts.length; ++j) { var compiled_line = new AscFormat.CLn(); compiled_line.merge(default_line); compiled_line.Fill = new AscFormat.CUniFill(); if(this.style !== 34) compiled_line.Fill.merge(style.line2[0]); else compiled_line.Fill.merge(base_line_fills[ser.idx]); if(ser.spPr && ser.spPr.ln) { compiled_line.merge(ser.spPr.ln); } if(Array.isArray(ser.dPt) && !(ser.getObjectType && ser.getObjectType() === AscDFH.historyitem_type_AreaSeries)) { for(var k = 0; k < ser.dPt.length; ++k) { if(ser.dPt[k].idx === pts[j].idx) { if(ser.dPt[k].spPr) { compiled_line.merge(ser.dPt[k].spPr.ln); } break; } } } pts[j].pen = compiled_line; pts[j].pen.calculate(parents.theme, parents.slide, parents.layout, parents.master, RGBA, this.clrMapOvr); if(pts[j].compiledMarker) { pts[j].compiledMarker.pen && pts[j].compiledMarker.pen.calculate(parents.theme, parents.slide, parents.layout, parents.master, RGBA, this.clrMapOvr); pts[j].compiledMarker.brush && pts[j].compiledMarker.brush.calculate(parents.theme, parents.slide, parents.layout, parents.master, RGBA, this.clrMapOvr); } } } } break; } } } } } }; CChartSpace.prototype.recalculateChartTitleEditMode = function(bWord) { var old_pos_x, old_pos_y, old_pos_cx, old_pos_cy; var pos_x, pos_y; old_pos_x = this.recalcInfo.recalcTitle.x; old_pos_y = this.recalcInfo.recalcTitle.y; old_pos_cx = this.recalcInfo.recalcTitle.x + this.recalcInfo.recalcTitle.extX/2; old_pos_cy = this.recalcInfo.recalcTitle.y + this.recalcInfo.recalcTitle.extY/2; this.recalculateAxisLabels(); if(checkVerticalTitle(this.recalcInfo.recalcTitle)) { pos_x = old_pos_x; pos_y = old_pos_cy - this.recalcInfo.recalcTitle.extY/2; } else { pos_x = old_pos_cx - this.recalcInfo.recalcTitle.extX/2; pos_y = old_pos_y; } this.recalcInfo.recalcTitle.setPosition(pos_x, pos_y); if(bWord) { this.recalcInfo.recalcTitle.updatePosition(this.posX, this.posY); } }; CChartSpace.prototype.recalculateMarkers = function() { if(this.chart && this.chart.plotArea) { var aCharts = this.chart.plotArea.charts; var oCurChart; var aAllsSeries = []; for(var t = 0; t < aCharts.length; ++t){ oCurChart = aCharts[t]; var series = oCurChart.series, pts; aAllsSeries = aAllsSeries.concat(series); for(var i = 0; i < series.length; ++i) { var ser = series[i]; ser.compiledSeriesMarker = null; pts = AscFormat.getPtsFromSeries(ser); for(var j = 0; j < pts.length; ++j) { pts[j].compiledMarker = null; } } var oThis = this; var recalculateMarkers2 = function() { var chart_style = CHART_STYLE_MANAGER.getStyleByIndex(oThis.style); var effect_fill = chart_style.fill1; var fill = chart_style.fill2; var line = chart_style.line4; var masrker_default_size = AscFormat.isRealNumber(oThis.style) ? chart_style.markerSize : 5; var default_marker = new AscFormat.CMarker(); default_marker.setSize(masrker_default_size); var parent_objects = oThis.getParentObjects(); if(parent_objects.theme && parent_objects.theme.themeElements && parent_objects.theme.themeElements.fmtScheme && parent_objects.theme.themeElements.fmtScheme.lnStyleLst) { default_marker.setSpPr(new AscFormat.CSpPr()); default_marker.spPr.setLn(new AscFormat.CLn()); default_marker.spPr.ln.merge(parent_objects.theme.themeElements.fmtScheme.lnStyleLst[0]); } var RGBA = {R:0, G:0, B:0, A: 255}; if(oCurChart.varyColors && (oCurChart.series.length === 1 || oCurChart.getObjectType() === AscDFH.historyitem_type_PieChart || oCurChart.getObjectType() === AscDFH.historyitem_type_DoughnutChart)) { var ser = oCurChart.series[0], pts; if(ser.marker && ser.marker.symbol === AscFormat.SYMBOL_NONE && (!Array.isArray(ser.dPt) || ser.dPt.length === 0)) return; pts = AscFormat.getPtsFromSeries(ser); var series_marker = ser.marker; var brushes = getArrayFillsFromBase(fill, getMaxIdx(pts)); var pens_fills = getArrayFillsFromBase(line, getMaxIdx(pts)); var compiled_markers = []; for(var i = 0; i < pts.length; ++i) { var compiled_marker = new AscFormat.CMarker(); compiled_marker.merge(default_marker); if(!compiled_marker.spPr) { compiled_marker.setSpPr(new AscFormat.CSpPr()); } compiled_marker.spPr.setFill(brushes[pts[i].idx]); compiled_marker.spPr.Fill.merge(pts[i].brush); if(!compiled_marker.spPr.ln) compiled_marker.spPr.setLn(new AscFormat.CLn()); compiled_marker.spPr.ln.merge(pts[i].pen); compiled_marker.setSymbol(GetTypeMarkerByIndex(i)); compiled_marker.merge(ser.marker); if(Array.isArray(ser.dPt)) { for(var j = 0; j < ser.dPt.length; ++j) { if(ser.dPt[j].idx === pts[i].idx) { var d_pt = ser.dPt[j]; if(d_pt.spPr && (d_pt.spPr.Fill || d_pt.spPr.ln)) { if(!compiled_marker.spPr) { compiled_marker.setSpPr(new AscFormat.CSpPr()); } if(d_pt.spPr.Fill) { compiled_marker.spPr.setFill(d_pt.spPr.Fill.createDuplicate()); } if(d_pt.spPr.ln) { if(!compiled_marker.spPr.ln) { compiled_marker.spPr.setLn(new AscFormat.CLn()); } compiled_marker.spPr.ln.merge(d_pt.spPr.ln); } } compiled_marker.merge(ser.dPt[j].marker); break; } } } pts[i].compiledMarker = compiled_marker; pts[i].compiledMarker.pen = compiled_marker.spPr.ln; pts[i].compiledMarker.brush = compiled_marker.spPr.Fill; pts[i].compiledMarker.brush.calculate(parent_objects.theme, parent_objects.slide, parent_objects.layout, parent_objects.master, RGBA, oThis.clrMapOvr); pts[i].compiledMarker.pen.calculate(parent_objects.theme, parent_objects.slide, parent_objects.layout, parent_objects.master, RGBA, oThis.clrMapOvr); } } else { var series = oCurChart.series; var brushes = getArrayFillsFromBase(fill, getMaxIdx(aAllsSeries)); var pens_fills = getArrayFillsFromBase(line, getMaxIdx(aAllsSeries)); for(var i = 0; i < series.length; ++i) { var ser = series[i]; if(ser.marker && ser.marker.symbol === AscFormat.SYMBOL_NONE && (!Array.isArray(ser.dPt) || ser.dPt.length === 0)) continue; pts = AscFormat.getPtsFromSeries(ser); for(var j = 0; j < pts.length; ++j) { var compiled_marker = new AscFormat.CMarker(); compiled_marker.merge(default_marker); if(!compiled_marker.spPr) { compiled_marker.setSpPr(new AscFormat.CSpPr()); } compiled_marker.spPr.setFill(brushes[series[i].idx]); if(!compiled_marker.spPr.ln) compiled_marker.spPr.setLn(new AscFormat.CLn()); compiled_marker.spPr.ln.setFill(pens_fills[series[i].idx]); compiled_marker.setSymbol(GetTypeMarkerByIndex(series[i].idx)); compiled_marker.merge(ser.marker); if(j === 0) ser.compiledSeriesMarker = compiled_marker.createDuplicate(); if(Array.isArray(ser.dPt)) { for(var k = 0; k < ser.dPt.length; ++k) { if(ser.dPt[k].idx === pts[j].idx) { compiled_marker.merge(ser.dPt[k].marker); break; } } } pts[j].compiledMarker = compiled_marker; pts[j].compiledMarker.pen = compiled_marker.spPr.ln; pts[j].compiledMarker.brush = compiled_marker.spPr.Fill; pts[j].compiledMarker.brush.calculate(parent_objects.theme, parent_objects.slide, parent_objects.layout, parent_objects.master, RGBA, oThis.clrMapOvr); pts[j].compiledMarker.pen.calculate(parent_objects.theme, parent_objects.slide, parent_objects.layout, parent_objects.master, RGBA, oThis.clrMapOvr); } } } }; switch (oCurChart.getObjectType()) { case AscDFH.historyitem_type_LineChart: case AscDFH.historyitem_type_RadarChart: { if(oCurChart.marker !== false) { recalculateMarkers2(); } break; } case AscDFH.historyitem_type_ScatterChart: { if(oCurChart.scatterStyle === AscFormat.SCATTER_STYLE_MARKER || oCurChart.scatterStyle === AscFormat.SCATTER_STYLE_LINE_MARKER || oCurChart.scatterStyle === AscFormat.SCATTER_STYLE_SMOOTH_MARKER) { recalculateMarkers2(); } break; } default: { recalculateMarkers2(); break; } } } } }; CChartSpace.prototype.calcGridLine = function(defaultStyle, spPr, subtleLine, parents) { if(spPr) { var compiled_grid_lines = new AscFormat.CLn(); compiled_grid_lines.merge(subtleLine); // if(compiled_grid_lines.Fill && compiled_grid_lines.Fill.fill && compiled_grid_lines.Fill.fill.color && compiled_grid_lines.Fill.fill.color.Mods) // { // compiled_grid_lines.Fill.fill.color.Mods.Mods.length = 0; // } if(!compiled_grid_lines.Fill) { compiled_grid_lines.setFill(new AscFormat.CUniFill()); } //if(compiled_grid_lines.Fill && compiled_grid_lines.Fill.fill && compiled_grid_lines.Fill.fill.color && compiled_grid_lines.Fill.fill.color.Mods) //{ // compiled_grid_lines.Fill.fill.color.Mods.Mods.length = 0; //} compiled_grid_lines.Fill.merge(defaultStyle); if(subtleLine && subtleLine.Fill && subtleLine.Fill.fill && subtleLine.Fill.fill.color && subtleLine.Fill.fill.color.Mods && compiled_grid_lines.Fill && compiled_grid_lines.Fill.fill && compiled_grid_lines.Fill.fill.color) { compiled_grid_lines.Fill.fill.color.Mods = subtleLine.Fill.fill.color.Mods.createDuplicate(); } compiled_grid_lines.merge(spPr.ln); compiled_grid_lines.calculate(parents.theme, parents.slide, parents.layout, parents.master, {R: 0, G: 0, B: 0, A: 255}, this.clrMapOvr); checkBlackUnifill(compiled_grid_lines.Fill, true); return compiled_grid_lines; } return null; }; CChartSpace.prototype.calcMajorMinorGridLines = function (axis, defaultStyle, subtleLine, parents) { if(!axis) return; axis.compiledMajorGridLines = this.calcGridLine(defaultStyle.axisAndMajorGridLines, axis.majorGridlines, subtleLine, parents); axis.compiledMinorGridLines = this.calcGridLine(defaultStyle.minorGridlines, axis.minorGridlines, subtleLine, parents); }; CChartSpace.prototype.handleTitlesAfterChangeTheme = function() { if(this.chart && this.chart.title) { this.chart.title.checkAfterChangeTheme(); } if(this.chart && this.chart.plotArea) { var hor_axis = this.chart.plotArea.getHorizontalAxis(); if(hor_axis && hor_axis.title) { hor_axis.title.checkAfterChangeTheme(); } var vert_axis = this.chart.plotArea.getVerticalAxis(); if(vert_axis && vert_axis.title) { vert_axis.title.checkAfterChangeTheme(); } } }; CChartSpace.prototype.recalculateGridLines = function() { if(this.chart && this.chart.plotArea) { var default_style = CHART_STYLE_MANAGER.getDefaultLineStyleByIndex(this.style); var parent_objects = this.getParentObjects(); var subtle_line; if(parent_objects.theme && parent_objects.theme.themeElements && parent_objects.theme.themeElements.fmtScheme && parent_objects.theme.themeElements.fmtScheme.lnStyleLst) { subtle_line = parent_objects.theme.themeElements.fmtScheme.lnStyleLst[0]; } var aAxes = this.chart.plotArea.axId; for(var i = 0; i < aAxes.length; ++i){ var oCurAxis = aAxes[i]; this.calcMajorMinorGridLines(oCurAxis, default_style, subtle_line, parent_objects); this.calcMajorMinorGridLines(oCurAxis, default_style, subtle_line, parent_objects); } } }; CChartSpace.prototype.hitToAdjustment = function() { return {hit: false}; }; CChartSpace.prototype.recalculateAxisLabels = function() { if(this.chart && this.chart.title) { var title = this.chart.title; //title.parent = this.chart; title.chart = this; title.recalculate(); } if(this.chart && this.chart.plotArea) { var hor_axis = this.chart.plotArea.getHorizontalAxis(); if(hor_axis && hor_axis.title) { var title = hor_axis.title; //title.parent = hor_axis; title.chart = this; title.recalculate(); } var vert_axis = this.chart.plotArea.getVerticalAxis(); if(vert_axis && vert_axis.title) { var title = vert_axis.title; //title.parent = vert_axis; title.chart = this; title.recalculate(); } } }; CChartSpace.prototype.updateLinks = function() { //Этот метод нужен, т. к. мы не полностью поддерживаем формат в котором в одном plotArea может быть несколько разных диаграмм(конкретных типов). // Здесь мы берем первую из диаграмм лежащих в массиве plotArea.charts, а также выставляем ссылки для осей ; if(this.chart && this.chart.plotArea) { var oCheckChart; var oPlotArea = this.chart.plotArea; var aCharts = oPlotArea.charts; this.chart.plotArea.chart = aCharts[0]; for(var i = 0; i < aCharts.length; ++i){ if(aCharts[i].getObjectType() !== AscDFH.historyitem_type_PieChart && aCharts[i].getObjectType() !== AscDFH.historyitem_type_DoughnutChart){ oCheckChart = aCharts[i]; break; } } if(oCheckChart){ this.chart.plotArea.chart = oCheckChart; this.chart.plotArea.serAx = null; if(oCheckChart.getAxisByTypes) { var axis_by_types = oCheckChart.getAxisByTypes(); if(axis_by_types.valAx.length > 0 && axis_by_types.catAx.length > 0) { for(var i = 0; i < axis_by_types.valAx.length; ++i) { if(axis_by_types.valAx[i].crossAx) { for(var j = 0; j < axis_by_types.catAx.length; ++j) { if(axis_by_types.catAx[j] === axis_by_types.valAx[i].crossAx) { this.chart.plotArea.valAx = axis_by_types.valAx[i]; this.chart.plotArea.catAx = axis_by_types.catAx[j]; break; } } if(j < axis_by_types.catAx.length) { break; } } } if(i === axis_by_types.valAx.length) { this.chart.plotArea.valAx = axis_by_types.valAx[0]; this.chart.plotArea.catAx = axis_by_types.catAx[0]; } if(this.chart.plotArea.valAx && this.chart.plotArea.catAx) { for(i = 0; i < axis_by_types.serAx.length; ++i) { if(axis_by_types.serAx[i].crossAx === this.chart.plotArea.valAx) { this.chart.plotArea.serAx = axis_by_types.serAx[i]; break; } } } } else { if(axis_by_types.valAx.length > 1) {//TODO: выставлять оси исходя из настроек this.chart.plotArea.valAx = axis_by_types.valAx[1]; this.chart.plotArea.catAx = axis_by_types.valAx[0]; } } } else { this.chart.plotArea.valAx = null; this.chart.plotArea.catAx = null; } } } }; CChartSpace.prototype.draw = function(graphics) { if(this.checkNeedRecalculate && this.checkNeedRecalculate()){ return; } if(graphics.IsSlideBoundsCheckerType) { graphics.transform3(this.transform); graphics._s(); graphics._m(0, 0); graphics._l(this.extX, 0); graphics._l(this.extX, this.extY); graphics._l(0, this.extY); graphics._e(); return; } if(graphics.updatedRect) { var rect = graphics.updatedRect; var bounds = this.bounds; if(bounds.x > rect.x + rect.w || bounds.y > rect.y + rect.h || bounds.x + bounds.w < rect.x || bounds.y + bounds.h < rect.y) return; } graphics.SaveGrState(); graphics.SetIntegerGrid(false); graphics.transform3(this.transform, false); var ln_width; if(this.pen && AscFormat.isRealNumber(this.pen.w)) { ln_width = this.pen.w/36000; } else { ln_width = 0; } graphics.AddClipRect(-ln_width, -ln_width, this.extX+2*ln_width, this.extY+2*ln_width); if(this.chartObj) { this.chartObj.draw(this, graphics); } if(this.chart && !this.bEmptySeries) { if(this.chart.plotArea) { // var oChartSize = this.getChartSizes(); // graphics.p_width(70); // graphics.p_color(0, 0, 0, 255); // graphics._s(); // graphics._m(oChartSize.startX, oChartSize.startY); // graphics._l(oChartSize.startX + oChartSize.w, oChartSize.startY + 0); // graphics._l(oChartSize.startX + oChartSize.w, oChartSize.startY + oChartSize.h); // graphics._l(oChartSize.startX + 0, oChartSize.startY + oChartSize.h); // graphics._z(); // graphics.ds(); var aCharts = this.chart.plotArea.charts; for(var t = 0; t < aCharts.length; ++t){ var oChart = aCharts[t]; if(oChart && oChart.series) { var series = oChart.series; var _len = oChart.getObjectType() === AscDFH.historyitem_type_PieChart ? 1 : series.length; for(var i = 0; i < _len; ++i) { var ser = series[i]; var pts = AscFormat.getPtsFromSeries(ser); for(var j = 0; j < pts.length; ++j) { if(pts[j].compiledDlb) pts[j].compiledDlb.draw(graphics); } } } } for(var i = 0; i < this.chart.plotArea.axId.length; ++i){ var oAxis = this.chart.plotArea.axId[i]; if(oAxis.title){ oAxis.title.draw(graphics); } if(oAxis.labels){ oAxis.labels.draw(graphics); } } } if(this.chart.title) { this.chart.title.draw(graphics); } if(this.chart.legend) { this.chart.legend.draw(graphics); } } graphics.RestoreGrState(); if(this.drawLocks(this.transform, graphics)){ graphics.RestoreGrState(); } }; CChartSpace.prototype.addToSetPosition = function(dLbl) { if(dLbl instanceof AscFormat.CDLbl) this.recalcInfo.dataLbls.push(dLbl); else if(dLbl instanceof AscFormat.CTitle) this.recalcInfo.axisLabels.push(dLbl); }; CChartSpace.prototype.recalculateChart = function() { this.pathMemory.curPos = -1; if(this.chartObj == null) this.chartObj = new AscFormat.CChartsDrawer(); this.chartObj.recalculate(this); }; CChartSpace.prototype.GetRevisionsChangeParagraph = function(SearchEngine){ var titles = this.getAllTitles(), i; if(titles.length === 0){ return; } var oSelectedTitle = this.selection.title || this.selection.textSelection; if(oSelectedTitle){ for(i = 0; i < titles.length; ++i){ if(oSelectedTitle === titles[i]){ break; } } if(i === titles.length){ return; } } else{ if(SearchEngine.Get_Direction() > 0){ i = 0; } else{ i = titles.length - 1; } } while(!SearchEngine.Is_Found()){ titles[i].GetRevisionsChangeParagraph(SearchEngine); if(SearchEngine.Get_Direction() > 0){ if(i === titles.length - 1){ break; } ++i; } else{ if(i === 0){ break; } --i; } } }; CChartSpace.prototype.Search = function(Str, Props, SearchEngine, Type) { var titles = this.getAllTitles(); for(var i = 0; i < titles.length; ++i) { titles[i].Search(Str, Props, SearchEngine, Type) } }; CChartSpace.prototype.Search_GetId = function(bNext, bCurrent) { var Current = -1; var titles = this.getAllTitles(); var Len = titles.length; var Id = null; if ( true === bCurrent ) { for(var i = 0; i < Len; ++i) { if(titles[i] === this.selection.textSelection) { Current = i; break; } } } if ( true === bNext ) { var Start = ( -1 !== Current ? Current : 0 ); for ( var i = Start; i < Len; i++ ) { if ( titles[i].Search_GetId ) { Id = titles[i].Search_GetId(true, i === Current ? true : false); if ( null !== Id ) return Id; } } } else { var Start = ( -1 !== Current ? Current : Len - 1 ); for ( var i = Start; i >= 0; i-- ) { if (titles[i].Search_GetId ) { Id = titles[i].Search_GetId(false, i === Current ? true : false); if ( null !== Id ) return Id; } } } return null; }; function getPtsFromSeries(ser) { if(ser) { if(ser.val) { if(ser.val.numRef && ser.val.numRef.numCache) return ser.val.numRef.numCache.pts; else if(ser.val.numLit) return ser.val.numLit.pts; } else if(ser.yVal) { if(ser.yVal.numRef && ser.yVal.numRef.numCache) return ser.yVal.numRef.numCache.pts; else if(ser.yVal.numLit) return ser.yVal.numLit.pts; } } return []; } function getCatStringPointsFromSeries(ser) { if(ser && ser.cat) { if(ser.cat.strRef && ser.cat.strRef.strCache) { return ser.cat.strRef.strCache; } else if(ser.cat.strLit) { return ser.cat.strLit; } } return null; } function getMaxIdx(arr) { var max_idx = 0; for(var i = 0; i < arr.length;++i) arr[i].idx > max_idx && (max_idx = arr[i].idx); return max_idx+1; } function getArrayFillsFromBase(arrBaseFills, needFillsCount) { var ret = []; var nMaxCycleIdx = parseInt((needFillsCount - 1)/arrBaseFills.length); for(var i = 0; i < needFillsCount; ++i) { var nCycleIdx = ( i / arrBaseFills.length ) >> 0; var fShadeTint = ( nCycleIdx + 1 ) / (nMaxCycleIdx + 2) * 1.4 - 0.7; if(fShadeTint < 0) { fShadeTint = -(1 + fShadeTint); } else { fShadeTint = (1 - fShadeTint); } var color = CreateUniFillSolidFillWidthTintOrShade(arrBaseFills[i % arrBaseFills.length], fShadeTint); ret.push(color); } return ret; } function GetTypeMarkerByIndex(index) { return AscFormat.MARKER_SYMBOL_TYPE[index % 9]; } function CreateUnfilFromRGB(r, g, b) { var ret = new AscFormat.CUniFill(); ret.setFill(new AscFormat.CSolidFill()); ret.fill.setColor(new AscFormat.CUniColor()); ret.fill.color.setColor(new AscFormat.CRGBColor()); ret.fill.color.color.setColor(r, g, b); return ret; } function CreateColorMapByIndex(index) { var ret = []; switch(index) { case 1: { ret.push(CreateUnfilFromRGB(85, 85, 85)); ret.push(CreateUnfilFromRGB(158, 158, 158)); ret.push(CreateUnfilFromRGB(114, 114, 114)); ret.push(CreateUnfilFromRGB(70, 70, 70)); ret.push(CreateUnfilFromRGB(131, 131, 131)); ret.push(CreateUnfilFromRGB(193, 193, 193)); break; } case 2: { for(var i = 0; i < 6; ++i) { ret.push(CreateUnifillSolidFillSchemeColorByIndex(i)); } break; } default: { ret.push(CreateUnifillSolidFillSchemeColorByIndex(index - 3)); break; } } return ret; } function CreateUniFillSolidFillWidthTintOrShade(unifill, effectVal) { var ret = unifill.createDuplicate(); var unicolor = ret.fill.color; if(effectVal !== 0) { effectVal*=100000.0; if(!unicolor.Mods) unicolor.setMods(new AscFormat.CColorModifiers()); var mod = new AscFormat.CColorMod(); if(effectVal > 0) { mod.setName("tint"); mod.setVal(effectVal); } else { mod.setName("shade"); mod.setVal(Math.abs(effectVal)); } unicolor.Mods.addMod(mod); } return ret; } function CreateUnifillSolidFillSchemeColor(colorId, tintOrShade) { var unifill = new AscFormat.CUniFill(); unifill.setFill(new AscFormat.CSolidFill()); unifill.fill.setColor(new AscFormat.CUniColor()); unifill.fill.color.setColor(new AscFormat.CSchemeColor()); unifill.fill.color.color.setId(colorId); return CreateUniFillSolidFillWidthTintOrShade(unifill, tintOrShade); } function CreateNoFillLine() { var ret = new AscFormat.CLn(); ret.setFill(CreateNoFillUniFill()); return ret; } function CreateNoFillUniFill() { var ret = new AscFormat.CUniFill(); ret.setFill(new AscFormat.CNoFill()); return ret; } function CExternalData() { this.autoUpdate = null; this.id = null; this.Id = g_oIdCounter.Get_NewId(); g_oTableId.Add(this, this.Id); } CExternalData.prototype = { Get_Id: function() { return this.Id; }, Refresh_RecalcData: function() {}, getObjectType: function() { return AscDFH.historyitem_type_ExternalData; }, setAutoUpdate: function(pr) { History.Add(new CChangesDrawingsBool(this, AscDFH.historyitem_ExternalData_SetAutoUpdate, this.autoUpdate, pr)); this.autoUpdate = pr; }, setId: function(pr) { History.Add(new CChangesDrawingsString(this, AscDFH.historyitem_ExternalData_SetId, this.id, pr)); this.id = pr; } }; function CPivotSource() { this.fmtId = null; this.name = null; this.Id = g_oIdCounter.Get_NewId(); g_oTableId.Add(this, this.Id); } CPivotSource.prototype = { Get_Id: function() { return this.Id; }, Refresh_RecalcData: function() {}, getObjectType: function() { return AscDFH.historyitem_type_PivotSource; }, Write_ToBinary2: function (w) { w.WriteLong(this.getObjectType()); w.WriteString2(this.Id); }, Read_FromBinary2: function (r) { this.Id = r.GetString2(); }, setFmtId: function(pr) { History.Add(new CChangesDrawingsLong(this, AscDFH.historyitem_PivotSource_SetFmtId, this.fmtId, pr)); this.fmtId = pr; }, setName: function(pr) { History.Add(new CChangesDrawingsString(this, AscDFH.historyitem_PivotSource_SetName, this.name, pr)); this.name = pr; }, createDuplicate: function() { var copy = new CPivotSource(); if(AscFormat.isRealNumber(this.fmtId)) { copy.setFmtId(this.fmtId); } if(typeof this.name === "string") { copy.setName(this.name); } return copy; } }; function CProtection() { this.chartObject = null; this.data = null; this.formatting = null; this.selection = null; this.userInterface = null; this.Id = g_oIdCounter.Get_NewId(); g_oTableId.Add(this, this.Id); } CProtection.prototype = { Get_Id: function() { return this.Id; }, Refresh_RecalcData: function() {}, getObjectType: function() { return AscDFH.historyitem_type_Protection; }, Write_ToBinary2: function (w) { w.WriteLong(this.getObjectType()); w.WriteString2(this.Id); }, Read_FromBinary2: function (r) { this.Id = r.GetString2(); }, setChartObject: function(pr) { History.Add(new CChangesDrawingsBool(this, AscDFH.historyitem_Protection_SetChartObject, this.chartObject, pr)); this.chartObject = pr; }, setData: function(pr) { History.Add(new CChangesDrawingsBool(this, AscDFH.historyitem_Protection_SetData, this.data, pr)); this.data = pr; }, setFormatting: function(pr) { History.Add(new CChangesDrawingsBool(this, AscDFH.historyitem_Protection_SetFormatting, this.formatting, pr)); this.formatting = pr; }, setSelection: function(pr) { History.Add(new CChangesDrawingsBool(this, AscDFH.historyitem_Protection_SetSelection, this.selection, pr)); this.selection = pr; }, setUserInterface: function(pr) { History.Add(new CChangesDrawingsBool(this, AscDFH.historyitem_Protection_SetUserInterface, this.userInterface, pr)); this.userInterface = pr; }, createDuplicate: function() { var c = new CProtection(); if(this.chartObject !== null) c.setChartObject(this.chartObject); if(this.data !== null) c.setData(this.data); if(this.formatting !== null) c.setFormatting(this.formatting); if(this.selection !== null) c.setSelection(this.selection); if(this.userInterface !== null) c.setUserInterface(this.userInterface); return c; } }; function CPrintSettings() { this.headerFooter = null; this.pageMargins = null; this.pageSetup = null; this.Id = g_oIdCounter.Get_NewId(); g_oTableId.Add(this, this.Id); } CPrintSettings.prototype = { Get_Id: function() { return this.Id; }, createDuplicate : function() { var oPS = new CPrintSettings(); if ( this.headerFooter ) oPS.setHeaderFooter(this.headerFooter.createDuplicate()); if ( this.pageMargins ) oPS.setPageMargins(this.pageMargins.createDuplicate()); if ( this.pageSetup ) oPS.setPageSetup(this.pageSetup.createDuplicate()); return oPS; }, Refresh_RecalcData: function() {}, getObjectType: function() { return AscDFH.historyitem_type_PrintSettings; }, Write_ToBinary2: function (w) { w.WriteLong(this.getObjectType()); w.WriteString2(this.Id); }, Read_FromBinary2: function (r) { this.Id = r.GetString2(); }, setHeaderFooter: function(pr) { History.Add(new CChangesDrawingsObject(this, AscDFH.historyitem_PrintSettingsSetHeaderFooter, this.headerFooter, pr)); this.headerFooter = pr; }, setPageMargins: function(pr) { History.Add(new CChangesDrawingsObject(this, AscDFH.historyitem_PrintSettingsSetPageMargins, this.pageMargins, pr)); this.pageMargins = pr; }, setPageSetup: function(pr) { History.Add(new CChangesDrawingsObject(this, AscDFH.historyitem_PrintSettingsSetPageSetup, this.pageSetup, pr)); this.pageSetup = pr; } }; function CHeaderFooterChart() { this.alignWithMargins = null; this.differentFirst = null; this.differentOddEven = null; this.evenFooter = null; this.evenHeader = null; this.firstFooter = null; this.firstHeader = null; this.oddFooter = null; this.oddHeader = null; this.Id = g_oIdCounter.Get_NewId(); g_oTableId.Add(this, this.Id); } CHeaderFooterChart.prototype = { Get_Id: function() { return this.Id; }, createDuplicate : function() { var oHFC = new CHeaderFooterChart(); if(this.alignWithMargins !== null) oHFC.setAlignWithMargins(this.alignWithMargins); if(this.differentFirst !== null) oHFC.setDifferentFirst(this.differentFirst); if(this.differentOddEven !== null) oHFC.setDifferentOddEven(this.differentOddEven); if ( this.evenFooter !== null ) oHFC.setEvenFooter(this.evenFooter); if ( this.evenHeader !== null) oHFC.setEvenHeader(this.evenHeader); if ( this.firstFooter !== null) oHFC.setFirstFooter(this.firstFooter); if ( this.firstHeader !== null) oHFC.setFirstHeader(this.firstHeader); if ( this.oddFooter !== null) oHFC.setOddFooter(this.oddFooter); if ( this.oddHeader !== null) oHFC.setOddHeader(this.oddHeader); return oHFC; }, Refresh_RecalcData: function() {}, Write_ToBinary2: function (w) { w.WriteLong(this.getObjectType()); w.WriteString2(this.Id); }, Read_FromBinary2: function (r) { this.Id = r.GetString2(); }, getObjectType: function() { return AscDFH.historyitem_type_HeaderFooterChart; }, setAlignWithMargins: function(pr) { History.Add(new CChangesDrawingsBool(this, AscDFH.historyitem_HeaderFooterChartSetAlignWithMargins, this.alignWithMargins, pr)); this.alignWithMargins = pr; }, setDifferentFirst: function(pr) { History.Add(new CChangesDrawingsBool(this, AscDFH.historyitem_HeaderFooterChartSetDifferentFirst, this.differentFirst, pr)); this.differentFirst = pr; }, setDifferentOddEven: function(pr) { History.Add(new CChangesDrawingsBool(this, AscDFH.historyitem_HeaderFooterChartSetDifferentOddEven, this.differentOddEven, pr)); this.differentOddEven = pr; }, setEvenFooter: function(pr) { History.Add(new CChangesDrawingsString(this, AscDFH.historyitem_HeaderFooterChartSetEvenFooter, this.evenFooter, pr)); this.evenFooter = pr; }, setEvenHeader: function(pr) { History.Add(new CChangesDrawingsString(this, AscDFH.historyitem_HeaderFooterChartSetEvenHeader, this.evenHeader, pr)); this.evenHeader = pr; }, setFirstFooter: function(pr) { History.Add(new CChangesDrawingsString(this, AscDFH.historyitem_HeaderFooterChartSetFirstFooter, this.firstFooter, pr)); this.firstFooter = pr; }, setFirstHeader: function(pr) { History.Add(new CChangesDrawingsString(this, AscDFH.historyitem_HeaderFooterChartSetFirstHeader, this.firstHeader, pr)); this.firstHeader = pr; }, setOddFooter: function(pr) { History.Add(new CChangesDrawingsString(this, AscDFH.historyitem_HeaderFooterChartSetOddFooter, this.oddFooter, pr)); this.oddFooter = pr; }, setOddHeader: function(pr) { History.Add(new CChangesDrawingsString(this, AscDFH.historyitem_HeaderFooterChartSetOddHeader, this.oddHeader, pr)); this.oddHeader = pr; } }; function CPageMarginsChart() { this.b = null; this.footer = null; this.header = null; this.l = null; this.r = null; this.t = null; this.Id = g_oIdCounter.Get_NewId(); g_oTableId.Add(this, this.Id); } CPageMarginsChart.prototype = { Get_Id: function() { return this.Id; }, createDuplicate : function() { var oPMC = new CPageMarginsChart(); if(this.b !== null) oPMC.setB(this.b); if(this.footer !== null) oPMC.setFooter(this.footer); if(this.header !== null) oPMC.setHeader(this.header); if(this.l !== null) oPMC.setL(this.l); if(this.r !== null) oPMC.setR(this.r); if(this.t !== null) oPMC.setT(this.t); return oPMC; }, Refresh_RecalcData: function() {}, Write_ToBinary2: function (w) { w.WriteLong(this.getObjectType()); w.WriteString2(this.Id); }, Read_FromBinary2: function (r) { this.Id = r.GetString2(); }, getObjectType: function() { return AscDFH.historyitem_type_PageMarginsChart; }, setB: function(pr) { History.Add(new CChangesDrawingsDouble(this, AscDFH.historyitem_PageMarginsSetB, this.b, pr)); this.b = pr; }, setFooter: function(pr) { History.Add(new CChangesDrawingsDouble(this, AscDFH.historyitem_PageMarginsSetFooter, this.footer, pr)); this.footer = pr; }, setHeader: function(pr) { History.Add(new CChangesDrawingsDouble(this, AscDFH.historyitem_PageMarginsSetHeader, this.header, pr)); this.header = pr; }, setL: function(pr) { History.Add(new CChangesDrawingsDouble(this, AscDFH.historyitem_PageMarginsSetL, this.l, pr)); this.l = pr; }, setR: function(pr) { History.Add(new CChangesDrawingsDouble(this, AscDFH.historyitem_PageMarginsSetR, this.r, pr)); this.r = pr; }, setT: function(pr) { History.Add(new CChangesDrawingsDouble(this, AscDFH.historyitem_PageMarginsSetT, this.t, pr)); this.t = pr; } }; function CPageSetup() { this.blackAndWhite = null; this.copies = null; this.draft = null; this.firstPageNumber = null; this.horizontalDpi = null; this.orientation = null; this.paperHeight = null; this.paperSize = null; this.paperWidth = null; this.useFirstPageNumb = null; this.verticalDpi = null; this.Id = g_oIdCounter.Get_NewId(); g_oTableId.Add(this, this.Id); } CPageSetup.prototype = { Get_Id: function() { return this.Id; }, createDuplicate : function() { var oPS = new CPageSetup(); if(this.blackAndWhite !== null) oPS.setBlackAndWhite(this.blackAndWhite); if(this.copies !== null) oPS.setCopies(this.copies); if(this.draft !== null) oPS.setDraft(this.draft); if(this.firstPageNumber !== null) oPS.setFirstPageNumber(this.firstPageNumber); if(this.horizontalDpi !== null) oPS.setHorizontalDpi(this.horizontalDpi); if(this.orientation !== null) oPS.setOrientation(this.orientation); if(this.paperHeight !== null) oPS.setPaperHeight(this.paperHeight); if(this.paperSize !== null) oPS.setPaperSize(this.paperSize); if(this.paperWidth !== null) oPS.setPaperWidth(this.paperWidth); if(this.useFirstPageNumb !== null) oPS.setUseFirstPageNumb(this.useFirstPageNumb); if(this.verticalDpi !== null) oPS.setVerticalDpi(this.verticalDpi); return oPS; }, Refresh_RecalcData: function() {}, Write_ToBinary2: function (w) { w.WriteLong(this.getObjectType()); w.WriteString2(this.Id); }, Read_FromBinary2: function (r) { this.Id = r.GetString2(); }, getObjectType: function() { return AscDFH.historyitem_type_PageSetup; }, setBlackAndWhite: function(pr) { History.Add(new CChangesDrawingsBool(this, AscDFH.historyitem_PageSetupSetBlackAndWhite, this.blackAndWhite, pr)); this.blackAndWhite = pr; }, setCopies: function(pr) { History.Add(new CChangesDrawingsLong(this, AscDFH.historyitem_PageSetupSetCopies, this.copies, pr)); this.copies = pr; }, setDraft: function(pr) { History.Add(new CChangesDrawingsBool(this, AscDFH.historyitem_PageSetupSetDraft, this.draft, pr)); this.draft = pr; }, setFirstPageNumber: function(pr) { History.Add(new CChangesDrawingsLong(this, AscDFH.historyitem_PageSetupSetFirstPageNumber, this.firstPageNumber, pr)); this.firstPageNumber = pr; }, setHorizontalDpi: function(pr) { History.Add(new CChangesDrawingsLong(this, AscDFH.historyitem_PageSetupSetHorizontalDpi, this.horizontalDpi, pr)); this.horizontalDpi = pr; }, setOrientation: function(pr) { History.Add(new CChangesDrawingsLong(this, AscDFH.historyitem_PageSetupSetOrientation, this.orientation, pr)); this.orientation = pr; }, setPaperHeight: function(pr) { History.Add(new CChangesDrawingsDouble(this, AscDFH.historyitem_PageSetupSetPaperHeight, this.paperHeight, pr)); this.paperHeight = pr; }, setPaperSize: function(pr) { History.Add(new CChangesDrawingsLong(this, AscDFH.historyitem_PageSetupSetPaperSize, this.paperSize, pr)); this.paperSize = pr; }, setPaperWidth: function(pr) { History.Add(new CChangesDrawingsDouble(this, AscDFH.historyitem_PageSetupSetPaperWidth, this.paperWidth, pr)); this.paperWidth = pr; }, setUseFirstPageNumb: function(pr) { History.Add(new CChangesDrawingsBool(this, AscDFH.historyitem_PageSetupSetUseFirstPageNumb, this.useFirstPageNumb, pr)); this.useFirstPageNumb = pr; }, setVerticalDpi: function(pr) { History.Add(new CChangesDrawingsLong(this, AscDFH.historyitem_PageSetupSetVerticalDpi, this.verticalDpi, pr)); this.verticalDpi = pr; } }; function CreateView3d(nRotX, nRotY, bRAngAx, nDepthPercent) { var oView3d = new AscFormat.CView3d(); AscFormat.isRealNumber(nRotX) && oView3d.setRotX(nRotX); AscFormat.isRealNumber(nRotY) && oView3d.setRotY(nRotY); AscFormat.isRealBool(bRAngAx) && oView3d.setRAngAx(bRAngAx); AscFormat.isRealNumber(nDepthPercent) && oView3d.setDepthPercent(nDepthPercent); return oView3d; } function GetNumFormatFromSeries(aAscSeries){ if(aAscSeries && aAscSeries[0] && aAscSeries[0].Val && aAscSeries[0].Val.NumCache && aAscSeries[0].Val.NumCache[0]){ if(typeof (aAscSeries[0].Val.NumCache[0].numFormatStr) === "string" && aAscSeries[0].Val.NumCache[0].numFormatStr.length > 0){ return aAscSeries[0].Val.NumCache[0].numFormatStr; } } return "General"; } function FillCatAxNumFormat(oCatAxis, aAscSeries){ if(!oCatAxis){ return; } var sFormatCode = null; if(aAscSeries && aAscSeries[0] && aAscSeries[0].Cat && aAscSeries[0].Cat.NumCache && aAscSeries[0].Cat.NumCache[0]){ if(typeof (aAscSeries[0].Cat.NumCache[0].numFormatStr) === "string" && aAscSeries[0].Cat.NumCache[0].numFormatStr.length > 0){ sFormatCode = aAscSeries[0].Cat.NumCache[0].numFormatStr; } } if(sFormatCode){ oCatAxis.setNumFmt(new AscFormat.CNumFmt()); oCatAxis.numFmt.setFormatCode(sFormatCode ? sFormatCode : "General"); oCatAxis.numFmt.setSourceLinked(true); } } function CreateLineChart(chartSeries, type, bUseCache, oOptions, b3D) { var asc_series = chartSeries.series; var chart_space = new CChartSpace(); chart_space.setDate1904(false); chart_space.setLang("en-US"); chart_space.setRoundedCorners(false); chart_space.setChart(new AscFormat.CChart()); chart_space.setPrintSettings(new CPrintSettings()); var chart = chart_space.chart; if(b3D) { chart.setView3D(CreateView3d(15, 20, true, 100)); chart.setDefaultWalls(); } chart.setAutoTitleDeleted(false); chart.setPlotArea(new AscFormat.CPlotArea()); chart.setPlotVisOnly(true); var disp_blanks_as; if(type === AscFormat.GROUPING_STANDARD) { disp_blanks_as = DISP_BLANKS_AS_GAP; } else { disp_blanks_as = DISP_BLANKS_AS_ZERO; } chart.setDispBlanksAs(disp_blanks_as); chart.setShowDLblsOverMax(false); var plot_area = chart.plotArea; plot_area.setLayout(new AscFormat.CLayout()); plot_area.addChart(new AscFormat.CLineChart()); var cat_ax = new AscFormat.CCatAx(); var val_ax = new AscFormat.CValAx(); cat_ax.setAxId(++Ax_Counter.GLOBAL_AX_ID_COUNTER); val_ax.setAxId(++Ax_Counter.GLOBAL_AX_ID_COUNTER); cat_ax.setCrossAx(val_ax); val_ax.setCrossAx(cat_ax); plot_area.addAxis(cat_ax); plot_area.addAxis(val_ax); var line_chart = plot_area.charts[0]; line_chart.setGrouping(type); line_chart.setVaryColors(false); line_chart.setMarker(true); line_chart.setSmooth(false); line_chart.addAxId(cat_ax); line_chart.addAxId(val_ax); val_ax.setCrosses(2); var parsedHeaders = chartSeries.parsedHeaders; var bInCols; if(isRealObject(oOptions)) { bInCols = oOptions.inColumns === true; } else { bInCols = false; } for(var i = 0; i < asc_series.length; ++i) { var series = new AscFormat.CLineSeries(); series.setIdx(i); series.setOrder(i); series.setMarker(new AscFormat.CMarker()); series.marker.setSymbol(AscFormat.SYMBOL_NONE); series.setSmooth(false); series.setVal(new AscFormat.CYVal()); FillValNum(series.val, asc_series[i].Val, bUseCache); if(parsedHeaders.bTop && !bInCols || bInCols && parsedHeaders.bLeft) { series.setCat(new AscFormat.CCat()); FillCatStr(series.cat, asc_series[i].Cat, bUseCache); } if((parsedHeaders.bLeft && !bInCols || bInCols && parsedHeaders.bTop) && asc_series[i].TxCache && typeof asc_series[i].TxCache.Formula === "string" && asc_series[i].TxCache.Formula.length > 0) { FillSeriesTx(series, asc_series[i].TxCache, bUseCache); } line_chart.addSer(series); } cat_ax.setScaling(new AscFormat.CScaling()); cat_ax.setDelete(false); cat_ax.setAxPos(AscFormat.AX_POS_B); cat_ax.setMajorTickMark(c_oAscTickMark.TICK_MARK_OUT); cat_ax.setMinorTickMark(c_oAscTickMark.TICK_MARK_OUT); cat_ax.setTickLblPos(c_oAscTickLabelsPos.TICK_LABEL_POSITION_NEXT_TO); cat_ax.setCrosses(AscFormat.CROSSES_AUTO_ZERO); cat_ax.setAuto(true); cat_ax.setLblAlgn(AscFormat.LBL_ALG_CTR); cat_ax.setLblOffset(100); cat_ax.setNoMultiLvlLbl(false); var scaling = cat_ax.scaling; scaling.setOrientation(AscFormat.ORIENTATION_MIN_MAX); FillCatAxNumFormat(cat_ax, asc_series); val_ax.setScaling(new AscFormat.CScaling()); val_ax.setDelete(false); val_ax.setAxPos(AscFormat.AX_POS_L); val_ax.setMajorGridlines(new AscFormat.CSpPr()); val_ax.setNumFmt(new AscFormat.CNumFmt()); val_ax.setMajorTickMark(c_oAscTickMark.TICK_MARK_OUT); val_ax.setMinorTickMark(c_oAscTickMark.TICK_MARK_NONE); val_ax.setTickLblPos(c_oAscTickLabelsPos.TICK_LABEL_POSITION_NEXT_TO); val_ax.setCrosses(AscFormat.CROSSES_AUTO_ZERO); val_ax.setCrossBetween(AscFormat.CROSS_BETWEEN_BETWEEN); scaling = val_ax.scaling; scaling.setOrientation(AscFormat.ORIENTATION_MIN_MAX); var num_fmt = val_ax.numFmt; var format_code; if(type === AscFormat.GROUPING_PERCENT_STACKED) { format_code = "0%"; } else { format_code = GetNumFormatFromSeries(asc_series); } num_fmt.setFormatCode(format_code); num_fmt.setSourceLinked(true); if(asc_series.length > 1) { chart.setLegend(new AscFormat.CLegend()); var legend = chart.legend; legend.setLegendPos(c_oAscChartLegendShowSettings.right); legend.setLayout(new AscFormat.CLayout()); legend.setOverlay(false); } var print_settings = chart_space.printSettings; print_settings.setHeaderFooter(new CHeaderFooterChart()); print_settings.setPageMargins(new CPageMarginsChart()); print_settings.setPageSetup(new CPageSetup()); var page_margins = print_settings.pageMargins; page_margins.setB(0.75); page_margins.setL(0.7); page_margins.setR(0.7); page_margins.setT(0.75); page_margins.setHeader(0.3); page_margins.setFooter(0.3); return chart_space; } function CreateBarChart(chartSeries, type, bUseCache, oOptions, b3D, bDepth) { var asc_series = chartSeries.series; var chart_space = new CChartSpace(); chart_space.setDate1904(false); chart_space.setLang("en-US"); chart_space.setRoundedCorners(false); chart_space.setChart(new AscFormat.CChart()); chart_space.setPrintSettings(new CPrintSettings()); var chart = chart_space.chart; chart.setAutoTitleDeleted(false); if(b3D) { chart.setView3D(CreateView3d(15, 20, true, bDepth ? 100 : undefined)); chart.setDefaultWalls(); } chart.setPlotArea(new AscFormat.CPlotArea()); chart.setPlotVisOnly(true); chart.setDispBlanksAs(DISP_BLANKS_AS_GAP); chart.setShowDLblsOverMax(false); var plot_area = chart.plotArea; plot_area.setLayout(new AscFormat.CLayout()); plot_area.addChart(new AscFormat.CBarChart()); var bInCols; if(isRealObject(oOptions)) { bInCols = oOptions.inColumns === true; } else { bInCols = false; } var cat_ax = new AscFormat.CCatAx(); var val_ax = new AscFormat.CValAx(); cat_ax.setAxId(++Ax_Counter.GLOBAL_AX_ID_COUNTER); val_ax.setAxId(++Ax_Counter.GLOBAL_AX_ID_COUNTER); cat_ax.setCrossAx(val_ax); val_ax.setCrossAx(cat_ax); plot_area.addAxis(cat_ax); plot_area.addAxis(val_ax); var bar_chart = plot_area.charts[0]; if(b3D) { bar_chart.set3D(true); } bar_chart.setBarDir(AscFormat.BAR_DIR_COL); bar_chart.setGrouping(type); bar_chart.setVaryColors(false); var parsedHeaders = chartSeries.parsedHeaders; for(var i = 0; i < asc_series.length; ++i) { var series = new AscFormat.CBarSeries(); series.setIdx(i); series.setOrder(i); series.setInvertIfNegative(false); series.setVal(new AscFormat.CYVal()); FillValNum(series.val, asc_series[i].Val, bUseCache); if(parsedHeaders.bTop && !bInCols || bInCols && parsedHeaders.bLeft) { series.setCat(new AscFormat.CCat()); FillCatStr(series.cat, asc_series[i].Cat, bUseCache); } if((parsedHeaders.bLeft && !bInCols || bInCols && parsedHeaders.bTop) && asc_series[i].TxCache && typeof asc_series[i].TxCache.Formula === "string" && asc_series[i].TxCache.Formula.length > 0) { FillSeriesTx(series, asc_series[i].TxCache, bUseCache); } bar_chart.addSer(series); } bar_chart.setGapWidth(150); if(AscFormat.BAR_GROUPING_PERCENT_STACKED === type || AscFormat.BAR_GROUPING_STACKED === type) bar_chart.setOverlap(100); if(b3D) { bar_chart.setShape(BAR_SHAPE_BOX); } bar_chart.addAxId(cat_ax); bar_chart.addAxId(val_ax); cat_ax.setScaling(new AscFormat.CScaling()); cat_ax.setDelete(false); cat_ax.setAxPos(AscFormat.AX_POS_B); cat_ax.setMajorTickMark(c_oAscTickMark.TICK_MARK_OUT); cat_ax.setMinorTickMark(c_oAscTickMark.TICK_MARK_NONE); cat_ax.setCrosses(AscFormat.CROSSES_AUTO_ZERO); cat_ax.setAuto(true); cat_ax.setLblAlgn(AscFormat.LBL_ALG_CTR); cat_ax.setLblOffset(100); cat_ax.setNoMultiLvlLbl(false); var scaling = cat_ax.scaling; scaling.setOrientation(AscFormat.ORIENTATION_MIN_MAX); FillCatAxNumFormat(cat_ax, asc_series); val_ax.setScaling(new AscFormat.CScaling()); val_ax.setDelete(false); val_ax.setAxPos(AscFormat.AX_POS_L); val_ax.setMajorGridlines(new AscFormat.CSpPr()); val_ax.setNumFmt(new AscFormat.CNumFmt()); var num_fmt = val_ax.numFmt; var format_code; if(type === AscFormat.BAR_GROUPING_PERCENT_STACKED) { format_code = "0%"; } else { format_code = GetNumFormatFromSeries(asc_series); } num_fmt.setFormatCode(format_code); num_fmt.setSourceLinked(true); val_ax.setMajorTickMark(c_oAscTickMark.TICK_MARK_OUT); val_ax.setMinorTickMark(c_oAscTickMark.TICK_MARK_NONE); val_ax.setTickLblPos(c_oAscTickLabelsPos.TICK_LABEL_POSITION_NEXT_TO); val_ax.setCrosses(AscFormat.CROSSES_AUTO_ZERO); val_ax.setCrossBetween(AscFormat.CROSS_BETWEEN_BETWEEN); scaling = val_ax.scaling; scaling.setOrientation(AscFormat.ORIENTATION_MIN_MAX); if(asc_series.length > 1) { chart.setLegend(new AscFormat.CLegend()); var legend = chart.legend; legend.setLegendPos(c_oAscChartLegendShowSettings.right); legend.setLayout(new AscFormat.CLayout()); legend.setOverlay(false); } var print_settings = chart_space.printSettings; print_settings.setHeaderFooter(new CHeaderFooterChart()); print_settings.setPageMargins(new CPageMarginsChart()); print_settings.setPageSetup(new CPageSetup()); var page_margins = print_settings.pageMargins; page_margins.setB(0.75); page_margins.setL(0.7); page_margins.setR(0.7); page_margins.setT(0.75); page_margins.setHeader(0.3); page_margins.setFooter(0.3); return chart_space; } function CreateHBarChart(chartSeries, type, bUseCache, oOptions, b3D) { var asc_series = chartSeries.series; var chart_space = new CChartSpace(); chart_space.setDate1904(false); chart_space.setLang("en-US"); chart_space.setRoundedCorners(false); chart_space.setChart(new AscFormat.CChart()); chart_space.setPrintSettings(new CPrintSettings()); var chart = chart_space.chart; chart.setAutoTitleDeleted(false); if(b3D) { chart.setView3D(CreateView3d(15, 20, true, undefined)); chart.setDefaultWalls(); } chart.setPlotArea(new AscFormat.CPlotArea()); chart.setPlotVisOnly(true); chart.setDispBlanksAs(DISP_BLANKS_AS_GAP); chart.setShowDLblsOverMax(false); var plot_area = chart.plotArea; plot_area.setLayout(new AscFormat.CLayout()); plot_area.addChart(new AscFormat.CBarChart()); var cat_ax = new AscFormat.CCatAx(); var val_ax = new AscFormat.CValAx(); cat_ax.setAxId(++Ax_Counter.GLOBAL_AX_ID_COUNTER); val_ax.setAxId(++Ax_Counter.GLOBAL_AX_ID_COUNTER); cat_ax.setCrossAx(val_ax); val_ax.setCrossAx(cat_ax); plot_area.addAxis(cat_ax); plot_area.addAxis(val_ax); var bar_chart = plot_area.charts[0]; bar_chart.setBarDir(AscFormat.BAR_DIR_BAR); bar_chart.setGrouping(type); bar_chart.setVaryColors(false); var parsedHeaders = chartSeries.parsedHeaders; var bInCols; if(isRealObject(oOptions)) { bInCols = oOptions.inColumns === true; } else { bInCols = false; } for(var i = 0; i < asc_series.length; ++i) { var series = new AscFormat.CBarSeries(); series.setIdx(i); series.setOrder(i); series.setInvertIfNegative(false); series.setVal(new AscFormat.CYVal()); FillValNum(series.val, asc_series[i].Val, bUseCache); if((parsedHeaders.bTop && !bInCols || bInCols && parsedHeaders.bLeft)) { series.setCat(new AscFormat.CCat()); FillCatStr(series.cat, asc_series[i].Cat, bUseCache); } if((parsedHeaders.bLeft && !bInCols || bInCols && parsedHeaders.bTop) && asc_series[i].TxCache && typeof asc_series[i].TxCache.Formula === "string" && asc_series[i].TxCache.Formula.length > 0) { FillSeriesTx(series, asc_series[i].TxCache, bUseCache); } bar_chart.addSer(series); if(b3D) { bar_chart.setShape(BAR_SHAPE_BOX); } } //bar_chart.setDLbls(new CDLbls()); //var d_lbls = bar_chart.dLbls; //d_lbls.setShowLegendKey(false); //d_lbls.setShowVal(true); bar_chart.setGapWidth(150); if(AscFormat.BAR_GROUPING_PERCENT_STACKED === type || AscFormat.BAR_GROUPING_STACKED === type) bar_chart.setOverlap(100); bar_chart.addAxId(cat_ax); bar_chart.addAxId(val_ax); cat_ax.setScaling(new AscFormat.CScaling()); cat_ax.setDelete(false); cat_ax.setAxPos(AscFormat.AX_POS_L); cat_ax.setMajorTickMark(c_oAscTickMark.TICK_MARK_OUT); cat_ax.setMinorTickMark(c_oAscTickMark.TICK_MARK_NONE); cat_ax.setTickLblPos(c_oAscTickLabelsPos.TICK_LABEL_POSITION_NEXT_TO); cat_ax.setCrosses(AscFormat.CROSSES_AUTO_ZERO); cat_ax.setAuto(true); cat_ax.setLblAlgn(AscFormat.LBL_ALG_CTR); cat_ax.setLblOffset(100); cat_ax.setNoMultiLvlLbl(false); var scaling = cat_ax.scaling; scaling.setOrientation(AscFormat.ORIENTATION_MIN_MAX); FillCatAxNumFormat(cat_ax, asc_series); val_ax.setScaling(new AscFormat.CScaling()); val_ax.setDelete(false); val_ax.setAxPos(AscFormat.AX_POS_B); val_ax.setMajorGridlines(new AscFormat.CSpPr()); val_ax.setNumFmt(new AscFormat.CNumFmt()); val_ax.setMajorTickMark(c_oAscTickMark.TICK_MARK_OUT); val_ax.setMinorTickMark(c_oAscTickMark.TICK_MARK_NONE); val_ax.setTickLblPos(c_oAscTickLabelsPos.TICK_LABEL_POSITION_NEXT_TO); val_ax.setCrosses(AscFormat.CROSSES_AUTO_ZERO); val_ax.setCrossBetween(AscFormat.CROSS_BETWEEN_BETWEEN); scaling = val_ax.scaling; scaling.setOrientation(AscFormat.ORIENTATION_MIN_MAX); var num_fmt = val_ax.numFmt; var format_code; /*if(type === GROUPING_PERCENT_STACKED) { format_code = "0%"; } else */ { format_code = GetNumFormatFromSeries(asc_series); } num_fmt.setFormatCode(format_code); num_fmt.setSourceLinked(true); if(asc_series.length > 1) { chart.setLegend(new AscFormat.CLegend()); var legend = chart.legend; legend.setLegendPos(c_oAscChartLegendShowSettings.right); legend.setLayout(new AscFormat.CLayout()); legend.setOverlay(false); } var print_settings = chart_space.printSettings; print_settings.setHeaderFooter(new CHeaderFooterChart()); print_settings.setPageMargins(new CPageMarginsChart()); print_settings.setPageSetup(new CPageSetup()); var page_margins = print_settings.pageMargins; page_margins.setB(0.75); page_margins.setL(0.7); page_margins.setR(0.7); page_margins.setT(0.75); page_margins.setHeader(0.3); page_margins.setFooter(0.3); return chart_space; } function CreateAreaChart(chartSeries, type, bUseCache, oOptions) { var asc_series = chartSeries.series; var chart_space = new CChartSpace(); chart_space.setDate1904(false); chart_space.setLang("en-US"); chart_space.setRoundedCorners(false); chart_space.setChart(new AscFormat.CChart()); chart_space.setPrintSettings(new CPrintSettings()); var chart = chart_space.chart; chart.setAutoTitleDeleted(false); chart.setPlotArea(new AscFormat.CPlotArea()); chart.setPlotVisOnly(true); chart.setDispBlanksAs(DISP_BLANKS_AS_ZERO); chart.setShowDLblsOverMax(false); var plot_area = chart.plotArea; plot_area.setLayout(new AscFormat.CLayout()); plot_area.addChart(new AscFormat.CAreaChart()); var cat_ax = new AscFormat.CCatAx(); var val_ax = new AscFormat.CValAx(); cat_ax.setAxId(++Ax_Counter.GLOBAL_AX_ID_COUNTER); val_ax.setAxId(++Ax_Counter.GLOBAL_AX_ID_COUNTER); cat_ax.setCrossAx(val_ax); val_ax.setCrossAx(cat_ax); plot_area.addAxis(cat_ax); plot_area.addAxis(val_ax); var bInCols; if(isRealObject(oOptions)) { bInCols = oOptions.inColumns === true; } else { bInCols = false; } var area_chart = plot_area.charts[0]; area_chart.setGrouping(type); area_chart.setVaryColors(false); var parsedHeaders = chartSeries.parsedHeaders; for(var i = 0; i < asc_series.length; ++i) { var series = new AscFormat.CAreaSeries(); series.setIdx(i); series.setOrder(i); series.setVal(new AscFormat.CYVal()); FillValNum(series.val, asc_series[i].Val, bUseCache); if(parsedHeaders.bTop && !bInCols || bInCols && parsedHeaders.bLeft) { series.setCat(new AscFormat.CCat()); FillCatStr(series.cat, asc_series[i].Cat, bUseCache); } if((parsedHeaders.bLeft && !bInCols || bInCols && parsedHeaders.bTop) && asc_series[i].TxCache && typeof asc_series[i].TxCache.Formula === "string" && asc_series[i].TxCache.Formula.length > 0) { FillSeriesTx(series, asc_series[i].TxCache, bUseCache); } area_chart.addSer(series); } //area_chart.setDLbls(new CDLbls()); area_chart.addAxId(cat_ax); area_chart.addAxId(val_ax); //var d_lbls = area_chart.dLbls; //d_lbls.setShowLegendKey(false); //d_lbls.setShowVal(true); cat_ax.setScaling(new AscFormat.CScaling()); cat_ax.setDelete(false); cat_ax.setAxPos(AscFormat.AX_POS_B); cat_ax.setMajorTickMark(c_oAscTickMark.TICK_MARK_OUT); cat_ax.setMinorTickMark(c_oAscTickMark.TICK_MARK_NONE); cat_ax.setTickLblPos(c_oAscTickLabelsPos.TICK_LABEL_POSITION_NEXT_TO); cat_ax.setCrosses(AscFormat.CROSSES_AUTO_ZERO); cat_ax.setAuto(true); cat_ax.setLblAlgn(AscFormat.LBL_ALG_CTR); cat_ax.setLblOffset(100); cat_ax.setNoMultiLvlLbl(false); cat_ax.scaling.setOrientation(AscFormat.ORIENTATION_MIN_MAX); FillCatAxNumFormat(cat_ax, asc_series); val_ax.setScaling(new AscFormat.CScaling()); val_ax.setDelete(false); val_ax.setAxPos(AscFormat.AX_POS_L); val_ax.setMajorGridlines(new AscFormat.CSpPr()); val_ax.setNumFmt(new AscFormat.CNumFmt()); val_ax.setMajorTickMark(c_oAscTickMark.TICK_MARK_OUT); val_ax.setMinorTickMark(c_oAscTickMark.TICK_MARK_NONE); val_ax.setTickLblPos(c_oAscTickLabelsPos.TICK_LABEL_POSITION_NEXT_TO); val_ax.setCrosses(AscFormat.CROSSES_AUTO_ZERO); val_ax.setCrossBetween(AscFormat.CROSS_BETWEEN_MID_CAT); var scaling = val_ax.scaling; scaling.setOrientation(AscFormat.ORIENTATION_MIN_MAX); var num_fmt = val_ax.numFmt; var format_code; if(type === AscFormat.GROUPING_PERCENT_STACKED) { format_code = "0%"; } else { format_code = GetNumFormatFromSeries(asc_series); } num_fmt.setFormatCode(format_code); num_fmt.setSourceLinked(true); if(asc_series.length > 1) { chart.setLegend(new AscFormat.CLegend()); var legend = chart.legend; legend.setLegendPos(c_oAscChartLegendShowSettings.right); legend.setLayout(new AscFormat.CLayout()); legend.setOverlay(false); } var print_settings = chart_space.printSettings; print_settings.setHeaderFooter(new CHeaderFooterChart()); print_settings.setPageMargins(new CPageMarginsChart()); print_settings.setPageSetup(new CPageSetup()); var page_margins = print_settings.pageMargins; page_margins.setB(0.75); page_margins.setL(0.7); page_margins.setR(0.7); page_margins.setT(0.75); page_margins.setHeader(0.3); page_margins.setFooter(0.3); return chart_space; } function CreatePieChart(chartSeries, bDoughnut, bUseCache, oOptions, b3D) { var asc_series = chartSeries.series; var chart_space = new CChartSpace(); chart_space.setDate1904(false); chart_space.setLang("en-US"); chart_space.setRoundedCorners(false); chart_space.setStyle(2); chart_space.setChart(new AscFormat.CChart()); var chart = chart_space.chart; chart.setAutoTitleDeleted(false); if(b3D) { chart.setView3D(CreateView3d(30, 0, true, 100)); chart.setDefaultWalls(); } chart.setPlotArea(new AscFormat.CPlotArea()); var plot_area = chart.plotArea; plot_area.setLayout(new AscFormat.CLayout()); plot_area.addChart(bDoughnut ? new AscFormat.CDoughnutChart() : new AscFormat.CPieChart()); var pie_chart = plot_area.charts[0]; pie_chart.setVaryColors(true); var parsedHeaders = chartSeries.parsedHeaders; var bInCols; if(isRealObject(oOptions)) { bInCols = oOptions.inColumns === true; } else { bInCols = false; } for(var i = 0; i < asc_series.length; ++i) { var series = new AscFormat.CPieSeries(); series.setIdx(i); series.setOrder(i); series.setVal(new AscFormat.CYVal()); var val = series.val; FillValNum(series.val, asc_series[i].Val, bUseCache); if(parsedHeaders.bTop && !bInCols || bInCols && parsedHeaders.bLeft) { series.setCat(new AscFormat.CCat()); FillCatStr(series.cat, asc_series[i].Cat, bUseCache); } if((parsedHeaders.bLeft && !bInCols || bInCols && parsedHeaders.bTop) && asc_series[i].TxCache && typeof asc_series[i].TxCache.Formula === "string" && asc_series[i].TxCache.Formula.length > 0) { FillSeriesTx(series, asc_series[i].TxCache, bUseCache); } pie_chart.addSer(series); } pie_chart.setFirstSliceAng(0); if(bDoughnut) pie_chart.setHoleSize(50); chart.setLegend(new AscFormat.CLegend()); var legend = chart.legend; legend.setLegendPos(c_oAscChartLegendShowSettings.right); legend.setLayout(new AscFormat.CLayout()); legend.setOverlay(false); chart.setPlotVisOnly(true); chart.setDispBlanksAs(DISP_BLANKS_AS_GAP); chart.setShowDLblsOverMax(false); chart_space.setPrintSettings(new CPrintSettings()); var print_settings = chart_space.printSettings; print_settings.setHeaderFooter(new CHeaderFooterChart()); print_settings.setPageMargins(new CPageMarginsChart()); print_settings.setPageSetup(new CPageSetup()); var page_margins = print_settings.pageMargins; page_margins.setB(0.75); page_margins.setL(0.7); page_margins.setR(0.7); page_margins.setT(0.75); page_margins.setHeader(0.3); page_margins.setFooter(0.3); return chart_space; } function FillCatStr(oCat, oCatCache, bUseCache, bFillCache) { oCat.setStrRef(new AscFormat.CStrRef()); var str_ref = oCat.strRef; str_ref.setF(oCatCache.Formula); if(bUseCache) { str_ref.setStrCache(new AscFormat.CStrCache()); var str_cache = str_ref.strCache; var cat_num_cache = oCatCache.NumCache; str_cache.setPtCount(cat_num_cache.length); if(!(bFillCache === false)) { for(var j = 0; j < cat_num_cache.length; ++j) { var string_pt = new AscFormat.CStringPoint(); string_pt.setIdx(j); string_pt.setVal(cat_num_cache[j].val); str_cache.addPt(string_pt); } } } } function FillValNum(oVal, oValCache, bUseCache, bFillCache) { oVal.setNumRef(new AscFormat.CNumRef()); var num_ref = oVal.numRef; num_ref.setF(oValCache.Formula); if(bUseCache) { num_ref.setNumCache(new AscFormat.CNumLit()); var num_cache = num_ref.numCache; num_cache.setPtCount(oValCache.NumCache.length); if(!(bFillCache === false)) { for(var j = 0; j < oValCache.NumCache.length; ++j) { var pt = new AscFormat.CNumericPoint(); pt.setIdx(j); pt.setFormatCode(oValCache.NumCache[j].numFormatStr); pt.setVal(oValCache.NumCache[j].val); num_cache.addPt(pt); } } } } function FillSeriesTx(oSeries, oTxCache, bUseCache, bFillCache) { oSeries.setTx(new AscFormat.CTx()); var tx= oSeries.tx; tx.setStrRef(new AscFormat.CStrRef()); var str_ref = tx.strRef; str_ref.setF(oTxCache.Formula); if(bUseCache) { str_ref.setStrCache(new AscFormat.CStrCache()); var str_cache = str_ref.strCache; str_cache.setPtCount(1); if(!(bFillCache === false)) { str_cache.addPt(new AscFormat.CStringPoint()); var pt = str_cache.pts[0]; pt.setIdx(0); pt.setVal(oTxCache.Tx); } } } function CreateScatterChart(chartSeries, bUseCache, oOptions) { var asc_series = chartSeries.series; var chart_space = new CChartSpace(); chart_space.setDate1904(false); chart_space.setLang("en-US"); chart_space.setRoundedCorners(false); chart_space.setStyle(2); chart_space.setChart(new AscFormat.CChart()); var chart = chart_space.chart; chart.setAutoTitleDeleted(false); chart.setPlotArea(new AscFormat.CPlotArea()); var plot_area = chart.plotArea; plot_area.setLayout(new AscFormat.CLayout()); plot_area.addChart(new AscFormat.CScatterChart()); var scatter_chart = plot_area.charts[0]; scatter_chart.setScatterStyle(AscFormat.SCATTER_STYLE_MARKER); scatter_chart.setVaryColors(false); var bInCols; if(isRealObject(oOptions)) { bInCols = oOptions.inColumns === true; } else { bInCols = false; } var parsedHeaders = chartSeries.parsedHeaders; var cat_ax = new AscFormat.CValAx(); var val_ax = new AscFormat.CValAx(); cat_ax.setAxId(++Ax_Counter.GLOBAL_AX_ID_COUNTER); val_ax.setAxId(++Ax_Counter.GLOBAL_AX_ID_COUNTER); cat_ax.setCrossAx(val_ax); val_ax.setCrossAx(cat_ax); plot_area.addAxis(cat_ax); plot_area.addAxis(val_ax); var oXVal; var first_series = null; var start_index = 0; var minus = 0; if(parsedHeaders.bTop && !bInCols || bInCols && parsedHeaders.bLeft) { oXVal = new AscFormat.CXVal(); FillCatStr(oXVal, asc_series[0].xVal, bUseCache); } else { first_series = asc_series.length > 1 ? asc_series[0] : null; start_index = asc_series.length > 1 ? 1 : 0; minus = start_index === 1 ? 1 : 0; if(first_series) { oXVal = new AscFormat.CXVal(); FillValNum(oXVal, first_series.Val, bUseCache); } } for(var i = start_index; i < asc_series.length; ++i) { var series = new AscFormat.CScatterSeries(); series.setIdx(i - minus); series.setOrder(i - minus); if(oXVal) { series.setXVal(oXVal.createDuplicate()); } series.setYVal(new AscFormat.CYVal()); FillValNum(series.yVal, asc_series[i].Val, bUseCache); if((parsedHeaders.bLeft && !bInCols || bInCols && parsedHeaders.bTop) && asc_series[i].TxCache && typeof asc_series[i].TxCache.Formula === "string" && asc_series[i].TxCache.Formula.length > 0) { FillSeriesTx(series, asc_series[i].TxCache, bUseCache) } scatter_chart.addSer(series); } scatter_chart.addAxId(cat_ax); scatter_chart.addAxId(val_ax); cat_ax.setScaling(new AscFormat.CScaling()); cat_ax.setDelete(false); cat_ax.setAxPos(AscFormat.AX_POS_B); cat_ax.setMajorTickMark(c_oAscTickMark.TICK_MARK_OUT); cat_ax.setMinorTickMark(c_oAscTickMark.TICK_MARK_NONE); cat_ax.setTickLblPos(c_oAscTickLabelsPos.TICK_LABEL_POSITION_NEXT_TO); cat_ax.setCrosses(AscFormat.CROSSES_AUTO_ZERO); cat_ax.scaling.setOrientation(AscFormat.ORIENTATION_MIN_MAX); val_ax.setScaling(new AscFormat.CScaling()); val_ax.setDelete(false); val_ax.setAxPos(AscFormat.AX_POS_L); val_ax.setMajorGridlines(new AscFormat.CSpPr()); val_ax.setNumFmt(new AscFormat.CNumFmt()); val_ax.setMajorTickMark(c_oAscTickMark.TICK_MARK_OUT); val_ax.setMinorTickMark(c_oAscTickMark.TICK_MARK_NONE); val_ax.setTickLblPos(c_oAscTickLabelsPos.TICK_LABEL_POSITION_NEXT_TO); val_ax.setCrosses(AscFormat.CROSSES_AUTO_ZERO); val_ax.setCrossBetween(AscFormat.CROSS_BETWEEN_BETWEEN); var scaling = val_ax.scaling; scaling.setOrientation(AscFormat.ORIENTATION_MIN_MAX); var num_fmt = val_ax.numFmt; var format_code = GetNumFormatFromSeries(asc_series); num_fmt.setFormatCode(format_code); num_fmt.setSourceLinked(true); if(scatter_chart.series.length > 1) { chart.setLegend(new AscFormat.CLegend()); var legend = chart.legend; legend.setLegendPos(c_oAscChartLegendShowSettings.right); legend.setLayout(new AscFormat.CLayout()); legend.setOverlay(false); } chart_space.setPrintSettings(new CPrintSettings()); var print_settings = chart_space.printSettings; print_settings.setHeaderFooter(new CHeaderFooterChart()); print_settings.setPageMargins(new CPageMarginsChart()); print_settings.setPageSetup(new CPageSetup()); var page_margins = print_settings.pageMargins; page_margins.setB(0.75); page_margins.setL(0.7); page_margins.setR(0.7); page_margins.setT(0.75); page_margins.setHeader(0.3); page_margins.setFooter(0.3); return chart_space; } function CreateStockChart(chartSeries, bUseCache, oOptions) { var asc_series = chartSeries.series; var chart_space = new CChartSpace(); chart_space.setDate1904(false); chart_space.setLang("en-US"); chart_space.setRoundedCorners(false); chart_space.setChart(new AscFormat.CChart()); chart_space.setPrintSettings(new CPrintSettings()); var chart = chart_space.chart; chart.setAutoTitleDeleted(false); chart.setPlotArea(new AscFormat.CPlotArea()); chart.setLegend(new AscFormat.CLegend()); chart.setPlotVisOnly(true); var disp_blanks_as; disp_blanks_as = DISP_BLANKS_AS_GAP; chart.setDispBlanksAs(disp_blanks_as); chart.setShowDLblsOverMax(false); var plot_area = chart.plotArea; plot_area.setLayout(new AscFormat.CLayout()); plot_area.addChart(new AscFormat.CStockChart()); var bInCols; if(isRealObject(oOptions)) { bInCols = oOptions.inColumns === true; } else { bInCols = false; } var cat_ax = new AscFormat.CCatAx(); var val_ax = new AscFormat.CValAx(); cat_ax.setAxId(++Ax_Counter.GLOBAL_AX_ID_COUNTER); val_ax.setAxId(++Ax_Counter.GLOBAL_AX_ID_COUNTER); cat_ax.setCrossAx(val_ax); val_ax.setCrossAx(cat_ax); plot_area.addAxis(cat_ax); plot_area.addAxis(val_ax); var line_chart = plot_area.charts[0]; line_chart.addAxId(cat_ax); line_chart.addAxId(val_ax); line_chart.setHiLowLines(new AscFormat.CSpPr()); line_chart.setUpDownBars(new AscFormat.CUpDownBars()); line_chart.upDownBars.setGapWidth(150); line_chart.upDownBars.setUpBars(new AscFormat.CSpPr()); line_chart.upDownBars.setDownBars(new AscFormat.CSpPr()); var parsedHeaders = chartSeries.parsedHeaders; for(var i = 0; i < asc_series.length; ++i) { var series = new AscFormat.CLineSeries(); series.setIdx(i); series.setOrder(i); series.setMarker(new AscFormat.CMarker()); series.setSpPr(new AscFormat.CSpPr()); series.spPr.setLn(new AscFormat.CLn()); series.spPr.ln.setW(28575); series.spPr.ln.setFill(CreateNoFillUniFill()); series.marker.setSymbol(AscFormat.SYMBOL_NONE); series.setSmooth(false); series.setVal(new AscFormat.CYVal()); var val = series.val; FillValNum(val, asc_series[i].Val, bUseCache); if((parsedHeaders.bTop && !bInCols || bInCols && parsedHeaders.bLeft)) { series.setCat(new AscFormat.CCat()); var cat = series.cat; if(typeof asc_series[i].Cat.formatCode === "string" && asc_series[i].Cat.formatCode.length > 0) { cat.setNumRef(new AscFormat.CNumRef()); var num_ref = cat.numRef; num_ref.setF(asc_series[i].Cat.Formula); if(bUseCache) { num_ref.setNumCache(new AscFormat.CNumLit()); var num_cache = num_ref.numCache; var cat_num_cache = asc_series[i].Cat.NumCache; num_cache.setPtCount(cat_num_cache.length); num_cache.setFormatCode(asc_series[i].Cat.formatCode); for(var j= 0; j < cat_num_cache.length; ++j) { var pt = new AscFormat.CNumericPoint(); pt.setIdx(j); pt.setVal(cat_num_cache[j].val); if(cat_num_cache[j].numFormatStr !== asc_series[i].Cat.formatCode) { pt.setFormatCode(cat_num_cache[j].numFormatStr); } num_cache.addPt(pt); } } } else { FillCatStr(cat, asc_series[i].Cat, bUseCache); } } if((parsedHeaders.bLeft && !bInCols || bInCols && parsedHeaders.bTop) && asc_series[i].TxCache && typeof asc_series[i].TxCache.Formula === "string" && asc_series[i].TxCache.Formula.length > 0) { FillSeriesTx(series, asc_series[i].TxCache, bUseCache); } line_chart.addSer(series); } cat_ax.setScaling(new AscFormat.CScaling()); cat_ax.setDelete(false); cat_ax.setAxPos(AscFormat.AX_POS_B); cat_ax.setMajorTickMark(c_oAscTickMark.TICK_MARK_OUT); cat_ax.setMinorTickMark(c_oAscTickMark.TICK_MARK_OUT); cat_ax.setTickLblPos(c_oAscTickLabelsPos.TICK_LABEL_POSITION_NEXT_TO); cat_ax.setCrosses(AscFormat.CROSSES_AUTO_ZERO); cat_ax.setAuto(true); cat_ax.setLblAlgn(AscFormat.LBL_ALG_CTR); cat_ax.setLblOffset(100); cat_ax.setNoMultiLvlLbl(false); var scaling = cat_ax.scaling; scaling.setOrientation(AscFormat.ORIENTATION_MIN_MAX); val_ax.setScaling(new AscFormat.CScaling()); val_ax.setDelete(false); val_ax.setAxPos(AscFormat.AX_POS_L); val_ax.setMajorGridlines(new AscFormat.CSpPr()); val_ax.setNumFmt(new AscFormat.CNumFmt()); val_ax.setMajorTickMark(c_oAscTickMark.TICK_MARK_OUT); val_ax.setMinorTickMark(c_oAscTickMark.TICK_MARK_NONE); val_ax.setTickLblPos(c_oAscTickLabelsPos.TICK_LABEL_POSITION_NEXT_TO); val_ax.setCrosses(AscFormat.CROSSES_AUTO_ZERO); val_ax.setCrossBetween(AscFormat.CROSS_BETWEEN_BETWEEN); scaling = val_ax.scaling; scaling.setOrientation(AscFormat.ORIENTATION_MIN_MAX); var num_fmt = val_ax.numFmt; var format_code; format_code = GetNumFormatFromSeries(asc_series); num_fmt.setFormatCode(format_code); num_fmt.setSourceLinked(true); var legend = chart.legend; legend.setLegendPos(c_oAscChartLegendShowSettings.right); legend.setLayout(new AscFormat.CLayout()); legend.setOverlay(false); var print_settings = chart_space.printSettings; print_settings.setHeaderFooter(new CHeaderFooterChart()); print_settings.setPageMargins(new CPageMarginsChart()); print_settings.setPageSetup(new CPageSetup()); var page_margins = print_settings.pageMargins; page_margins.setB(0.75); page_margins.setL(0.7); page_margins.setR(0.7); page_margins.setT(0.75); page_margins.setHeader(0.3); page_margins.setFooter(0.3); return chart_space; } function CreateSurfaceChart(chartSeries, bUseCache, oOptions, bContour, bWireFrame){ var asc_series = chartSeries.series; var oChartSpace = new AscFormat.CChartSpace(); oChartSpace.setDate1904(false); oChartSpace.setLang("en-Us"); oChartSpace.setRoundedCorners(false); oChartSpace.setStyle(2); oChartSpace.setChart(new AscFormat.CChart()); var oChart = oChartSpace.chart; oChart.setAutoTitleDeleted(false); var oView3D = new AscFormat.CView3d(); oChart.setView3D(oView3D); if(!bContour){ oView3D.setRotX(15); oView3D.setRotY(20); oView3D.setRAngAx(false); oView3D.setPerspective(30); } else{ oView3D.setRotX(90); oView3D.setRotY(0); oView3D.setRAngAx(false); oView3D.setPerspective(0); } oChart.setFloor(new AscFormat.CChartWall()); oChart.floor.setThickness(0); oChart.setSideWall(new AscFormat.CChartWall()); oChart.sideWall.setThickness(0); oChart.setBackWall(new AscFormat.CChartWall()); oChart.backWall.setThickness(0); oChart.setPlotArea(new AscFormat.CPlotArea()); oChart.plotArea.setLayout(new AscFormat.CLayout()); var oSurfaceChart; //if(bContour){ oSurfaceChart = new AscFormat.CSurfaceChart(); //} if(bWireFrame){ oSurfaceChart.setWireframe(true); } else{ oSurfaceChart.setWireframe(false); } oChart.plotArea.addChart(oSurfaceChart); var bInCols; if(isRealObject(oOptions)) { bInCols = oOptions.inColumns === true; } else { bInCols = false; } var parsedHeaders = chartSeries.parsedHeaders; for(var i = 0; i < asc_series.length; ++i) { var series = new AscFormat.CSurfaceSeries(); series.setIdx(i); series.setOrder(i); series.setVal(new AscFormat.CYVal()); FillValNum(series.val, asc_series[i].Val, bUseCache); if(parsedHeaders.bTop && !bInCols || bInCols && parsedHeaders.bLeft) { series.setCat(new AscFormat.CCat()); FillCatStr(series.cat, asc_series[i].Cat, bUseCache); } if((parsedHeaders.bLeft && !bInCols || bInCols && parsedHeaders.bTop) && asc_series[i].TxCache && typeof asc_series[i].TxCache.Formula === "string" && asc_series[i].TxCache.Formula.length > 0) { FillSeriesTx(series, asc_series[i].TxCache, bUseCache); } oSurfaceChart.addSer(series); } var oCatAx = new AscFormat.CCatAx(); oCatAx.setAxId(++AscFormat.Ax_Counter.GLOBAL_AX_ID_COUNTER); var oScaling = new AscFormat.CScaling(); oScaling.setOrientation(AscFormat.ORIENTATION_MIN_MAX); oCatAx.setScaling(oScaling); oCatAx.setDelete(false); oCatAx.setAxPos(AscFormat.AX_POS_B); oCatAx.setMajorTickMark(c_oAscTickMark.TICK_MARK_OUT); oCatAx.setMinorTickMark(c_oAscTickMark.TICK_MARK_NONE); oCatAx.setTickLblPos(c_oAscTickLabelsPos.TICK_LABEL_POSITION_NEXT_TO); oCatAx.setCrosses(AscFormat.CROSSES_AUTO_ZERO); oCatAx.setAuto(true); oCatAx.setLblAlgn(AscFormat.LBL_ALG_CTR); oCatAx.setLblOffset(100); oCatAx.setNoMultiLvlLbl(false); var oValAx = new AscFormat.CValAx(); oValAx.setAxId(++AscFormat.Ax_Counter.GLOBAL_AX_ID_COUNTER); var oValScaling = new AscFormat.CScaling(); oValScaling.setOrientation(AscFormat.ORIENTATION_MIN_MAX); oValAx.setScaling(oValScaling); oValAx.setDelete(false); oValAx.setAxPos(AscFormat.AX_POS_L); oValAx.setMajorGridlines(new AscFormat.CSpPr()); var oNumFmt = new AscFormat.CNumFmt(); oNumFmt.setFormatCode(GetNumFormatFromSeries(asc_series)); oNumFmt.setSourceLinked(true); oValAx.setNumFmt(oNumFmt); oValAx.setMajorTickMark(c_oAscTickMark.TICK_MARK_OUT); oValAx.setMinorTickMark(c_oAscTickMark.TICK_MARK_NONE); oValAx.setTickLblPos(c_oAscTickLabelsPos.TICK_LABEL_POSITION_NEXT_TO); oCatAx.setCrossAx(oValAx); oValAx.setCrossAx(oCatAx); oValAx.setCrosses(AscFormat.CROSSES_AUTO_ZERO); oValAx.setCrossBetween(AscFormat.CROSS_BETWEEN_MID_CAT); var oSerAx = new AscFormat.CSerAx(); oSerAx.setAxId(++AscFormat.Ax_Counter.GLOBAL_AX_ID_COUNTER); var oSerScaling = new AscFormat.CScaling(); oSerScaling.setOrientation(AscFormat.ORIENTATION_MIN_MAX); oSerAx.setScaling(oSerScaling); oSerAx.setDelete(false); oSerAx.setAxPos(AscFormat.AX_POS_B); oSerAx.setMajorTickMark(c_oAscTickMark.TICK_MARK_OUT); oSerAx.setMinorTickMark(c_oAscTickMark.TICK_MARK_NONE); oSerAx.setTickLblPos(c_oAscTickLabelsPos.TICK_LABEL_POSITION_NEXT_TO); oSerAx.setCrossAx(oCatAx); oSerAx.setCrosses(AscFormat.CROSSES_AUTO_ZERO); oChart.plotArea.addAxis(oCatAx); oChart.plotArea.addAxis(oValAx); oChart.plotArea.addAxis(oSerAx); oSurfaceChart.addAxId(oCatAx); oSurfaceChart.addAxId(oValAx); oSurfaceChart.addAxId(oSerAx); var oLegend = new AscFormat.CLegend(); oLegend.setLegendPos(c_oAscChartLegendShowSettings.right); oLegend.setLayout(new AscFormat.CLayout()); oLegend.setOverlay(false); //oLegend.setTxPr(AscFormat.CreateTextBodyFromString("", oDrawingDocument, oElement)); oChart.setLegend(oLegend); oChart.setPlotVisOnly(true); oChart.setDispBlanksAs(DISP_BLANKS_AS_ZERO); oChart.setShowDLblsOverMax(false); var oPrintSettings = new AscFormat.CPrintSettings(); oPrintSettings.setHeaderFooter(new AscFormat.CHeaderFooterChart()); var oPageMargins = new AscFormat.CPageMarginsChart(); oPageMargins.setB(0.75); oPageMargins.setL(0.7); oPageMargins.setR(0.7); oPageMargins.setT(0.75); oPageMargins.setHeader(0.3); oPageMargins.setFooter(0.3); oPrintSettings.setPageMargins(oPageMargins); oPrintSettings.setPageSetup(new AscFormat.CPageSetup()); oChartSpace.setPrintSettings(oPrintSettings); return oChartSpace; } function CreateDefaultAxises(valFormatCode) { var cat_ax = new AscFormat.CCatAx(); var val_ax = new AscFormat.CValAx(); cat_ax.setAxId(++Ax_Counter.GLOBAL_AX_ID_COUNTER); val_ax.setAxId(++Ax_Counter.GLOBAL_AX_ID_COUNTER); cat_ax.setCrossAx(val_ax); val_ax.setCrossAx(cat_ax); cat_ax.setScaling(new AscFormat.CScaling()); cat_ax.setDelete(false); cat_ax.setAxPos(AscFormat.AX_POS_B); cat_ax.setMajorTickMark(c_oAscTickMark.TICK_MARK_OUT); cat_ax.setMinorTickMark(c_oAscTickMark.TICK_MARK_NONE); cat_ax.setCrosses(AscFormat.CROSSES_AUTO_ZERO); cat_ax.setAuto(true); cat_ax.setLblAlgn(AscFormat.LBL_ALG_CTR); cat_ax.setLblOffset(100); cat_ax.setNoMultiLvlLbl(false); var scaling = cat_ax.scaling; scaling.setOrientation(AscFormat.ORIENTATION_MIN_MAX); val_ax.setScaling(new AscFormat.CScaling()); val_ax.setDelete(false); val_ax.setAxPos(AscFormat.AX_POS_L); val_ax.setMajorGridlines(new AscFormat.CSpPr()); val_ax.setNumFmt(new AscFormat.CNumFmt()); var num_fmt = val_ax.numFmt; num_fmt.setFormatCode(valFormatCode); num_fmt.setSourceLinked(true); val_ax.setMajorTickMark(c_oAscTickMark.TICK_MARK_OUT); val_ax.setMinorTickMark(c_oAscTickMark.TICK_MARK_NONE); val_ax.setTickLblPos(c_oAscTickLabelsPos.TICK_LABEL_POSITION_NEXT_TO); val_ax.setCrosses(AscFormat.CROSSES_AUTO_ZERO); val_ax.setCrossBetween(AscFormat.CROSS_BETWEEN_BETWEEN); scaling = val_ax.scaling; scaling.setOrientation(AscFormat.ORIENTATION_MIN_MAX); //cat_ax.setTitle(new CTitle()); //val_ax.setTitle(new CTitle()); // var title = val_ax.title; // title.setTxPr(new CTextBody()); // title.txPr.setBodyPr(new AscFormat.CBodyPr()); // title.txPr.bodyPr.setVert(AscFormat.nVertTTvert); return {valAx: val_ax, catAx: cat_ax}; } function CreateScatterAxis() { var cat_ax = new AscFormat.CValAx(); var val_ax = new AscFormat.CValAx(); cat_ax.setAxId(++Ax_Counter.GLOBAL_AX_ID_COUNTER); val_ax.setAxId(++Ax_Counter.GLOBAL_AX_ID_COUNTER); cat_ax.setCrossAx(val_ax); val_ax.setCrossAx(cat_ax); cat_ax.setScaling(new AscFormat.CScaling()); cat_ax.setDelete(false); cat_ax.setAxPos(AscFormat.AX_POS_B); cat_ax.setMajorTickMark(c_oAscTickMark.TICK_MARK_OUT); cat_ax.setMinorTickMark(c_oAscTickMark.TICK_MARK_NONE); cat_ax.setTickLblPos(c_oAscTickLabelsPos.TICK_LABEL_POSITION_NEXT_TO); cat_ax.setCrosses(AscFormat.CROSSES_AUTO_ZERO); cat_ax.scaling.setOrientation(AscFormat.ORIENTATION_MIN_MAX); val_ax.setScaling(new AscFormat.CScaling()); val_ax.setDelete(false); val_ax.setAxPos(AscFormat.AX_POS_L); val_ax.setMajorGridlines(new AscFormat.CSpPr()); val_ax.setNumFmt(new AscFormat.CNumFmt()); val_ax.setMajorTickMark(c_oAscTickMark.TICK_MARK_OUT); val_ax.setMinorTickMark(c_oAscTickMark.TICK_MARK_NONE); val_ax.setTickLblPos(c_oAscTickLabelsPos.TICK_LABEL_POSITION_NEXT_TO); val_ax.setCrosses(AscFormat.CROSSES_AUTO_ZERO); val_ax.setCrossBetween(AscFormat.CROSS_BETWEEN_BETWEEN); var scaling = val_ax.scaling; scaling.setOrientation(AscFormat.ORIENTATION_MIN_MAX); var num_fmt = val_ax.numFmt; var format_code = "General"; num_fmt.setFormatCode(format_code); num_fmt.setSourceLinked(true); return {valAx: val_ax, catAx: cat_ax}; } function fCheckNumFormatType(numFormatType){ return (numFormatType === c_oAscNumFormatType.Time || numFormatType === c_oAscNumFormatType.Date || numFormatType === c_oAscNumFormatType.Percent) } function parseSeriesHeaders (ws, rangeBBox) { var cntLeft = 0, cntTop = 0; var headers = { bLeft: false, bTop: false }; var i, cell, value, numFormatType, j; var bLeftOnlyDateTime = true, bTopOnlyDateTime = true; var nStartIndex; if (rangeBBox) { if (rangeBBox.c2 - rangeBBox.c1 > 0) { var nStartIndex = (rangeBBox.r1 === rangeBBox.r2) ? rangeBBox.r1 : (rangeBBox.r1 + 1); for (i = nStartIndex; i <= rangeBBox.r2; i++) { cell = ws.getCell3(i, rangeBBox.c1); value = cell.getValue(); numFormatType = cell.getNumFormatType(); if(!AscCommon.isNumber(value) && (value != "")) { bLeftOnlyDateTime = false; headers.bLeft = true; } else if(fCheckNumFormatType(numFormatType)) { headers.bLeft = true; } } } if (rangeBBox.r2 - rangeBBox.r1 > 0) { var nStartIndex = (rangeBBox.c1 === rangeBBox.c2) ? rangeBBox.c1 : (rangeBBox.c1 + 1); for (i = nStartIndex; i <= rangeBBox.c2; i++) { cell = ws.getCell3(rangeBBox.r1, i); value = cell.getValue(); numFormatType= cell.getNumFormatType(); if(!AscCommon.isNumber(value) && value != "") { bTopOnlyDateTime = false; headers.bTop = true; } else if(fCheckNumFormatType(numFormatType) ) { headers.bTop = true; } } } if(headers.bTop || headers.bLeft) { var nRowStart = headers.bTop ? rangeBBox.r1 + 1 : rangeBBox.r1, nColStart = headers.bLeft ? rangeBBox.c1 + 1 : rangeBBox.c1; for(i = nRowStart; i <= rangeBBox.r2; ++i) { for(j = nColStart; j <= rangeBBox.c2; ++j) { cell = ws.getCell3(i, j); value = cell.getValue(); numFormatType= cell.getNumFormatType(); if (!fCheckNumFormatType(numFormatType) && value !== "") { break; } } if(j <= rangeBBox.c2) { break; } } if(i === rangeBBox.r2 + 1) { if(headers.bLeft && bLeftOnlyDateTime) { headers.bLeft = false; } if(headers.bTop && bTopOnlyDateTime) { headers.bTop = false; } } } } else headers = { bLeft: true, bTop: true }; return headers; } function getChartSeries (worksheet, options, catHeadersBBox, serHeadersBBox) { var api = window["Asc"]["editor"]; var ws = null; var range = null; var result = parserHelp.parse3DRef(options.range); if (null !== result) { ws = worksheet.workbook.getWorksheetByName(result.sheet); if (ws) range = ws.getRange2(result.range); } if (null === range) return null; var bbox = range.getBBox0(); var nameIndex = 1; var i, series = []; function getNumCache(c1, c2, r1, r2) { // (c1 == c2) || (r1 == r2) var cache = [], cell, item; if ( c1 == c2 ) { // vertical cache for (var row = r1; row <= r2; row++) { cell = ws.getCell3(row, c1); item = {}; item.numFormatStr = cell.getNumFormatStr(); item.isDateTimeFormat = cell.getNumFormat().isDateTimeFormat(); item.val = cell.getValue(); item.isHidden = ws.getColHidden(c1) || ws.getRowHidden(row); cache.push(item); } } else /*r1 == r2*/ { // horizontal cache for (var col = c1; col <= c2; col++) { cell = ws.getCell3(r1, col, 0); item = {}; item.numFormatStr = cell.getNumFormatStr(); item.isDateTimeFormat = cell.getNumFormat().isDateTimeFormat(); item.val = cell.getValue(); item.isHidden = ws.getColHidden(col) || ws.getRowHidden(r1); cache.push(item); } } return cache; } var parsedHeaders = parseSeriesHeaders(ws, bbox); var data_bbox = {r1: bbox.r1, r2: bbox.r2, c1: bbox.c1, c2: bbox.c2}; if(parsedHeaders.bTop) { ++data_bbox.r1; } else { if(!options.getInColumns()) { if(catHeadersBBox && catHeadersBBox.c1 === data_bbox.c1 && catHeadersBBox.c2 === data_bbox.c2 && catHeadersBBox.r1 === catHeadersBBox.r2 && catHeadersBBox.r1 === data_bbox.r1) { ++data_bbox.r1; } } else { if(serHeadersBBox && serHeadersBBox.c1 === data_bbox.c1 && serHeadersBBox.c2 === data_bbox.c2 && serHeadersBBox.r1 === serHeadersBBox.r2 && serHeadersBBox.r1 === data_bbox.r1) { ++data_bbox.r1; } } } if(parsedHeaders.bLeft) { ++data_bbox.c1; } else { if(!options.getInColumns()) { if(serHeadersBBox && serHeadersBBox.c1 === serHeadersBBox.c2 && serHeadersBBox.r1 === data_bbox.r1 && serHeadersBBox.r2 === data_bbox.r2 && serHeadersBBox.c1 === data_bbox.c1) { ++data_bbox.c1; } } else { if(catHeadersBBox && catHeadersBBox.c1 === catHeadersBBox.c2 && catHeadersBBox.r1 === data_bbox.r1 && catHeadersBBox.r2 === data_bbox.r2 && catHeadersBBox.c1 === data_bbox.c1) { ++data_bbox.c1; } } } var bIsScatter = (Asc.c_oAscChartTypeSettings.scatter <= options.type && options.type <= Asc.c_oAscChartTypeSettings.scatterSmoothMarker); var top_header_bbox, left_header_bbox, ser, startCell, endCell, formulaCell, start, end, formula, numCache, sStartCellId, sEndCellId; if (!options.getInColumns()) { if(parsedHeaders.bTop) top_header_bbox = {r1: bbox.r1, c1: data_bbox.c1, r2: bbox.r1, c2: data_bbox.c2}; else if(catHeadersBBox && catHeadersBBox.c1 === data_bbox.c1 && catHeadersBBox.c2 === data_bbox.c2 && catHeadersBBox.r1 === catHeadersBBox.r2) top_header_bbox = {r1: catHeadersBBox.r1, c1: catHeadersBBox.c1, r2: catHeadersBBox.r1, c2:catHeadersBBox.c2}; if(parsedHeaders.bLeft) left_header_bbox = {r1: data_bbox.r1, r2: data_bbox.r2, c1: bbox.c1, c2: bbox.c1}; else if(serHeadersBBox && serHeadersBBox.c1 === serHeadersBBox.c2 && serHeadersBBox.r1 === data_bbox.r1 && serHeadersBBox.r2 === data_bbox.r2) left_header_bbox = {r1: serHeadersBBox.r1, c1: serHeadersBBox.c1, r2: serHeadersBBox.r1, c2: serHeadersBBox.c2}; for (i = data_bbox.r1; i <= data_bbox.r2; ++i) { ser = new AscFormat.asc_CChartSeria(); startCell = new CellAddress(i, data_bbox.c1, 0); endCell = new CellAddress(i, data_bbox.c2, 0); ser.isHidden = !!ws.getRowHidden(i); // Val sStartCellId = startCell.getIDAbsolute(); sEndCellId = endCell.getIDAbsolute(); ser.Val.Formula = parserHelp.get3DRef(ws.sName, sStartCellId === sEndCellId ? sStartCellId : sStartCellId + ':' + sEndCellId); ser.Val.NumCache = getNumCache(data_bbox.c1, data_bbox.c2, i, i); if(left_header_bbox) { formulaCell = new CellAddress( i, left_header_bbox.c1, 0 ); ser.TxCache.Formula = parserHelp.get3DRef(ws.sName, formulaCell.getIDAbsolute()); } // xVal if(top_header_bbox) { start = new CellAddress(top_header_bbox.r1, top_header_bbox.c1, 0); end = new CellAddress(top_header_bbox.r1, top_header_bbox.c2, 0); formula = parserHelp.get3DRef(ws.sName, start.getIDAbsolute() + ':' + end.getIDAbsolute()); numCache = getNumCache(top_header_bbox.c1, top_header_bbox.c2, top_header_bbox.r1, top_header_bbox.r1 ); if (bIsScatter) { ser.xVal.Formula = formula; ser.xVal.NumCache = numCache; } else { ser.Cat.Formula = formula; ser.Cat.NumCache = numCache; } } ser.TxCache.Tx = left_header_bbox ? (ws.getCell3(i, left_header_bbox.c1).getValue()) : (AscCommon.translateManager.getValue('Series') + " " + nameIndex); series.push(ser); nameIndex++; } } else { if(parsedHeaders.bTop) top_header_bbox = {r1: bbox.r1, c1: data_bbox.c1, r2: bbox.r1, c2: data_bbox.c2}; else if(serHeadersBBox && serHeadersBBox.r1 === serHeadersBBox.r2 && serHeadersBBox.c1 === data_bbox.c1 && serHeadersBBox.c2 === data_bbox.c2) top_header_bbox = {r1: serHeadersBBox.r1, c1: serHeadersBBox.c1, r2: serHeadersBBox.r2, c2: serHeadersBBox.c2}; if(parsedHeaders.bLeft) left_header_bbox = {r1: data_bbox.r1, c1: bbox.c1, r2: data_bbox.r2, c2: bbox.c1}; else if(catHeadersBBox && catHeadersBBox.c1 === catHeadersBBox.c2 && catHeadersBBox.r1 === data_bbox.r1 && catHeadersBBox.r2 === data_bbox.r2) left_header_bbox = {r1: catHeadersBBox.r1, c1: catHeadersBBox.c1, r2: catHeadersBBox.r2, c2: catHeadersBBox.c2}; for (i = data_bbox.c1; i <= data_bbox.c2; i++) { ser = new AscFormat.asc_CChartSeria(); startCell = new CellAddress(data_bbox.r1, i, 0); endCell = new CellAddress(data_bbox.r2, i, 0); ser.isHidden = !!ws.getColHidden(i); // Val sStartCellId = startCell.getIDAbsolute(); sEndCellId = endCell.getIDAbsolute(); if (sStartCellId == sEndCellId) ser.Val.Formula = parserHelp.get3DRef(ws.sName, sStartCellId); else ser.Val.Formula = parserHelp.get3DRef(ws.sName, sStartCellId + ':' + sEndCellId); ser.Val.NumCache = getNumCache(i, i, data_bbox.r1, bbox.r2); if ( left_header_bbox ) { start = new CellAddress(left_header_bbox.r1, left_header_bbox.c1, 0); end = new CellAddress(left_header_bbox.r2, left_header_bbox.c1, 0); formula = parserHelp.get3DRef(ws.sName, start.getIDAbsolute() + ':' + end.getIDAbsolute()); numCache = getNumCache( left_header_bbox.c1, left_header_bbox.c1, left_header_bbox.r1, left_header_bbox.r2 ); if (bIsScatter) { ser.xVal.Formula = formula; ser.xVal.NumCache = numCache; } else { ser.Cat.Formula = formula; ser.Cat.NumCache = numCache; } } if (top_header_bbox) { formulaCell = new CellAddress( top_header_bbox.r1, i, 0 ); ser.TxCache.Formula = parserHelp.get3DRef(ws.sName, formulaCell.getIDAbsolute()); } ser.TxCache.Tx = top_header_bbox ? (ws.getCell3(top_header_bbox.r1, i).getValue()) : (AscCommon.translateManager.getValue('Series') + " " + nameIndex); series.push(ser); nameIndex++; } } return {series: series, parsedHeaders: parsedHeaders}; } function checkSpPrRasterImages(spPr) { if(spPr && spPr.Fill && spPr.Fill && spPr.Fill.fill && spPr.Fill.fill.type === Asc.c_oAscFill.FILL_TYPE_BLIP) { var copyBlipFill = spPr.Fill.createDuplicate(); copyBlipFill.fill.setRasterImageId(spPr.Fill.fill.RasterImageId); spPr.setFill(copyBlipFill); } } function checkBlipFillRasterImages(sp) { switch (sp.getObjectType()) { case AscDFH.historyitem_type_Shape: { checkSpPrRasterImages(sp.spPr); break; } case AscDFH.historyitem_type_ImageShape: case AscDFH.historyitem_type_OleObject: { if(sp.blipFill) { var newBlipFill = sp.blipFill.createDuplicate(); newBlipFill.setRasterImageId(sp.blipFill.RasterImageId); sp.setBlipFill(newBlipFill); } break; } case AscDFH.historyitem_type_ChartSpace: { checkSpPrRasterImages(sp.spPr); var chart = sp.chart; if(chart) { chart.backWall && checkSpPrRasterImages(chart.backWall.spPr); chart.floor && checkSpPrRasterImages(chart.floor.spPr); chart.legend && checkSpPrRasterImages(chart.legend.spPr); chart.sideWall && checkSpPrRasterImages(chart.sideWall.spPr); chart.title && checkSpPrRasterImages(chart.title.spPr); //plotArea var plot_area = sp.chart.plotArea; if(plot_area) { checkSpPrRasterImages(plot_area.spPr); for(var j = 0; j < plot_area.axId.length; ++j) { var axis = plot_area.axId[j]; if(axis) { checkSpPrRasterImages(axis.spPr); axis.title && axis.title && checkSpPrRasterImages(axis.title.spPr); } } for(j = 0; j < plot_area.charts.length; ++j) { plot_area.charts[j].checkSpPrRasterImages(); } } } break; } case AscDFH.historyitem_type_GroupShape: { for(var i = 0; i < sp.spTree.length; ++i) { checkBlipFillRasterImages(sp.spTree[i]); } break; } case AscDFH.historyitem_type_GraphicFrame: { break; } } } function initStyleManager() { CHART_STYLE_MANAGER.init(); } //--------------------------------------------------------export---------------------------------------------------- window['AscFormat'] = window['AscFormat'] || {}; window['AscFormat'].BAR_SHAPE_CONE = BAR_SHAPE_CONE; window['AscFormat'].BAR_SHAPE_CONETOMAX = BAR_SHAPE_CONETOMAX; window['AscFormat'].BAR_SHAPE_BOX = BAR_SHAPE_BOX; window['AscFormat'].BAR_SHAPE_CYLINDER = BAR_SHAPE_CYLINDER; window['AscFormat'].BAR_SHAPE_PYRAMID = BAR_SHAPE_PYRAMID; window['AscFormat'].BAR_SHAPE_PYRAMIDTOMAX = BAR_SHAPE_PYRAMIDTOMAX; window['AscFormat'].DISP_BLANKS_AS_GAP = DISP_BLANKS_AS_GAP; window['AscFormat'].DISP_BLANKS_AS_SPAN = DISP_BLANKS_AS_SPAN; window['AscFormat'].DISP_BLANKS_AS_ZERO = DISP_BLANKS_AS_ZERO; window['AscFormat'].checkBlackUnifill = checkBlackUnifill; window['AscFormat'].BBoxInfo = BBoxInfo; window['AscFormat'].CreateUnifillSolidFillSchemeColorByIndex = CreateUnifillSolidFillSchemeColorByIndex; window['AscFormat'].CreateUniFillSchemeColorWidthTint = CreateUniFillSchemeColorWidthTint; window['AscFormat'].G_O_VISITED_HLINK_COLOR = G_O_VISITED_HLINK_COLOR; window['AscFormat'].G_O_HLINK_COLOR = G_O_HLINK_COLOR; window['AscFormat'].G_O_NO_ACTIVE_COMMENT_BRUSH = G_O_NO_ACTIVE_COMMENT_BRUSH; window['AscFormat'].G_O_ACTIVE_COMMENT_BRUSH = G_O_ACTIVE_COMMENT_BRUSH; window['AscFormat'].CChartSpace = CChartSpace; window['AscFormat'].getPtsFromSeries = getPtsFromSeries; window['AscFormat'].CreateUnfilFromRGB = CreateUnfilFromRGB; window['AscFormat'].CreateUniFillSolidFillWidthTintOrShade = CreateUniFillSolidFillWidthTintOrShade; window['AscFormat'].CreateUnifillSolidFillSchemeColor = CreateUnifillSolidFillSchemeColor; window['AscFormat'].CreateNoFillLine = CreateNoFillLine; window['AscFormat'].CreateNoFillUniFill = CreateNoFillUniFill; window['AscFormat'].CExternalData = CExternalData; window['AscFormat'].CPivotSource = CPivotSource; window['AscFormat'].CProtection = CProtection; window['AscFormat'].CPrintSettings = CPrintSettings; window['AscFormat'].CHeaderFooterChart = CHeaderFooterChart; window['AscFormat'].CPageMarginsChart = CPageMarginsChart; window['AscFormat'].CPageSetup = CPageSetup; window['AscFormat'].CreateView3d = CreateView3d; window['AscFormat'].CreateLineChart = CreateLineChart; window['AscFormat'].CreateBarChart = CreateBarChart; window['AscFormat'].CreateHBarChart = CreateHBarChart; window['AscFormat'].CreateAreaChart = CreateAreaChart; window['AscFormat'].CreatePieChart = CreatePieChart; window['AscFormat'].CreateScatterChart = CreateScatterChart; window['AscFormat'].CreateStockChart = CreateStockChart; window['AscFormat'].CreateDefaultAxises = CreateDefaultAxises; window['AscFormat'].CreateScatterAxis = CreateScatterAxis; window['AscFormat'].getChartSeries = getChartSeries; window['AscFormat'].checkSpPrRasterImages = checkSpPrRasterImages; window['AscFormat'].checkBlipFillRasterImages = checkBlipFillRasterImages; window['AscFormat'].PAGE_SETUP_ORIENTATION_DEFAULT = 0; window['AscFormat'].PAGE_SETUP_ORIENTATION_LANDSCAPE = 1; window['AscFormat'].PAGE_SETUP_ORIENTATION_PORTRAIT = 2; window['AscFormat'].initStyleManager = initStyleManager; window['AscFormat'].CHART_STYLE_MANAGER = CHART_STYLE_MANAGER; window['AscFormat'].CheckParagraphTextPr = CheckParagraphTextPr; window['AscFormat'].CheckObjectTextPr = CheckObjectTextPr; window['AscFormat'].CreateColorMapByIndex = CreateColorMapByIndex; window['AscFormat'].getArrayFillsFromBase = getArrayFillsFromBase; window['AscFormat'].getMaxIdx = getMaxIdx; window['AscFormat'].CreateSurfaceChart = CreateSurfaceChart; })(window);
[charts] Add bNotRecalculate flag
common/Drawings/Format/ChartSpace.js
[charts] Add bNotRecalculate flag
<ide><path>ommon/Drawings/Format/ChartSpace.js <ide> } <ide> if(!this.chartObj) <ide> this.chartObj = new AscFormat.CChartsDrawer(); <del> var oChartSize = this.chartObj.calculateSizePlotArea(this); <add> var oChartSize = this.chartObj.calculateSizePlotArea(this, bNotRecalculate); <ide> var oLayout = this.chart.plotArea.layout; <ide> if(oLayout){ <ide>
Java
apache-2.0
4f3f1dc28e7c4902e1886cdb852854f12afea246
0
EBISPOT/goci,EBISPOT/goci,EBISPOT/goci,EBISPOT/goci,EBISPOT/goci,EBISPOT/goci
package uk.ac.ebi.spot.goci.curation.service; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import org.springframework.validation.BindingResult; import uk.ac.ebi.spot.goci.curation.model.AssociationValidationView; import uk.ac.ebi.spot.goci.curation.model.LastViewedAssociation; import uk.ac.ebi.spot.goci.curation.model.MappingDetails; import uk.ac.ebi.spot.goci.curation.model.SnpAssociationForm; import uk.ac.ebi.spot.goci.curation.model.SnpAssociationInteractionForm; import uk.ac.ebi.spot.goci.curation.model.SnpAssociationStandardMultiForm; import uk.ac.ebi.spot.goci.curation.model.SnpFormColumn; import uk.ac.ebi.spot.goci.curation.model.SnpFormRow; import uk.ac.ebi.spot.goci.curation.validator.SnpFormColumnValidator; import uk.ac.ebi.spot.goci.curation.validator.SnpFormRowValidator; import uk.ac.ebi.spot.goci.exception.EnsemblMappingException; import uk.ac.ebi.spot.goci.model.Association; import uk.ac.ebi.spot.goci.model.AssociationReport; import uk.ac.ebi.spot.goci.model.AssociationValidationReport; import uk.ac.ebi.spot.goci.model.Curator; import uk.ac.ebi.spot.goci.model.Gene; import uk.ac.ebi.spot.goci.model.Locus; import uk.ac.ebi.spot.goci.model.RiskAllele; import uk.ac.ebi.spot.goci.model.Study; import uk.ac.ebi.spot.goci.model.ValidationError; import uk.ac.ebi.spot.goci.repository.AssociationReportRepository; import uk.ac.ebi.spot.goci.repository.AssociationRepository; import uk.ac.ebi.spot.goci.repository.AssociationValidationReportRepository; import uk.ac.ebi.spot.goci.repository.LocusRepository; import uk.ac.ebi.spot.goci.service.MappingService; import uk.ac.ebi.spot.goci.service.ValidationService; import java.util.ArrayList; import java.util.Collection; import java.util.Date; import java.util.List; /** * Created by emma on 03/03/2016. * * @author emma * <p> * Service class that handles common operations performed on associations */ @Service public class AssociationOperationsService { private SingleSnpMultiSnpAssociationService singleSnpMultiSnpAssociationService; private SnpInteractionAssociationService snpInteractionAssociationService; private AssociationReportRepository associationReportRepository; private AssociationRepository associationRepository; private LocusRepository locusRepository; private AssociationValidationReportRepository associationValidationReportRepository; // Validators private SnpFormRowValidator snpFormRowValidator; private SnpFormColumnValidator snpFormColumnValidator; private MappingService mappingService; private LociAttributesService lociAttributesService; private ValidationService validationService; @Autowired public AssociationOperationsService(SingleSnpMultiSnpAssociationService singleSnpMultiSnpAssociationService, SnpInteractionAssociationService snpInteractionAssociationService, AssociationReportRepository associationReportRepository, AssociationRepository associationRepository, LocusRepository locusRepository, AssociationValidationReportRepository associationValidationReportRepository, SnpFormRowValidator snpFormRowValidator, SnpFormColumnValidator snpFormColumnValidator, MappingService mappingService, LociAttributesService lociAttributesService, ValidationService validationService) { this.singleSnpMultiSnpAssociationService = singleSnpMultiSnpAssociationService; this.snpInteractionAssociationService = snpInteractionAssociationService; this.associationReportRepository = associationReportRepository; this.associationRepository = associationRepository; this.locusRepository = locusRepository; this.associationValidationReportRepository = associationValidationReportRepository; this.snpFormRowValidator = snpFormRowValidator; this.snpFormColumnValidator = snpFormColumnValidator; this.mappingService = mappingService; this.lociAttributesService = lociAttributesService; this.validationService = validationService; } /** * Save association created from details on webform * * @param study Study to assign association to * @param association Association to validate and save */ public Collection<AssociationValidationView> saveAssociationCreatedFromForm(Study study, Association association) throws EnsemblMappingException { // Validate association Collection<ValidationError> associationValidationErrors = validationService.runAssociationValidation(association, "full"); // Create errors view that will be returned via controller Collection<AssociationValidationView> associationValidationViews = processAssociationValidationErrors(associationValidationErrors); // Validation returns warnings and errors, errors prevent a save action long errorCount = associationValidationErrors.parallelStream() .filter(validationError -> !validationError.getWarning()) .count(); if (errorCount == 0) { savAssociation(association, study, associationValidationErrors); } return associationValidationViews; } /** * Save edited association * * @param study Study to assign association to * @param association Association to validate and save * @param associationId existing association Id */ public Collection<AssociationValidationView> saveEditedAssociationFromForm(Study study, Association association, Long associationId) throws EnsemblMappingException { // Validate association Collection<ValidationError> associationValidationErrors = validationService.runAssociationValidation(association, "full"); // Create errors view that will be returned via controller Collection<AssociationValidationView> associationValidationViews = processAssociationValidationErrors(associationValidationErrors); // Validation returns warnings and errors, errors prevent a save action long errorCount = associationValidationErrors.parallelStream() .filter(validationError -> !validationError.getWarning()) .count(); if (errorCount == 0) { // Set ID of new association to the ID of the association we're currently editing association.setId(associationId); // Check for existing loci, when editing delete any existing loci and risk alleles // They will be recreated as part of the save method Association associationUserIsEditing = associationRepository.findOne(associationId); Collection<Locus> associationLoci = associationUserIsEditing.getLoci(); Collection<RiskAllele> existingRiskAlleles = new ArrayList<>(); if (associationLoci != null) { for (Locus locus : associationLoci) { existingRiskAlleles.addAll(locus.getStrongestRiskAlleles()); } for (Locus locus : associationLoci) { lociAttributesService.deleteLocus(locus); } for (RiskAllele existingRiskAllele : existingRiskAlleles) { lociAttributesService.deleteRiskAllele(existingRiskAllele); } } savAssociation(association, study, associationValidationErrors); } return associationValidationViews; } public void savAssociation(Association association, Study study, Collection<ValidationError> errors) throws EnsemblMappingException { association.getLoci().forEach(this::saveLocusAttributes); // Set the study ID for our association association.setStudy(study); // Save our association information association.setLastUpdateDate(new Date()); associationRepository.save(association); createAssociationValidationReport(errors, association.getId()); // Run mapping on association runMapping(study.getHousekeeping().getCurator(), association); } private void createAssociationValidationReport(Collection<ValidationError> errors, Long id) { Association association = associationRepository.findOne(id); errors.forEach(validationError -> { AssociationValidationReport associationValidationReport = new AssociationValidationReport(validationError.getError(), validationError.getField(), false, association); // save validation report associationValidationReportRepository.save(associationValidationReport); }); } private void runMapping(Curator curator, Association association) throws EnsemblMappingException { mappingService.validateAndMapAssociation(association, curator.getLastName()); } /** * Save transient objects on association before saving association * * @param locus Locus to save */ private void saveLocusAttributes(Locus locus) { // Save genes Collection<Gene> savedGenes = lociAttributesService.saveGene(locus.getAuthorReportedGenes()); locus.setAuthorReportedGenes(savedGenes); // Save risk allele Collection<RiskAllele> savedRiskAlleles = lociAttributesService.saveRiskAlleles(locus.getStrongestRiskAlleles()); locus.setStrongestRiskAlleles(savedRiskAlleles); locusRepository.save(locus); } /** * Check if association is an OR or BETA type association * * @param association Association to check */ public String determineIfAssociationIsOrType(Association association) { String measurementType = "none"; if (association.getBetaNum() != null) { measurementType = "beta"; } else { if (association.getOrPerCopyNum() != null) { measurementType = "or"; } } return measurementType; } /** * Generate a the correct form type from association details * * @param association Association to create form from */ public SnpAssociationForm generateForm(Association association) { if (association.getSnpInteraction() != null && association.getSnpInteraction()) { return createForm(association, snpInteractionAssociationService); } else { return createForm(association, singleSnpMultiSnpAssociationService); } } /** * Create a form from association details * * @param association Association to create form from * @param service Service to create form */ private SnpAssociationForm createForm(Association association, SnpAssociationFormService service) { return service.createForm(association); } /** * Gather mapping details for an association * * @param association Association with mapping details */ public MappingDetails createMappingDetails(Association association) { MappingDetails mappingDetails = new MappingDetails(); mappingDetails.setPerformer(association.getLastMappingPerformedBy()); mappingDetails.setMappingDate(association.getLastMappingDate()); return mappingDetails; } /** * Mark errors for a particular association as checked, this involves updating the linked association report * * @param association Association to mark as errors checked */ public void associationErrorsChecked(Association association) { AssociationReport associationReport = association.getAssociationReport(); associationReport.setErrorCheckedByCurator(true); associationReport.setLastUpdateDate(new Date()); associationReportRepository.save(associationReport); } /** * Mark errors for a particular association as unchecked, this involves updating the linked association report * * @param association Association to mark as errors unchecked */ public void associationErrorsUnchecked(Association association) { AssociationReport associationReport = association.getAssociationReport(); associationReport.setErrorCheckedByCurator(false); associationReport.setLastUpdateDate(new Date()); associationReportRepository.save(associationReport); } /** * Determine last viewed association * * @param associationId ID of association last viewed */ public LastViewedAssociation getLastViewedAssociation(Long associationId) { LastViewedAssociation lastViewedAssociation = new LastViewedAssociation(); if (associationId != null) { lastViewedAssociation.setId(associationId); } return lastViewedAssociation; } /** * Check a standard SNP association form for errors * * @param result Binding result from edit form * @param form The form to validate */ public Boolean checkSnpAssociationFormErrors(BindingResult result, SnpAssociationStandardMultiForm form) { for (SnpFormRow row : form.getSnpFormRows()) { snpFormRowValidator.validate(row, result); } return result.hasErrors(); } /** * Check a SNP association interaction form for errors * * @param result Binding result from edit form * @param form The form to validate */ public Boolean checkSnpAssociationInteractionFormErrors(BindingResult result, SnpAssociationInteractionForm form) { for (SnpFormColumn column : form.getSnpFormColumns()) { snpFormColumnValidator.validate(column, result); } return result.hasErrors(); } /** * Retrieve validation warnings for an association and return this is a structure accessible by view * * @param associationId ID of association to get warning for */ public List<AssociationValidationView> getAssociationWarnings(Long associationId) { List<AssociationValidationView> associationValidationViews = new ArrayList<>(); associationValidationReportRepository.findByAssociationId(associationId) .forEach(associationValidationReport -> { associationValidationViews.add(new AssociationValidationView(associationValidationReport.getValidatedField(), associationValidationReport.getWarning(), true)); }); return associationValidationViews; } /** * Retrieve validation warnings for an association and return this is a structure accessible by view * * @param errors List of validation errors to process */ private List<AssociationValidationView> processAssociationValidationErrors(Collection<ValidationError> errors) { List<AssociationValidationView> associationValidationViews = new ArrayList<>(); errors.forEach(validationError -> { associationValidationViews.add(new AssociationValidationView(validationError.getField(), validationError.getError(), validationError.getWarning())); }); return associationValidationViews; } }
goci-interfaces/goci-curation/src/main/java/uk/ac/ebi/spot/goci/curation/service/AssociationOperationsService.java
package uk.ac.ebi.spot.goci.curation.service; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import org.springframework.validation.BindingResult; import uk.ac.ebi.spot.goci.curation.model.AssociationValidationView; import uk.ac.ebi.spot.goci.curation.model.LastViewedAssociation; import uk.ac.ebi.spot.goci.curation.model.MappingDetails; import uk.ac.ebi.spot.goci.curation.model.SnpAssociationForm; import uk.ac.ebi.spot.goci.curation.model.SnpAssociationInteractionForm; import uk.ac.ebi.spot.goci.curation.model.SnpAssociationStandardMultiForm; import uk.ac.ebi.spot.goci.curation.model.SnpFormColumn; import uk.ac.ebi.spot.goci.curation.model.SnpFormRow; import uk.ac.ebi.spot.goci.curation.validator.SnpFormColumnValidator; import uk.ac.ebi.spot.goci.curation.validator.SnpFormRowValidator; import uk.ac.ebi.spot.goci.exception.EnsemblMappingException; import uk.ac.ebi.spot.goci.model.Association; import uk.ac.ebi.spot.goci.model.AssociationReport; import uk.ac.ebi.spot.goci.model.AssociationValidationReport; import uk.ac.ebi.spot.goci.model.Curator; import uk.ac.ebi.spot.goci.model.Gene; import uk.ac.ebi.spot.goci.model.Locus; import uk.ac.ebi.spot.goci.model.RiskAllele; import uk.ac.ebi.spot.goci.model.Study; import uk.ac.ebi.spot.goci.model.ValidationError; import uk.ac.ebi.spot.goci.repository.AssociationReportRepository; import uk.ac.ebi.spot.goci.repository.AssociationRepository; import uk.ac.ebi.spot.goci.repository.AssociationValidationReportRepository; import uk.ac.ebi.spot.goci.repository.LocusRepository; import uk.ac.ebi.spot.goci.service.MappingService; import uk.ac.ebi.spot.goci.service.ValidationService; import java.util.ArrayList; import java.util.Collection; import java.util.Date; import java.util.List; /** * Created by emma on 03/03/2016. * * @author emma * <p> * Service class that handles common operations performed on associations */ @Service public class AssociationOperationsService { private SingleSnpMultiSnpAssociationService singleSnpMultiSnpAssociationService; private SnpInteractionAssociationService snpInteractionAssociationService; private AssociationReportRepository associationReportRepository; private AssociationRepository associationRepository; private LocusRepository locusRepository; private AssociationValidationReportRepository associationValidationReportRepository; // Validators private SnpFormRowValidator snpFormRowValidator; private SnpFormColumnValidator snpFormColumnValidator; private MappingService mappingService; private LociAttributesService lociAttributesService; private ValidationService validationService; @Autowired public AssociationOperationsService(SingleSnpMultiSnpAssociationService singleSnpMultiSnpAssociationService, SnpInteractionAssociationService snpInteractionAssociationService, AssociationReportRepository associationReportRepository, AssociationRepository associationRepository, LocusRepository locusRepository, AssociationValidationReportRepository associationValidationReportRepository, SnpFormRowValidator snpFormRowValidator, SnpFormColumnValidator snpFormColumnValidator, MappingService mappingService, LociAttributesService lociAttributesService, ValidationService validationService) { this.singleSnpMultiSnpAssociationService = singleSnpMultiSnpAssociationService; this.snpInteractionAssociationService = snpInteractionAssociationService; this.associationReportRepository = associationReportRepository; this.associationRepository = associationRepository; this.locusRepository = locusRepository; this.associationValidationReportRepository = associationValidationReportRepository; this.snpFormRowValidator = snpFormRowValidator; this.snpFormColumnValidator = snpFormColumnValidator; this.mappingService = mappingService; this.lociAttributesService = lociAttributesService; this.validationService = validationService; } /** * Save association created from details on webform * * @param study Study to assign association to * @param association Association to validate and save */ public Collection<AssociationValidationView> saveAssociationCreatedFromForm(Study study, Association association) throws EnsemblMappingException { // Validate association Collection<ValidationError> associationValidationErrors = validationService.runAssociationValidation(association, "full"); // Create errors view that will be returned via controller Collection<AssociationValidationView> associationValidationViews = processAssociationValidationErrors(associationValidationErrors); // Validation returns warnings and errors, errors prevent a save action long errorCount = associationValidationErrors.parallelStream() .filter(validationError -> !validationError.getWarning()) .count(); if (errorCount == 0) { savAssociation(association, study, associationValidationErrors); } return associationValidationViews; } /** * Save edited association * * @param study Study to assign association to * @param association Association to validate and save * @param associationId existing association Id */ public Collection<AssociationValidationView> saveEditedAssociationFromForm(Study study, Association association, Long associationId) throws EnsemblMappingException { // Validate association Collection<ValidationError> associationValidationErrors = validationService.runAssociationValidation(association, "full"); // Create errors view that will be returned via controller Collection<AssociationValidationView> associationValidationViews = processAssociationValidationErrors(associationValidationErrors); // Validation returns warnings and errors, errors prevent a save action long errorCount = associationValidationErrors.parallelStream() .filter(validationError -> !validationError.getWarning()) .count(); if (errorCount == 0) { // Set ID of new association to the ID of the association we're currently editing association.setId(associationId); savAssociation(association, study, associationValidationErrors); } return associationValidationViews; } public void savAssociation(Association association, Study study, Collection<ValidationError> errors) throws EnsemblMappingException { association.getLoci().forEach(this::saveLocusAttributes); // Set the study ID for our association association.setStudy(study); // Save our association information association.setLastUpdateDate(new Date()); associationRepository.save(association); createAssociationValidationReport(errors, association.getId()); // Run mapping on association runMapping(study.getHousekeeping().getCurator(), association); } private void createAssociationValidationReport(Collection<ValidationError> errors, Long id) { Association association = associationRepository.findOne(id); errors.forEach(validationError -> { AssociationValidationReport associationValidationReport = new AssociationValidationReport(validationError.getError(), validationError.getField(), false, association); // save validation report associationValidationReportRepository.save(associationValidationReport); }); } private void runMapping(Curator curator, Association association) throws EnsemblMappingException { mappingService.validateAndMapAssociation(association, curator.getLastName()); } /** * Save transient objects on association before saving association * * @param locus Locus to save */ private void saveLocusAttributes(Locus locus) { // Save genes Collection<Gene> savedGenes = lociAttributesService.saveGene(locus.getAuthorReportedGenes()); locus.setAuthorReportedGenes(savedGenes); // Save risk allele Collection<RiskAllele> savedRiskAlleles = lociAttributesService.saveRiskAlleles(locus.getStrongestRiskAlleles()); locus.setStrongestRiskAlleles(savedRiskAlleles); locusRepository.save(locus); } /** * Check if association is an OR or BETA type association * * @param association Association to check */ public String determineIfAssociationIsOrType(Association association) { String measurementType = "none"; if (association.getBetaNum() != null) { measurementType = "beta"; } else { if (association.getOrPerCopyNum() != null) { measurementType = "or"; } } return measurementType; } /** * Generate a the correct form type from association details * * @param association Association to create form from */ public SnpAssociationForm generateForm(Association association) { if (association.getSnpInteraction() != null && association.getSnpInteraction()) { return createForm(association, snpInteractionAssociationService); } else { return createForm(association, singleSnpMultiSnpAssociationService); } } /** * Create a form from association details * * @param association Association to create form from * @param service Service to create form */ private SnpAssociationForm createForm(Association association, SnpAssociationFormService service) { return service.createForm(association); } /** * Gather mapping details for an association * * @param association Association with mapping details */ public MappingDetails createMappingDetails(Association association) { MappingDetails mappingDetails = new MappingDetails(); mappingDetails.setPerformer(association.getLastMappingPerformedBy()); mappingDetails.setMappingDate(association.getLastMappingDate()); return mappingDetails; } /** * Mark errors for a particular association as checked, this involves updating the linked association report * * @param association Association to mark as errors checked */ public void associationErrorsChecked(Association association) { AssociationReport associationReport = association.getAssociationReport(); associationReport.setErrorCheckedByCurator(true); associationReport.setLastUpdateDate(new Date()); associationReportRepository.save(associationReport); } /** * Mark errors for a particular association as unchecked, this involves updating the linked association report * * @param association Association to mark as errors unchecked */ public void associationErrorsUnchecked(Association association) { AssociationReport associationReport = association.getAssociationReport(); associationReport.setErrorCheckedByCurator(false); associationReport.setLastUpdateDate(new Date()); associationReportRepository.save(associationReport); } /** * Determine last viewed association * * @param associationId ID of association last viewed */ public LastViewedAssociation getLastViewedAssociation(Long associationId) { LastViewedAssociation lastViewedAssociation = new LastViewedAssociation(); if (associationId != null) { lastViewedAssociation.setId(associationId); } return lastViewedAssociation; } /** * Check a standard SNP association form for errors * * @param result Binding result from edit form * @param form The form to validate */ public Boolean checkSnpAssociationFormErrors(BindingResult result, SnpAssociationStandardMultiForm form) { for (SnpFormRow row : form.getSnpFormRows()) { snpFormRowValidator.validate(row, result); } return result.hasErrors(); } /** * Check a SNP association interaction form for errors * * @param result Binding result from edit form * @param form The form to validate */ public Boolean checkSnpAssociationInteractionFormErrors(BindingResult result, SnpAssociationInteractionForm form) { for (SnpFormColumn column : form.getSnpFormColumns()) { snpFormColumnValidator.validate(column, result); } return result.hasErrors(); } /** * Retrieve validation warnings for an association and return this is a structure accessible by view * * @param associationId ID of association to get warning for */ public List<AssociationValidationView> getAssociationWarnings(Long associationId) { List<AssociationValidationView> associationValidationViews = new ArrayList<>(); associationValidationReportRepository.findByAssociationId(associationId) .forEach(associationValidationReport -> { associationValidationViews.add(new AssociationValidationView(associationValidationReport.getValidatedField(), associationValidationReport.getWarning(), true)); }); return associationValidationViews; } /** * Retrieve validation warnings for an association and return this is a structure accessible by view * * @param errors List of validation errors to process */ private List<AssociationValidationView> processAssociationValidationErrors(Collection<ValidationError> errors) { List<AssociationValidationView> associationValidationViews = new ArrayList<>(); errors.forEach(validationError -> { associationValidationViews.add(new AssociationValidationView(validationError.getField(), validationError.getError(), validationError.getWarning())); }); return associationValidationViews; } }
Added logic to delete existing locus and risk alleles
goci-interfaces/goci-curation/src/main/java/uk/ac/ebi/spot/goci/curation/service/AssociationOperationsService.java
Added logic to delete existing locus and risk alleles
<ide><path>oci-interfaces/goci-curation/src/main/java/uk/ac/ebi/spot/goci/curation/service/AssociationOperationsService.java <ide> if (errorCount == 0) { <ide> // Set ID of new association to the ID of the association we're currently editing <ide> association.setId(associationId); <add> <add> // Check for existing loci, when editing delete any existing loci and risk alleles <add> // They will be recreated as part of the save method <add> Association associationUserIsEditing = <add> associationRepository.findOne(associationId); <add> Collection<Locus> associationLoci = associationUserIsEditing.getLoci(); <add> Collection<RiskAllele> existingRiskAlleles = new ArrayList<>(); <add> <add> if (associationLoci != null) { <add> for (Locus locus : associationLoci) { <add> existingRiskAlleles.addAll(locus.getStrongestRiskAlleles()); <add> } <add> for (Locus locus : associationLoci) { <add> lociAttributesService.deleteLocus(locus); <add> } <add> for (RiskAllele existingRiskAllele : existingRiskAlleles) { <add> lociAttributesService.deleteRiskAllele(existingRiskAllele); <add> } <add> } <add> <ide> savAssociation(association, study, associationValidationErrors); <ide> } <ide> return associationValidationViews;
Java
mit
error: pathspec 'app/src/main/java/com/naijab/nextzytimeline/base/BaseMvpInterface.java' did not match any file(s) known to git
9e778cc71ff63a70f002bd9ceadc7bc099922e67
1
naijab/nextzytimeline,naijab/nextzytimeline
package com.naijab.nextzytimeline.base; /** * Created by Xiltron on 16/5/2560. */ public interface BaseMvpInterface { interface View { Presenter getPresenter(); } interface Presenter<V extends BaseMvpInterface.View> { void attachView(V mvpView); void detachView(); void onViewStart(); void onViewStop(); void onViewCreate(); void onViewDestroy(); } }
app/src/main/java/com/naijab/nextzytimeline/base/BaseMvpInterface.java
Add Base MVP Interface
app/src/main/java/com/naijab/nextzytimeline/base/BaseMvpInterface.java
Add Base MVP Interface
<ide><path>pp/src/main/java/com/naijab/nextzytimeline/base/BaseMvpInterface.java <add>package com.naijab.nextzytimeline.base; <add> <add>/** <add> * Created by Xiltron on 16/5/2560. <add> */ <add> <add>public interface BaseMvpInterface { <add> <add> interface View { <add> <add> Presenter getPresenter(); <add> } <add> <add> interface Presenter<V extends BaseMvpInterface.View> { <add> <add> void attachView(V mvpView); <add> <add> void detachView(); <add> <add> void onViewStart(); <add> <add> void onViewStop(); <add> <add> void onViewCreate(); <add> <add> void onViewDestroy(); <add> } <add> <add> <add>}
Java
bsd-3-clause
b950e57ed39937b8946b098a3dfc6b6a8af5b07b
0
dart-lang/sdk,dart-archive/dart-sdk,dartino/dart-sdk,dartino/dart-sdk,dart-lang/sdk,dart-archive/dart-sdk,dartino/dart-sdk,dart-lang/sdk,dart-archive/dart-sdk,dartino/dart-sdk,dartino/dart-sdk,dart-lang/sdk,dart-archive/dart-sdk,dart-archive/dart-sdk,dart-lang/sdk,dartino/dart-sdk,dart-archive/dart-sdk,dart-lang/sdk,dart-archive/dart-sdk,dartino/dart-sdk,dart-archive/dart-sdk,dartino/dart-sdk,dartino/dart-sdk,dart-archive/dart-sdk,dart-lang/sdk,dart-lang/sdk
// Copyright (c) 2012, the Dart project authors. Please see the AUTHORS file // for details. All rights reserved. Use of this source code is governed by a // BSD-style license that can be found in the LICENSE file. package com.google.dart.compiler; import java.io.File; import java.net.URI; import java.net.URISyntaxException; import java.util.ArrayList; import java.util.Arrays; import java.util.Collection; import java.util.List; /** * Manages the collection of {@link SystemLibrary}s. */ public class PackageLibraryManager { public static class NotADartShortUriException extends RuntimeException { private static final long serialVersionUID = 1L; public NotADartShortUriException(String uriString) { super("Expected dart:<short name>, got: " + uriString); } public NotADartShortUriException(URI uri) { super("Expected dart:<short name>, got: " + uri.toString()); } } /** * The "any" platform is meant to have definitions for all known dart system libraries. * Other implementations may only contain a subset. */ public static final String DEFAULT_PLATFORM = "any"; public static final File DEFAULT_SDK_PATH = new File(System.getProperty( "com.google.dart.sdk", "../")); public static final File DEFAULT_PACKAGE_ROOT = new File("packages"); public static final List<File> DEFAULT_PACKAGE_ROOTS = Arrays.asList(new File[] {DEFAULT_PACKAGE_ROOT}); public static final String PACKAGE_SCHEME = "package"; public static final String PACKAGE_SCHEME_SPEC = "package:"; public static final String DART_SCHEME = "dart"; public static final String DART_SCHEME_SPEC = "dart:"; /** * Answer <code>true</code> if the string is a dart spec */ public static boolean isDartSpec(String spec) { return spec != null && spec.startsWith(DART_SCHEME_SPEC); } /** * Answer <code>true</code> if the specified URI has a "dart" scheme */ public static boolean isDartUri(URI uri) { return uri != null && DART_SCHEME.equals(uri.getScheme()); } /** * Answer <code>true</code> if the string is a package spec */ public static boolean isPackageSpec(String spec) { return spec != null && spec.startsWith(PACKAGE_SCHEME_SPEC); } /** * Answer <code>true</code> if the specified URI has a "package" scheme */ public static boolean isPackageUri(URI uri) { return uri != null && PACKAGE_SCHEME.equals(uri.getScheme()); } private static SystemLibraryManager SDK_LIBRARY_MANAGER; private List<File> packageRoots = new ArrayList<File>(); private List<URI> packageRootsUri = new ArrayList<URI>(); public PackageLibraryManager() { this(DEFAULT_SDK_PATH, DEFAULT_PLATFORM); } public PackageLibraryManager(File sdkPath, String platformName) { if (SDK_LIBRARY_MANAGER == null){ SDK_LIBRARY_MANAGER = new SystemLibraryManager(sdkPath); } setPackageRoots(DEFAULT_PACKAGE_ROOTS); } /** * Expand a relative or short URI (e.g. "dart:html") which is implementation independent to its * full URI (e.g. "dart://html/com/google/dart/htmllib/html.dart"). * * @param uri the relative URI * @return the expanded URI * or the original URI if it could not be expanded * or null if the uri is of the form "dart:<libname>" but does not correspond to a system library */ public URI expandRelativeDartUri(URI uri) throws AssertionError { if (isDartUri(uri)) { return SDK_LIBRARY_MANAGER.expandRelativeDartUri(uri); } if (isPackageUri(uri)){ String host = uri.getHost(); if (host == null) { String spec = uri.getSchemeSpecificPart(); if (!spec.startsWith("//")){ try { if (spec.startsWith("/")){ // TODO(keertip): fix to handle spaces uri = new URI(PACKAGE_SCHEME + ":/" + spec); } else { uri = new URI(PACKAGE_SCHEME + "://" + spec); } } catch (URISyntaxException e) { throw new AssertionError(); } } } } return uri; } /** * Given an absolute file URI (e.g. "file:/some/install/directory/dart-sdk/lib/core/bool.dart"), * answer the corresponding dart: URI (e.g. "dart://core/bool.dart") for that file URI, * or <code>null</code> if the file URI does not map to a dart: URI * @param fileUri the file URI * @return the dart URI or <code>null</code> */ public URI getRelativeUri(URI fileUri) { // TODO (danrubel): does not convert dart: libraries outside the dart-sdk/lib directory if (fileUri == null || !fileUri.getScheme().equals("file")) { return null; } URI relativeUri = SDK_LIBRARY_MANAGER.getRelativeUri(fileUri); if (relativeUri != null){ return relativeUri; } for (URI rootUri : packageRootsUri){ relativeUri = rootUri.relativize(fileUri); if (relativeUri.getScheme() == null) { try { return new URI(null, null, "package://" + relativeUri.getPath(), null, null); } catch (URISyntaxException e) { //$FALL-THROUGH$ } } } return null; } /** * Given a package URI (package:foo/foo.dart), convert it into a file system URI. */ public URI resolvePackageUri(String packageUriRef) { if (packageUriRef.startsWith(PACKAGE_SCHEME_SPEC)) { String relPath = packageUriRef.substring(PACKAGE_SCHEME_SPEC.length()); if (relPath.startsWith("/")){ relPath = relPath.replaceAll("^\\/+", ""); } for (URI rootUri : packageRootsUri){ URI fileUri = rootUri.resolve(relPath); if (new File(fileUri).exists()){ return fileUri; } } // don't return null for package scheme return packageRootsUri.get(0).resolve(relPath); } return null; } /** * Answer the original "dart:<libname>" URI for the specified resolved URI or <code>null</code> if * it does not map to a short URI. */ public URI getShortUri(URI uri) { URI shortUri = SDK_LIBRARY_MANAGER.getShortUri(uri); if (shortUri != null){ return shortUri; } shortUri = getRelativeUri(uri); if (shortUri != null){ try { return new URI(null, null, shortUri.getScheme() + ":" + shortUri.getHost() + shortUri.getPath(),null, null); } catch (URISyntaxException e) { } } return null; } /** * Expand a relative or short URI (e.g. "dart:html") which is implementation independent to its * full URI (e.g. "dart://html/com/google/dart/htmllib/html.dart") and then translate that URI to * a "file:" URI (e.g. * "file:/some/install/directory/com/google/dart/htmllib/html.dart"). * * @param uri the original URI * @return the expanded and translated URI, which may be <code>null</code> and may not exist * @exception RuntimeException if the URI is a "dart" scheme, but does not map to a defined system * library */ public URI resolveDartUri(URI uri) { return translateDartUri(expandRelativeDartUri(uri)); } public List<File> getPackageRoots(){ return packageRoots; } public void setPackageRoots(List<File> roots){ if (roots == null || roots.isEmpty()){ roots = DEFAULT_PACKAGE_ROOTS; } packageRoots.clear(); for (File file : roots){ packageRoots.add(file.getAbsoluteFile()); } packageRootsUri.clear(); for (File file : roots){ packageRootsUri.add(file.toURI()); } } /** * Translate the URI from dart://[host]/[pathToLib] (e.g. dart://html/html.dart) * to a "file:" URI (e.g. "file:/some/install/directory/html.dart") * * @param uri the original URI * @return the translated URI, which may be <code>null</code> and may not exist * @exception RuntimeException if the URI is a "dart" scheme, * but does not map to a defined system library */ public URI translateDartUri(URI uri) { if (isDartUri(uri)) { return SDK_LIBRARY_MANAGER.translateDartUri(uri); } if (isPackageUri(uri)){ URI fileUri; for (URI rootUri : packageRootsUri){ fileUri = getResolvedPackageUri(uri, rootUri); File file = new File(fileUri); if (file.exists()){ return file.toURI(); } } // resolve against first package root fileUri = getResolvedPackageUri(uri, packageRootsUri.get(0)); return fileUri; } return uri; } /** * Given a uri, resolve against the list of package roots, used to find generated files * @return uri - resolved uri if file exists, else return given uri */ public URI findExistingFileInPackages(URI fileUri){ URI resolvedUri = getRelativeUri(fileUri); if (isPackageUri(resolvedUri)){ resolvedUri = resolvePackageUri(resolvedUri.toString()); return resolvedUri; } return fileUri; } /** * Resolves the given uri against the package root uri */ private URI getResolvedPackageUri(URI uri, URI packageRootUri) { URI fileUri; // TODO(keertip): Investigate further // if uri.getHost() returns null, then it is resolved right // so use uri.getAuthority to resolve // package://third_party/dart_lang/lib/unittest/unittest.dart if (uri.getHost() != null){ fileUri = packageRootUri.resolve(uri.getHost() + uri.getPath()); } else { fileUri = packageRootUri.resolve(uri.getAuthority() + uri.getPath()); } return fileUri; } /** * Answer a collection of all bundled library URL specs (e.g. "dart:html"). * * @return a collection of specs (not <code>null</code>, contains no <code>null</code>s) */ public Collection<String> getAllLibrarySpecs() { return SDK_LIBRARY_MANAGER.getAllLibrarySpecs(); } protected SystemLibrary[] getDefaultLibraries() { return SDK_LIBRARY_MANAGER.getDefaultLibraries(); } public Collection<SystemLibrary> getSystemLibraries(){ return SDK_LIBRARY_MANAGER.getAllSystemLibraries(); } public File getSdkLibPath() { return SDK_LIBRARY_MANAGER.getSdkLibPath(); } }
compiler/java/com/google/dart/compiler/PackageLibraryManager.java
// Copyright (c) 2012, the Dart project authors. Please see the AUTHORS file // for details. All rights reserved. Use of this source code is governed by a // BSD-style license that can be found in the LICENSE file. package com.google.dart.compiler; import java.io.File; import java.net.URI; import java.net.URISyntaxException; import java.util.ArrayList; import java.util.Arrays; import java.util.Collection; import java.util.List; /** * Manages the collection of {@link SystemLibrary}s. */ public class PackageLibraryManager { public static class NotADartShortUriException extends RuntimeException { private static final long serialVersionUID = 1L; public NotADartShortUriException(String uriString) { super("Expected dart:<short name>, got: " + uriString); } public NotADartShortUriException(URI uri) { super("Expected dart:<short name>, got: " + uri.toString()); } } /** * The "any" platform is meant to have definitions for all known dart system libraries. * Other implementations may only contain a subset. */ public static final String DEFAULT_PLATFORM = "any"; public static final File DEFAULT_SDK_PATH = new File(System.getProperty( "com.google.dart.sdk", "../")); public static final File DEFAULT_PACKAGE_ROOT = new File("packages"); public static final List<File> DEFAULT_PACKAGE_ROOTS = Arrays.asList(new File[] {DEFAULT_PACKAGE_ROOT}); public static final String PACKAGE_SCHEME = "package"; public static final String PACKAGE_SCHEME_SPEC = "package:"; public static final String DART_SCHEME = "dart"; public static final String DART_SCHEME_SPEC = "dart:"; /** * Answer <code>true</code> if the string is a dart spec */ public static boolean isDartSpec(String spec) { return spec != null && spec.startsWith(DART_SCHEME_SPEC); } /** * Answer <code>true</code> if the specified URI has a "dart" scheme */ public static boolean isDartUri(URI uri) { return uri != null && DART_SCHEME.equals(uri.getScheme()); } /** * Answer <code>true</code> if the string is a package spec */ public static boolean isPackageSpec(String spec) { return spec != null && spec.startsWith(PACKAGE_SCHEME_SPEC); } /** * Answer <code>true</code> if the specified URI has a "package" scheme */ public static boolean isPackageUri(URI uri) { return uri != null && PACKAGE_SCHEME.equals(uri.getScheme()); } private static SystemLibraryManager SDK_LIBRARY_MANAGER; private List<File> packageRoots = new ArrayList<File>(); private List<URI> packageRootsUri = new ArrayList<URI>(); public PackageLibraryManager() { this(DEFAULT_SDK_PATH, DEFAULT_PLATFORM); } public PackageLibraryManager(File sdkPath, String platformName) { if (SDK_LIBRARY_MANAGER == null){ SDK_LIBRARY_MANAGER = new SystemLibraryManager(sdkPath); } setPackageRoots(DEFAULT_PACKAGE_ROOTS); } /** * Expand a relative or short URI (e.g. "dart:html") which is implementation independent to its * full URI (e.g. "dart://html/com/google/dart/htmllib/html.dart"). * * @param uri the relative URI * @return the expanded URI * or the original URI if it could not be expanded * or null if the uri is of the form "dart:<libname>" but does not correspond to a system library */ public URI expandRelativeDartUri(URI uri) throws AssertionError { if (isDartUri(uri)) { return SDK_LIBRARY_MANAGER.expandRelativeDartUri(uri); } if (isPackageUri(uri)){ String host = uri.getHost(); if (host == null) { String spec = uri.getSchemeSpecificPart(); if (!spec.startsWith("//")){ try { if (spec.startsWith("/")){ // TODO(keertip): fix to handle spaces uri = new URI(PACKAGE_SCHEME + ":/" + spec); } else { uri = new URI(PACKAGE_SCHEME + "://" + spec); } } catch (URISyntaxException e) { throw new AssertionError(); } } } } return uri; } /** * Given an absolute file URI (e.g. "file:/some/install/directory/dart-sdk/lib/core/bool.dart"), * answer the corresponding dart: URI (e.g. "dart://core/bool.dart") for that file URI, * or <code>null</code> if the file URI does not map to a dart: URI * @param fileUri the file URI * @return the dart URI or <code>null</code> */ public URI getRelativeUri(URI fileUri) { // TODO (danrubel): does not convert dart: libraries outside the dart-sdk/lib directory if (fileUri == null || !fileUri.getScheme().equals("file")) { return null; } URI relativeUri = SDK_LIBRARY_MANAGER.getRelativeUri(fileUri); if (relativeUri != null){ return relativeUri; } for (URI rootUri : packageRootsUri){ relativeUri = rootUri.relativize(fileUri); if (relativeUri.getScheme() == null) { try { return new URI(null, null, "package://" + relativeUri.getPath(), null, null); } catch (URISyntaxException e) { //$FALL-THROUGH$ } } } return null; } /** * Given a package URI (package:foo/foo.dart), convert it into a file system URI. */ public URI resolvePackageUri(String packageUriRef) { if (packageUriRef.startsWith(PACKAGE_SCHEME_SPEC)) { String relPath = packageUriRef.substring(PACKAGE_SCHEME_SPEC.length()); if (relPath.startsWith("/")){ relPath = relPath.replaceAll("^\\/+", ""); } for (URI rootUri : packageRootsUri){ URI fileUri = rootUri.resolve(relPath); if (new File(fileUri).exists()){ return fileUri; } } // don't return null for package scheme return packageRootsUri.get(0).resolve(relPath); } return null; } /** * Answer the original "dart:<libname>" URI for the specified resolved URI or <code>null</code> if * it does not map to a short URI. */ public URI getShortUri(URI uri) { URI shortUri = SDK_LIBRARY_MANAGER.getShortUri(uri); if (shortUri != null){ return shortUri; } shortUri = getRelativeUri(uri); if (shortUri != null){ try { return new URI(null, null, shortUri.getScheme() + ":" + shortUri.getHost() + shortUri.getPath(),null, null); } catch (URISyntaxException e) { } } return null; } /** * Expand a relative or short URI (e.g. "dart:html") which is implementation independent to its * full URI (e.g. "dart://html/com/google/dart/htmllib/html.dart") and then translate that URI to * a "file:" URI (e.g. * "file:/some/install/directory/com/google/dart/htmllib/html.dart"). * * @param uri the original URI * @return the expanded and translated URI, which may be <code>null</code> and may not exist * @exception RuntimeException if the URI is a "dart" scheme, but does not map to a defined system * library */ public URI resolveDartUri(URI uri) { return translateDartUri(expandRelativeDartUri(uri)); } public List<File> getPackageRoots(){ return packageRoots; } public void setPackageRoots(List<File> roots){ if (roots == null || roots.isEmpty()){ this.packageRoots = DEFAULT_PACKAGE_ROOTS; } else { packageRoots.clear(); for (File file : roots){ packageRoots.add(file.getAbsoluteFile()); } } packageRootsUri.clear(); for (File file : roots){ packageRootsUri.add(file.toURI()); } } /** * Translate the URI from dart://[host]/[pathToLib] (e.g. dart://html/html.dart) * to a "file:" URI (e.g. "file:/some/install/directory/html.dart") * * @param uri the original URI * @return the translated URI, which may be <code>null</code> and may not exist * @exception RuntimeException if the URI is a "dart" scheme, * but does not map to a defined system library */ public URI translateDartUri(URI uri) { if (isDartUri(uri)) { return SDK_LIBRARY_MANAGER.translateDartUri(uri); } if (isPackageUri(uri)){ URI fileUri; for (URI rootUri : packageRootsUri){ fileUri = getResolvedPackageUri(uri, rootUri); File file = new File(fileUri); if (file.exists()){ return file.toURI(); } } // resolve against first package root fileUri = getResolvedPackageUri(uri, packageRootsUri.get(0)); return fileUri; } return uri; } /** * Given a uri, resolve against the list of package roots, used to find generated files * @return uri - resolved uri if file exists, else return given uri */ public URI findExistingFileInPackages(URI fileUri){ URI resolvedUri = getRelativeUri(fileUri); if (isPackageUri(resolvedUri)){ resolvedUri = resolvePackageUri(resolvedUri.toString()); return resolvedUri; } return fileUri; } /** * Resolves the given uri against the package root uri */ private URI getResolvedPackageUri(URI uri, URI packageRootUri) { URI fileUri; // TODO(keertip): Investigate further // if uri.getHost() returns null, then it is resolved right // so use uri.getAuthority to resolve // package://third_party/dart_lang/lib/unittest/unittest.dart if (uri.getHost() != null){ fileUri = packageRootUri.resolve(uri.getHost() + uri.getPath()); } else { fileUri = packageRootUri.resolve(uri.getAuthority() + uri.getPath()); } return fileUri; } /** * Answer a collection of all bundled library URL specs (e.g. "dart:html"). * * @return a collection of specs (not <code>null</code>, contains no <code>null</code>s) */ public Collection<String> getAllLibrarySpecs() { return SDK_LIBRARY_MANAGER.getAllLibrarySpecs(); } protected SystemLibrary[] getDefaultLibraries() { return SDK_LIBRARY_MANAGER.getDefaultLibraries(); } public Collection<SystemLibrary> getSystemLibraries(){ return SDK_LIBRARY_MANAGER.getAllSystemLibraries(); } public File getSdkLibPath() { return SDK_LIBRARY_MANAGER.getSdkLibPath(); } }
Fix PackageLibraryManager set package directory Review URL: https://chromiumcodereview.appspot.com//10919160 git-svn-id: c93d8a2297af3b929165606efe145742a534bc71@12067 260f80e4-7a28-3924-810f-c04153c831b5
compiler/java/com/google/dart/compiler/PackageLibraryManager.java
Fix PackageLibraryManager set package directory Review URL: https://chromiumcodereview.appspot.com//10919160
<ide><path>ompiler/java/com/google/dart/compiler/PackageLibraryManager.java <ide> <ide> public void setPackageRoots(List<File> roots){ <ide> if (roots == null || roots.isEmpty()){ <del> this.packageRoots = DEFAULT_PACKAGE_ROOTS; <del> } else { <del> packageRoots.clear(); <del> for (File file : roots){ <del> packageRoots.add(file.getAbsoluteFile()); <del> } <del> } <add> roots = DEFAULT_PACKAGE_ROOTS; <add> } <add> packageRoots.clear(); <add> for (File file : roots){ <add> packageRoots.add(file.getAbsoluteFile()); <add> } <ide> packageRootsUri.clear(); <ide> for (File file : roots){ <ide> packageRootsUri.add(file.toURI());
Java
mit
08c52b3e4065b5462a314f7e562a26bcf6beb483
0
theonly500/Kniffel
import javax.swing.*; import java.util.ArrayList; /** * Created by Felix on 11.06.2015. */ public class UI { //all visible GUI display elements JFrame frame; //all invisible GUI display elements JPanel base; JPanel diceBase; JPanel[] individualDiceBase; //all background elements Calc calc; int playerCount; public UI(Calc calc,ArrayList<String> names){ this.calc=calc; playerCount=names.size(); } private void createUI(){ //create JFrame to contain every element frame=new JFrame("Yahtzee"); frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE); //add the base panel to the frame base=new JPanel(); base.setLayout(new BoxLayout(base, BoxLayout.X_AXIS)); frame.add(base); //add the panel for all dices diceBase=new JPanel(); diceBase.setLayout(new BoxLayout(diceBase, BoxLayout.X_AXIS)); base.add(diceBase); //create and add the panel for every singular dice individualDiceBase = new JPanel[5]; for (int i=0;i<5;i++){ individualDiceBase[i]=new JPanel(); individualDiceBase[i].setLayout(new BoxLayout(individualDiceBase[i],BoxLayout.Y_AXIS)); base.add(individualDiceBase[i]); } } }
src/UI.java
import javax.swing.*; import java.util.ArrayList; /** * Created by Felix on 11.06.2015. */ public class UI { //all visible GUI display elements JFrame frame; //all invisible GUI display elements JPanel base; JPanel diceBase; JPanel[] individualDiceBase; //all background elements Calc calc; int playerCount; public UI(Calc calc,ArrayList<String> names){ this.calc=calc; playerCount=names.size(); } private void createUI(){ //create JFrame to contain every element frame=new JFrame("Yahtzee"); frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE); //add the base panel to the frame base=new JPanel(); base.setLayout(new BoxLayout(base, BoxLayout.X_AXIS)); frame.add(base); //add the panel for all dices diceBase=new JPanel(); diceBase.setLayout(new BoxLayout(diceBase, BoxLayout.X_AXIS)); base.add(diceBase); //create and add the panel for every singular dice individualDiceBase = new JPanel[5]; for (int i=0;i<5;i++){ individualDiceBase[i]=new JPanel(); individualDiceBase[i].setLayout(new BoxLayout(individualDiceBase[i],BoxLayout.Y_AXIS)); } } }
Version 0.0.1
src/UI.java
Version 0.0.1
<ide><path>rc/UI.java <ide> for (int i=0;i<5;i++){ <ide> individualDiceBase[i]=new JPanel(); <ide> individualDiceBase[i].setLayout(new BoxLayout(individualDiceBase[i],BoxLayout.Y_AXIS)); <add> base.add(individualDiceBase[i]); <ide> } <ide> } <ide> }
JavaScript
bsd-2-clause
cd3b21735b9d410cf0321d05fb9a84e1244186da
0
nmco/MapStore2,mircobe87/MapStore2,paolo-tn/MapStore2,paolo-tn/MapStore2,nmco/MapStore2,paolo-tn/MapStore2,mircobe87/MapStore2,nmco/MapStore2,mircobe87/MapStore2
/** * Copyright 2015, GeoSolutions Sas. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. */ var axios = require('axios'); var ConfigUtils = require('../utils/ConfigUtils'); var toString = Object.prototype.toString; function isArray(val) { return toString.call(val) === '[object Array]'; } function isObject(val) { return val !== null && typeof val === 'object'; } function isDate(val) { return toString.call(val) === '[object Date]'; } function isArguments(val) { return toString.call(val) === '[object Arguments]'; } function forEach(arg, fn) { var obj; // Check if arg is array-like const isArrayLike = isArray(arg) || isArguments(arg); // Force an array if not already something iterable if (typeof arg !== 'object' && !isArrayLike) { obj = [arg]; } else { obj = arg; } // Iterate over array values if (isArrayLike) { for (let i = 0, l = obj.length; i < l; i++) { fn.call(null, obj[i], i, obj); } } else { // Iterate over object keys for (let key in obj) { if (obj.hasOwnProperty(key)) { fn.call(null, obj[key], key, obj); } } } } function buildUrl(argUrl, params) { var url = argUrl; var parts = []; if (!params) { return url; } forEach(params, function(argVal, argKey) { var val = argVal; var key = argKey; if (val === null || typeof val === 'undefined') { return; } if (isArray(val)) { key = key + '[]'; } if (!isArray(val)) { val = [val]; } forEach(val, function(argV) { var v = argV; if (isDate(v)) { v = v.toISOString(); } else if (isObject(v)) { v = JSON.stringify(v); } parts.push(encodeURI(key) + '=' + encodeURI(v)); }); }); if (parts.length > 0) { url += (url.indexOf('?') === -1 ? '?' : '&') + parts.join('&'); } return url; } axios.interceptors.request.use(config => { var uri = config.url || ''; var sameOrigin = !(uri.indexOf("http") === 0); var urlParts = !sameOrigin && uri.match(/([^:]*:)\/\/([^:]*:?[^@]*@)?([^:\/\?]*):?([^\/\?]*)/); if (urlParts) { let location = window.location; sameOrigin = urlParts[1] === location.protocol && urlParts[3] === location.hostname; let uPort = urlParts[4]; let lPort = location.port; if (uPort !== 80 && uPort !== "" || lPort !== "80" && lPort !== "") { sameOrigin = sameOrigin && uPort === lPort; } } if (!sameOrigin) { let proxyUrl = ConfigUtils.getProxyUrl(config); if (proxyUrl) { if (proxyUrl.match(/^http:\/\//i) === null) { proxyUrl = 'http://' + window.location.host + proxyUrl; } config.url = proxyUrl + encodeURIComponent(buildUrl(uri, config.params)); config.params = undefined; } } return config; }); module.exports = axios;
web/client/libs/ajax.js
/** * Copyright 2015, GeoSolutions Sas. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. */ var axios = require('axios'); var ConfigUtils = require('../utils/ConfigUtils'); function isArray(val) { return toString.call(val) === '[object Array]'; } function isObject(val) { return val !== null && typeof val === 'object'; } function isDate(val) { return toString.call(val) === '[object Date]'; } function isArguments(val) { return toString.call(val) === '[object Arguments]'; } function forEach(arg, fn) { var obj; // Check if arg is array-like const isArrayLike = isArray(arg) || isArguments(arg); // Force an array if not already something iterable if (typeof arg !== 'object' && !isArrayLike) { obj = [arg]; } else { obj = arg; } // Iterate over array values if (isArrayLike) { for (let i = 0, l = obj.length; i < l; i++) { fn.call(null, obj[i], i, obj); } } else { // Iterate over object keys for (let key in obj) { if (obj.hasOwnProperty(key)) { fn.call(null, obj[key], key, obj); } } } } function buildUrl(argUrl, params) { var url = argUrl; var parts = []; if (!params) { return url; } forEach(params, function(argVal, argKey) { var val = argVal; var key = argKey; if (val === null || typeof val === 'undefined') { return; } if (isArray(val)) { key = key + '[]'; } if (!isArray(val)) { val = [val]; } forEach(val, function(argV) { var v = argV; if (isDate(v)) { v = v.toISOString(); } else if (isObject(v)) { v = JSON.stringify(v); } parts.push(encodeURI(key) + '=' + encodeURI(v)); }); }); if (parts.length > 0) { url += (url.indexOf('?') === -1 ? '?' : '&') + parts.join('&'); } return url; } axios.interceptors.request.use(config => { var uri = config.url || ''; var sameOrigin = !(uri.indexOf("http") === 0); var urlParts = !sameOrigin && uri.match(/([^:]*:)\/\/([^:]*:?[^@]*@)?([^:\/\?]*):?([^\/\?]*)/); if (urlParts) { let location = window.location; sameOrigin = urlParts[1] === location.protocol && urlParts[3] === location.hostname; let uPort = urlParts[4]; let lPort = location.port; if (uPort !== 80 && uPort !== "" || lPort !== "80" && lPort !== "") { sameOrigin = sameOrigin && uPort === lPort; } } if (!sameOrigin) { let proxyUrl = ConfigUtils.getProxyUrl(config); if (proxyUrl) { if (proxyUrl.match(/^http:\/\//i) === null) { proxyUrl = 'http://' + window.location.host + proxyUrl; } config.url = proxyUrl + encodeURIComponent(buildUrl(uri, config.params)); config.params = undefined; } } return config; }); module.exports = axios;
fixes #169
web/client/libs/ajax.js
fixes #169
<ide><path>eb/client/libs/ajax.js <ide> <ide> var axios = require('axios'); <ide> var ConfigUtils = require('../utils/ConfigUtils'); <add>var toString = Object.prototype.toString; <ide> <ide> function isArray(val) { <ide> return toString.call(val) === '[object Array]';
JavaScript
agpl-3.0
c0bcccb3b99fbd5f273373f8e3b8b05cb0ff3066
0
privacyidea/privacyidea,privacyidea/privacyidea,privacyidea/privacyidea,privacyidea/privacyidea,privacyidea/privacyidea,privacyidea/privacyidea
/** * http://www.privacyidea.org * (c) cornelius kölbel, [email protected] * * 2015-01-11 Cornelius Kölbel, <[email protected]> * * This code is free software; you can redistribute it and/or * modify it under the terms of the GNU AFFERO GENERAL PUBLIC LICENSE * License as published by the Free Software Foundation; either * version 3 of the License, or any later version. * * This code 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 AFFERO GENERAL PUBLIC LICENSE for more details. * * You should have received a copy of the GNU Affero General Public * License along with this program. If not, see <http://www.gnu.org/licenses/>. * */ myApp.controller("tokenController", function (TokenFactory, ConfigFactory, $scope, $location, AuthFactory, instanceUrl, $rootScope, gettextCatalog, hotkeys) { $scope.tokensPerPage = $scope.token_page_size; $scope.params = {page: 1, sortdir: "asc"}; $scope.reverse = false; $scope.loggedInUser = AuthFactory.getUser(); $scope.selectedToken = {serial: null}; $scope.clientpart = ""; // Change the pagination $scope.pageChanged = function () { //debug: console.log('Page changed to: ' + $scope.params.page); $scope.get(); }; // This function fills $scope.tokendata $scope.get = function (live_search) { if ((!$rootScope.search_on_enter) || ($rootScope.search_on_enter && !live_search)) { $scope.params.serial = "*" + ($scope.serialFilter || "") + "*"; $scope.params.tokenrealm = "*" + ($scope.tokenrealmFilter || "") + "*"; $scope.params.type = "*" + ($scope.typeFilter || "") + "*"; $scope.params.description = "*" + ($scope.descriptionFilter || "") + "*"; $scope.params.userid = "*" + ($scope.userIdFilter || "") + "*"; $scope.params.resolver = "*" + ($scope.resolverFilter || "") + "*"; $scope.params.pagesize = $scope.token_page_size; $scope.params.sortBy = $scope.sortBy; if ($scope.reverse) { $scope.params.sortdir = "desc"; } else { $scope.params.sortdir = "asc"; } TokenFactory.getTokens(function (data) { if (data) { $scope.tokendata = data.result.value; } }, $scope.params); } }; if ($scope.loggedInUser.role === "admin") { /* * Functions to check and to create a default realm. At the moment this is * in the tokenview, as the token view is the first view. This could be * changed to be located anywhere else. */ ConfigFactory.getRealms(function (data) { // Check if there is a realm defined, or if we should display the // Auto Create Dialog var number_of_realms = Object.keys(data.result.value).length; if (number_of_realms === 0) { $('#dialogAutoCreateRealm').modal(); } }); /* Welcome dialog, which displays a lot of information to the administrator. We display it if subscription_state = 0 and hide_welcome = false subscription_state = 1 subscription_state = 2 */ if ($scope.welcomeStep < 4) { // We did not walk throught the welcome dialog, yet. if (($scope.subscription_state === 0 && !$scope.hide_welcome) || ($scope.subscription_state === 1) || ($scope.subscription_state === 2)) { $('#dialogWelcome').modal("show"); $("body").addClass("modal-open"); } } } // single token function $scope.reset = function (serial) { TokenFactory.reset(serial, $scope.get); }; $scope.disable = function (serial) { TokenFactory.disable(serial, $scope.get); }; $scope.enable = function (serial) { TokenFactory.enable(serial, $scope.get); }; if ($location.path() === "/token/list") { $scope.get(); } // go to the list view by default if ($location.path() === "/token") { $location.path("/token/list"); } // go to token.wizard, if the wizard is defined if ($scope.token_wizard) { $location.path("/token/wizard"); } // go to change PIN, if we should change the PIN if ($scope.pin_change) { $location.path("/pinchange"); } // listen to the reload broadcast $scope.$on("piReload", function() { /* Due to the parameter "live_search" in the get function we can not bind the get-function to piReload below. This will break in Chrome, would work in Firefox. So we need this wrapper function */ $scope.get(); }); }); myApp.controller("tokenAssignController", function ($scope, TokenFactory, $stateParams, AuthFactory, UserFactory, $state) { $scope.assignToken = function () { TokenFactory.assign({ serial: fixSerial($scope.newToken.serial), pin: $scope.newToken.pin }, function () { $state.go('token.list'); }); }; }); myApp.controller("tokenEnrollController", function ($scope, TokenFactory, $timeout, $stateParams, AuthFactory, UserFactory, $state, ConfigFactory, instanceUrl, $http, hotkeys, gettextCatalog, inform, U2fFactory) { hotkeys.bindTo($scope).add({ combo: 'alt+e', description: gettextCatalog.getString('Enroll a new token'), callback: function (event, hotkey) { event.preventDefault(); $state.go('token.enroll'); $scope.enrolledToken = null; } }); hotkeys.bindTo($scope).add({ combo: 'alt+r', description: gettextCatalog.getString('Roll the token'), callback: function () { $scope.enrollToken(); } }); $scope.qrCodeWidth = 250; if ($state.includes('token.wizard') && !$scope.show_seed) { $scope.qrCodeWidth = 500; } $scope.checkRight = AuthFactory.checkRight; $scope.loggedInUser = AuthFactory.getUser(); $scope.newUser = {}; $scope.tempData = {}; $scope.instanceUrl = instanceUrl; $scope.click_wait = true; $scope.U2FToken = {}; // System default values for enrollment $scope.systemDefault = {}; // questions for questionnaire token $scope.questions = []; $scope.num_questions = 5; // These are values that are also sent to the backend! $scope.form = { timeStep: 30, otplen: 6, genkey: true, type: $scope.default_tokentype, hashlib: "sha1", 'radius.system_settings': true }; $scope.vasco = { // Note: A primitive does not work in the ng-model of the checkbox! useIt: false }; $scope.formInit = { tokenTypes: {"hotp": gettextCatalog.getString("HOTP: event based One Time Passwords"), "totp": gettextCatalog.getString("TOTP: time based One Time Passwords"), "spass": gettextCatalog.getString("SPass: Simple Pass token. Static passwords"), "motp": gettextCatalog.getString("mOTP: classical mobile One Time Passwords"), "sshkey": gettextCatalog.getString("SSH Public Key: The public SSH key"), "yubikey": gettextCatalog.getString("Yubikey AES mode: One Time Passwords with" + " Yubikey"), "remote": gettextCatalog.getString("Remote Token: Forward authentication request" + " to another server"), "yubico": gettextCatalog.getString("Yubikey Cloud mode: Forward authentication" + " request to YubiCloud"), "radius": gettextCatalog.getString("RADIUS: Forward authentication request to a" + " RADIUS server"), "email": gettextCatalog.getString("EMail: Send a One Time Password to the users email" + " address."), "sms": gettextCatalog.getString("SMS: Send a One Time Password to the users" + " mobile phone."), "certificate": gettextCatalog.getString("Certificate: Enroll an x509 Certificate" + " Token."), "4eyes": gettextCatalog.getString("Four Eyes: Two or more users are required to" + " log in."), "tiqr": gettextCatalog.getString("TiQR: Authenticate with Smartphone by scanning" + " a QR code."), "u2f": gettextCatalog.getString("U2F: Universal 2nd Factor hardware token."), "indexedsecret": gettextCatalog.getString("IndexedSecret: Challenge token based on a shared secret."), "paper": gettextCatalog.getString("PAPER: OTP values on a sheet of paper.")}, timesteps: [30, 60], otplens: [6, 8], hashlibs: ["sha1", "sha256", "sha512"] }; $scope.setVascoSerial = function() { if ($scope.form.otpkey.length === 496) { //console.log('DEBUG: got 496 hexlify otpkey, check vasco serialnumber!'); // convert hexlified input blob to ascii and use the serialnumber (first 10 chars) var vasco_hex = $scope.form.otpkey.toString();//force conversion var vasco_otpstr = ''; for (var i = 0; i < vasco_hex.length; i += 2) vasco_otpstr += String.fromCharCode(parseInt(vasco_hex.substr(i, 2), 16)); var vasco_serial = vasco_otpstr.slice(0, 10); //console.log(vasco_serial); $scope.vascoSerial = vasco_serial; if ($scope.vasco.useIt) { $scope.form.serial = vasco_serial; } else { delete $scope.form.serial; } } else { // If we do not have 496 characters this might be no correct vasco blob. // So we reset the serial $scope.vascoSerial = ""; delete $scope.form.serial; } }; // These token need to PIN // TODO: This is also contained in the tokentype class! $scope.changeTokenType = function() { //debug: console.log("Token Type Changed."); if (["sshkey", "certificate"].indexOf($scope.form.type) >= 0) { $scope.hidePin = true; } else { $scope.hidePin = false; } if ($scope.form.type === "hotp") { // preset HOTP hashlib $scope.form.hashlib = $scope.systemDefault['hotp.hashlib'] || 'sha1'; } else if ($scope.form.type === "totp") { // preset TOTP hashlib $scope.form.hashlib = $scope.systemDefault['totp.hashlib'] || 'sha1'; $scope.form.timeStep = parseInt($scope.systemDefault['totp.timeStep'] || '30'); } if ($scope.form.type === "vasco") { $scope.form.genkey = false; } else { $scope.form.genkey = true; } $scope.preset_indexedsecret(); if ($scope.form.type === "radius") { // only load RADIUS servers when the user actually tries to enroll a RADIUS token, // because the user might not be allowed to list RADIUS servers $scope.getRADIUSIdentifiers(); } if ($scope.form.type === "certificate") { $scope.getCAConnectors(); } // preset twostep enrollment $scope.setTwostepEnrollmentDefault(); }; // helper function for setting indexed secret attribute $scope.preset_indexedsecret = function() { if ($scope.form.type === "indexedsecret") { // in case of indexedsecret we do never generate a key from the UI $scope.form.genkey = false; // Only fetch, if a preset_attribute is defined if ($scope.tokensettings.indexedsecret.preset_attribute) { // In case of a normal logged in user, an empty params is fine var params = {}; if (AuthFactory.getRole() === 'admin') { params = {realm: $scope.newUser.realm, username: fixUser($scope.newUser.user)}; } UserFactory.getUsers(params, function(data) { var userObject = data.result.value[0]; // preset for indexedsecret token $scope.form.otpkey = userObject[$scope.tokensettings.indexedsecret.preset_attribute]; }); } } }; // Set the default value of the "2stepinit" field if twostep enrollment should be forced $scope.setTwostepEnrollmentDefault = function () { $scope.form["2stepinit"] = $scope.checkRight($scope.form.type + "_2step=force"); }; // Initially set the default value $scope.setTwostepEnrollmentDefault(); // A watch function to change the form data in case another user is selected $scope.$watch(function(scope) {return scope.newUser.email;}, function(newValue, oldValue){ if (newValue != '') { $scope.form.email = newValue; } }); $scope.$watch(function(scope) {return scope.newUser.mobile;}, function(newValue, oldValue){ if (newValue != '') { $scope.form.phone = newValue; } }); $scope.$watch(function(scope) {return fixUser(scope.newUser.user);}, function(newValue, oldValue) { // The newUser was changed $scope.preset_indexedsecret(); }); // Get the realms and fill the realm dropdown box if (AuthFactory.getRole() === 'admin') { ConfigFactory.getRealms(function (data) { $scope.realms = data.result.value; // Set the default realm var size = Object.keys($scope.realms).length; angular.forEach($scope.realms, function (realm, realmname) { if (size === 1) { // if there is only one realm, preset it $scope.newUser = {user: "", realm: realmname}; } // if there is a default realm, preset the default realm if (realm.default && !$stateParams.realmname) { $scope.newUser = {user: "", realm: realmname}; //debug: console.log("tokenEnrollController"); //debug: console.log($scope.newUser); } }); // init the user, if token.enroll was called from the user.details if ($stateParams.realmname) { $scope.newUser.realm = $stateParams.realmname; } if ($stateParams.username) { $scope.newUser.user = $stateParams.username; // preset the mobile and email for SMS or EMAIL token UserFactory.getUsers({realm: $scope.newUser.realm, username: $scope.newUser.user}, function(data) { var userObject = data.result.value[0]; $scope.form.email = userObject.email; if (typeof userObject.mobile === "string") { $scope.form.phone = userObject.mobile; } else { $scope.phone_list = userObject.mobile; if ($scope.phone_list.length === 1) { $scope.form.phone = $scope.phone_list[0]; } } }); } }); } else if (AuthFactory.getRole() === 'user') { // init the user, if token.enroll was called as a normal user $scope.newUser.user = AuthFactory.getUser().username; $scope.newUser.realm = AuthFactory.getUser().realm; } // Read the the tokentypes from the server TokenFactory.getEnrollTokens(function(data){ //debug: console.log("getEnrollTokens"); //debug: console.log(data); $scope.formInit["tokenTypes"] = data.result.value; // set the default tokentype if (!$scope.formInit.tokenTypes.hasOwnProperty( $scope.default_tokentype)) { // if HOTP does not exist, we set another default type for (var tkey in $scope.formInit.tokenTypes) { // set the first key to be the default tokentype $scope.form.type = tkey; // Set the 2step enrollment value $scope.setTwostepEnrollmentDefault(); break; } } }); $scope.CAConnectors = []; $scope.CATemplates = {}; $scope.radioCSR = 'csrgenerate'; // default enrollment callback $scope.callback = function (data) { $scope.U2FToken = {}; $scope.enrolledToken = data.detail; $scope.click_wait=false; if ($scope.enrolledToken.otps) { var otps_count = Object.keys($scope.enrolledToken.otps).length; $scope.otp_row_count = parseInt(otps_count/5 + 0.5); $scope.otp_rows = Object.keys($scope.enrolledToken.otps).slice(0, $scope.otp_row_count); } if ($scope.enrolledToken.certificate) { var blob = new Blob([ $scope.enrolledToken.certificate ], { type : 'text/plain' }); $scope.certificateBlob = (window.URL || window.webkitURL).createObjectURL( blob ); } if ($scope.enrolledToken.pkcs12) { var bytechars = atob($scope.enrolledToken.pkcs12); var byteNumbers = new Array(bytechars.length); for (var i = 0; i < bytechars.length; i++) { byteNumbers[i] = bytechars.charCodeAt(i); } var byteArray = new Uint8Array(byteNumbers); var blob = new Blob([byteArray], {type: 'application/x-pkcs12'}); $scope.pkcs12Blob = (window.URL || window.webkitURL).createObjectURL( blob ); } if ($scope.enrolledToken.u2fRegisterRequest) { // This is the first step of U2F registering // save serial $scope.serial = data.detail.serial; // We need to send the 2nd stage of the U2F enroll $scope.register_u2f($scope.enrolledToken.u2fRegisterRequest); $scope.click_wait=true; } if ($scope.enrolledToken.rollout_state === "clientwait") { $scope.pollTokenInfo(); } $('html,body').scrollTop(0); }; $scope.enrollToken = function () { //debug: console.log($scope.newUser.user); //debug: console.log($scope.newUser.realm); //debug: console.log($scope.newUser.pin); $scope.newUser.user = fixUser($scope.newUser.user); // convert the date object to a string $scope.form.validity_period_start = date_object_to_string($scope.form.validity_period_start); $scope.form.validity_period_end = date_object_to_string($scope.form.validity_period_end); TokenFactory.enroll($scope.newUser, $scope.form, $scope.callback); }; $scope.pollTokenInfo = function () { TokenFactory.getTokenForSerial($scope.enrolledToken.serial, function(data) { $scope.enrolledToken.rollout_state = data.result.value.tokens[0].rollout_state; // Poll the data after 2.5 seconds again if ($scope.enrolledToken.rollout_state === "clientwait") { $timeout($scope.pollTokenInfo, 2500); } }) }; $scope.regenerateToken = function () { var params = $scope.form; params.serial = $scope.enrolledToken.serial; TokenFactory.enroll($scope.newUser, params, $scope.callback); }; $scope.sendClientPart = function () { var params = { "otpkey": $scope.clientpart.replace(/ /g, ""), "otpkeyformat": "base32check", "serial": $scope.enrolledToken.serial, "type": $scope.form.type }; TokenFactory.enroll($scope.newUser, params, function (data) { $scope.clientpart = ""; $scope.callback(data); }); }; // Special Token functions $scope.sshkeyChanged = function () { var keyArr = $scope.form.sshkey.split(" "); $scope.form.description = keyArr.slice(2).join(" "); }; $scope.yubikeyGetLen = function () { if ($scope.tempData.yubikeyTest.length >= 32) { $scope.form.otplen = $scope.tempData.yubikeyTest.length; if ($scope.tempData.yubikeyTest.length > 32) { $scope.tempData.yubikeyUid = true; $scope.tempData.yubikeyUidLen = $scope.tempData.yubikeyTest.length - 32; } } }; // U2F $scope.register_u2f = function (registerRequest) { U2fFactory.register_request(registerRequest, function (params) { params.serial = $scope.serial; TokenFactory.enroll($scope.newUser, params, function (response) { $scope.click_wait = false; $scope.U2FToken.subject = response.detail.u2fRegisterResponse.subject; $scope.U2FToken.vendor = $scope.U2FToken.subject.split(" ")[0]; //debug: console.log($scope.U2FToken); }); }); }; // get the list of configured RADIUS server identifiers $scope.getRADIUSIdentifiers = function() { ConfigFactory.getRadiusNames(function(data){ $scope.radiusIdentifiers = data.result.value; }); }; // get the list of configured CA connectors $scope.getCAConnectors = function () { ConfigFactory.getCAConnectorNames(function (data){ var CAConnectors = data.result.value; angular.forEach(CAConnectors, function(value, key){ $scope.CAConnectors.push(value.connectorname); $scope.form.ca = value.connectorname; $scope.CATemplates[value.connectorname] = value; }); //debug: console.log($scope.CAConnectors); }); }; // If the user is admin, he can read the config. ConfigFactory.loadSystemConfig(function (data) { /* Default config values like radius.server, radius.secret... are stored in systemDefault and $scope.form */ $scope.systemDefault = data.result.value; //debug: console.log("system default config"); //debug: console.log(systemDefault); // TODO: The entries should be handled automatically. var entries = ["radius.server", "radius.secret", "remote.server", "radius.identifier", "email.mailserver", "email.mailfrom", "yubico.id", "tiqr.regServer"]; entries.forEach(function(entry) { if (!$scope.form[entry]) { // preset the UI $scope.form[entry] = $scope.systemDefault[entry]; } }); // Default HOTP hashlib $scope.form.hashlib = $scope.systemDefault["hotp.hashlib"] || 'sha1'; // Now add the questions angular.forEach($scope.systemDefault, function(value, key) { if (key.indexOf("question.question.") === 0) { $scope.questions.push(value); } }); $scope.num_answers = $scope.systemDefault["question.num_answers"]; //debug: console.log($scope.questions); //debug: console.log($scope.form); }); // open the window to generate the key pair $scope.openCertificateWindow = function () { var params = {authtoken: AuthFactory.getAuthToken(), ca: $scope.form.ca}; var tabWindowId = window.open('about:blank', '_blank'); $http.post(instanceUrl + '/certificate', params).then( function (response) { //debug: console.log(response); tabWindowId.document.write(response.data); //tabWindowId.location.href = response.headers('Location'); }); }; // print the paper token $scope.printOtp = function () { var serial = $scope.enrolledToken.serial; var mywindow = window.open('', 'otpPrintingWindow', 'height=400,width=600'); var css = '<link' + ' href="' + instanceUrl + '/static/css/papertoken.css"' + ' rel="stylesheet">'; mywindow.document.write('<html><head><title>'+serial+'</title>'); mywindow.document.write(css); mywindow.document.write('</head>' + '<body onload="window.print(); window.close()">'); mywindow.document.write($('#paperOtpTable').html()); mywindow.document.write('</body></html>'); mywindow.document.close(); // necessary for IE >= 10 mywindow.focus(); // necessary for IE >= 10 return true; }; // =========================================================== // =============== Date stuff =============================== // =========================================================== $scope.openDate = function($event) { $event.stopPropagation(); return true; }; $scope.today = new Date(); $scope.dateOptions = { formatYear: 'yy', startingDay: 1 }; }); myApp.controller("tokenImportController", function ($scope, $upload, AuthFactory, tokenUrl, ConfigFactory, inform) { $scope.formInit = { fileTypes: ["aladdin-xml", "OATH CSV", "Yubikey CSV", "pskc"] }; // These are values that are also sent to the backend! $scope.form = { type: "OATH CSV", realm: "" }; // get Realms ConfigFactory.getRealms(function (data) { $scope.realms = data.result.value; // Preset the default realm angular.forEach($scope.realms, function (realm, realmname) { if (realm.default) { $scope.form.realm = realmname; } }); }); // get PGP keys ConfigFactory.getPGPKeys(function (data) { $scope.pgpkeys = data.result.value; }); $scope.upload = function (files) { if (files && files.length) { for (var i = 0; i < files.length; i++) { var file = files[i]; $upload.upload({ url: tokenUrl + '/load/filename', headers: {'PI-Authorization': AuthFactory.getAuthToken()}, fields: {type: $scope.form.type, psk: $scope.form.psk, password: $scope.form.password, tokenrealms: $scope.form.realm}, file: file }).progress(function (evt) { $scope.progressPercentage = parseInt(100.0 * evt.loaded / evt.total); }).success(function (data, status, headers, config) { $scope.uploadedFile = config.file.name; $scope.uploadedTokens = data.result.value; }).error(function (error) { if (error.result.error.code === -401) { $state.go('login'); } else { inform.add(error.result.error.message, {type: "danger", ttl: 10000}); } }); } } }; });
privacyidea/static/components/token/controllers/tokenControllers.js
/** * http://www.privacyidea.org * (c) cornelius kölbel, [email protected] * * 2015-01-11 Cornelius Kölbel, <[email protected]> * * This code is free software; you can redistribute it and/or * modify it under the terms of the GNU AFFERO GENERAL PUBLIC LICENSE * License as published by the Free Software Foundation; either * version 3 of the License, or any later version. * * This code 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 AFFERO GENERAL PUBLIC LICENSE for more details. * * You should have received a copy of the GNU Affero General Public * License along with this program. If not, see <http://www.gnu.org/licenses/>. * */ myApp.controller("tokenController", function (TokenFactory, ConfigFactory, $scope, $location, AuthFactory, instanceUrl, $rootScope, gettextCatalog, hotkeys) { $scope.tokensPerPage = $scope.token_page_size; $scope.params = {page: 1, sortdir: "asc"}; $scope.reverse = false; $scope.loggedInUser = AuthFactory.getUser(); $scope.selectedToken = {serial: null}; $scope.clientpart = ""; // Change the pagination $scope.pageChanged = function () { //debug: console.log('Page changed to: ' + $scope.params.page); $scope.get(); }; // This function fills $scope.tokendata $scope.get = function (live_search) { if ((!$rootScope.search_on_enter) || ($rootScope.search_on_enter && !live_search)) { $scope.params.serial = "*" + ($scope.serialFilter || "") + "*"; $scope.params.tokenrealm = "*" + ($scope.tokenrealmFilter || "") + "*"; $scope.params.type = "*" + ($scope.typeFilter || "") + "*"; $scope.params.description = "*" + ($scope.descriptionFilter || "") + "*"; $scope.params.userid = "*" + ($scope.userIdFilter || "") + "*"; $scope.params.resolver = "*" + ($scope.resolverFilter || "") + "*"; $scope.params.pagesize = $scope.token_page_size; $scope.params.sortBy = $scope.sortBy; if ($scope.reverse) { $scope.params.sortdir = "desc"; } else { $scope.params.sortdir = "asc"; } TokenFactory.getTokens(function (data) { if (data) { $scope.tokendata = data.result.value; } }, $scope.params); } }; if ($scope.loggedInUser.role === "admin") { /* * Functions to check and to create a default realm. At the moment this is * in the tokenview, as the token view is the first view. This could be * changed to be located anywhere else. */ ConfigFactory.getRealms(function (data) { // Check if there is a realm defined, or if we should display the // Auto Create Dialog var number_of_realms = Object.keys(data.result.value).length; if (number_of_realms === 0) { $('#dialogAutoCreateRealm').modal(); } }); /* Welcome dialog, which displays a lot of information to the administrator. We display it if subscription_state = 0 and hide_welcome = false subscription_state = 1 subscription_state = 2 */ if ($scope.welcomeStep < 4) { // We did not walk throught the welcome dialog, yet. if (($scope.subscription_state === 0 && !$scope.hide_welcome) || ($scope.subscription_state === 1) || ($scope.subscription_state === 2)) { $('#dialogWelcome').modal("show"); $("body").addClass("modal-open"); } } } // single token function $scope.reset = function (serial) { TokenFactory.reset(serial, $scope.get); }; $scope.disable = function (serial) { TokenFactory.disable(serial, $scope.get); }; $scope.enable = function (serial) { TokenFactory.enable(serial, $scope.get); }; if ($location.path() === "/token/list") { $scope.get(); } // go to the list view by default if ($location.path() === "/token") { $location.path("/token/list"); } // go to token.wizard, if the wizard is defined if ($scope.token_wizard) { $location.path("/token/wizard"); } // go to change PIN, if we should change the PIN if ($scope.pin_change) { $location.path("/pinchange"); } // listen to the reload broadcast $scope.$on("piReload", function() { /* Due to the parameter "live_search" in the get function we can not bind the get-function to piReload below. This will break in Chrome, would work in Firefox. So we need this wrapper function */ $scope.get(); }); }); myApp.controller("tokenAssignController", function ($scope, TokenFactory, $stateParams, AuthFactory, UserFactory, $state) { $scope.assignToken = function () { TokenFactory.assign({ serial: fixSerial($scope.newToken.serial), pin: $scope.newToken.pin }, function () { $state.go('token.list'); }); }; }); myApp.controller("tokenEnrollController", function ($scope, TokenFactory, $timeout, $stateParams, AuthFactory, UserFactory, $state, ConfigFactory, instanceUrl, $http, hotkeys, gettextCatalog, inform, U2fFactory) { hotkeys.bindTo($scope).add({ combo: 'alt+e', description: gettextCatalog.getString('Enroll a new token'), callback: function (event, hotkey) { event.preventDefault(); $state.go('token.enroll'); $scope.enrolledToken = null; } }); hotkeys.bindTo($scope).add({ combo: 'alt+r', description: gettextCatalog.getString('Roll the token'), callback: function () { $scope.enrollToken(); } }); $scope.qrCodeWidth = 250; if ($state.includes('token.wizard') && !$scope.show_seed) { $scope.qrCodeWidth = 500; } $scope.checkRight = AuthFactory.checkRight; $scope.loggedInUser = AuthFactory.getUser(); $scope.newUser = {}; $scope.tempData = {}; $scope.instanceUrl = instanceUrl; $scope.click_wait = true; $scope.U2FToken = {}; // System default values for enrollment $scope.systemDefault = {}; // questions for questionnaire token $scope.questions = []; $scope.num_questions = 5; // These are values that are also sent to the backend! $scope.form = { timeStep: 30, otplen: 6, genkey: true, type: $scope.default_tokentype, hashlib: "sha1", 'radius.system_settings': true }; $scope.vasco = { // Note: A primitive does not work in the ng-model of the checkbox! useIt: false }; $scope.formInit = { tokenTypes: {"hotp": gettextCatalog.getString("HOTP: event based One Time Passwords"), "totp": gettextCatalog.getString("TOTP: time based One Time Passwords"), "spass": gettextCatalog.getString("SPass: Simple Pass token. Static passwords"), "motp": gettextCatalog.getString("mOTP: classical mobile One Time Passwords"), "sshkey": gettextCatalog.getString("SSH Public Key: The public SSH key"), "yubikey": gettextCatalog.getString("Yubikey AES mode: One Time Passwords with" + " Yubikey"), "remote": gettextCatalog.getString("Remote Token: Forward authentication request" + " to another server"), "yubico": gettextCatalog.getString("Yubikey Cloud mode: Forward authentication" + " request to YubiCloud"), "radius": gettextCatalog.getString("RADIUS: Forward authentication request to a" + " RADIUS server"), "email": gettextCatalog.getString("EMail: Send a One Time Password to the users email" + " address."), "sms": gettextCatalog.getString("SMS: Send a One Time Password to the users" + " mobile phone."), "certificate": gettextCatalog.getString("Certificate: Enroll an x509 Certificate" + " Token."), "4eyes": gettextCatalog.getString("Four Eyes: Two or more users are required to" + " log in."), "tiqr": gettextCatalog.getString("TiQR: Authenticate with Smartphone by scanning" + " a QR code."), "u2f": gettextCatalog.getString("U2F: Universal 2nd Factor hardware token."), "indexedsecret": gettextCatalog.getString("IndexedSecret: Challenge token based on a shared secret."), "paper": gettextCatalog.getString("PAPER: OTP values on a sheet of paper.")}, timesteps: [30, 60], otplens: [6, 8], hashlibs: ["sha1", "sha256", "sha512"] }; $scope.setVascoSerial = function() { if ($scope.form.otpkey.length === 496) { //console.log('DEBUG: got 496 hexlify otpkey, check vasco serialnumber!'); // convert hexlified input blob to ascii and use the serialnumber (first 10 chars) var vasco_hex = $scope.form.otpkey.toString();//force conversion var vasco_otpstr = ''; for (var i = 0; i < vasco_hex.length; i += 2) vasco_otpstr += String.fromCharCode(parseInt(vasco_hex.substr(i, 2), 16)); var vasco_serial = vasco_otpstr.slice(0, 10); //console.log(vasco_serial); $scope.vascoSerial = vasco_serial; if ($scope.vasco.useIt) { $scope.form.serial = vasco_serial; } else { delete $scope.form.serial; } } else { // If we do not have 496 characters this might be no correct vasco blob. // So we reset the serial $scope.vascoSerial = ""; delete $scope.form.serial; } }; // These token need to PIN // TODO: This is also contained in the tokentype class! $scope.changeTokenType = function() { //debug: console.log("Token Type Changed."); if (["sshkey", "certificate"].indexOf($scope.form.type) >= 0) { $scope.hidePin = true; } else { $scope.hidePin = false; } if ($scope.form.type === "hotp") { // preset HOTP hashlib $scope.form.hashlib = $scope.systemDefault['hotp.hashlib'] || 'sha1'; } else if ($scope.form.type === "totp") { // preset TOTP hashlib $scope.form.hashlib = $scope.systemDefault['totp.hashlib'] || 'sha1'; $scope.form.timeStep = parseInt($scope.systemDefault['totp.timeStep'] || '30'); } if ($scope.form.type === "vasco") { $scope.form.genkey = false; } else { $scope.form.genkey = true; } $scope.preset_indexedsecret(); if ($scope.form.type === "radius") { // only load RADIUS servers when the user actually tries to enroll a RADIUS token, // because the user might not be allowed to list RADIUS servers $scope.getRADIUSIdentifiers(); } if ($scope.form.type === "certificate") { $scope.getCAConnectors(); } // preset twostep enrollment $scope.setTwostepEnrollmentDefault(); }; // helper function for setting indexed secret attribute $scope.preset_indexedsecret = function() { if ($scope.form.type === "indexedsecret") { // in case of indexedsecret we do never generate a key from the UI $scope.form.genkey = false; // Only fetch, if a preset_attribute is defined if ($scope.tokensettings.indexedsecret.preset_attribute) { // getUsers will only work, if we are admin if (AuthFactory.getRole() === 'admin') { UserFactory.getUsers({realm: $scope.newUser.realm, username: fixUser($scope.newUser.user)}, function(data) { var userObject = data.result.value[0]; // preset for indexedsecret token $scope.form.otpkey = userObject[$scope.tokensettings.indexedsecret.preset_attribute]; }); } } } }; // Set the default value of the "2stepinit" field if twostep enrollment should be forced $scope.setTwostepEnrollmentDefault = function () { $scope.form["2stepinit"] = $scope.checkRight($scope.form.type + "_2step=force"); }; // Initially set the default value $scope.setTwostepEnrollmentDefault(); // A watch function to change the form data in case another user is selected $scope.$watch(function(scope) {return scope.newUser.email;}, function(newValue, oldValue){ if (newValue != '') { $scope.form.email = newValue; } }); $scope.$watch(function(scope) {return scope.newUser.mobile;}, function(newValue, oldValue){ if (newValue != '') { $scope.form.phone = newValue; } }); $scope.$watch(function(scope) {return fixUser(scope.newUser.user);}, function(newValue, oldValue) { // The newUser was changed $scope.preset_indexedsecret(); }); // Get the realms and fill the realm dropdown box if (AuthFactory.getRole() === 'admin') { ConfigFactory.getRealms(function (data) { $scope.realms = data.result.value; // Set the default realm var size = Object.keys($scope.realms).length; angular.forEach($scope.realms, function (realm, realmname) { if (size === 1) { // if there is only one realm, preset it $scope.newUser = {user: "", realm: realmname}; } // if there is a default realm, preset the default realm if (realm.default && !$stateParams.realmname) { $scope.newUser = {user: "", realm: realmname}; //debug: console.log("tokenEnrollController"); //debug: console.log($scope.newUser); } }); // init the user, if token.enroll was called from the user.details if ($stateParams.realmname) { $scope.newUser.realm = $stateParams.realmname; } if ($stateParams.username) { $scope.newUser.user = $stateParams.username; // preset the mobile and email for SMS or EMAIL token UserFactory.getUsers({realm: $scope.newUser.realm, username: $scope.newUser.user}, function(data) { var userObject = data.result.value[0]; $scope.form.email = userObject.email; if (typeof userObject.mobile === "string") { $scope.form.phone = userObject.mobile; } else { $scope.phone_list = userObject.mobile; if ($scope.phone_list.length === 1) { $scope.form.phone = $scope.phone_list[0]; } } }); } }); } else if (AuthFactory.getRole() === 'user') { // init the user, if token.enroll was called as a normal user $scope.newUser.user = AuthFactory.getUser().username; $scope.newUser.realm = AuthFactory.getUser().realm; } // Read the the tokentypes from the server TokenFactory.getEnrollTokens(function(data){ //debug: console.log("getEnrollTokens"); //debug: console.log(data); $scope.formInit["tokenTypes"] = data.result.value; // set the default tokentype if (!$scope.formInit.tokenTypes.hasOwnProperty( $scope.default_tokentype)) { // if HOTP does not exist, we set another default type for (var tkey in $scope.formInit.tokenTypes) { // set the first key to be the default tokentype $scope.form.type = tkey; // Set the 2step enrollment value $scope.setTwostepEnrollmentDefault(); break; } } }); $scope.CAConnectors = []; $scope.CATemplates = {}; $scope.radioCSR = 'csrgenerate'; // default enrollment callback $scope.callback = function (data) { $scope.U2FToken = {}; $scope.enrolledToken = data.detail; $scope.click_wait=false; if ($scope.enrolledToken.otps) { var otps_count = Object.keys($scope.enrolledToken.otps).length; $scope.otp_row_count = parseInt(otps_count/5 + 0.5); $scope.otp_rows = Object.keys($scope.enrolledToken.otps).slice(0, $scope.otp_row_count); } if ($scope.enrolledToken.certificate) { var blob = new Blob([ $scope.enrolledToken.certificate ], { type : 'text/plain' }); $scope.certificateBlob = (window.URL || window.webkitURL).createObjectURL( blob ); } if ($scope.enrolledToken.pkcs12) { var bytechars = atob($scope.enrolledToken.pkcs12); var byteNumbers = new Array(bytechars.length); for (var i = 0; i < bytechars.length; i++) { byteNumbers[i] = bytechars.charCodeAt(i); } var byteArray = new Uint8Array(byteNumbers); var blob = new Blob([byteArray], {type: 'application/x-pkcs12'}); $scope.pkcs12Blob = (window.URL || window.webkitURL).createObjectURL( blob ); } if ($scope.enrolledToken.u2fRegisterRequest) { // This is the first step of U2F registering // save serial $scope.serial = data.detail.serial; // We need to send the 2nd stage of the U2F enroll $scope.register_u2f($scope.enrolledToken.u2fRegisterRequest); $scope.click_wait=true; } if ($scope.enrolledToken.rollout_state === "clientwait") { $scope.pollTokenInfo(); } $('html,body').scrollTop(0); }; $scope.enrollToken = function () { //debug: console.log($scope.newUser.user); //debug: console.log($scope.newUser.realm); //debug: console.log($scope.newUser.pin); $scope.newUser.user = fixUser($scope.newUser.user); // convert the date object to a string $scope.form.validity_period_start = date_object_to_string($scope.form.validity_period_start); $scope.form.validity_period_end = date_object_to_string($scope.form.validity_period_end); TokenFactory.enroll($scope.newUser, $scope.form, $scope.callback); }; $scope.pollTokenInfo = function () { TokenFactory.getTokenForSerial($scope.enrolledToken.serial, function(data) { $scope.enrolledToken.rollout_state = data.result.value.tokens[0].rollout_state; // Poll the data after 2.5 seconds again if ($scope.enrolledToken.rollout_state === "clientwait") { $timeout($scope.pollTokenInfo, 2500); } }) }; $scope.regenerateToken = function () { var params = $scope.form; params.serial = $scope.enrolledToken.serial; TokenFactory.enroll($scope.newUser, params, $scope.callback); }; $scope.sendClientPart = function () { var params = { "otpkey": $scope.clientpart.replace(/ /g, ""), "otpkeyformat": "base32check", "serial": $scope.enrolledToken.serial, "type": $scope.form.type }; TokenFactory.enroll($scope.newUser, params, function (data) { $scope.clientpart = ""; $scope.callback(data); }); }; // Special Token functions $scope.sshkeyChanged = function () { var keyArr = $scope.form.sshkey.split(" "); $scope.form.description = keyArr.slice(2).join(" "); }; $scope.yubikeyGetLen = function () { if ($scope.tempData.yubikeyTest.length >= 32) { $scope.form.otplen = $scope.tempData.yubikeyTest.length; if ($scope.tempData.yubikeyTest.length > 32) { $scope.tempData.yubikeyUid = true; $scope.tempData.yubikeyUidLen = $scope.tempData.yubikeyTest.length - 32; } } }; // U2F $scope.register_u2f = function (registerRequest) { U2fFactory.register_request(registerRequest, function (params) { params.serial = $scope.serial; TokenFactory.enroll($scope.newUser, params, function (response) { $scope.click_wait = false; $scope.U2FToken.subject = response.detail.u2fRegisterResponse.subject; $scope.U2FToken.vendor = $scope.U2FToken.subject.split(" ")[0]; //debug: console.log($scope.U2FToken); }); }); }; // get the list of configured RADIUS server identifiers $scope.getRADIUSIdentifiers = function() { ConfigFactory.getRadiusNames(function(data){ $scope.radiusIdentifiers = data.result.value; }); }; // get the list of configured CA connectors $scope.getCAConnectors = function () { ConfigFactory.getCAConnectorNames(function (data){ var CAConnectors = data.result.value; angular.forEach(CAConnectors, function(value, key){ $scope.CAConnectors.push(value.connectorname); $scope.form.ca = value.connectorname; $scope.CATemplates[value.connectorname] = value; }); //debug: console.log($scope.CAConnectors); }); }; // If the user is admin, he can read the config. ConfigFactory.loadSystemConfig(function (data) { /* Default config values like radius.server, radius.secret... are stored in systemDefault and $scope.form */ $scope.systemDefault = data.result.value; //debug: console.log("system default config"); //debug: console.log(systemDefault); // TODO: The entries should be handled automatically. var entries = ["radius.server", "radius.secret", "remote.server", "radius.identifier", "email.mailserver", "email.mailfrom", "yubico.id", "tiqr.regServer"]; entries.forEach(function(entry) { if (!$scope.form[entry]) { // preset the UI $scope.form[entry] = $scope.systemDefault[entry]; } }); // Default HOTP hashlib $scope.form.hashlib = $scope.systemDefault["hotp.hashlib"] || 'sha1'; // Now add the questions angular.forEach($scope.systemDefault, function(value, key) { if (key.indexOf("question.question.") === 0) { $scope.questions.push(value); } }); $scope.num_answers = $scope.systemDefault["question.num_answers"]; //debug: console.log($scope.questions); //debug: console.log($scope.form); }); // open the window to generate the key pair $scope.openCertificateWindow = function () { var params = {authtoken: AuthFactory.getAuthToken(), ca: $scope.form.ca}; var tabWindowId = window.open('about:blank', '_blank'); $http.post(instanceUrl + '/certificate', params).then( function (response) { //debug: console.log(response); tabWindowId.document.write(response.data); //tabWindowId.location.href = response.headers('Location'); }); }; // print the paper token $scope.printOtp = function () { var serial = $scope.enrolledToken.serial; var mywindow = window.open('', 'otpPrintingWindow', 'height=400,width=600'); var css = '<link' + ' href="' + instanceUrl + '/static/css/papertoken.css"' + ' rel="stylesheet">'; mywindow.document.write('<html><head><title>'+serial+'</title>'); mywindow.document.write(css); mywindow.document.write('</head>' + '<body onload="window.print(); window.close()">'); mywindow.document.write($('#paperOtpTable').html()); mywindow.document.write('</body></html>'); mywindow.document.close(); // necessary for IE >= 10 mywindow.focus(); // necessary for IE >= 10 return true; }; // =========================================================== // =============== Date stuff =============================== // =========================================================== $scope.openDate = function($event) { $event.stopPropagation(); return true; }; $scope.today = new Date(); $scope.dateOptions = { formatYear: 'yy', startingDay: 1 }; }); myApp.controller("tokenImportController", function ($scope, $upload, AuthFactory, tokenUrl, ConfigFactory, inform) { $scope.formInit = { fileTypes: ["aladdin-xml", "OATH CSV", "Yubikey CSV", "pskc"] }; // These are values that are also sent to the backend! $scope.form = { type: "OATH CSV", realm: "" }; // get Realms ConfigFactory.getRealms(function (data) { $scope.realms = data.result.value; // Preset the default realm angular.forEach($scope.realms, function (realm, realmname) { if (realm.default) { $scope.form.realm = realmname; } }); }); // get PGP keys ConfigFactory.getPGPKeys(function (data) { $scope.pgpkeys = data.result.value; }); $scope.upload = function (files) { if (files && files.length) { for (var i = 0; i < files.length; i++) { var file = files[i]; $upload.upload({ url: tokenUrl + '/load/filename', headers: {'PI-Authorization': AuthFactory.getAuthToken()}, fields: {type: $scope.form.type, psk: $scope.form.psk, password: $scope.form.password, tokenrealms: $scope.form.realm}, file: file }).progress(function (evt) { $scope.progressPercentage = parseInt(100.0 * evt.loaded / evt.total); }).success(function (data, status, headers, config) { $scope.uploadedFile = config.file.name; $scope.uploadedTokens = data.result.value; }).error(function (error) { if (error.result.error.code === -401) { $state.go('login'); } else { inform.add(error.result.error.message, {type: "danger", ttl: 10000}); } }); } } }; });
Also allow the user to preset the indexedsecret
privacyidea/static/components/token/controllers/tokenControllers.js
Also allow the user to preset the indexedsecret
<ide><path>rivacyidea/static/components/token/controllers/tokenControllers.js <ide> $scope.form.genkey = false; <ide> // Only fetch, if a preset_attribute is defined <ide> if ($scope.tokensettings.indexedsecret.preset_attribute) { <del> // getUsers will only work, if we are admin <add> // In case of a normal logged in user, an empty params is fine <add> var params = {}; <ide> if (AuthFactory.getRole() === 'admin') { <del> UserFactory.getUsers({realm: $scope.newUser.realm, <del> username: fixUser($scope.newUser.user)}, <add> params = {realm: $scope.newUser.realm, <add> username: fixUser($scope.newUser.user)}; <add> } <add> UserFactory.getUsers(params, <ide> function(data) { <ide> var userObject = data.result.value[0]; <ide> // preset for indexedsecret token <ide> $scope.form.otpkey = userObject[$scope.tokensettings.indexedsecret.preset_attribute]; <ide> }); <del> } <ide> } <ide> } <ide> };
Java
apache-2.0
f39a4829f61984c556c35cc8a0bc8da267b5527f
0
pferraro/JGroups,pferraro/JGroups,pferraro/JGroups,rhusar/JGroups,belaban/JGroups,belaban/JGroups,rhusar/JGroups,rhusar/JGroups,belaban/JGroups
package org.jgroups.protocols; import org.jgroups.Address; import org.jgroups.Event; import org.jgroups.Global; import org.jgroups.View; import org.jgroups.annotations.LocalAddress; import org.jgroups.annotations.MBean; import org.jgroups.annotations.Property; import org.jgroups.stack.IpAddress; import org.jgroups.util.Runner; import org.jgroups.util.Tuple; import org.jgroups.util.Util; import javax.crypto.SecretKey; import javax.crypto.spec.SecretKeySpec; import javax.net.ssl.*; import java.io.*; import java.net.InetAddress; import java.security.KeyStore; import java.util.Map; import java.util.Objects; /** * Key exchange based on SSL sockets. The key server creates an {@link javax.net.ssl.SSLServerSocket} on a given port * and members fetch the secret key by creating a {@link javax.net.ssl.SSLSocket} to the key server. The key server * authenticates the client (and vice versa) and then sends the secret key over this encrypted channel. * <br/> * When the key exchange has completed, the secret key requester closes its SSL connection to the key server. * <br/> * Note that this implementation should prevent man-in-the-middle attacks. * @author Bela Ban * @since 4.0.5 */ @MBean(description="Key exchange protocol based on an SSL connection between secret key requester and provider " + "(key server) to fetch a shared secret group key from the key server. That shared (symmetric) key is subsequently " + "used to encrypt communication between cluster members") public class SSL_KEY_EXCHANGE extends KeyExchange { protected enum Type { SECRET_KEY_REQ, SECRET_KEY_RSP // data: | length | version | length | secret key | } public interface SessionVerifier { /** Called after creation with session_verifier_arg */ void init(String arg); /** * Called to verify that the session is correct, e.g. by matching the peer's certificate-CN. Needs to throw a * SecurityException if not */ void verify(SSLSession session) throws SecurityException; } @LocalAddress @Property(description="Bind address for the server or client socket. " + "The following special values are also recognized: GLOBAL, SITE_LOCAL, LINK_LOCAL and NON_LOOPBACK", systemProperty={Global.BIND_ADDR}) protected InetAddress bind_addr; @Property(description="The port at which the key server is listening. If the port is not available, the next port " + "will be probed, up to port+port_range. Used by the key server (server) to create an SSLServerSocket and " + "by clients to connect to the key server.") protected int port=2157; @Property(description="The port range to probe") protected int port_range=5; @Property(description="Location of the keystore") protected String keystore_name="keystore.jks"; @Property(description="The type of the keystore. " + "Types are listed in http://docs.oracle.com/javase/8/docs/technotes/tools/unix/keytool.html") protected String keystore_type="JKS"; @Property(description="Password to access the keystore",exposeAsManagedAttribute=false) protected String keystore_password="changeit"; @Property(description="The type of secret key to be sent up the stack (converted from DH). " + "Should be the same as ASYM_ENCRYPT.sym_algorithm if ASYM_ENCRYPT is used") protected String secret_key_algorithm="AES"; @Property(description="If enabled, clients are authenticated as well (not just the server). Set to true to prevent " + "rogue clients to fetch the secret group key (e.g. via man-in-the-middle attacks)") protected boolean require_client_authentication=true; @Property(description="Timeout (in ms) for a socket read. This applies for example to the initial SSL handshake, " + "e.g. if the client connects to a non-JGroups service accidentally running on the same port") protected int socket_timeout=1000; @Property(description="The fully qualified name of a class implementing SessionVerifier") protected String session_verifier_class; @Property(description="The argument to the session verifier") protected String session_verifier_arg; protected SSLContext ssl_ctx; protected SSLServerSocket srv_sock; protected Runner srv_sock_handler; protected KeyStore key_store; protected View view; protected SessionVerifier session_verifier; public InetAddress getBindAddress() {return bind_addr;} public SSL_KEY_EXCHANGE setBindAddress(InetAddress a) {this.bind_addr=a; return this;} public int getPort() {return port;} public SSL_KEY_EXCHANGE setPort(int p) {this.port=p; return this;} public int getPortRange() {return port_range;} public SSL_KEY_EXCHANGE setPortRange(int r) {this.port_range=r; return this;} public String getKeystoreName() {return keystore_name;} public SSL_KEY_EXCHANGE setKeystoreName(String name) {this.keystore_name=name; return this;} public String getKeystoreType() {return keystore_type;} public SSL_KEY_EXCHANGE setKeystoreType(String type) {this.keystore_type=type; return this;} public String getKeystorePassword() {return keystore_password;} public SSL_KEY_EXCHANGE setKeystorePassword(String pwd) {this.keystore_password=pwd; return this;} public String getSecretKeyAlgorithm() {return secret_key_algorithm;} public SSL_KEY_EXCHANGE setSecretKeyAlgorithm(String a) {this.secret_key_algorithm=a; return this;} public boolean getRequireClientAuthentication() {return require_client_authentication;} public SSL_KEY_EXCHANGE setRequireClientAuthentication(boolean b) {this.require_client_authentication=b; return this;} public int getSocketTimeout() {return socket_timeout;} public SSL_KEY_EXCHANGE setSocketTimeout(int timeout) {this.socket_timeout=timeout; return this;} public String getSessionVerifierClass() {return session_verifier_class;} public SSL_KEY_EXCHANGE setSessionVerifierClass(String cl) {this.session_verifier_class=cl; return this;} public String getSessionVerifierArg() {return session_verifier_arg;} public SSL_KEY_EXCHANGE setSessionVerifierArg(String arg) {this.session_verifier_arg=arg; return this;} public KeyStore getKeystore() {return key_store;} public SSL_KEY_EXCHANGE setKeystore(KeyStore ks) {this.key_store=ks; return this;} public SessionVerifier getSessionVerifier() {return session_verifier;} public SSL_KEY_EXCHANGE setSessionVerifier(SessionVerifier s) {this.session_verifier=s; return this;} public SSLContext getSSLContext() {return ssl_ctx;} public SSL_KEY_EXCHANGE setSSLContext(SSLContext ssl_ctx) {this.ssl_ctx=ssl_ctx; return this;} public Address getServerLocation() { return srv_sock == null? null : new IpAddress(getTransport().getBindAddress(), srv_sock.getLocalPort()); } public void init() throws Exception { super.init(); if(port == 0) throw new IllegalStateException("port must not be 0 or else clients will not be able to connect"); ASYM_ENCRYPT asym_encrypt=findProtocolAbove(ASYM_ENCRYPT.class); if(asym_encrypt != null) { String sym_alg=asym_encrypt.symAlgorithm(); if(!Util.match(sym_alg, secret_key_algorithm)) { log.warn("%s: overriding %s=%s to %s from %s", "secret_key_algorithm", local_addr, secret_key_algorithm, sym_alg, ASYM_ENCRYPT.class.getSimpleName()); secret_key_algorithm=sym_alg; } } key_store=KeyStore.getInstance(keystore_type != null? keystore_type : KeyStore.getDefaultType()); InputStream input; try { input=new FileInputStream(keystore_name); } catch(FileNotFoundException not_found) { input=Util.getResourceAsStream(keystore_name, getClass()); } if(input == null) throw new FileNotFoundException(keystore_name); key_store.load(input, keystore_password.toCharArray()); if(session_verifier == null && session_verifier_class != null) { Class<? extends SessionVerifier> verifier_class=Util.loadClass(session_verifier_class, getClass()); session_verifier=verifier_class.getDeclaredConstructor().newInstance(); if(session_verifier_arg != null) session_verifier.init(session_verifier_arg); } } public void start() throws Exception { super.start(); } public void stop() { super.stop(); stopKeyserver(); } public void destroy() { super.destroy(); } public Object up(Event evt) { if(evt.getType() == Event.CONFIG) { if(bind_addr == null) { Map<String,Object> config=evt.getArg(); bind_addr=(InetAddress)config.get("bind_addr"); } return up_prot.up(evt); } return super.up(evt); } public void fetchSecretKeyFrom(Address target) throws Exception { try(SSLSocket sock=createSocketTo(target)) { DataInput in=new DataInputStream(sock.getInputStream()); OutputStream out=sock.getOutputStream(); // send the secret key request out.write(Type.SECRET_KEY_REQ.ordinal()); out.flush(); byte ordinal=in.readByte(); Type rsp=Type.values()[ordinal]; if(rsp != Type.SECRET_KEY_RSP) throw new IllegalStateException(String.format("expected response of %s but got type=%d", Type.SECRET_KEY_RSP, ordinal)); int version_len=in.readInt(); byte[] version=new byte[version_len]; in.readFully(version); int secret_key_len=in.readInt(); byte[] secret_key=new byte[secret_key_len]; in.readFully(secret_key); SecretKey sk=new SecretKeySpec(secret_key, secret_key_algorithm); Tuple<SecretKey,byte[]> tuple=new Tuple<>(sk, version); log.debug("%s: sending up secret key (version: %s)", local_addr, Util.byteArrayToHexString(version)); up_prot.up(new Event(Event.SET_SECRET_KEY, tuple)); } } protected void accept() { try(SSLSocket client_sock=(SSLSocket)srv_sock.accept()) { client_sock.setEnabledCipherSuites(client_sock.getSupportedCipherSuites()); client_sock.startHandshake(); SSLSession sslSession=client_sock.getSession(); log.debug("%s: accepted SSL connection from %s; protocol: %s, cipher suite: %s", local_addr, client_sock.getRemoteSocketAddress(), sslSession.getProtocol(), sslSession.getCipherSuite()); if(session_verifier != null) session_verifier.verify(sslSession); // Start handling application content InputStream in=client_sock.getInputStream(); DataOutput out=new DataOutputStream(client_sock.getOutputStream()); byte ordinal=(byte)in.read(); Type req=Type.values()[ordinal]; if(req != Type.SECRET_KEY_REQ) throw new IllegalStateException(String.format("expected request of %s but got type=%d", Type.SECRET_KEY_REQ, ordinal)); Tuple<SecretKey,byte[]> tuple=(Tuple<SecretKey,byte[]>)up_prot.up(new Event(Event.GET_SECRET_KEY)); if(tuple == null) return; byte[] version=tuple.getVal2(); byte[] secret_key=tuple.getVal1().getEncoded(); out.write(Type.SECRET_KEY_RSP.ordinal()); out.writeInt(version.length); out.write(version, 0, version.length); out.writeInt(secret_key.length); out.write(secret_key); } catch(Throwable t) { log.trace("%s: failure handling client socket: %s", local_addr, t.getMessage()); } } protected void handleView(View view) { Address old_coord=this.view != null? this.view.getCoord() : null; this.view=view; if(Objects.equals(view.getCoord(), local_addr)) { if(!Objects.equals(old_coord, local_addr)) { try { becomeKeyserver(); } catch(Throwable e) { log.error("failed becoming key server", e); } } } else { // stop being keyserver, close the server socket and handler if(Objects.equals(old_coord, local_addr)) stopKeyserver(); } } protected synchronized void becomeKeyserver() throws Exception { if(srv_sock == null || srv_sock.isClosed()) { log.debug("%s: becoming keyserver; creating server socket", local_addr); srv_sock=createServerSocket(); srv_sock_handler=new Runner(getThreadFactory(), SSL_KEY_EXCHANGE.class.getSimpleName() + "-runner", this::accept, () -> Util.close(srv_sock)); srv_sock_handler.start(); log.debug("%s: SSL server socket listening on %s", local_addr, srv_sock.getLocalSocketAddress()); } } protected synchronized void stopKeyserver() { if(srv_sock != null) { Util.close(srv_sock); // should not be necessary (check) srv_sock=null; } if(srv_sock_handler != null) { log.debug("%s: ceasing to be the keyserver; closing the server socket", local_addr); srv_sock_handler.stop(); srv_sock_handler=null; } } protected SSLServerSocket createServerSocket() throws Exception { SSLContext ctx=getContext(); SSLServerSocketFactory sslServerSocketFactory=ctx.getServerSocketFactory(); SSLServerSocket sslServerSocket; for(int i=0; i < port_range; i++) { try { sslServerSocket=(SSLServerSocket)sslServerSocketFactory.createServerSocket(port + i, 50, bind_addr); sslServerSocket.setNeedClientAuth(require_client_authentication); return sslServerSocket; } catch(Throwable t) { } } throw new IllegalStateException(String.format("found no valid port to bind to in range [%d-%d]", port, port+port_range)); } protected SSLSocket createSocketTo(Address target) throws Exception { SSLContext ctx=getContext(); SSLSocketFactory sslSocketFactory=ctx.getSocketFactory(); if(target instanceof IpAddress) return createSocketTo((IpAddress)target, sslSocketFactory); IpAddress dest=(IpAddress)down_prot.down(new Event(Event.GET_PHYSICAL_ADDRESS, target)); SSLSocket sock; for(int i=0; i < port_range; i++) { try { sock=(SSLSocket)sslSocketFactory.createSocket(dest.getIpAddress(), port+i); sock.setSoTimeout(socket_timeout); sock.setEnabledCipherSuites(sock.getSupportedCipherSuites()); sock.startHandshake(); SSLSession sslSession=sock.getSession(); log.debug("%s: created SSL connection to %s (%s); protocol: %s, cipher suite: %s", local_addr, target, sock.getRemoteSocketAddress(), sslSession.getProtocol(), sslSession.getCipherSuite()); if(session_verifier != null) session_verifier.verify(sslSession); return sock; } catch(SecurityException sec_ex) { throw sec_ex; } catch(Throwable t) { } } throw new IllegalStateException(String.format("failed connecting to %s (port range [%d - %d])", dest.getIpAddress(), port, port+port_range)); } protected SSLSocket createSocketTo(IpAddress dest, SSLSocketFactory sslSocketFactory) { try { SSLSocket sock=(SSLSocket)sslSocketFactory.createSocket(dest.getIpAddress(), dest.getPort()); sock.setSoTimeout(socket_timeout); sock.setEnabledCipherSuites(sock.getSupportedCipherSuites()); sock.startHandshake(); SSLSession sslSession=sock.getSession(); log.debug("%s: created SSL connection to %s (%s); protocol: %s, cipher suite: %s", local_addr, dest, sock.getRemoteSocketAddress(), sslSession.getProtocol(), sslSession.getCipherSuite()); if(session_verifier != null) session_verifier.verify(sslSession); return sock; } catch(SecurityException sec_ex) { throw sec_ex; } catch(Throwable t) { throw new IllegalStateException(String.format("failed connecting to %s: %s", dest, t.getMessage())); } } protected SSLContext getContext() throws Exception { if(this.ssl_ctx != null) return this.ssl_ctx; // Create key manager KeyManagerFactory keyManagerFactory=KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm()); keyManagerFactory.init(key_store, keystore_password.toCharArray()); KeyManager[] km=keyManagerFactory.getKeyManagers(); // Create trust manager TrustManagerFactory trustManagerFactory=TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm()); trustManagerFactory.init(key_store); TrustManager[] tm=trustManagerFactory.getTrustManagers(); // Initialize SSLContext SSLContext sslContext=SSLContext.getInstance("TLSv1"); sslContext.init(km, tm, null); return this.ssl_ctx=sslContext; } }
src/org/jgroups/protocols/SSL_KEY_EXCHANGE.java
package org.jgroups.protocols; import org.jgroups.Address; import org.jgroups.Event; import org.jgroups.Global; import org.jgroups.View; import org.jgroups.annotations.LocalAddress; import org.jgroups.annotations.MBean; import org.jgroups.annotations.Property; import org.jgroups.stack.IpAddress; import org.jgroups.util.Runner; import org.jgroups.util.Tuple; import org.jgroups.util.Util; import javax.crypto.SecretKey; import javax.crypto.spec.SecretKeySpec; import javax.net.ssl.*; import java.io.*; import java.net.InetAddress; import java.security.KeyStore; import java.security.MessageDigest; import java.security.NoSuchAlgorithmException; import java.security.PublicKey; import java.util.Map; import java.util.Objects; /** * Key exchange based on SSL sockets. The key server creates an {@link javax.net.ssl.SSLServerSocket} on a given port * and members fetch the secret key by creating a {@link javax.net.ssl.SSLSocket} to the key server. The key server * authenticates the client (and vice versa) and then sends the secret key over this encrypted channel. * <br/> * When the key exchange has completed, the secret key requester closes its SSL connection to the key server. * <br/> * Note that this implementation should prevent man-in-the-middle attacks. * @author Bela Ban * @since 4.0.5 */ @MBean(description="Key exchange protocol based on an SSL connection between secret key requester and provider " + "(key server) to fetch a shared secret group key from the key server. That shared (symmetric) key is subsequently " + "used to encrypt communication between cluster members") public class SSL_KEY_EXCHANGE extends KeyExchange { protected enum Type { SECRET_KEY_REQ, SECRET_KEY_RSP // data: | length | version | length | secret key | } public interface SessionVerifier { /** Called after creation with session_verifier_arg */ void init(String arg); /** * Called to verify that the session is correct, e.g. by matching the peer's certificate-CN. Needs to throw a * SecurityException if not */ void verify(SSLSession session) throws SecurityException; } @LocalAddress @Property(description="Bind address for the server or client socket. " + "The following special values are also recognized: GLOBAL, SITE_LOCAL, LINK_LOCAL and NON_LOOPBACK", systemProperty={Global.BIND_ADDR}) protected InetAddress bind_addr; @Property(description="The port at which the key server is listening. If the port is not available, the next port " + "will be probed, up to port+port_range. Used by the key server (server) to create an SSLServerSocket and " + "by clients to connect to the key server.") protected int port=2157; @Property(description="The port range to probe") protected int port_range=5; @Property(description="Location of the keystore") protected String keystore_name="keystore.jks"; @Property(description="The type of the keystore. " + "Types are listed in http://docs.oracle.com/javase/8/docs/technotes/tools/unix/keytool.html") protected String keystore_type="JKS"; @Property(description="Password to access the keystore",exposeAsManagedAttribute=false) protected String keystore_password="changeit"; @Property(description="The type of secret key to be sent up the stack (converted from DH). " + "Should be the same as ASYM_ENCRYPT.sym_algorithm if ASYM_ENCRYPT is used") protected String secret_key_algorithm="AES"; @Property(description="If enabled, clients are authenticated as well (not just the server). Set to true to prevent " + "rogue clients to fetch the secret group key (e.g. via man-in-the-middle attacks)") protected boolean require_client_authentication=true; @Property(description="Timeout (in ms) for a socket read. This applies for example to the initial SSL handshake, " + "e.g. if the client connects to a non-JGroups service accidentally running on the same port") protected int socket_timeout=1000; @Property(description="The fully qualified name of a class implementing SessionVerifier") protected String session_verifier_class; @Property(description="The argument to the session verifier") protected String session_verifier_arg; protected SSLContext ssl_ctx; protected SSLServerSocket srv_sock; protected Runner srv_sock_handler; protected KeyStore key_store; protected View view; protected SessionVerifier session_verifier; public InetAddress getBindAddress() {return bind_addr;} public SSL_KEY_EXCHANGE setBindAddress(InetAddress a) {this.bind_addr=a; return this;} public int getPort() {return port;} public SSL_KEY_EXCHANGE setPort(int p) {this.port=p; return this;} public int getPortRange() {return port_range;} public SSL_KEY_EXCHANGE setPortRange(int r) {this.port_range=r; return this;} public String getKeystoreName() {return keystore_name;} public SSL_KEY_EXCHANGE setKeystoreName(String name) {this.keystore_name=name; return this;} public String getKeystoreType() {return keystore_type;} public SSL_KEY_EXCHANGE setKeystoreType(String type) {this.keystore_type=type; return this;} public String getKeystorePassword() {return keystore_password;} public SSL_KEY_EXCHANGE setKeystorePassword(String pwd) {this.keystore_password=pwd; return this;} public String getSecretKeyAlgorithm() {return secret_key_algorithm;} public SSL_KEY_EXCHANGE setSecretKeyAlgorithm(String a) {this.secret_key_algorithm=a; return this;} public boolean getRequireClientAuthentication() {return require_client_authentication;} public SSL_KEY_EXCHANGE setRequireClientAuthentication(boolean b) {require_client_authentication=b; return this;} public int getSocketTimeout() {return socket_timeout;} public SSL_KEY_EXCHANGE setSocketTimeout(int timeout) {this.socket_timeout=timeout; return this;} public String getSessionVerifierClass() {return session_verifier_class;} public SSL_KEY_EXCHANGE setSessionVerifierClass(String cl) {this.session_verifier_class=cl; return this;} public String getSessionVerifierArg() {return session_verifier_arg;} public SSL_KEY_EXCHANGE setSessionVerifierArg(String arg) {this.session_verifier_arg=arg; return this;} public KeyStore getKeystore() {return key_store;} public SSL_KEY_EXCHANGE setKeystore(KeyStore ks) {this.key_store=ks; return this;} public SessionVerifier getSessionVerifier() {return session_verifier;} public SSL_KEY_EXCHANGE setSessionVerifier(SessionVerifier s) {this.session_verifier=s; return this;} public SSLContext getSSLContext() {return ssl_ctx;} public SSL_KEY_EXCHANGE setSSLContext(SSLContext ssl_ctx) {this.ssl_ctx=ssl_ctx; return this;} public Address getServerLocation() { return srv_sock == null? null : new IpAddress(getTransport().getBindAddress(), srv_sock.getLocalPort()); } public void init() throws Exception { super.init(); if(port == 0) throw new IllegalStateException("port must not be 0 or else clients will not be able to connect"); ASYM_ENCRYPT asym_encrypt=findProtocolAbove(ASYM_ENCRYPT.class); if(asym_encrypt != null) { String sym_alg=asym_encrypt.symAlgorithm(); if(!Util.match(sym_alg, secret_key_algorithm)) { log.warn("%s: overriding %s=%s to %s from %s", "secret_key_algorithm", local_addr, secret_key_algorithm, sym_alg, ASYM_ENCRYPT.class.getSimpleName()); secret_key_algorithm=sym_alg; } } key_store=KeyStore.getInstance(keystore_type != null? keystore_type : KeyStore.getDefaultType()); InputStream input=null; try { input=new FileInputStream(keystore_name); } catch(FileNotFoundException not_found) { input=Util.getResourceAsStream(keystore_name, getClass()); } if(input == null) throw new FileNotFoundException(keystore_name); key_store.load(input, keystore_password.toCharArray()); if(session_verifier == null && session_verifier_class != null) { Class<? extends SessionVerifier> verifier_class=Util.loadClass(session_verifier_class, getClass()); session_verifier=verifier_class.getDeclaredConstructor().newInstance(); if(session_verifier_arg != null) session_verifier.init(session_verifier_arg); } } public void start() throws Exception { super.start(); } public void stop() { super.stop(); stopKeyserver(); } public void destroy() { super.destroy(); } public Object up(Event evt) { if(evt.getType() == Event.CONFIG) { if(bind_addr == null) { Map<String,Object> config=evt.getArg(); bind_addr=(InetAddress)config.get("bind_addr"); } return up_prot.up(evt); } return super.up(evt); } public void fetchSecretKeyFrom(Address target) throws Exception { try(SSLSocket sock=createSocketTo(target)) { DataInput in=new DataInputStream(sock.getInputStream()); OutputStream out=sock.getOutputStream(); // send the secret key request out.write(Type.SECRET_KEY_REQ.ordinal()); out.flush(); byte ordinal=in.readByte(); Type rsp=Type.values()[ordinal]; if(rsp != Type.SECRET_KEY_RSP) throw new IllegalStateException(String.format("expected response of %s but got type=%d", Type.SECRET_KEY_RSP, ordinal)); int version_len=in.readInt(); byte[] version=new byte[version_len]; in.readFully(version); int secret_key_len=in.readInt(); byte[] secret_key=new byte[secret_key_len]; in.readFully(secret_key); SecretKey sk=new SecretKeySpec(secret_key, secret_key_algorithm); Tuple<SecretKey,byte[]> tuple=new Tuple<>(sk, version); log.debug("%s: sending up secret key (version: %s)", local_addr, Util.byteArrayToHexString(version)); up_prot.up(new Event(Event.SET_SECRET_KEY, tuple)); } } protected void accept() { try(SSLSocket client_sock=(SSLSocket)srv_sock.accept()) { client_sock.setEnabledCipherSuites(client_sock.getSupportedCipherSuites()); client_sock.startHandshake(); SSLSession sslSession=client_sock.getSession(); log.debug("%s: accepted SSL connection from %s; protocol: %s, cipher suite: %s", local_addr, client_sock.getRemoteSocketAddress(), sslSession.getProtocol(), sslSession.getCipherSuite()); if(session_verifier != null) session_verifier.verify(sslSession); // Start handling application content InputStream in=client_sock.getInputStream(); DataOutput out=new DataOutputStream(client_sock.getOutputStream()); byte ordinal=(byte)in.read(); Type req=Type.values()[ordinal]; if(req != Type.SECRET_KEY_REQ) throw new IllegalStateException(String.format("expected request of %s but got type=%d", Type.SECRET_KEY_REQ, ordinal)); Tuple<SecretKey,byte[]> tuple=(Tuple<SecretKey,byte[]>)up_prot.up(new Event(Event.GET_SECRET_KEY)); if(tuple == null) return; byte[] version=tuple.getVal2(); byte[] secret_key=tuple.getVal1().getEncoded(); out.write(Type.SECRET_KEY_RSP.ordinal()); out.writeInt(version.length); out.write(version, 0, version.length); out.writeInt(secret_key.length); out.write(secret_key); } catch(Throwable t) { log.trace("%s: failure handling client socket: %s", local_addr, t.getMessage()); } } protected void handleView(View view) { Address old_coord=this.view != null? this.view.getCoord() : null; this.view=view; if(Objects.equals(view.getCoord(), local_addr)) { if(!Objects.equals(old_coord, local_addr)) { try { becomeKeyserver(); } catch(Throwable e) { log.error("failed becoming key server", e); } } } else { // stop being keyserver, close the server socket and handler if(Objects.equals(old_coord, local_addr)) stopKeyserver(); } } protected synchronized void becomeKeyserver() throws Exception { if(srv_sock == null || srv_sock.isClosed()) { log.debug("%s: becoming keyserver; creating server socket", local_addr); srv_sock=createServerSocket(); srv_sock_handler=new Runner(getThreadFactory(), SSL_KEY_EXCHANGE.class.getSimpleName() + "-runner", this::accept, () -> Util.close(srv_sock)); srv_sock_handler.start(); log.debug("%s: SSL server socket listening on %s", local_addr, srv_sock.getLocalSocketAddress()); } } protected synchronized void stopKeyserver() { if(srv_sock != null) { Util.close(srv_sock); // should not be necessary (check) srv_sock=null; } if(srv_sock_handler != null) { log.debug("%s: ceasing to be the keyserver; closing the server socket", local_addr); srv_sock_handler.stop(); srv_sock_handler=null; } } protected SSLServerSocket createServerSocket() throws Exception { SSLContext ctx=getContext(); SSLServerSocketFactory sslServerSocketFactory=ctx.getServerSocketFactory(); SSLServerSocket sslServerSocket=null; for(int i=0; i < port_range; i++) { try { sslServerSocket=(SSLServerSocket)sslServerSocketFactory.createServerSocket(port + i, 50, bind_addr); sslServerSocket.setNeedClientAuth(require_client_authentication); return sslServerSocket; } catch(Throwable t) { } } throw new IllegalStateException(String.format("found no valid port to bind to in range [%d-%d]", port, port+port_range)); } protected SSLSocket createSocketTo(Address target) throws Exception { SSLContext ctx=getContext(); SSLSocketFactory sslSocketFactory=ctx.getSocketFactory(); if(target instanceof IpAddress) return createSocketTo((IpAddress)target, sslSocketFactory); IpAddress dest=(IpAddress)down_prot.down(new Event(Event.GET_PHYSICAL_ADDRESS, target)); SSLSocket sock=null; for(int i=0; i < port_range; i++) { try { sock=(SSLSocket)sslSocketFactory.createSocket(dest.getIpAddress(), port+i); sock.setSoTimeout(socket_timeout); sock.setEnabledCipherSuites(sock.getSupportedCipherSuites()); sock.startHandshake(); SSLSession sslSession=sock.getSession(); log.debug("%s: created SSL connection to %s (%s); protocol: %s, cipher suite: %s", local_addr, target, sock.getRemoteSocketAddress(), sslSession.getProtocol(), sslSession.getCipherSuite()); if(session_verifier != null) session_verifier.verify(sslSession); return sock; } catch(SecurityException sec_ex) { throw sec_ex; } catch(Throwable t) { } } throw new IllegalStateException(String.format("failed connecting to %s (port range [%d - %d])", dest.getIpAddress(), port, port+port_range)); } protected SSLSocket createSocketTo(IpAddress dest, SSLSocketFactory sslSocketFactory) { try { SSLSocket sock=(SSLSocket)sslSocketFactory.createSocket(dest.getIpAddress(), dest.getPort()); sock.setSoTimeout(socket_timeout); sock.setEnabledCipherSuites(sock.getSupportedCipherSuites()); sock.startHandshake(); SSLSession sslSession=sock.getSession(); log.debug("%s: created SSL connection to %s (%s); protocol: %s, cipher suite: %s", local_addr, dest, sock.getRemoteSocketAddress(), sslSession.getProtocol(), sslSession.getCipherSuite()); if(session_verifier != null) session_verifier.verify(sslSession); return sock; } catch(SecurityException sec_ex) { throw sec_ex; } catch(Throwable t) { throw new IllegalStateException(String.format("failed connecting to %s: %s", dest, t.getMessage())); } } protected SSLContext getContext() throws Exception { if(this.ssl_ctx != null) return this.ssl_ctx; // Create key manager KeyManagerFactory keyManagerFactory=KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm()); keyManagerFactory.init(key_store, keystore_password.toCharArray()); KeyManager[] km=keyManagerFactory.getKeyManagers(); // Create trust manager // TrustManagerFactory trustManagerFactory=TrustManagerFactory.getInstance("SunX509"); TrustManagerFactory trustManagerFactory=TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm()); trustManagerFactory.init(key_store); TrustManager[] tm=trustManagerFactory.getTrustManagers(); // Initialize SSLContext SSLContext sslContext=SSLContext.getInstance("TLSv1"); sslContext.init(km, tm, null); return this.ssl_ctx=sslContext; } protected static String print16(PublicKey pub_key) { // use SHA256 to create a hash of secret_key and only then truncate it to secret_key_length MessageDigest digest=null; try { digest=MessageDigest.getInstance("SHA-256"); digest.update(pub_key.getEncoded()); return Util.byteArrayToHexString(digest.digest(), 0, 16); } catch(NoSuchAlgorithmException e) { return e.toString(); } } }
Drop unused methods, drop unused imports, drop redudant assignments, and code style in SSL_KEY_EXCHANGE
src/org/jgroups/protocols/SSL_KEY_EXCHANGE.java
Drop unused methods, drop unused imports, drop redudant assignments, and code style in SSL_KEY_EXCHANGE
<ide><path>rc/org/jgroups/protocols/SSL_KEY_EXCHANGE.java <ide> import java.io.*; <ide> import java.net.InetAddress; <ide> import java.security.KeyStore; <del>import java.security.MessageDigest; <del>import java.security.NoSuchAlgorithmException; <del>import java.security.PublicKey; <ide> import java.util.Map; <ide> import java.util.Objects; <ide> <ide> public String getSecretKeyAlgorithm() {return secret_key_algorithm;} <ide> public SSL_KEY_EXCHANGE setSecretKeyAlgorithm(String a) {this.secret_key_algorithm=a; return this;} <ide> public boolean getRequireClientAuthentication() {return require_client_authentication;} <del> public SSL_KEY_EXCHANGE setRequireClientAuthentication(boolean b) {require_client_authentication=b; return this;} <add> public SSL_KEY_EXCHANGE setRequireClientAuthentication(boolean b) {this.require_client_authentication=b; return this;} <ide> public int getSocketTimeout() {return socket_timeout;} <ide> public SSL_KEY_EXCHANGE setSocketTimeout(int timeout) {this.socket_timeout=timeout; return this;} <ide> public String getSessionVerifierClass() {return session_verifier_class;} <ide> } <ide> key_store=KeyStore.getInstance(keystore_type != null? keystore_type : KeyStore.getDefaultType()); <ide> <del> InputStream input=null; <add> InputStream input; <ide> try { <ide> input=new FileInputStream(keystore_name); <ide> } <ide> SSLContext ctx=getContext(); <ide> SSLServerSocketFactory sslServerSocketFactory=ctx.getServerSocketFactory(); <ide> <del> SSLServerSocket sslServerSocket=null; <add> SSLServerSocket sslServerSocket; <ide> for(int i=0; i < port_range; i++) { <ide> try { <ide> sslServerSocket=(SSLServerSocket)sslServerSocketFactory.createServerSocket(port + i, 50, bind_addr); <ide> return createSocketTo((IpAddress)target, sslSocketFactory); <ide> <ide> IpAddress dest=(IpAddress)down_prot.down(new Event(Event.GET_PHYSICAL_ADDRESS, target)); <del> SSLSocket sock=null; <add> SSLSocket sock; <ide> for(int i=0; i < port_range; i++) { <ide> try { <ide> sock=(SSLSocket)sslSocketFactory.createSocket(dest.getIpAddress(), port+i); <ide> KeyManager[] km=keyManagerFactory.getKeyManagers(); <ide> <ide> // Create trust manager <del> // TrustManagerFactory trustManagerFactory=TrustManagerFactory.getInstance("SunX509"); <ide> TrustManagerFactory trustManagerFactory=TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm()); <ide> trustManagerFactory.init(key_store); <ide> TrustManager[] tm=trustManagerFactory.getTrustManagers(); <ide> sslContext.init(km, tm, null); <ide> return this.ssl_ctx=sslContext; <ide> } <del> <del> <del> protected static String print16(PublicKey pub_key) { <del> // use SHA256 to create a hash of secret_key and only then truncate it to secret_key_length <del> MessageDigest digest=null; <del> try { <del> digest=MessageDigest.getInstance("SHA-256"); <del> digest.update(pub_key.getEncoded()); <del> return Util.byteArrayToHexString(digest.digest(), 0, 16); <del> } <del> catch(NoSuchAlgorithmException e) { <del> return e.toString(); <del> } <del> } <del> <del> <del> <ide> } <ide>
Java
apache-2.0
6830eff526ba44bd30b567407313616d1f82a027
0
treasure-data/digdag,treasure-data/digdag,treasure-data/digdag,treasure-data/digdag,treasure-data/digdag,treasure-data/digdag,treasure-data/digdag
package io.digdag.core.database; import com.google.common.base.Optional; import com.google.common.base.Strings; import com.google.common.base.Throwables; import com.google.common.collect.ImmutableList; import io.digdag.core.repository.Project; import io.digdag.core.repository.ProjectStore; import io.digdag.core.repository.StoredProject; import io.digdag.spi.SecretControlStore; import io.digdag.spi.SecretScopes; import io.digdag.spi.SecretStore; import java.util.concurrent.Executors; import java.util.concurrent.ExecutorService; import java.util.concurrent.Future; import java.util.concurrent.atomic.AtomicBoolean; import java.util.concurrent.atomic.AtomicReference; import org.junit.Before; import org.junit.Test; import java.util.Base64; import static java.nio.charset.StandardCharsets.UTF_8; import static org.hamcrest.Matchers.empty; import static org.hamcrest.Matchers.is; import static org.junit.Assert.assertThat; public class DatabaseSecretStoreTest { private static final String SECRET = Base64.getEncoder().encodeToString( Strings.repeat(".", 16).getBytes(UTF_8)); private static final int SITE_ID = 17; private static final String KEY1 = "foo1"; private static final String KEY2 = "foo2"; private static final String VALUE1 = "bar1"; private static final String VALUE2 = "bar2"; private static final String VALUE3 = "bar3"; private DatabaseFactory factory; private StoredProject storedProject; private DatabaseSecretControlStoreManager controlStoreManager; private DatabaseSecretStoreManager storeManager; private SecretControlStore secretControlStore; private SecretStore secretStore; private int projectId; @Before public void setUp() throws Exception { factory = DatabaseTestingUtils.setupDatabase(); ProjectStore projectStore = factory.getProjectStoreManager().getProjectStore(SITE_ID); Project project = Project.of("proj1"); storedProject = projectStore.putAndLockProject(project, (store, stored) -> stored); controlStoreManager = factory.getSecretControlStoreManager(SECRET); storeManager = factory.getSecretStoreManager(SECRET); secretControlStore = controlStoreManager.getSecretControlStore(SITE_ID); secretStore = storeManager.getSecretStore(SITE_ID); projectId = storedProject.getId(); } @Test public void noSecret() throws Exception { assertThat(secretControlStore.listProjectSecrets(projectId, SecretScopes.PROJECT), is(empty())); assertThat(secretStore.getSecret(projectId, KEY1, SecretScopes.PROJECT), is(Optional.absent())); secretControlStore.deleteProjectSecret(projectId, KEY1, SecretScopes.PROJECT); } @Test public void singleSecret() throws Exception { secretControlStore.setProjectSecret(projectId, SecretScopes.PROJECT, KEY1, VALUE1); assertThat(secretStore.getSecret(projectId, SecretScopes.PROJECT, KEY1), is(Optional.of(VALUE1))); } @Test public void lockSecretGetsValue() throws Exception { Optional<String> absent = secretControlStore.lockProjectSecret(projectId, SecretScopes.PROJECT, KEY1, (control, value) -> value); assertThat(absent, is(Optional.absent())); secretControlStore.setProjectSecret(projectId, SecretScopes.PROJECT, KEY1, VALUE1); Optional<String> present = secretControlStore.lockProjectSecret(projectId, SecretScopes.PROJECT, KEY1, (control, value) -> value); assertThat(present, is(Optional.of(VALUE1))); } @Test public void lockSecret() throws Exception { secretControlStore.setProjectSecret(projectId, SecretScopes.PROJECT, KEY1, VALUE1); AtomicReference<Optional<String>> blockedGetValue = new AtomicReference<>(null); AtomicBoolean comitting = new AtomicBoolean(false); AtomicBoolean blockedCheckComitting = new AtomicBoolean(false); Thread thread = secretControlStore.lockProjectSecret(projectId, SecretScopes.PROJECT, KEY1, (control, value) -> { try { AtomicBoolean started = new AtomicBoolean(false); Thread t = new Thread(() -> { started.set(true); blockedGetValue.set( secretControlStore.lockProjectSecret(projectId, SecretScopes.PROJECT, KEY1, (c1, v1) -> v1)); blockedCheckComitting.set(comitting.get()); }); t.setDaemon(true); t.start(); // wait until the thread starts while (!started.get()) { Thread.sleep(500); } // wait some more to make sure that lockProjectSecret is called & blocked Thread.sleep(500); control.setProjectSecret(projectId, SecretScopes.PROJECT, KEY1, VALUE1 + ".changed"); comitting.set(true); return t; } catch (InterruptedException ex) { throw new AssertionError(ex); } }); thread.join(); assertThat(blockedGetValue.get(), is(Optional.of(VALUE1 + ".changed"))); assertThat(blockedCheckComitting.get(), is(true)); } @Test public void multipleSecrets() throws Exception { secretControlStore.setProjectSecret(projectId, SecretScopes.PROJECT, KEY1, VALUE1); secretControlStore.setProjectSecret(projectId, SecretScopes.PROJECT, KEY2, VALUE2); secretControlStore.setProjectSecret(projectId, SecretScopes.PROJECT_DEFAULT, KEY2, VALUE3); assertThat(secretStore.getSecret(projectId, SecretScopes.PROJECT, KEY1), is(Optional.of(VALUE1))); assertThat(secretStore.getSecret(projectId, SecretScopes.PROJECT, KEY2), is(Optional.of(VALUE2))); assertThat(secretStore.getSecret(projectId, SecretScopes.PROJECT_DEFAULT, KEY2), is(Optional.of(VALUE3))); // Delete with different scope should not delete the secret secretControlStore.deleteProjectSecret(projectId, SecretScopes.PROJECT_DEFAULT, KEY1); assertThat(secretStore.getSecret(projectId, SecretScopes.PROJECT, KEY1), is(Optional.of(VALUE1))); assertThat(secretStore.getSecret(projectId, SecretScopes.PROJECT, KEY2), is(Optional.of(VALUE2))); assertThat(secretStore.getSecret(projectId, SecretScopes.PROJECT_DEFAULT, KEY2), is(Optional.of(VALUE3))); secretControlStore.deleteProjectSecret(projectId, SecretScopes.PROJECT, KEY1); assertThat(secretStore.getSecret(projectId, SecretScopes.PROJECT, KEY1), is(Optional.absent())); assertThat(secretStore.getSecret(projectId, SecretScopes.PROJECT, KEY2), is(Optional.of(VALUE2))); assertThat(secretStore.getSecret(projectId, SecretScopes.PROJECT_DEFAULT, KEY2), is(Optional.of(VALUE3))); secretControlStore.deleteProjectSecret(projectId, SecretScopes.PROJECT, KEY2); assertThat(secretStore.getSecret(projectId, SecretScopes.PROJECT, KEY2), is(Optional.absent())); assertThat(secretStore.getSecret(projectId, SecretScopes.PROJECT_DEFAULT, KEY2), is(Optional.of(VALUE3))); } @Test public void getSecretWithScope() throws Exception { String[] scopes = { SecretScopes.PROJECT, SecretScopes.PROJECT_DEFAULT, "foobar"}; for (String setScope : scopes) { secretControlStore.setProjectSecret(projectId, setScope, KEY1, VALUE1); assertThat(secretStore.getSecret(projectId, setScope, KEY1), is(Optional.of(VALUE1))); for (String getScope : scopes) { if (getScope.equals(setScope)) { continue; } assertThat("set: " + setScope + ", get: " + getScope, secretStore.getSecret(projectId, getScope, KEY1), is(Optional.absent())); } secretControlStore.deleteProjectSecret(storedProject.getId(), setScope, KEY1); } } @Test public void concurrentPutShouldNotThrowExceptions() throws Exception { ExecutorService threads = Executors.newCachedThreadPool(); ImmutableList.Builder<Future> futures = ImmutableList.builder(); for (int i = 0; i < 20; i++) { String value = "thread-" + i; futures.add(threads.submit(() -> { try { for (int j = 0; j < 50; j++) { secretControlStore.deleteProjectSecret(projectId, SecretScopes.PROJECT, KEY1); secretControlStore.setProjectSecret(projectId, SecretScopes.PROJECT, KEY1, value); } } catch (Exception ex) { throw Throwables.propagate(ex); } })); } for (Future f : futures.build()) { f.get(); } } }
digdag-core/src/test/java/io/digdag/core/database/DatabaseSecretStoreTest.java
package io.digdag.core.database; import com.google.common.base.Optional; import com.google.common.base.Strings; import com.google.common.base.Throwables; import com.google.common.collect.ImmutableList; import io.digdag.core.repository.Project; import io.digdag.core.repository.ProjectStore; import io.digdag.core.repository.StoredProject; import io.digdag.spi.SecretControlStore; import io.digdag.spi.SecretScopes; import io.digdag.spi.SecretStore; import java.util.concurrent.Executors; import java.util.concurrent.ExecutorService; import java.util.concurrent.Future; import org.junit.Before; import org.junit.Test; import java.util.Base64; import static java.nio.charset.StandardCharsets.UTF_8; import static org.hamcrest.Matchers.empty; import static org.hamcrest.Matchers.is; import static org.junit.Assert.assertThat; public class DatabaseSecretStoreTest { private static final String SECRET = Base64.getEncoder().encodeToString( Strings.repeat(".", 16).getBytes(UTF_8)); private static final int SITE_ID = 17; private static final String KEY1 = "foo1"; private static final String KEY2 = "foo2"; private static final String VALUE1 = "bar1"; private static final String VALUE2 = "bar2"; private static final String VALUE3 = "bar3"; private DatabaseFactory factory; private StoredProject storedProject; private DatabaseSecretControlStoreManager controlStoreManager; private DatabaseSecretStoreManager storeManager; private SecretControlStore secretControlStore; private SecretStore secretStore; private int projectId; @Before public void setUp() throws Exception { factory = DatabaseTestingUtils.setupDatabase(); ProjectStore projectStore = factory.getProjectStoreManager().getProjectStore(SITE_ID); Project project = Project.of("proj1"); storedProject = projectStore.putAndLockProject(project, (store, stored) -> stored); controlStoreManager = factory.getSecretControlStoreManager(SECRET); storeManager = factory.getSecretStoreManager(SECRET); secretControlStore = controlStoreManager.getSecretControlStore(SITE_ID); secretStore = storeManager.getSecretStore(SITE_ID); projectId = storedProject.getId(); } @Test public void noSecret() throws Exception { assertThat(secretControlStore.listProjectSecrets(projectId, SecretScopes.PROJECT), is(empty())); assertThat(secretStore.getSecret(projectId, KEY1, SecretScopes.PROJECT), is(Optional.absent())); secretControlStore.deleteProjectSecret(projectId, KEY1, SecretScopes.PROJECT); } @Test public void singleSecret() throws Exception { secretControlStore.setProjectSecret(projectId, SecretScopes.PROJECT, KEY1, VALUE1); assertThat(secretStore.getSecret(projectId, SecretScopes.PROJECT, KEY1), is(Optional.of(VALUE1))); } @Test public void lockSecret() throws Exception { Optional<String> absent = secretControlStore.lockProjectSecret(projectId, SecretScopes.PROJECT, KEY1, (control, value) -> value); assertThat(absent, is(Optional.absent())); secretControlStore.setProjectSecret(projectId, SecretScopes.PROJECT, KEY1, VALUE1); Optional<String> present = secretControlStore.lockProjectSecret(projectId, SecretScopes.PROJECT, KEY1, (control, value) -> value); assertThat(present, is(Optional.of(VALUE1))); } @Test public void multipleSecrets() throws Exception { secretControlStore.setProjectSecret(projectId, SecretScopes.PROJECT, KEY1, VALUE1); secretControlStore.setProjectSecret(projectId, SecretScopes.PROJECT, KEY2, VALUE2); secretControlStore.setProjectSecret(projectId, SecretScopes.PROJECT_DEFAULT, KEY2, VALUE3); assertThat(secretStore.getSecret(projectId, SecretScopes.PROJECT, KEY1), is(Optional.of(VALUE1))); assertThat(secretStore.getSecret(projectId, SecretScopes.PROJECT, KEY2), is(Optional.of(VALUE2))); assertThat(secretStore.getSecret(projectId, SecretScopes.PROJECT_DEFAULT, KEY2), is(Optional.of(VALUE3))); // Delete with different scope should not delete the secret secretControlStore.deleteProjectSecret(projectId, SecretScopes.PROJECT_DEFAULT, KEY1); assertThat(secretStore.getSecret(projectId, SecretScopes.PROJECT, KEY1), is(Optional.of(VALUE1))); assertThat(secretStore.getSecret(projectId, SecretScopes.PROJECT, KEY2), is(Optional.of(VALUE2))); assertThat(secretStore.getSecret(projectId, SecretScopes.PROJECT_DEFAULT, KEY2), is(Optional.of(VALUE3))); secretControlStore.deleteProjectSecret(projectId, SecretScopes.PROJECT, KEY1); assertThat(secretStore.getSecret(projectId, SecretScopes.PROJECT, KEY1), is(Optional.absent())); assertThat(secretStore.getSecret(projectId, SecretScopes.PROJECT, KEY2), is(Optional.of(VALUE2))); assertThat(secretStore.getSecret(projectId, SecretScopes.PROJECT_DEFAULT, KEY2), is(Optional.of(VALUE3))); secretControlStore.deleteProjectSecret(projectId, SecretScopes.PROJECT, KEY2); assertThat(secretStore.getSecret(projectId, SecretScopes.PROJECT, KEY2), is(Optional.absent())); assertThat(secretStore.getSecret(projectId, SecretScopes.PROJECT_DEFAULT, KEY2), is(Optional.of(VALUE3))); } @Test public void getSecretWithScope() throws Exception { String[] scopes = { SecretScopes.PROJECT, SecretScopes.PROJECT_DEFAULT, "foobar"}; for (String setScope : scopes) { secretControlStore.setProjectSecret(projectId, setScope, KEY1, VALUE1); assertThat(secretStore.getSecret(projectId, setScope, KEY1), is(Optional.of(VALUE1))); for (String getScope : scopes) { if (getScope.equals(setScope)) { continue; } assertThat("set: " + setScope + ", get: " + getScope, secretStore.getSecret(projectId, getScope, KEY1), is(Optional.absent())); } secretControlStore.deleteProjectSecret(storedProject.getId(), setScope, KEY1); } } @Test public void concurrentPutShouldNotThrowExceptions() throws Exception { ExecutorService threads = Executors.newCachedThreadPool(); ImmutableList.Builder<Future> futures = ImmutableList.builder(); for (int i = 0; i < 20; i++) { String value = "thread-" + i; futures.add(threads.submit(() -> { try { for (int j = 0; j < 50; j++) { secretControlStore.deleteProjectSecret(projectId, SecretScopes.PROJECT, KEY1); secretControlStore.setProjectSecret(projectId, SecretScopes.PROJECT, KEY1, value); } } catch (Exception ex) { throw Throwables.propagate(ex); } })); } for (Future f : futures.build()) { f.get(); } } }
added a test case to lockProjectSecret
digdag-core/src/test/java/io/digdag/core/database/DatabaseSecretStoreTest.java
added a test case to lockProjectSecret
<ide><path>igdag-core/src/test/java/io/digdag/core/database/DatabaseSecretStoreTest.java <ide> import java.util.concurrent.Executors; <ide> import java.util.concurrent.ExecutorService; <ide> import java.util.concurrent.Future; <add>import java.util.concurrent.atomic.AtomicBoolean; <add>import java.util.concurrent.atomic.AtomicReference; <ide> import org.junit.Before; <ide> import org.junit.Test; <ide> <ide> } <ide> <ide> @Test <del> public void lockSecret() <add> public void lockSecretGetsValue() <ide> throws Exception <ide> { <ide> Optional<String> absent = secretControlStore.lockProjectSecret(projectId, SecretScopes.PROJECT, KEY1, (control, value) -> value); <ide> secretControlStore.setProjectSecret(projectId, SecretScopes.PROJECT, KEY1, VALUE1); <ide> Optional<String> present = secretControlStore.lockProjectSecret(projectId, SecretScopes.PROJECT, KEY1, (control, value) -> value); <ide> assertThat(present, is(Optional.of(VALUE1))); <add> } <add> <add> @Test <add> public void lockSecret() <add> throws Exception <add> { <add> secretControlStore.setProjectSecret(projectId, SecretScopes.PROJECT, KEY1, VALUE1); <add> <add> AtomicReference<Optional<String>> blockedGetValue = new AtomicReference<>(null); <add> AtomicBoolean comitting = new AtomicBoolean(false); <add> AtomicBoolean blockedCheckComitting = new AtomicBoolean(false); <add> <add> Thread thread = secretControlStore.lockProjectSecret(projectId, SecretScopes.PROJECT, KEY1, (control, value) -> { <add> try { <add> AtomicBoolean started = new AtomicBoolean(false); <add> <add> Thread t = new Thread(() -> { <add> started.set(true); <add> blockedGetValue.set( <add> secretControlStore.lockProjectSecret(projectId, SecretScopes.PROJECT, KEY1, (c1, v1) -> v1)); <add> blockedCheckComitting.set(comitting.get()); <add> }); <add> t.setDaemon(true); <add> t.start(); <add> <add> // wait until the thread starts <add> while (!started.get()) { <add> Thread.sleep(500); <add> } <add> // wait some more to make sure that lockProjectSecret is called & blocked <add> Thread.sleep(500); <add> <add> control.setProjectSecret(projectId, SecretScopes.PROJECT, KEY1, VALUE1 + ".changed"); <add> <add> comitting.set(true); <add> return t; <add> } <add> catch (InterruptedException ex) { <add> throw new AssertionError(ex); <add> } <add> }); <add> <add> thread.join(); <add> <add> assertThat(blockedGetValue.get(), is(Optional.of(VALUE1 + ".changed"))); <add> assertThat(blockedCheckComitting.get(), is(true)); <ide> } <ide> <ide> @Test
Java
apache-2.0
95d57cc52eb33c42fe793e269f69bb9e4ab6c7bc
0
revapi/revapi,revapi/revapi,revapi/revapi
package org.revapi.java.compilation; import static java.util.stream.Collectors.toList; import static java.util.stream.Collectors.toMap; import static java.util.stream.Collectors.toSet; import static org.revapi.java.model.JavaElementFactory.elementFor; import java.io.File; import java.io.IOException; import java.io.InputStream; import java.lang.reflect.Field; import java.net.URI; import java.util.AbstractMap; import java.util.ArrayDeque; import java.util.Arrays; import java.util.Collections; import java.util.Comparator; import java.util.EnumMap; import java.util.EnumSet; import java.util.HashMap; import java.util.HashSet; import java.util.IdentityHashMap; import java.util.LinkedHashSet; import java.util.List; import java.util.Map; import java.util.Set; import java.util.function.Function; import java.util.stream.Collectors; import javax.annotation.Nonnull; import javax.lang.model.element.AnnotationMirror; import javax.lang.model.element.Element; import javax.lang.model.element.ElementKind; import javax.lang.model.element.ExecutableElement; import javax.lang.model.element.Modifier; import javax.lang.model.element.TypeElement; import javax.lang.model.element.VariableElement; import javax.lang.model.type.ArrayType; import javax.lang.model.type.DeclaredType; import javax.lang.model.type.ExecutableType; import javax.lang.model.type.IntersectionType; import javax.lang.model.type.NoType; import javax.lang.model.type.PrimitiveType; import javax.lang.model.type.TypeKind; import javax.lang.model.type.TypeMirror; import javax.lang.model.type.TypeVariable; import javax.lang.model.type.TypeVisitor; import javax.lang.model.type.WildcardType; import javax.lang.model.util.ElementFilter; import javax.lang.model.util.Elements; import javax.lang.model.util.SimpleTypeVisitor8; import javax.lang.model.util.Types; import javax.tools.JavaFileManager; import javax.tools.JavaFileObject; import javax.tools.StandardJavaFileManager; import org.revapi.Archive; import org.revapi.java.AnalysisConfiguration; import org.revapi.java.FlatFilter; import org.revapi.java.model.AnnotationElement; import org.revapi.java.model.JavaElementBase; import org.revapi.java.model.JavaElementFactory; import org.revapi.java.model.MethodElement; import org.revapi.java.model.MissingClassElement; import org.revapi.java.spi.IgnoreCompletionFailures; import org.revapi.java.spi.UseSite; import org.revapi.java.spi.Util; import org.revapi.query.Filter; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * @author Lukas Krejci * @since 0.11.0 */ final class ClasspathScanner { private static final Logger LOG = LoggerFactory.getLogger(ClasspathScanner.class); private static final List<Modifier> ACCESSIBLE_MODIFIERS = Arrays.asList(Modifier.PUBLIC, Modifier.PROTECTED); private static final String SYSTEM_CLASSPATH_NAME = "<system classpath>"; private final StandardJavaFileManager fileManager; private final ProbingEnvironment environment; private final Map<Archive, File> classPath; private final Map<Archive, File> additionalClassPath; private final AnalysisConfiguration.MissingClassReporting missingClassReporting; private final boolean ignoreMissingAnnotations; private final InclusionFilter inclusionFilter; private final boolean defaultInclusionCase; ClasspathScanner(StandardJavaFileManager fileManager, ProbingEnvironment environment, Map<Archive, File> classPath, Map<Archive, File> additionalClassPath, AnalysisConfiguration.MissingClassReporting missingClassReporting, boolean ignoreMissingAnnotations, InclusionFilter inclusionFilter) { this.fileManager = fileManager; this.environment = environment; this.classPath = classPath; this.additionalClassPath = additionalClassPath; this.missingClassReporting = missingClassReporting == null ? AnalysisConfiguration.MissingClassReporting.ERROR : missingClassReporting; this.ignoreMissingAnnotations = ignoreMissingAnnotations; this.inclusionFilter = inclusionFilter; this.defaultInclusionCase = inclusionFilter.defaultCase(); } void initTree() throws IOException { List<ArchiveLocation> classPathLocations = classPath.keySet().stream().map(ArchiveLocation::new) .collect(toList()); Scanner scanner = new Scanner(); for (ArchiveLocation loc : classPathLocations) { scanner.scan(loc, classPath.get(loc.getArchive()), true); } Set<TypeElement> lastUnknowns = Collections.emptySet(); Map<String, ArchiveLocation> cachedArchives = new HashMap<>(additionalClassPath.size()); while (!scanner.requiredTypes.isEmpty() && !lastUnknowns.equals(scanner.requiredTypes.keySet())) { lastUnknowns = new HashSet<>(scanner.requiredTypes.keySet()); for (TypeElement t : lastUnknowns) { try { Field f = t.getClass().getField("classfile"); JavaFileObject jfo = (JavaFileObject) f.get(t); if (jfo == null) { t = environment.getElementUtils().getTypeElement(t.getQualifiedName()); if (t == null) { //this type is really missing... continue; } jfo = (JavaFileObject) f.get(t); } URI uri = jfo.toUri(); String path; if ("jar".equals(uri.getScheme())) { path = uri.getSchemeSpecificPart(); //jar:file:/path .. let's get rid of the "file:" part int colonIdx = path.indexOf(':'); if (colonIdx >= 0) { path = path.substring(colonIdx + 1); } //separate the file path from the in-jar path path = path.substring(0, path.lastIndexOf('!')); } else { path = uri.getPath(); } ArchiveLocation loc = cachedArchives.get(path); if (loc == null) { Archive ar = null; for (Map.Entry<Archive, File> e : additionalClassPath.entrySet()) { if (e.getValue().getAbsolutePath().equals(path)) { ar = e.getKey(); break; } } if (ar != null) { loc = new ArchiveLocation(ar); cachedArchives.put(path, loc); } } if (loc != null) { scanner.scanClass(loc, t, false); } } catch (NoSuchFieldException e) { //TODO fallback to manually looping through archives } catch (IllegalAccessException e) { //should not happen throw new AssertionError("Illegal access after setAccessible(true) on a field. Wha?", e); } } } //ok, so scanning the archives doesn't give us any new resolved classes that we need in the API... //let's scan the system classpath. What will be left after this will be the truly missing classes. //making a copy because the required types might be modified during scanning Map<TypeElement, Boolean> rts = new HashMap<>(scanner.requiredTypes); ArchiveLocation systemClassPath = new ArchiveLocation(new Archive() { @Nonnull @Override public String getName() { return SYSTEM_CLASSPATH_NAME; } @Nonnull @Override public InputStream openStream() throws IOException { throw new UnsupportedOperationException(); } }); for (Map.Entry<TypeElement, Boolean> e : rts.entrySet()) { if (e.getKey().asType().getKind() != TypeKind.ERROR) { scanner.scanClass(systemClassPath, e.getKey(), false); } } scanner.initEnvironment(); } private final class Scanner { final Set<TypeElement> processed = new HashSet<>(); final Map<TypeElement, Boolean> requiredTypes = new IdentityHashMap<>(); final Map<TypeElement, TypeRecord> types = new IdentityHashMap<>(); final TypeVisitor<TypeElement, Void> getTypeElement = new SimpleTypeVisitor8<TypeElement, Void>() { @Override protected TypeElement defaultAction(TypeMirror e, Void ignored) { throw new IllegalStateException("Could not determine the element of a type: " + e); } @Override public TypeElement visitDeclared(DeclaredType t, Void ignored) { return (TypeElement) t.asElement(); } @Override public TypeElement visitTypeVariable(TypeVariable t, Void ignored) { return t.getUpperBound().accept(this, null); } @Override public TypeElement visitArray(ArrayType t, Void ignored) { return t.getComponentType().accept(this, null); } @Override public TypeElement visitPrimitive(PrimitiveType t, Void ignored) { return null; } @Override public TypeElement visitIntersection(IntersectionType t, Void aVoid) { return t.getBounds().get(0).accept(this, null); } @Override public TypeElement visitWildcard(WildcardType t, Void aVoid) { if (t.getExtendsBound() != null) { return t.getExtendsBound().accept(this, null); } else if (t.getSuperBound() != null) { return t.getSuperBound().accept(this, null); } else { return environment.getElementUtils().getTypeElement("java.lang.Object"); } } @Override public TypeElement visitNoType(NoType t, Void aVoid) { return null; } }; void scan(ArchiveLocation location, File path, boolean primaryApi) throws IOException { fileManager.setLocation(location, Collections.singleton(path)); Iterable<? extends JavaFileObject> jfos = fileManager.list(location, "", EnumSet.of(JavaFileObject.Kind.CLASS), true); for (JavaFileObject jfo : jfos) { TypeElement type = Util.findTypeByBinaryName(environment.getElementUtils(), fileManager.inferBinaryName(location, jfo)); //type can be null if it represents an anonymous or member class... if (type != null) { scanClass(location, type, primaryApi); } } } void scanClass(ArchiveLocation loc, TypeElement type, boolean primaryApi) { try { if (processed.contains(type)) { return; } processed.add(type); Boolean wasAnno = requiredTypes.remove(type); String bn = environment.getElementUtils().getBinaryName(type).toString(); String cn = type.getQualifiedName().toString(); boolean includes = inclusionFilter.accepts(bn, cn); boolean excludes = inclusionFilter.rejects(bn, cn); //technically, we could find this out later on in the method, but doing this here ensures that the //javac tries to fully load the class (and therefore throw any completion failures. //Doing this then ensures that we get a correct TypeKind after this call. TypeElement superType = getTypeElement.visit(IgnoreCompletionFailures.in(type::getSuperclass)); //type.asType() possibly not completely correct when dealing with inner class of a parameterized class TypeMirror typeType = type.asType(); if (typeType.getKind() == TypeKind.ERROR) { //just re-add the missing type and return. It will be dealt with accordingly //in initEnvironment requiredTypes.put(type, wasAnno); return; } org.revapi.java.model.TypeElement t = new org.revapi.java.model.TypeElement(environment, loc.getArchive(), type, (DeclaredType) type.asType()); TypeRecord tr = getTypeRecord(type); tr.modelElement = t; //this will be revisited... in here we're just establishing the types that are in the API for sure... tr.inApi = !excludes && (primaryApi && !shouldBeIgnored(type) && !(type.getEnclosingElement() instanceof TypeElement)); tr.primaryApi = primaryApi; tr.explicitlyExcluded = excludes; tr.explicitlyIncluded = includes; if (tr.explicitlyExcluded) { return; } if (superType != null) { addUse(tr, type, superType, UseSite.Type.IS_INHERITED); tr.superTypes.add(getTypeRecord(superType)); if (!processed.contains(superType)) { requiredTypes.put(superType, false); } } IgnoreCompletionFailures.in(type::getInterfaces).stream().map(getTypeElement::visit) .forEach(e -> { if (!processed.contains(e)) { requiredTypes.put(e, false); } addUse(tr, type, e, UseSite.Type.IS_IMPLEMENTED); tr.superTypes.add(getTypeRecord(e)); }); addTypeParamUses(tr, type, type.asType()); for (Element e : IgnoreCompletionFailures.in(type::getEnclosedElements)) { switch (e.getKind()) { case ANNOTATION_TYPE: case CLASS: case ENUM: case INTERFACE: addUse(tr, type, (TypeElement) e, UseSite.Type.CONTAINS); //the contained classes by default inherit the API status of their containing class scanClass(loc, (TypeElement) e, tr.inApi); break; case CONSTRUCTOR: case METHOD: scanMethod(tr, (ExecutableElement) e); break; case ENUM_CONSTANT: case FIELD: scanField(tr, (VariableElement) e); break; } } type.getAnnotationMirrors().forEach(a -> scanAnnotation(tr, type, a)); } catch (Exception e) { LOG.error("Failed to scan class " + type.getQualifiedName().toString() + ". Analysis results may be skewed.", e); } } void placeInTree(TypeRecord typeRecord) { TypeElement type = typeRecord.modelElement.getDeclaringElement(); if (!(type.getEnclosingElement() instanceof TypeElement)) { environment.getTree().getRootsUnsafe().add(typeRecord.modelElement); } else { ArrayDeque<String> nesting = new ArrayDeque<>(); type = (TypeElement) type.getEnclosingElement(); while (type != null) { nesting.push(type.getQualifiedName().toString()); type = type.getEnclosingElement() instanceof TypeElement ? (TypeElement) type.getEnclosingElement() : null; } Function<String, Filter<org.revapi.java.model.TypeElement>> findByCN = cn -> FlatFilter.by(e -> cn.equals(e.getCanonicalName())); List<org.revapi.java.model.TypeElement> parents = Collections.emptyList(); while (parents.isEmpty() && !nesting.isEmpty()) { parents = environment.getTree().searchUnsafe( org.revapi.java.model.TypeElement.class, false, findByCN.apply(nesting.pop()), null); } org.revapi.java.model.TypeElement parent = parents.isEmpty() ? null : parents.get(0); while (!nesting.isEmpty()) { String cn = nesting.pop(); parents = environment.getTree().searchUnsafe( org.revapi.java.model.TypeElement.class, false, findByCN.apply(cn), parent); if (parents.isEmpty()) { //we found a "gap" in the parents included in the model. let's start from the top //again do { parents = environment.getTree().searchUnsafe( org.revapi.java.model.TypeElement.class, false, findByCN.apply(cn), null); if (parents.isEmpty() && !nesting.isEmpty()) { cn = nesting.pop(); } else { break; } } while (!nesting.isEmpty()); } parent = parents.isEmpty() ? null : parents.get(0); } if (parent == null) { environment.getTree().getRootsUnsafe().add(typeRecord.modelElement); } else { parent.getChildren().add(typeRecord.modelElement); } } } void scanField(TypeRecord owningType, VariableElement field) { if (shouldBeIgnored(field)) { owningType.inaccessibleDeclaredNonClassMembers.add(field); return; } owningType.accessibleDeclaredNonClassMembers.add(field); TypeElement fieldType = field.asType().accept(getTypeElement, null); //fieldType == null means primitive type, if no type can be found, exception is thrown if (fieldType == null) { return; } addUse(owningType, field, fieldType, UseSite.Type.HAS_TYPE); addType(fieldType, false); addTypeParamUses(owningType, field, field.asType()); field.getAnnotationMirrors().forEach(a -> scanAnnotation(owningType, field, a)); } void scanMethod(TypeRecord owningType, ExecutableElement method) { if (shouldBeIgnored(method)) { owningType.inaccessibleDeclaredNonClassMembers.add(method); return; } owningType.accessibleDeclaredNonClassMembers.add(method); TypeElement returnType = method.getReturnType().accept(getTypeElement, null); if (returnType != null) { addUse(owningType, method, returnType, UseSite.Type.RETURN_TYPE); addType(returnType, false); addTypeParamUses(owningType, method, method.getReturnType()); } int idx = 0; for (VariableElement p : method.getParameters()) { TypeElement pt = p.asType().accept(getTypeElement, null); if (pt != null) { addUse(owningType, method, pt, UseSite.Type.PARAMETER_TYPE, idx++); addType(pt, false); addTypeParamUses(owningType, method, p.asType()); } p.getAnnotationMirrors().forEach(a -> scanAnnotation(owningType, p, a)); } method.getThrownTypes().forEach(t -> { TypeElement ex = t.accept(getTypeElement, null); if (ex != null) { addUse(owningType, method, ex, UseSite.Type.IS_THROWN); addType(ex, false); addTypeParamUses(owningType, method, t); } t.getAnnotationMirrors().forEach(a -> scanAnnotation(owningType, method, a)); }); method.getAnnotationMirrors().forEach(a -> scanAnnotation(owningType, method, a)); } void scanAnnotation(TypeRecord owningType, Element annotated, AnnotationMirror annotation) { TypeElement type = annotation.getAnnotationType().accept(getTypeElement, null); if (type != null) { addUse(owningType, annotated, type, UseSite.Type.ANNOTATES); addType(type, true); } } boolean addType(TypeElement type, boolean isAnnotation) { if (processed.contains(type)) { return true; } requiredTypes.put(type, isAnnotation); return false; } void addTypeParamUses(TypeRecord userType, Element user, TypeMirror usedType) { HashSet<String> visited = new HashSet<>(4); usedType.accept(new SimpleTypeVisitor8<Void, Void>() { @Override public Void visitIntersection(IntersectionType t, Void aVoid) { t.getBounds().forEach(b -> b.accept(this, null)); return null; } @Override public Void visitArray(ArrayType t, Void ignored) { return t.getComponentType().accept(this, null); } @Override public Void visitDeclared(DeclaredType t, Void ignored) { String type = Util.toUniqueString(t); if (!visited.contains(type)) { visited.add(type); if (t != usedType) { TypeElement typeEl = (TypeElement) t.asElement(); addType(typeEl, false); addUse(userType, user, typeEl, UseSite.Type.TYPE_PARAMETER_OR_BOUND); } t.getTypeArguments().forEach(a -> a.accept(this, null)); } return null; } @Override public Void visitTypeVariable(TypeVariable t, Void ignored) { return t.getUpperBound().accept(this, null); } @Override public Void visitWildcard(WildcardType t, Void ignored) { TypeMirror bound = t.getExtendsBound(); if (bound != null) { bound.accept(this, null); } bound = t.getSuperBound(); if (bound != null) { bound.accept(this, null); } return null; } }, null); } void addUse(TypeRecord userType, Element user, TypeElement used, UseSite.Type useType) { addUse(userType, user, used, useType, -1); } void addUse(TypeRecord userType, Element user, TypeElement used, UseSite.Type useType, int indexInParent) { TypeRecord usedTr = getTypeRecord(used); Set<ClassPathUseSite> sites = usedTr.useSites; sites.add(new ClassPathUseSite(useType, user, indexInParent)); Set<TypeRecord> usedTypes = userType.usedTypes.get(useType); if (usedTypes == null) { usedTypes = new HashSet<>(4); userType.usedTypes.put(useType, usedTypes); } usedTypes.add(usedTr); } TypeRecord getTypeRecord(TypeElement type) { TypeRecord rec = types.get(type); if (rec == null) { rec = new TypeRecord(); rec.javacElement = type; int depth = 0; Element e = type.getEnclosingElement(); while (e != null && e instanceof TypeElement) { depth++; e = e.getEnclosingElement(); } rec.nestingDepth = depth; types.put(type, rec); } return rec; } void initEnvironment() { if (ignoreMissingAnnotations && !requiredTypes.isEmpty()) { removeAnnotatesUses(); } moveInnerClassesOfPrimariesToApi(); determineApiStatus(); initChildren(); Set<TypeRecord> types = constructTree(); if (!requiredTypes.isEmpty()) { handleMissingClasses(types); } environment.setTypeMap(types.stream().collect(toMap(tr -> tr.javacElement, tr -> tr.modelElement))); } private void handleMissingClasses(Set<TypeRecord> types) { Elements els = environment.getElementUtils(); switch (missingClassReporting) { case ERROR: List<String> reallyMissing = requiredTypes.keySet().stream() .map(t -> els.getTypeElement(t.getQualifiedName())) .filter(t -> els.getTypeElement(t.getQualifiedName()) == null) .map(t -> t.getQualifiedName().toString()) .sorted() .collect(toList()); if (!reallyMissing.isEmpty()) { throw new IllegalStateException( "The following classes that contribute to the public API of " + environment.getApi() + " could not be located: " + reallyMissing); } break; case REPORT: for (TypeElement t : requiredTypes.keySet()) { TypeElement type = els.getTypeElement(t.getQualifiedName()); if (type == null) { TypeRecord tr = this.types.get(t); String bin = els.getBinaryName(t).toString(); MissingClassElement mce = new MissingClassElement(environment, bin, t.getQualifiedName().toString()); if (tr == null) { tr = new TypeRecord(); } mce.setInApi(tr.inApi); mce.setInApiThroughUse(tr.inApiThroughUse); mce.setRawUseSites(tr.useSites); tr.javacElement = mce.getDeclaringElement(); tr.modelElement = mce; types.add(tr); environment.getTree().getRootsUnsafe().add(mce); } } } } private Set<TypeRecord> constructTree() { Set<TypeRecord> types = new HashSet<>(); Set<TypeElement> ignored = new HashSet<>(); Comparator<Map.Entry<TypeElement, TypeRecord>> byNestingDepth = (a, b) -> { TypeRecord ar = a.getValue(); TypeRecord br = b.getValue(); int ret = ar.nestingDepth - br.nestingDepth; if (ret == 0) { ret = a.getKey().getQualifiedName().toString().compareTo(b.getKey().getQualifiedName().toString()); } //the less nested classes need to come first return ret; }; this.types.entrySet().stream().sorted(byNestingDepth).forEach(e -> { TypeElement t = e.getKey(); TypeRecord r = e.getValue(); //the model element will be null for missing types. Additionally, we don't want the system classpath //in our tree, because that is superfluous. if (r.modelElement != null && !r.modelElement.getArchive().getName().equals(SYSTEM_CLASSPATH_NAME)) { String cn = t.getQualifiedName().toString(); boolean includes = r.explicitlyIncluded; boolean excludes = r.explicitlyExcluded; if (includes) { environment.addExplicitInclusion(cn); } if (excludes) { environment.addExplicitExclusion(cn); ignored.add(t); } else { boolean include = defaultInclusionCase || includes; Element owner = t.getEnclosingElement(); if (owner != null && owner instanceof TypeElement) { ArrayDeque<TypeElement> owners = new ArrayDeque<>(); while (owner != null && owner instanceof TypeElement) { owners.push((TypeElement) owner); owner = owner.getEnclosingElement(); } //find the first owning class that is part of our model List<TypeElement> siblings = environment.getTree().getRootsUnsafe().stream().map( org.revapi.java.model.TypeElement::getDeclaringElement).collect(Collectors.toList()); while (!owners.isEmpty()) { if (ignored.contains(owners.peek()) || siblings.contains(owners.peek())) { break; } owners.pop(); } //if the user doesn't want this type included explicitly, we need to check in the parents //if some of them wasn't explicitly excluded if (!includes && !owners.isEmpty()) { do { TypeElement o = owners.pop(); include = !ignored.contains(o) && siblings.contains(o); siblings = ElementFilter.typesIn(o.getEnclosedElements()); } while (include && !owners.isEmpty()); } } if (include) { placeInTree(r); r.modelElement.setRawUseSites(r.useSites); types.add(r); r.modelElement.setInApi(r.inApi); r.modelElement.setInApiThroughUse(r.inApiThroughUse); } } } }); return types; } private void determineApiStatus() { Set<TypeRecord> undetermined = new HashSet<>(this.types.values()); while (!undetermined.isEmpty()) { undetermined = undetermined.stream() .filter(tr -> !tr.explicitlyExcluded) .filter(tr -> tr.inApi) .flatMap(tr -> tr.usedTypes.entrySet().stream() .map(e -> new AbstractMap.SimpleImmutableEntry<>(tr, e))) .filter(e -> movesToApi(e.getValue().getKey())) .flatMap(e -> e.getValue().getValue().stream()) .filter(usedTr -> !usedTr.inApi) .filter(usedTr -> !usedTr.explicitlyExcluded) .map(usedTr -> { usedTr.inApi = true; usedTr.inApiThroughUse = true; return usedTr; }) .collect(toSet()); } } private void moveInnerClassesOfPrimariesToApi() { Set<TypeRecord> primaries = this.types.values().stream() .filter(tr -> tr.primaryApi) .filter(tr -> tr.inApi) .filter(tr -> tr.nestingDepth == 0) .collect(toSet()); while (!primaries.isEmpty()) { primaries = primaries.stream() .flatMap(tr -> tr.usedTypes.getOrDefault(UseSite.Type.CONTAINS, Collections.emptySet()).stream()) .filter(containedTr -> containedTr.modelElement != null) .filter(containedTr -> !shouldBeIgnored(containedTr.modelElement.getDeclaringElement())) .map(containedTr -> { containedTr.inApi = true; return containedTr; }) .collect(toSet()); } } private void removeAnnotatesUses() { Map<TypeElement, Boolean> newTypes = requiredTypes.entrySet().stream().filter(e -> { boolean isAnno = e.getValue(); if (isAnno) { this.types.get(e.getKey()).useSites.clear(); } return !isAnno; }).collect(toMap(Map.Entry::getKey, Map.Entry::getValue)); requiredTypes.clear(); requiredTypes.putAll(newTypes); } private void initChildren() { for (TypeRecord tr : this.types.values()) { if (tr.modelElement == null) { continue; } //the set of methods' override-sensitive signatures - I.e. this is the list of methods //actually visible on a type. Set<String> methods = new HashSet<>(8); Function<JavaElementBase<?, ?>, JavaElementBase<?, ?>> addOverride = e -> { if (e instanceof MethodElement) { MethodElement me = (MethodElement) e; methods.add(getOverrideMapKey(me.getDeclaringElement())); } return e; }; Function<JavaElementBase<?, ?>, JavaElementBase<?, ?>> initChildren = e -> { initNonClassElementChildrenAndMoveToApi(tr, e, false); return e; }; //add declared stuff tr.accessibleDeclaredNonClassMembers.stream() .map(e -> elementFor(e, e.asType(), environment, tr.modelElement.getArchive())) .map(addOverride) .map(initChildren) .forEach(c -> tr.modelElement.getChildren().add(c)); tr.inaccessibleDeclaredNonClassMembers.stream() .map(e -> elementFor(e, e.asType(), environment, tr.modelElement.getArchive())) .map(addOverride) .map(initChildren) .forEach(c -> tr.modelElement.getChildren().add(c)); //now add inherited stuff tr.superTypes.forEach(str -> addInherited(tr, str, methods)); //and finally the annotations for (AnnotationMirror m : tr.javacElement.getAnnotationMirrors()) { tr.modelElement.getChildren().add(new AnnotationElement(environment, tr.modelElement.getArchive(), m)); } } } private void addInherited(TypeRecord target, TypeRecord superType, Set<String> methodOverrideMap) { Types types = environment.getTypeUtils(); superType.accessibleDeclaredNonClassMembers.stream() .map(e -> { if (e instanceof ExecutableElement) { ExecutableElement me = (ExecutableElement) e; if (!shouldAddInheritedMethodChild(me, methodOverrideMap)) { return null; } } TypeMirror elementType = types.asMemberOf((DeclaredType) target.javacElement.asType(), e); JavaElementBase<?, ?> element = JavaElementFactory .elementFor(e, elementType, environment, superType.modelElement.getArchive()); element.setInherited(true); initNonClassElementChildrenAndMoveToApi(target, element, true); return element; }) .filter(e -> e != null) .forEach(c -> target.modelElement.getChildren().add(c)); for (TypeRecord st : superType.superTypes) { addInherited(target, st, methodOverrideMap); } } private boolean shouldAddInheritedMethodChild(ExecutableElement methodElement, Set<String> overrideMap) { if (methodElement.getKind() == ElementKind.CONSTRUCTOR) { return false; } String overrideKey = getOverrideMapKey(methodElement); boolean alreadyIncludedMethod = overrideMap.contains(overrideKey); if (alreadyIncludedMethod) { return false; } else { //remember this to check if the next super type doesn't declare a method this one overrides overrideMap.add(overrideKey); return true; } } private void initNonClassElementChildrenAndMoveToApi(TypeRecord targetType, JavaElementBase<?, ?> parent, boolean inherited) { Types types = environment.getTypeUtils(); if (targetType.inApi && !shouldBeIgnored(parent.getDeclaringElement())) { TypeMirror representation = types.asMemberOf(targetType.modelElement.getModelRepresentation(), parent.getDeclaringElement()); representation.accept(new SimpleTypeVisitor8<Void, Void>() { @Override protected Void defaultAction(TypeMirror e, Void aVoid) { if (e.getKind().isPrimitive() || e.getKind() == TypeKind.VOID) { return null; } TypeElement childType = getTypeElement.visit(e); if (childType != null) { TypeRecord tr = Scanner.this.types.get(childType); if (tr != null && tr.modelElement != null) { if (!tr.inApi) { tr.inApiThroughUse = true; } tr.inApi = true; } } return null; } @Override public Void visitExecutable(ExecutableType t, Void aVoid) { t.getReturnType().accept(this, null); t.getParameterTypes().forEach(p -> p.accept(this, null)); return null; } }, null); } for (Element child : parent.getDeclaringElement().getEnclosedElements()) { if (child.getKind().isClass() || child.getKind().isInterface()) { continue; } TypeMirror representation = types.asMemberOf(targetType.modelElement.getModelRepresentation(), child); JavaElementBase<?, ?> childEl = JavaElementFactory.elementFor(child, representation, environment, parent.getArchive()); childEl.setInherited(inherited); parent.getChildren().add(childEl); initNonClassElementChildrenAndMoveToApi(targetType, childEl, inherited); } for (AnnotationMirror m : parent.getDeclaringElement().getAnnotationMirrors()) { parent.getChildren().add(new AnnotationElement(environment, parent.getArchive(), m)); } } } private static String getOverrideMapKey(ExecutableElement method) { return method.getSimpleName() + "#" + Util.toUniqueString(method.asType()); } private static final class ArchiveLocation implements JavaFileManager.Location { private final Archive archive; private ArchiveLocation(Archive archive) { this.archive = archive; } Archive getArchive() { return archive; } @Override public String getName() { return "archiveLocation_" + archive.getName(); } @Override public boolean isOutputLocation() { return false; } } private static final class TypeRecord { Set<ClassPathUseSite> useSites = new HashSet<>(2); TypeElement javacElement; org.revapi.java.model.TypeElement modelElement; Map<UseSite.Type, Set<TypeRecord>> usedTypes = new EnumMap<>(UseSite.Type.class); Set<Element> accessibleDeclaredNonClassMembers = new HashSet<>(4); Set<Element> inaccessibleDeclaredNonClassMembers = new HashSet<>(4); //important for this to be a linked hashset so that superclasses are processed prior to implemented interfaces Set<TypeRecord> superTypes = new LinkedHashSet<>(2); boolean explicitlyExcluded; boolean explicitlyIncluded; boolean inApi; boolean inApiThroughUse; boolean primaryApi; int nestingDepth; @Override public String toString() { final StringBuilder sb = new StringBuilder("TypeRecord["); sb.append("inApi=").append(inApi); sb.append(", modelElement=").append(modelElement); sb.append(']'); return sb.toString(); } } private static boolean movesToApi(UseSite.Type useType) { return useType.isMovingToApi(); } static boolean shouldBeIgnored(Element element) { return Collections.disjoint(element.getModifiers(), ACCESSIBLE_MODIFIERS); } }
revapi-java/src/main/java/org/revapi/java/compilation/ClasspathScanner.java
package org.revapi.java.compilation; import static java.util.stream.Collectors.toList; import static java.util.stream.Collectors.toMap; import static java.util.stream.Collectors.toSet; import static org.revapi.java.model.JavaElementFactory.elementFor; import java.io.File; import java.io.IOException; import java.io.InputStream; import java.lang.reflect.Field; import java.net.URI; import java.util.AbstractMap; import java.util.ArrayDeque; import java.util.Arrays; import java.util.Collections; import java.util.Comparator; import java.util.EnumMap; import java.util.EnumSet; import java.util.HashMap; import java.util.HashSet; import java.util.IdentityHashMap; import java.util.LinkedHashSet; import java.util.List; import java.util.Map; import java.util.Set; import java.util.function.Function; import java.util.stream.Collectors; import javax.annotation.Nonnull; import javax.lang.model.element.AnnotationMirror; import javax.lang.model.element.Element; import javax.lang.model.element.ElementKind; import javax.lang.model.element.ExecutableElement; import javax.lang.model.element.Modifier; import javax.lang.model.element.TypeElement; import javax.lang.model.element.VariableElement; import javax.lang.model.type.ArrayType; import javax.lang.model.type.DeclaredType; import javax.lang.model.type.ExecutableType; import javax.lang.model.type.IntersectionType; import javax.lang.model.type.NoType; import javax.lang.model.type.PrimitiveType; import javax.lang.model.type.TypeKind; import javax.lang.model.type.TypeMirror; import javax.lang.model.type.TypeVariable; import javax.lang.model.type.TypeVisitor; import javax.lang.model.type.WildcardType; import javax.lang.model.util.ElementFilter; import javax.lang.model.util.Elements; import javax.lang.model.util.SimpleTypeVisitor8; import javax.lang.model.util.Types; import javax.tools.JavaFileManager; import javax.tools.JavaFileObject; import javax.tools.StandardJavaFileManager; import org.revapi.Archive; import org.revapi.java.AnalysisConfiguration; import org.revapi.java.FlatFilter; import org.revapi.java.model.AnnotationElement; import org.revapi.java.model.JavaElementBase; import org.revapi.java.model.JavaElementFactory; import org.revapi.java.model.MethodElement; import org.revapi.java.model.MissingClassElement; import org.revapi.java.spi.IgnoreCompletionFailures; import org.revapi.java.spi.UseSite; import org.revapi.java.spi.Util; import org.revapi.query.Filter; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * @author Lukas Krejci * @since 0.11.0 */ final class ClasspathScanner { private static final Logger LOG = LoggerFactory.getLogger(ClasspathScanner.class); private static final List<Modifier> ACCESSIBLE_MODIFIERS = Arrays.asList(Modifier.PUBLIC, Modifier.PROTECTED); private static final String SYSTEM_CLASSPATH_NAME = "<system classpath>"; private final StandardJavaFileManager fileManager; private final ProbingEnvironment environment; private final Map<Archive, File> classPath; private final Map<Archive, File> additionalClassPath; private final AnalysisConfiguration.MissingClassReporting missingClassReporting; private final boolean ignoreMissingAnnotations; private final InclusionFilter inclusionFilter; private final boolean defaultInclusionCase; ClasspathScanner(StandardJavaFileManager fileManager, ProbingEnvironment environment, Map<Archive, File> classPath, Map<Archive, File> additionalClassPath, AnalysisConfiguration.MissingClassReporting missingClassReporting, boolean ignoreMissingAnnotations, InclusionFilter inclusionFilter) { this.fileManager = fileManager; this.environment = environment; this.classPath = classPath; this.additionalClassPath = additionalClassPath; this.missingClassReporting = missingClassReporting == null ? AnalysisConfiguration.MissingClassReporting.ERROR : missingClassReporting; this.ignoreMissingAnnotations = ignoreMissingAnnotations; this.inclusionFilter = inclusionFilter; this.defaultInclusionCase = inclusionFilter.defaultCase(); } void initTree() throws IOException { List<ArchiveLocation> classPathLocations = classPath.keySet().stream().map(ArchiveLocation::new) .collect(toList()); Scanner scanner = new Scanner(); for (ArchiveLocation loc : classPathLocations) { scanner.scan(loc, classPath.get(loc.getArchive()), true); } Set<TypeElement> lastUnknowns = Collections.emptySet(); Map<String, ArchiveLocation> cachedArchives = new HashMap<>(additionalClassPath.size()); while (!scanner.requiredTypes.isEmpty() && !lastUnknowns.equals(scanner.requiredTypes.keySet())) { lastUnknowns = new HashSet<>(scanner.requiredTypes.keySet()); for (TypeElement t : lastUnknowns) { try { Field f = t.getClass().getField("classfile"); JavaFileObject jfo = (JavaFileObject) f.get(t); if (jfo == null) { t = environment.getElementUtils().getTypeElement(t.getQualifiedName()); if (t == null) { //this type is really missing... continue; } jfo = (JavaFileObject) f.get(t); } URI uri = jfo.toUri(); String path; if ("jar".equals(uri.getScheme())) { uri = URI.create(uri.getSchemeSpecificPart()); path = uri.getPath().substring(0, uri.getPath().lastIndexOf('!')); } else { path = uri.getPath(); } ArchiveLocation loc = cachedArchives.get(path); if (loc == null) { Archive ar = null; for (Map.Entry<Archive, File> e : additionalClassPath.entrySet()) { if (e.getValue().getAbsolutePath().equals(path)) { ar = e.getKey(); break; } } if (ar != null) { loc = new ArchiveLocation(ar); cachedArchives.put(path, loc); } } if (loc != null) { scanner.scanClass(loc, t, false); } } catch (NoSuchFieldException e) { //TODO fallback to manually looping through archives } catch (IllegalAccessException e) { //should not happen throw new AssertionError("Illegal access after setAccessible(true) on a field. Wha?", e); } } } //ok, so scanning the archives doesn't give us any new resolved classes that we need in the API... //let's scan the system classpath. What will be left after this will be the truly missing classes. //making a copy because the required types might be modified during scanning Map<TypeElement, Boolean> rts = new HashMap<>(scanner.requiredTypes); ArchiveLocation systemClassPath = new ArchiveLocation(new Archive() { @Nonnull @Override public String getName() { return SYSTEM_CLASSPATH_NAME; } @Nonnull @Override public InputStream openStream() throws IOException { throw new UnsupportedOperationException(); } }); for (Map.Entry<TypeElement, Boolean> e : rts.entrySet()) { if (e.getKey().asType().getKind() != TypeKind.ERROR) { scanner.scanClass(systemClassPath, e.getKey(), false); } } scanner.initEnvironment(); } private final class Scanner { final Set<TypeElement> processed = new HashSet<>(); final Map<TypeElement, Boolean> requiredTypes = new IdentityHashMap<>(); final Map<TypeElement, TypeRecord> types = new IdentityHashMap<>(); final TypeVisitor<TypeElement, Void> getTypeElement = new SimpleTypeVisitor8<TypeElement, Void>() { @Override protected TypeElement defaultAction(TypeMirror e, Void ignored) { throw new IllegalStateException("Could not determine the element of a type: " + e); } @Override public TypeElement visitDeclared(DeclaredType t, Void ignored) { return (TypeElement) t.asElement(); } @Override public TypeElement visitTypeVariable(TypeVariable t, Void ignored) { return t.getUpperBound().accept(this, null); } @Override public TypeElement visitArray(ArrayType t, Void ignored) { return t.getComponentType().accept(this, null); } @Override public TypeElement visitPrimitive(PrimitiveType t, Void ignored) { return null; } @Override public TypeElement visitIntersection(IntersectionType t, Void aVoid) { return t.getBounds().get(0).accept(this, null); } @Override public TypeElement visitWildcard(WildcardType t, Void aVoid) { if (t.getExtendsBound() != null) { return t.getExtendsBound().accept(this, null); } else if (t.getSuperBound() != null) { return t.getSuperBound().accept(this, null); } else { return environment.getElementUtils().getTypeElement("java.lang.Object"); } } @Override public TypeElement visitNoType(NoType t, Void aVoid) { return null; } }; void scan(ArchiveLocation location, File path, boolean primaryApi) throws IOException { fileManager.setLocation(location, Collections.singleton(path)); Iterable<? extends JavaFileObject> jfos = fileManager.list(location, "", EnumSet.of(JavaFileObject.Kind.CLASS), true); for (JavaFileObject jfo : jfos) { TypeElement type = Util.findTypeByBinaryName(environment.getElementUtils(), fileManager.inferBinaryName(location, jfo)); //type can be null if it represents an anonymous or member class... if (type != null) { scanClass(location, type, primaryApi); } } } void scanClass(ArchiveLocation loc, TypeElement type, boolean primaryApi) { try { if (processed.contains(type)) { return; } processed.add(type); Boolean wasAnno = requiredTypes.remove(type); String bn = environment.getElementUtils().getBinaryName(type).toString(); String cn = type.getQualifiedName().toString(); boolean includes = inclusionFilter.accepts(bn, cn); boolean excludes = inclusionFilter.rejects(bn, cn); //technically, we could find this out later on in the method, but doing this here ensures that the //javac tries to fully load the class (and therefore throw any completion failures. //Doing this then ensures that we get a correct TypeKind after this call. TypeElement superType = getTypeElement.visit(IgnoreCompletionFailures.in(type::getSuperclass)); //type.asType() possibly not completely correct when dealing with inner class of a parameterized class TypeMirror typeType = type.asType(); if (typeType.getKind() == TypeKind.ERROR) { //just re-add the missing type and return. It will be dealt with accordingly //in initEnvironment requiredTypes.put(type, wasAnno); return; } org.revapi.java.model.TypeElement t = new org.revapi.java.model.TypeElement(environment, loc.getArchive(), type, (DeclaredType) type.asType()); TypeRecord tr = getTypeRecord(type); tr.modelElement = t; //this will be revisited... in here we're just establishing the types that are in the API for sure... tr.inApi = !excludes && (primaryApi && !shouldBeIgnored(type) && !(type.getEnclosingElement() instanceof TypeElement)); tr.primaryApi = primaryApi; tr.explicitlyExcluded = excludes; tr.explicitlyIncluded = includes; if (tr.explicitlyExcluded) { return; } if (superType != null) { addUse(tr, type, superType, UseSite.Type.IS_INHERITED); tr.superTypes.add(getTypeRecord(superType)); if (!processed.contains(superType)) { requiredTypes.put(superType, false); } } IgnoreCompletionFailures.in(type::getInterfaces).stream().map(getTypeElement::visit) .forEach(e -> { if (!processed.contains(e)) { requiredTypes.put(e, false); } addUse(tr, type, e, UseSite.Type.IS_IMPLEMENTED); tr.superTypes.add(getTypeRecord(e)); }); addTypeParamUses(tr, type, type.asType()); for (Element e : IgnoreCompletionFailures.in(type::getEnclosedElements)) { switch (e.getKind()) { case ANNOTATION_TYPE: case CLASS: case ENUM: case INTERFACE: addUse(tr, type, (TypeElement) e, UseSite.Type.CONTAINS); //the contained classes by default inherit the API status of their containing class scanClass(loc, (TypeElement) e, tr.inApi); break; case CONSTRUCTOR: case METHOD: scanMethod(tr, (ExecutableElement) e); break; case ENUM_CONSTANT: case FIELD: scanField(tr, (VariableElement) e); break; } } type.getAnnotationMirrors().forEach(a -> scanAnnotation(tr, type, a)); } catch (Exception e) { LOG.error("Failed to scan class " + type.getQualifiedName().toString() + ". Analysis results may be skewed.", e); } } void placeInTree(TypeRecord typeRecord) { TypeElement type = typeRecord.modelElement.getDeclaringElement(); if (!(type.getEnclosingElement() instanceof TypeElement)) { environment.getTree().getRootsUnsafe().add(typeRecord.modelElement); } else { ArrayDeque<String> nesting = new ArrayDeque<>(); type = (TypeElement) type.getEnclosingElement(); while (type != null) { nesting.push(type.getQualifiedName().toString()); type = type.getEnclosingElement() instanceof TypeElement ? (TypeElement) type.getEnclosingElement() : null; } Function<String, Filter<org.revapi.java.model.TypeElement>> findByCN = cn -> FlatFilter.by(e -> cn.equals(e.getCanonicalName())); List<org.revapi.java.model.TypeElement> parents = Collections.emptyList(); while (parents.isEmpty() && !nesting.isEmpty()) { parents = environment.getTree().searchUnsafe( org.revapi.java.model.TypeElement.class, false, findByCN.apply(nesting.pop()), null); } org.revapi.java.model.TypeElement parent = parents.isEmpty() ? null : parents.get(0); while (!nesting.isEmpty()) { String cn = nesting.pop(); parents = environment.getTree().searchUnsafe( org.revapi.java.model.TypeElement.class, false, findByCN.apply(cn), parent); if (parents.isEmpty()) { //we found a "gap" in the parents included in the model. let's start from the top //again do { parents = environment.getTree().searchUnsafe( org.revapi.java.model.TypeElement.class, false, findByCN.apply(cn), null); if (parents.isEmpty() && !nesting.isEmpty()) { cn = nesting.pop(); } else { break; } } while (!nesting.isEmpty()); } parent = parents.isEmpty() ? null : parents.get(0); } if (parent == null) { environment.getTree().getRootsUnsafe().add(typeRecord.modelElement); } else { parent.getChildren().add(typeRecord.modelElement); } } } void scanField(TypeRecord owningType, VariableElement field) { if (shouldBeIgnored(field)) { owningType.inaccessibleDeclaredNonClassMembers.add(field); return; } owningType.accessibleDeclaredNonClassMembers.add(field); TypeElement fieldType = field.asType().accept(getTypeElement, null); //fieldType == null means primitive type, if no type can be found, exception is thrown if (fieldType == null) { return; } addUse(owningType, field, fieldType, UseSite.Type.HAS_TYPE); addType(fieldType, false); addTypeParamUses(owningType, field, field.asType()); field.getAnnotationMirrors().forEach(a -> scanAnnotation(owningType, field, a)); } void scanMethod(TypeRecord owningType, ExecutableElement method) { if (shouldBeIgnored(method)) { owningType.inaccessibleDeclaredNonClassMembers.add(method); return; } owningType.accessibleDeclaredNonClassMembers.add(method); TypeElement returnType = method.getReturnType().accept(getTypeElement, null); if (returnType != null) { addUse(owningType, method, returnType, UseSite.Type.RETURN_TYPE); addType(returnType, false); addTypeParamUses(owningType, method, method.getReturnType()); } int idx = 0; for (VariableElement p : method.getParameters()) { TypeElement pt = p.asType().accept(getTypeElement, null); if (pt != null) { addUse(owningType, method, pt, UseSite.Type.PARAMETER_TYPE, idx++); addType(pt, false); addTypeParamUses(owningType, method, p.asType()); } p.getAnnotationMirrors().forEach(a -> scanAnnotation(owningType, p, a)); } method.getThrownTypes().forEach(t -> { TypeElement ex = t.accept(getTypeElement, null); if (ex != null) { addUse(owningType, method, ex, UseSite.Type.IS_THROWN); addType(ex, false); addTypeParamUses(owningType, method, t); } t.getAnnotationMirrors().forEach(a -> scanAnnotation(owningType, method, a)); }); method.getAnnotationMirrors().forEach(a -> scanAnnotation(owningType, method, a)); } void scanAnnotation(TypeRecord owningType, Element annotated, AnnotationMirror annotation) { TypeElement type = annotation.getAnnotationType().accept(getTypeElement, null); if (type != null) { addUse(owningType, annotated, type, UseSite.Type.ANNOTATES); addType(type, true); } } boolean addType(TypeElement type, boolean isAnnotation) { if (processed.contains(type)) { return true; } requiredTypes.put(type, isAnnotation); return false; } void addTypeParamUses(TypeRecord userType, Element user, TypeMirror usedType) { HashSet<String> visited = new HashSet<>(4); usedType.accept(new SimpleTypeVisitor8<Void, Void>() { @Override public Void visitIntersection(IntersectionType t, Void aVoid) { t.getBounds().forEach(b -> b.accept(this, null)); return null; } @Override public Void visitArray(ArrayType t, Void ignored) { return t.getComponentType().accept(this, null); } @Override public Void visitDeclared(DeclaredType t, Void ignored) { String type = Util.toUniqueString(t); if (!visited.contains(type)) { visited.add(type); if (t != usedType) { TypeElement typeEl = (TypeElement) t.asElement(); addType(typeEl, false); addUse(userType, user, typeEl, UseSite.Type.TYPE_PARAMETER_OR_BOUND); } t.getTypeArguments().forEach(a -> a.accept(this, null)); } return null; } @Override public Void visitTypeVariable(TypeVariable t, Void ignored) { return t.getUpperBound().accept(this, null); } @Override public Void visitWildcard(WildcardType t, Void ignored) { TypeMirror bound = t.getExtendsBound(); if (bound != null) { bound.accept(this, null); } bound = t.getSuperBound(); if (bound != null) { bound.accept(this, null); } return null; } }, null); } void addUse(TypeRecord userType, Element user, TypeElement used, UseSite.Type useType) { addUse(userType, user, used, useType, -1); } void addUse(TypeRecord userType, Element user, TypeElement used, UseSite.Type useType, int indexInParent) { TypeRecord usedTr = getTypeRecord(used); Set<ClassPathUseSite> sites = usedTr.useSites; sites.add(new ClassPathUseSite(useType, user, indexInParent)); Set<TypeRecord> usedTypes = userType.usedTypes.get(useType); if (usedTypes == null) { usedTypes = new HashSet<>(4); userType.usedTypes.put(useType, usedTypes); } usedTypes.add(usedTr); } TypeRecord getTypeRecord(TypeElement type) { TypeRecord rec = types.get(type); if (rec == null) { rec = new TypeRecord(); rec.javacElement = type; int depth = 0; Element e = type.getEnclosingElement(); while (e != null && e instanceof TypeElement) { depth++; e = e.getEnclosingElement(); } rec.nestingDepth = depth; types.put(type, rec); } return rec; } void initEnvironment() { if (ignoreMissingAnnotations && !requiredTypes.isEmpty()) { removeAnnotatesUses(); } moveInnerClassesOfPrimariesToApi(); determineApiStatus(); initChildren(); Set<TypeRecord> types = constructTree(); if (!requiredTypes.isEmpty()) { handleMissingClasses(types); } environment.setTypeMap(types.stream().collect(toMap(tr -> tr.javacElement, tr -> tr.modelElement))); } private void handleMissingClasses(Set<TypeRecord> types) { Elements els = environment.getElementUtils(); switch (missingClassReporting) { case ERROR: List<String> reallyMissing = requiredTypes.keySet().stream() .map(t -> els.getTypeElement(t.getQualifiedName())) .filter(t -> els.getTypeElement(t.getQualifiedName()) == null) .map(t -> t.getQualifiedName().toString()) .sorted() .collect(toList()); if (!reallyMissing.isEmpty()) { throw new IllegalStateException( "The following classes that contribute to the public API of " + environment.getApi() + " could not be located: " + reallyMissing); } break; case REPORT: for (TypeElement t : requiredTypes.keySet()) { TypeElement type = els.getTypeElement(t.getQualifiedName()); if (type == null) { TypeRecord tr = this.types.get(t); String bin = els.getBinaryName(t).toString(); MissingClassElement mce = new MissingClassElement(environment, bin, t.getQualifiedName().toString()); if (tr == null) { tr = new TypeRecord(); } mce.setInApi(tr.inApi); mce.setInApiThroughUse(tr.inApiThroughUse); mce.setRawUseSites(tr.useSites); tr.javacElement = mce.getDeclaringElement(); tr.modelElement = mce; types.add(tr); environment.getTree().getRootsUnsafe().add(mce); } } } } private Set<TypeRecord> constructTree() { Set<TypeRecord> types = new HashSet<>(); Set<TypeElement> ignored = new HashSet<>(); Comparator<Map.Entry<TypeElement, TypeRecord>> byNestingDepth = (a, b) -> { TypeRecord ar = a.getValue(); TypeRecord br = b.getValue(); int ret = ar.nestingDepth - br.nestingDepth; if (ret == 0) { ret = a.getKey().getQualifiedName().toString().compareTo(b.getKey().getQualifiedName().toString()); } //the less nested classes need to come first return ret; }; this.types.entrySet().stream().sorted(byNestingDepth).forEach(e -> { TypeElement t = e.getKey(); TypeRecord r = e.getValue(); //the model element will be null for missing types. Additionally, we don't want the system classpath //in our tree, because that is superfluous. if (r.modelElement != null && !r.modelElement.getArchive().getName().equals(SYSTEM_CLASSPATH_NAME)) { String cn = t.getQualifiedName().toString(); boolean includes = r.explicitlyIncluded; boolean excludes = r.explicitlyExcluded; if (includes) { environment.addExplicitInclusion(cn); } if (excludes) { environment.addExplicitExclusion(cn); ignored.add(t); } else { boolean include = defaultInclusionCase || includes; Element owner = t.getEnclosingElement(); if (owner != null && owner instanceof TypeElement) { ArrayDeque<TypeElement> owners = new ArrayDeque<>(); while (owner != null && owner instanceof TypeElement) { owners.push((TypeElement) owner); owner = owner.getEnclosingElement(); } //find the first owning class that is part of our model List<TypeElement> siblings = environment.getTree().getRootsUnsafe().stream().map( org.revapi.java.model.TypeElement::getDeclaringElement).collect(Collectors.toList()); while (!owners.isEmpty()) { if (ignored.contains(owners.peek()) || siblings.contains(owners.peek())) { break; } owners.pop(); } //if the user doesn't want this type included explicitly, we need to check in the parents //if some of them wasn't explicitly excluded if (!includes && !owners.isEmpty()) { do { TypeElement o = owners.pop(); include = !ignored.contains(o) && siblings.contains(o); siblings = ElementFilter.typesIn(o.getEnclosedElements()); } while (include && !owners.isEmpty()); } } if (include) { placeInTree(r); r.modelElement.setRawUseSites(r.useSites); types.add(r); r.modelElement.setInApi(r.inApi); r.modelElement.setInApiThroughUse(r.inApiThroughUse); } } } }); return types; } private void determineApiStatus() { Set<TypeRecord> undetermined = new HashSet<>(this.types.values()); while (!undetermined.isEmpty()) { undetermined = undetermined.stream() .filter(tr -> !tr.explicitlyExcluded) .filter(tr -> tr.inApi) .flatMap(tr -> tr.usedTypes.entrySet().stream() .map(e -> new AbstractMap.SimpleImmutableEntry<>(tr, e))) .filter(e -> movesToApi(e.getValue().getKey())) .flatMap(e -> e.getValue().getValue().stream()) .filter(usedTr -> !usedTr.inApi) .filter(usedTr -> !usedTr.explicitlyExcluded) .map(usedTr -> { usedTr.inApi = true; usedTr.inApiThroughUse = true; return usedTr; }) .collect(toSet()); } } private void moveInnerClassesOfPrimariesToApi() { Set<TypeRecord> primaries = this.types.values().stream() .filter(tr -> tr.primaryApi) .filter(tr -> tr.inApi) .filter(tr -> tr.nestingDepth == 0) .collect(toSet()); while (!primaries.isEmpty()) { primaries = primaries.stream() .flatMap(tr -> tr.usedTypes.getOrDefault(UseSite.Type.CONTAINS, Collections.emptySet()).stream()) .filter(containedTr -> containedTr.modelElement != null) .filter(containedTr -> !shouldBeIgnored(containedTr.modelElement.getDeclaringElement())) .map(containedTr -> { containedTr.inApi = true; return containedTr; }) .collect(toSet()); } } private void removeAnnotatesUses() { Map<TypeElement, Boolean> newTypes = requiredTypes.entrySet().stream().filter(e -> { boolean isAnno = e.getValue(); if (isAnno) { this.types.get(e.getKey()).useSites.clear(); } return !isAnno; }).collect(toMap(Map.Entry::getKey, Map.Entry::getValue)); requiredTypes.clear(); requiredTypes.putAll(newTypes); } private void initChildren() { for (TypeRecord tr : this.types.values()) { if (tr.modelElement == null) { continue; } //the set of methods' override-sensitive signatures - I.e. this is the list of methods //actually visible on a type. Set<String> methods = new HashSet<>(8); Function<JavaElementBase<?, ?>, JavaElementBase<?, ?>> addOverride = e -> { if (e instanceof MethodElement) { MethodElement me = (MethodElement) e; methods.add(getOverrideMapKey(me.getDeclaringElement())); } return e; }; Function<JavaElementBase<?, ?>, JavaElementBase<?, ?>> initChildren = e -> { initNonClassElementChildrenAndMoveToApi(tr, e, false); return e; }; //add declared stuff tr.accessibleDeclaredNonClassMembers.stream() .map(e -> elementFor(e, e.asType(), environment, tr.modelElement.getArchive())) .map(addOverride) .map(initChildren) .forEach(c -> tr.modelElement.getChildren().add(c)); tr.inaccessibleDeclaredNonClassMembers.stream() .map(e -> elementFor(e, e.asType(), environment, tr.modelElement.getArchive())) .map(addOverride) .map(initChildren) .forEach(c -> tr.modelElement.getChildren().add(c)); //now add inherited stuff tr.superTypes.forEach(str -> addInherited(tr, str, methods)); //and finally the annotations for (AnnotationMirror m : tr.javacElement.getAnnotationMirrors()) { tr.modelElement.getChildren().add(new AnnotationElement(environment, tr.modelElement.getArchive(), m)); } } } private void addInherited(TypeRecord target, TypeRecord superType, Set<String> methodOverrideMap) { Types types = environment.getTypeUtils(); superType.accessibleDeclaredNonClassMembers.stream() .map(e -> { if (e instanceof ExecutableElement) { ExecutableElement me = (ExecutableElement) e; if (!shouldAddInheritedMethodChild(me, methodOverrideMap)) { return null; } } TypeMirror elementType = types.asMemberOf((DeclaredType) target.javacElement.asType(), e); JavaElementBase<?, ?> element = JavaElementFactory .elementFor(e, elementType, environment, superType.modelElement.getArchive()); element.setInherited(true); initNonClassElementChildrenAndMoveToApi(target, element, true); return element; }) .filter(e -> e != null) .forEach(c -> target.modelElement.getChildren().add(c)); for (TypeRecord st : superType.superTypes) { addInherited(target, st, methodOverrideMap); } } private boolean shouldAddInheritedMethodChild(ExecutableElement methodElement, Set<String> overrideMap) { if (methodElement.getKind() == ElementKind.CONSTRUCTOR) { return false; } String overrideKey = getOverrideMapKey(methodElement); boolean alreadyIncludedMethod = overrideMap.contains(overrideKey); if (alreadyIncludedMethod) { return false; } else { //remember this to check if the next super type doesn't declare a method this one overrides overrideMap.add(overrideKey); return true; } } private void initNonClassElementChildrenAndMoveToApi(TypeRecord targetType, JavaElementBase<?, ?> parent, boolean inherited) { Types types = environment.getTypeUtils(); if (targetType.inApi && !shouldBeIgnored(parent.getDeclaringElement())) { TypeMirror representation = types.asMemberOf(targetType.modelElement.getModelRepresentation(), parent.getDeclaringElement()); representation.accept(new SimpleTypeVisitor8<Void, Void>() { @Override protected Void defaultAction(TypeMirror e, Void aVoid) { if (e.getKind().isPrimitive() || e.getKind() == TypeKind.VOID) { return null; } TypeElement childType = getTypeElement.visit(e); if (childType != null) { TypeRecord tr = Scanner.this.types.get(childType); if (tr != null && tr.modelElement != null) { if (!tr.inApi) { tr.inApiThroughUse = true; } tr.inApi = true; } } return null; } @Override public Void visitExecutable(ExecutableType t, Void aVoid) { t.getReturnType().accept(this, null); t.getParameterTypes().forEach(p -> p.accept(this, null)); return null; } }, null); } for (Element child : parent.getDeclaringElement().getEnclosedElements()) { if (child.getKind().isClass() || child.getKind().isInterface()) { continue; } TypeMirror representation = types.asMemberOf(targetType.modelElement.getModelRepresentation(), child); JavaElementBase<?, ?> childEl = JavaElementFactory.elementFor(child, representation, environment, parent.getArchive()); childEl.setInherited(inherited); parent.getChildren().add(childEl); initNonClassElementChildrenAndMoveToApi(targetType, childEl, inherited); } for (AnnotationMirror m : parent.getDeclaringElement().getAnnotationMirrors()) { parent.getChildren().add(new AnnotationElement(environment, parent.getArchive(), m)); } } } private static String getOverrideMapKey(ExecutableElement method) { return method.getSimpleName() + "#" + Util.toUniqueString(method.asType()); } private static final class ArchiveLocation implements JavaFileManager.Location { private final Archive archive; private ArchiveLocation(Archive archive) { this.archive = archive; } Archive getArchive() { return archive; } @Override public String getName() { return "archiveLocation_" + archive.getName(); } @Override public boolean isOutputLocation() { return false; } } private static final class TypeRecord { Set<ClassPathUseSite> useSites = new HashSet<>(2); TypeElement javacElement; org.revapi.java.model.TypeElement modelElement; Map<UseSite.Type, Set<TypeRecord>> usedTypes = new EnumMap<>(UseSite.Type.class); Set<Element> accessibleDeclaredNonClassMembers = new HashSet<>(4); Set<Element> inaccessibleDeclaredNonClassMembers = new HashSet<>(4); //important for this to be a linked hashset so that superclasses are processed prior to implemented interfaces Set<TypeRecord> superTypes = new LinkedHashSet<>(2); boolean explicitlyExcluded; boolean explicitlyIncluded; boolean inApi; boolean inApiThroughUse; boolean primaryApi; int nestingDepth; @Override public String toString() { final StringBuilder sb = new StringBuilder("TypeRecord["); sb.append("inApi=").append(inApi); sb.append(", modelElement=").append(modelElement); sb.append(']'); return sb.toString(); } } private static boolean movesToApi(UseSite.Type useType) { return useType.isMovingToApi(); } static boolean shouldBeIgnored(Element element) { return Collections.disjoint(element.getModifiers(), ACCESSIBLE_MODIFIERS); } }
[#55] Handle spaces in jar URIs.
revapi-java/src/main/java/org/revapi/java/compilation/ClasspathScanner.java
[#55] Handle spaces in jar URIs.
<ide><path>evapi-java/src/main/java/org/revapi/java/compilation/ClasspathScanner.java <ide> URI uri = jfo.toUri(); <ide> String path; <ide> if ("jar".equals(uri.getScheme())) { <del> uri = URI.create(uri.getSchemeSpecificPart()); <del> path = uri.getPath().substring(0, uri.getPath().lastIndexOf('!')); <add> path = uri.getSchemeSpecificPart(); <add> <add> //jar:file:/path .. let's get rid of the "file:" part <add> int colonIdx = path.indexOf(':'); <add> if (colonIdx >= 0) { <add> path = path.substring(colonIdx + 1); <add> } <add> <add> //separate the file path from the in-jar path <add> path = path.substring(0, path.lastIndexOf('!')); <ide> } else { <ide> path = uri.getPath(); <ide> }
JavaScript
mit
8b53842bcdbc3ec507bd3319fab2fb9a94176ed0
0
pravi/jsxc,jsxc/jsxc,svbergerem/jsxc,pravi/jsxc,diaspora/jsxc,diaspora/jsxc,pravi/jsxc,svbergerem/jsxc,Zauberstuhl/jsxc,jsxc/jsxc,jsxc/jsxc,svbergerem/jsxc,diaspora/jsxc,Zauberstuhl/jsxc,Zauberstuhl/jsxc
var jsxc; (function($) { "use strict"; /** * JavaScript Xmpp Chat namespace * * @namespace jsxc */ jsxc = { /** Version of jsxc */ version: '< $ app.version $ >', /** True if i'm the master */ master: false, /** True if the role allocation is finished */ role_allocation: false, /** Timeout for keepalive */ to: null, /** Timeout after normal keepalive starts */ toBusy: null, /** Timeout for notification */ toNotification: null, /** Timeout delay for notification */ toNotificationDelay: 500, /** Interval for keep-alive */ keepalive: null, /** True if last activity was 10 min ago */ restore: false, /** True if restore is complete */ restoreCompleted: false, /** True if login through box */ triggeredFromBox: false, /** True if logout through element click */ triggeredFromElement: false, /** True if logout through logout click */ triggeredFromLogout: false, /** last values which we wrote into localstorage (IE workaround) */ ls: [], /** * storage event is even fired if I write something into storage (IE * workaround) 0: conform, 1: not conform, 2: not shure */ storageNotConform: null, /** Timeout for storageNotConform test */ toSNC: null, /** My bar id */ bid: null, /** Some constants */ CONST: { NOTIFICATION_DEFAULT: 'default', NOTIFICATION_GRANTED: 'granted', NOTIFICATION_DENIED: 'denied', STATUS: [ 'offline', 'dnd', 'xa', 'away', 'chat', 'online' ], SOUNDS: { MSG: 'incomingMessage.wav', CALL: 'Rotary-Phone6.mp3', NOTICE: 'Ping1.mp3' }, REGEX: { JID: new RegExp('\\b[^"&\'\\/:<>@\\s]+@[\\w-_.]+\\b', 'ig'), URL: new RegExp(/((?:https?:\/\/|www\.|([\w\-]+\.[a-zA-Z]{2,3})(?=\b))(?:(?:[\-A-Za-z0-9+&@#\/%?=~_|!:,.;]*\([\-A-Za-z0-9+&@#\/%?=~_|!:,.;]*\)([\-A-Za-z0-9+&@#\/%?=~_|!:,.;]*[\-A-Za-z0-9+&@#\/%=~_|])?)|(?:[\-A-Za-z0-9+&@#\/%?=~_|!:,.;]*[\-A-Za-z0-9+&@#\/%=~_|]))?)/gi) }, NS: { CARBONS: 'urn:xmpp:carbons:2', FORWARD: 'urn:xmpp:forward:0' } }, /** * Parse a unix timestamp and return a formatted time string * * @memberOf jsxc * @param {Object} unixtime * @returns time of day and/or date */ getFormattedTime: function(unixtime) { var msgDate = new Date(parseInt(unixtime)); var date = ('0' + msgDate.getDate()).slice(-2); var month = ('0' + (msgDate.getMonth() + 1)).slice(-2); var year = msgDate.getFullYear(); var hours = ('0' + msgDate.getHours()).slice(-2); var minutes = ('0' + msgDate.getMinutes()).slice(-2); var dateNow = new Date(), time = hours + ':' + minutes; // compare dates only dateNow.setHours(0, 0, 0, 0); msgDate.setHours(0, 0, 0, 0); if (dateNow.getTime() !== msgDate.getTime()) { return date + '.' + month + '.' + year + ' ' + time; } return time; }, /** * Write debug message to console and to log. * * @memberOf jsxc * @param {String} msg Debug message * @param {Object} data * @param {String} Could be warn|error|null */ debug: function(msg, data, level) { if (level) { msg = '[' + level + '] ' + msg; } if (data) { if (jsxc.storage.getItem('debug') === true) { console.log(msg, data); } // try to convert data to string var d; try { // clone html snippet d = $("<span>").prepend($(data).clone()).html(); } catch (err) { try { d = JSON.stringify(data); } catch (err2) { d = 'see js console'; } } jsxc.log = jsxc.log + msg + ': ' + d + '\n'; } else { console.log(msg); jsxc.log = jsxc.log + msg + '\n'; } }, /** * Write warn message. * * @memberOf jsxc * @param {String} msg Warn message * @param {Object} data */ warn: function(msg, data) { jsxc.debug(msg, data, 'WARN'); }, /** * Write error message. * * @memberOf jsxc * @param {String} msg Error message * @param {Object} data */ error: function(msg, data) { jsxc.debug(msg, data, 'ERROR'); }, /** debug log */ log: '', /** * Starts the action * * @memberOf jsxc * @param {object} options */ init: function(options) { if (options) { // override default options $.extend(true, jsxc.options, options); } /** * Getter method for options. Saved options will override default one. * * @param {string} key option key * @returns default or saved option value */ jsxc.options.get = function(key) { var local = jsxc.storage.getUserItem('options') || {}; return local[key] || jsxc.options[key]; }; /** * Setter method for options. Will write into localstorage. * * @param {string} key option key * @param {object} value option value */ jsxc.options.set = function(key, value) { jsxc.storage.updateItem('options', key, value, true); }; jsxc.storageNotConform = jsxc.storage.getItem('storageNotConform'); if (jsxc.storageNotConform === null) { jsxc.storageNotConform = 2; } // detect language var lang; if (jsxc.storage.getItem('lang') !== null) { lang = jsxc.storage.getItem('lang'); } else if (jsxc.options.autoLang && navigator.language) { lang = navigator.language.substr(0, 2); } else { lang = jsxc.options.defaultLang; } // set language jsxc.l = jsxc.l10n.en; $.extend(jsxc.l, jsxc.l10n[lang]); // Check localStorage if (typeof (localStorage) === 'undefined') { jsxc.debug("Browser doesn't support localStorage."); return; } if (jsxc.storage.getItem('debug') === true) { jsxc.options.otr.debug = true; } // Register event listener for the storage event window.addEventListener('storage', jsxc.storage.onStorage, false); var lastActivity = jsxc.storage.getItem('lastActivity') || 0; if ((new Date()).getTime() - lastActivity < jsxc.options.loginTimeout) { jsxc.restore = true; } // Check if we have to establish a new connection if (!jsxc.storage.getItem('rid') || !jsxc.storage.getItem('sid') || !jsxc.restore) { // Looking for a login form if (!jsxc.options.loginForm.form || !(jsxc.el_exists(jsxc.options.loginForm.form) && jsxc.el_exists(jsxc.options.loginForm.jid) && jsxc.el_exists(jsxc.options.loginForm.pass))) { if (jsxc.options.displayRosterMinimized()) { // Show minimized roster jsxc.storage.setUserItem('roster', 'hidden'); jsxc.gui.roster.init(); jsxc.gui.roster.noConnection(); } return; } if (typeof jsxc.options.formFound === 'function') { jsxc.options.formFound.call(); } // create jquery object var form = jsxc.options.loginForm.form = $(jsxc.options.loginForm.form); var events = form.data('events') || { submit: [] }; var submits = []; // save attached submit events and remove them. Will be reattached // in jsxc.submitLoginForm $.each(events.submit, function(index, val) { submits.push(val.handler); }); form.data('submits', submits); form.off('submit'); // Add jsxc login action to form form.submit(function() { var settings = jsxc.prepareLogin(); if (settings !== false && (settings.xmpp.onlogin === "true" || settings.xmpp.onlogin === true)) { jsxc.options.loginForm.triggered = true; jsxc.xmpp.login(); // Trigger submit in jsxc.xmpp.connected() return false; } return true; }); } else { // Restore old connection jsxc.bid = jsxc.jidToBid(jsxc.storage.getItem('jid')); jsxc.gui.init(); // Looking for logout element if (jsxc.options.logoutElement !== null && jsxc.options.logoutElement.length > 0) { jsxc.options.logoutElement.one('click', function() { jsxc.options.logoutElement = $(this); jsxc.triggeredFromLogout = true; return jsxc.xmpp.logout(); }); } if (typeof (jsxc.storage.getItem('alive')) === 'undefined' || !jsxc.restore) { jsxc.onMaster(); } else { jsxc.checkMaster(); } } }, /** * Load settings and prepare jid. * * @memberOf jsxc * @returns Loaded settings */ prepareLogin: function() { var username = $(jsxc.options.loginForm.jid).val(); var password = $(jsxc.options.loginForm.pass).val(); if (typeof jsxc.options.loadSettings !== 'function') { jsxc.error('No loadSettings function given. Abort.'); return; } jsxc.gui.showWaitAlert(jsxc.l.Logging_in); var settings = jsxc.options.loadSettings.call(this, username, password); if (settings === false || settings === null || typeof settings === 'undefined') { jsxc.warn('No settings provided'); return false; } if (typeof settings.xmpp.username === 'string') { username = settings.xmpp.username; } var resource = (settings.xmpp.resource) ? '/' + settings.xmpp.resource : ''; var domain = settings.xmpp.domain; var jid; if (username.match(/@(.*)$/)) { jid = (username.match(/\/(.*)$/)) ? username : username + resource; } else { jid = username + '@' + domain + resource; } if (typeof jsxc.options.loginForm.preJid === 'function') { jid = jsxc.options.loginForm.preJid(jid); } jsxc.bid = jsxc.jidToBid(jid); settings.xmpp.username = jid.split('@')[0]; settings.xmpp.domain = jid.split('@')[1].split('/')[0]; settings.xmpp.resource = jid.split('@')[1].split('/')[1] || ""; $.each(settings, function(key, val) { jsxc.options.set(key, val); }); jsxc.options.xmpp.jid = jid; jsxc.options.xmpp.password = password; return settings; }, /** * Called if the script is a slave */ onSlave: function() { jsxc.debug('I am the slave.'); jsxc.role_allocation = true; jsxc.restoreRoster(); jsxc.restoreWindows(); jsxc.restoreCompleted = true; $(document).trigger('restoreCompleted.jsxc'); }, /** * Called if the script is the master */ onMaster: function() { jsxc.debug('I am master.'); jsxc.master = true; // Init local storage jsxc.storage.setItem('alive', 0); jsxc.storage.setItem('alive_busy', 0); if (!jsxc.storage.getUserItem('windowlist')) { jsxc.storage.setUserItem('windowlist', []); } // Sending keepalive signal jsxc.startKeepAlive(); if (jsxc.options.get('otr').enable) { // create or load DSA key and call _onMaster jsxc.otr.createDSA(); } else { jsxc._onMaster(); } }, /** * Second half of the onMaster routine */ _onMaster: function() { // create otr objects, if we lost the master if (jsxc.role_allocation) { $.each(jsxc.storage.getUserItem('windowlist'), function(index, val) { jsxc.otr.create(val); }); } jsxc.role_allocation = true; if (jsxc.restore && !jsxc.restoreCompleted) { jsxc.restoreRoster(); jsxc.restoreWindows(); jsxc.restoreCompleted = true; $(document).trigger('restoreCompleted.jsxc'); } // Prepare notifications if (jsxc.restore) { var noti = jsxc.storage.getUserItem('notification') || 2; if (jsxc.options.notification && noti > 0 && jsxc.notification.hasSupport()) { if (jsxc.notification.hasPermission()) { jsxc.notification.init(); } else { jsxc.notification.prepareRequest(); } } else { // No support => disable jsxc.options.notification = false; } } $(document).on('connectionReady.jsxc', function() { jsxc.gui.updateAvatar($('#jsxc_avatar'), jsxc.storage.getItem('jid'), 'own'); }); jsxc.xmpp.login(); }, /** * Checks if there is a master */ checkMaster: function() { jsxc.debug('check master'); jsxc.to = window.setTimeout(jsxc.onMaster, 1000); jsxc.storage.ink('alive'); }, /** * Start sending keep-alive signal */ startKeepAlive: function() { jsxc.keepalive = window.setInterval(jsxc.keepAlive, jsxc.options.timeout - 1000); }, /** * Sends the keep-alive signal to signal that the master is still there. */ keepAlive: function() { jsxc.storage.ink('alive'); if (jsxc.role_allocation) { jsxc.storage.setItem('lastActivity', (new Date()).getTime()); } }, /** * Send one keep-alive signal with higher timeout, and than resume with * normal signal */ keepBusyAlive: function() { if (jsxc.toBusy) { window.clearTimeout(jsxc.toBusy); } if (jsxc.keepalive) { window.clearInterval(jsxc.keepalive); } jsxc.storage.ink('alive_busy'); jsxc.toBusy = window.setTimeout(jsxc.startKeepAlive, jsxc.options.busyTimeout - 1000); }, /** * Generates a random integer number between 0 and max * * @param {Integer} max * @return {Integer} random integer between 0 and max */ random: function(max) { return Math.floor(Math.random() * max); }, /** * Checks if there is a element with the given selector * * @param {String} selector jQuery selector * @return {Boolean} */ el_exists: function(selector) { return $(selector).length > 0; }, /** * Creates a CSS compatible string from a JID * * @param {type} jid Valid Jabber ID * @returns {String} css Compatible string */ jidToCid: function(jid) { jsxc.warn('jsxc.jidToCid is deprecated!'); var cid = Strophe.getBareJidFromJid(jid).replace('@', '-').replace(/\./g, '-').toLowerCase(); return cid; }, /** * Create comparable bar jid. * * @memberOf jsxc * @param jid * @returns comparable bar jid */ jidToBid: function(jid) { return Strophe.getBareJidFromJid(jid).toLowerCase(); }, /** * Restore roster */ restoreRoster: function() { var buddies = jsxc.storage.getUserItem('buddylist'); if (!buddies || buddies.length === 0) { jsxc.debug('No saved buddylist.'); jsxc.gui.roster.empty(); return; } $.each(buddies, function(index, value) { jsxc.gui.roster.add(value); }); $(document).trigger('cloaded.roster.jsxc'); }, /** * Restore all windows */ restoreWindows: function() { var windows = jsxc.storage.getUserItem('windowlist'); if (windows === null) { return; } $.each(windows, function(index, bid) { var window = jsxc.storage.getUserItem('window', bid); if (!window) { jsxc.debug('Associated window-element is missing: ' + bid); return true; } jsxc.gui.window.init(bid); if (!window.minimize) { jsxc.gui.window.show(bid); } else { jsxc.gui.window.hide(bid); } jsxc.gui.window.setText(bid, window.text); }); }, /** * This method submits the specified login form. */ submitLoginForm: function() { var form = jsxc.options.loginForm.form.off('submit'); // Attach original events var submits = form.data('submits') || []; $.each(submits, function(index, val) { form.submit(val); }); if (form.find('#submit').length > 0) { form.find('#submit').click(); } else { form.submit(); } }, /** * Escapes some characters to HTML character */ escapeHTML: function(text) { text = text.replace(/&amp;/g, '&').replace(/&lt;/g, '<').replace(/&gt;/g, '>'); return text.replace(/&/g, '&amp;').replace(/</g, '&lt;').replace(/>/g, '&gt;'); }, /** * Removes all html tags. * * @memberOf jsxc * @param text * @returns stripped text */ removeHTML: function(text) { return $('<span>').html(text).text(); }, /** * Executes only one of the given events * * @param {string} obj.key event name * @param {function} obj.value function to execute * @returns {string} namespace of all events */ switchEvents: function(obj) { var ns = Math.random().toString(36).substr(2, 12); var self = this; $.each(obj, function(key, val) { $(document).one(key + '.' + ns, function() { $(document).off('.' + ns); val.apply(self, arguments); }); }); return ns; }, /** * Checks if tab is hidden. * * @returns {boolean} True if tab is hidden */ isHidden: function() { var hidden = false; if (typeof document.hidden !== 'undefined') { hidden = document.hidden; } else if (typeof document.webkitHidden !== 'undefined') { hidden = document.webkitHidden; } else if (typeof document.mozHidden !== 'undefined') { hidden = document.mozHidden; } else if (typeof document.msHidden !== 'undefined') { hidden = document.msHidden; } // handle multiple tabs if (hidden && jsxc.master) { jsxc.storage.ink('hidden', 0); } else if (!hidden && !jsxc.master) { jsxc.storage.ink('hidden'); } return hidden; }, /** * Replace %%tokens%% with correct translation. * * @param {String} text Given text * @returns {String} Translated string */ translate: function(text) { return text.replace(/%%([a-zA-Z0-9_-}{ .!,?/'@]+)%%/g, function(s, key) { var k = key.replace(/ /gi, '_').replace(/[.!,?/'@]/g, ''); if (!jsxc.l[k]) { jsxc.warn('No translation for: ' + k); } return jsxc.l[k] || key.replace(/_/g, ' '); }); }, /** * Executes the given function in jsxc namespace. * * @memberOf jsxc * @param {string} fnName Function name * @param {array} fnParams Function parameters * @returns Function return value */ exec: function(fnName, fnParams) { var fnList = fnName.split('.'); var fn = jsxc[fnList[0]]; var i; for (i = 1; i < fnList.length; i++) { fn = fn[fnList[i]]; } if (typeof fn === 'function') { return fn.apply(null, fnParams); } } }; /** * Set some options for the chat. * * @namespace jsxc.options */ jsxc.options = { /** name of container application (e.g. owncloud or SOGo) */ app_name: 'web applications', /** Timeout for the keepalive signal */ timeout: 3000, /** Timeout for the keepalive signal if the master is busy */ busyTimeout: 15000, /** OTR options */ otr: { enable: true, ERROR_START_AKE: false, debug: false, SEND_WHITESPACE_TAG: true, WHITESPACE_START_AKE: true }, /** xmpp options */ xmpp: { url: null, jid: null, domain: null, password: null, overwrite: false, onlogin: true }, /** default xmpp priorities */ priority: { online: 0, chat: 0, away: 0, xa: 0, dnd: 0 }, /** If all 3 properties are set, the login form is used */ loginForm: { /** jquery object from form */ form: null, /** jquery object from input element which contains the jid */ jid: null, /** jquery object from input element which contains the password */ pass: null, /** manipulate JID from input element */ preJid: function(jid) { return jid; }, /** * Action after connected: submit [String] Submit form, false [boolean] * Do nothing, continue [String] Start chat */ onConnected: 'submit', /** * Action after auth fail: submit [String] Submit form, false [boolean] * Do nothing, ask [String] Show auth fail dialog */ onAuthFail: 'submit' }, /** jquery object from logout element */ logoutElement: null, /** How many messages should be logged? */ numberOfMsg: 10, /** Default language */ defaultLang: 'en', /** auto language detection */ autoLang: true, /** Place for roster */ rosterAppend: 'body', /** Should we use the HTML5 notification API? */ notification: true, /** duration for notification */ popupDuration: 6000, /** Absolute path root of JSXC installation */ root: '', /** Timeout for restore in ms */ loginTimeout: 1000 * 60 * 10, /** * This function decides wether the roster will be displayed or not if no * connection is found. */ displayRosterMinimized: function() { return false; }, /** Set to true if you want to hide offline buddies. */ hideOffline: false, /** Mute notification sound? */ muteNotification: false, /** * If no avatar is found, this function is called. * * @param jid Jid of that user. * @this {jQuery} Elements to update with probable .jsxc_avatar elements */ defaultAvatar: function() { }, /** * Returns permanent saved settings and overwrite default jsxc.options. * * @memberOf jsxc.options * @param username String username * @param password String password * @returns {object} at least xmpp.url */ loadSettings: function() { }, /** * Call this function to save user settings permanent. * * @memberOf jsxc.options * @param data Holds all data as key/value * @returns {boolean} false if function failes */ saveSettinsPermanent: function() { }, carbons: { /** Enable carbon copies? */ enable: false } }; /** * Handle functions for chat window's and buddylist * * @namespace jsxc.gui */ jsxc.gui = { /** Smilie token to file mapping */ emotions: [ [ 'O:-) O:)', 'angel' ], [ '>:-( >:( &gt;:-( &gt;:(', 'angry' ], [ ':-) :)', 'smile' ], [ ':-D :D', 'grin' ], [ ':-( :(', 'sad' ], [ ';-) ;)', 'wink' ], [ ':-P :P', 'tonguesmile' ], [ '=-O', 'surprised' ], [ ':kiss: :-*', 'kiss' ], [ '8-) :cool:', 'sunglassess' ], [ ':\'-( :\'( :&amp;apos;-(', 'crysad' ], [ ':-/', 'doubt' ], [ ':-X :X', 'zip' ], [ ':yes:', 'thumbsup' ], [ ':no:', 'thumbsdown' ], [ ':beer:', 'beer' ], [ ':devil:', 'devil' ], [ ':kiss: :kissing:', 'kissing' ], [ '@->-- :rose: @-&gt;--', 'rose' ], [ ':music:', 'music' ], [ ':love:', 'love' ], [ ':zzz:', 'tired' ] ], /** * Different uri query actions as defined in XEP-0147. * * @namespace jsxc.gui.queryActions */ queryActions: { /** xmpp:JID?message[;body=TEXT] */ message: function(jid, params) { var win = jsxc.gui.window.open(jsxc.jidToBid(jid)); if (params && typeof params.body === 'string') { win.find('.jsxc_textinput').val(params.body); } }, /** xmpp:JID?remove */ remove: function(jid) { jsxc.gui.showRemoveDialog(jsxc.jidToBid(jid)); }, /** xmpp:JID?subscribe[;name=NAME] */ subscribe: function(jid, params) { jsxc.gui.showContactDialog(jid); if (params && typeof params.name) { $('#jsxc_alias').val(params.name); } }, /** xmpp:JID?vcard */ vcard: function(jid) { jsxc.gui.showVcard(jid); } }, /** * Creates application skeleton. * * @memberOf jsxc.gui */ init: function() { $('body').append($(jsxc.gui.template.get('windowList'))); $(window).resize(jsxc.gui.updateWindowListSB); $('#jsxc_windowList').resize(jsxc.gui.updateWindowListSB); $('#jsxc_windowListSB .jsxc_scrollLeft').click(function() { jsxc.gui.scrollWindowListBy(-200); }); $('#jsxc_windowListSB .jsxc_scrollRight').click(function() { jsxc.gui.scrollWindowListBy(200); }); $('#jsxc_windowList').on('wheel', function(ev) { if ($('#jsxc_windowList').data('isOver')) { jsxc.gui.scrollWindowListBy((ev.originalEvent.wheelDelta > 0) ? 200 : -200); } }); jsxc.gui.tooltip('#jsxc_windowList'); if (!jsxc.el_exists('#jsxc_roster')) { jsxc.gui.roster.init(); } // prepare regexp for emotions $.each(jsxc.gui.emotions, function(i, val) { // escape characters var reg = val[0].replace(/(\/|\||\*|\.|\+|\?|\^|\$|\(|\)|\[|\]|\{|\})/g, '\\$1'); reg = '(' + reg.split(' ').join('|') + ')'; jsxc.gui.emotions[i][2] = new RegExp(reg, 'g'); }); // We need this often, so we creates some template jquery objects jsxc.gui.windowTemplate = $(jsxc.gui.template.get('chatWindow')); jsxc.gui.buddyTemplate = $(jsxc.gui.template.get('rosterBuddy')); }, /** * Init tooltip plugin for given jQuery selector. * * @param {String} selector jQuery selector * @memberOf jsxc.gui */ tooltip: function(selector) { $(selector).tooltip({ show: { delay: 600 }, content: function() { return $(this).attr('title').replace(/\n/g, '<br />'); } }); }, /** * Updates Information in roster and chatbar * * @param {String} bid bar jid */ update: function(bid) { var data = jsxc.storage.getUserItem('buddy', bid); if (!data) { jsxc.debug('No data for ' + bid); return; } var ri = jsxc.gui.roster.getItem(bid); // roster item from user var we = jsxc.gui.window.get(bid); // window element from user var ue = ri.add(we); // both var spot = $('.jsxc_spot[data-bid="' + bid + '"]'); // Attach data to corresponding roster item ri.data(data); // Add online status ue.add(spot).removeClass('jsxc_' + jsxc.CONST.STATUS.join(' jsxc_')).addClass('jsxc_' + jsxc.CONST.STATUS[data.status]); // Change name and add title ue.find('.jsxc_name').add(spot).text(data.name).attr('title', jsxc.l.is + ' ' + jsxc.CONST.STATUS[data.status]); // Update gui according to encryption state switch (data.msgstate) { case 0: we.find('.jsxc_transfer').removeClass('jsxc_enc jsxc_fin').attr('title', jsxc.l.your_connection_is_unencrypted); we.find('.jsxc_settings .jsxc_verification').addClass('jsxc_disabled'); we.find('.jsxc_settings .jsxc_transfer').text(jsxc.l.start_private); break; case 1: we.find('.jsxc_transfer').addClass('jsxc_enc').attr('title', jsxc.l.your_connection_is_encrypted); we.find('.jsxc_settings .jsxc_verification').removeClass('jsxc_disabled'); we.find('.jsxc_settings .jsxc_transfer').text(jsxc.l.close_private); break; case 2: we.find('.jsxc_settings .jsxc_verification').addClass('jsxc_disabled'); we.find('.jsxc_transfer').removeClass('jsxc_enc').addClass('jsxc_fin').attr('title', jsxc.l.your_buddy_closed_the_private_connection); we.find('.jsxc_settings .jsxc_transfer').text(jsxc.l.close_private); break; } // update gui according to verification state if (data.trust) { we.find('.jsxc_transfer').addClass('jsxc_trust').attr('title', jsxc.l.your_buddy_is_verificated); } else { we.find('.jsxc_transfer').removeClass('jsxc_trust'); } // update gui according to subscription state if (data.sub && data.sub !== 'both') { ue.addClass('jsxc_oneway'); } else { ue.removeClass('jsxc_oneway'); } var info = '<b>' + Strophe.getBareJidFromJid(data.jid) + '</b>\n'; info += jsxc.translate('%%Subscription%%: %%' + data.sub + '%%\n'); info += jsxc.translate('%%Status%%: %%' + jsxc.CONST.STATUS[data.status] + '%%'); ri.find('.jsxc_name').attr('title', info); if (data.avatar && data.avatar.length > 0) { jsxc.gui.updateAvatar(ue, data.jid, data.avatar); } else { jsxc.options.defaultAvatar.call(ue, data.jid); } }, /** * Update avatar on all given elements. * * @memberOf jsxc.gui * @param {jQuery} el Elements with subelement .jsxc_avatar * @param {string} jid Jid * @param {string} aid Avatar id (sha1 hash of image) */ updateAvatar: function(el, jid, aid) { if (typeof aid === 'undefined') { if (typeof jsxc.options.defaultAvatar === 'function') { jsxc.options.defaultAvatar.call(el, jid); } return; } var avatarSrc = jsxc.storage.getUserItem('avatar', aid); var setAvatar = function(src) { if (src === 0 || src === '0') { jsxc.options.defaultAvatar.call(el, jid); return; } el.find('.jsxc_avatar').removeAttr('style'); el.find('.jsxc_avatar').css({ 'background-image': 'url(' + src + ')', 'text-indent': '999px' }); }; if (avatarSrc !== null) { setAvatar(avatarSrc); } else { jsxc.xmpp.conn.vcard.get(function(stanza) { jsxc.debug('vCard', stanza); var vCard = $(stanza).find("vCard > PHOTO"); var src; if (vCard.length === 0) { jsxc.debug('No photo provided'); src = '0'; } else if (vCard.find('EXTVAL').length > 0) { src = vCard.find('EXTVAL').text(); } else { var img = vCard.find('BINVAL').text(); var type = vCard.find('TYPE').text(); src = 'data:' + type + ';base64,' + img; } // concat chunks src = src.replace(/[\t\r\n\f]/gi, ''); jsxc.storage.setUserItem('avatar', aid, src); setAvatar(src); }, Strophe.getBareJidFromJid(jid), function(msg) { jsxc.warn('Could not load vcard.', msg); jsxc.storage.setUserItem('avatar', aid, 0); setAvatar(0); }); } }, /** * Updates scrollbar handlers. * * @memberOf jsxc.gui */ updateWindowListSB: function() { if ($('#jsxc_windowList>ul').width() > $('#jsxc_windowList').width()) { $('#jsxc_windowListSB > div').removeClass('jsxc_disabled'); } else { $('#jsxc_windowListSB > div').addClass('jsxc_disabled'); $('#jsxc_windowList>ul').css('right', '0px'); } }, /** * Scroll window list by offset. * * @memberOf jsxc.gui * @param offset */ scrollWindowListBy: function(offset) { var scrollWidth = $('#jsxc_windowList>ul').width(); var width = $('#jsxc_windowList').width(); var el = $('#jsxc_windowList>ul'); var right = parseInt(el.css('right')) - offset; var padding = $("#jsxc_windowListSB").width(); if (scrollWidth < width) { return; } if (right > 0) { right = 0; } if (right < width - scrollWidth - padding) { right = width - scrollWidth - padding; } el.css('right', right + 'px'); }, /** * Returns the window element * * @param {String} bid * @returns {jquery} jQuery object of the window element */ getWindow: function(bid) { jsxc.warn('jsxc.gui.getWindow is deprecated!'); return jsxc.gui.window.get(bid); }, /** * Toggle list with timeout, like menu or settings * * @memberof jsxc.gui */ toggleList: function() { var self = $(this); self.disableSelection(); var ul = self.find('ul'); var slideUp = null; slideUp = function() { ul.slideUp({ complete: function() { self.removeClass('jsxc_opened'); } }); $('body').off('click', null, slideUp); }; $(this).click(function() { if (ul.is(":hidden")) { // hide other lists $('body').click(); $('body').one('click', slideUp); } else { $('body').off('click', null, slideUp); } ul.slideToggle(); window.clearTimeout(ul.data('timer')); self.toggleClass('jsxc_opened'); return false; }).mouseleave(function() { ul.data('timer', window.setTimeout(slideUp, 2000)); }).mouseenter(function() { window.clearTimeout(ul.data('timer')); }); }, /** * Creates and show loginbox */ showLoginBox: function() { // Set focus to password field $(document).on("complete.dialog.jsxc", function() { $('#jsxc_password').focus(); }); jsxc.gui.dialog.open(jsxc.gui.template.get('loginBox')); $('#jsxc_dialog').find('form').submit(function() { $(this).find('input[type=submit]').prop('disabled', true); jsxc.options.loginForm.form = $(this); jsxc.options.loginForm.jid = $(this).find('#jsxc_username'); jsxc.options.loginForm.pass = $(this).find('#jsxc_password'); var settings = jsxc.prepareLogin(); jsxc.triggeredFromBox = true; jsxc.options.loginForm.triggered = false; if (settings === false) { jsxc.gui.showAuthFail(); } else { jsxc.xmpp.login(); } return false; }); }, /** * Creates and show the fingerprint dialog * * @param {String} bid */ showFingerprints: function(bid) { jsxc.gui.dialog.open(jsxc.gui.template.get('fingerprintsDialog', bid)); }, /** * Creates and show the verification dialog * * @param {String} bid */ showVerification: function(bid) { // Check if there is a open dialog if ($('#jsxc_dialog').length > 0) { setTimeout(function() { jsxc.gui.showVerification(bid); }, 3000); return; } // verification only possible if the connection is encrypted if (jsxc.storage.getUserItem('buddy', bid).msgstate !== OTR.CONST.MSGSTATE_ENCRYPTED) { jsxc.warn('Connection not encrypted'); return; } jsxc.gui.dialog.open(jsxc.gui.template.get('authenticationDialog', bid)); // Add handler $('#jsxc_dialog > div:gt(0)').hide(); $('#jsxc_dialog select').change(function() { $('#jsxc_dialog > div:gt(0)').hide(); $('#jsxc_dialog > div:eq(' + $(this).prop('selectedIndex') + ')').slideDown({ complete: function() { jsxc.gui.dialog.resize(); } }); }); // Manual $('#jsxc_dialog > div:eq(1) a.creation').click(function() { if (jsxc.master) { jsxc.otr.objects[bid].trust = true; } jsxc.storage.updateUserItem('buddy', bid, 'trust', true); jsxc.gui.dialog.close(); jsxc.storage.updateUserItem('buddy', bid, 'trust', true); jsxc.gui.window.postMessage(bid, 'sys', jsxc.l.conversation_is_now_verified); jsxc.gui.update(bid); }); // Question $('#jsxc_dialog > div:eq(2) a.creation').click(function() { var div = $('#jsxc_dialog > div:eq(2)'); var sec = div.find('#jsxc_secret2').val(); var quest = div.find('#jsxc_quest').val(); if (sec === '' || quest === '') { // Add information for the user which form is missing div.find('input[value=""]').addClass('jsxc_invalid').keyup(function() { if ($(this).val().match(/.*/)) { $(this).removeClass('jsxc_invalid'); } }); return; } if (jsxc.master) { jsxc.otr.sendSmpReq(bid, sec, quest); } else { jsxc.storage.setUserItem('smp_' + bid, { sec: sec, quest: quest }); } jsxc.gui.dialog.close(); jsxc.gui.window.postMessage(bid, 'sys', jsxc.l.authentication_query_sent); }); // Secret $('#jsxc_dialog > div:eq(3) .creation').click(function() { var div = $('#jsxc_dialog > div:eq(3)'); var sec = div.find('#jsxc_secret').val(); if (sec === '') { // Add information for the user which form is missing div.find('#jsxc_secret').addClass('jsxc_invalid').keyup(function() { if ($(this).val().match(/.*/)) { $(this).removeClass('jsxc_invalid'); } }); return; } if (jsxc.master) { jsxc.otr.sendSmpReq(bid, sec); } else { jsxc.storage.setUserItem('smp_' + bid, { sec: sec, quest: null }); } jsxc.gui.dialog.close(); jsxc.gui.window.postMessage(bid, 'sys', jsxc.l.authentication_query_sent); }); }, /** * Create and show approve dialog * * @param {type} from valid jid */ showApproveDialog: function(from) { jsxc.gui.dialog.open(jsxc.gui.template.get('approveDialog'), { 'noClose': true }); $('#jsxc_dialog .jsxc_their_jid').text(Strophe.getBareJidFromJid(from)); $('#jsxc_dialog .jsxc_deny').click(function(ev) { ev.stopPropagation(); jsxc.xmpp.resFriendReq(from, false); jsxc.gui.dialog.close(); }); $('#jsxc_dialog .jsxc_approve').click(function(ev) { ev.stopPropagation(); var data = jsxc.storage.getUserItem('buddy', jsxc.jidToBid(from)); jsxc.xmpp.resFriendReq(from, true); // If friendship is not mutual show contact dialog if (!data || data.sub === 'from') { $(document).one('close.dialog.jsxc', function() { jsxc.gui.showContactDialog(from); }); } jsxc.gui.dialog.close(); }); }, /** * Create and show dialog to add a buddy * * @param {string} [username] jabber id */ showContactDialog: function(username) { jsxc.gui.dialog.open(jsxc.gui.template.get('contactDialog')); // If we got a friendship request, we would display the username in our // response if (username) { $('#jsxc_username').val(username); } $('#jsxc_dialog form').submit(function() { var username = $('#jsxc_username').val(); var alias = $('#jsxc_alias').val(); if (!username.match(/@(.*)$/)) { username += '@' + Strophe.getDomainFromJid(jsxc.storage.getItem('jid')); } // Check if the username is valid if (!username || !username.match(jsxc.CONST.REGEX.JID)) { // Add notification $('#jsxc_username').addClass('jsxc_invalid').keyup(function() { if ($(this).val().match(jsxc.CONST.REGEX.JID)) { $(this).removeClass('jsxc_invalid'); } }); return false; } jsxc.xmpp.addBuddy(username, alias); jsxc.gui.dialog.close(); return false; }); }, /** * Create and show dialog to remove a buddy * * @param {type} bid * @returns {undefined} */ showRemoveDialog: function(bid) { jsxc.gui.dialog.open(jsxc.gui.template.get('removeDialog', bid)); var data = jsxc.storage.getUserItem('buddy', bid); $('#jsxc_dialog .creation').click(function(ev) { ev.stopPropagation(); if (jsxc.master) { jsxc.xmpp.removeBuddy(data.jid); } else { // inform master jsxc.storage.setUserItem('deletebuddy', bid, { jid: data.jid }); } jsxc.gui.dialog.close(); }); }, /** * Create and show a wait dialog * * @param {type} msg message to display to the user * @returns {undefined} */ showWaitAlert: function(msg) { jsxc.gui.dialog.open(jsxc.gui.template.get('waitAlert', null, msg), { 'noClose': true }); }, /** * Create and show a wait dialog * * @param {type} msg message to display to the user * @returns {undefined} */ showAlert: function(msg) { jsxc.gui.dialog.open(jsxc.gui.template.get('alert', null, msg)); }, /** * Create and show a auth fail dialog * * @returns {undefined} */ showAuthFail: function() { jsxc.gui.dialog.open(jsxc.gui.template.get('authFailDialog')); if (jsxc.options.loginForm.triggered !== false) { $('#jsxc_dialog .jsxc_cancel').hide(); } $('#jsxc_dialog .creation').click(function() { jsxc.gui.dialog.close(); }); $('#jsxc_dialog .jsxc_cancel').click(function() { jsxc.submitLoginForm(); }); }, /** * Create and show a confirm dialog * * @param {String} msg Message * @param {function} confirm * @param {function} dismiss * @returns {undefined} */ showConfirmDialog: function(msg, confirm, dismiss) { jsxc.gui.dialog.open(jsxc.gui.template.get('confirmDialog', null, msg), { noClose: true }); if (confirm) { $('#jsxc_dialog .creation').click(confirm); } if (dismiss) { $('#jsxc_dialog .jsxc_cancel').click(dismiss); } }, /** * Show about dialog. * * @memberOf jsxc.gui */ showAboutDialog: function() { jsxc.gui.dialog.open(jsxc.gui.template.get('aboutDialog')); $('#jsxc_dialog .jsxc_debuglog').click(function() { jsxc.gui.showDebugLog(); }); }, /** * Show debug log. * * @memberOf jsxc.gui */ showDebugLog: function() { var userInfo = '<h3>User information</h3>'; if (navigator) { var key; for (key in navigator) { if (navigator.hasOwnProperty(key) && typeof navigator[key] === 'string') { userInfo += '<b>' + key + ':</b> ' + navigator[key] + '<br />'; } } } if (window.screen) { userInfo += '<b>Height:</b> ' + window.screen.height + '<br />'; userInfo += '<b>Width:</b> ' + window.screen.width + '<br />'; } userInfo += '<b>jsxc version:</b> ' + jsxc.version + '<br />'; jsxc.gui.dialog.open('<div class="jsxc_log">' + userInfo + '<h3>Log</h3><pre>' + jsxc.escapeHTML(jsxc.log) + '</pre></div>'); }, /** * Show vCard of user with the given bar jid. * * @memberOf jsxc.gui * @param {String} jid */ showVcard: function(jid) { var bid = jsxc.jidToBid(jid); jsxc.gui.dialog.open(jsxc.gui.template.get('vCard', bid)); var data = jsxc.storage.getUserItem('buddy', bid); if (data) { // Display resources and corresponding information var i, j, res, identities, identity = null, cap, client; for (i = 0; i < data.res.length; i++) { res = data.res[i]; identities = []; cap = jsxc.xmpp.getCapabilitiesByJid(bid + '/' + res); if (cap !== null && cap.identities !== null) { identities = cap.identities; } client = ''; for (j = 0; j < identities.length; j++) { identity = identities[j]; if (identity.category === 'client') { if (client !== '') { client += ',\n'; } client += identity.name + ' (' + identity.type + ')'; } } var status = jsxc.storage.getUserItem('res', bid)[res]; $('#jsxc_dialog ul.jsxc_vCard').append('<li class="jsxc_sep"><strong>' + jsxc.translate('%%Resource%%') + ':</strong> ' + res + '</li>'); $('#jsxc_dialog ul.jsxc_vCard').append('<li><strong>' + jsxc.translate('%%Client%%') + ':</strong> ' + client + '</li>'); $('#jsxc_dialog ul.jsxc_vCard').append('<li>' + jsxc.translate('<strong>%%Status%%:</strong> %%' + jsxc.CONST.STATUS[status] + '%%') + '</li>'); } } var printProp = function(el, depth) { var content = ''; el.each(function() { var item = $(this); var children = $(this).children(); content += '<li>'; var prop = jsxc.translate('%%' + item[0].tagName + '%%'); if (prop !== ' ') { content += '<strong>' + prop + ':</strong> '; } if (item[0].tagName === 'PHOTO') { } else if (children.length > 0) { content += '<ul>'; content += printProp(children, depth + 1); content += '</ul>'; } else if (item.text() !== '') { content += jsxc.escapeHTML(item.text()); } content += '</li>'; if (depth === 0 && $('#jsxc_dialog ul.jsxc_vCard').length > 0) { if ($('#jsxc_dialog ul.jsxc_vCard li.jsxc_sep:first').length > 0) { $('#jsxc_dialog ul.jsxc_vCard li.jsxc_sep:first').before(content); } else { $('#jsxc_dialog ul.jsxc_vCard').append(content); } content = ''; } }); if (depth > 0) { return content; } }; var failedToLoad = function() { if ($('#jsxc_dialog ul.jsxc_vCard').length === 0) { return; } $('#jsxc_dialog p').remove(); var content = '<p>'; content += jsxc.translate('%%Sorry, your buddy doesn\'t provide any information.%%'); content += '</p>'; $('#jsxc_dialog').append(content); }; jsxc.xmpp.loadVcard(bid, function(stanza) { if ($('#jsxc_dialog ul.jsxc_vCard').length === 0) { return; } $('#jsxc_dialog p').remove(); var photo = $(stanza).find("vCard > PHOTO"); if (photo.length > 0) { var img = photo.find('BINVAL').text(); var type = photo.find('TYPE').text(); var src = 'data:' + type + ';base64,' + img; if (photo.find('EXTVAL').length > 0) { src = photo.find('EXTVAL').text(); } // concat chunks src = src.replace(/[\t\r\n\f]/gi, ''); var img_el = $('<img class="jsxc_vCard" alt="avatar" />'); img_el.attr('src', src); $('#jsxc_dialog h3').before(img_el); } if ($(stanza).find('vCard').length === 0 || ($(stanza).find('vcard > *').length === 1 && photo.length === 1)) { failedToLoad(); return; } printProp($(stanza).find('vcard > *'), 0); }, failedToLoad); }, showSettings: function() { jsxc.gui.dialog.open(jsxc.gui.template.get('settings')); if (jsxc.options.get('xmpp').overwrite === 'false' || jsxc.options.get('xmpp').overwrite === false) { $('.jsxc_fieldsetXmpp').hide(); } $('#jsxc_dialog form').each(function() { var self = $(this); self.find('input[type!="submit"]').each(function() { var id = this.id.split("-"); var prop = id[0]; var key = id[1]; var type = this.type; var data = jsxc.options.get(prop); if (data && typeof data[key] !== 'undefined') { if (type === 'checkbox') { if (data[key] !== 'false' && data[key] !== false) { this.checked = 'checked'; } } else { $(this).val(data[key]); } } }); }); $('#jsxc_dialog form').submit(function() { var self = $(this); var data = {}; self.find('input[type!="submit"]').each(function() { var id = this.id.split("-"); var prop = id[0]; var key = id[1]; var val; var type = this.type; if (type === 'checkbox') { val = this.checked; } else { val = $(this).val(); } if (!data[prop]) { data[prop] = {}; } data[prop][key] = val; }); $.each(data, function(key, val) { jsxc.options.set(key, val); }); var err = jsxc.options.saveSettinsPermanent.call(this, data); if (typeof self.attr('data-onsubmit') === 'string') { jsxc.exec(self.attr('data-onsubmit'), [ err ]); } setTimeout(function() { self.find('input[type="submit"]').effect('highlight', { color: (err) ? 'green' : 'red' }, 4000); }, 200); return false; }); }, /** * Show prompt for notification permission. * * @memberOf jsxc.gui */ showRequestNotification: function() { jsxc.gui.showConfirmDialog(jsxc.translate("%%Should we notify you_%%"), function() { jsxc.gui.dialog.open(jsxc.gui.template.get('pleaseAccept'), { noClose: true }); jsxc.notification.requestPermission(); }, function() { $(document).trigger('notificationfailure.jsxc'); }); }, showUnknownSender: function(bid) { jsxc.gui.showConfirmDialog(jsxc.translate('%%You_received_a_message_from_an_unknown_sender%% (' + bid + '). %%Do_you_want_to_display_them%%'), function() { jsxc.gui.dialog.close(); jsxc.storage.saveBuddy(bid, { jid: bid, name: bid, status: 0, sub: 'none', res: [] }); jsxc.gui.window.open(bid); }, function() { // reset state jsxc.storage.removeUserItem('chat', bid); }); }, /** * Change own presence to pres. * * @memberOf jsxc.gui * @param pres {CONST.STATUS} New presence state * @param external {boolean} True if triggered from other tab. */ changePresence: function(pres, external) { if (external !== true) { jsxc.storage.setUserItem('presence', pres); } if (jsxc.master) { jsxc.xmpp.sendPres(); } $('#jsxc_presence > span').text($('#jsxc_presence > ul .jsxc_' + pres).text()); jsxc.gui.updatePresence('own', pres); }, /** * Update all presence objects for given user. * * @memberOf jsxc.gui * @param bid bar jid of user. * @param {CONST.STATUS} pres New presence state. */ updatePresence: function(bid, pres) { if (bid === 'own') { if (pres === 'dnd') { $('#jsxc_menu .jsxc_muteNotification').addClass('jsxc_disabled'); jsxc.notification.muteSound(true); } else { $('#jsxc_menu .jsxc_muteNotification').removeClass('jsxc_disabled'); if (!jsxc.options.get('muteNotification')) { jsxc.notification.unmuteSound(true); } } } $('.jsxc_presence[data-bid="' + bid + '"]').removeClass('jsxc_' + jsxc.CONST.STATUS.join(' jsxc_')).addClass('jsxc_' + pres); }, /** * Switch read state to UNread. * * @memberOf jsxc.gui * @param bid */ unreadMsg: function(bid) { var win = jsxc.gui.window.get(bid); jsxc.gui.roster.getItem(bid).add(win).addClass('jsxc_unreadMsg'); jsxc.storage.updateUserItem('window', bid, 'unread', true); }, /** * Switch read state to read. * * @memberOf jsxc.gui * @param bid */ readMsg: function(bid) { var win = jsxc.gui.window.get(bid); if (win.hasClass('jsxc_unreadMsg')) { jsxc.gui.roster.getItem(bid).add(win).removeClass('jsxc_unreadMsg'); jsxc.storage.updateUserItem('window', bid, 'unread', false); } }, /** * This function searches for URI scheme according to XEP-0147. * * @memberOf jsxc.gui * @param container In which element should we search? */ detectUriScheme: function(container) { container = (container) ? $(container) : $('body'); container.find("a[href^='xmpp:']").each(function() { var element = $(this); var href = element.attr('href').replace(/^xmpp:/, ''); var jid = href.split('?')[0]; var action, params = {}; if (href.indexOf('?') < 0) { action = 'message'; } else { var pairs = href.substring(href.indexOf('?') + 1).split(';'); action = pairs[0]; var i, key, value; for (i = 1; i < pairs.length; i++) { key = pairs[i].split('=')[0]; value = (pairs[i].indexOf('=') > 0) ? pairs[i].substring(pairs[i].indexOf('=') + 1) : null; params[decodeURIComponent(key)] = decodeURIComponent(value); } } if (typeof jsxc.gui.queryActions[action] === 'function') { element.addClass('jsxc_uriScheme jsxc_uriScheme_' + action); element.off('click').click(function(ev) { ev.stopPropagation(); jsxc.gui.queryActions[action].call(jsxc, jid, params); return false; }); } }); }, detectEmail: function(container) { container = (container) ? $(container) : $('body'); container.find('a[href^="mailto:"]').each(function() { var spot = $("<span>X</span>").addClass("jsxc_spot"); var href = $(this).attr("href").replace(/^ *mailto:/, "").trim(); if (href !== '' && href !== Strophe.getBareJidFromJid(jsxc.storage.getItem("jid"))) { var bid = jsxc.jidToBid(href); var self = $(this); var s = self.prev(); if (!s.hasClass('jsxc_spot')) { s = spot.clone().attr('data-bid', bid); self.before(s); } s.off('click'); if (jsxc.storage.getUserItem('buddy', bid)) { jsxc.gui.update(bid); s.click(function() { jsxc.gui.window.open(bid); return false; }); } else { s.click(function() { jsxc.gui.showContactDialog(href); return false; }); } } }); } }; /** * Handle functions related to the gui of the roster * * @namespace jsxc.gui.roster */ jsxc.gui.roster = { /** * Init the roster skeleton * * @memberOf jsxc.gui.roster * @returns {undefined} */ init: function() { $(jsxc.options.rosterAppend + ':first').append($(jsxc.gui.template.get('roster'))); if (jsxc.options.get('hideOffline')) { $('#jsxc_menu .jsxc_hideOffline').text(jsxc.translate('%%Show offline%%')); $('#jsxc_buddylist').addClass('jsxc_hideOffline'); } $('#jsxc_menu .jsxc_settings').click(function() { jsxc.gui.showSettings(); }); $('#jsxc_menu .jsxc_hideOffline').click(function() { var hideOffline = !jsxc.options.get('hideOffline'); if (hideOffline) { $('#jsxc_buddylist').addClass('jsxc_hideOffline'); } else { $('#jsxc_buddylist').removeClass('jsxc_hideOffline'); } $(this).text(hideOffline ? jsxc.translate('%%Show offline%%') : jsxc.translate('%%Hide offline%%')); jsxc.options.set('hideOffline', hideOffline); }); if (jsxc.options.get('muteNotification')) { jsxc.notification.muteSound(); } $('#jsxc_menu .jsxc_muteNotification').click(function() { if (jsxc.storage.getUserItem('presence') === 'dnd') { return; } // invert current choice var mute = !jsxc.options.get('muteNotification'); if (mute) { jsxc.notification.muteSound(); } else { jsxc.notification.unmuteSound(); } }); $('#jsxc_roster .jsxc_addBuddy').click(function() { jsxc.gui.showContactDialog(); }); $('#jsxc_roster .jsxc_onlineHelp').click(function() { window.open("http://www.jsxc.org/manual.html", "onlineHelp"); }); $('#jsxc_roster .jsxc_about').click(function() { jsxc.gui.showAboutDialog(); }); $('#jsxc_toggleRoster').click(function() { jsxc.gui.roster.toggle(); }); $('#jsxc_presence > ul > li').click(function() { var self = $(this); jsxc.gui.changePresence(self.data('pres')); }); $('#jsxc_buddylist').slimScroll({ distance: '3px', height: ($('#jsxc_roster').height() - 31) + 'px', width: $('#jsxc_buddylist').width() + 'px', color: '#fff', opacity: '0.5' }); $('#jsxc_roster > .jsxc_bottom > div').each(function() { jsxc.gui.toggleList.call($(this)); }); if (jsxc.storage.getUserItem('roster') === 'hidden') { $('#jsxc_roster').css('right', '-200px'); $('#jsxc_windowList > ul').css('paddingRight', '10px'); } var pres = jsxc.storage.getUserItem('presence') || 'online'; $('#jsxc_presence > span').text($('#jsxc_presence > ul .jsxc_' + pres).text()); jsxc.gui.updatePresence('own', pres); jsxc.gui.tooltip('#jsxc_roster'); jsxc.notice.load(); $(document).trigger('ready.roster.jsxc'); }, /** * Create roster item and add it to the roster * * @param {String} bid bar jid */ add: function(bid) { var data = jsxc.storage.getUserItem('buddy', bid); var bud = jsxc.gui.buddyTemplate.clone().attr('data-bid', bid).attr('data-type', data.type || 'chat'); jsxc.gui.roster.insert(bid, bud); bud.click(function() { jsxc.gui.window.open(bid); }); bud.find('.jsxc_chaticon').click(function() { jsxc.gui.window.open(bid); }); bud.find('.jsxc_rename').click(function() { jsxc.gui.roster.rename(bid); return false; }); bud.find('.jsxc_delete').click(function() { jsxc.gui.showRemoveDialog(bid); return false; }); var expandClick = function() { bud.trigger('extra.jsxc'); bud.toggleClass('jsxc_expand'); jsxc.gui.updateAvatar(bud, data.jid, data.avatar); return false; }; bud.find('.jsxc_control').click(expandClick); bud.dblclick(expandClick); bud.find('.jsxc_vcardicon').click(function() { jsxc.gui.showVcard(data.jid); return false; }); jsxc.gui.update(bid); // update scrollbar $('#jsxc_buddylist').slimScroll({ scrollTo: '0px' }); $(document).trigger('add.roster.jsxc', [ bid, data, bud ]); }, getItem: function(bid) { return $("#jsxc_buddylist > li[data-bid='" + bid + "']"); }, /** * Insert roster item. First order: online > away > offline. Second order: * alphabetical of the name * * @param {type} bid * @param {jquery} li roster item which should be insert * @returns {undefined} */ insert: function(bid, li) { var data = jsxc.storage.getUserItem('buddy', bid); var listElements = $('#jsxc_buddylist > li'); var insert = false; // Insert buddy with no mutual friendship to the end var status = (data.sub === 'both') ? data.status : -1; listElements.each(function() { var thisStatus = ($(this).data('sub') === 'both') ? $(this).data('status') : -1; if (($(this).data('name').toLowerCase() > data.name.toLowerCase() && thisStatus === status) || thisStatus < status) { $(this).before(li); insert = true; return false; } }); if (!insert) { li.appendTo('#jsxc_buddylist'); } }, /** * Initiate reorder of roster item * * @param {type} bid * @returns {undefined} */ reorder: function(bid) { jsxc.gui.roster.insert(bid, jsxc.gui.roster.remove(bid)); }, /** * Removes buddy from roster * * @param {String} bid bar jid * @return {JQueryObject} Roster list element */ remove: function(bid) { return jsxc.gui.roster.getItem(bid).detach(); }, /** * Removes buddy from roster and clean up * * @param {String} bid bar compatible jid */ purge: function(bid) { if (jsxc.master) { jsxc.storage.removeUserItem('buddy', bid); jsxc.storage.removeUserItem('otr', bid); jsxc.storage.removeUserItem('otr_version_' + bid); jsxc.storage.removeUserItem('chat', bid); jsxc.storage.removeUserItem('window', bid); jsxc.storage.removeUserElement('buddylist', bid); jsxc.storage.removeUserElement('windowlist', bid); } jsxc.gui.window._close(bid); jsxc.gui.roster.remove(bid); }, /** * Create input element for rename action * * @param {type} bid * @returns {undefined} */ rename: function(bid) { var name = jsxc.gui.roster.getItem(bid).find('.jsxc_name'); var options = jsxc.gui.roster.getItem(bid).find('.jsxc_options, .jsxc_control'); var input = $('<input type="text" name="name"/>'); options.hide(); name = name.replaceWith(input); input.val(name.text()); input.keypress(function(ev) { if (ev.which !== 13) { return; } options.show(); input.replaceWith(name); jsxc.gui.roster._rename(bid, $(this).val()); $('html').off('click'); }); // Disable html click event, if click on input input.click(function() { return false; }); $('html').one('click', function() { options.show(); input.replaceWith(name); jsxc.gui.roster._rename(bid, input.val()); }); }, /** * Rename buddy * * @param {type} bid * @param {type} newname new name of buddy * @returns {undefined} */ _rename: function(bid, newname) { if (jsxc.master) { var d = jsxc.storage.getUserItem('buddy', bid); var iq = $iq({ type: 'set' }).c('query', { xmlns: 'jabber:iq:roster' }).c('item', { jid: Strophe.getBareJidFromJid(d.jid), name: newname }); jsxc.xmpp.conn.sendIQ(iq); } jsxc.storage.updateUserItem('buddy', bid, 'name', newname); jsxc.gui.update(bid); }, /** * Toogle complete roster * * @param {Integer} d Duration in ms */ toggle: function(d) { var duration = d || 500; var roster = $('#jsxc_roster'); var wl = $('#jsxc_windowList'); var roster_width = roster.innerWidth(); var roster_right = parseFloat($('#jsxc_roster').css('right')); var state = (roster_right < 0) ? 'shown' : 'hidden'; jsxc.storage.setUserItem('roster', state); roster.animate({ right: ((roster_width + roster_right) * -1) + 'px' }, duration); wl.animate({ right: (10 - roster_right) + 'px' }, duration); $(document).trigger('toggle.roster.jsxc', [ state, duration ]); }, /** * Shows a text with link to a login box that no connection exists. */ noConnection: function() { $('#jsxc_roster').addClass('jsxc_noConnection'); $('#jsxc_roster').append($('<p>' + jsxc.l.no_connection + '</p>').append(' <a>' + jsxc.l.relogin + '</a>').click(function() { jsxc.gui.showLoginBox(); })); }, /** * Shows a text with link to add a new buddy. * * @memberOf jsxc.gui.roster */ empty: function() { var text = $('<p>' + jsxc.l.Your_roster_is_empty_add_a + '</p>'); var link = $('<a>' + jsxc.l.new_buddy + '</a>'); link.click(function() { jsxc.gui.showContactDialog(); }); text.append(link); text.append('.'); $('#jsxc_roster').prepend(text); } }; /** * Wrapper for dialog * * @namespace jsxc.gui.dialog */ jsxc.gui.dialog = { /** * Open a Dialog. * * @memberOf jsxc.gui.dialog * @param {String} data Data of the dialog * @param {Object} [o] Options for the dialog * @param {Boolean} [o.noClose] If true, hide all default close options * @returns {jQuery} Dialog object */ open: function(data, o) { var opt = o || {}; // default options var options = {}; options = { onComplete: function() { $('#jsxc_dialog .jsxc_close').click(function(ev) { ev.preventDefault(); jsxc.gui.dialog.close(); }); // workaround for old colorbox version (used by firstrunwizard) if (options.closeButton === false) { $('#cboxClose').hide(); } $.colorbox.resize(); $(document).trigger('complete.dialog.jsxc'); }, onClosed: function() { $(document).trigger('close.dialog.jsxc'); }, onCleanup: function() { $(document).trigger('cleanup.dialog.jsxc'); }, opacity: 0.5 }; if (opt.noClose) { options.overlayClose = false; options.escKey = false; options.closeButton = false; delete opt.noClose; } $.extend(options, opt); options.html = '<div id="jsxc_dialog">' + data + '</div>'; $.colorbox(options); return $('#jsxc_dialog'); }, /** * Close current dialog. */ close: function() { jsxc.debug('close dialog'); $.colorbox.close(); }, /** * Resizes current dialog. * * @param {Object} options e.g. width and height */ resize: function(options) { $.colorbox.resize(options); } }; /** * Handle functions related to the gui of the window * * @namespace jsxc.gui.window */ jsxc.gui.window = { /** * Init a window skeleton * * @memberOf jsxc.gui.window * @param {String} bid * @returns {jQuery} Window object */ init: function(bid) { if (jsxc.gui.window.get(bid).length > 0) { return jsxc.gui.window.get(bid); } var win = jsxc.gui.windowTemplate.clone().attr('data-bid', bid).hide().appendTo('#jsxc_windowList > ul').show('slow'); var data = jsxc.storage.getUserItem('buddy', bid); // Attach jid to window win.data('jid', data.jid); // Add handler jsxc.gui.toggleList.call(win.find('.jsxc_settings')); win.find('.jsxc_verification').click(function() { jsxc.gui.showVerification(bid); }); win.find('.jsxc_fingerprints').click(function() { jsxc.gui.showFingerprints(bid); }); win.find('.jsxc_transfer').click(function() { jsxc.otr.toggleTransfer(bid); }); win.find('.jsxc_bar').click(function() { jsxc.gui.window.toggle(bid); }); win.find('.jsxc_close').click(function() { jsxc.gui.window.close(bid); }); win.find('.jsxc_clear').click(function() { jsxc.gui.window.clear(bid); }); win.find('.jsxc_tools').click(function() { return false; }); win.find('.jsxc_textinput').keyup(function(ev) { var body = $(this).val(); if (ev.which === 13) { body = ''; } jsxc.storage.updateUserItem('window', bid, 'text', body); if (ev.which === 27) { jsxc.gui.window.close(bid); } }).keypress(function(ev) { if (ev.which !== 13 || !$(this).val()) { return; } jsxc.gui.window.postMessage(bid, 'out', $(this).val()); $(this).val(''); }).focus(function() { // remove unread flag jsxc.gui.readMsg(bid); }).mouseenter(function() { $('#jsxc_windowList').data('isOver', true); }).mouseleave(function() { $('#jsxc_windowList').data('isOver', false); }); win.find('.jsxc_textarea').click(function() { win.find('.jsxc_textinput').focus(); }); win.find('.jsxc_textarea').slimScroll({ height: '234px', distance: '3px' }); win.find('.jsxc_fade').hide(); win.find('.jsxc_name').disableSelection(); win.find('.slimScrollDiv').resizable({ handles: 'w, nw, n', minHeight: 234, minWidth: 250, resize: function(event, ui) { win.width(ui.size.width); win.find('.jsxc_textarea').slimScroll({ height: ui.size.height }); win.find('.jsxc_emoticons').css('top', (ui.size.height + 6) + 'px'); } }); if ($.inArray(bid, jsxc.storage.getUserItem('windowlist')) < 0) { // add window to windowlist var wl = jsxc.storage.getUserItem('windowlist'); wl.push(bid); jsxc.storage.setUserItem('windowlist', wl); // init window element in storage jsxc.storage.setUserItem('window', bid, { minimize: true, text: '', unread: false }); } else { if (jsxc.storage.getUserItem('window', bid).unread) { jsxc.gui.unreadMsg(bid); } } $.each(jsxc.gui.emotions, function(i, val) { var ins = val[0].split(' ')[0]; var li = $('<li><div title="' + ins + '" class="jsxc_' + val[1] + '"/></li>'); li.click(function() { win.find('input').val(win.find('input').val() + ins); win.find('input').focus(); }); win.find('.jsxc_emoticons ul').append(li); }); jsxc.gui.toggleList.call(win.find('.jsxc_emoticons')); jsxc.gui.window.restoreChat(bid); jsxc.gui.update(bid); jsxc.gui.updateWindowListSB(); // create related otr object if (jsxc.master && !jsxc.otr.objects[bid]) { jsxc.otr.create(bid); } else { jsxc.otr.enable(bid); } $(document).trigger('init.window.jsxc', [ win ]); return win; }, /** * Returns the window element * * @param {String} bid * @returns {jquery} jQuery object of the window element */ get: function(id) { return $("li.jsxc_windowItem[data-bid='" + jsxc.jidToBid(id) + "']"); }, /** * Open a window, related to the bid. If the window doesn't exist, it will * be created. * * @param {String} bid * @returns {jQuery} Window object */ open: function(bid) { var win = jsxc.gui.window.init(bid); jsxc.gui.window.show(bid); jsxc.gui.window.highlight(bid); var padding = $("#jsxc_windowListSB").width(); var innerWidth = $('#jsxc_windowList>ul').width(); var outerWidth = $('#jsxc_windowList').width() - padding; if (innerWidth > outerWidth) { var offset = parseInt($('#jsxc_windowList>ul').css('right')); var width = win.outerWidth(true); var right = innerWidth - win.position().left - width + offset; var left = outerWidth - (innerWidth - win.position().left) - offset; if (left < 0) { jsxc.gui.scrollWindowListBy(left * -1); } if (right < 0) { jsxc.gui.scrollWindowListBy(right); } } return win; }, /** * Close chatwindow and clean up * * @param {String} bid bar jid */ close: function(bid) { if (jsxc.gui.window.get(bid).length === 0) { jsxc.warn('Want to close a window, that is not open.'); return; } jsxc.storage.removeUserElement('windowlist', bid); jsxc.storage.removeUserItem('window', bid); if (jsxc.storage.getUserItem('buddylist').indexOf(bid) < 0) { // delete data from unknown sender jsxc.storage.removeUserItem('buddy', bid); jsxc.storage.removeUserItem('chat', bid); } jsxc.gui.window._close(bid); }, /** * Close chatwindow * * @param {String} bid */ _close: function(bid) { jsxc.gui.window.get(bid).hide('slow', function() { $(this).remove(); jsxc.gui.updateWindowListSB(); }); }, /** * Toggle between minimize and maximize of the text area * * @param {String} bid bar jid */ toggle: function(bid) { var win = jsxc.gui.window.get(bid); if (win.parents("#jsxc_windowList").length === 0) { return; } if (win.find('.jsxc_fade').is(':hidden')) { jsxc.gui.window.show(bid); } else { jsxc.gui.window.hide(bid); } jsxc.gui.updateWindowListSB(); }, /** * Maximize text area and save * * @param {String} bid */ show: function(bid) { jsxc.storage.updateUserItem('window', bid, 'minimize', false); jsxc.gui.window._show(bid); }, /** * Maximize text area * * @param {String} bid * @returns {undefined} */ _show: function(bid) { var win = jsxc.gui.window.get(bid); jsxc.gui.window.get(bid).find('.jsxc_fade').slideDown(); win.removeClass('jsxc_min'); // If the area is hidden, the scrolldown function doesn't work. So we // call it here. jsxc.gui.window.scrollDown(bid); if (jsxc.restoreCompleted) { win.find('.jsxc_textinput').focus(); } win.trigger('show.window.jsxc'); }, /** * Minimize text area and save * * @param {String} bid */ hide: function(bid) { jsxc.storage.updateUserItem('window', bid, 'minimize', true); jsxc.gui.window._hide(bid); }, /** * Minimize text area * * @param {String} bid */ _hide: function(bid) { jsxc.gui.window.get(bid).addClass('jsxc_min').find(' .jsxc_fade').slideUp(); jsxc.gui.window.get(bid).trigger('hidden.window.jsxc'); }, /** * Highlight window * * @param {type} bid */ highlight: function(bid) { var el = jsxc.gui.window.get(bid).find(' .jsxc_bar'); if (!el.is(':animated')) { el.effect('highlight', { color: 'orange' }, 2000); } }, /** * Scroll chat area to the bottom * * @param {String} bid bar jid */ scrollDown: function(bid) { var chat = jsxc.gui.window.get(bid).find('.jsxc_textarea'); // check if chat exist if (chat.length === 0) { return; } chat.slimScroll({ scrollTo: (chat.get(0).scrollHeight + 'px') }); }, /** * Write Message to chat area and save * * @param {String} bid bar jid * @param {String} direction 'in' message is received or 'out' message is * send * @param {String} msg Message to display * @param {boolean} encrypted Was this message encrypted? Default: false * @param {boolean} forwarded Was this message forwarded? Default: false * @param {integer} stamp Timestamp */ postMessage: function(bid, direction, msg, encrypted, forwarded, stamp) { var data = jsxc.storage.getUserItem('buddy', bid); var html_msg = msg; // remove html tags and reencode html tags msg = jsxc.removeHTML(msg); msg = jsxc.escapeHTML(msg); // exceptions: if (direction === 'out' && data.msgstate === OTR.CONST.MSGSTATE_FINISHED && forwarded !== true) { direction = 'sys'; msg = jsxc.l.your_message_wasnt_send_please_end_your_private_conversation; } if (direction === 'in' && data.msgstate === OTR.CONST.MSGSTATE_FINISHED) { direction = 'sys'; msg = jsxc.l.unencrypted_message_received + ' ' + msg; } if (direction === 'out' && data.sub === 'from') { direction = 'sys'; msg = jsxc.l.your_message_wasnt_send_because_you_have_no_valid_subscription; } encrypted = encrypted || data.msgstate === OTR.CONST.MSGSTATE_ENCRYPTED; var post = jsxc.storage.saveMessage(bid, direction, msg, encrypted, forwarded, stamp); if (direction === 'in') { $(document).trigger('postmessagein.jsxc', [ bid, html_msg ]); } if (direction === 'out' && jsxc.master && forwarded !== true) { jsxc.xmpp.sendMessage(bid, html_msg, post.uid); } jsxc.gui.window._postMessage(bid, post); if (direction === 'out' && msg === '?') { jsxc.gui.window.postMessage(bid, 'sys', '42'); } }, /** * Write Message to chat area * * @param {String} bid bar jid * @param {Object} post Post object with direction, msg, uid, received * @param {Bool} restore If true no highlights are used and so unread flag * set */ _postMessage: function(bid, post, restore) { var win = jsxc.gui.window.get(bid); var msg = post.msg; var direction = post.direction; var uid = post.uid; if (win.find('.jsxc_textinput').is(':not(:focus)') && jsxc.restoreCompleted && direction === 'in' && !restore) { jsxc.gui.window.highlight(bid); } msg = msg.replace(jsxc.CONST.REGEX.URL, function(url) { var href = (url.match(/^https?:\/\//i)) ? url : 'http://' + url; return '<a href="' + href + '" target="_blank">' + url + '</a>'; }); msg = msg.replace(new RegExp('(xmpp:)?(' + jsxc.CONST.REGEX.JID.source + ')(\\?[^\\s]+\\b)?', 'i'), function(match, protocol, jid, action) { if (protocol === 'xmpp:') { if (typeof action === 'string') { jid += action; } return '<a href="xmpp:' + jid + '">' + jid + '</a>'; } return '<a href="mailto:' + jid + '" target="_blank">' + jid + '</a>'; }); $.each(jsxc.gui.emotions, function(i, val) { msg = msg.replace(val[2], function(match, p1) { // escape value for alt and title, this prevents double // replacement var esc = '', i; for (i = 0; i < p1.length; i++) { esc += '&#' + p1.charCodeAt(i) + ';'; } return '<div title="' + esc + '" class="jsxc_emoticon jsxc_' + val[1] + '"/>'; }); }); var msgDiv = $("<div>"), msgTsDiv = $("<div>"); msgDiv.addClass('jsxc_chatmessage jsxc_' + direction); msgDiv.attr('id', uid); msgDiv.html('<div>' + msg + '</div>'); msgTsDiv.addClass('jsxc_timestamp'); msgTsDiv.html(jsxc.getFormattedTime(post.stamp)); if (post.received || false) { msgDiv.addClass('jsxc_received'); } if (post.forwarded) { msgDiv.addClass('jsxc_forwarded'); } if (post.encrypted) { msgDiv.addClass('jsxc_encrypted'); } if (direction === 'sys') { jsxc.gui.window.get(bid).find('.jsxc_textarea').append('<div style="clear:both"/>'); } else if (typeof post.stamp !== 'undefined') { msgDiv.append(msgTsDiv); } win.find('.jsxc_textarea').append(msgDiv); jsxc.gui.detectUriScheme(win); jsxc.gui.detectEmail(win); jsxc.gui.window.scrollDown(bid); // if window has no focus set unread flag if (!win.find('.jsxc_textinput').is(':focus') && jsxc.restoreCompleted && !restore) { jsxc.gui.unreadMsg(bid); } }, /** * Set text into input area * * @param {type} bid * @param {type} text * @returns {undefined} */ setText: function(bid, text) { jsxc.gui.window.get(bid).find('.jsxc_textinput').val(text); }, /** * Load old log into chat area * * @param {type} bid * @returns {undefined} */ restoreChat: function(bid) { var chat = jsxc.storage.getUserItem('chat', bid); while (chat !== null && chat.length > 0) { var c = chat.pop(); jsxc.gui.window._postMessage(bid, c, true); } }, /** * Clear chat history * * @param {type} bid * @returns {undefined} */ clear: function(bid) { jsxc.storage.setUserItem('chat', bid, []); jsxc.gui.window.get(bid).find('.jsxc_textarea').empty(); } }; /** * Hold all HTML templates. * * @namespace jsxc.gui.template */ jsxc.gui.template = { /** * Return requested template and replace all placeholder * * @memberOf jsxc.gui.template; * @param {type} name template name * @param {type} bid * @param {type} msg * @returns {String} HTML Template */ get: function(name, bid, msg) { // common placeholder var ph = { my_priv_fingerprint: jsxc.storage.getUserItem('priv_fingerprint') ? jsxc.storage.getUserItem('priv_fingerprint').replace(/(.{8})/g, '$1 ') : jsxc.l.not_available, my_jid: jsxc.storage.getItem('jid') || '', my_node: Strophe.getNodeFromJid(jsxc.storage.getItem('jid') || '') || '', root: jsxc.options.root, app_name: jsxc.options.app_name }; // placeholder depending on bid if (bid) { var data = jsxc.storage.getUserItem('buddy', bid); $.extend(ph, { bid_priv_fingerprint: (data && data.fingerprint) ? data.fingerprint.replace(/(.{8})/g, '$1 ') : jsxc.l.not_available, bid_jid: bid, bid_name: (data && data.name) ? data.name : bid }); } // placeholder depending on msg if (msg) { $.extend(ph, { msg: msg }); } var ret = jsxc.gui.template[name]; if (typeof (ret) === 'string') { ret = jsxc.translate(ret); ret = ret.replace(/\{\{([a-zA-Z0-9_\-]+)\}\}/g, function(s, key) { return (typeof ph[key] === 'string') ? ph[key] : s; }); return ret; } jsxc.debug('Template not available: ' + name); return name; }, authenticationDialog: '<h3>Verification</h3>\ <p>%%Authenticating_a_buddy_helps_%%</p>\ <div>\ <p style="margin:0px;">%%How_do_you_want_to_authenticate_your_buddy%%</p>\ <select size="1">\ <option>%%Select_method%%</option>\ <option>%%Manual%%</option>\ <option>%%Question%%</option>\ <option>%%Secret%%</option>\ </select>\ </div>\ <div style="display:none">\ <p class=".jsxc_explanation">%%To_verify_the_fingerprint_%%</p>\ <p><strong>%%Your_fingerprint%%</strong><br />\ <span style="text-transform:uppercase">{{my_priv_fingerprint}}</span></p>\ <p><strong>%%Buddy_fingerprint%%</strong><br />\ <span style="text-transform:uppercase">{{bid_priv_fingerprint}}</span></p><br />\ <p class="jsxc_right"><a href="#" class="jsxc_close button">%%Close%%</a> <a href="#" class="button creation">%%Compared%%</a></p>\ </div>\ <div style="display:none">\ <p class=".jsxc_explanation">%%To_authenticate_using_a_question_%%</p>\ <p><label for="jsxc_quest">%%Question%%:</label><input type="text" name="quest" id="jsxc_quest" /></p>\ <p><label for="jsxc_secret2">%%Secret%%:</label><input type="text" name="secret2" id="jsxc_secret2" /></p>\ <p class="jsxc_right"><a href="#" class="button jsxc_close">%%Close%%</a> <a href="#" class="button creation">%%Ask%%</a></p>\ </div>\ <div style="display:none">\ <p class=".jsxc_explanation">%%To_authenticate_pick_a_secret_%%</p>\ <p><label for="jsxc_secret">%%Secret%%:</label><input type="text" name="secret" id="jsxc_secret" /></p>\ <p class="jsxc_right"><a href="#" class="button jsxc_close">%%Close%%</a> <a href="#" class="button creation">%%Compare%%</a></p>\ </div>', fingerprintsDialog: '<div>\ <p class="jsxc_maxWidth">%%A_fingerprint_%%</p>\ <p><strong>%%Your_fingerprint%%</strong><br />\ <span style="text-transform:uppercase">{{my_priv_fingerprint}}</span></p>\ <p><strong>%%Buddy_fingerprint%%</strong><br />\ <span style="text-transform:uppercase">{{bid_priv_fingerprint}}</span></p><br />\ <p class="jsxc_right"><a href="#" class="button jsxc_close">%%Close%%</a></p>\ </div>', chatWindow: '<li class="jsxc_min jsxc_windowItem">\ <div class="jsxc_window">\ <div class="jsxc_bar">\ <div class="jsxc_avatar">☺</div>\ <div class="jsxc_tools">\ <div class="jsxc_settings">\ <ul>\ <li class="jsxc_fingerprints jsxc_otr jsxc_disabled">%%Fingerprints%%</li>\ <li class="jsxc_verification">%%Authentication%%</li>\ <li class="jsxc_transfer jsxc_otr jsxc_disabled">%%start_private%%</li>\ <li class="jsxc_clear">%%clear_history%%</li>\ </ul>\ </div>\ <div class="jsxc_transfer jsxc_otr jsxc_disabled"/>\ <div class="jsxc_close">×</div>\ </div>\ <div class="jsxc_name"/>\ <div class="jsxc_cycle"/>\ </div>\ <div class="jsxc_fade">\ <div class="jsxc_gradient"/>\ <div class="jsxc_textarea"/>\ <div class="jsxc_emoticons"><ul/></div>\ <input type="text" class="jsxc_textinput" placeholder="...%%Message%%" />\ </div>\ </div>\ </li>', roster: '<div id="jsxc_roster">\ <ul id="jsxc_buddylist"></ul>\ <div class="jsxc_bottom jsxc_presence" data-bid="own">\ <div id="jsxc_avatar">\ <div class="jsxc_avatar">☺</div>\ </div>\ <div id="jsxc_menu">\ <span></span>\ <ul>\ <li class="jsxc_settings">%%Settings%%</li>\ <li class="jsxc_muteNotification">%%Mute%%</li>\ <li class="jsxc_addBuddy">%%Add_buddy%%</li>\ <li class="jsxc_hideOffline">%%Hide offline%%</li>\ <li class="jsxc_onlineHelp">%%Online help%%</li>\ <li class="jsxc_about">%%About%%</li>\ </ul>\ </div>\ <div id="jsxc_notice">\ <span></span>\ <ul></ul>\ </div>\ <div id="jsxc_presence">\ <span>%%Online%%</span>\ <ul>\ <li data-pres="online" class="jsxc_online">%%Online%%</li>\ <li data-pres="chat" class="jsxc_chat">%%Chatty%%</li>\ <li data-pres="away" class="jsxc_away">%%Away%%</li>\ <li data-pres="xa" class="jsxc_xa">%%Extended away%%</li>\ <li data-pres="dnd" class="jsxc_dnd">%%dnd%%</li>\ <!-- <li data-pres="offline" class="jsxc_offline">%%Offline%%</li> -->\ </ul>\ </div>\ </div>\ <div id="jsxc_toggleRoster"></div>\ </div>', windowList: '<div id="jsxc_windowList">\ <ul></ul>\ </div>\ <div id="jsxc_windowListSB">\ <div class="jsxc_scrollLeft jsxc_disabled">&lt;</div>\ <div class="jsxc_scrollRight jsxc_disabled">&gt;</div>\ </div>', rosterBuddy: '<li>\ <div class="jsxc_avatar">☺</div>\ <div class="jsxc_control"></div>\ <div class="jsxc_name"/>\ <div class="jsxc_options jsxc_right">\ <div class="jsxc_rename" title="%%rename_buddy%%">✎</div>\ <div class="jsxc_delete" title="%%delete_buddy%%">✘</div>\ </div>\ <div class="jsxc_options jsxc_left">\ <div class="jsxc_chaticon" title="%%send_message%%"/>\ <div class="jsxc_vcardicon" title="%%get_info%%">i</div>\ </div>\ </li>', loginBox: '<h3>%%Login%%</h3>\ <form>\ <p><label for="jsxc_username">%%Username%%:</label>\ <input type="text" name="username" id="jsxc_username" required="required" value="{{my_node}}"/></p>\ <p><label for="jsxc_password">%%Password%%:</label>\ <input type="password" name="password" required="required" id="jsxc_password" /></p>\ <div class="bottom_submit_section">\ <input type="reset" class="button jsxc_close" name="clear" value="%%Cancel%%"/>\ <input type="submit" class="button creation" name="commit" value="%%Connect%%"/>\ </div>\ </form>', contactDialog: '<h3>%%Add_buddy%%</h3>\ <p class=".jsxc_explanation">%%Type_in_the_full_username_%%</p>\ <form>\ <p><label for="jsxc_username">* %%Username%%:</label>\ <input type="text" name="username" id="jsxc_username" pattern="^[^\\x22&\'\\/:<>@\\s]+(@[.\\-_\\w]+)?" required="required" /></p>\ <p><label for="jsxc_alias">%%Alias%%:</label>\ <input type="text" name="alias" id="jsxc_alias" /></p>\ <p class="jsxc_right">\ <input class="button" type="submit" value="%%Add%%" />\ </p>\ <form>', approveDialog: '<h3>%%Subscription_request%%</h3>\ <p>%%You_have_a_request_from%% <b class="jsxc_their_jid"></b>.</p>\ <p class="jsxc_right"><a href="#" class="button jsxc_deny">%%Deny%%</a> <a href="#" class="button creation jsxc_approve">%%Approve%%</a></p>', removeDialog: '<h3>%%Remove buddy%%</h3>\ <p class="jsxc_maxWidth">%%You_are_about_to_remove_%%</p>\ <p class="jsxc_right"><a href="#" class="button jsxc_cancel jsxc_close">%%Cancel%%</a> <a href="#" class="button creation">%%Remove%%</a></p>', waitAlert: '<h3>{{msg}}</h3>\ <p>%%Please_wait%%</p>\ <p class="jsxc_center"><img src="{{root}}/img/loading.gif" alt="wait" width="32px" height="32px" /></p>', alert: '<h3>%%Alert%%</h3>\ <p>{{msg}}</p>\ <p class="jsxc_right"><a href="#" class="button jsxc_close jsxc_cancel">%%Ok%%</a></p>', authFailDialog: '<h3>%%Login_failed%%</h3>\ <p>%%Sorry_we_cant_authentikate_%%</p>\ <p class="jsxc_right">\ <a class="button jsxc_cancel">%%Continue_without_chat%%</a>\ <a class="button creation">%%Retry%%</a>\ </p>', confirmDialog: '<p>{{msg}}</p>\ <p class="jsxc_right">\ <a class="button jsxc_cancel jsxc_close">%%Dismiss%%</a>\ <a class="button creation">%%Confirm%%</a>\ </p>', pleaseAccept: '<p>%%Please_accept_%%</p>', aboutDialog: '<h3>JavaScript XMPP Chat</h3>\ <p><b>Version: </b>' + jsxc.version + '<br />\ <a href="http://jsxc.org/" target="_blank">www.jsxc.org</a><br />\ <br />\ <i>Released under the MIT license</i><br />\ <br />\ Real-time chat app for {{app_name}} and more.<br />\ Requires an external <a href="https://xmpp.org/xmpp-software/servers/" target="_blank">XMPP server</a>.<br />\ <br />\ <b>Credits: </b> <a href="http://www.beepzoid.com/old-phones/" target="_blank">David English (Ringtone)</a>,\ <a href="https://soundcloud.com/freefilmandgamemusic/ping-1?in=freefilmandgamemusic/sets/free-notification-sounds-and" target="_blank">CameronMusic (Ping)</a></p>\ <p class="jsxc_right"><a class="button jsxc_debuglog" href="#">Show debug log</a></p>', vCard: '<h3>%%Info_about%% {{bid_name}}</h3>\ <ul class="jsxc_vCard"></ul>\ <p><img src="{{root}}/img/loading.gif" alt="wait" width="32px" height="32px" /> %%Please_wait%%...</p>', settings: '<h3>%%User_settings%%</h3>\ <p></p>\ <form>\ <fieldset class="jsxc_fieldsetXmpp jsxc_fieldset">\ <legend>%%Login options%%</legend>\ <label for="xmpp-url">%%BOSH url%%</label><input type="text" id="xmpp-url" readonly="readonly"/><br />\ <label for="xmpp-username">%%Username%%</label><input type="text" id="xmpp-username"/><br />\ <label for="xmpp-domain">%%Domain%%</label><input type="text" id="xmpp-domain"/><br />\ <label for="xmpp-resource">%%Resource%%</label><input type="text" id="xmpp-resource"/><br />\ <label for="xmpp-onlogin">%%On login%%</label><input type="checkbox" id="xmpp-onlogin" /><br />\ <input type="submit" value="%%Save%%"/>\ </fieldset>\ </form>\ <p></p>\ <form>\ <fieldset class="jsxc_fieldsetPriority jsxc_fieldset">\ <legend>%%Priority%%</legend>\ <label for="priority-online">%%Online%%</label><input type="number" value="0" id="priority-online" min="-128" max="127" step="1" required="required"/><br />\ <label for="priority-chat">%%Chatty%%</label><input type="number" value="0" id="priority-chat" min="-128" max="127" step="1" required="required"/><br />\ <label for="priority-away">%%Away%%</label><input type="number" value="0" id="priority-away" min="-128" max="127" step="1" required="required"/><br />\ <label for="priority-xa">%%Extended_away%%</label><input type="number" value="0" id="priority-xa" min="-128" max="127" step="1" required="required"/><br />\ <label for="priority-dnd">%%dnd%%</label><input type="number" value="0" id="priority-dnd" min="-128" max="127" step="1" required="required"/><br />\ <input type="submit" value="%%Save%%"/>\ </fieldset>\ </form>\ <p></p>\ <form data-onsubmit="xmpp.carbons.refresh">\ <fieldset class="jsxc_fieldsetCarbons jsxc_fieldset">\ <legend>%%Carbon copy%%</legend>\ <label for="carbons-enable">%%Enable%%</label><input type="checkbox" id="carbons-enable" /><br />\ <input type="submit" value="%%Save%%"/>\ </fieldset>\ </form>' }; /** * Handle XMPP stuff. * * @namespace jsxc.xmpp */ jsxc.xmpp = { conn: null, // connection /** * Create new connection or attach to old * * @name login * @memberOf jsxc.xmpp */ /** * Create new connection with given parameters. * * @name login^2 * @param {string} jid * @param {string} password * @memberOf jsxc.xmpp */ /** * Attach connection with given parameters. * * @name login^3 * @param {string} jid * @param {string} sid * @param {string} rid * @memberOf jsxc.xmpp */ login: function() { if (jsxc.xmpp.conn && jsxc.xmpp.conn.connected) { return; } var jid = null, password = null, sid = null, rid = null; switch (arguments.length) { case 2: jid = arguments[0]; password = arguments[1]; break; case 3: jid = arguments[0]; sid = arguments[1]; rid = arguments[2]; break; default: jid = jsxc.storage.getItem('jid'); sid = jsxc.storage.getItem('sid'); rid = jsxc.storage.getItem('rid'); } var url = jsxc.options.get('xmpp').url; // Register eventlistener $(document).on('connected.jsxc', jsxc.xmpp.connected); $(document).on('attached.jsxc', jsxc.xmpp.attached); $(document).on('disconnected.jsxc', jsxc.xmpp.disconnected); $(document).on('ridChange', jsxc.xmpp.onRidChange); $(document).on('connfail.jsxc', jsxc.xmpp.onConnfail); $(document).on('authfail.jsxc', jsxc.xmpp.onAuthFail); Strophe.addNamespace('RECEIPTS', 'urn:xmpp:receipts'); // Create new connection (no login) jsxc.xmpp.conn = new Strophe.Connection(url); // Override default function to preserve unique id var stropheGetUniqueId = jsxc.xmpp.conn.getUniqueId; jsxc.xmpp.conn.getUniqueId = function(suffix) { var uid = stropheGetUniqueId.call(jsxc.xmpp.conn, suffix); jsxc.storage.setItem('_uniqueId', jsxc.xmpp.conn._uniqueId); return uid; }; if (jsxc.storage.getItem('debug') === true) { jsxc.xmpp.conn.xmlInput = function(data) { console.log('<', data); }; jsxc.xmpp.conn.xmlOutput = function(data) { console.log('>', data); }; } var callback = function(status, condition) { jsxc.debug(Object.getOwnPropertyNames(Strophe.Status)[status] + ': ' + condition); switch (status) { case Strophe.Status.CONNECTED: jsxc.bid = jsxc.jidToBid(jsxc.xmpp.conn.jid.toLowerCase()); $(document).trigger('connected.jsxc'); break; case Strophe.Status.ATTACHED: $(document).trigger('attached.jsxc'); break; case Strophe.Status.DISCONNECTED: $(document).trigger('disconnected.jsxc'); break; case Strophe.Status.CONNFAIL: $(document).trigger('connfail.jsxc'); break; case Strophe.Status.AUTHFAIL: $(document).trigger('authfail.jsxc'); break; } }; if (jsxc.xmpp.conn.caps) { jsxc.xmpp.conn.caps.node = 'http://jsxc.org/'; } if (jsxc.restore && sid && rid) { jsxc.debug('Try to attach'); jsxc.debug('SID: ' + sid); jsxc.xmpp.conn.attach(jid, sid, rid, callback); } else { jsxc.debug('New connection'); if (jsxc.xmpp.conn.caps) { // Add system handler, because user handler isn't called before // we are authenticated jsxc.xmpp.conn._addSysHandler(function(stanza) { var from = jsxc.xmpp.conn.domain, c = stanza.querySelector('c'), ver = c.getAttribute('ver'), node = c.getAttribute('node'); var _jidNodeIndex = JSON.parse(localStorage.getItem('strophe.caps._jidNodeIndex')) || {}; jsxc.xmpp.conn.caps._jidVerIndex[from] = ver; _jidNodeIndex[from] = node; localStorage.setItem('strophe.caps._jidVerIndex', JSON.stringify(jsxc.xmpp.conn.caps._jidVerIndex)); localStorage.setItem('strophe.caps._jidNodeIndex', JSON.stringify(_jidNodeIndex)); }, Strophe.NS.CAPS); } jsxc.xmpp.conn.connect(jid || jsxc.options.xmpp.jid, password || jsxc.options.xmpp.password, callback); } }, /** * Logs user out of his xmpp session and does some clean up. * * @returns {Boolean} */ logout: function() { // instruct all tabs jsxc.storage.removeItem('sid'); // clean up jsxc.storage.removeUserItem('buddylist'); jsxc.storage.removeUserItem('windowlist'); jsxc.storage.removeItem('_uniqueId'); if (!jsxc.master) { $('#jsxc_roster').remove(); $('#jsxc_windowlist').remove(); return true; } if (jsxc.xmpp.conn === null) { return true; } // Hide dropdown menu $('body').click(); jsxc.triggeredFromElement = true; // restore all otr objects $.each(jsxc.storage.getUserItem('otrlist') || {}, function(i, val) { jsxc.otr.create(val); }); var numOtr = Object.keys(jsxc.otr.objects || {}).length + 1; var disReady = function() { if (--numOtr <= 0) { jsxc.xmpp.conn.flush(); setTimeout(function() { jsxc.xmpp.conn.disconnect(); }, 600); } }; // end all private conversations $.each(jsxc.otr.objects || {}, function(key, obj) { if (obj.msgstate === OTR.CONST.MSGSTATE_ENCRYPTED) { obj.endOtr.call(obj, function() { obj.init.call(obj); jsxc.otr.backup(key); disReady(); }); } else { disReady(); } }); disReady(); // Trigger real logout in jsxc.xmpp.disconnected() return false; }, /** * Triggered if connection is established * * @private */ connected: function() { jsxc.xmpp.conn.pause(); var nomJid = Strophe.getBareJidFromJid(jsxc.xmpp.conn.jid).toLowerCase() + '/' + Strophe.getResourceFromJid(jsxc.xmpp.conn.jid); // Save sid and jid jsxc.storage.setItem('sid', jsxc.xmpp.conn._proto.sid); jsxc.storage.setItem('jid', nomJid); jsxc.storage.setItem('lastActivity', (new Date()).getTime()); // make shure roster will be reloaded jsxc.storage.removeUserItem('buddylist'); jsxc.storage.removeUserItem('windowlist'); jsxc.storage.removeUserItem('own'); jsxc.storage.removeUserItem('avatar', 'own'); jsxc.storage.removeUserItem('otrlist'); if (jsxc.options.loginForm.triggered) { switch (jsxc.options.loginForm.onConnected || 'submit') { case 'submit': jsxc.submitLoginForm(); /* falls through */ case false: jsxc.xmpp.connectionReady(); return; } } // start chat jsxc.gui.init(); $('#jsxc_roster').removeClass('jsxc_noConnection'); jsxc.onMaster(); jsxc.xmpp.conn.resume(); jsxc.gui.dialog.close(); $(document).trigger('attached.jsxc'); }, /** * Triggered if connection is attached * * @private */ attached: function() { jsxc.xmpp.conn.addHandler(jsxc.xmpp.onRosterChanged, 'jabber:iq:roster', 'iq', 'set'); jsxc.xmpp.conn.addHandler(jsxc.xmpp.onMessage, null, 'message', 'chat'); jsxc.xmpp.conn.addHandler(jsxc.xmpp.onReceived, null, 'message'); jsxc.xmpp.conn.addHandler(jsxc.xmpp.onPresence, null, 'presence'); var caps = jsxc.xmpp.conn.caps; var domain = jsxc.xmpp.conn.domain; if (caps && jsxc.options.get('carbons').enable) { var conditionalEnable = function() { if (jsxc.xmpp.conn.caps.hasFeatureByJid(domain, jsxc.CONST.NS.CARBONS)) { jsxc.xmpp.carbons.enable(); } }; if (typeof caps._knownCapabilities[caps._jidVerIndex[domain]] === 'undefined') { var _jidNodeIndex = JSON.parse(localStorage.getItem('strophe.caps._jidNodeIndex')) || {}; $(document).on('caps.strophe', function onCaps(ev, from) { if (from !== domain) { return; } conditionalEnable(); $(document).off('caps.strophe', onCaps); }); caps._requestCapabilities(jsxc.xmpp.conn.domain, _jidNodeIndex[domain], caps._jidVerIndex[domain]); } else { // We know server caps conditionalEnable(); } } // Only load roaster if necessary if (!jsxc.restore || !jsxc.storage.getUserItem('buddylist')) { // in order to not overide existing presence information, we send // pres first after roster is ready $(document).one('cloaded.roster.jsxc', jsxc.xmpp.sendPres); $('#jsxc_roster > p:first').remove(); var iq = $iq({ type: 'get' }).c('query', { xmlns: 'jabber:iq:roster' }); jsxc.xmpp.conn.sendIQ(iq, jsxc.xmpp.onRoster); } else { jsxc.xmpp.sendPres(); } jsxc.xmpp.connectionReady(); }, /** * Triggered if the connection is ready */ connectionReady: function() { // Load saved unique id jsxc.xmpp.conn._uniqueId = jsxc.storage.getItem('_uniqueId') || new Date().getTime(); $(document).trigger('connectionReady.jsxc'); }, /** * Sends presence stanza to server. */ sendPres: function() { // disco stuff if (jsxc.xmpp.conn.disco) { jsxc.xmpp.conn.disco.addIdentity('client', 'web', 'JSXC'); jsxc.xmpp.conn.disco.addFeature(Strophe.NS.DISCO_INFO); jsxc.xmpp.conn.disco.addFeature(Strophe.NS.RECEIPTS); } // create presence stanza var pres = $pres(); if (jsxc.xmpp.conn.caps) { // attach caps pres.c('c', jsxc.xmpp.conn.caps.generateCapsAttrs()).up(); } var presState = jsxc.storage.getUserItem('presence') || 'online'; if (presState !== 'online') { pres.c('show').t(presState).up(); } var priority = jsxc.options.get('priority'); if (priority && typeof priority[presState] !== 'undefined' && parseInt(priority[presState]) !== 0) { pres.c('priority').t(priority[presState]).up(); } jsxc.debug('Send presence', pres.toString()); jsxc.xmpp.conn.send(pres); }, /** * Triggered if lost connection * * @private */ disconnected: function() { jsxc.debug('disconnected'); jsxc.storage.removeItem('sid'); jsxc.storage.removeItem('rid'); jsxc.storage.removeItem('lastActivity'); jsxc.storage.removeItem('hidden'); jsxc.storage.removeUserItem('avatar', 'own'); jsxc.storage.removeUserItem('otrlist'); $(document).off('connected.jsxc', jsxc.xmpp.connected); $(document).off('attached.jsxc', jsxc.xmpp.attached); $(document).off('disconnected.jsxc', jsxc.xmpp.disconnected); $(document).off('ridChange', jsxc.xmpp.onRidChange); $(document).off('connfail.jsxc', jsxc.xmpp.onConnfail); $(document).off('authfail.jsxc', jsxc.xmpp.onAuthFail); jsxc.xmpp.conn = null; $('#jsxc_windowList').remove(); if (jsxc.triggeredFromElement) { $('#jsxc_roster').remove(); if (jsxc.triggeredFromLogout) { window.location = jsxc.options.logoutElement.attr('href'); } } else { jsxc.gui.roster.noConnection(); } window.clearInterval(jsxc.keepalive); }, /** * Triggered on connection fault * * @param {String} condition information why we lost the connection * @private */ onConnfail: function(ev, condition) { jsxc.debug('XMPP connection failed: ' + condition); if (jsxc.options.loginForm.triggered) { jsxc.submitLoginForm(); } }, /** * Triggered on auth fail. * * @private */ onAuthFail: function() { if (jsxc.options.loginForm.triggered) { switch (jsxc.options.loginForm.onAuthFail || 'ask') { case 'ask': jsxc.gui.showAuthFail(); break; case 'submit': jsxc.submitLoginForm(); break; } } }, /** * Triggered on initial roster load * * @param {dom} iq * @private */ onRoster: function(iq) { /* * <iq from='' type='get' id=''> <query xmlns='jabber:iq:roster'> <item * jid='' name='' subscription='' /> ... </query> </iq> */ jsxc.debug('Load roster', iq); var buddies = []; $(iq).find('item').each(function() { var jid = $(this).attr('jid'); var name = $(this).attr('name') || jid; var bid = jsxc.jidToBid(jid); var sub = $(this).attr('subscription'); buddies.push(bid); jsxc.storage.removeUserItem('res', bid); jsxc.storage.saveBuddy(bid, { jid: jid, name: name, status: 0, sub: sub, res: [] }); jsxc.gui.roster.add(bid); }); if (buddies.length === 0) { jsxc.gui.roster.empty(); } jsxc.storage.setUserItem('buddylist', buddies); jsxc.debug('Roster loaded'); $(document).trigger('cloaded.roster.jsxc'); }, /** * Triggerd on roster changes * * @param {dom} iq * @returns {Boolean} True to preserve handler * @private */ onRosterChanged: function(iq) { /* * <iq from='' type='set' id=''> <query xmlns='jabber:iq:roster'> <item * jid='' name='' subscription='' /> </query> </iq> */ jsxc.debug('onRosterChanged', iq); $(iq).find('item').each(function() { var jid = $(this).attr('jid'); var name = $(this).attr('name') || jid; var bid = jsxc.jidToBid(jid); var sub = $(this).attr('subscription'); // var ask = $(this).attr('ask'); if (sub === 'remove') { jsxc.gui.roster.purge(bid); } else { var bl = jsxc.storage.getUserItem('buddylist'); if (bl.indexOf(bid) < 0) { bl.push(bid); // (INFO) push returns the new length jsxc.storage.setUserItem('buddylist', bl); } var temp = jsxc.storage.saveBuddy(bid, { jid: jid, name: name, sub: sub }); if (temp === 'updated') { jsxc.gui.update(bid); jsxc.gui.roster.reorder(bid); } else { jsxc.gui.roster.add(bid); } } // Remove pending friendship request from notice list if (sub === 'from' || sub === 'both') { var notices = jsxc.storage.getUserItem('notices'); var noticeKey = null, notice; for (noticeKey in notices) { notice = notices[noticeKey]; if (notice.fnName === 'gui.showApproveDialog' && notice.fnParams[0] === jid) { jsxc.debug('Remove notice with key ' + noticeKey); jsxc.notice.remove(noticeKey); } } } }); if (!jsxc.storage.getUserItem('buddylist') || jsxc.storage.getUserItem('buddylist').length === 0) { jsxc.gui.roster.empty(); } else { $('#jsxc_roster > p:first').remove(); } // preserve handler return true; }, /** * Triggered on incoming presence stanzas * * @param {dom} presence * @private */ onPresence: function(presence) { /* * <presence xmlns='jabber:client' type='unavailable' from='' to=''/> * * <presence xmlns='jabber:client' from='' to=''> <priority>5</priority> * <c xmlns='http://jabber.org/protocol/caps' * node='http://psi-im.org/caps' ver='caps-b75d8d2b25' ext='ca cs * ep-notify-2 html'/> </presence> * * <presence xmlns='jabber:client' from='' to=''> <show>chat</show> * <status></status> <priority>5</priority> <c * xmlns='http://jabber.org/protocol/caps' * node='http://psi-im.org/caps' ver='caps-b75d8d2b25' ext='ca cs * ep-notify-2 html'/> </presence> */ jsxc.debug('onPresence', presence); var ptype = $(presence).attr('type'); var from = $(presence).attr('from'); var jid = Strophe.getBareJidFromJid(from).toLowerCase(); var r = Strophe.getResourceFromJid(from); var bid = jsxc.jidToBid(jid); var data = jsxc.storage.getUserItem('buddy', bid); var res = jsxc.storage.getUserItem('res', bid) || {}; var status = null; var xVCard = $(presence).find('x[xmlns="vcard-temp:x:update"]'); if (jid === Strophe.getBareJidFromJid(jsxc.storage.getItem("jid"))) { return true; } if (ptype === 'error') { jsxc.error('[XMPP] ' + $(presence).attr('code')); return true; } // incoming friendship request if (ptype === 'subscribe') { jsxc.storage.setUserItem('friendReq', { jid: jid, approve: -1 }); jsxc.notice.add('%%Friendship request%%', '%%from%% ' + jid, 'gui.showApproveDialog', [ jid ]); return true; } else if (ptype === 'unavailable' || ptype === 'unsubscribed') { status = jsxc.CONST.STATUS.indexOf('offline'); } else { var show = $(presence).find('show').text(); if (show === '') { status = jsxc.CONST.STATUS.indexOf('online'); } else { status = jsxc.CONST.STATUS.indexOf(show); } } if (status === 0) { delete res[r]; } else { res[r] = status; } var maxVal = []; var max = 0, prop = null; for (prop in res) { if (res.hasOwnProperty(prop)) { if (max <= res[prop]) { if (max !== res[prop]) { maxVal = []; max = res[prop]; } maxVal.push(prop); } } } if (data.status === 0 && max > 0) { // buddy has come online jsxc.notification.notify(data.name, jsxc.translate('%%has come online%%.')); } data.status = max; data.res = maxVal; data.jid = jid; // Looking for avatar if (xVCard.length > 0) { var photo = xVCard.find('photo'); if (photo.length > 0 && photo.text() !== data.avatar) { jsxc.storage.removeUserItem('avatar', data.avatar); data.avatar = photo.text(); } } // Reset jid if (jsxc.gui.window.get(bid).length > 0) { jsxc.gui.window.get(bid).data('jid', jid); } jsxc.storage.setUserItem('buddy', bid, data); jsxc.storage.setUserItem('res', bid, res); jsxc.debug('Presence (' + from + '): ' + status); jsxc.gui.update(bid); jsxc.gui.roster.reorder(bid); $(document).trigger('presence.jsxc', [ from, status, presence ]); // preserve handler return true; }, /** * Triggered on incoming message stanzas * * @param {dom} presence * @returns {Boolean} * @private */ onMessage: function(stanza) { var forwarded = $(stanza).find('forwarded[xmlns="' + jsxc.CONST.NS.FORWARD + '"]'); var message, carbon; if (forwarded.length > 0) { message = forwarded.find('> message'); forwarded = true; carbon = $(stanza).find('> [xmlns="' + jsxc.CONST.NS.CARBONS + '"]'); if (carbon.length === 0) { carbon = false; } jsxc.debug('Incoming forwarded message', message); } else { message = stanza; forwarded = false; carbon = false; jsxc.debug('Incoming message', message); } var body = $(message).find('body:first').text(); if (!body || (body.match(/\?OTR/i) && forwarded)) { return true; } var type = $(message).attr('type'); var from = $(message).attr('from'); var mid = $(message).attr('id'); var bid; var delay = $(message).find('delay[xmlns="urn:xmpp:delay"]'); var stamp = (delay.length > 0) ? new Date(delay.attr('stamp')) : new Date(); stamp = stamp.getTime(); if (carbon) { var direction = (carbon.prop("tagName") === 'sent') ? 'out' : 'in'; bid = jsxc.jidToBid((direction === 'out') ? $(message).attr('to') : from); jsxc.gui.window.postMessage(bid, direction, body, false, forwarded, stamp); return true; } else if (forwarded) { // Someone forwarded a message to us body = from + jsxc.translate(' %%to%% ') + $(stanza).attr('to') + '"' + body + '"'; from = $(stanza).attr('from'); } var jid = Strophe.getBareJidFromJid(from); bid = jsxc.jidToBid(jid); var data = jsxc.storage.getUserItem('buddy', bid); var request = $(message).find("request[xmlns='urn:xmpp:receipts']"); if (data === null) { // jid not in roster var chat = jsxc.storage.getUserItem('chat', bid) || []; if (chat.length === 0) { jsxc.notice.add('%%Unknown sender%%', '%%You received a message from an unknown sender%% (' + bid + ').', 'gui.showUnknownSender', [ bid ]); } var msg = jsxc.removeHTML(body); msg = jsxc.escapeHTML(msg); jsxc.storage.saveMessage(bid, 'in', msg, false, forwarded, stamp); return true; } var win = jsxc.gui.window.init(bid); // If we now the full jid, we use it if (type === 'chat') { win.data('jid', from); jsxc.storage.updateUserItem('buddy', bid, { jid: from }); } $(document).trigger('message.jsxc', [ from, body ]); // create related otr object if (jsxc.master && !jsxc.otr.objects[bid]) { jsxc.otr.create(bid); } if (!forwarded && mid !== null && request.length && data !== null && (data.sub === 'both' || data.sub === 'from') && type === 'chat') { // Send received according to XEP-0184 jsxc.xmpp.conn.send($msg({ to: from }).c('received', { xmlns: 'urn:xmpp:receipts', id: mid })); } if (jsxc.otr.objects.hasOwnProperty(bid)) { jsxc.otr.objects[bid].receiveMsg(body, { stamp: stamp, forwarded: forwarded }); } else { jsxc.gui.window.postMessage(bid, 'in', body, false, forwarded, stamp); } // preserve handler return true; }, /** * Triggerd if the rid changed * * @param {event} ev * @param {obejct} data * @private */ onRidChange: function(ev, data) { jsxc.storage.setItem('rid', data.rid); }, /** * response to friendship request * * @param {string} from jid from original friendship req * @param {boolean} approve */ resFriendReq: function(from, approve) { if (jsxc.master) { jsxc.xmpp.conn.send($pres({ to: from, type: (approve) ? 'subscribed' : 'unsubscribed' })); jsxc.storage.removeUserItem('friendReq'); jsxc.gui.dialog.close(); } else { jsxc.storage.updateUserItem('friendReq', 'approve', approve); } }, /** * Add buddy to my friends * * @param {string} username jid * @param {string} alias */ addBuddy: function(username, alias) { var bid = jsxc.jidToBid(username); if (jsxc.master) { // add buddy to roster (trigger onRosterChanged) var iq = $iq({ type: 'set' }).c('query', { xmlns: 'jabber:iq:roster' }).c('item', { jid: username, name: alias || '' }); jsxc.xmpp.conn.sendIQ(iq); // send subscription request to buddy (trigger onRosterChanged) jsxc.xmpp.conn.send($pres({ to: username, type: 'subscribe' })); jsxc.storage.removeUserItem('add_' + bid); } else { jsxc.storage.setUserItem('add_' + bid, { username: username, alias: alias || null }); } }, /** * Remove buddy from my friends * * @param {type} jid */ removeBuddy: function(jid) { var bid = jsxc.jidToBid(jid); // Shortcut to remove buddy from roster and cancle all subscriptions var iq = $iq({ type: 'set' }).c('query', { xmlns: 'jabber:iq:roster' }).c('item', { jid: Strophe.getBareJidFromJid(jid), subscription: 'remove' }); jsxc.xmpp.conn.sendIQ(iq); jsxc.gui.roster.purge(bid); }, onReceived: function(message) { var from = $(message).attr('from'); var jid = Strophe.getBareJidFromJid(from); var bid = jsxc.jidToBid(jid); var received = $(message).find("received[xmlns='urn:xmpp:receipts']"); if (received.length) { var receivedId = received.attr('id').replace(/:/, '-'); var chat = jsxc.storage.getUserItem('chat', bid); var i; for (i = chat.length - 1; i >= 0; i--) { if (chat[i].uid === receivedId) { chat[i].received = true; $('#' + receivedId).addClass('jsxc_received'); jsxc.storage.setUserItem('chat', bid, chat); break; } } } return true; }, /** * Public function to send message. * * @memberOf jsxc.xmpp * @param bid css jid of user * @param msg message * @param uid unique id */ sendMessage: function(bid, msg, uid) { if (jsxc.otr.objects.hasOwnProperty(bid)) { jsxc.otr.objects[bid].sendMsg(msg, uid); } else { jsxc.xmpp._sendMessage(jsxc.gui.window.get(bid).data('jid'), msg, uid); } }, /** * Create message stanza and send it. * * @memberOf jsxc.xmpp * @param jid Jabber id * @param msg Message * @param uid unique id * @private */ _sendMessage: function(jid, msg, uid) { var data = jsxc.storage.getUserItem('buddy', jsxc.jidToBid(jid)) || {}; var isBar = (Strophe.getBareJidFromJid(jid) === jid); var type = data.type || 'chat'; var xmlMsg = $msg({ to: jid, type: type, id: uid }).c('body').t(msg); if (jsxc.xmpp.carbons.enabled && msg.match(/^\?OTR/)) { xmlMsg.up().c("private", { xmlns: jsxc.CONST.NS.CARBONS }); } if (type === 'chat' && (isBar || jsxc.xmpp.conn.caps.hasFeatureByJid(jid, Strophe.NS.RECEIPTS))) { // Add request according to XEP-0184 xmlMsg.up().c('request', { xmlns: 'urn:xmpp:receipts' }); } jsxc.xmpp.conn.send(xmlMsg); }, /** * This function loads a vcard. * * @memberOf jsxc.xmpp * @param bid * @param cb * @param error_cb */ loadVcard: function(bid, cb, error_cb) { if (jsxc.master) { jsxc.xmpp.conn.vcard.get(cb, bid, error_cb); } else { jsxc.storage.setUserItem('vcard', bid, 'request:' + (new Date()).getTime()); $(document).one('loaded.vcard.jsxc', function(ev, result) { if (result && result.state === 'success') { cb($(result.data).get(0)); } else { error_cb(); } }); } }, /** * Retrieves capabilities. * * @memberOf jsxc.xmpp * @param jid * @returns List of known capabilities */ getCapabilitiesByJid: function(jid) { if (jsxc.xmpp.conn) { return jsxc.xmpp.conn.caps.getCapabilitiesByJid(jid); } var jidVerIndex = JSON.parse(localStorage.getItem('strophe.caps._jidVerIndex')) || {}; var knownCapabilities = JSON.parse(localStorage.getItem('strophe.caps._knownCapabilities')) || {}; if (jidVerIndex[jid]) { return knownCapabilities[jidVerIndex[jid]]; } return null; } }; /** * Handle carbons (XEP-0280); * * @namespace jsxc.xmpp.carbons */ jsxc.xmpp.carbons = { enabled: false, /** * Enable carbons. * * @memberOf jsxc.xmpp.carbons * @param cb callback */ enable: function(cb) { var iq = $iq({ type: 'set' }).c('enable', { xmlns: jsxc.CONST.NS.CARBONS }); jsxc.xmpp.conn.sendIQ(iq, function() { jsxc.xmpp.carbons.enabled = true; jsxc.debug('Carbons enabled'); if (cb) { cb.call(this); } }, function(stanza) { jsxc.warn('Could not enable carbons', stanza); }); }, /** * Disable carbons. * * @memberOf jsxc.xmpp.carbons * @param cb callback */ disable: function(cb) { var iq = $iq({ type: 'set' }).c('disable', { xmlns: jsxc.CONST.NS.CARBONS }); jsxc.xmpp.conn.sendIQ(iq, function() { jsxc.xmpp.carbons.enabled = false; jsxc.debug('Carbons disabled'); if (cb) { cb.call(this); } }, function(stanza) { jsxc.warn('Could not disable carbons', stanza); }); }, /** * Enable/Disable carbons depending on options key. * * @memberOf jsxc.xmpp.carbons * @param err error message */ refresh: function(err) { if (err === false) { return; } if (jsxc.options.get('carbons').enable) { return jsxc.xmpp.carbons.enable(); } return jsxc.xmpp.carbons.disable(); } }; /** * Handle long-live data * * @namespace jsxc.storage */ jsxc.storage = { /** * Prefix for localstorage * * @privat */ PREFIX: 'jsxc', SEP: ':', /** * @param {type} uk Should we generate a user prefix? * @returns {String} prefix * @memberOf jsxc.storage */ getPrefix: function(uk) { var self = jsxc.storage; return self.PREFIX + self.SEP + ((uk && jsxc.bid) ? jsxc.bid + self.SEP : ''); }, /** * Save item to storage * * @function * @param {String} key variablename * @param {Object} value value * @param {String} uk Userkey? Should we add the bid as prefix? */ setItem: function(key, value, uk) { // Workaround for non-conform browser if (jsxc.storageNotConform > 0 && key !== 'rid' && key !== 'lastActivity') { if (jsxc.storageNotConform > 1 && jsxc.toSNC === null) { jsxc.toSNC = window.setTimeout(function() { jsxc.storageNotConform = 0; jsxc.storage.setItem('storageNotConform', 0); }, 1000); } jsxc.ls.push(JSON.stringify({ key: key, value: value })); } if (typeof (value) === 'object') { value = JSON.stringify(value); } localStorage.setItem(jsxc.storage.getPrefix(uk) + key, value); }, setUserItem: function(type, key, value) { var self = jsxc.storage; if (arguments.length === 2) { value = key; key = type; type = ''; } else if (arguments.length === 3) { key = type + self.SEP + key; } return jsxc.storage.setItem(key, value, true); }, /** * Load item from storage * * @function * @param {String} key variablename * @param {String} uk Userkey? Should we add the bid as prefix? */ getItem: function(key, uk) { key = jsxc.storage.getPrefix(uk) + key; var value = localStorage.getItem(key); try { return JSON.parse(value); } catch (e) { return value; } }, /** * Get a user item from storage. * * @param key * @returns user item */ getUserItem: function(type, key) { var self = jsxc.storage; if (arguments.length === 1) { key = type; } else if (arguments.length === 2) { key = type + self.SEP + key; } return jsxc.storage.getItem(key, true); }, /** * Remove item from storage * * @function * @param {String} key variablename * @param {String} uk Userkey? Should we add the bid as prefix? */ removeItem: function(key, uk) { // Workaround for non-conform browser if (jsxc.storageNotConform && key !== 'rid' && key !== 'lastActivity') { jsxc.ls.push(JSON.stringify({ key: jsxc.storage.prefix + key, value: '' })); } localStorage.removeItem(jsxc.storage.getPrefix(uk) + key); }, /** * Remove user item from storage. * * @param key */ removeUserItem: function(type, key) { var self = jsxc.storage; if (arguments.length === 1) { key = type; } else if (arguments.length === 2) { key = type + self.SEP + key; } jsxc.storage.removeItem(key, true); }, /** * Updates value of a variable in a saved object. * * @function * @param {String} key variablename * @param {String|object} variable variablename in object or object with * variable/key pairs * @param {Object} [value] value * @param {String} uk Userkey? Should we add the bid as prefix? */ updateItem: function(key, variable, value, uk) { var data = jsxc.storage.getItem(key, uk) || {}; if (typeof (variable) === 'object') { $.each(variable, function(key, val) { if (typeof (data[key]) === 'undefined') { jsxc.debug('Variable ' + key + ' doesn\'t exist in ' + variable + '. It was created.'); } data[key] = val; }); } else { if (typeof (data[variable]) === 'undefined') { jsxc.debug('Variable ' + variable + ' doesn\'t exist. It was created.'); } data[variable] = value; } jsxc.storage.setItem(key, data, uk); }, /** * Updates value of a variable in a saved user object. * * @param {String} key variablename * @param {String|object} variable variablename in object or object with * variable/key pairs * @param {Object} [value] value */ updateUserItem: function(type, key, variable, value) { var self = jsxc.storage; if (arguments.length === 4 || (arguments.length === 3 && typeof variable === 'object')) { key = type + self.SEP + key; } else { value = variable; variable = key; key = type; } return jsxc.storage.updateItem(key, variable, value, true); }, /** * Inkrements value * * @function * @param {String} key variablename * @param {String} uk Userkey? Should we add the bid as prefix? */ ink: function(key, uk) { jsxc.storage.setItem(key, Number(jsxc.storage.getItem(key, uk)) + 1, uk); }, /** * Remove element from array or object * * @param {string} key name of array or object * @param {string} name name of element in array or object * @param {String} uk Userkey? Should we add the bid as prefix? * @returns {undefined} */ removeElement: function(key, name, uk) { var item = jsxc.storage.getItem(key, uk); if ($.isArray(item)) { item = $.grep(item, function(e) { return e !== name; }); } else if (typeof (item) === 'object') { delete item[name]; } jsxc.storage.setItem(key, item, uk); }, removeUserElement: function(type, key, name) { var self = jsxc.storage; if (arguments.length === 2) { name = key; key = type; } else if (arguments.length === 3) { key = type + self.SEP + key; } return jsxc.storage.removeElement(key, name, true); }, /** * Triggered if changes are recognized * * @function * @param {event} e Storageevent * @param {String} e.key Keyname which triggered event * @param {Object} e.oldValue Old Value for key * @param {Object} e.newValue New Value for key * @param {String} e.url */ onStorage: function(e) { // skip if (e.key === jsxc.storage.PREFIX + jsxc.storage.SEP + 'rid' || e.key === jsxc.storage.PREFIX + jsxc.storage.SEP + 'lastActivity') { return; } var re = new RegExp('^' + jsxc.storage.PREFIX + jsxc.storage.SEP + '(?:[^' + jsxc.storage.SEP + ']+@[^' + jsxc.storage.SEP + ']+' + jsxc.storage.SEP + ')?(.*)', 'i'); var key = e.key.replace(re, '$1'); // Workaround for non-conform browser: Triggered event on every page // (own) if (jsxc.storageNotConform > 0 && jsxc.ls.length > 0) { var val = e.newValue; try { val = JSON.parse(val); } catch (err) { } var index = $.inArray(JSON.stringify({ key: key, value: val }), jsxc.ls); if (index >= 0) { // confirm that the storage event is not fired regularly if (jsxc.storageNotConform > 1) { window.clearTimeout(jsxc.toSNC); jsxc.storageNotConform = 1; jsxc.storage.setItem('storageNotConform', 1); } jsxc.ls.splice(index, 1); return; } } // Workaround for non-conform browser if (e.oldValue === e.newValue) { return; } var n, o; var bid = key.replace(new RegExp('[^' + jsxc.storage.SEP + ']+' + jsxc.storage.SEP + '(.*)', 'i'), '$1'); // react if someone ask, if there is a master if (jsxc.master && key === 'alive') { jsxc.debug('Master request.'); jsxc.storage.ink('alive'); return; } // master alive if (!jsxc.master && (key === 'alive' || key === 'alive_busy') && !jsxc.triggeredFromElement) { // reset timeout window.clearTimeout(jsxc.to); jsxc.to = window.setTimeout(jsxc.checkMaster, ((key === 'alive') ? jsxc.options.timeout : jsxc.options.busyTimeout) + jsxc.random(60)); // only call the first time if (!jsxc.role_allocation) { jsxc.onSlave(); } return; } if (key.match(/^notices/)) { jsxc.notice.load(); } if (key.match(/^presence/)) { jsxc.gui.changePresence(e.newValue, true); } if (key.match(/^options/) && e.newValue) { n = JSON.parse(e.newValue); if (typeof n.muteNotification !== 'undefined' && n.muteNotification) { jsxc.notification.muteSound(true); } else { jsxc.notification.unmuteSound(true); } } if (key.match(/^hidden/)) { if (jsxc.master) { clearTimeout(jsxc.toNotification); } else { jsxc.isHidden(); } } if (key.match(new RegExp('^chat' + jsxc.storage.SEP))) { var posts = JSON.parse(e.newValue); var data, el; while (posts.length > 0) { data = posts.pop(); el = $('#' + data.uid); if (el.length === 0) { if (jsxc.master && data.direction === 'out') { jsxc.xmpp.sendMessage(bid, data.msg, data.uid); } jsxc.gui.window._postMessage(bid, data); } else if (data.received) { el.addClass('jsxc_received'); } } return; } if (key.match(new RegExp('^window' + jsxc.storage.SEP))) { if (!e.newValue) { jsxc.gui.window._close(bid); return; } if (!e.oldValue) { jsxc.gui.window.open(bid); return; } n = JSON.parse(e.newValue); if (n.minimize) { jsxc.gui.window._hide(bid); } else { jsxc.gui.window._show(bid); } jsxc.gui.window.setText(bid, n.text); return; } if (key.match(new RegExp('^smp' + jsxc.storage.SEP))) { if (!e.newValue) { jsxc.gui.dialog.close(); if (jsxc.master) { jsxc.otr.objects[bid].sm.abort(); } return; } n = JSON.parse(e.newValue); if (typeof (n.data) !== 'undefined') { jsxc.otr.onSmpQuestion(bid, n.data); } else if (jsxc.master && n.sec) { jsxc.gui.dialog.close(); jsxc.otr.sendSmpReq(bid, n.sec, n.quest); } } if (!jsxc.master && key.match(new RegExp('^buddy' + jsxc.storage.SEP))) { if (!e.newValue) { jsxc.gui.roster.purge(bid); return; } if (!e.oldValue) { jsxc.gui.roster.add(bid); return; } n = JSON.parse(e.newValue); o = JSON.parse(e.oldValue); jsxc.gui.update(bid); if (o.status !== n.status || o.sub !== n.sub) { jsxc.gui.roster.reorder(bid); } } if (jsxc.master && key.match(new RegExp('^deletebuddy' + jsxc.storage.SEP)) && e.newValue) { n = JSON.parse(e.newValue); jsxc.xmpp.removeBuddy(n.jid); jsxc.storage.removeUserItem(key); } if (jsxc.master && key.match(new RegExp('^buddy' + jsxc.storage.SEP))) { n = JSON.parse(e.newValue); o = JSON.parse(e.oldValue); if (o.transferReq !== n.transferReq) { jsxc.storage.updateUserItem('buddy', bid, 'transferReq', -1); if (n.transferReq === 0) { jsxc.otr.goPlain(bid); } if (n.transferReq === 1) { jsxc.otr.goEncrypt(bid); } } if (o.name !== n.name) { jsxc.gui.roster._rename(bid, n.name); } } // logout if (key === 'sid') { if (!e.newValue) { // if (jsxc.master && jsxc.xmpp.conn) { // jsxc.xmpp.conn.disconnect(); // jsxc.triggeredFromElement = true; // } jsxc.xmpp.logout(); } return; } if (key === 'friendReq') { n = JSON.parse(e.newValue); if (jsxc.master && n.approve >= 0) { jsxc.xmpp.resFriendReq(n.jid, n.approve); } } if (jsxc.master && key.match(new RegExp('^add' + jsxc.storage.SEP))) { n = JSON.parse(e.newValue); jsxc.xmpp.addBuddy(n.username, n.alias); } if (key === 'roster') { jsxc.gui.roster.toggle(); } if (jsxc.master && key.match(new RegExp('^vcard' + jsxc.storage.SEP)) && e.newValue !== null && e.newValue.match(/^request:/)) { jsxc.xmpp.loadVcard(bid, function(stanza) { jsxc.storage.setUserItem('vcard', bid, { state: 'success', data: $('<div>').append(stanza).html() }); }, function() { jsxc.storage.setUserItem('vcard', bid, { state: 'error' }); }); } if (!jsxc.master && key.match(new RegExp('^vcard' + jsxc.storage.SEP)) && e.newValue !== null && !e.newValue.match(/^request:/)) { n = JSON.parse(e.newValue); if (typeof n.state !== 'undefined') { $(document).trigger('loaded.vcard.jsxc', n); } jsxc.storage.removeUserItem('vcard', bid); } }, /** * Save message to storage. * * @memberOf jsxc.storage * @param bid * @param direction * @param msg * @param encrypted * @param forwarded * @return post */ saveMessage: function(bid, direction, msg, encrypted, forwarded, stamp) { var chat = jsxc.storage.getUserItem('chat', bid) || []; var uid = new Date().getTime() + ':msg'; if (chat.length > jsxc.options.get('numberOfMsg')) { chat.pop(); } var post = { direction: direction, msg: msg, uid: uid.replace(/:/, '-'), received: false, encrypted: encrypted || false, forwarded: forwarded || false, stamp: stamp || new Date().getTime() }; chat.unshift(post); jsxc.storage.setUserItem('chat', bid, chat); return post; }, /** * Save or update buddy data. * * @memberOf jsxc.storage * @param bid * @param data * @returns {String} Updated or created */ saveBuddy: function(bid, data) { if (jsxc.storage.getUserItem('buddy', bid)) { jsxc.storage.updateUserItem('buddy', bid, data); return 'updated'; } jsxc.storage.setUserItem('buddy', bid, $.extend({ jid: '', name: '', status: 0, sub: 'none', msgstate: 0, transferReq: -1, trust: false, fingerprint: null, res: [], type: 'chat' }, data)); return 'created'; } }; /** * @namespace jsxc.otr */ jsxc.otr = { /** list of otr objects */ objects: {}, dsaFallback: null, /** * Handler for otr receive event * * @memberOf jsxc.otr * @param {Object} d * @param {string} d.bid * @param {string} d.msg received message * @param {boolean} d.encrypted True, if msg was encrypted. * @param {boolean} d.forwarded * @param {string} d.stamp timestamp */ receiveMessage: function(d) { var bid = d.bid; if (jsxc.otr.objects[bid].msgstate !== OTR.CONST.MSGSTATE_PLAINTEXT) { jsxc.otr.backup(bid); } if (jsxc.otr.objects[bid].msgstate !== OTR.CONST.MSGSTATE_PLAINTEXT && !encrypted) { jsxc.gui.window.postMessage(bid, 'sys', jsxc.translate('%%Received an unencrypted message.%% [') + d.msg + ']', d.encrypted, d.forwarded, d.stamp); } else { jsxc.gui.window.postMessage(bid, 'in', d.msg, d.encrypted, d.forwarded, d.stamp); } }, /** * Handler for otr send event * * @param {string} jid * @param {string} msg message to be send */ sendMessage: function(jid, msg, uid) { if (jsxc.otr.objects[jsxc.jidToBid(jid)].msgstate !== 0) { jsxc.otr.backup(jsxc.jidToBid(jid)); } jsxc.xmpp._sendMessage(jid, msg, uid); }, /** * Create new otr instance * * @param {type} bid * @returns {undefined} */ create: function(bid) { if (jsxc.otr.objects.hasOwnProperty(bid)) { return; } if (!jsxc.options.otr.priv) { return; } // save list of otr objects var ol = jsxc.storage.getUserItem('otrlist') || []; if (ol.indexOf(bid) < 0) { ol.push(bid); jsxc.storage.setUserItem('otrlist', ol); } jsxc.otr.objects[bid] = new OTR(jsxc.options.otr); if (jsxc.options.otr.SEND_WHITESPACE_TAG) { jsxc.otr.objects[bid].SEND_WHITESPACE_TAG = true; } if (jsxc.options.otr.WHITESPACE_START_AKE) { jsxc.otr.objects[bid].WHITESPACE_START_AKE = true; } jsxc.otr.objects[bid].on('status', function(status) { var data = jsxc.storage.getUserItem('buddy', bid); if (data === null) { return; } switch (status) { case OTR.CONST.STATUS_SEND_QUERY: jsxc.gui.window.postMessage(bid, 'sys', jsxc.l.trying_to_start_private_conversation); break; case OTR.CONST.STATUS_AKE_SUCCESS: data.fingerprint = jsxc.otr.objects[bid].their_priv_pk.fingerprint(); data.msgstate = OTR.CONST.MSGSTATE_ENCRYPTED; var msg = (jsxc.otr.objects[bid].trust ? jsxc.l.Verified : jsxc.l.Unverified) + ' ' + jsxc.l.private_conversation_started; jsxc.gui.window.postMessage(bid, 'sys', msg); break; case OTR.CONST.STATUS_END_OTR: data.fingerprint = null; if (jsxc.otr.objects[bid].msgstate === OTR.CONST.MSGSTATE_PLAINTEXT) { // we abort the private conversation data.msgstate = OTR.CONST.MSGSTATE_PLAINTEXT; jsxc.gui.window.postMessage(bid, 'sys', jsxc.l.private_conversation_aborted); } else { // the buddy abort the private conversation data.msgstate = OTR.CONST.MSGSTATE_FINISHED; jsxc.gui.window.postMessage(bid, 'sys', jsxc.l.your_buddy_closed_the_private_conversation_you_should_do_the_same); } break; case OTR.CONST.STATUS_SMP_HANDLE: jsxc.keepBusyAlive(); break; } jsxc.storage.setUserItem('buddy', bid, data); // for encryption and verification state jsxc.gui.update(bid); }); jsxc.otr.objects[bid].on('smp', function(type, data) { switch (type) { case 'question': // verification request received jsxc.gui.window.postMessage(bid, 'sys', jsxc.l.Authentication_request_received); if ($('#jsxc_dialog').length > 0) { jsxc.otr.objects[bid].sm.abort(); break; } jsxc.otr.onSmpQuestion(bid, data); jsxc.storage.setUserItem('smp_' + bid, { data: data || null }); break; case 'trust': // verification completed jsxc.otr.objects[bid].trust = data; jsxc.storage.updateUserItem('buddy', bid, 'trust', data); jsxc.otr.backup(bid); jsxc.gui.update(bid); if (data) { jsxc.gui.window.postMessage(bid, 'sys', jsxc.l.conversation_is_now_verified); } else { jsxc.gui.window.postMessage(bid, 'sys', jsxc.l.authentication_failed); } jsxc.storage.removeUserItem('smp_' + bid); jsxc.gui.dialog.close(); break; case 'abort': jsxc.gui.window.postMessage(bid, 'sys', jsxc.l.Authentication_aborted); break; default: jsxc.debug('[OTR] sm callback: Unknown type: ' + type); } }); // Receive message jsxc.otr.objects[bid].on('ui', function(msg, encrypted, meta) { jsxc.otr.receiveMessage({ bid: bid, msg: msg, encrypted: encrypted === true, stamp: meta.stamp, forwarded: meta.forwarded }); }); // Send message jsxc.otr.objects[bid].on('io', function(msg, uid) { var jid = jsxc.gui.window.get(bid).data('jid') || jsxc.otr.objects[bid].jid; jsxc.otr.objects[bid].jid = jid; jsxc.otr.sendMessage(jid, msg, uid); }); jsxc.otr.objects[bid].on('error', function(err) { // Handle this case in jsxc.otr.receiveMessage if (err !== 'Received an unencrypted message.') { jsxc.gui.window.postMessage(bid, 'sys', '[OTR] ' + jsxc.translate('%%' + err + '%%')); } jsxc.error('[OTR] ' + err); }); jsxc.otr.restore(bid); }, /** * show verification dialog with related part (secret or question) * * @param {type} bid * @param {string} [data] * @returns {undefined} */ onSmpQuestion: function(bid, data) { jsxc.gui.showVerification(bid); $('#jsxc_dialog select').prop('selectedIndex', (data ? 2 : 3)).change(); $('#jsxc_dialog > div:eq(0)').hide(); if (data) { $('#jsxc_dialog > div:eq(2)').find('#jsxc_quest').val(data).prop('disabled', true); $('#jsxc_dialog > div:eq(2)').find('.creation').text('Answer'); $('#jsxc_dialog > div:eq(2)').find('.jsxc_explanation').text(jsxc.l.your_buddy_is_attempting_to_determine_ + ' ' + jsxc.l.to_authenticate_to_your_buddy + jsxc.l.enter_the_answer_and_click_answer); } else { $('#jsxc_dialog > div:eq(3)').find('.jsxc_explanation').text(jsxc.l.your_buddy_is_attempting_to_determine_ + ' ' + jsxc.l.to_authenticate_to_your_buddy + jsxc.l.enter_the_secret); } $('#jsxc_dialog .jsxc_close').click(function() { jsxc.storage.removeUserItem('smp_' + bid); if (jsxc.master) { jsxc.otr.objects[bid].sm.abort(); } }); }, /** * Send verification request to buddy * * @param {string} bid * @param {string} sec secret * @param {string} [quest] question * @returns {undefined} */ sendSmpReq: function(bid, sec, quest) { jsxc.keepBusyAlive(); jsxc.otr.objects[bid].smpSecret(sec, quest || ''); }, /** * Toggle encryption state * * @param {type} bid * @returns {undefined} */ toggleTransfer: function(bid) { if (jsxc.storage.getUserItem('buddy', bid).msgstate === 0) { jsxc.otr.goEncrypt(bid); } else { jsxc.otr.goPlain(bid); } }, /** * Send request to encrypt the session * * @param {type} bid * @returns {undefined} */ goEncrypt: function(bid) { if (jsxc.master) { jsxc.otr.objects[bid].sendQueryMsg(); } else { jsxc.storage.updateUserItem('buddy', bid, 'transferReq', 1); } }, /** * Abort encryptet session * * @param {type} bid * @param cb callback * @returns {undefined} */ goPlain: function(bid, cb) { if (jsxc.master) { jsxc.otr.objects[bid].endOtr.call(jsxc.otr.objects[bid], cb); jsxc.otr.objects[bid].init.call(jsxc.otr.objects[bid]); jsxc.otr.backup(bid); } else { jsxc.storage.updateUserItem('buddy', bid, 'transferReq', 0); } }, /** * Backups otr session * * @param {string} bid */ backup: function(bid) { var o = jsxc.otr.objects[bid]; // otr object var r = {}; // return value if (o === null) { return; } // all variables which should be saved var savekey = [ 'jid', 'our_instance_tag', 'msgstate', 'authstate', 'fragment', 'their_y', 'their_old_y', 'their_keyid', 'their_instance_tag', 'our_dh', 'our_old_dh', 'our_keyid', 'sessKeys', 'storedMgs', 'oldMacKeys', 'trust', 'transmittedRS', 'ssid', 'receivedPlaintext', 'authstate', 'send_interval' ]; var i; for (i = 0; i < savekey.length; i++) { r[savekey[i]] = JSON.stringify(o[savekey[i]]); } if (o.their_priv_pk !== null) { r.their_priv_pk = JSON.stringify(o.their_priv_pk.packPublic()); } if (o.ake.otr_version && o.ake.otr_version !== '') { r.otr_version = JSON.stringify(o.ake.otr_version); } jsxc.storage.setUserItem('otr', bid, r); }, /** * Restore old otr session * * @param {string} bid */ restore: function(bid) { var o = jsxc.otr.objects[bid]; var d = jsxc.storage.getUserItem('otr', bid); if (o !== null || d !== null) { var key; for (key in d) { if (d.hasOwnProperty(key)) { var val = JSON.parse(d[key]); if (key === 'their_priv_pk' && val !== null) { val = DSA.parsePublic(val); } if (key === 'otr_version' && val !== null) { o.ake.otr_version = val; } else { o[key] = val; } } } jsxc.otr.objects[bid] = o; if (o.msgstate === 1 && o.their_priv_pk !== null) { o._smInit.call(jsxc.otr.objects[bid]); } } jsxc.otr.enable(bid); }, /** * Create or load DSA key * * @returns {unresolved} */ createDSA: function() { if (jsxc.options.otr.priv) { return; } if (jsxc.storage.getUserItem('key') === null) { var msg = jsxc.l.Creating_your_private_key_; var worker = null; if (Worker) { // try to create web-worker try { worker = new Worker(jsxc.options.root + '/lib/otr/build/dsa-webworker.js'); } catch (err) { jsxc.warn('Couldn\'t create web-worker.', err); } } jsxc.otr.dsaFallback = (worker === null); if (!jsxc.otr.dsaFallback) { // create DSA key in background jsxc._onMaster(); worker.onmessage = function(e) { var type = e.data.type; var val = e.data.val; if (type === 'debug') { jsxc.debug(val); } else if (type === 'data') { jsxc.otr.DSAready(DSA.parsePrivate(val)); } }; // start worker worker.postMessage({ imports: [ jsxc.options.root + '/lib/otr/vendor/salsa20.js', jsxc.options.root + '/lib/otr/vendor/bigint.js', jsxc.options.root + '/lib/otr/vendor/crypto.js', jsxc.options.root + '/lib/otr/vendor/eventemitter.js', jsxc.options.root + '/lib/otr/lib/const.js', jsxc.options.root + '/lib/otr/lib/helpers.js', jsxc.options.root + '/lib/otr/lib/dsa.js' ], seed: BigInt.getSeed(), debug: true }); } else { // fallback jsxc.gui.dialog.open(jsxc.gui.template.get('waitAlert', null, msg), { noClose: true }); jsxc.debug('DSA key creation started.'); // wait until the wait alert is opened setTimeout(function() { var dsa = new DSA(); jsxc.otr.DSAready(dsa); }, 500); } } else { jsxc.debug('DSA key loaded'); jsxc.options.otr.priv = DSA.parsePrivate(jsxc.storage.getUserItem('key')); jsxc.otr._createDSA(); } }, /** * Ending of createDSA(). */ _createDSA: function() { jsxc.storage.setUserItem('priv_fingerprint', jsxc.options.otr.priv.fingerprint()); if (jsxc.otr.dsaFallback !== false) { jsxc._onMaster(); } }, /** * Ending of DSA key generation. * * @param {DSA} dsa DSA object */ DSAready: function(dsa) { jsxc.storage.setUserItem('key', dsa.packPrivate()); jsxc.options.otr.priv = dsa; // close wait alert if (jsxc.otr.dsaFallback) { jsxc.gui.dialog.close(); } else { $.each(jsxc.storage.getUserItem('windowlist'), function(index, val) { jsxc.otr.create(val); }); } jsxc.otr._createDSA(); }, enable: function(bid) { jsxc.gui.window.get(bid).find('.jsxc_otr').removeClass('jsxc_disabled'); } }; /** * This namespace handles the Notification API. * * @namespace jsxc.notification */ jsxc.notification = { /** Current audio file. */ audio: null, /** * Register notification on incoming messages. * * @memberOf jsxc.notification */ init: function() { $(document).on('postmessagein.jsxc', function(event, bid, msg) { msg = (msg.match(/^\?OTR/)) ? jsxc.translate('%%Encrypted message%%') : msg; var data = jsxc.storage.getUserItem('buddy', bid); jsxc.notification.notify(jsxc.translate('%%New message from%% ') + data.name, msg, undefined, undefined, jsxc.CONST.SOUNDS.MSG); }); $(document).on('callincoming.jingle', function() { jsxc.notification.playSound(jsxc.CONST.SOUNDS.CALL, true, true); }); $(document).on('accept.call.jsxc reject.call.jsxc', function() { jsxc.notification.stopSound(); }); }, /** * Shows a pop up notification and optional play sound. * * @param title Title * @param msg Message * @param d Duration * @param force Should message also shown, if tab is visible? * @param soundFile Playing given sound file * @param loop Loop sound file? */ notify: function(title, msg, d, force, soundFile, loop) { if (!jsxc.options.notification || !jsxc.notification.hasPermission()) { return; // notifications disabled } if (!jsxc.isHidden() && !force) { return; // Tab is visible } jsxc.toNotification = setTimeout(function() { if (typeof soundFile === 'string') { jsxc.notification.playSound(soundFile, loop, force); } var popup = new Notification(jsxc.translate(title), { body: jsxc.translate(msg), icon: jsxc.options.root + '/img/XMPP_logo.png' }); var duration = d || jsxc.options.popupDuration; if (duration > 0) { setTimeout(function() { popup.close(); }, duration); } }, jsxc.toNotificationDelay); }, /** * Checks if browser has support for notifications and add on chrome to * the default api. * * @returns {Boolean} True if the browser has support. */ hasSupport: function() { if (window.webkitNotifications) { // prepare chrome window.Notification = function(title, opt) { var popup = window.webkitNotifications.createNotification(null, title, opt.body); popup.show(); popup.close = function() { popup.cancel(); }; return popup; }; var permission; switch (window.webkitNotifications.checkPermission()) { case 0: permission = jsxc.CONST.NOTIFICATION_GRANTED; break; case 2: permission = jsxc.CONST.NOTIFICATION_DENIED; break; default: // 1 permission = jsxc.CONST.NOTIFICATION_DEFAULT; } window.Notification.permission = permission; window.Notification.requestPermission = function(func) { window.webkitNotifications.requestPermission(func); }; return true; } else if (window.Notification) { return true; } else { return false; } }, /** * Ask user on first incoming message if we should inform him about new * messages. */ prepareRequest: function() { $(document).one('postmessagein.jsxc', function() { jsxc.switchEvents({ 'notificationready.jsxc': function() { jsxc.gui.dialog.close(); jsxc.notification.init(); jsxc.storage.setUserItem('notification', true); }, 'notificationfailure.jsxc': function() { jsxc.gui.dialog.close(); jsxc.options.notification = false; jsxc.storage.setUserItem('notification', false); } }); setTimeout(function() { jsxc.notice.add('%%Notifications%%?', '%%Should_we_notify_you_%%', 'gui.showRequestNotification'); }, 1000); }); }, /** * Request notification permission. */ requestPermission: function() { window.Notification.requestPermission(function(status) { if (window.Notification.permission !== status) { window.Notification.permission = status; } if (jsxc.notification.hasPermission()) { $(document).trigger('notificationready.jsxc'); } else { $(document).trigger('notificationfailure.jsxc'); } }); }, /** * Check permission. * * @returns {Boolean} True if we have the permission */ hasPermission: function() { return window.Notification.permission === jsxc.CONST.NOTIFICATION_GRANTED; }, /** * Plays the given file. * * @memberOf jsxc.notification * @param {string} soundFile File relative to the sound directory * @param {boolean} loop True for loop * @param {boolean} force Play even if a tab is visible. Default: false. */ playSound: function(soundFile, loop, force) { if (!jsxc.master) { // only master plays sound return; } if (jsxc.options.get('muteNotification') || jsxc.storage.getUserItem('presence') === 'dnd') { // sound mute or own presence is dnd return; } if (!jsxc.isHidden() && !force) { // tab is visible return; } // stop current audio file jsxc.notification.stopSound(); var audio = new Audio(jsxc.options.root + '/sound/' + soundFile); audio.loop = loop || false; audio.play(); jsxc.notification.audio = audio; }, /** * Stop/remove current sound. * * @memberOf jsxc.notification */ stopSound: function() { var audio = jsxc.notification.audio; if (typeof audio !== 'undefined' && audio !== null) { audio.pause(); jsxc.notification.audio = null; } }, /** * Mute sound. * * @memberOf jsxc.notification * @param {boolean} external True if triggered from external tab. Default: * false. */ muteSound: function(external) { $('#jsxc_menu .jsxc_muteNotification').text(jsxc.translate('%%Unmute%%')); if (external !== true) { jsxc.options.set('muteNotification', true); } }, /** * Unmute sound. * * @memberOf jsxc.notification * @param {boolean} external True if triggered from external tab. Default: * false. */ unmuteSound: function(external) { $('#jsxc_menu .jsxc_muteNotification').text(jsxc.translate('%%Mute%%')); if (external !== true) { jsxc.options.set('muteNotification', false); } } }; /** * This namespace handle the notice system. * * @namspace jsxc.notice * @memberOf jsxc */ jsxc.notice = { /** Number of notices. */ _num: 0, /** * Loads the saved notices. * * @memberOf jsxc.notice */ load: function() { // reset list $('#jsxc_notice ul li').remove(); $('#jsxc_notice > span').text(''); jsxc.notice._num = 0; var saved = jsxc.storage.getUserItem('notices') || []; var key = null; for (key in saved) { if (saved.hasOwnProperty(key)) { var val = saved[key]; jsxc.notice.add(val.msg, val.description, val.fnName, val.fnParams, key); } } }, /** * Add a new notice to the stack; * * @memberOf jsxc.notice * @param msg Header message * @param description Notice description * @param fnName Function name to be called if you open the notice * @param fnParams Array of params for function * @param id Notice id */ add: function(msg, description, fnName, fnParams, id) { var nid = id || Date.now(); var list = $('#jsxc_notice ul'); var notice = $('<li/>'); notice.click(function() { jsxc.notice.remove(nid); jsxc.exec(fnName, fnParams); return false; }); notice.text(jsxc.translate(msg)); notice.attr('title', jsxc.translate(description) || ''); notice.attr('data-nid', nid); list.append(notice); $('#jsxc_notice > span').text(++jsxc.notice._num); if (!id) { var saved = jsxc.storage.getUserItem('notices') || {}; saved[nid] = { msg: msg, description: description, fnName: fnName, fnParams: fnParams }; jsxc.storage.setUserItem('notices', saved); jsxc.notification.notify(msg, description || '', null, true, jsxc.CONST.SOUNDS.NOTICE); } }, /** * Removes notice from stack * * @memberOf jsxc.notice * @param nid The notice id */ remove: function(nid) { var el = $('#jsxc_notice li[data-nid=' + nid + ']'); el.remove(); $('#jsxc_notice > span').text(--jsxc.notice._num || ''); var s = jsxc.storage.getUserItem('notices'); delete s[nid]; jsxc.storage.setUserItem('notices', s); } }; /** * Contains all available translations * * @namespace jsxc.l10n * @memberOf jsxc */ jsxc.l10n = { en: { Logging_in: 'Logging in…', your_connection_is_unencrypted: 'Your connection is unencrypted.', your_connection_is_encrypted: 'Your connection is encrypted.', your_buddy_closed_the_private_connection: 'Your buddy closed the private connection.', start_private: 'Start private', close_private: 'Close private', your_buddy_is_verificated: 'Your buddy is verified.', you_have_only_a_subscription_in_one_way: 'You only have a one-way subscription.', authentication_query_sent: 'Authentication query sent.', your_message_wasnt_send_please_end_your_private_conversation: 'Your message was not sent. Please end your private conversation.', unencrypted_message_received: 'Unencrypted message received:', your_message_wasnt_send_because_you_have_no_valid_subscription: 'Your message was not sent because you have no valid subscription.', not_available: 'Not available', no_connection: 'No connection!', relogin: 'relogin', trying_to_start_private_conversation: 'Trying to start private conversation!', Verified: 'Verified', Unverified: 'Unverified', private_conversation_started: 'Private conversation started.', private_conversation_aborted: 'Private conversation aborted!', your_buddy_closed_the_private_conversation_you_should_do_the_same: 'Your buddy closed the private conversation! You should do the same.', conversation_is_now_verified: 'Conversation is now verified.', authentication_failed: 'Authentication failed.', your_buddy_is_attempting_to_determine_: 'You buddy is attempting to determine if he or she is really talking to you.', to_authenticate_to_your_buddy: 'To authenticate to your buddy, ', enter_the_answer_and_click_answer: 'enter the answer and click Answer.', enter_the_secret: 'enter the secret.', Creating_your_private_key_: 'Creating your private key; this may take a while.', Authenticating_a_buddy_helps_: 'Authenticating a buddy helps ensure that the person you are talking to is really the one he or she claims to be.', How_do_you_want_to_authenticate_your_buddy: 'How do you want to authenticate {{bid_name}} (<b>{{bid_jid}}</b>)?', Select_method: 'Select method...', Manual: 'Manual', Question: 'Question', Secret: 'Secret', To_verify_the_fingerprint_: 'To verify the fingerprint, contact your buddy via some other trustworthy channel, such as the telephone.', Your_fingerprint: 'Your fingerprint', Buddy_fingerprint: 'Buddy fingerprint', Close: 'Close', Compared: 'Compared', To_authenticate_using_a_question_: 'To authenticate using a question, pick a question whose answer is known only you and your buddy.', Ask: 'Ask', To_authenticate_pick_a_secret_: 'To authenticate, pick a secret known only to you and your buddy.', Compare: 'Compare', Fingerprints: 'Fingerprints', Authentication: 'Authentication', Message: 'Message', Add_buddy: 'Add buddy', rename_buddy: 'rename buddy', delete_buddy: 'delete buddy', Login: 'Login', Username: 'Username', Password: 'Password', Cancel: 'Cancel', Connect: 'Connect', Type_in_the_full_username_: 'Type in the full username and an optional alias.', Alias: 'Alias', Add: 'Add', Subscription_request: 'Subscription request', You_have_a_request_from: 'You have a request from', Deny: 'Deny', Approve: 'Approve', Remove_buddy: 'Remove buddy', You_are_about_to_remove_: 'You are about to remove {{bid_name}} (<b>{{bid_jid}}</b>) from your buddy list. All related chats will be closed.', Continue_without_chat: 'Continue without chat', Please_wait: 'Please wait', Login_failed: 'Chat login failed', Sorry_we_cant_authentikate_: 'Authentication failed with the chat server. Maybe the password is wrong?', Retry: 'Back', clear_history: 'Clear history', New_message_from: 'New message from', Should_we_notify_you_: 'Should we notify you about new messages in the future?', Please_accept_: 'Please click the "Allow" button at the top.', Hide_offline: 'Hide offline contacts', Show_offline: 'Show offline contacts', About: 'About', dnd: 'Do Not Disturb', Mute: 'Mute', Unmute: 'Unmute', Subscription: 'Subscription', both: 'both', Status: 'Status', online: 'online', chat: 'chat', away: 'away', xa: 'extended away', offline: 'offline', none: 'none', Unknown_instance_tag: 'Unknown instance tag.', Not_one_of_our_latest_keys: 'Not one of our latest keys.', Received_an_unreadable_encrypted_message: 'Received an unreadable encrypted message.', Online: 'Online', Chatty: 'Chatty', Away: 'Away', Extended_away: 'Extended away', Offline: 'Offline', Friendship_request: 'Friendship request', Confirm: 'Confirm', Dismiss: 'Dismiss', Remove: 'Remove', Online_help: 'Online help', FN: 'Full name', N: ' ', FAMILY: 'Family name', GIVEN: 'Given name', NICKNAME: 'Nickname', URL: 'URL', ADR: 'Address', STREET: 'Street Address', EXTADD: 'Extended Address', LOCALITY: 'Locality', REGION: 'Region', PCODE: 'Postal Code', CTRY: 'Country', TEL: 'Telephone', NUMBER: 'Number', EMAIL: 'Email', USERID: ' ', ORG: 'Organization', ORGNAME: 'Name', ORGUNIT: 'Unit', TITLE: 'Job title', ROLE: 'Role', BDAY: 'Birthday', DESC: 'Description', PHOTO: ' ', send_message: 'Send message', get_info: 'Show information', Settings: 'Settings', Priority: 'Priority', Save: 'Save', User_settings: 'User settings', A_fingerprint_: 'A fingerprint is used to make sure that the person you are talking to is who he or she is saying.', Your_roster_is_empty_add_a: 'Your roster is empty, add a ', new_buddy: 'new buddy', is: 'is', Login_options: 'Login options', BOSH_url: 'BOSH URL', Domain: 'Domain', Resource: 'Resource', On_login: 'On login', Received_an_unencrypted_message: 'Received an unencrypted message', Sorry_your_buddy_doesnt_provide_any_information: 'Sorry, your buddy does not provide any information.', Info_about: 'Info about', Authentication_aborted: 'Authentication aborted.', Authentication_request_received: 'Authentication request received.', Do_you_want_to_display_them: 'Do you want to display them?', Log_in_without_chat: 'Log in without chat', has_come_online: 'has come online', Unknown_sender: 'Unknown sender', You_received_a_message_from_an_unknown_sender: 'You received a message from an unknown sender' }, de: { Logging_in: 'Login läuft…', your_connection_is_unencrypted: 'Deine Verbindung ist UNverschlüsselt.', your_connection_is_encrypted: 'Deine Verbindung ist verschlüsselt.', your_buddy_closed_the_private_connection: 'Dein Freund hat die private Verbindung getrennt.', start_private: 'Privat starten', close_private: 'Privat abbrechen', your_buddy_is_verificated: 'Dein Freund ist verifiziert.', you_have_only_a_subscription_in_one_way: 'Die Freundschaft ist nur einseitig.', authentication_query_sent: 'Authentifizierungsanfrage gesendet.', your_message_wasnt_send_please_end_your_private_conversation: 'Deine Nachricht wurde nicht gesendet. Bitte beende die private Konversation.', unencrypted_message_received: 'Unverschlüsselte Nachricht erhalten.', your_message_wasnt_send_because_you_have_no_valid_subscription: 'Deine Nachricht wurde nicht gesandt, da die Freundschaft einseitig ist.', not_available: 'Nicht verfügbar.', no_connection: 'Keine Verbindung.', relogin: 'Neu anmelden.', trying_to_start_private_conversation: 'Versuche private Konversation zu starten.', Verified: 'Verifiziert', Unverified: 'Unverifiziert', private_conversation_started: 'Private Konversation gestartet.', private_conversation_aborted: 'Private Konversation abgebrochen.', your_buddy_closed_the_private_conversation_you_should_do_the_same: 'Dein Freund hat die private Konversation beendet. Das solltest du auch tun!', conversation_is_now_verified: 'Konversation ist jetzt verifiziert', authentication_failed: 'Authentifizierung fehlgeschlagen.', your_buddy_is_attempting_to_determine_: 'Dein Freund versucht herauszufinden ob er wirklich mit dir redet.', to_authenticate_to_your_buddy: 'Um dich gegenüber deinem Freund zu verifizieren ', enter_the_answer_and_click_answer: 'gib die Antwort ein und klick auf Antworten.', enter_the_secret: 'gib das Geheimnis ein.', Creating_your_private_key_: 'Wir werden jetzt deinen privaten Schlüssel generieren. Das kann einige Zeit in Anspruch nehmen.', Authenticating_a_buddy_helps_: 'Einen Freund zu authentifizieren hilft sicher zustellen, dass die Person mit der du sprichst auch die ist die sie sagt.', How_do_you_want_to_authenticate_your_buddy: 'Wie willst du {{bid_name}} (<b>{{bid_jid}}</b>) authentifizieren?', Select_method: 'Wähle...', Manual: 'Manual', Question: 'Frage', Secret: 'Geheimnis', To_verify_the_fingerprint_: 'Um den Fingerprint zu verifizieren kontaktiere dein Freund über einen anderen Kommunikationsweg. Zum Beispiel per Telefonanruf.', Your_fingerprint: 'Dein Fingerprint', Buddy_fingerprint: 'Sein/Ihr Fingerprint', Close: 'Schließen', Compared: 'Verglichen', To_authenticate_using_a_question_: 'Um die Authentifizierung per Frage durchzuführen, wähle eine Frage bei welcher nur dein Freund die Antwort weiß.', Ask: 'Frage', To_authenticate_pick_a_secret_: 'Um deinen Freund zu authentifizieren, wähle ein Geheimnis welches nur deinem Freund und dir bekannt ist.', Compare: 'Vergleiche', Fingerprints: 'Fingerprints', Authentication: 'Authentifizierung', Message: 'Nachricht', Add_buddy: 'Freund hinzufügen', rename_buddy: 'Freund umbenennen', delete_buddy: 'Freund löschen', Login: 'Anmeldung', Username: 'Benutzername', Password: 'Passwort', Cancel: 'Abbrechen', Connect: 'Verbinden', Type_in_the_full_username_: 'Gib bitte den vollen Benutzernamen und optional ein Alias an.', Alias: 'Alias', Add: 'Hinzufügen', Subscription_request: 'Freundschaftsanfrage', You_have_a_request_from: 'Du hast eine Anfrage von', Deny: 'Ablehnen', Approve: 'Bestätigen', Remove_buddy: 'Freund entfernen', You_are_about_to_remove_: 'Du bist gerade dabei {{bid_name}} (<b>{{bid_jid}}</b>) von deiner Kontaktliste zu entfernen. Alle Chats werden geschlossen.', Continue_without_chat: 'Weiter ohne Chat', Please_wait: 'Bitte warten', Login_failed: 'Chat-Anmeldung fehlgeschlagen', Sorry_we_cant_authentikate_: 'Der Chatserver hat die Anmeldung abgelehnt. Falsches Passwort?', Retry: 'Zurück', clear_history: 'Lösche Verlauf', New_message_from: 'Neue Nachricht von', Should_we_notify_you_: 'Sollen wir dich in Zukunft über eingehende Nachrichten informieren, auch wenn dieser Tab nicht im Vordergrund ist?', Please_accept_: 'Bitte klick auf den "Zulassen" Button oben.', Menu: 'Menü', Hide_offline: 'Offline ausblenden', Show_offline: 'Offline einblenden', About: 'Über', dnd: 'Beschäftigt', Mute: 'Ton aus', Unmute: 'Ton an', Subscription: 'Bezug', both: 'beidseitig', Status: 'Status', online: 'online', chat: 'chat', away: 'abwesend', xa: 'länger abwesend', offline: 'offline', none: 'keine', Unknown_instance_tag: 'Unbekannter instance tag.', Not_one_of_our_latest_keys: 'Nicht einer unserer letzten Schlüssel.', Received_an_unreadable_encrypted_message: 'Eine unlesbare verschlüsselte Nachricht erhalten.', Online: 'Online', Chatty: 'Gesprächig', Away: 'Abwesend', Extended_away: 'Länger abwesend', Offline: 'Offline', Friendship_request: 'Freundschaftsanfrage', Confirm: 'Bestätigen', Dismiss: 'Ablehnen', Remove: 'Löschen', Online_help: 'Online Hilfe', FN: 'Name', N: ' ', FAMILY: 'Familienname', GIVEN: 'Vorname', NICKNAME: 'Spitzname', URL: 'URL', ADR: 'Adresse', STREET: 'Straße', EXTADD: 'Zusätzliche Adresse', LOCALITY: 'Ortschaft', REGION: 'Region', PCODE: 'Postleitzahl', CTRY: 'Land', TEL: 'Telefon', NUMBER: 'Nummer', EMAIL: 'E-Mail', USERID: ' ', ORG: 'Organisation', ORGNAME: 'Name', ORGUNIT: 'Abteilung', TITLE: 'Titel', ROLE: 'Rolle', BDAY: 'Geburtstag', DESC: 'Beschreibung', PHOTO: ' ', send_message: 'Sende Nachricht', get_info: 'Benutzerinformationen', Settings: 'Einstellungen', Priority: 'Priorität', Save: 'Speichern', User_settings: 'Benutzereinstellungen', A_fingerprint_: 'Ein Fingerabdruck wird dazu benutzt deinen Gesprächspartner zu identifizieren.', Your_roster_is_empty_add_a: 'Deine Freundesliste ist leer, füge einen neuen Freund ', new_buddy: 'hinzu', is: 'ist', Login_options: 'Anmeldeoptionen', BOSH_url: 'BOSH url', Domain: 'Domain', Resource: 'Ressource', On_login: 'Beim Anmelden', Received_an_unencrypted_message: 'Unverschlüsselte Nachricht empfangen', Sorry_your_buddy_doesnt_provide_any_information: 'Dein Freund stellt leider keine Informationen bereit.', Info_about: 'Info über', Authentication_aborted: 'Authentifizierung abgebrochen.', Authentication_request_received: 'Authentifizierunganfrage empfangen.', Log_in_without_chat: 'Anmelden ohne Chat', Do_you_want_to_display_them: 'Möchtest du sie sehen?', has_come_online: 'ist online gekommen', Unknown_sender: 'Unbekannter Sender', You_received_a_message_from_an_unknown_sender: 'Du hast eine Nachricht von einem unbekannten Sender erhalten' }, es: { Logging_in: 'Por favor, espere...', your_connection_is_unencrypted: 'Su conexión no está cifrada.', your_connection_is_encrypted: 'Su conexión está cifrada.', your_buddy_closed_the_private_connection: 'Su amigo ha cerrado la conexión privada.', start_private: 'Iniciar privado', close_private: 'Cerrar privado', your_buddy_is_verificated: 'Tu amigo está verificado.', you_have_only_a_subscription_in_one_way: 'Sólo tienes una suscripción de un modo.', authentication_query_sent: 'Consulta de verificación enviada.', your_message_wasnt_send_please_end_your_private_conversation: 'Su mensaje no fue enviado. Por favor, termine su conversación privada.', unencrypted_message_received: 'Mensaje no cifrado recibido:', your_message_wasnt_send_because_you_have_no_valid_subscription: 'Su mensaje no se ha enviado, porque usted no tiene suscripción válida.', not_available: 'No disponible', no_connection: 'Sin conexión!', relogin: 'iniciar sesión nuevamente', trying_to_start_private_conversation: 'Intentando iniciar una conversación privada!', Verified: 'Verificado', Unverified: 'No verificado', private_conversation_started: 'se inició una conversación privada.', private_conversation_aborted: 'Conversación privada abortada!', your_buddy_closed_the_private_conversation_you_should_do_the_same: 'Su amigo cerró la conversación privada! Usted debería hacer lo mismo.', conversation_is_now_verified: 'La conversación es ahora verificada.', authentication_failed: 'Fallo la verificación.', your_buddy_is_attempting_to_determine_: 'Tu amigo está tratando de determinar si él o ella está realmente hablando con usted.', to_authenticate_to_your_buddy: 'Para autenticar a su amigo, ', enter_the_answer_and_click_answer: 'introduce la respuesta y haga clic en Contestar.', enter_the_secret: 'especifique el secreto.', Creating_your_private_key_: 'Ahora vamos a crear su clave privada. Esto puede tomar algún tiempo.', Authenticating_a_buddy_helps_: 'Autenticación de un amigo ayuda a garantizar que la persona que está hablando es quien él o ella está diciendo.', How_do_you_want_to_authenticate_your_buddy: '¿Cómo desea autenticar {{bid_name}} (<b>{{bid_jid}}</b>)?', Select_method: 'Escoja un método...', Manual: 'Manual', Question: 'Pregunta', Secret: 'Secreto', To_verify_the_fingerprint_: 'Para verificar la firma digital, póngase en contacto con su amigo a través de algún otro canal autenticado, como el teléfono.', Your_fingerprint: 'Tu firma digital', Buddy_fingerprint: 'firma digital de tu amigo', Close: 'Cerrar', Compared: 'Comparado', To_authenticate_using_a_question_: 'Para autenticar mediante una pregunta, elegir una pregunta cuya respuesta se conoce sólo usted y su amigo.', Ask: 'Preguntar', To_authenticate_pick_a_secret_: 'Para autenticar, elija un secreto conocido sólo por usted y su amigo.', Compare: 'Comparar', Fingerprints: 'Firmas digitales', Authentication: 'Autenticación', Message: 'Mensaje', Add_buddy: 'Añadir amigo', rename_buddy: 'renombrar amigo', delete_buddy: 'eliminar amigo', Login: 'Iniciar Sesión', Username: 'Usuario', Password: 'Contraseña', Cancel: 'Cancelar', Connect: 'Conectar', Type_in_the_full_username_: 'Escriba el usuario completo y un alias opcional.', Alias: 'Alias', Add: 'Añadir', Subscription_request: 'Solicitud de suscripción', You_have_a_request_from: 'Tienes una petición de', Deny: 'Rechazar', Approve: 'Aprobar', Remove_buddy: 'Eliminar amigo', You_are_about_to_remove_: 'Vas a eliminar a {{bid_name}} (<b>{{bid_jid}}</b>) de tu lista de amigos. Todas las conversaciones relacionadas serán cerradas.', Continue_without_chat: 'Continuar', Please_wait: 'Espere por favor', Login_failed: 'Fallo el inicio de sesión', Sorry_we_cant_authentikate_: 'Lo sentimos, no podemos autentificarlo en nuestro servidor de chat. ¿Tal vez la contraseña es incorrecta?', Retry: 'Reintentar', clear_history: 'Borrar el historial', New_message_from: 'Nuevo mensaje de', Should_we_notify_you_: '¿Debemos notificarle sobre nuevos mensajes en el futuro?', Please_accept_: 'Por favor, haga clic en el botón "Permitir" en la parte superior.', dnd: 'No Molestar', Mute: 'Desactivar sonido', Unmute: 'Activar sonido', Subscription: 'Suscripción', both: 'ambos', Status: 'Estado', online: 'en línea', chat: 'chat', away: 'ausente', xa: 'mas ausente', offline: 'desconectado', none: 'nadie', Unknown_instance_tag: 'Etiqueta de instancia desconocida.', Not_one_of_our_latest_keys: 'No de nuestra ultima tecla.', Received_an_unreadable_encrypted_message: 'Se recibió un mensaje cifrado ilegible.', Online: 'En linea', Chatty: 'Hablador', Away: 'Ausente', Extended_away: 'Mas ausente', Offline: 'Desconectado', Friendship_request: 'Solicitud de amistad', Confirm: 'Confirmar', Dismiss: 'Rechazar', Remove: 'Eliminar', Online_help: 'Ayuda en línea', FN: 'Nombre completo ', N: ' ', FAMILY: 'Apellido', GIVEN: 'Nombre', NICKNAME: 'Apodar', URL: 'URL', ADR: 'Dirección', STREET: 'Calle', EXTADD: 'Extendido dirección', LOCALITY: 'Población', REGION: 'Región', PCODE: 'Código postal', CTRY: 'País', TEL: 'Teléfono', NUMBER: 'Número', EMAIL: 'Emilio', USERID: ' ', ORG: 'Organización', ORGNAME: 'Nombre', ORGUNIT: 'Departamento', TITLE: 'Título', ROLE: 'Rol', BDAY: 'Cumpleaños', DESC: 'Descripción', PHOTO: ' ', send_message: 'mandar un texto', get_info: 'obtener información', Settings: 'Ajustes', Priority: 'Prioridad', Save: 'Guardar', User_settings: 'Configuración de usuario', A_fingerprint_: 'La huella digital se utiliza para que puedas estar seguro que la persona con la que estas hablando es quien realmente dice ser', Your_roster_is_empty_add_a: 'Tu lista de amigos esta vacia', new_buddy: 'Nuevo amigo', is: 'es', Login_options: 'Opciones de login', BOSH_url: 'BOSH url', Domain: 'Dominio', Resource: 'Recurso', On_login: 'Iniciar sesión', Received_an_unencrypted_message: 'Recibe un mensaje no cifrado' } }; }(jQuery));
jsxc.lib.js
var jsxc; (function($) { "use strict"; /** * JavaScript Xmpp Chat namespace * * @namespace jsxc */ jsxc = { /** Version of jsxc */ version: '< $ app.version $ >', /** True if i'm the master */ master: false, /** True if the role allocation is finished */ role_allocation: false, /** Timeout for keepalive */ to: null, /** Timeout after normal keepalive starts */ toBusy: null, /** Timeout for notification */ toNotification: null, /** Timeout delay for notification */ toNotificationDelay: 500, /** Interval for keep-alive */ keepalive: null, /** True if last activity was 10 min ago */ restore: false, /** True if restore is complete */ restoreCompleted: false, /** True if login through box */ triggeredFromBox: false, /** True if logout through element click */ triggeredFromElement: false, /** True if logout through logout click */ triggeredFromLogout: false, /** last values which we wrote into localstorage (IE workaround) */ ls: [], /** * storage event is even fired if I write something into storage (IE * workaround) 0: conform, 1: not conform, 2: not shure */ storageNotConform: null, /** Timeout for storageNotConform test */ toSNC: null, /** My bar id */ bid: null, /** Some constants */ CONST: { NOTIFICATION_DEFAULT: 'default', NOTIFICATION_GRANTED: 'granted', NOTIFICATION_DENIED: 'denied', STATUS: [ 'offline', 'dnd', 'xa', 'away', 'chat', 'online' ], SOUNDS: { MSG: 'incomingMessage.wav', CALL: 'Rotary-Phone6.mp3', NOTICE: 'Ping1.mp3' }, REGEX: { JID: new RegExp('\\b[^"&\'\\/:<>@\\s]+@[\\w-_.]+\\b', 'ig'), URL: new RegExp(/((?:https?:\/\/|www\.|([\w\-]+\.[a-zA-Z]{2,3})(?=\b))(?:(?:[\-A-Za-z0-9+&@#\/%?=~_|!:,.;]*\([\-A-Za-z0-9+&@#\/%?=~_|!:,.;]*\)([\-A-Za-z0-9+&@#\/%?=~_|!:,.;]*[\-A-Za-z0-9+&@#\/%=~_|])?)|(?:[\-A-Za-z0-9+&@#\/%?=~_|!:,.;]*[\-A-Za-z0-9+&@#\/%=~_|]))?)/gi) }, NS: { CARBONS: 'urn:xmpp:carbons:2', FORWARD: 'urn:xmpp:forward:0' } }, /** * Parse a unix timestamp and return a formatted time string * * @memberOf jsxc * @param {Object} unixtime * @returns time of day and/or date */ getFormattedTime: function(unixtime) { var msgDate = new Date(parseInt(unixtime)); var date = ('0' + msgDate.getDate()).slice(-2); var month = ('0' + (msgDate.getMonth() + 1)).slice(-2); var year = msgDate.getFullYear(); var hours = ('0' + msgDate.getHours()).slice(-2); var minutes = ('0' + msgDate.getMinutes()).slice(-2); var dateNow = new Date(), time = hours + ':' + minutes; // compare dates only dateNow.setHours(0, 0, 0, 0); msgDate.setHours(0, 0, 0, 0); if (dateNow.getTime() !== msgDate.getTime()) { return date + '.' + month + '.' + year + ' ' + time; } return time; }, /** * Write debug message to console and to log. * * @memberOf jsxc * @param {String} msg Debug message * @param {Object} data * @param {String} Could be warn|error|null */ debug: function(msg, data, level) { if (level) { msg = '[' + level + '] ' + msg; } if (data) { if (jsxc.storage.getItem('debug') === true) { console.log(msg, data); } // try to convert data to string var d; try { // clone html snippet d = $("<span>").prepend($(data).clone()).html(); } catch (err) { try { d = JSON.stringify(data); } catch (err2) { d = 'see js console'; } } jsxc.log = jsxc.log + msg + ': ' + d + '\n'; } else { console.log(msg); jsxc.log = jsxc.log + msg + '\n'; } }, /** * Write warn message. * * @memberOf jsxc * @param {String} msg Warn message * @param {Object} data */ warn: function(msg, data) { jsxc.debug(msg, data, 'WARN'); }, /** * Write error message. * * @memberOf jsxc * @param {String} msg Error message * @param {Object} data */ error: function(msg, data) { jsxc.debug(msg, data, 'ERROR'); }, /** debug log */ log: '', /** * Starts the action * * @memberOf jsxc * @param {object} options */ init: function(options) { if (options) { // override default options $.extend(true, jsxc.options, options); } /** * Getter method for options. Saved options will override default one. * * @param {string} key option key * @returns default or saved option value */ jsxc.options.get = function(key) { var local = jsxc.storage.getUserItem('options') || {}; return local[key] || jsxc.options[key]; }; /** * Setter method for options. Will write into localstorage. * * @param {string} key option key * @param {object} value option value */ jsxc.options.set = function(key, value) { jsxc.storage.updateItem('options', key, value, true); }; jsxc.storageNotConform = jsxc.storage.getItem('storageNotConform'); if (jsxc.storageNotConform === null) { jsxc.storageNotConform = 2; } // detect language var lang; if (jsxc.storage.getItem('lang') !== null) { lang = jsxc.storage.getItem('lang'); } else if (jsxc.options.autoLang && navigator.language) { lang = navigator.language.substr(0, 2); } else { lang = jsxc.options.defaultLang; } // set language jsxc.l = jsxc.l10n.en; $.extend(jsxc.l, jsxc.l10n[lang]); // Check localStorage if (typeof (localStorage) === 'undefined') { jsxc.debug("Browser doesn't support localStorage."); return; } if (jsxc.storage.getItem('debug') === true) { jsxc.options.otr.debug = true; } // Register event listener for the storage event window.addEventListener('storage', jsxc.storage.onStorage, false); var lastActivity = jsxc.storage.getItem('lastActivity') || 0; if ((new Date()).getTime() - lastActivity < jsxc.options.loginTimeout) { jsxc.restore = true; } // Check if we have to establish a new connection if (!jsxc.storage.getItem('rid') || !jsxc.storage.getItem('sid') || !jsxc.restore) { // Looking for a login form if (!jsxc.options.loginForm.form || !(jsxc.el_exists(jsxc.options.loginForm.form) && jsxc.el_exists(jsxc.options.loginForm.jid) && jsxc.el_exists(jsxc.options.loginForm.pass))) { if (jsxc.options.displayRosterMinimized()) { // Show minimized roster jsxc.storage.setUserItem('roster', 'hidden'); jsxc.gui.roster.init(); jsxc.gui.roster.noConnection(); } return; } if (typeof jsxc.options.formFound === 'function') { jsxc.options.formFound.call(); } // create jquery object var form = jsxc.options.loginForm.form = $(jsxc.options.loginForm.form); var events = form.data('events') || { submit: [] }; var submits = []; // save attached submit events and remove them. Will be reattached // in jsxc.submitLoginForm $.each(events.submit, function(index, val) { submits.push(val.handler); }); form.data('submits', submits); form.off('submit'); // Add jsxc login action to form form.submit(function() { var settings = jsxc.prepareLogin(); if (settings !== false && (settings.xmpp.onlogin === "true" || settings.xmpp.onlogin === true)) { jsxc.options.loginForm.triggered = true; jsxc.xmpp.login(); // Trigger submit in jsxc.xmpp.connected() return false; } return true; }); } else { // Restore old connection jsxc.bid = jsxc.jidToBid(jsxc.storage.getItem('jid')); jsxc.gui.init(); // Looking for logout element if (jsxc.options.logoutElement !== null && jsxc.options.logoutElement.length > 0) { jsxc.options.logoutElement.one('click', function() { jsxc.options.logoutElement = $(this); jsxc.triggeredFromLogout = true; return jsxc.xmpp.logout(); }); } if (typeof (jsxc.storage.getItem('alive')) === 'undefined' || !jsxc.restore) { jsxc.onMaster(); } else { jsxc.checkMaster(); } } }, /** * Load settings and prepare jid. * * @memberOf jsxc * @returns Loaded settings */ prepareLogin: function() { var username = $(jsxc.options.loginForm.jid).val(); var password = $(jsxc.options.loginForm.pass).val(); if (typeof jsxc.options.loadSettings !== 'function') { jsxc.error('No loadSettings function given. Abort.'); return; } jsxc.gui.showWaitAlert(jsxc.l.Logging_in); var settings = jsxc.options.loadSettings.call(this, username, password); if (settings === false || settings === null || typeof settings === 'undefined') { jsxc.warn('No settings provided'); return false; } if (typeof settings.xmpp.username === 'string') { username = settings.xmpp.username; } var resource = (settings.xmpp.resource) ? '/' + settings.xmpp.resource : ''; var domain = settings.xmpp.domain; var jid; if (username.match(/@(.*)$/)) { jid = (username.match(/\/(.*)$/)) ? username : username + resource; } else { jid = username + '@' + domain + resource; } if (typeof jsxc.options.loginForm.preJid === 'function') { jid = jsxc.options.loginForm.preJid(jid); } jsxc.bid = jsxc.jidToBid(jid); settings.xmpp.username = jid.split('@')[0]; settings.xmpp.domain = jid.split('@')[1].split('/')[0]; settings.xmpp.resource = jid.split('@')[1].split('/')[1] || ""; $.each(settings, function(key, val) { jsxc.options.set(key, val); }); jsxc.options.xmpp.jid = jid; jsxc.options.xmpp.password = password; return settings; }, /** * Called if the script is a slave */ onSlave: function() { jsxc.debug('I am the slave.'); jsxc.role_allocation = true; jsxc.restoreRoster(); jsxc.restoreWindows(); jsxc.restoreCompleted = true; $(document).trigger('restoreCompleted.jsxc'); }, /** * Called if the script is the master */ onMaster: function() { jsxc.debug('I am master.'); jsxc.master = true; // Init local storage jsxc.storage.setItem('alive', 0); jsxc.storage.setItem('alive_busy', 0); if (!jsxc.storage.getUserItem('windowlist')) { jsxc.storage.setUserItem('windowlist', []); } // Sending keepalive signal jsxc.startKeepAlive(); if (jsxc.options.get('otr').enable) { // create or load DSA key and call _onMaster jsxc.otr.createDSA(); } else { jsxc._onMaster(); } }, /** * Second half of the onMaster routine */ _onMaster: function() { // create otr objects, if we lost the master if (jsxc.role_allocation) { $.each(jsxc.storage.getUserItem('windowlist'), function(index, val) { jsxc.otr.create(val); }); } jsxc.role_allocation = true; if (jsxc.restore && !jsxc.restoreCompleted) { jsxc.restoreRoster(); jsxc.restoreWindows(); jsxc.restoreCompleted = true; $(document).trigger('restoreCompleted.jsxc'); } // Prepare notifications if (jsxc.restore) { var noti = jsxc.storage.getUserItem('notification') || 2; if (jsxc.options.notification && noti > 0 && jsxc.notification.hasSupport()) { if (jsxc.notification.hasPermission()) { jsxc.notification.init(); } else { jsxc.notification.prepareRequest(); } } else { // No support => disable jsxc.options.notification = false; } } $(document).on('connectionReady.jsxc', function() { jsxc.gui.updateAvatar($('#jsxc_avatar'), jsxc.storage.getItem('jid'), 'own'); }); jsxc.xmpp.login(); }, /** * Checks if there is a master */ checkMaster: function() { jsxc.debug('check master'); jsxc.to = window.setTimeout(jsxc.onMaster, 1000); jsxc.storage.ink('alive'); }, /** * Start sending keep-alive signal */ startKeepAlive: function() { jsxc.keepalive = window.setInterval(jsxc.keepAlive, jsxc.options.timeout - 1000); }, /** * Sends the keep-alive signal to signal that the master is still there. */ keepAlive: function() { jsxc.storage.ink('alive'); if (jsxc.role_allocation) { jsxc.storage.setItem('lastActivity', (new Date()).getTime()); } }, /** * Send one keep-alive signal with higher timeout, and than resume with * normal signal */ keepBusyAlive: function() { if (jsxc.toBusy) { window.clearTimeout(jsxc.toBusy); } if (jsxc.keepalive) { window.clearInterval(jsxc.keepalive); } jsxc.storage.ink('alive_busy'); jsxc.toBusy = window.setTimeout(jsxc.startKeepAlive, jsxc.options.busyTimeout - 1000); }, /** * Generates a random integer number between 0 and max * * @param {Integer} max * @return {Integer} random integer between 0 and max */ random: function(max) { return Math.floor(Math.random() * max); }, /** * Checks if there is a element with the given selector * * @param {String} selector jQuery selector * @return {Boolean} */ el_exists: function(selector) { return $(selector).length > 0; }, /** * Creates a CSS compatible string from a JID * * @param {type} jid Valid Jabber ID * @returns {String} css Compatible string */ jidToCid: function(jid) { jsxc.warn('jsxc.jidToCid is deprecated!'); var cid = Strophe.getBareJidFromJid(jid).replace('@', '-').replace(/\./g, '-').toLowerCase(); return cid; }, /** * Create comparable bar jid. * * @memberOf jsxc * @param jid * @returns comparable bar jid */ jidToBid: function(jid) { return Strophe.getBareJidFromJid(jid).toLowerCase(); }, /** * Restore roster */ restoreRoster: function() { var buddies = jsxc.storage.getUserItem('buddylist'); if (!buddies || buddies.length === 0) { jsxc.debug('No saved buddylist.'); jsxc.gui.roster.empty(); return; } $.each(buddies, function(index, value) { jsxc.gui.roster.add(value); }); $(document).trigger('cloaded.roster.jsxc'); }, /** * Restore all windows */ restoreWindows: function() { var windows = jsxc.storage.getUserItem('windowlist'); if (windows === null) { return; } $.each(windows, function(index, bid) { var window = jsxc.storage.getUserItem('window', bid); if (!window) { jsxc.debug('Associated window-element is missing: ' + bid); return true; } jsxc.gui.window.init(bid); if (!window.minimize) { jsxc.gui.window.show(bid); } else { jsxc.gui.window.hide(bid); } jsxc.gui.window.setText(bid, window.text); }); }, /** * This method submits the specified login form. */ submitLoginForm: function() { var form = jsxc.options.loginForm.form.off('submit'); // Attach original events var submits = form.data('submits') || []; $.each(submits, function(index, val) { form.submit(val); }); if (form.find('#submit').length > 0) { form.find('#submit').click(); } else { form.submit(); } }, /** * Escapes some characters to HTML character */ escapeHTML: function(text) { text = text.replace(/&amp;/g, '&').replace(/&lt;/g, '<').replace(/&gt;/g, '>'); return text.replace(/&/g, '&amp;').replace(/</g, '&lt;').replace(/>/g, '&gt;'); }, /** * Removes all html tags. * * @memberOf jsxc * @param text * @returns stripped text */ removeHTML: function(text) { return $('<span>').html(text).text(); }, /** * Executes only one of the given events * * @param {string} obj.key event name * @param {function} obj.value function to execute * @returns {string} namespace of all events */ switchEvents: function(obj) { var ns = Math.random().toString(36).substr(2, 12); var self = this; $.each(obj, function(key, val) { $(document).one(key + '.' + ns, function() { $(document).off('.' + ns); val.apply(self, arguments); }); }); return ns; }, /** * Checks if tab is hidden. * * @returns {boolean} True if tab is hidden */ isHidden: function() { var hidden = false; if (typeof document.hidden !== 'undefined') { hidden = document.hidden; } else if (typeof document.webkitHidden !== 'undefined') { hidden = document.webkitHidden; } else if (typeof document.mozHidden !== 'undefined') { hidden = document.mozHidden; } else if (typeof document.msHidden !== 'undefined') { hidden = document.msHidden; } // handle multiple tabs if (hidden && jsxc.master) { jsxc.storage.ink('hidden', 0); } else if (!hidden && !jsxc.master) { jsxc.storage.ink('hidden'); } return hidden; }, /** * Replace %%tokens%% with correct translation. * * @param {String} text Given text * @returns {String} Translated string */ translate: function(text) { return text.replace(/%%([a-zA-Z0-9_-}{ .!,?/'@]+)%%/g, function(s, key) { var k = key.replace(/ /gi, '_').replace(/[.!,?/'@]/g, ''); if (!jsxc.l[k]) { jsxc.warn('No translation for: ' + k); } return jsxc.l[k] || key.replace(/_/g, ' '); }); }, /** * Executes the given function in jsxc namespace. * * @memberOf jsxc * @param {string} fnName Function name * @param {array} fnParams Function parameters * @returns Function return value */ exec: function(fnName, fnParams) { var fnList = fnName.split('.'); var fn = jsxc[fnList[0]]; var i; for (i = 1; i < fnList.length; i++) { fn = fn[fnList[i]]; } if (typeof fn === 'function') { return fn.apply(null, fnParams); } } }; /** * Set some options for the chat. * * @namespace jsxc.options */ jsxc.options = { /** name of container application (e.g. owncloud or SOGo) */ app_name: 'web applications', /** Timeout for the keepalive signal */ timeout: 3000, /** Timeout for the keepalive signal if the master is busy */ busyTimeout: 15000, /** OTR options */ otr: { enable: true, ERROR_START_AKE: false, debug: false, SEND_WHITESPACE_TAG: true, WHITESPACE_START_AKE: true }, /** xmpp options */ xmpp: { url: null, jid: null, domain: null, password: null, overwrite: false, onlogin: true }, /** default xmpp priorities */ priority: { online: 0, chat: 0, away: 0, xa: 0, dnd: 0 }, /** If all 3 properties are set, the login form is used */ loginForm: { /** jquery object from form */ form: null, /** jquery object from input element which contains the jid */ jid: null, /** jquery object from input element which contains the password */ pass: null, /** manipulate JID from input element */ preJid: function(jid) { return jid; }, /** * Action after connected: submit [String] Submit form, false [boolean] * Do nothing, continue [String] Start chat */ onConnected: 'submit', /** * Action after auth fail: submit [String] Submit form, false [boolean] * Do nothing, ask [String] Show auth fail dialog */ onAuthFail: 'submit' }, /** jquery object from logout element */ logoutElement: null, /** How many messages should be logged? */ numberOfMsg: 10, /** Default language */ defaultLang: 'en', /** auto language detection */ autoLang: true, /** Place for roster */ rosterAppend: 'body', /** Should we use the HTML5 notification API? */ notification: true, /** duration for notification */ popupDuration: 6000, /** Absolute path root of JSXC installation */ root: '', /** Timeout for restore in ms */ loginTimeout: 1000 * 60 * 10, /** * This function decides wether the roster will be displayed or not if no * connection is found. */ displayRosterMinimized: function() { return false; }, /** Set to true if you want to hide offline buddies. */ hideOffline: false, /** Mute notification sound? */ muteNotification: false, /** * If no avatar is found, this function is called. * * @param jid Jid of that user. * @this {jQuery} Elements to update with probable .jsxc_avatar elements */ defaultAvatar: function() { }, /** * Returns permanent saved settings and overwrite default jsxc.options. * * @memberOf jsxc.options * @param username String username * @param password String password * @returns {object} at least xmpp.url */ loadSettings: function() { }, /** * Call this function to save user settings permanent. * * @memberOf jsxc.options * @param data Holds all data as key/value * @returns {boolean} false if function failes */ saveSettinsPermanent: function() { }, carbons: { /** Enable carbon copies? */ enable: false } }; /** * Handle functions for chat window's and buddylist * * @namespace jsxc.gui */ jsxc.gui = { /** Smilie token to file mapping */ emotions: [ [ 'O:-) O:)', 'angel' ], [ '>:-( >:( &gt;:-( &gt;:(', 'angry' ], [ ':-) :)', 'smile' ], [ ':-D :D', 'grin' ], [ ':-( :(', 'sad' ], [ ';-) ;)', 'wink' ], [ ':-P :P', 'tonguesmile' ], [ '=-O', 'surprised' ], [ ':kiss: :-*', 'kiss' ], [ '8-) :cool:', 'sunglassess' ], [ ':\'-( :\'( :&amp;apos;-(', 'crysad' ], [ ':-/', 'doubt' ], [ ':-X :X', 'zip' ], [ ':yes:', 'thumbsup' ], [ ':no:', 'thumbsdown' ], [ ':beer:', 'beer' ], [ ':devil:', 'devil' ], [ ':kiss: :kissing:', 'kissing' ], [ '@->-- :rose: @-&gt;--', 'rose' ], [ ':music:', 'music' ], [ ':love:', 'love' ], [ ':zzz:', 'tired' ] ], /** * Different uri query actions as defined in XEP-0147. * * @namespace jsxc.gui.queryActions */ queryActions: { /** xmpp:JID?message[;body=TEXT] */ message: function(jid, params) { var win = jsxc.gui.window.open(jsxc.jidToBid(jid)); if (params && typeof params.body === 'string') { win.find('.jsxc_textinput').val(params.body); } }, /** xmpp:JID?remove */ remove: function(jid) { jsxc.gui.showRemoveDialog(jsxc.jidToBid(jid)); }, /** xmpp:JID?subscribe[;name=NAME] */ subscribe: function(jid, params) { jsxc.gui.showContactDialog(jid); if (params && typeof params.name) { $('#jsxc_alias').val(params.name); } }, /** xmpp:JID?vcard */ vcard: function(jid) { jsxc.gui.showVcard(jid); } }, /** * Creates application skeleton. * * @memberOf jsxc.gui */ init: function() { $('body').append($(jsxc.gui.template.get('windowList'))); $(window).resize(jsxc.gui.updateWindowListSB); $('#jsxc_windowList').resize(jsxc.gui.updateWindowListSB); $('#jsxc_windowListSB .jsxc_scrollLeft').click(function() { jsxc.gui.scrollWindowListBy(-200); }); $('#jsxc_windowListSB .jsxc_scrollRight').click(function() { jsxc.gui.scrollWindowListBy(200); }); $('#jsxc_windowList').on('wheel', function(ev) { if ($('#jsxc_windowList').data('isOver')) { jsxc.gui.scrollWindowListBy((ev.originalEvent.wheelDelta > 0) ? 200 : -200); } }); jsxc.gui.tooltip('#jsxc_windowList'); if (!jsxc.el_exists('#jsxc_roster')) { jsxc.gui.roster.init(); } // prepare regexp for emotions $.each(jsxc.gui.emotions, function(i, val) { // escape characters var reg = val[0].replace(/(\/|\||\*|\.|\+|\?|\^|\$|\(|\)|\[|\]|\{|\})/g, '\\$1'); reg = '(' + reg.split(' ').join('|') + ')'; jsxc.gui.emotions[i][2] = new RegExp(reg, 'g'); }); // We need this often, so we creates some template jquery objects jsxc.gui.windowTemplate = $(jsxc.gui.template.get('chatWindow')); jsxc.gui.buddyTemplate = $(jsxc.gui.template.get('rosterBuddy')); }, /** * Init tooltip plugin for given jQuery selector. * * @param {String} selector jQuery selector * @memberOf jsxc.gui */ tooltip: function(selector) { $(selector).tooltip({ show: { delay: 600 }, content: function() { return $(this).attr('title').replace(/\n/g, '<br />'); } }); }, /** * Updates Information in roster and chatbar * * @param {String} bid bar jid */ update: function(bid) { var data = jsxc.storage.getUserItem('buddy', bid); if (!data) { jsxc.debug('No data for ' + bid); return; } var ri = jsxc.gui.roster.getItem(bid); // roster item from user var we = jsxc.gui.window.get(bid); // window element from user var ue = ri.add(we); // both var spot = $('.jsxc_spot[data-bid="' + bid + '"]'); // Attach data to corresponding roster item ri.data(data); // Add online status ue.add(spot).removeClass('jsxc_' + jsxc.CONST.STATUS.join(' jsxc_')).addClass('jsxc_' + jsxc.CONST.STATUS[data.status]); // Change name and add title ue.find('.jsxc_name').add(spot).text(data.name).attr('title', jsxc.l.is + ' ' + jsxc.CONST.STATUS[data.status]); // Update gui according to encryption state switch (data.msgstate) { case 0: we.find('.jsxc_transfer').removeClass('jsxc_enc jsxc_fin').attr('title', jsxc.l.your_connection_is_unencrypted); we.find('.jsxc_settings .jsxc_verification').addClass('jsxc_disabled'); we.find('.jsxc_settings .jsxc_transfer').text(jsxc.l.start_private); break; case 1: we.find('.jsxc_transfer').addClass('jsxc_enc').attr('title', jsxc.l.your_connection_is_encrypted); we.find('.jsxc_settings .jsxc_verification').removeClass('jsxc_disabled'); we.find('.jsxc_settings .jsxc_transfer').text(jsxc.l.close_private); break; case 2: we.find('.jsxc_settings .jsxc_verification').addClass('jsxc_disabled'); we.find('.jsxc_transfer').removeClass('jsxc_enc').addClass('jsxc_fin').attr('title', jsxc.l.your_buddy_closed_the_private_connection); we.find('.jsxc_settings .jsxc_transfer').text(jsxc.l.close_private); break; } // update gui according to verification state if (data.trust) { we.find('.jsxc_transfer').addClass('jsxc_trust').attr('title', jsxc.l.your_buddy_is_verificated); } else { we.find('.jsxc_transfer').removeClass('jsxc_trust'); } // update gui according to subscription state if (data.sub && data.sub !== 'both') { ue.addClass('jsxc_oneway'); } else { ue.removeClass('jsxc_oneway'); } var info = '<b>' + Strophe.getBareJidFromJid(data.jid) + '</b>\n'; info += jsxc.translate('%%Subscription%%: %%' + data.sub + '%%\n'); info += jsxc.translate('%%Status%%: %%' + jsxc.CONST.STATUS[data.status] + '%%'); ri.find('.jsxc_name').attr('title', info); if (data.avatar && data.avatar.length > 0) { jsxc.gui.updateAvatar(ue, data.jid, data.avatar); } else { jsxc.options.defaultAvatar.call(ue, data.jid); } }, /** * Update avatar on all given elements. * * @memberOf jsxc.gui * @param {jQuery} el Elements with subelement .jsxc_avatar * @param {string} jid Jid * @param {string} aid Avatar id (sha1 hash of image) */ updateAvatar: function(el, jid, aid) { if (typeof aid === 'undefined') { if (typeof jsxc.options.defaultAvatar === 'function') { jsxc.options.defaultAvatar.call(el, jid); } return; } var avatarSrc = jsxc.storage.getUserItem('avatar', aid); var setAvatar = function(src) { if (src === 0 || src === '0') { jsxc.options.defaultAvatar.call(el, jid); return; } el.find('.jsxc_avatar').removeAttr('style'); el.find('.jsxc_avatar').css({ 'background-image': 'url(' + src + ')', 'text-indent': '999px' }); }; if (avatarSrc !== null) { setAvatar(avatarSrc); } else { jsxc.xmpp.conn.vcard.get(function(stanza) { jsxc.debug('vCard', stanza); var vCard = $(stanza).find("vCard > PHOTO"); var src; if (vCard.length === 0) { jsxc.debug('No photo provided'); src = '0'; } else if (vCard.find('EXTVAL').length > 0) { src = vCard.find('EXTVAL').text(); } else { var img = vCard.find('BINVAL').text(); var type = vCard.find('TYPE').text(); src = 'data:' + type + ';base64,' + img; } // concat chunks src = src.replace(/[\t\r\n\f]/gi, ''); jsxc.storage.setUserItem('avatar', aid, src); setAvatar(src); }, Strophe.getBareJidFromJid(jid), function(msg) { jsxc.warn('Could not load vcard.', msg); jsxc.storage.setUserItem('avatar', aid, 0); setAvatar(0); }); } }, /** * Updates scrollbar handlers. * * @memberOf jsxc.gui */ updateWindowListSB: function() { if ($('#jsxc_windowList>ul').width() > $('#jsxc_windowList').width()) { $('#jsxc_windowListSB > div').removeClass('jsxc_disabled'); } else { $('#jsxc_windowListSB > div').addClass('jsxc_disabled'); $('#jsxc_windowList>ul').css('right', '0px'); } }, /** * Scroll window list by offset. * * @memberOf jsxc.gui * @param offset */ scrollWindowListBy: function(offset) { var scrollWidth = $('#jsxc_windowList>ul').width(); var width = $('#jsxc_windowList').width(); var el = $('#jsxc_windowList>ul'); var right = parseInt(el.css('right')) - offset; var padding = $("#jsxc_windowListSB").width(); if (scrollWidth < width) { return; } if (right > 0) { right = 0; } if (right < width - scrollWidth - padding) { right = width - scrollWidth - padding; } el.css('right', right + 'px'); }, /** * Returns the window element * * @param {String} bid * @returns {jquery} jQuery object of the window element */ getWindow: function(bid) { jsxc.warn('jsxc.gui.getWindow is deprecated!'); return jsxc.gui.window.get(bid); }, /** * Toggle list with timeout, like menu or settings * * @memberof jsxc.gui */ toggleList: function() { var self = $(this); self.disableSelection(); var ul = self.find('ul'); var slideUp = null; slideUp = function() { ul.slideUp({ complete: function() { self.removeClass('jsxc_opened'); } }); $('body').off('click', null, slideUp); }; $(this).click(function() { if (ul.is(":hidden")) { // hide other lists $('body').click(); $('body').one('click', slideUp); } else { $('body').off('click', null, slideUp); } ul.slideToggle(); window.clearTimeout(ul.data('timer')); self.toggleClass('jsxc_opened'); return false; }).mouseleave(function() { ul.data('timer', window.setTimeout(slideUp, 2000)); }).mouseenter(function() { window.clearTimeout(ul.data('timer')); }); }, /** * Creates and show loginbox */ showLoginBox: function() { // Set focus to password field $(document).on("complete.dialog.jsxc", function() { $('#jsxc_password').focus(); }); jsxc.gui.dialog.open(jsxc.gui.template.get('loginBox')); $('#jsxc_dialog').find('form').submit(function() { $(this).find('input[type=submit]').prop('disabled', true); jsxc.options.loginForm.form = $(this); jsxc.options.loginForm.jid = $(this).find('#jsxc_username'); jsxc.options.loginForm.pass = $(this).find('#jsxc_password'); var settings = jsxc.prepareLogin(); jsxc.triggeredFromBox = true; jsxc.options.loginForm.triggered = false; if (settings === false) { jsxc.gui.showAuthFail(); } else { jsxc.xmpp.login(); } return false; }); }, /** * Creates and show the fingerprint dialog * * @param {String} bid */ showFingerprints: function(bid) { jsxc.gui.dialog.open(jsxc.gui.template.get('fingerprintsDialog', bid)); }, /** * Creates and show the verification dialog * * @param {String} bid */ showVerification: function(bid) { // Check if there is a open dialog if ($('#jsxc_dialog').length > 0) { setTimeout(function() { jsxc.gui.showVerification(bid); }, 3000); return; } // verification only possible if the connection is encrypted if (jsxc.storage.getUserItem('buddy', bid).msgstate !== OTR.CONST.MSGSTATE_ENCRYPTED) { jsxc.warn('Connection not encrypted'); return; } jsxc.gui.dialog.open(jsxc.gui.template.get('authenticationDialog', bid)); // Add handler $('#jsxc_dialog > div:gt(0)').hide(); $('#jsxc_dialog select').change(function() { $('#jsxc_dialog > div:gt(0)').hide(); $('#jsxc_dialog > div:eq(' + $(this).prop('selectedIndex') + ')').slideDown({ complete: function() { jsxc.gui.dialog.resize(); } }); }); // Manual $('#jsxc_dialog > div:eq(1) a.creation').click(function() { if (jsxc.master) { jsxc.otr.objects[bid].trust = true; } jsxc.storage.updateUserItem('buddy', bid, 'trust', true); jsxc.gui.dialog.close(); jsxc.storage.updateUserItem('buddy', bid, 'trust', true); jsxc.gui.window.postMessage(bid, 'sys', jsxc.l.conversation_is_now_verified); jsxc.gui.update(bid); }); // Question $('#jsxc_dialog > div:eq(2) a.creation').click(function() { var div = $('#jsxc_dialog > div:eq(2)'); var sec = div.find('#jsxc_secret2').val(); var quest = div.find('#jsxc_quest').val(); if (sec === '' || quest === '') { // Add information for the user which form is missing div.find('input[value=""]').addClass('jsxc_invalid').keyup(function() { if ($(this).val().match(/.*/)) { $(this).removeClass('jsxc_invalid'); } }); return; } if (jsxc.master) { jsxc.otr.sendSmpReq(bid, sec, quest); } else { jsxc.storage.setUserItem('smp_' + bid, { sec: sec, quest: quest }); } jsxc.gui.dialog.close(); jsxc.gui.window.postMessage(bid, 'sys', jsxc.l.authentication_query_sent); }); // Secret $('#jsxc_dialog > div:eq(3) .creation').click(function() { var div = $('#jsxc_dialog > div:eq(3)'); var sec = div.find('#jsxc_secret').val(); if (sec === '') { // Add information for the user which form is missing div.find('#jsxc_secret').addClass('jsxc_invalid').keyup(function() { if ($(this).val().match(/.*/)) { $(this).removeClass('jsxc_invalid'); } }); return; } if (jsxc.master) { jsxc.otr.sendSmpReq(bid, sec); } else { jsxc.storage.setUserItem('smp_' + bid, { sec: sec, quest: null }); } jsxc.gui.dialog.close(); jsxc.gui.window.postMessage(bid, 'sys', jsxc.l.authentication_query_sent); }); }, /** * Create and show approve dialog * * @param {type} from valid jid */ showApproveDialog: function(from) { jsxc.gui.dialog.open(jsxc.gui.template.get('approveDialog'), { 'noClose': true }); $('#jsxc_dialog .jsxc_their_jid').text(Strophe.getBareJidFromJid(from)); $('#jsxc_dialog .jsxc_deny').click(function(ev) { ev.stopPropagation(); jsxc.xmpp.resFriendReq(from, false); jsxc.gui.dialog.close(); }); $('#jsxc_dialog .jsxc_approve').click(function(ev) { ev.stopPropagation(); var data = jsxc.storage.getUserItem('buddy', jsxc.jidToBid(from)); jsxc.xmpp.resFriendReq(from, true); // If friendship is not mutual show contact dialog if (!data || data.sub === 'from') { $(document).one('close.dialog.jsxc', function() { jsxc.gui.showContactDialog(from); }); } jsxc.gui.dialog.close(); }); }, /** * Create and show dialog to add a buddy * * @param {string} [username] jabber id */ showContactDialog: function(username) { jsxc.gui.dialog.open(jsxc.gui.template.get('contactDialog')); // If we got a friendship request, we would display the username in our // response if (username) { $('#jsxc_username').val(username); } $('#jsxc_dialog form').submit(function() { var username = $('#jsxc_username').val(); var alias = $('#jsxc_alias').val(); if (!username.match(/@(.*)$/)) { username += '@' + Strophe.getDomainFromJid(jsxc.storage.getItem('jid')); } // Check if the username is valid if (!username || !username.match(jsxc.CONST.REGEX.JID)) { // Add notification $('#jsxc_username').addClass('jsxc_invalid').keyup(function() { if ($(this).val().match(jsxc.CONST.REGEX.JID)) { $(this).removeClass('jsxc_invalid'); } }); return false; } jsxc.xmpp.addBuddy(username, alias); jsxc.gui.dialog.close(); return false; }); }, /** * Create and show dialog to remove a buddy * * @param {type} bid * @returns {undefined} */ showRemoveDialog: function(bid) { jsxc.gui.dialog.open(jsxc.gui.template.get('removeDialog', bid)); var data = jsxc.storage.getUserItem('buddy', bid); $('#jsxc_dialog .creation').click(function(ev) { ev.stopPropagation(); if (jsxc.master) { jsxc.xmpp.removeBuddy(data.jid); } else { // inform master jsxc.storage.setUserItem('deletebuddy', bid, { jid: data.jid }); } jsxc.gui.dialog.close(); }); }, /** * Create and show a wait dialog * * @param {type} msg message to display to the user * @returns {undefined} */ showWaitAlert: function(msg) { jsxc.gui.dialog.open(jsxc.gui.template.get('waitAlert', null, msg), { 'noClose': true }); }, /** * Create and show a wait dialog * * @param {type} msg message to display to the user * @returns {undefined} */ showAlert: function(msg) { jsxc.gui.dialog.open(jsxc.gui.template.get('alert', null, msg)); }, /** * Create and show a auth fail dialog * * @returns {undefined} */ showAuthFail: function() { jsxc.gui.dialog.open(jsxc.gui.template.get('authFailDialog')); if (jsxc.options.loginForm.triggered !== false) { $('#jsxc_dialog .jsxc_cancel').hide(); } $('#jsxc_dialog .creation').click(function() { jsxc.gui.dialog.close(); }); $('#jsxc_dialog .jsxc_cancel').click(function() { jsxc.submitLoginForm(); }); }, /** * Create and show a confirm dialog * * @param {String} msg Message * @param {function} confirm * @param {function} dismiss * @returns {undefined} */ showConfirmDialog: function(msg, confirm, dismiss) { jsxc.gui.dialog.open(jsxc.gui.template.get('confirmDialog', null, msg), { noClose: true }); if (confirm) { $('#jsxc_dialog .creation').click(confirm); } if (dismiss) { $('#jsxc_dialog .jsxc_cancel').click(dismiss); } }, /** * Show about dialog. * * @memberOf jsxc.gui */ showAboutDialog: function() { jsxc.gui.dialog.open(jsxc.gui.template.get('aboutDialog')); $('#jsxc_dialog .jsxc_debuglog').click(function() { jsxc.gui.showDebugLog(); }); }, /** * Show debug log. * * @memberOf jsxc.gui */ showDebugLog: function() { var userInfo = '<h3>User information</h3>'; if (navigator) { var key; for (key in navigator) { if (navigator.hasOwnProperty(key) && typeof navigator[key] === 'string') { userInfo += '<b>' + key + ':</b> ' + navigator[key] + '<br />'; } } } if (window.screen) { userInfo += '<b>Height:</b> ' + window.screen.height + '<br />'; userInfo += '<b>Width:</b> ' + window.screen.width + '<br />'; } userInfo += '<b>jsxc version:</b> ' + jsxc.version + '<br />'; jsxc.gui.dialog.open('<div class="jsxc_log">' + userInfo + '<h3>Log</h3><pre>' + jsxc.escapeHTML(jsxc.log) + '</pre></div>'); }, /** * Show vCard of user with the given bar jid. * * @memberOf jsxc.gui * @param {String} jid */ showVcard: function(jid) { var bid = jsxc.jidToBid(jid); jsxc.gui.dialog.open(jsxc.gui.template.get('vCard', bid)); var data = jsxc.storage.getUserItem('buddy', bid); if (data) { // Display resources and corresponding information var i, j, res, identities, identity = null, cap, client; for (i = 0; i < data.res.length; i++) { res = data.res[i]; identities = []; cap = jsxc.xmpp.getCapabilitiesByJid(bid + '/' + res); if (cap !== null && cap.identities !== null) { identities = cap.identities; } client = ''; for (j = 0; j < identities.length; j++) { identity = identities[j]; if (identity.category === 'client') { if (client !== '') { client += ',\n'; } client += identity.name + ' (' + identity.type + ')'; } } var status = jsxc.storage.getUserItem('res', bid)[res]; $('#jsxc_dialog ul.jsxc_vCard').append('<li class="jsxc_sep"><strong>' + jsxc.translate('%%Resource%%') + ':</strong> ' + res + '</li>'); $('#jsxc_dialog ul.jsxc_vCard').append('<li><strong>' + jsxc.translate('%%Client%%') + ':</strong> ' + client + '</li>'); $('#jsxc_dialog ul.jsxc_vCard').append('<li>' + jsxc.translate('<strong>%%Status%%:</strong> %%' + jsxc.CONST.STATUS[status] + '%%') + '</li>'); } } var printProp = function(el, depth) { var content = ''; el.each(function() { var item = $(this); var children = $(this).children(); content += '<li>'; var prop = jsxc.translate('%%' + item[0].tagName + '%%'); if (prop !== ' ') { content += '<strong>' + prop + ':</strong> '; } if (item[0].tagName === 'PHOTO') { } else if (children.length > 0) { content += '<ul>'; content += printProp(children, depth + 1); content += '</ul>'; } else if (item.text() !== '') { content += jsxc.escapeHTML(item.text()); } content += '</li>'; if (depth === 0 && $('#jsxc_dialog ul.jsxc_vCard').length > 0) { if ($('#jsxc_dialog ul.jsxc_vCard li.jsxc_sep:first').length > 0) { $('#jsxc_dialog ul.jsxc_vCard li.jsxc_sep:first').before(content); } else { $('#jsxc_dialog ul.jsxc_vCard').append(content); } content = ''; } }); if (depth > 0) { return content; } }; var failedToLoad = function() { if ($('#jsxc_dialog ul.jsxc_vCard').length === 0) { return; } $('#jsxc_dialog p').remove(); var content = '<p>'; content += jsxc.translate('%%Sorry, your buddy doesn\'t provide any information.%%'); content += '</p>'; $('#jsxc_dialog').append(content); }; jsxc.xmpp.loadVcard(bid, function(stanza) { if ($('#jsxc_dialog ul.jsxc_vCard').length === 0) { return; } $('#jsxc_dialog p').remove(); var photo = $(stanza).find("vCard > PHOTO"); if (photo.length > 0) { var img = photo.find('BINVAL').text(); var type = photo.find('TYPE').text(); var src = 'data:' + type + ';base64,' + img; if (photo.find('EXTVAL').length > 0) { src = photo.find('EXTVAL').text(); } // concat chunks src = src.replace(/[\t\r\n\f]/gi, ''); var img_el = $('<img class="jsxc_vCard" alt="avatar" />'); img_el.attr('src', src); $('#jsxc_dialog h3').before(img_el); } if ($(stanza).find('vCard').length === 0 || ($(stanza).find('vcard > *').length === 1 && photo.length === 1)) { failedToLoad(); return; } printProp($(stanza).find('vcard > *'), 0); }, failedToLoad); }, showSettings: function() { jsxc.gui.dialog.open(jsxc.gui.template.get('settings')); if (jsxc.options.get('xmpp').overwrite === 'false' || jsxc.options.get('xmpp').overwrite === false) { $('.jsxc_fieldsetXmpp').hide(); } $('#jsxc_dialog form').each(function() { var self = $(this); self.find('input[type!="submit"]').each(function() { var id = this.id.split("-"); var prop = id[0]; var key = id[1]; var type = this.type; var data = jsxc.options.get(prop); if (data && typeof data[key] !== 'undefined') { if (type === 'checkbox') { if (data[key] !== 'false' && data[key] !== false) { this.checked = 'checked'; } } else { $(this).val(data[key]); } } }); }); $('#jsxc_dialog form').submit(function() { var self = $(this); var data = {}; self.find('input[type!="submit"]').each(function() { var id = this.id.split("-"); var prop = id[0]; var key = id[1]; var val; var type = this.type; if (type === 'checkbox') { val = this.checked; } else { val = $(this).val(); } if (!data[prop]) { data[prop] = {}; } data[prop][key] = val; }); $.each(data, function(key, val) { jsxc.options.set(key, val); }); var err = jsxc.options.saveSettinsPermanent.call(this, data); if (typeof self.attr('data-onsubmit') === 'string') { jsxc.exec(self.attr('data-onsubmit'), [ err ]); } setTimeout(function() { self.find('input[type="submit"]').effect('highlight', { color: (err) ? 'green' : 'red' }, 4000); }, 200); return false; }); }, /** * Show prompt for notification permission. * * @memberOf jsxc.gui */ showRequestNotification: function() { jsxc.gui.showConfirmDialog(jsxc.translate("%%Should we notify you_%%"), function() { jsxc.gui.dialog.open(jsxc.gui.template.get('pleaseAccept'), { noClose: true }); jsxc.notification.requestPermission(); }, function() { $(document).trigger('notificationfailure.jsxc'); }); }, showUnknownSender: function(bid) { jsxc.gui.showConfirmDialog(jsxc.translate('%%You_received_a_message_from_an_unknown_sender%% (' + bid + '). %%Do_you_want_to_display_them%%'), function() { jsxc.gui.dialog.close(); jsxc.storage.saveBuddy(bid, { jid: bid, name: bid, status: 0, sub: 'none', res: [] }); jsxc.gui.window.open(bid); }, function() { // reset state jsxc.storage.removeUserItem('chat', bid); }); }, /** * Change own presence to pres. * * @memberOf jsxc.gui * @param pres {CONST.STATUS} New presence state * @param external {boolean} True if triggered from other tab. */ changePresence: function(pres, external) { if (external !== true) { jsxc.storage.setUserItem('presence', pres); } if (jsxc.master) { jsxc.xmpp.sendPres(); } $('#jsxc_presence > span').text($('#jsxc_presence > ul .jsxc_' + pres).text()); jsxc.gui.updatePresence('own', pres); }, /** * Update all presence objects for given user. * * @memberOf jsxc.gui * @param bid bar jid of user. * @param {CONST.STATUS} pres New presence state. */ updatePresence: function(bid, pres) { if (bid === 'own') { if (pres === 'dnd') { $('#jsxc_menu .jsxc_muteNotification').addClass('jsxc_disabled'); jsxc.notification.muteSound(true); } else { $('#jsxc_menu .jsxc_muteNotification').removeClass('jsxc_disabled'); if (!jsxc.options.get('muteNotification')) { jsxc.notification.unmuteSound(true); } } } $('.jsxc_presence[data-bid="' + bid + '"]').removeClass('jsxc_' + jsxc.CONST.STATUS.join(' jsxc_')).addClass('jsxc_' + pres); }, /** * Switch read state to UNread. * * @memberOf jsxc.gui * @param bid */ unreadMsg: function(bid) { var win = jsxc.gui.window.get(bid); jsxc.gui.roster.getItem(bid).add(win).addClass('jsxc_unreadMsg'); jsxc.storage.updateUserItem('window', bid, 'unread', true); }, /** * Switch read state to read. * * @memberOf jsxc.gui * @param bid */ readMsg: function(bid) { var win = jsxc.gui.window.get(bid); if (win.hasClass('jsxc_unreadMsg')) { jsxc.gui.roster.getItem(bid).add(win).removeClass('jsxc_unreadMsg'); jsxc.storage.updateUserItem('window', bid, 'unread', false); } }, /** * This function searches for URI scheme according to XEP-0147. * * @memberOf jsxc.gui * @param container In which element should we search? */ detectUriScheme: function(container) { container = (container) ? $(container) : $('body'); container.find("a[href^='xmpp:']").each(function() { var element = $(this); var href = element.attr('href').replace(/^xmpp:/, ''); var jid = href.split('?')[0]; var action, params = {}; if (href.indexOf('?') < 0) { action = 'message'; } else { var pairs = href.substring(href.indexOf('?') + 1).split(';'); action = pairs[0]; var i, key, value; for (i = 1; i < pairs.length; i++) { key = pairs[i].split('=')[0]; value = (pairs[i].indexOf('=') > 0) ? pairs[i].substring(pairs[i].indexOf('=') + 1) : null; params[decodeURIComponent(key)] = decodeURIComponent(value); } } if (typeof jsxc.gui.queryActions[action] === 'function') { element.addClass('jsxc_uriScheme jsxc_uriScheme_' + action); element.off('click').click(function(ev) { ev.stopPropagation(); jsxc.gui.queryActions[action].call(jsxc, jid, params); return false; }); } }); }, detectEmail: function(container) { container = (container) ? $(container) : $('body'); container.find('a[href^="mailto:"]').each(function() { var spot = $("<span>X</span>").addClass("jsxc_spot"); var href = $(this).attr("href").replace(/^ *mailto:/, "").trim(); if (href !== '' && href !== Strophe.getBareJidFromJid(jsxc.storage.getItem("jid"))) { var bid = jsxc.jidToBid(href); var self = $(this); var s = self.prev(); if (!s.hasClass('jsxc_spot')) { s = spot.clone().attr('data-bid', bid); self.before(s); } s.off('click'); if (jsxc.storage.getUserItem('buddy', bid)) { jsxc.gui.update(bid); s.click(function() { jsxc.gui.window.open(bid); return false; }); } else { s.click(function() { jsxc.gui.showContactDialog(href); return false; }); } } }); } }; /** * Handle functions related to the gui of the roster * * @namespace jsxc.gui.roster */ jsxc.gui.roster = { /** * Init the roster skeleton * * @memberOf jsxc.gui.roster * @returns {undefined} */ init: function() { $(jsxc.options.rosterAppend + ':first').append($(jsxc.gui.template.get('roster'))); if (jsxc.options.get('hideOffline')) { $('#jsxc_menu .jsxc_hideOffline').text(jsxc.translate('%%Show offline%%')); $('#jsxc_buddylist').addClass('jsxc_hideOffline'); } $('#jsxc_menu .jsxc_settings').click(function() { jsxc.gui.showSettings(); }); $('#jsxc_menu .jsxc_hideOffline').click(function() { var hideOffline = !jsxc.options.get('hideOffline'); if (hideOffline) { $('#jsxc_buddylist').addClass('jsxc_hideOffline'); } else { $('#jsxc_buddylist').removeClass('jsxc_hideOffline'); } $(this).text(hideOffline ? jsxc.translate('%%Show offline%%') : jsxc.translate('%%Hide offline%%')); jsxc.options.set('hideOffline', hideOffline); }); if (jsxc.options.get('muteNotification')) { jsxc.notification.muteSound(); } $('#jsxc_menu .jsxc_muteNotification').click(function() { if (jsxc.storage.getUserItem('presence') === 'dnd') { return; } // invert current choice var mute = !jsxc.options.get('muteNotification'); if (mute) { jsxc.notification.muteSound(); } else { jsxc.notification.unmuteSound(); } }); $('#jsxc_roster .jsxc_addBuddy').click(function() { jsxc.gui.showContactDialog(); }); $('#jsxc_roster .jsxc_onlineHelp').click(function() { window.open("http://www.jsxc.org/manual.html", "onlineHelp"); }); $('#jsxc_roster .jsxc_about').click(function() { jsxc.gui.showAboutDialog(); }); $('#jsxc_toggleRoster').click(function() { jsxc.gui.roster.toggle(); }); $('#jsxc_presence > ul > li').click(function() { var self = $(this); jsxc.gui.changePresence(self.data('pres')); }); $('#jsxc_buddylist').slimScroll({ distance: '3px', height: ($('#jsxc_roster').height() - 31) + 'px', width: $('#jsxc_buddylist').width() + 'px', color: '#fff', opacity: '0.5' }); $('#jsxc_roster > .jsxc_bottom > div').each(function() { jsxc.gui.toggleList.call($(this)); }); if (jsxc.storage.getUserItem('roster') === 'hidden') { $('#jsxc_roster').css('right', '-200px'); $('#jsxc_windowList > ul').css('paddingRight', '10px'); } var pres = jsxc.storage.getUserItem('presence') || 'online'; $('#jsxc_presence > span').text($('#jsxc_presence > ul .jsxc_' + pres).text()); jsxc.gui.updatePresence('own', pres); jsxc.gui.tooltip('#jsxc_roster'); jsxc.notice.load(); $(document).trigger('ready.roster.jsxc'); }, /** * Create roster item and add it to the roster * * @param {String} bid bar jid */ add: function(bid) { var data = jsxc.storage.getUserItem('buddy', bid); var bud = jsxc.gui.buddyTemplate.clone().attr('data-bid', bid).attr('data-type', data.type || 'chat'); jsxc.gui.roster.insert(bid, bud); bud.click(function() { jsxc.gui.window.open(bid); }); bud.find('.jsxc_chaticon').click(function() { jsxc.gui.window.open(bid); }); bud.find('.jsxc_rename').click(function() { jsxc.gui.roster.rename(bid); return false; }); bud.find('.jsxc_delete').click(function() { jsxc.gui.showRemoveDialog(bid); return false; }); var expandClick = function() { bud.trigger('extra.jsxc'); bud.toggleClass('jsxc_expand'); jsxc.gui.updateAvatar(bud, data.jid, data.avatar); return false; }; bud.find('.jsxc_control').click(expandClick); bud.dblclick(expandClick); bud.find('.jsxc_vcardicon').click(function() { jsxc.gui.showVcard(data.jid); return false; }); jsxc.gui.update(bid); // update scrollbar $('#jsxc_buddylist').slimScroll({ scrollTo: '0px' }); $(document).trigger('add.roster.jsxc', [ bid, data, bud ]); }, getItem: function(bid) { return $("#jsxc_buddylist > li[data-bid='" + bid + "']"); }, /** * Insert roster item. First order: online > away > offline. Second order: * alphabetical of the name * * @param {type} bid * @param {jquery} li roster item which should be insert * @returns {undefined} */ insert: function(bid, li) { var data = jsxc.storage.getUserItem('buddy', bid); var listElements = $('#jsxc_buddylist > li'); var insert = false; // Insert buddy with no mutual friendship to the end var status = (data.sub === 'both') ? data.status : -1; listElements.each(function() { var thisStatus = ($(this).data('sub') === 'both') ? $(this).data('status') : -1; if (($(this).data('name').toLowerCase() > data.name.toLowerCase() && thisStatus === status) || thisStatus < status) { $(this).before(li); insert = true; return false; } }); if (!insert) { li.appendTo('#jsxc_buddylist'); } }, /** * Initiate reorder of roster item * * @param {type} bid * @returns {undefined} */ reorder: function(bid) { jsxc.gui.roster.insert(bid, jsxc.gui.roster.remove(bid)); }, /** * Removes buddy from roster * * @param {String} bid bar jid * @return {JQueryObject} Roster list element */ remove: function(bid) { return jsxc.gui.roster.getItem(bid).detach(); }, /** * Removes buddy from roster and clean up * * @param {String} bid bar compatible jid */ purge: function(bid) { if (jsxc.master) { jsxc.storage.removeUserItem('buddy', bid); jsxc.storage.removeUserItem('otr', bid); jsxc.storage.removeUserItem('otr_version_' + bid); jsxc.storage.removeUserItem('chat', bid); jsxc.storage.removeUserItem('window', bid); jsxc.storage.removeUserElement('buddylist', bid); jsxc.storage.removeUserElement('windowlist', bid); } jsxc.gui.window._close(bid); jsxc.gui.roster.remove(bid); }, /** * Create input element for rename action * * @param {type} bid * @returns {undefined} */ rename: function(bid) { var name = jsxc.gui.roster.getItem(bid).find('.jsxc_name'); var options = jsxc.gui.roster.getItem(bid).find('.jsxc_options, .jsxc_control'); var input = $('<input type="text" name="name"/>'); options.hide(); name = name.replaceWith(input); input.val(name.text()); input.keypress(function(ev) { if (ev.which !== 13) { return; } options.show(); input.replaceWith(name); jsxc.gui.roster._rename(bid, $(this).val()); $('html').off('click'); }); // Disable html click event, if click on input input.click(function() { return false; }); $('html').one('click', function() { options.show(); input.replaceWith(name); jsxc.gui.roster._rename(bid, input.val()); }); }, /** * Rename buddy * * @param {type} bid * @param {type} newname new name of buddy * @returns {undefined} */ _rename: function(bid, newname) { if (jsxc.master) { var d = jsxc.storage.getUserItem('buddy', bid); var iq = $iq({ type: 'set' }).c('query', { xmlns: 'jabber:iq:roster' }).c('item', { jid: Strophe.getBareJidFromJid(d.jid), name: newname }); jsxc.xmpp.conn.sendIQ(iq); } jsxc.storage.updateUserItem('buddy', bid, 'name', newname); jsxc.gui.update(bid); }, /** * Toogle complete roster * * @param {Integer} d Duration in ms */ toggle: function(d) { var duration = d || 500; var roster = $('#jsxc_roster'); var wl = $('#jsxc_windowList'); var roster_width = roster.innerWidth(); var roster_right = parseFloat($('#jsxc_roster').css('right')); var state = (roster_right < 0) ? 'shown' : 'hidden'; jsxc.storage.setUserItem('roster', state); roster.animate({ right: ((roster_width + roster_right) * -1) + 'px' }, duration); wl.animate({ right: (10 - roster_right) + 'px' }, duration); $(document).trigger('toggle.roster.jsxc', [ state, duration ]); }, /** * Shows a text with link to a login box that no connection exists. */ noConnection: function() { $('#jsxc_roster').addClass('jsxc_noConnection'); $('#jsxc_roster').append($('<p>' + jsxc.l.no_connection + '</p>').append(' <a>' + jsxc.l.relogin + '</a>').click(function() { jsxc.gui.showLoginBox(); })); }, /** * Shows a text with link to add a new buddy. * * @memberOf jsxc.gui.roster */ empty: function() { var text = $('<p>' + jsxc.l.Your_roster_is_empty_add_a + '</p>'); var link = $('<a>' + jsxc.l.new_buddy + '</a>'); link.click(function() { jsxc.gui.showContactDialog(); }); text.append(link); text.append('.'); $('#jsxc_roster').prepend(text); } }; /** * Wrapper for dialog * * @namespace jsxc.gui.dialog */ jsxc.gui.dialog = { /** * Open a Dialog. * * @memberOf jsxc.gui.dialog * @param {String} data Data of the dialog * @param {Object} [o] Options for the dialog * @param {Boolean} [o.noClose] If true, hide all default close options * @returns {jQuery} Dialog object */ open: function(data, o) { var opt = o || {}; // default options var options = {}; options = { onComplete: function() { $('#jsxc_dialog .jsxc_close').click(function(ev) { ev.preventDefault(); jsxc.gui.dialog.close(); }); // workaround for old colorbox version (used by firstrunwizard) if (options.closeButton === false) { $('#cboxClose').hide(); } $.colorbox.resize(); $(document).trigger('complete.dialog.jsxc'); }, onClosed: function() { $(document).trigger('close.dialog.jsxc'); }, onCleanup: function() { $(document).trigger('cleanup.dialog.jsxc'); }, opacity: 0.5 }; if (opt.noClose) { options.overlayClose = false; options.escKey = false; options.closeButton = false; delete opt.noClose; } $.extend(options, opt); options.html = '<div id="jsxc_dialog">' + data + '</div>'; $.colorbox(options); return $('#jsxc_dialog'); }, /** * Close current dialog. */ close: function() { jsxc.debug('close dialog'); $.colorbox.close(); }, /** * Resizes current dialog. * * @param {Object} options e.g. width and height */ resize: function(options) { $.colorbox.resize(options); } }; /** * Handle functions related to the gui of the window * * @namespace jsxc.gui.window */ jsxc.gui.window = { /** * Init a window skeleton * * @memberOf jsxc.gui.window * @param {String} bid * @returns {jQuery} Window object */ init: function(bid) { if (jsxc.gui.window.get(bid).length > 0) { return jsxc.gui.window.get(bid); } var win = jsxc.gui.windowTemplate.clone().attr('data-bid', bid).hide().appendTo('#jsxc_windowList > ul').show('slow'); var data = jsxc.storage.getUserItem('buddy', bid); // Attach jid to window win.data('jid', data.jid); // Add handler jsxc.gui.toggleList.call(win.find('.jsxc_settings')); win.find('.jsxc_verification').click(function() { jsxc.gui.showVerification(bid); }); win.find('.jsxc_fingerprints').click(function() { jsxc.gui.showFingerprints(bid); }); win.find('.jsxc_transfer').click(function() { jsxc.otr.toggleTransfer(bid); }); win.find('.jsxc_bar').click(function() { jsxc.gui.window.toggle(bid); }); win.find('.jsxc_close').click(function() { jsxc.gui.window.close(bid); }); win.find('.jsxc_clear').click(function() { jsxc.gui.window.clear(bid); }); win.find('.jsxc_tools').click(function() { return false; }); win.find('.jsxc_textinput').keyup(function(ev) { var body = $(this).val(); if (ev.which === 13) { body = ''; } jsxc.storage.updateUserItem('window', bid, 'text', body); if (ev.which === 27) { jsxc.gui.window.close(bid); } }).keypress(function(ev) { if (ev.which !== 13 || !$(this).val()) { return; } jsxc.gui.window.postMessage(bid, 'out', $(this).val()); $(this).val(''); }).focus(function() { // remove unread flag jsxc.gui.readMsg(bid); }).mouseenter(function() { $('#jsxc_windowList').data('isOver', true); }).mouseleave(function() { $('#jsxc_windowList').data('isOver', false); }); win.find('.jsxc_textarea').click(function() { win.find('.jsxc_textinput').focus(); }); win.find('.jsxc_textarea').slimScroll({ height: '234px', distance: '3px' }); win.find('.jsxc_fade').hide(); win.find('.jsxc_name').disableSelection(); win.find('.slimScrollDiv').resizable({ handles: 'w, nw, n', minHeight: 234, minWidth: 250, resize: function(event, ui) { win.width(ui.size.width); win.find('.jsxc_textarea').slimScroll({ height: ui.size.height }); win.find('.jsxc_emoticons').css('top', (ui.size.height + 6) + 'px'); } }); if ($.inArray(bid, jsxc.storage.getUserItem('windowlist')) < 0) { // add window to windowlist var wl = jsxc.storage.getUserItem('windowlist'); wl.push(bid); jsxc.storage.setUserItem('windowlist', wl); // init window element in storage jsxc.storage.setUserItem('window', bid, { minimize: true, text: '', unread: false }); } else { if (jsxc.storage.getUserItem('window', bid).unread) { jsxc.gui.unreadMsg(bid); } } $.each(jsxc.gui.emotions, function(i, val) { var ins = val[0].split(' ')[0]; var li = $('<li><div title="' + ins + '" class="jsxc_' + val[1] + '"/></li>'); li.click(function() { win.find('input').val(win.find('input').val() + ins); win.find('input').focus(); }); win.find('.jsxc_emoticons ul').append(li); }); jsxc.gui.toggleList.call(win.find('.jsxc_emoticons')); jsxc.gui.window.restoreChat(bid); jsxc.gui.update(bid); jsxc.gui.updateWindowListSB(); // create related otr object if (jsxc.master && !jsxc.otr.objects[bid]) { jsxc.otr.create(bid); } else { jsxc.otr.enable(bid); } $(document).trigger('init.window.jsxc', [ win ]); return win; }, /** * Returns the window element * * @param {String} bid * @returns {jquery} jQuery object of the window element */ get: function(id) { return $("li.jsxc_windowItem[data-bid='" + jsxc.jidToBid(id) + "']"); }, /** * Open a window, related to the bid. If the window doesn't exist, it will * be created. * * @param {String} bid * @returns {jQuery} Window object */ open: function(bid) { var win = jsxc.gui.window.init(bid); jsxc.gui.window.show(bid); jsxc.gui.window.highlight(bid); var padding = $("#jsxc_windowListSB").width(); var innerWidth = $('#jsxc_windowList>ul').width(); var outerWidth = $('#jsxc_windowList').width() - padding; if (innerWidth > outerWidth) { var offset = parseInt($('#jsxc_windowList>ul').css('right')); var width = win.outerWidth(true); var right = innerWidth - win.position().left - width + offset; var left = outerWidth - (innerWidth - win.position().left) - offset; if (left < 0) { jsxc.gui.scrollWindowListBy(left * -1); } if (right < 0) { jsxc.gui.scrollWindowListBy(right); } } return win; }, /** * Close chatwindow and clean up * * @param {String} bid bar jid */ close: function(bid) { if (jsxc.gui.window.get(bid).length === 0) { jsxc.warn('Want to close a window, that is not open.'); return; } jsxc.storage.removeUserElement('windowlist', bid); jsxc.storage.removeUserItem('window', bid); if (jsxc.storage.getUserItem('buddylist').indexOf(bid) < 0) { // delete data from unknown sender jsxc.storage.removeUserItem('buddy', bid); jsxc.storage.removeUserItem('chat', bid); } jsxc.gui.window._close(bid); }, /** * Close chatwindow * * @param {String} bid */ _close: function(bid) { jsxc.gui.window.get(bid).hide('slow', function() { $(this).remove(); jsxc.gui.updateWindowListSB(); }); }, /** * Toggle between minimize and maximize of the text area * * @param {String} bid bar jid */ toggle: function(bid) { var win = jsxc.gui.window.get(bid); if (win.parents("#jsxc_windowList").length === 0) { return; } if (win.find('.jsxc_fade').is(':hidden')) { jsxc.gui.window.show(bid); } else { jsxc.gui.window.hide(bid); } jsxc.gui.updateWindowListSB(); }, /** * Maximize text area and save * * @param {String} bid */ show: function(bid) { jsxc.storage.updateUserItem('window', bid, 'minimize', false); jsxc.gui.window._show(bid); }, /** * Maximize text area * * @param {String} bid * @returns {undefined} */ _show: function(bid) { var win = jsxc.gui.window.get(bid); jsxc.gui.window.get(bid).find('.jsxc_fade').slideDown(); win.removeClass('jsxc_min'); // If the area is hidden, the scrolldown function doesn't work. So we // call it here. jsxc.gui.window.scrollDown(bid); if (jsxc.restoreCompleted) { win.find('.jsxc_textinput').focus(); } win.trigger('show.window.jsxc'); }, /** * Minimize text area and save * * @param {String} bid */ hide: function(bid) { jsxc.storage.updateUserItem('window', bid, 'minimize', true); jsxc.gui.window._hide(bid); }, /** * Minimize text area * * @param {String} bid */ _hide: function(bid) { jsxc.gui.window.get(bid).addClass('jsxc_min').find(' .jsxc_fade').slideUp(); jsxc.gui.window.get(bid).trigger('hidden.window.jsxc'); }, /** * Highlight window * * @param {type} bid */ highlight: function(bid) { var el = jsxc.gui.window.get(bid).find(' .jsxc_bar'); if (!el.is(':animated')) { el.effect('highlight', { color: 'orange' }, 2000); } }, /** * Scroll chat area to the bottom * * @param {String} bid bar jid */ scrollDown: function(bid) { var chat = jsxc.gui.window.get(bid).find('.jsxc_textarea'); // check if chat exist if (chat.length === 0) { return; } chat.slimScroll({ scrollTo: (chat.get(0).scrollHeight + 'px') }); }, /** * Write Message to chat area and save * * @param {String} bid bar jid * @param {String} direction 'in' message is received or 'out' message is * send * @param {String} msg Message to display * @param {boolean} encrypted Was this message encrypted? Default: false * @param {boolean} forwarded Was this message forwarded? Default: false * @param {integer} stamp Timestamp */ postMessage: function(bid, direction, msg, encrypted, forwarded, stamp) { var data = jsxc.storage.getUserItem('buddy', bid); var html_msg = msg; // remove html tags and reencode html tags msg = jsxc.removeHTML(msg); msg = jsxc.escapeHTML(msg); // exceptions: if (direction === 'out' && data.msgstate === OTR.CONST.MSGSTATE_FINISHED && forwarded !== true) { direction = 'sys'; msg = jsxc.l.your_message_wasnt_send_please_end_your_private_conversation; } if (direction === 'in' && data.msgstate === OTR.CONST.MSGSTATE_FINISHED) { direction = 'sys'; msg = jsxc.l.unencrypted_message_received + ' ' + msg; } if (direction === 'out' && data.sub === 'from') { direction = 'sys'; msg = jsxc.l.your_message_wasnt_send_because_you_have_no_valid_subscription; } encrypted = encrypted || data.msgstate === OTR.CONST.MSGSTATE_ENCRYPTED; var post = jsxc.storage.saveMessage(bid, direction, msg, encrypted, forwarded, stamp); if (direction === 'in') { $(document).trigger('postmessagein.jsxc', [ bid, html_msg ]); } if (direction === 'out' && jsxc.master && forwarded !== true) { jsxc.xmpp.sendMessage(bid, html_msg, post.uid); } jsxc.gui.window._postMessage(bid, post); if (direction === 'out' && msg === '?') { jsxc.gui.window.postMessage(bid, 'sys', '42'); } }, /** * Write Message to chat area * * @param {String} bid bar jid * @param {Object} post Post object with direction, msg, uid, received * @param {Bool} restore If true no highlights are used and so unread flag * set */ _postMessage: function(bid, post, restore) { var win = jsxc.gui.window.get(bid); var msg = post.msg; var direction = post.direction; var uid = post.uid; if (win.find('.jsxc_textinput').is(':not(:focus)') && jsxc.restoreCompleted && direction === 'in' && !restore) { jsxc.gui.window.highlight(bid); } msg = msg.replace(jsxc.CONST.REGEX.URL, function(url) { var href = (url.match(/^https?:\/\//i)) ? url : 'http://' + url; return '<a href="' + href + '" target="_blank">' + url + '</a>'; }); msg = msg.replace(new RegExp('(xmpp:)?(' + jsxc.CONST.REGEX.JID.source + ')(\\?[^\\s]+\\b)?', 'i'), function(match, protocol, jid, action) { if (protocol === 'xmpp:') { if (typeof action === 'string') { jid += action; } return '<a href="xmpp:' + jid + '">' + jid + '</a>'; } return '<a href="mailto:' + jid + '" target="_blank">' + jid + '</a>'; }); $.each(jsxc.gui.emotions, function(i, val) { msg = msg.replace(val[2], function(match, p1) { // escape value for alt and title, this prevents double // replacement var esc = '', i; for (i = 0; i < p1.length; i++) { esc += '&#' + p1.charCodeAt(i) + ';'; } return '<div title="' + esc + '" class="jsxc_emoticon jsxc_' + val[1] + '"/>'; }); }); var msgDiv = $("<div>"), msgTsDiv = $("<div>"); msgDiv.addClass('jsxc_chatmessage jsxc_' + direction); msgDiv.attr('id', uid); msgDiv.html('<div>' + msg + '</div>'); msgTsDiv.addClass('jsxc_timestamp'); msgTsDiv.html(jsxc.getFormattedTime(post.stamp)); if (post.received || false) { msgDiv.addClass('jsxc_received'); } if (post.forwarded) { msgDiv.addClass('jsxc_forwarded'); } if (post.encrypted) { msgDiv.addClass('jsxc_encrypted'); } if (direction === 'sys') { jsxc.gui.window.get(bid).find('.jsxc_textarea').append('<div style="clear:both"/>'); } else if (typeof post.stamp !== 'undefined') { msgDiv.append(msgTsDiv); } win.find('.jsxc_textarea').append(msgDiv); jsxc.gui.detectUriScheme(win); jsxc.gui.detectEmail(win); jsxc.gui.window.scrollDown(bid); // if window has no focus set unread flag if (!win.find('.jsxc_textinput').is(':focus') && jsxc.restoreCompleted && !restore) { jsxc.gui.unreadMsg(bid); } }, /** * Set text into input area * * @param {type} bid * @param {type} text * @returns {undefined} */ setText: function(bid, text) { jsxc.gui.window.get(bid).find('.jsxc_textinput').val(text); }, /** * Load old log into chat area * * @param {type} bid * @returns {undefined} */ restoreChat: function(bid) { var chat = jsxc.storage.getUserItem('chat', bid); while (chat !== null && chat.length > 0) { var c = chat.pop(); jsxc.gui.window._postMessage(bid, c, true); } }, /** * Clear chat history * * @param {type} bid * @returns {undefined} */ clear: function(bid) { jsxc.storage.setUserItem('chat', bid, []); jsxc.gui.window.get(bid).find('.jsxc_textarea').empty(); } }; /** * Hold all HTML templates. * * @namespace jsxc.gui.template */ jsxc.gui.template = { /** * Return requested template and replace all placeholder * * @memberOf jsxc.gui.template; * @param {type} name template name * @param {type} bid * @param {type} msg * @returns {String} HTML Template */ get: function(name, bid, msg) { // common placeholder var ph = { my_priv_fingerprint: jsxc.storage.getUserItem('priv_fingerprint') ? jsxc.storage.getUserItem('priv_fingerprint').replace(/(.{8})/g, '$1 ') : jsxc.l.not_available, my_jid: jsxc.storage.getItem('jid') || '', my_node: Strophe.getNodeFromJid(jsxc.storage.getItem('jid') || '') || '', root: jsxc.options.root, app_name: jsxc.options.app_name }; // placeholder depending on bid if (bid) { var data = jsxc.storage.getUserItem('buddy', bid); $.extend(ph, { bid_priv_fingerprint: (data && data.fingerprint) ? data.fingerprint.replace(/(.{8})/g, '$1 ') : jsxc.l.not_available, bid_jid: bid, bid_name: (data && data.name) ? data.name : bid }); } // placeholder depending on msg if (msg) { $.extend(ph, { msg: msg }); } var ret = jsxc.gui.template[name]; if (typeof (ret) === 'string') { ret = jsxc.translate(ret); ret = ret.replace(/\{\{([a-zA-Z0-9_\-]+)\}\}/g, function(s, key) { return (typeof ph[key] === 'string') ? ph[key] : s; }); return ret; } jsxc.debug('Template not available: ' + name); return name; }, authenticationDialog: '<h3>Verification</h3>\ <p>%%Authenticating_a_buddy_helps_%%</p>\ <div>\ <p style="margin:0px;">%%How_do_you_want_to_authenticate_your_buddy%%</p>\ <select size="1">\ <option>%%Select_method%%</option>\ <option>%%Manual%%</option>\ <option>%%Question%%</option>\ <option>%%Secret%%</option>\ </select>\ </div>\ <div style="display:none">\ <p class=".jsxc_explanation">%%To_verify_the_fingerprint_%%</p>\ <p><strong>%%Your_fingerprint%%</strong><br />\ <span style="text-transform:uppercase">{{my_priv_fingerprint}}</span></p>\ <p><strong>%%Buddy_fingerprint%%</strong><br />\ <span style="text-transform:uppercase">{{bid_priv_fingerprint}}</span></p><br />\ <p class="jsxc_right"><a href="#" class="jsxc_close button">%%Close%%</a> <a href="#" class="button creation">%%Compared%%</a></p>\ </div>\ <div style="display:none">\ <p class=".jsxc_explanation">%%To_authenticate_using_a_question_%%</p>\ <p><label for="jsxc_quest">%%Question%%:</label><input type="text" name="quest" id="jsxc_quest" /></p>\ <p><label for="jsxc_secret2">%%Secret%%:</label><input type="text" name="secret2" id="jsxc_secret2" /></p>\ <p class="jsxc_right"><a href="#" class="button jsxc_close">%%Close%%</a> <a href="#" class="button creation">%%Ask%%</a></p>\ </div>\ <div style="display:none">\ <p class=".jsxc_explanation">%%To_authenticate_pick_a_secret_%%</p>\ <p><label for="jsxc_secret">%%Secret%%:</label><input type="text" name="secret" id="jsxc_secret" /></p>\ <p class="jsxc_right"><a href="#" class="button jsxc_close">%%Close%%</a> <a href="#" class="button creation">%%Compare%%</a></p>\ </div>', fingerprintsDialog: '<div>\ <p class="jsxc_maxWidth">%%A_fingerprint_%%</p>\ <p><strong>%%Your_fingerprint%%</strong><br />\ <span style="text-transform:uppercase">{{my_priv_fingerprint}}</span></p>\ <p><strong>%%Buddy_fingerprint%%</strong><br />\ <span style="text-transform:uppercase">{{bid_priv_fingerprint}}</span></p><br />\ <p class="jsxc_right"><a href="#" class="button jsxc_close">%%Close%%</a></p>\ </div>', chatWindow: '<li class="jsxc_min jsxc_windowItem">\ <div class="jsxc_window">\ <div class="jsxc_bar">\ <div class="jsxc_avatar">☺</div>\ <div class="jsxc_tools">\ <div class="jsxc_settings">\ <ul>\ <li class="jsxc_fingerprints jsxc_otr jsxc_disabled">%%Fingerprints%%</li>\ <li class="jsxc_verification">%%Authentication%%</li>\ <li class="jsxc_transfer jsxc_otr jsxc_disabled">%%start_private%%</li>\ <li class="jsxc_clear">%%clear_history%%</li>\ </ul>\ </div>\ <div class="jsxc_transfer jsxc_otr jsxc_disabled"/>\ <div class="jsxc_close">×</div>\ </div>\ <div class="jsxc_name"/>\ <div class="jsxc_cycle"/>\ </div>\ <div class="jsxc_fade">\ <div class="jsxc_gradient"/>\ <div class="jsxc_textarea"/>\ <div class="jsxc_emoticons"><ul/></div>\ <input type="text" class="jsxc_textinput" placeholder="...%%Message%%" />\ </div>\ </div>\ </li>', roster: '<div id="jsxc_roster">\ <ul id="jsxc_buddylist"></ul>\ <div class="jsxc_bottom jsxc_presence" data-bid="own">\ <div id="jsxc_avatar">\ <div class="jsxc_avatar">☺</div>\ </div>\ <div id="jsxc_menu">\ <span></span>\ <ul>\ <li class="jsxc_settings">%%Settings%%</li>\ <li class="jsxc_muteNotification">%%Mute%%</li>\ <li class="jsxc_addBuddy">%%Add_buddy%%</li>\ <li class="jsxc_hideOffline">%%Hide offline%%</li>\ <li class="jsxc_onlineHelp">%%Online help%%</li>\ <li class="jsxc_about">%%About%%</li>\ </ul>\ </div>\ <div id="jsxc_notice">\ <span></span>\ <ul></ul>\ </div>\ <div id="jsxc_presence">\ <span>%%Online%%</span>\ <ul>\ <li data-pres="online" class="jsxc_online">%%Online%%</li>\ <li data-pres="chat" class="jsxc_chat">%%Chatty%%</li>\ <li data-pres="away" class="jsxc_away">%%Away%%</li>\ <li data-pres="xa" class="jsxc_xa">%%Extended away%%</li>\ <li data-pres="dnd" class="jsxc_dnd">%%dnd%%</li>\ <!-- <li data-pres="offline" class="jsxc_offline">%%Offline%%</li> -->\ </ul>\ </div>\ </div>\ <div id="jsxc_toggleRoster"></div>\ </div>', windowList: '<div id="jsxc_windowList">\ <ul></ul>\ </div>\ <div id="jsxc_windowListSB">\ <div class="jsxc_scrollLeft jsxc_disabled">&lt;</div>\ <div class="jsxc_scrollRight jsxc_disabled">&gt;</div>\ </div>', rosterBuddy: '<li>\ <div class="jsxc_avatar">☺</div>\ <div class="jsxc_control"></div>\ <div class="jsxc_name"/>\ <div class="jsxc_options jsxc_right">\ <div class="jsxc_rename" title="%%rename_buddy%%">✎</div>\ <div class="jsxc_delete" title="%%delete_buddy%%">✘</div>\ </div>\ <div class="jsxc_options jsxc_left">\ <div class="jsxc_chaticon" title="%%send_message%%"/>\ <div class="jsxc_vcardicon" title="%%get_info%%">i</div>\ </div>\ </li>', loginBox: '<h3>%%Login%%</h3>\ <form>\ <p><label for="jsxc_username">%%Username%%:</label>\ <input type="text" name="username" id="jsxc_username" required="required" value="{{my_node}}"/></p>\ <p><label for="jsxc_password">%%Password%%:</label>\ <input type="password" name="password" required="required" id="jsxc_password" /></p>\ <div class="bottom_submit_section">\ <input type="reset" class="button jsxc_close" name="clear" value="%%Cancel%%"/>\ <input type="submit" class="button creation" name="commit" value="%%Connect%%"/>\ </div>\ </form>', contactDialog: '<h3>%%Add_buddy%%</h3>\ <p class=".jsxc_explanation">%%Type_in_the_full_username_%%</p>\ <form>\ <p><label for="jsxc_username">* %%Username%%:</label>\ <input type="text" name="username" id="jsxc_username" pattern="^[^\\x22&\'\\/:<>@\\s]+(@[.\\-_\\w]+)?" required="required" /></p>\ <p><label for="jsxc_alias">%%Alias%%:</label>\ <input type="text" name="alias" id="jsxc_alias" /></p>\ <p class="jsxc_right">\ <input class="button" type="submit" value="%%Add%%" />\ </p>\ <form>', approveDialog: '<h3>%%Subscription_request%%</h3>\ <p>%%You_have_a_request_from%% <b class="jsxc_their_jid"></b>.</p>\ <p class="jsxc_right"><a href="#" class="button jsxc_deny">%%Deny%%</a> <a href="#" class="button creation jsxc_approve">%%Approve%%</a></p>', removeDialog: '<h3>%%Remove buddy%%</h3>\ <p class="jsxc_maxWidth">%%You_are_about_to_remove_%%</p>\ <p class="jsxc_right"><a href="#" class="button jsxc_cancel jsxc_close">%%Cancel%%</a> <a href="#" class="button creation">%%Remove%%</a></p>', waitAlert: '<h3>{{msg}}</h3>\ <p>%%Please_wait%%</p>\ <p class="jsxc_center"><img src="{{root}}/img/loading.gif" alt="wait" width="32px" height="32px" /></p>', alert: '<h3>%%Alert%%</h3>\ <p>{{msg}}</p>\ <p class="jsxc_right"><a href="#" class="button jsxc_close jsxc_cancel">%%Ok%%</a></p>', authFailDialog: '<h3>%%Login_failed%%</h3>\ <p>%%Sorry_we_cant_authentikate_%%</p>\ <p class="jsxc_right">\ <a class="button jsxc_cancel">%%Continue_without_chat%%</a>\ <a class="button creation">%%Retry%%</a>\ </p>', confirmDialog: '<p>{{msg}}</p>\ <p class="jsxc_right">\ <a class="button jsxc_cancel jsxc_close">%%Dismiss%%</a>\ <a class="button creation">%%Confirm%%</a>\ </p>', pleaseAccept: '<p>%%Please_accept_%%</p>', aboutDialog: '<h3>JavaScript XMPP Chat</h3>\ <p><b>Version: </b>' + jsxc.version + '<br />\ <a href="http://jsxc.org/" target="_blank">www.jsxc.org</a><br />\ <br />\ <i>Released under the MIT license</i><br />\ <br />\ Real-time chat app for {{app_name}} and more.<br />\ Requires an external <a href="https://xmpp.org/xmpp-software/servers/" target="_blank">XMPP server</a>.<br />\ <br />\ <b>Credits: </b> <a href="http://www.beepzoid.com/old-phones/" target="_blank">David English (Ringtone)</a>,\ <a href="https://soundcloud.com/freefilmandgamemusic/ping-1?in=freefilmandgamemusic/sets/free-notification-sounds-and" target="_blank">CameronMusic (Ping)</a></p>\ <p class="jsxc_right"><a class="button jsxc_debuglog" href="#">Show debug log</a></p>', vCard: '<h3>%%Info_about%% {{bid_name}}</h3>\ <ul class="jsxc_vCard"></ul>\ <p><img src="{{root}}/img/loading.gif" alt="wait" width="32px" height="32px" /> %%Please_wait%%...</p>', settings: '<h3>%%User_settings%%</h3>\ <p></p>\ <form>\ <fieldset class="jsxc_fieldsetXmpp jsxc_fieldset">\ <legend>%%Login options%%</legend>\ <label for="xmpp-url">%%BOSH url%%</label><input type="text" id="xmpp-url" readonly="readonly"/><br />\ <label for="xmpp-username">%%Username%%</label><input type="text" id="xmpp-username"/><br />\ <label for="xmpp-domain">%%Domain%%</label><input type="text" id="xmpp-domain"/><br />\ <label for="xmpp-resource">%%Resource%%</label><input type="text" id="xmpp-resource"/><br />\ <label for="xmpp-onlogin">%%On login%%</label><input type="checkbox" id="xmpp-onlogin" /><br />\ <input type="submit" value="%%Save%%"/>\ </fieldset>\ </form>\ <p></p>\ <form>\ <fieldset class="jsxc_fieldsetPriority jsxc_fieldset">\ <legend>%%Priority%%</legend>\ <label for="priority-online">%%Online%%</label><input type="number" value="0" id="priority-online" min="-128" max="127" step="1" required="required"/><br />\ <label for="priority-chat">%%Chatty%%</label><input type="number" value="0" id="priority-chat" min="-128" max="127" step="1" required="required"/><br />\ <label for="priority-away">%%Away%%</label><input type="number" value="0" id="priority-away" min="-128" max="127" step="1" required="required"/><br />\ <label for="priority-xa">%%Extended_away%%</label><input type="number" value="0" id="priority-xa" min="-128" max="127" step="1" required="required"/><br />\ <label for="priority-dnd">%%dnd%%</label><input type="number" value="0" id="priority-dnd" min="-128" max="127" step="1" required="required"/><br />\ <input type="submit" value="%%Save%%"/>\ </fieldset>\ </form>\ <p></p>\ <form data-onsubmit="xmpp.carbons.refresh">\ <fieldset class="jsxc_fieldsetCarbons jsxc_fieldset">\ <legend>%%Carbon copy%%</legend>\ <label for="carbons-enable">%%Enable%%</label><input type="checkbox" id="carbons-enable" /><br />\ <input type="submit" value="%%Save%%"/>\ </fieldset>\ </form>' }; /** * Handle XMPP stuff. * * @namespace jsxc.xmpp */ jsxc.xmpp = { conn: null, // connection /** * Create new connection or attach to old * * @name login * @memberOf jsxc.xmpp */ /** * Create new connection with given parameters. * * @name login^2 * @param {string} jid * @param {string} password * @memberOf jsxc.xmpp */ /** * Attach connection with given parameters. * * @name login^3 * @param {string} jid * @param {string} sid * @param {string} rid * @memberOf jsxc.xmpp */ login: function() { if (jsxc.xmpp.conn && jsxc.xmpp.conn.connected) { return; } var jid = null, password = null, sid = null, rid = null; switch (arguments.length) { case 2: jid = arguments[0]; password = arguments[1]; break; case 3: jid = arguments[0]; sid = arguments[1]; rid = arguments[2]; break; default: jid = jsxc.storage.getItem('jid'); sid = jsxc.storage.getItem('sid'); rid = jsxc.storage.getItem('rid'); } var url = jsxc.options.get('xmpp').url; // Register eventlistener $(document).on('connected.jsxc', jsxc.xmpp.connected); $(document).on('attached.jsxc', jsxc.xmpp.attached); $(document).on('disconnected.jsxc', jsxc.xmpp.disconnected); $(document).on('ridChange', jsxc.xmpp.onRidChange); $(document).on('connfail.jsxc', jsxc.xmpp.onConnfail); $(document).on('authfail.jsxc', jsxc.xmpp.onAuthFail); Strophe.addNamespace('RECEIPTS', 'urn:xmpp:receipts'); // Create new connection (no login) jsxc.xmpp.conn = new Strophe.Connection(url); // Override default function to preserve unique id var stropheGetUniqueId = jsxc.xmpp.conn.getUniqueId; jsxc.xmpp.conn.getUniqueId = function(suffix) { var uid = stropheGetUniqueId.call(jsxc.xmpp.conn, suffix); jsxc.storage.setItem('_uniqueId', jsxc.xmpp.conn._uniqueId); return uid; }; if (jsxc.storage.getItem('debug') === true) { jsxc.xmpp.conn.xmlInput = function(data) { console.log('<', data); }; jsxc.xmpp.conn.xmlOutput = function(data) { console.log('>', data); }; } var callback = function(status, condition) { jsxc.debug(Object.getOwnPropertyNames(Strophe.Status)[status] + ': ' + condition); switch (status) { case Strophe.Status.CONNECTED: jsxc.bid = jsxc.jidToBid(jsxc.xmpp.conn.jid.toLowerCase()); $(document).trigger('connected.jsxc'); break; case Strophe.Status.ATTACHED: $(document).trigger('attached.jsxc'); break; case Strophe.Status.DISCONNECTED: $(document).trigger('disconnected.jsxc'); break; case Strophe.Status.CONNFAIL: $(document).trigger('connfail.jsxc'); break; case Strophe.Status.AUTHFAIL: $(document).trigger('authfail.jsxc'); break; } }; if (jsxc.xmpp.conn.caps) { jsxc.xmpp.conn.caps.node = 'http://jsxc.org/'; } if (jsxc.restore && sid && rid) { jsxc.debug('Try to attach'); jsxc.debug('SID: ' + sid); jsxc.xmpp.conn.attach(jid, sid, rid, callback); } else { jsxc.debug('New connection'); if (jsxc.xmpp.conn.caps) { // Add system handler, because user handler isn't called before // we are authenticated jsxc.xmpp.conn._addSysHandler(function(stanza) { var from = jsxc.xmpp.conn.domain, c = stanza.querySelector('c'), ver = c.getAttribute('ver'), node = c.getAttribute('node'); var _jidNodeIndex = JSON.parse(localStorage.getItem('strophe.caps._jidNodeIndex')) || {}; jsxc.xmpp.conn.caps._jidVerIndex[from] = ver; _jidNodeIndex[from] = node; localStorage.setItem('strophe.caps._jidVerIndex', JSON.stringify(jsxc.xmpp.conn.caps._jidVerIndex)); localStorage.setItem('strophe.caps._jidNodeIndex', JSON.stringify(_jidNodeIndex)); }, Strophe.NS.CAPS); } jsxc.xmpp.conn.connect(jid || jsxc.options.xmpp.jid, password || jsxc.options.xmpp.password, callback); } }, /** * Logs user out of his xmpp session and does some clean up. * * @returns {Boolean} */ logout: function() { // instruct all tabs jsxc.storage.removeItem('sid'); // clean up jsxc.storage.removeUserItem('buddylist'); jsxc.storage.removeUserItem('windowlist'); jsxc.storage.removeItem('_uniqueId'); if (!jsxc.master) { $('#jsxc_roster').remove(); $('#jsxc_windowlist').remove(); return true; } if (jsxc.xmpp.conn === null) { return true; } // Hide dropdown menu $('body').click(); jsxc.triggeredFromElement = true; // restore all otr objects $.each(jsxc.storage.getUserItem('otrlist') || {}, function(i, val) { jsxc.otr.create(val); }); var numOtr = Object.keys(jsxc.otr.objects || {}).length + 1; var disReady = function() { if (--numOtr <= 0) { jsxc.xmpp.conn.flush(); setTimeout(function() { jsxc.xmpp.conn.disconnect(); }, 600); } }; // end all private conversations $.each(jsxc.otr.objects || {}, function(key, obj) { if (obj.msgstate === OTR.CONST.MSGSTATE_ENCRYPTED) { obj.endOtr.call(obj, function() { obj.init.call(obj); jsxc.otr.backup(key); disReady(); }); } else { disReady(); } }); disReady(); // Trigger real logout in jsxc.xmpp.disconnected() return false; }, /** * Triggered if connection is established * * @private */ connected: function() { jsxc.xmpp.conn.pause(); var nomJid = Strophe.getBareJidFromJid(jsxc.xmpp.conn.jid).toLowerCase() + '/' + Strophe.getResourceFromJid(jsxc.xmpp.conn.jid); // Save sid and jid jsxc.storage.setItem('sid', jsxc.xmpp.conn._proto.sid); jsxc.storage.setItem('jid', nomJid); jsxc.storage.setItem('lastActivity', (new Date()).getTime()); // make shure roster will be reloaded jsxc.storage.removeUserItem('buddylist'); jsxc.storage.removeUserItem('windowlist'); jsxc.storage.removeUserItem('own'); jsxc.storage.removeUserItem('avatar', 'own'); jsxc.storage.removeUserItem('otrlist'); if (jsxc.options.loginForm.triggered) { switch (jsxc.options.loginForm.onConnected || 'submit') { case 'submit': jsxc.submitLoginForm(); /* falls through */ case false: jsxc.xmpp.connectionReady(); return; } } // start chat jsxc.gui.init(); $('#jsxc_roster').removeClass('jsxc_noConnection'); jsxc.onMaster(); jsxc.xmpp.conn.resume(); jsxc.gui.dialog.close(); $(document).trigger('attached.jsxc'); }, /** * Triggered if connection is attached * * @private */ attached: function() { jsxc.xmpp.conn.addHandler(jsxc.xmpp.onRosterChanged, 'jabber:iq:roster', 'iq', 'set'); jsxc.xmpp.conn.addHandler(jsxc.xmpp.onMessage, null, 'message', 'chat'); jsxc.xmpp.conn.addHandler(jsxc.xmpp.onReceived, null, 'message'); jsxc.xmpp.conn.addHandler(jsxc.xmpp.onPresence, null, 'presence'); var caps = jsxc.xmpp.conn.caps; var domain = jsxc.xmpp.conn.domain; if (caps && jsxc.options.get('carbons').enable) { var conditionalEnable = function() { if (jsxc.xmpp.conn.caps.hasFeatureByJid(domain, jsxc.CONST.NS.CARBONS)) { jsxc.xmpp.carbons.enable(); } }; if (typeof caps._knownCapabilities[caps._jidVerIndex[domain]] === 'undefined') { var _jidNodeIndex = JSON.parse(localStorage.getItem('strophe.caps._jidNodeIndex')) || {}; $(document).on('caps.strophe', function onCaps(ev, from) { if (from !== domain) { return; } conditionalEnable(); $(document).off('caps.strophe', onCaps); }); caps._requestCapabilities(jsxc.xmpp.conn.domain, _jidNodeIndex[domain], caps._jidVerIndex[domain]); } else { // We know server caps conditionalEnable(); } } // Only load roaster if necessary if (!jsxc.restore || !jsxc.storage.getUserItem('buddylist')) { // in order to not overide existing presence information, we send // pres first after roster is ready $(document).one('cloaded.roster.jsxc', jsxc.xmpp.sendPres); $('#jsxc_roster > p:first').remove(); var iq = $iq({ type: 'get' }).c('query', { xmlns: 'jabber:iq:roster' }); jsxc.xmpp.conn.sendIQ(iq, jsxc.xmpp.onRoster); } else { jsxc.xmpp.sendPres(); } jsxc.xmpp.connectionReady(); }, /** * Triggered if the connection is ready */ connectionReady: function() { // Load saved unique id jsxc.xmpp.conn._uniqueId = jsxc.storage.getItem('_uniqueId') || new Date().getTime(); $(document).trigger('connectionReady.jsxc'); }, /** * Sends presence stanza to server. */ sendPres: function() { // disco stuff if (jsxc.xmpp.conn.disco) { jsxc.xmpp.conn.disco.addIdentity('client', 'web', 'JSXC'); jsxc.xmpp.conn.disco.addFeature(Strophe.NS.DISCO_INFO); jsxc.xmpp.conn.disco.addFeature(Strophe.NS.RECEIPTS); } // create presence stanza var pres = $pres(); if (jsxc.xmpp.conn.caps) { // attach caps pres.c('c', jsxc.xmpp.conn.caps.generateCapsAttrs()).up(); } var presState = jsxc.storage.getUserItem('presence') || 'online'; if (presState !== 'online') { pres.c('show').t(presState).up(); } var priority = jsxc.options.get('priority'); if (priority && typeof priority[presState] !== 'undefined' && parseInt(priority[presState]) !== 0) { pres.c('priority').t(priority[presState]).up(); } jsxc.debug('Send presence', pres.toString()); jsxc.xmpp.conn.send(pres); }, /** * Triggered if lost connection * * @private */ disconnected: function() { jsxc.debug('disconnected'); jsxc.storage.removeItem('sid'); jsxc.storage.removeItem('rid'); jsxc.storage.removeItem('lastActivity'); jsxc.storage.removeItem('hidden'); jsxc.storage.removeUserItem('avatar', 'own'); jsxc.storage.removeUserItem('otrlist'); $(document).off('connected.jsxc', jsxc.xmpp.connected); $(document).off('attached.jsxc', jsxc.xmpp.attached); $(document).off('disconnected.jsxc', jsxc.xmpp.disconnected); $(document).off('ridChange', jsxc.xmpp.onRidChange); $(document).off('connfail.jsxc', jsxc.xmpp.onConnfail); $(document).off('authfail.jsxc', jsxc.xmpp.onAuthFail); jsxc.xmpp.conn = null; $('#jsxc_windowList').remove(); if (jsxc.triggeredFromElement) { $('#jsxc_roster').remove(); if (jsxc.triggeredFromLogout) { window.location = jsxc.options.logoutElement.attr('href'); } } else { jsxc.gui.roster.noConnection(); } window.clearInterval(jsxc.keepalive); }, /** * Triggered on connection fault * * @param {String} condition information why we lost the connection * @private */ onConnfail: function(ev, condition) { jsxc.debug('XMPP connection failed: ' + condition); if (jsxc.options.loginForm.triggered) { jsxc.submitLoginForm(); } }, /** * Triggered on auth fail. * * @private */ onAuthFail: function() { if (jsxc.options.loginForm.triggered) { switch (jsxc.options.loginForm.onAuthFail || 'ask') { case 'ask': jsxc.gui.showAuthFail(); break; case 'submit': jsxc.submitLoginForm(); break; } } }, /** * Triggered on initial roster load * * @param {dom} iq * @private */ onRoster: function(iq) { /* * <iq from='' type='get' id=''> <query xmlns='jabber:iq:roster'> <item * jid='' name='' subscription='' /> ... </query> </iq> */ jsxc.debug('Load roster', iq); var buddies = []; $(iq).find('item').each(function() { var jid = $(this).attr('jid'); var name = $(this).attr('name') || jid; var bid = jsxc.jidToBid(jid); var sub = $(this).attr('subscription'); buddies.push(bid); jsxc.storage.removeUserItem('res', bid); jsxc.storage.saveBuddy(bid, { jid: jid, name: name, status: 0, sub: sub, res: [] }); jsxc.gui.roster.add(bid); }); if (buddies.length === 0) { jsxc.gui.roster.empty(); } jsxc.storage.setUserItem('buddylist', buddies); jsxc.debug('Roster loaded'); $(document).trigger('cloaded.roster.jsxc'); }, /** * Triggerd on roster changes * * @param {dom} iq * @returns {Boolean} True to preserve handler * @private */ onRosterChanged: function(iq) { /* * <iq from='' type='set' id=''> <query xmlns='jabber:iq:roster'> <item * jid='' name='' subscription='' /> </query> </iq> */ jsxc.debug('onRosterChanged', iq); $(iq).find('item').each(function() { var jid = $(this).attr('jid'); var name = $(this).attr('name') || jid; var bid = jsxc.jidToBid(jid); var sub = $(this).attr('subscription'); // var ask = $(this).attr('ask'); if (sub === 'remove') { jsxc.gui.roster.purge(bid); } else { var bl = jsxc.storage.getUserItem('buddylist'); if (bl.indexOf(bid) < 0) { bl.push(bid); // (INFO) push returns the new length jsxc.storage.setUserItem('buddylist', bl); } var temp = jsxc.storage.saveBuddy(bid, { jid: jid, name: name, sub: sub }); if (temp === 'updated') { jsxc.gui.update(bid); jsxc.gui.roster.reorder(bid); } else { jsxc.gui.roster.add(bid); } } // Remove pending friendship request from notice list if (sub === 'from' || sub === 'both') { var notices = jsxc.storage.getUserItem('notices'); var noticeKey = null, notice; for (noticeKey in notices) { notice = notices[noticeKey]; if (notice.fnName === 'gui.showApproveDialog' && notice.fnParams[0] === jid) { jsxc.debug('Remove notice with key ' + noticeKey); jsxc.notice.remove(noticeKey); } } } }); if (!jsxc.storage.getUserItem('buddylist') || jsxc.storage.getUserItem('buddylist').length === 0) { jsxc.gui.roster.empty(); } else { $('#jsxc_roster > p:first').remove(); } // preserve handler return true; }, /** * Triggered on incoming presence stanzas * * @param {dom} presence * @private */ onPresence: function(presence) { /* * <presence xmlns='jabber:client' type='unavailable' from='' to=''/> * * <presence xmlns='jabber:client' from='' to=''> <priority>5</priority> * <c xmlns='http://jabber.org/protocol/caps' * node='http://psi-im.org/caps' ver='caps-b75d8d2b25' ext='ca cs * ep-notify-2 html'/> </presence> * * <presence xmlns='jabber:client' from='' to=''> <show>chat</show> * <status></status> <priority>5</priority> <c * xmlns='http://jabber.org/protocol/caps' * node='http://psi-im.org/caps' ver='caps-b75d8d2b25' ext='ca cs * ep-notify-2 html'/> </presence> */ jsxc.debug('onPresence', presence); var ptype = $(presence).attr('type'); var from = $(presence).attr('from'); var jid = Strophe.getBareJidFromJid(from).toLowerCase(); var r = Strophe.getResourceFromJid(from); var bid = jsxc.jidToBid(jid); var data = jsxc.storage.getUserItem('buddy', bid); var res = jsxc.storage.getUserItem('res', bid) || {}; var status = null; var xVCard = $(presence).find('x[xmlns="vcard-temp:x:update"]'); if (jid === Strophe.getBareJidFromJid(jsxc.storage.getItem("jid"))) { return true; } if (ptype === 'error') { jsxc.error('[XMPP] ' + $(presence).attr('code')); return true; } // incoming friendship request if (ptype === 'subscribe') { jsxc.storage.setUserItem('friendReq', { jid: jid, approve: -1 }); jsxc.notice.add('%%Friendship request%%', '%%from%% ' + jid, 'gui.showApproveDialog', [ jid ]); return true; } else if (ptype === 'unavailable' || ptype === 'unsubscribed') { status = jsxc.CONST.STATUS.indexOf('offline'); } else { var show = $(presence).find('show').text(); if (show === '') { status = jsxc.CONST.STATUS.indexOf('online'); } else { status = jsxc.CONST.STATUS.indexOf(show); } } if (status === 0) { delete res[r]; } else { res[r] = status; } var maxVal = []; var max = 0, prop = null; for (prop in res) { if (res.hasOwnProperty(prop)) { if (max <= res[prop]) { if (max !== res[prop]) { maxVal = []; max = res[prop]; } maxVal.push(prop); } } } if (data.status === 0 && max > 0) { // buddy has come online jsxc.notification.notify(data.name, jsxc.translate('%%has come online%%.')); } data.status = max; data.res = maxVal; data.jid = jid; // Looking for avatar if (xVCard.length > 0) { var photo = xVCard.find('photo'); if (photo.length > 0 && photo.text() !== data.avatar) { jsxc.storage.removeUserItem('avatar', data.avatar); data.avatar = photo.text(); } } // Reset jid if (jsxc.gui.window.get(bid).length > 0) { jsxc.gui.window.get(bid).data('jid', jid); } jsxc.storage.setUserItem('buddy', bid, data); jsxc.storage.setUserItem('res', bid, res); jsxc.debug('Presence (' + from + '): ' + status); jsxc.gui.update(bid); jsxc.gui.roster.reorder(bid); $(document).trigger('presence.jsxc', [ from, status, presence ]); // preserve handler return true; }, /** * Triggered on incoming message stanzas * * @param {dom} presence * @returns {Boolean} * @private */ onMessage: function(stanza) { var forwarded = $(stanza).find('forwarded[xmlns="' + jsxc.CONST.NS.FORWARD + '"]'); var message, carbon; if (forwarded.length > 0) { message = forwarded.find('> message'); forwarded = true; carbon = $(stanza).find('> [xmlns="' + jsxc.CONST.NS.CARBONS + '"]'); if (carbon.length === 0) { carbon = false; } jsxc.debug('Incoming forwarded message', message); } else { message = stanza; forwarded = false; carbon = false; jsxc.debug('Incoming message', message); } var body = $(message).find('body:first').text(); if (!body || (body.match(/\?OTR/i) && forwarded)) { return true; } var type = $(message).attr('type'); var from = $(message).attr('from'); var mid = $(message).attr('id'); var bid; var delay = $(message).find('delay[xmlns="urn:xmpp:delay"]'); var stamp = (delay.length > 0) ? new Date(delay.attr('stamp')) : new Date(); stamp = stamp.getTime(); if (carbon) { var direction = (carbon.prop("tagName") === 'sent') ? 'out' : 'in'; bid = jsxc.jidToBid((direction === 'out') ? $(message).attr('to') : from); jsxc.gui.window.postMessage(bid, direction, body, false, forwarded, stamp); return true; } else if (forwarded) { // Someone forwarded a message to us body = from + jsxc.translate(' %%to%% ') + $(stanza).attr('to') + '"' + body + '"'; from = $(stanza).attr('from'); } var jid = Strophe.getBareJidFromJid(from); bid = jsxc.jidToBid(jid); var data = jsxc.storage.getUserItem('buddy', bid); var request = $(message).find("request[xmlns='urn:xmpp:receipts']"); if (data === null) { // jid not in roster var chat = jsxc.storage.getUserItem('chat', bid) || []; if (chat.length === 0) { jsxc.notice.add('%%Unknown sender%%', '%%You received a message from an unknown sender%% (' + bid + ').', 'gui.showUnknownSender', [ bid ]); } var msg = jsxc.removeHTML(body); msg = jsxc.escapeHTML(msg); jsxc.storage.saveMessage(bid, 'in', msg, false, forwarded, stamp); return true; } var win = jsxc.gui.window.init(bid); // If we now the full jid, we use it if (type === 'chat') { win.data('jid', from); jsxc.storage.updateUserItem('buddy', bid, { jid: from }); } $(document).trigger('message.jsxc', [ from, body ]); // create related otr object if (jsxc.master && !jsxc.otr.objects[bid]) { jsxc.otr.create(bid); } if (!forwarded && mid !== null && request.length && data !== null && (data.sub === 'both' || data.sub === 'from') && type === 'chat') { // Send received according to XEP-0184 jsxc.xmpp.conn.send($msg({ to: from }).c('received', { xmlns: 'urn:xmpp:receipts', id: mid })); } if (jsxc.otr.objects.hasOwnProperty(bid)) { jsxc.otr.objects[bid].receiveMsg(body, stamp); } else { jsxc.gui.window.postMessage(bid, 'in', body, false, forwarded, stamp); } // preserve handler return true; }, /** * Triggerd if the rid changed * * @param {event} ev * @param {obejct} data * @private */ onRidChange: function(ev, data) { jsxc.storage.setItem('rid', data.rid); }, /** * response to friendship request * * @param {string} from jid from original friendship req * @param {boolean} approve */ resFriendReq: function(from, approve) { if (jsxc.master) { jsxc.xmpp.conn.send($pres({ to: from, type: (approve) ? 'subscribed' : 'unsubscribed' })); jsxc.storage.removeUserItem('friendReq'); jsxc.gui.dialog.close(); } else { jsxc.storage.updateUserItem('friendReq', 'approve', approve); } }, /** * Add buddy to my friends * * @param {string} username jid * @param {string} alias */ addBuddy: function(username, alias) { var bid = jsxc.jidToBid(username); if (jsxc.master) { // add buddy to roster (trigger onRosterChanged) var iq = $iq({ type: 'set' }).c('query', { xmlns: 'jabber:iq:roster' }).c('item', { jid: username, name: alias || '' }); jsxc.xmpp.conn.sendIQ(iq); // send subscription request to buddy (trigger onRosterChanged) jsxc.xmpp.conn.send($pres({ to: username, type: 'subscribe' })); jsxc.storage.removeUserItem('add_' + bid); } else { jsxc.storage.setUserItem('add_' + bid, { username: username, alias: alias || null }); } }, /** * Remove buddy from my friends * * @param {type} jid */ removeBuddy: function(jid) { var bid = jsxc.jidToBid(jid); // Shortcut to remove buddy from roster and cancle all subscriptions var iq = $iq({ type: 'set' }).c('query', { xmlns: 'jabber:iq:roster' }).c('item', { jid: Strophe.getBareJidFromJid(jid), subscription: 'remove' }); jsxc.xmpp.conn.sendIQ(iq); jsxc.gui.roster.purge(bid); }, onReceived: function(message) { var from = $(message).attr('from'); var jid = Strophe.getBareJidFromJid(from); var bid = jsxc.jidToBid(jid); var received = $(message).find("received[xmlns='urn:xmpp:receipts']"); if (received.length) { var receivedId = received.attr('id').replace(/:/, '-'); var chat = jsxc.storage.getUserItem('chat', bid); var i; for (i = chat.length - 1; i >= 0; i--) { if (chat[i].uid === receivedId) { chat[i].received = true; $('#' + receivedId).addClass('jsxc_received'); jsxc.storage.setUserItem('chat', bid, chat); break; } } } return true; }, /** * Public function to send message. * * @memberOf jsxc.xmpp * @param bid css jid of user * @param msg message * @param uid unique id */ sendMessage: function(bid, msg, uid) { if (jsxc.otr.objects.hasOwnProperty(bid)) { jsxc.otr.objects[bid].sendMsg(msg, uid); } else { jsxc.xmpp._sendMessage(jsxc.gui.window.get(bid).data('jid'), msg, uid); } }, /** * Create message stanza and send it. * * @memberOf jsxc.xmpp * @param jid Jabber id * @param msg Message * @param uid unique id * @private */ _sendMessage: function(jid, msg, uid) { var data = jsxc.storage.getUserItem('buddy', jsxc.jidToBid(jid)) || {}; var isBar = (Strophe.getBareJidFromJid(jid) === jid); var type = data.type || 'chat'; var xmlMsg = $msg({ to: jid, type: type, id: uid }).c('body').t(msg); if (jsxc.xmpp.carbons.enabled && msg.match(/^\?OTR/)) { xmlMsg.up().c("private", { xmlns: jsxc.CONST.NS.CARBONS }); } if (type === 'chat' && (isBar || jsxc.xmpp.conn.caps.hasFeatureByJid(jid, Strophe.NS.RECEIPTS))) { // Add request according to XEP-0184 xmlMsg.up().c('request', { xmlns: 'urn:xmpp:receipts' }); } jsxc.xmpp.conn.send(xmlMsg); }, /** * This function loads a vcard. * * @memberOf jsxc.xmpp * @param bid * @param cb * @param error_cb */ loadVcard: function(bid, cb, error_cb) { if (jsxc.master) { jsxc.xmpp.conn.vcard.get(cb, bid, error_cb); } else { jsxc.storage.setUserItem('vcard', bid, 'request:' + (new Date()).getTime()); $(document).one('loaded.vcard.jsxc', function(ev, result) { if (result && result.state === 'success') { cb($(result.data).get(0)); } else { error_cb(); } }); } }, /** * Retrieves capabilities. * * @memberOf jsxc.xmpp * @param jid * @returns List of known capabilities */ getCapabilitiesByJid: function(jid) { if (jsxc.xmpp.conn) { return jsxc.xmpp.conn.caps.getCapabilitiesByJid(jid); } var jidVerIndex = JSON.parse(localStorage.getItem('strophe.caps._jidVerIndex')) || {}; var knownCapabilities = JSON.parse(localStorage.getItem('strophe.caps._knownCapabilities')) || {}; if (jidVerIndex[jid]) { return knownCapabilities[jidVerIndex[jid]]; } return null; } }; /** * Handle carbons (XEP-0280); * * @namespace jsxc.xmpp.carbons */ jsxc.xmpp.carbons = { enabled: false, /** * Enable carbons. * * @memberOf jsxc.xmpp.carbons * @param cb callback */ enable: function(cb) { var iq = $iq({ type: 'set' }).c('enable', { xmlns: jsxc.CONST.NS.CARBONS }); jsxc.xmpp.conn.sendIQ(iq, function() { jsxc.xmpp.carbons.enabled = true; jsxc.debug('Carbons enabled'); if (cb) { cb.call(this); } }, function(stanza) { jsxc.warn('Could not enable carbons', stanza); }); }, /** * Disable carbons. * * @memberOf jsxc.xmpp.carbons * @param cb callback */ disable: function(cb) { var iq = $iq({ type: 'set' }).c('disable', { xmlns: jsxc.CONST.NS.CARBONS }); jsxc.xmpp.conn.sendIQ(iq, function() { jsxc.xmpp.carbons.enabled = false; jsxc.debug('Carbons disabled'); if (cb) { cb.call(this); } }, function(stanza) { jsxc.warn('Could not disable carbons', stanza); }); }, /** * Enable/Disable carbons depending on options key. * * @memberOf jsxc.xmpp.carbons * @param err error message */ refresh: function(err) { if (err === false) { return; } if (jsxc.options.get('carbons').enable) { return jsxc.xmpp.carbons.enable(); } return jsxc.xmpp.carbons.disable(); } }; /** * Handle long-live data * * @namespace jsxc.storage */ jsxc.storage = { /** * Prefix for localstorage * * @privat */ PREFIX: 'jsxc', SEP: ':', /** * @param {type} uk Should we generate a user prefix? * @returns {String} prefix * @memberOf jsxc.storage */ getPrefix: function(uk) { var self = jsxc.storage; return self.PREFIX + self.SEP + ((uk && jsxc.bid) ? jsxc.bid + self.SEP : ''); }, /** * Save item to storage * * @function * @param {String} key variablename * @param {Object} value value * @param {String} uk Userkey? Should we add the bid as prefix? */ setItem: function(key, value, uk) { // Workaround for non-conform browser if (jsxc.storageNotConform > 0 && key !== 'rid' && key !== 'lastActivity') { if (jsxc.storageNotConform > 1 && jsxc.toSNC === null) { jsxc.toSNC = window.setTimeout(function() { jsxc.storageNotConform = 0; jsxc.storage.setItem('storageNotConform', 0); }, 1000); } jsxc.ls.push(JSON.stringify({ key: key, value: value })); } if (typeof (value) === 'object') { value = JSON.stringify(value); } localStorage.setItem(jsxc.storage.getPrefix(uk) + key, value); }, setUserItem: function(type, key, value) { var self = jsxc.storage; if (arguments.length === 2) { value = key; key = type; type = ''; } else if (arguments.length === 3) { key = type + self.SEP + key; } return jsxc.storage.setItem(key, value, true); }, /** * Load item from storage * * @function * @param {String} key variablename * @param {String} uk Userkey? Should we add the bid as prefix? */ getItem: function(key, uk) { key = jsxc.storage.getPrefix(uk) + key; var value = localStorage.getItem(key); try { return JSON.parse(value); } catch (e) { return value; } }, /** * Get a user item from storage. * * @param key * @returns user item */ getUserItem: function(type, key) { var self = jsxc.storage; if (arguments.length === 1) { key = type; } else if (arguments.length === 2) { key = type + self.SEP + key; } return jsxc.storage.getItem(key, true); }, /** * Remove item from storage * * @function * @param {String} key variablename * @param {String} uk Userkey? Should we add the bid as prefix? */ removeItem: function(key, uk) { // Workaround for non-conform browser if (jsxc.storageNotConform && key !== 'rid' && key !== 'lastActivity') { jsxc.ls.push(JSON.stringify({ key: jsxc.storage.prefix + key, value: '' })); } localStorage.removeItem(jsxc.storage.getPrefix(uk) + key); }, /** * Remove user item from storage. * * @param key */ removeUserItem: function(type, key) { var self = jsxc.storage; if (arguments.length === 1) { key = type; } else if (arguments.length === 2) { key = type + self.SEP + key; } jsxc.storage.removeItem(key, true); }, /** * Updates value of a variable in a saved object. * * @function * @param {String} key variablename * @param {String|object} variable variablename in object or object with * variable/key pairs * @param {Object} [value] value * @param {String} uk Userkey? Should we add the bid as prefix? */ updateItem: function(key, variable, value, uk) { var data = jsxc.storage.getItem(key, uk) || {}; if (typeof (variable) === 'object') { $.each(variable, function(key, val) { if (typeof (data[key]) === 'undefined') { jsxc.debug('Variable ' + key + ' doesn\'t exist in ' + variable + '. It was created.'); } data[key] = val; }); } else { if (typeof (data[variable]) === 'undefined') { jsxc.debug('Variable ' + variable + ' doesn\'t exist. It was created.'); } data[variable] = value; } jsxc.storage.setItem(key, data, uk); }, /** * Updates value of a variable in a saved user object. * * @param {String} key variablename * @param {String|object} variable variablename in object or object with * variable/key pairs * @param {Object} [value] value */ updateUserItem: function(type, key, variable, value) { var self = jsxc.storage; if (arguments.length === 4 || (arguments.length === 3 && typeof variable === 'object')) { key = type + self.SEP + key; } else { value = variable; variable = key; key = type; } return jsxc.storage.updateItem(key, variable, value, true); }, /** * Inkrements value * * @function * @param {String} key variablename * @param {String} uk Userkey? Should we add the bid as prefix? */ ink: function(key, uk) { jsxc.storage.setItem(key, Number(jsxc.storage.getItem(key, uk)) + 1, uk); }, /** * Remove element from array or object * * @param {string} key name of array or object * @param {string} name name of element in array or object * @param {String} uk Userkey? Should we add the bid as prefix? * @returns {undefined} */ removeElement: function(key, name, uk) { var item = jsxc.storage.getItem(key, uk); if ($.isArray(item)) { item = $.grep(item, function(e) { return e !== name; }); } else if (typeof (item) === 'object') { delete item[name]; } jsxc.storage.setItem(key, item, uk); }, removeUserElement: function(type, key, name) { var self = jsxc.storage; if (arguments.length === 2) { name = key; key = type; } else if (arguments.length === 3) { key = type + self.SEP + key; } return jsxc.storage.removeElement(key, name, true); }, /** * Triggered if changes are recognized * * @function * @param {event} e Storageevent * @param {String} e.key Keyname which triggered event * @param {Object} e.oldValue Old Value for key * @param {Object} e.newValue New Value for key * @param {String} e.url */ onStorage: function(e) { // skip if (e.key === jsxc.storage.PREFIX + jsxc.storage.SEP + 'rid' || e.key === jsxc.storage.PREFIX + jsxc.storage.SEP + 'lastActivity') { return; } var re = new RegExp('^' + jsxc.storage.PREFIX + jsxc.storage.SEP + '(?:[^' + jsxc.storage.SEP + ']+@[^' + jsxc.storage.SEP + ']+' + jsxc.storage.SEP + ')?(.*)', 'i'); var key = e.key.replace(re, '$1'); // Workaround for non-conform browser: Triggered event on every page // (own) if (jsxc.storageNotConform > 0 && jsxc.ls.length > 0) { var val = e.newValue; try { val = JSON.parse(val); } catch (err) { } var index = $.inArray(JSON.stringify({ key: key, value: val }), jsxc.ls); if (index >= 0) { // confirm that the storage event is not fired regularly if (jsxc.storageNotConform > 1) { window.clearTimeout(jsxc.toSNC); jsxc.storageNotConform = 1; jsxc.storage.setItem('storageNotConform', 1); } jsxc.ls.splice(index, 1); return; } } // Workaround for non-conform browser if (e.oldValue === e.newValue) { return; } var n, o; var bid = key.replace(new RegExp('[^' + jsxc.storage.SEP + ']+' + jsxc.storage.SEP + '(.*)', 'i'), '$1'); // react if someone ask, if there is a master if (jsxc.master && key === 'alive') { jsxc.debug('Master request.'); jsxc.storage.ink('alive'); return; } // master alive if (!jsxc.master && (key === 'alive' || key === 'alive_busy') && !jsxc.triggeredFromElement) { // reset timeout window.clearTimeout(jsxc.to); jsxc.to = window.setTimeout(jsxc.checkMaster, ((key === 'alive') ? jsxc.options.timeout : jsxc.options.busyTimeout) + jsxc.random(60)); // only call the first time if (!jsxc.role_allocation) { jsxc.onSlave(); } return; } if (key.match(/^notices/)) { jsxc.notice.load(); } if (key.match(/^presence/)) { jsxc.gui.changePresence(e.newValue, true); } if (key.match(/^options/) && e.newValue) { n = JSON.parse(e.newValue); if (typeof n.muteNotification !== 'undefined' && n.muteNotification) { jsxc.notification.muteSound(true); } else { jsxc.notification.unmuteSound(true); } } if (key.match(/^hidden/)) { if (jsxc.master) { clearTimeout(jsxc.toNotification); } else { jsxc.isHidden(); } } if (key.match(new RegExp('^chat' + jsxc.storage.SEP))) { var posts = JSON.parse(e.newValue); var data, el; while (posts.length > 0) { data = posts.pop(); el = $('#' + data.uid); if (el.length === 0) { if (jsxc.master && data.direction === 'out') { jsxc.xmpp.sendMessage(bid, data.msg, data.uid); } jsxc.gui.window._postMessage(bid, data); } else if (data.received) { el.addClass('jsxc_received'); } } return; } if (key.match(new RegExp('^window' + jsxc.storage.SEP))) { if (!e.newValue) { jsxc.gui.window._close(bid); return; } if (!e.oldValue) { jsxc.gui.window.open(bid); return; } n = JSON.parse(e.newValue); if (n.minimize) { jsxc.gui.window._hide(bid); } else { jsxc.gui.window._show(bid); } jsxc.gui.window.setText(bid, n.text); return; } if (key.match(new RegExp('^smp' + jsxc.storage.SEP))) { if (!e.newValue) { jsxc.gui.dialog.close(); if (jsxc.master) { jsxc.otr.objects[bid].sm.abort(); } return; } n = JSON.parse(e.newValue); if (typeof (n.data) !== 'undefined') { jsxc.otr.onSmpQuestion(bid, n.data); } else if (jsxc.master && n.sec) { jsxc.gui.dialog.close(); jsxc.otr.sendSmpReq(bid, n.sec, n.quest); } } if (!jsxc.master && key.match(new RegExp('^buddy' + jsxc.storage.SEP))) { if (!e.newValue) { jsxc.gui.roster.purge(bid); return; } if (!e.oldValue) { jsxc.gui.roster.add(bid); return; } n = JSON.parse(e.newValue); o = JSON.parse(e.oldValue); jsxc.gui.update(bid); if (o.status !== n.status || o.sub !== n.sub) { jsxc.gui.roster.reorder(bid); } } if (jsxc.master && key.match(new RegExp('^deletebuddy' + jsxc.storage.SEP)) && e.newValue) { n = JSON.parse(e.newValue); jsxc.xmpp.removeBuddy(n.jid); jsxc.storage.removeUserItem(key); } if (jsxc.master && key.match(new RegExp('^buddy' + jsxc.storage.SEP))) { n = JSON.parse(e.newValue); o = JSON.parse(e.oldValue); if (o.transferReq !== n.transferReq) { jsxc.storage.updateUserItem('buddy', bid, 'transferReq', -1); if (n.transferReq === 0) { jsxc.otr.goPlain(bid); } if (n.transferReq === 1) { jsxc.otr.goEncrypt(bid); } } if (o.name !== n.name) { jsxc.gui.roster._rename(bid, n.name); } } // logout if (key === 'sid') { if (!e.newValue) { // if (jsxc.master && jsxc.xmpp.conn) { // jsxc.xmpp.conn.disconnect(); // jsxc.triggeredFromElement = true; // } jsxc.xmpp.logout(); } return; } if (key === 'friendReq') { n = JSON.parse(e.newValue); if (jsxc.master && n.approve >= 0) { jsxc.xmpp.resFriendReq(n.jid, n.approve); } } if (jsxc.master && key.match(new RegExp('^add' + jsxc.storage.SEP))) { n = JSON.parse(e.newValue); jsxc.xmpp.addBuddy(n.username, n.alias); } if (key === 'roster') { jsxc.gui.roster.toggle(); } if (jsxc.master && key.match(new RegExp('^vcard' + jsxc.storage.SEP)) && e.newValue !== null && e.newValue.match(/^request:/)) { jsxc.xmpp.loadVcard(bid, function(stanza) { jsxc.storage.setUserItem('vcard', bid, { state: 'success', data: $('<div>').append(stanza).html() }); }, function() { jsxc.storage.setUserItem('vcard', bid, { state: 'error' }); }); } if (!jsxc.master && key.match(new RegExp('^vcard' + jsxc.storage.SEP)) && e.newValue !== null && !e.newValue.match(/^request:/)) { n = JSON.parse(e.newValue); if (typeof n.state !== 'undefined') { $(document).trigger('loaded.vcard.jsxc', n); } jsxc.storage.removeUserItem('vcard', bid); } }, /** * Save message to storage. * * @memberOf jsxc.storage * @param bid * @param direction * @param msg * @param encrypted * @param forwarded * @return post */ saveMessage: function(bid, direction, msg, encrypted, forwarded, stamp) { var chat = jsxc.storage.getUserItem('chat', bid) || []; var uid = new Date().getTime() + ':msg'; if (chat.length > jsxc.options.get('numberOfMsg')) { chat.pop(); } var post = { direction: direction, msg: msg, uid: uid.replace(/:/, '-'), received: false, encrypted: encrypted || false, forwarded: forwarded || false, stamp: stamp || new Date().getTime() }; chat.unshift(post); jsxc.storage.setUserItem('chat', bid, chat); return post; }, /** * Save or update buddy data. * * @memberOf jsxc.storage * @param bid * @param data * @returns {String} Updated or created */ saveBuddy: function(bid, data) { if (jsxc.storage.getUserItem('buddy', bid)) { jsxc.storage.updateUserItem('buddy', bid, data); return 'updated'; } jsxc.storage.setUserItem('buddy', bid, $.extend({ jid: '', name: '', status: 0, sub: 'none', msgstate: 0, transferReq: -1, trust: false, fingerprint: null, res: [], type: 'chat' }, data)); return 'created'; } }; /** * @namespace jsxc.otr */ jsxc.otr = { /** list of otr objects */ objects: {}, dsaFallback: null, /** * Handler for otr receive event * * @memberOf jsxc.otr * @param {string} bid * @param {string} msg received message * @param {string} encrypted True, if msg was encrypted. */ receiveMessage: function(bid, msg, encrypted, stamp) { if (jsxc.otr.objects[bid].msgstate !== OTR.CONST.MSGSTATE_PLAINTEXT) { jsxc.otr.backup(bid); } if (jsxc.otr.objects[bid].msgstate !== OTR.CONST.MSGSTATE_PLAINTEXT && !encrypted) { jsxc.gui.window.postMessage(bid, 'sys', jsxc.translate('%%Received an unencrypted message.%% [') + msg + ']', encrypted, stamp); } else { jsxc.gui.window.postMessage(bid, 'in', msg, encrypted, stamp); } }, /** * Handler for otr send event * * @param {string} jid * @param {string} msg message to be send */ sendMessage: function(jid, msg, uid) { if (jsxc.otr.objects[jsxc.jidToBid(jid)].msgstate !== 0) { jsxc.otr.backup(jsxc.jidToBid(jid)); } jsxc.xmpp._sendMessage(jid, msg, uid); }, /** * Create new otr instance * * @param {type} bid * @returns {undefined} */ create: function(bid) { if (jsxc.otr.objects.hasOwnProperty(bid)) { return; } if (!jsxc.options.otr.priv) { return; } // save list of otr objects var ol = jsxc.storage.getUserItem('otrlist') || []; if (ol.indexOf(bid) < 0) { ol.push(bid); jsxc.storage.setUserItem('otrlist', ol); } jsxc.otr.objects[bid] = new OTR(jsxc.options.otr); if (jsxc.options.otr.SEND_WHITESPACE_TAG) { jsxc.otr.objects[bid].SEND_WHITESPACE_TAG = true; } if (jsxc.options.otr.WHITESPACE_START_AKE) { jsxc.otr.objects[bid].WHITESPACE_START_AKE = true; } jsxc.otr.objects[bid].on('status', function(status) { var data = jsxc.storage.getUserItem('buddy', bid); if (data === null) { return; } switch (status) { case OTR.CONST.STATUS_SEND_QUERY: jsxc.gui.window.postMessage(bid, 'sys', jsxc.l.trying_to_start_private_conversation); break; case OTR.CONST.STATUS_AKE_SUCCESS: data.fingerprint = jsxc.otr.objects[bid].their_priv_pk.fingerprint(); data.msgstate = OTR.CONST.MSGSTATE_ENCRYPTED; var msg = (jsxc.otr.objects[bid].trust ? jsxc.l.Verified : jsxc.l.Unverified) + ' ' + jsxc.l.private_conversation_started; jsxc.gui.window.postMessage(bid, 'sys', msg); break; case OTR.CONST.STATUS_END_OTR: data.fingerprint = null; if (jsxc.otr.objects[bid].msgstate === OTR.CONST.MSGSTATE_PLAINTEXT) { // we abort the private conversation data.msgstate = OTR.CONST.MSGSTATE_PLAINTEXT; jsxc.gui.window.postMessage(bid, 'sys', jsxc.l.private_conversation_aborted); } else { // the buddy abort the private conversation data.msgstate = OTR.CONST.MSGSTATE_FINISHED; jsxc.gui.window.postMessage(bid, 'sys', jsxc.l.your_buddy_closed_the_private_conversation_you_should_do_the_same); } break; case OTR.CONST.STATUS_SMP_HANDLE: jsxc.keepBusyAlive(); break; } jsxc.storage.setUserItem('buddy', bid, data); // for encryption and verification state jsxc.gui.update(bid); }); jsxc.otr.objects[bid].on('smp', function(type, data) { switch (type) { case 'question': // verification request received jsxc.gui.window.postMessage(bid, 'sys', jsxc.l.Authentication_request_received); if ($('#jsxc_dialog').length > 0) { jsxc.otr.objects[bid].sm.abort(); break; } jsxc.otr.onSmpQuestion(bid, data); jsxc.storage.setUserItem('smp_' + bid, { data: data || null }); break; case 'trust': // verification completed jsxc.otr.objects[bid].trust = data; jsxc.storage.updateUserItem('buddy', bid, 'trust', data); jsxc.otr.backup(bid); jsxc.gui.update(bid); if (data) { jsxc.gui.window.postMessage(bid, 'sys', jsxc.l.conversation_is_now_verified); } else { jsxc.gui.window.postMessage(bid, 'sys', jsxc.l.authentication_failed); } jsxc.storage.removeUserItem('smp_' + bid); jsxc.gui.dialog.close(); break; case 'abort': jsxc.gui.window.postMessage(bid, 'sys', jsxc.l.Authentication_aborted); break; default: jsxc.debug('[OTR] sm callback: Unknown type: ' + type); } }); // Receive message jsxc.otr.objects[bid].on('ui', function(msg, encrypted, stamp) { jsxc.otr.receiveMessage(bid, msg, encrypted === true, stamp); }); // Send message jsxc.otr.objects[bid].on('io', function(msg, uid) { var jid = jsxc.gui.window.get(bid).data('jid') || jsxc.otr.objects[bid].jid; jsxc.otr.objects[bid].jid = jid; jsxc.otr.sendMessage(jid, msg, uid); }); jsxc.otr.objects[bid].on('error', function(err) { // Handle this case in jsxc.otr.receiveMessage if (err !== 'Received an unencrypted message.') { jsxc.gui.window.postMessage(bid, 'sys', '[OTR] ' + jsxc.translate('%%' + err + '%%')); } jsxc.error('[OTR] ' + err); }); jsxc.otr.restore(bid); }, /** * show verification dialog with related part (secret or question) * * @param {type} bid * @param {string} [data] * @returns {undefined} */ onSmpQuestion: function(bid, data) { jsxc.gui.showVerification(bid); $('#jsxc_dialog select').prop('selectedIndex', (data ? 2 : 3)).change(); $('#jsxc_dialog > div:eq(0)').hide(); if (data) { $('#jsxc_dialog > div:eq(2)').find('#jsxc_quest').val(data).prop('disabled', true); $('#jsxc_dialog > div:eq(2)').find('.creation').text('Answer'); $('#jsxc_dialog > div:eq(2)').find('.jsxc_explanation').text(jsxc.l.your_buddy_is_attempting_to_determine_ + ' ' + jsxc.l.to_authenticate_to_your_buddy + jsxc.l.enter_the_answer_and_click_answer); } else { $('#jsxc_dialog > div:eq(3)').find('.jsxc_explanation').text(jsxc.l.your_buddy_is_attempting_to_determine_ + ' ' + jsxc.l.to_authenticate_to_your_buddy + jsxc.l.enter_the_secret); } $('#jsxc_dialog .jsxc_close').click(function() { jsxc.storage.removeUserItem('smp_' + bid); if (jsxc.master) { jsxc.otr.objects[bid].sm.abort(); } }); }, /** * Send verification request to buddy * * @param {string} bid * @param {string} sec secret * @param {string} [quest] question * @returns {undefined} */ sendSmpReq: function(bid, sec, quest) { jsxc.keepBusyAlive(); jsxc.otr.objects[bid].smpSecret(sec, quest || ''); }, /** * Toggle encryption state * * @param {type} bid * @returns {undefined} */ toggleTransfer: function(bid) { if (jsxc.storage.getUserItem('buddy', bid).msgstate === 0) { jsxc.otr.goEncrypt(bid); } else { jsxc.otr.goPlain(bid); } }, /** * Send request to encrypt the session * * @param {type} bid * @returns {undefined} */ goEncrypt: function(bid) { if (jsxc.master) { jsxc.otr.objects[bid].sendQueryMsg(); } else { jsxc.storage.updateUserItem('buddy', bid, 'transferReq', 1); } }, /** * Abort encryptet session * * @param {type} bid * @param cb callback * @returns {undefined} */ goPlain: function(bid, cb) { if (jsxc.master) { jsxc.otr.objects[bid].endOtr.call(jsxc.otr.objects[bid], cb); jsxc.otr.objects[bid].init.call(jsxc.otr.objects[bid]); jsxc.otr.backup(bid); } else { jsxc.storage.updateUserItem('buddy', bid, 'transferReq', 0); } }, /** * Backups otr session * * @param {string} bid */ backup: function(bid) { var o = jsxc.otr.objects[bid]; // otr object var r = {}; // return value if (o === null) { return; } // all variables which should be saved var savekey = [ 'jid', 'our_instance_tag', 'msgstate', 'authstate', 'fragment', 'their_y', 'their_old_y', 'their_keyid', 'their_instance_tag', 'our_dh', 'our_old_dh', 'our_keyid', 'sessKeys', 'storedMgs', 'oldMacKeys', 'trust', 'transmittedRS', 'ssid', 'receivedPlaintext', 'authstate', 'send_interval' ]; var i; for (i = 0; i < savekey.length; i++) { r[savekey[i]] = JSON.stringify(o[savekey[i]]); } if (o.their_priv_pk !== null) { r.their_priv_pk = JSON.stringify(o.their_priv_pk.packPublic()); } if (o.ake.otr_version && o.ake.otr_version !== '') { r.otr_version = JSON.stringify(o.ake.otr_version); } jsxc.storage.setUserItem('otr', bid, r); }, /** * Restore old otr session * * @param {string} bid */ restore: function(bid) { var o = jsxc.otr.objects[bid]; var d = jsxc.storage.getUserItem('otr', bid); if (o !== null || d !== null) { var key; for (key in d) { if (d.hasOwnProperty(key)) { var val = JSON.parse(d[key]); if (key === 'their_priv_pk' && val !== null) { val = DSA.parsePublic(val); } if (key === 'otr_version' && val !== null) { o.ake.otr_version = val; } else { o[key] = val; } } } jsxc.otr.objects[bid] = o; if (o.msgstate === 1 && o.their_priv_pk !== null) { o._smInit.call(jsxc.otr.objects[bid]); } } jsxc.otr.enable(bid); }, /** * Create or load DSA key * * @returns {unresolved} */ createDSA: function() { if (jsxc.options.otr.priv) { return; } if (jsxc.storage.getUserItem('key') === null) { var msg = jsxc.l.Creating_your_private_key_; var worker = null; if (Worker) { // try to create web-worker try { worker = new Worker(jsxc.options.root + '/lib/otr/build/dsa-webworker.js'); } catch (err) { jsxc.warn('Couldn\'t create web-worker.', err); } } jsxc.otr.dsaFallback = (worker === null); if (!jsxc.otr.dsaFallback) { // create DSA key in background jsxc._onMaster(); worker.onmessage = function(e) { var type = e.data.type; var val = e.data.val; if (type === 'debug') { jsxc.debug(val); } else if (type === 'data') { jsxc.otr.DSAready(DSA.parsePrivate(val)); } }; // start worker worker.postMessage({ imports: [ jsxc.options.root + '/lib/otr/vendor/salsa20.js', jsxc.options.root + '/lib/otr/vendor/bigint.js', jsxc.options.root + '/lib/otr/vendor/crypto.js', jsxc.options.root + '/lib/otr/vendor/eventemitter.js', jsxc.options.root + '/lib/otr/lib/const.js', jsxc.options.root + '/lib/otr/lib/helpers.js', jsxc.options.root + '/lib/otr/lib/dsa.js' ], seed: BigInt.getSeed(), debug: true }); } else { // fallback jsxc.gui.dialog.open(jsxc.gui.template.get('waitAlert', null, msg), { noClose: true }); jsxc.debug('DSA key creation started.'); // wait until the wait alert is opened setTimeout(function() { var dsa = new DSA(); jsxc.otr.DSAready(dsa); }, 500); } } else { jsxc.debug('DSA key loaded'); jsxc.options.otr.priv = DSA.parsePrivate(jsxc.storage.getUserItem('key')); jsxc.otr._createDSA(); } }, /** * Ending of createDSA(). */ _createDSA: function() { jsxc.storage.setUserItem('priv_fingerprint', jsxc.options.otr.priv.fingerprint()); if (jsxc.otr.dsaFallback !== false) { jsxc._onMaster(); } }, /** * Ending of DSA key generation. * * @param {DSA} dsa DSA object */ DSAready: function(dsa) { jsxc.storage.setUserItem('key', dsa.packPrivate()); jsxc.options.otr.priv = dsa; // close wait alert if (jsxc.otr.dsaFallback) { jsxc.gui.dialog.close(); } else { $.each(jsxc.storage.getUserItem('windowlist'), function(index, val) { jsxc.otr.create(val); }); } jsxc.otr._createDSA(); }, enable: function(bid) { jsxc.gui.window.get(bid).find('.jsxc_otr').removeClass('jsxc_disabled'); } }; /** * This namespace handles the Notification API. * * @namespace jsxc.notification */ jsxc.notification = { /** Current audio file. */ audio: null, /** * Register notification on incoming messages. * * @memberOf jsxc.notification */ init: function() { $(document).on('postmessagein.jsxc', function(event, bid, msg) { msg = (msg.match(/^\?OTR/)) ? jsxc.translate('%%Encrypted message%%') : msg; var data = jsxc.storage.getUserItem('buddy', bid); jsxc.notification.notify(jsxc.translate('%%New message from%% ') + data.name, msg, undefined, undefined, jsxc.CONST.SOUNDS.MSG); }); $(document).on('callincoming.jingle', function() { jsxc.notification.playSound(jsxc.CONST.SOUNDS.CALL, true, true); }); $(document).on('accept.call.jsxc reject.call.jsxc', function() { jsxc.notification.stopSound(); }); }, /** * Shows a pop up notification and optional play sound. * * @param title Title * @param msg Message * @param d Duration * @param force Should message also shown, if tab is visible? * @param soundFile Playing given sound file * @param loop Loop sound file? */ notify: function(title, msg, d, force, soundFile, loop) { if (!jsxc.options.notification || !jsxc.notification.hasPermission()) { return; // notifications disabled } if (!jsxc.isHidden() && !force) { return; // Tab is visible } jsxc.toNotification = setTimeout(function() { if (typeof soundFile === 'string') { jsxc.notification.playSound(soundFile, loop, force); } var popup = new Notification(jsxc.translate(title), { body: jsxc.translate(msg), icon: jsxc.options.root + '/img/XMPP_logo.png' }); var duration = d || jsxc.options.popupDuration; if (duration > 0) { setTimeout(function() { popup.close(); }, duration); } }, jsxc.toNotificationDelay); }, /** * Checks if browser has support for notifications and add on chrome to * the default api. * * @returns {Boolean} True if the browser has support. */ hasSupport: function() { if (window.webkitNotifications) { // prepare chrome window.Notification = function(title, opt) { var popup = window.webkitNotifications.createNotification(null, title, opt.body); popup.show(); popup.close = function() { popup.cancel(); }; return popup; }; var permission; switch (window.webkitNotifications.checkPermission()) { case 0: permission = jsxc.CONST.NOTIFICATION_GRANTED; break; case 2: permission = jsxc.CONST.NOTIFICATION_DENIED; break; default: // 1 permission = jsxc.CONST.NOTIFICATION_DEFAULT; } window.Notification.permission = permission; window.Notification.requestPermission = function(func) { window.webkitNotifications.requestPermission(func); }; return true; } else if (window.Notification) { return true; } else { return false; } }, /** * Ask user on first incoming message if we should inform him about new * messages. */ prepareRequest: function() { $(document).one('postmessagein.jsxc', function() { jsxc.switchEvents({ 'notificationready.jsxc': function() { jsxc.gui.dialog.close(); jsxc.notification.init(); jsxc.storage.setUserItem('notification', true); }, 'notificationfailure.jsxc': function() { jsxc.gui.dialog.close(); jsxc.options.notification = false; jsxc.storage.setUserItem('notification', false); } }); setTimeout(function() { jsxc.notice.add('%%Notifications%%?', '%%Should_we_notify_you_%%', 'gui.showRequestNotification'); }, 1000); }); }, /** * Request notification permission. */ requestPermission: function() { window.Notification.requestPermission(function(status) { if (window.Notification.permission !== status) { window.Notification.permission = status; } if (jsxc.notification.hasPermission()) { $(document).trigger('notificationready.jsxc'); } else { $(document).trigger('notificationfailure.jsxc'); } }); }, /** * Check permission. * * @returns {Boolean} True if we have the permission */ hasPermission: function() { return window.Notification.permission === jsxc.CONST.NOTIFICATION_GRANTED; }, /** * Plays the given file. * * @memberOf jsxc.notification * @param {string} soundFile File relative to the sound directory * @param {boolean} loop True for loop * @param {boolean} force Play even if a tab is visible. Default: false. */ playSound: function(soundFile, loop, force) { if (!jsxc.master) { // only master plays sound return; } if (jsxc.options.get('muteNotification') || jsxc.storage.getUserItem('presence') === 'dnd') { // sound mute or own presence is dnd return; } if (!jsxc.isHidden() && !force) { // tab is visible return; } // stop current audio file jsxc.notification.stopSound(); var audio = new Audio(jsxc.options.root + '/sound/' + soundFile); audio.loop = loop || false; audio.play(); jsxc.notification.audio = audio; }, /** * Stop/remove current sound. * * @memberOf jsxc.notification */ stopSound: function() { var audio = jsxc.notification.audio; if (typeof audio !== 'undefined' && audio !== null) { audio.pause(); jsxc.notification.audio = null; } }, /** * Mute sound. * * @memberOf jsxc.notification * @param {boolean} external True if triggered from external tab. Default: * false. */ muteSound: function(external) { $('#jsxc_menu .jsxc_muteNotification').text(jsxc.translate('%%Unmute%%')); if (external !== true) { jsxc.options.set('muteNotification', true); } }, /** * Unmute sound. * * @memberOf jsxc.notification * @param {boolean} external True if triggered from external tab. Default: * false. */ unmuteSound: function(external) { $('#jsxc_menu .jsxc_muteNotification').text(jsxc.translate('%%Mute%%')); if (external !== true) { jsxc.options.set('muteNotification', false); } } }; /** * This namespace handle the notice system. * * @namspace jsxc.notice * @memberOf jsxc */ jsxc.notice = { /** Number of notices. */ _num: 0, /** * Loads the saved notices. * * @memberOf jsxc.notice */ load: function() { // reset list $('#jsxc_notice ul li').remove(); $('#jsxc_notice > span').text(''); jsxc.notice._num = 0; var saved = jsxc.storage.getUserItem('notices') || []; var key = null; for (key in saved) { if (saved.hasOwnProperty(key)) { var val = saved[key]; jsxc.notice.add(val.msg, val.description, val.fnName, val.fnParams, key); } } }, /** * Add a new notice to the stack; * * @memberOf jsxc.notice * @param msg Header message * @param description Notice description * @param fnName Function name to be called if you open the notice * @param fnParams Array of params for function * @param id Notice id */ add: function(msg, description, fnName, fnParams, id) { var nid = id || Date.now(); var list = $('#jsxc_notice ul'); var notice = $('<li/>'); notice.click(function() { jsxc.notice.remove(nid); jsxc.exec(fnName, fnParams); return false; }); notice.text(jsxc.translate(msg)); notice.attr('title', jsxc.translate(description) || ''); notice.attr('data-nid', nid); list.append(notice); $('#jsxc_notice > span').text(++jsxc.notice._num); if (!id) { var saved = jsxc.storage.getUserItem('notices') || {}; saved[nid] = { msg: msg, description: description, fnName: fnName, fnParams: fnParams }; jsxc.storage.setUserItem('notices', saved); jsxc.notification.notify(msg, description || '', null, true, jsxc.CONST.SOUNDS.NOTICE); } }, /** * Removes notice from stack * * @memberOf jsxc.notice * @param nid The notice id */ remove: function(nid) { var el = $('#jsxc_notice li[data-nid=' + nid + ']'); el.remove(); $('#jsxc_notice > span').text(--jsxc.notice._num || ''); var s = jsxc.storage.getUserItem('notices'); delete s[nid]; jsxc.storage.setUserItem('notices', s); } }; /** * Contains all available translations * * @namespace jsxc.l10n * @memberOf jsxc */ jsxc.l10n = { en: { Logging_in: 'Logging in…', your_connection_is_unencrypted: 'Your connection is unencrypted.', your_connection_is_encrypted: 'Your connection is encrypted.', your_buddy_closed_the_private_connection: 'Your buddy closed the private connection.', start_private: 'Start private', close_private: 'Close private', your_buddy_is_verificated: 'Your buddy is verified.', you_have_only_a_subscription_in_one_way: 'You only have a one-way subscription.', authentication_query_sent: 'Authentication query sent.', your_message_wasnt_send_please_end_your_private_conversation: 'Your message was not sent. Please end your private conversation.', unencrypted_message_received: 'Unencrypted message received:', your_message_wasnt_send_because_you_have_no_valid_subscription: 'Your message was not sent because you have no valid subscription.', not_available: 'Not available', no_connection: 'No connection!', relogin: 'relogin', trying_to_start_private_conversation: 'Trying to start private conversation!', Verified: 'Verified', Unverified: 'Unverified', private_conversation_started: 'Private conversation started.', private_conversation_aborted: 'Private conversation aborted!', your_buddy_closed_the_private_conversation_you_should_do_the_same: 'Your buddy closed the private conversation! You should do the same.', conversation_is_now_verified: 'Conversation is now verified.', authentication_failed: 'Authentication failed.', your_buddy_is_attempting_to_determine_: 'You buddy is attempting to determine if he or she is really talking to you.', to_authenticate_to_your_buddy: 'To authenticate to your buddy, ', enter_the_answer_and_click_answer: 'enter the answer and click Answer.', enter_the_secret: 'enter the secret.', Creating_your_private_key_: 'Creating your private key; this may take a while.', Authenticating_a_buddy_helps_: 'Authenticating a buddy helps ensure that the person you are talking to is really the one he or she claims to be.', How_do_you_want_to_authenticate_your_buddy: 'How do you want to authenticate {{bid_name}} (<b>{{bid_jid}}</b>)?', Select_method: 'Select method...', Manual: 'Manual', Question: 'Question', Secret: 'Secret', To_verify_the_fingerprint_: 'To verify the fingerprint, contact your buddy via some other trustworthy channel, such as the telephone.', Your_fingerprint: 'Your fingerprint', Buddy_fingerprint: 'Buddy fingerprint', Close: 'Close', Compared: 'Compared', To_authenticate_using_a_question_: 'To authenticate using a question, pick a question whose answer is known only you and your buddy.', Ask: 'Ask', To_authenticate_pick_a_secret_: 'To authenticate, pick a secret known only to you and your buddy.', Compare: 'Compare', Fingerprints: 'Fingerprints', Authentication: 'Authentication', Message: 'Message', Add_buddy: 'Add buddy', rename_buddy: 'rename buddy', delete_buddy: 'delete buddy', Login: 'Login', Username: 'Username', Password: 'Password', Cancel: 'Cancel', Connect: 'Connect', Type_in_the_full_username_: 'Type in the full username and an optional alias.', Alias: 'Alias', Add: 'Add', Subscription_request: 'Subscription request', You_have_a_request_from: 'You have a request from', Deny: 'Deny', Approve: 'Approve', Remove_buddy: 'Remove buddy', You_are_about_to_remove_: 'You are about to remove {{bid_name}} (<b>{{bid_jid}}</b>) from your buddy list. All related chats will be closed.', Continue_without_chat: 'Continue without chat', Please_wait: 'Please wait', Login_failed: 'Chat login failed', Sorry_we_cant_authentikate_: 'Authentication failed with the chat server. Maybe the password is wrong?', Retry: 'Back', clear_history: 'Clear history', New_message_from: 'New message from', Should_we_notify_you_: 'Should we notify you about new messages in the future?', Please_accept_: 'Please click the "Allow" button at the top.', Hide_offline: 'Hide offline contacts', Show_offline: 'Show offline contacts', About: 'About', dnd: 'Do Not Disturb', Mute: 'Mute', Unmute: 'Unmute', Subscription: 'Subscription', both: 'both', Status: 'Status', online: 'online', chat: 'chat', away: 'away', xa: 'extended away', offline: 'offline', none: 'none', Unknown_instance_tag: 'Unknown instance tag.', Not_one_of_our_latest_keys: 'Not one of our latest keys.', Received_an_unreadable_encrypted_message: 'Received an unreadable encrypted message.', Online: 'Online', Chatty: 'Chatty', Away: 'Away', Extended_away: 'Extended away', Offline: 'Offline', Friendship_request: 'Friendship request', Confirm: 'Confirm', Dismiss: 'Dismiss', Remove: 'Remove', Online_help: 'Online help', FN: 'Full name', N: ' ', FAMILY: 'Family name', GIVEN: 'Given name', NICKNAME: 'Nickname', URL: 'URL', ADR: 'Address', STREET: 'Street Address', EXTADD: 'Extended Address', LOCALITY: 'Locality', REGION: 'Region', PCODE: 'Postal Code', CTRY: 'Country', TEL: 'Telephone', NUMBER: 'Number', EMAIL: 'Email', USERID: ' ', ORG: 'Organization', ORGNAME: 'Name', ORGUNIT: 'Unit', TITLE: 'Job title', ROLE: 'Role', BDAY: 'Birthday', DESC: 'Description', PHOTO: ' ', send_message: 'Send message', get_info: 'Show information', Settings: 'Settings', Priority: 'Priority', Save: 'Save', User_settings: 'User settings', A_fingerprint_: 'A fingerprint is used to make sure that the person you are talking to is who he or she is saying.', Your_roster_is_empty_add_a: 'Your roster is empty, add a ', new_buddy: 'new buddy', is: 'is', Login_options: 'Login options', BOSH_url: 'BOSH URL', Domain: 'Domain', Resource: 'Resource', On_login: 'On login', Received_an_unencrypted_message: 'Received an unencrypted message', Sorry_your_buddy_doesnt_provide_any_information: 'Sorry, your buddy does not provide any information.', Info_about: 'Info about', Authentication_aborted: 'Authentication aborted.', Authentication_request_received: 'Authentication request received.', Do_you_want_to_display_them: 'Do you want to display them?', Log_in_without_chat: 'Log in without chat', has_come_online: 'has come online', Unknown_sender: 'Unknown sender', You_received_a_message_from_an_unknown_sender: 'You received a message from an unknown sender' }, de: { Logging_in: 'Login läuft…', your_connection_is_unencrypted: 'Deine Verbindung ist UNverschlüsselt.', your_connection_is_encrypted: 'Deine Verbindung ist verschlüsselt.', your_buddy_closed_the_private_connection: 'Dein Freund hat die private Verbindung getrennt.', start_private: 'Privat starten', close_private: 'Privat abbrechen', your_buddy_is_verificated: 'Dein Freund ist verifiziert.', you_have_only_a_subscription_in_one_way: 'Die Freundschaft ist nur einseitig.', authentication_query_sent: 'Authentifizierungsanfrage gesendet.', your_message_wasnt_send_please_end_your_private_conversation: 'Deine Nachricht wurde nicht gesendet. Bitte beende die private Konversation.', unencrypted_message_received: 'Unverschlüsselte Nachricht erhalten.', your_message_wasnt_send_because_you_have_no_valid_subscription: 'Deine Nachricht wurde nicht gesandt, da die Freundschaft einseitig ist.', not_available: 'Nicht verfügbar.', no_connection: 'Keine Verbindung.', relogin: 'Neu anmelden.', trying_to_start_private_conversation: 'Versuche private Konversation zu starten.', Verified: 'Verifiziert', Unverified: 'Unverifiziert', private_conversation_started: 'Private Konversation gestartet.', private_conversation_aborted: 'Private Konversation abgebrochen.', your_buddy_closed_the_private_conversation_you_should_do_the_same: 'Dein Freund hat die private Konversation beendet. Das solltest du auch tun!', conversation_is_now_verified: 'Konversation ist jetzt verifiziert', authentication_failed: 'Authentifizierung fehlgeschlagen.', your_buddy_is_attempting_to_determine_: 'Dein Freund versucht herauszufinden ob er wirklich mit dir redet.', to_authenticate_to_your_buddy: 'Um dich gegenüber deinem Freund zu verifizieren ', enter_the_answer_and_click_answer: 'gib die Antwort ein und klick auf Antworten.', enter_the_secret: 'gib das Geheimnis ein.', Creating_your_private_key_: 'Wir werden jetzt deinen privaten Schlüssel generieren. Das kann einige Zeit in Anspruch nehmen.', Authenticating_a_buddy_helps_: 'Einen Freund zu authentifizieren hilft sicher zustellen, dass die Person mit der du sprichst auch die ist die sie sagt.', How_do_you_want_to_authenticate_your_buddy: 'Wie willst du {{bid_name}} (<b>{{bid_jid}}</b>) authentifizieren?', Select_method: 'Wähle...', Manual: 'Manual', Question: 'Frage', Secret: 'Geheimnis', To_verify_the_fingerprint_: 'Um den Fingerprint zu verifizieren kontaktiere dein Freund über einen anderen Kommunikationsweg. Zum Beispiel per Telefonanruf.', Your_fingerprint: 'Dein Fingerprint', Buddy_fingerprint: 'Sein/Ihr Fingerprint', Close: 'Schließen', Compared: 'Verglichen', To_authenticate_using_a_question_: 'Um die Authentifizierung per Frage durchzuführen, wähle eine Frage bei welcher nur dein Freund die Antwort weiß.', Ask: 'Frage', To_authenticate_pick_a_secret_: 'Um deinen Freund zu authentifizieren, wähle ein Geheimnis welches nur deinem Freund und dir bekannt ist.', Compare: 'Vergleiche', Fingerprints: 'Fingerprints', Authentication: 'Authentifizierung', Message: 'Nachricht', Add_buddy: 'Freund hinzufügen', rename_buddy: 'Freund umbenennen', delete_buddy: 'Freund löschen', Login: 'Anmeldung', Username: 'Benutzername', Password: 'Passwort', Cancel: 'Abbrechen', Connect: 'Verbinden', Type_in_the_full_username_: 'Gib bitte den vollen Benutzernamen und optional ein Alias an.', Alias: 'Alias', Add: 'Hinzufügen', Subscription_request: 'Freundschaftsanfrage', You_have_a_request_from: 'Du hast eine Anfrage von', Deny: 'Ablehnen', Approve: 'Bestätigen', Remove_buddy: 'Freund entfernen', You_are_about_to_remove_: 'Du bist gerade dabei {{bid_name}} (<b>{{bid_jid}}</b>) von deiner Kontaktliste zu entfernen. Alle Chats werden geschlossen.', Continue_without_chat: 'Weiter ohne Chat', Please_wait: 'Bitte warten', Login_failed: 'Chat-Anmeldung fehlgeschlagen', Sorry_we_cant_authentikate_: 'Der Chatserver hat die Anmeldung abgelehnt. Falsches Passwort?', Retry: 'Zurück', clear_history: 'Lösche Verlauf', New_message_from: 'Neue Nachricht von', Should_we_notify_you_: 'Sollen wir dich in Zukunft über eingehende Nachrichten informieren, auch wenn dieser Tab nicht im Vordergrund ist?', Please_accept_: 'Bitte klick auf den "Zulassen" Button oben.', Menu: 'Menü', Hide_offline: 'Offline ausblenden', Show_offline: 'Offline einblenden', About: 'Über', dnd: 'Beschäftigt', Mute: 'Ton aus', Unmute: 'Ton an', Subscription: 'Bezug', both: 'beidseitig', Status: 'Status', online: 'online', chat: 'chat', away: 'abwesend', xa: 'länger abwesend', offline: 'offline', none: 'keine', Unknown_instance_tag: 'Unbekannter instance tag.', Not_one_of_our_latest_keys: 'Nicht einer unserer letzten Schlüssel.', Received_an_unreadable_encrypted_message: 'Eine unlesbare verschlüsselte Nachricht erhalten.', Online: 'Online', Chatty: 'Gesprächig', Away: 'Abwesend', Extended_away: 'Länger abwesend', Offline: 'Offline', Friendship_request: 'Freundschaftsanfrage', Confirm: 'Bestätigen', Dismiss: 'Ablehnen', Remove: 'Löschen', Online_help: 'Online Hilfe', FN: 'Name', N: ' ', FAMILY: 'Familienname', GIVEN: 'Vorname', NICKNAME: 'Spitzname', URL: 'URL', ADR: 'Adresse', STREET: 'Straße', EXTADD: 'Zusätzliche Adresse', LOCALITY: 'Ortschaft', REGION: 'Region', PCODE: 'Postleitzahl', CTRY: 'Land', TEL: 'Telefon', NUMBER: 'Nummer', EMAIL: 'E-Mail', USERID: ' ', ORG: 'Organisation', ORGNAME: 'Name', ORGUNIT: 'Abteilung', TITLE: 'Titel', ROLE: 'Rolle', BDAY: 'Geburtstag', DESC: 'Beschreibung', PHOTO: ' ', send_message: 'Sende Nachricht', get_info: 'Benutzerinformationen', Settings: 'Einstellungen', Priority: 'Priorität', Save: 'Speichern', User_settings: 'Benutzereinstellungen', A_fingerprint_: 'Ein Fingerabdruck wird dazu benutzt deinen Gesprächspartner zu identifizieren.', Your_roster_is_empty_add_a: 'Deine Freundesliste ist leer, füge einen neuen Freund ', new_buddy: 'hinzu', is: 'ist', Login_options: 'Anmeldeoptionen', BOSH_url: 'BOSH url', Domain: 'Domain', Resource: 'Ressource', On_login: 'Beim Anmelden', Received_an_unencrypted_message: 'Unverschlüsselte Nachricht empfangen', Sorry_your_buddy_doesnt_provide_any_information: 'Dein Freund stellt leider keine Informationen bereit.', Info_about: 'Info über', Authentication_aborted: 'Authentifizierung abgebrochen.', Authentication_request_received: 'Authentifizierunganfrage empfangen.', Log_in_without_chat: 'Anmelden ohne Chat', Do_you_want_to_display_them: 'Möchtest du sie sehen?', has_come_online: 'ist online gekommen', Unknown_sender: 'Unbekannter Sender', You_received_a_message_from_an_unknown_sender: 'Du hast eine Nachricht von einem unbekannten Sender erhalten' }, es: { Logging_in: 'Por favor, espere...', your_connection_is_unencrypted: 'Su conexión no está cifrada.', your_connection_is_encrypted: 'Su conexión está cifrada.', your_buddy_closed_the_private_connection: 'Su amigo ha cerrado la conexión privada.', start_private: 'Iniciar privado', close_private: 'Cerrar privado', your_buddy_is_verificated: 'Tu amigo está verificado.', you_have_only_a_subscription_in_one_way: 'Sólo tienes una suscripción de un modo.', authentication_query_sent: 'Consulta de verificación enviada.', your_message_wasnt_send_please_end_your_private_conversation: 'Su mensaje no fue enviado. Por favor, termine su conversación privada.', unencrypted_message_received: 'Mensaje no cifrado recibido:', your_message_wasnt_send_because_you_have_no_valid_subscription: 'Su mensaje no se ha enviado, porque usted no tiene suscripción válida.', not_available: 'No disponible', no_connection: 'Sin conexión!', relogin: 'iniciar sesión nuevamente', trying_to_start_private_conversation: 'Intentando iniciar una conversación privada!', Verified: 'Verificado', Unverified: 'No verificado', private_conversation_started: 'se inició una conversación privada.', private_conversation_aborted: 'Conversación privada abortada!', your_buddy_closed_the_private_conversation_you_should_do_the_same: 'Su amigo cerró la conversación privada! Usted debería hacer lo mismo.', conversation_is_now_verified: 'La conversación es ahora verificada.', authentication_failed: 'Fallo la verificación.', your_buddy_is_attempting_to_determine_: 'Tu amigo está tratando de determinar si él o ella está realmente hablando con usted.', to_authenticate_to_your_buddy: 'Para autenticar a su amigo, ', enter_the_answer_and_click_answer: 'introduce la respuesta y haga clic en Contestar.', enter_the_secret: 'especifique el secreto.', Creating_your_private_key_: 'Ahora vamos a crear su clave privada. Esto puede tomar algún tiempo.', Authenticating_a_buddy_helps_: 'Autenticación de un amigo ayuda a garantizar que la persona que está hablando es quien él o ella está diciendo.', How_do_you_want_to_authenticate_your_buddy: '¿Cómo desea autenticar {{bid_name}} (<b>{{bid_jid}}</b>)?', Select_method: 'Escoja un método...', Manual: 'Manual', Question: 'Pregunta', Secret: 'Secreto', To_verify_the_fingerprint_: 'Para verificar la firma digital, póngase en contacto con su amigo a través de algún otro canal autenticado, como el teléfono.', Your_fingerprint: 'Tu firma digital', Buddy_fingerprint: 'firma digital de tu amigo', Close: 'Cerrar', Compared: 'Comparado', To_authenticate_using_a_question_: 'Para autenticar mediante una pregunta, elegir una pregunta cuya respuesta se conoce sólo usted y su amigo.', Ask: 'Preguntar', To_authenticate_pick_a_secret_: 'Para autenticar, elija un secreto conocido sólo por usted y su amigo.', Compare: 'Comparar', Fingerprints: 'Firmas digitales', Authentication: 'Autenticación', Message: 'Mensaje', Add_buddy: 'Añadir amigo', rename_buddy: 'renombrar amigo', delete_buddy: 'eliminar amigo', Login: 'Iniciar Sesión', Username: 'Usuario', Password: 'Contraseña', Cancel: 'Cancelar', Connect: 'Conectar', Type_in_the_full_username_: 'Escriba el usuario completo y un alias opcional.', Alias: 'Alias', Add: 'Añadir', Subscription_request: 'Solicitud de suscripción', You_have_a_request_from: 'Tienes una petición de', Deny: 'Rechazar', Approve: 'Aprobar', Remove_buddy: 'Eliminar amigo', You_are_about_to_remove_: 'Vas a eliminar a {{bid_name}} (<b>{{bid_jid}}</b>) de tu lista de amigos. Todas las conversaciones relacionadas serán cerradas.', Continue_without_chat: 'Continuar', Please_wait: 'Espere por favor', Login_failed: 'Fallo el inicio de sesión', Sorry_we_cant_authentikate_: 'Lo sentimos, no podemos autentificarlo en nuestro servidor de chat. ¿Tal vez la contraseña es incorrecta?', Retry: 'Reintentar', clear_history: 'Borrar el historial', New_message_from: 'Nuevo mensaje de', Should_we_notify_you_: '¿Debemos notificarle sobre nuevos mensajes en el futuro?', Please_accept_: 'Por favor, haga clic en el botón "Permitir" en la parte superior.', dnd: 'No Molestar', Mute: 'Desactivar sonido', Unmute: 'Activar sonido', Subscription: 'Suscripción', both: 'ambos', Status: 'Estado', online: 'en línea', chat: 'chat', away: 'ausente', xa: 'mas ausente', offline: 'desconectado', none: 'nadie', Unknown_instance_tag: 'Etiqueta de instancia desconocida.', Not_one_of_our_latest_keys: 'No de nuestra ultima tecla.', Received_an_unreadable_encrypted_message: 'Se recibió un mensaje cifrado ilegible.', Online: 'En linea', Chatty: 'Hablador', Away: 'Ausente', Extended_away: 'Mas ausente', Offline: 'Desconectado', Friendship_request: 'Solicitud de amistad', Confirm: 'Confirmar', Dismiss: 'Rechazar', Remove: 'Eliminar', Online_help: 'Ayuda en línea', FN: 'Nombre completo ', N: ' ', FAMILY: 'Apellido', GIVEN: 'Nombre', NICKNAME: 'Apodar', URL: 'URL', ADR: 'Dirección', STREET: 'Calle', EXTADD: 'Extendido dirección', LOCALITY: 'Población', REGION: 'Región', PCODE: 'Código postal', CTRY: 'País', TEL: 'Teléfono', NUMBER: 'Número', EMAIL: 'Emilio', USERID: ' ', ORG: 'Organización', ORGNAME: 'Nombre', ORGUNIT: 'Departamento', TITLE: 'Título', ROLE: 'Rol', BDAY: 'Cumpleaños', DESC: 'Descripción', PHOTO: ' ', send_message: 'mandar un texto', get_info: 'obtener información', Settings: 'Ajustes', Priority: 'Prioridad', Save: 'Guardar', User_settings: 'Configuración de usuario', A_fingerprint_: 'La huella digital se utiliza para que puedas estar seguro que la persona con la que estas hablando es quien realmente dice ser', Your_roster_is_empty_add_a: 'Tu lista de amigos esta vacia', new_buddy: 'Nuevo amigo', is: 'es', Login_options: 'Opciones de login', BOSH_url: 'BOSH url', Domain: 'Dominio', Resource: 'Recurso', On_login: 'Iniciar sesión', Received_an_unencrypted_message: 'Recibe un mensaje no cifrado' } }; }(jQuery));
fix delayed timestamp (fix #125)
jsxc.lib.js
fix delayed timestamp (fix #125)
<ide><path>sxc.lib.js <ide> } <ide> <ide> if (jsxc.otr.objects.hasOwnProperty(bid)) { <del> jsxc.otr.objects[bid].receiveMsg(body, stamp); <add> jsxc.otr.objects[bid].receiveMsg(body, { <add> stamp: stamp, <add> forwarded: forwarded <add> }); <ide> } else { <ide> jsxc.gui.window.postMessage(bid, 'in', body, false, forwarded, stamp); <ide> } <ide> * Handler for otr receive event <ide> * <ide> * @memberOf jsxc.otr <del> * @param {string} bid <del> * @param {string} msg received message <del> * @param {string} encrypted True, if msg was encrypted. <del> */ <del> receiveMessage: function(bid, msg, encrypted, stamp) { <add> * @param {Object} d <add> * @param {string} d.bid <add> * @param {string} d.msg received message <add> * @param {boolean} d.encrypted True, if msg was encrypted. <add> * @param {boolean} d.forwarded <add> * @param {string} d.stamp timestamp <add> */ <add> receiveMessage: function(d) { <add> var bid = d.bid; <ide> <ide> if (jsxc.otr.objects[bid].msgstate !== OTR.CONST.MSGSTATE_PLAINTEXT) { <ide> jsxc.otr.backup(bid); <ide> } <ide> <ide> if (jsxc.otr.objects[bid].msgstate !== OTR.CONST.MSGSTATE_PLAINTEXT && !encrypted) { <del> jsxc.gui.window.postMessage(bid, 'sys', jsxc.translate('%%Received an unencrypted message.%% [') + msg + ']', encrypted, stamp); <add> jsxc.gui.window.postMessage(bid, 'sys', jsxc.translate('%%Received an unencrypted message.%% [') + d.msg + ']', d.encrypted, d.forwarded, d.stamp); <ide> } else { <del> jsxc.gui.window.postMessage(bid, 'in', msg, encrypted, stamp); <add> jsxc.gui.window.postMessage(bid, 'in', d.msg, d.encrypted, d.forwarded, d.stamp); <ide> } <ide> }, <ide> <ide> }); <ide> <ide> // Receive message <del> jsxc.otr.objects[bid].on('ui', function(msg, encrypted, stamp) { <del> jsxc.otr.receiveMessage(bid, msg, encrypted === true, stamp); <add> jsxc.otr.objects[bid].on('ui', function(msg, encrypted, meta) { <add> jsxc.otr.receiveMessage({ <add> bid: bid, <add> msg: msg, <add> encrypted: encrypted === true, <add> stamp: meta.stamp, <add> forwarded: meta.forwarded <add> }); <ide> }); <ide> <ide> // Send message
Java
lgpl-2.1
3cc3b17a6848c2f70ba2926a9318fe6222e5779c
0
anddann/soot,anddann/soot,anddann/soot,anddann/soot
package soot; import com.google.common.base.Optional; import com.google.common.cache.Cache; import com.google.common.cache.CacheBuilder; import com.google.common.cache.CacheLoader; import com.google.common.cache.LoadingCache; import soot.options.Options; import java.io.*; import java.net.URISyntaxException; import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.Paths; import java.util.*; import java.util.concurrent.ExecutionException; import java.util.regex.Pattern; /** * A utility class for dealing with java 9 modules and module dependencies * * @author adann */ public final class ModuleUtil { public ModuleUtil(Singletons.Global g) { } public static ModuleUtil v() { return G.v().soot_ModuleUtil(); } private final Cache<String, String> modulePackageCache = CacheBuilder.newBuilder().initialCapacity(60).maximumSize(800).concurrencyLevel(Runtime.getRuntime().availableProcessors()).build(); private final LoadingCache<String, ModuleClassNameWrapper> wrapperCache = CacheBuilder.newBuilder().initialCapacity(100).maximumSize(1000).concurrencyLevel(Runtime.getRuntime().availableProcessors()).build( new CacheLoader<String, ModuleClassNameWrapper>() { @Override public ModuleClassNameWrapper load(String key) throws Exception { return new ModuleClassNameWrapper(key); } } ); public final ModuleClassNameWrapper makeWrapper(String className) { try { return wrapperCache.get(className); } catch (ExecutionException e) { throw new RuntimeException(e); } } /** * Check if Soot is run with module mode enables * * @return true, if module mode is used */ public static boolean module_mode() { return !Options.v().soot_modulepath().isEmpty(); } /** * Finds the module that exports the given class to the given module * * @param className the requested class * @param toModuleName the module from which the request is made * @return the module's name that exports the class to the given module */ public final String findModuleThatExports(String className, String toModuleName) { if (className.equalsIgnoreCase(SootModuleInfo.MODULE_INFO)) { return toModuleName; } SootModuleInfo modInfo = (SootModuleInfo) SootModuleResolver.v().resolveClass(SootModuleInfo.MODULE_INFO, SootClass.BODIES, Optional.fromNullable(toModuleName)); String packageName = getPackageName(className); if (modInfo == null) { return null; } String moduleName = modulePackageCache.getIfPresent(modInfo.getModuleName() + "/" + packageName); if (moduleName != null) { return moduleName; } if (modInfo.exportsPackage(packageName, toModuleName)) { return modInfo.getModuleName(); } if (modInfo.isAutomaticModule()) { //shortcut, an automatic module is allowed to access any other class if (ModuleScene.v().containsClass(className)) { String foundModuleName = ModuleScene.v().getSootClass(className).getModuleInformation().getModuleName(); modulePackageCache.put(modInfo.getModuleName() + "/" + packageName, foundModuleName); return foundModuleName; } } for (SootModuleInfo modInf : modInfo.retrieveRequiredModules().keySet()) { if (modInf.exportsPackage(packageName, toModuleName)) { modulePackageCache.put(modInfo.getModuleName() + "/" + packageName, modInf.getModuleName()); return modInf.getModuleName(); } else { //check if exported packages is "requires public" for (Map.Entry<SootModuleInfo, Integer> entry : modInf.retrieveRequiredModules().entrySet()) { if ((entry.getValue() & Modifier.REQUIRES_TRANSITIVE) != 0) //check if module is reexported via "requires public" { if (entry.getKey().exportsPackage(packageName, toModuleName)) { modulePackageCache.put(modInfo.getModuleName() + "/" + packageName, entry.getKey().getModuleName()); return entry.getKey().getModuleName(); } } } } } //if the class is not exported by any package, it has to internal to this module return toModuleName; } /** * The returns the package name of a full qualified class name * * @param className a full qualified className * @return the package name */ private static String getPackageName(String className) { String packageName = ""; int index = className.lastIndexOf('.'); if (index > 0) { packageName = className.substring(0, index); } return packageName; } /* In Soot are a hard coded class names as string constants that are now contained in the java.base module, this list serves as a lookup for these string constant */ private static final List<String> packagesJavaBaseModule = parseJavaBasePackage(); private static final String JAVABASEFILE = "javabase.txt"; private static List<String> parseJavaBasePackage() { List<String> packages = new ArrayList<>(); Path excludeFile = Paths.get(JAVABASEFILE); if (!Files.exists(excludeFile)) { //else take the one package try { excludeFile = Paths.get(ModuleUtil.class.getResource(File.separator + JAVABASEFILE).toURI()); } catch (URISyntaxException e) { e.printStackTrace(); } } //read file into stream, try-with-resources try (InputStream in = Files.newInputStream(excludeFile); BufferedReader reader = new BufferedReader(new InputStreamReader(in))) { String line; while ((line = reader.readLine()) != null) { packages.add(line); } } catch (IOException x) { G.v().out.println("[WARN] No files specifying the packages of module java.base"); } return packages; } /** * Wrapper class for backward compatibility with existing soot code * In existing soot code classes are resolved based on their name without specifying a module * to avoid changing all occurrences of String constants in Soot this classes deals with these String constants */ public static final class ModuleClassNameWrapper { //check for occurrence of full qualified class names private static final String fullQualifiedName = "([a-zA-Z_$][a-zA-Z\\d_$]*\\.)+[a-zA-Z_$][a-zA-Z\\d_$]*"; private static final Pattern fqnClassNamePattern = Pattern.compile(fullQualifiedName); //check for occurrence of module name private static final String qualifiedModuleName = "([a-zA-Z_$])([a-zA-Z\\d_$\\.]*)+"; private static final Pattern qualifiedModuleNamePattern = Pattern.compile(qualifiedModuleName); private final String className; private String moduleName; private ModuleClassNameWrapper(String className) { String refinedClassName = className; String refinedModuleName = null; if (className.equals(SootClass.INVOKEDYNAMIC_DUMMY_CLASS_NAME)) { this.className = refinedClassName; return; } else if (className.contains(":")) { String split[] = className.split(":"); if (split.length == 2) { //check if first is valid module name if (qualifiedModuleNamePattern.matcher(split[0]).matches()) { //check if second is fq classname if (fqnClassNamePattern.matcher(split[1]).matches()) { refinedModuleName = split[0]; refinedClassName = split[1]; } } } } else if (fqnClassNamePattern.matcher(className).matches()) { for (String packageName : packagesJavaBaseModule) { if (packageName.equals(ModuleUtil.getPackageName(className))) { refinedModuleName = "java.base"; break; } } } this.className = refinedClassName; this.moduleName = refinedModuleName; ModuleUtil.v().wrapperCache.put(className, this); } public String getClassName() { return this.className; } public String getModuleName() { return this.moduleName; } public Optional<String> getModuleNameOptional() { return Optional.fromNullable(this.moduleName); } } }
src/soot/ModuleUtil.java
package soot; import com.google.common.base.Optional; import com.google.common.cache.Cache; import com.google.common.cache.CacheBuilder; import com.google.common.cache.CacheLoader; import com.google.common.cache.LoadingCache; import soot.options.Options; import java.io.*; import java.net.URISyntaxException; import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.Paths; import java.util.*; import java.util.concurrent.ExecutionException; import java.util.regex.Pattern; /** * A utility class for dealing with java 9 modules and module dependencies * * @author adann */ public final class ModuleUtil { public ModuleUtil(Singletons.Global g) { } public static ModuleUtil v() { return G.v().soot_ModuleUtil(); } private final Cache<String, String> modulePackageCache = CacheBuilder.newBuilder().initialCapacity(60).maximumSize(800).concurrencyLevel(Runtime.getRuntime().availableProcessors()).build(); private final LoadingCache<String, ModuleClassNameWrapper> wrapperCache = CacheBuilder.newBuilder().initialCapacity(100).maximumSize(1000).concurrencyLevel(Runtime.getRuntime().availableProcessors()).build( new CacheLoader<String, ModuleClassNameWrapper>() { @Override public ModuleClassNameWrapper load(String key) throws Exception { return new ModuleClassNameWrapper(key); } } ); public final ModuleClassNameWrapper makeWrapper(String className) { try { return wrapperCache.get(className); } catch (ExecutionException e) { throw new RuntimeException(e); } } /** * Check if Soot is run with module mode enables * * @return true, if module mode is used */ public static boolean module_mode() { return !Options.v().soot_modulepath().isEmpty(); } /** * Finds the module that exports the given class to the given module * * @param className the requested class * @param toModuleName the module from which the request is made * @return the module's name that exports the class to the given module */ public final String findModuleThatExports(String className, String toModuleName) { if (className.equalsIgnoreCase(SootModuleInfo.MODULE_INFO)) { return toModuleName; } SootModuleInfo modInfo = (SootModuleInfo) SootModuleResolver.v().resolveClass(SootModuleInfo.MODULE_INFO, SootClass.BODIES, Optional.fromNullable(toModuleName)); String packageName = getPackageName(className); if (modInfo == null) { return null; } String moduleName = modulePackageCache.getIfPresent(modInfo.getModuleName() + "/" + packageName); if (moduleName != null) { return moduleName; } if (modInfo.exportsPackage(packageName, toModuleName)) { return modInfo.getModuleName(); } if (modInfo.isAutomaticModule()) { //shortcut, an automatic module is allowed to access any other class if (ModuleScene.v().containsClass(className)) { String foundModuleName = ModuleScene.v().getSootClass(className).getModuleInformation().getModuleName(); modulePackageCache.put(modInfo.getModuleName() + "/" + packageName, foundModuleName); return foundModuleName; } } for (SootModuleInfo modInf : modInfo.retrieveRequiredModules().keySet()) { if (modInf.exportsPackage(packageName, toModuleName)) { modulePackageCache.put(modInfo.getModuleName() + "/" + packageName, modInf.getModuleName()); return modInf.getModuleName(); } else { //check if exported packages is "requires public" for (Map.Entry<SootModuleInfo, Integer> entry : modInf.retrieveRequiredModules().entrySet()) { if ((entry.getValue() & Modifier.REQUIRES_TRANSITIVE) != 0) //check if module is reexported via "requires public" { if (entry.getKey().exportsPackage(packageName, toModuleName)) { modulePackageCache.put(modInfo.getModuleName() + "/" + packageName, entry.getKey().getModuleName()); return entry.getKey().getModuleName(); } } } } } //if the class is not exported by any package, it has to internal to this module return toModuleName; } /** * The returns the package name of a full qualified class name * * @param className a full qualified className * @return the package name */ private static String getPackageName(String className) { String packageName = ""; int index = className.lastIndexOf('.'); if (index > 0) { packageName = className.substring(0, index); } return packageName; } /* In Soot are a hard coded class names as string constants that are now contained in the java.base module, this list serves as a lookup for these string constant */ private static final List<String> packagesJavaBaseModule = parseJavaBasePackage(); private static final String JAVABASEFILE = "javabase.txt"; private static List<String> parseJavaBasePackage() { List<String> packages = new ArrayList<>(); Path excludeFile = Paths.get(JAVABASEFILE); if (!Files.exists(excludeFile)) { //else take the one package try { excludeFile = Paths.get(ModuleUtil.class.getResource(File.separator + JAVABASEFILE).toURI()); } catch (URISyntaxException e) { e.printStackTrace(); } } //read file into stream, try-with-resources try (InputStream in = Files.newInputStream(excludeFile); BufferedReader reader = new BufferedReader(new InputStreamReader(in))) { String line; while ((line = reader.readLine()) != null) { packages.add(line); } } catch (IOException x) { G.v().out.println("[WARN] No files specifying the packages of module java.base"); } return packages; } /** * Wrapper class for backward compatibility with existing soot code * In existing soot code classes are resolved based on their name without specifying a module * to avoid changing all occurrences of String constants in Soot this classes deals with these String constants */ public static final class ModuleClassNameWrapper { //check for occurrence of full qualified class names private static final String fullQualifiedName = "([a-zA-Z_$][a-zA-Z\\d_$]*\\.)+[a-zA-Z_$][a-zA-Z\\d_$]*"; private static final Pattern fqnClassNamePattern = Pattern.compile("([a-zA-Z_$][a-zA-Z\\d_$]*\\.)*[a-zA-Z_$][a-zA-Z\\d_$]*"); //check for occurrence of module name private static final String qualifiedModuleName = "([a-zA-Z_$])([a-zA-Z\\d_$\\.]*)+"; private static final Pattern moduleClassNamePattern = Pattern.compile(qualifiedModuleName + "(:)" + fullQualifiedName); private final String className; private String moduleName; private ModuleClassNameWrapper(String className) { String refinedClassName = className; String refinedModuleName = null; if (className.equals(SootClass.INVOKEDYNAMIC_DUMMY_CLASS_NAME)) { this.className = refinedClassName; return; } else if (moduleClassNamePattern.matcher(className).matches()) { String split[] = className.split(":"); refinedModuleName = split[0]; refinedClassName = split[1]; } else if (fqnClassNamePattern.matcher(className).matches()) { for (String packageName : packagesJavaBaseModule) { if (packageName.equals(ModuleUtil.getPackageName(className))) { refinedModuleName = "java.base"; break; } } } this.className = refinedClassName; this.moduleName = refinedModuleName; ModuleUtil.v().wrapperCache.put(className, this); } public String getClassName() { return this.className; } public String getModuleName() { return this.moduleName; } public Optional<String> getModuleNameOptional() { return Optional.fromNullable(this.moduleName); } } }
Fixed Regex Pattern for fully qualified classname and modulename
src/soot/ModuleUtil.java
Fixed Regex Pattern for fully qualified classname and modulename
<ide><path>rc/soot/ModuleUtil.java <ide> <ide> //check for occurrence of full qualified class names <ide> private static final String fullQualifiedName = "([a-zA-Z_$][a-zA-Z\\d_$]*\\.)+[a-zA-Z_$][a-zA-Z\\d_$]*"; <del> private static final Pattern fqnClassNamePattern = Pattern.compile("([a-zA-Z_$][a-zA-Z\\d_$]*\\.)*[a-zA-Z_$][a-zA-Z\\d_$]*"); <add> private static final Pattern fqnClassNamePattern = Pattern.compile(fullQualifiedName); <ide> <ide> //check for occurrence of module name <ide> private static final String qualifiedModuleName = "([a-zA-Z_$])([a-zA-Z\\d_$\\.]*)+"; <del> private static final Pattern moduleClassNamePattern = Pattern.compile(qualifiedModuleName + "(:)" + fullQualifiedName); <add> private static final Pattern qualifiedModuleNamePattern = Pattern.compile(qualifiedModuleName); <ide> <ide> <ide> private final String className; <ide> if (className.equals(SootClass.INVOKEDYNAMIC_DUMMY_CLASS_NAME)) { <ide> this.className = refinedClassName; <ide> return; <del> } else if (moduleClassNamePattern.matcher(className).matches()) { <add> } else if (className.contains(":")) { <ide> String split[] = className.split(":"); <del> refinedModuleName = split[0]; <del> refinedClassName = split[1]; <del> } else if (fqnClassNamePattern.matcher(className).matches()) { <add> if (split.length == 2) { <add> //check if first is valid module name <add> if (qualifiedModuleNamePattern.matcher(split[0]).matches()) { <add> //check if second is fq classname <add> if (fqnClassNamePattern.matcher(split[1]).matches()) { <add> refinedModuleName = split[0]; <add> refinedClassName = split[1]; <add> } <add> } <add> } <add> } else if (fqnClassNamePattern.matcher(className).matches()) { <ide> for (String packageName : packagesJavaBaseModule) { <ide> if (packageName.equals(ModuleUtil.getPackageName(className))) { <ide> refinedModuleName = "java.base";
Java
apache-2.0
467765a76145f6c28939111d6a5a56253833c9d0
0
savanibharat/concourse,bigtreeljc/concourse,vrnithinkumar/concourse,dubex/concourse,remiemalik/concourse,chiranjeevjain/concourse,vrnithinkumar/concourse,dubex/concourse,chiranjeevjain/concourse,mAzurkovic/concourse,Qunzer/concourse,dubex/concourse,bigtreeljc/concourse,chiranjeevjain/concourse,kylycht/concourse,aabdin01/concourse,mAzurkovic/concourse,mAzurkovic/concourse,prateek135/concourse,Qunzer/concourse,hcuffy/concourse,Qunzer/concourse,MattiasZurkovic/concourse,hcuffy/concourse,kylycht/concourse,dubex/concourse,JerJohn15/concourse,Qunzer/concourse,chiranjeevjain/concourse,cinchapi/concourse,aabdin01/concourse,savanibharat/concourse,karthikprabhu17/concourse,remiemalik/concourse,bigtreeljc/concourse,vrnithinkumar/concourse,hcuffy/concourse,MattiasZurkovic/concourse,prateek135/concourse,kylycht/concourse,remiemalik/concourse,vrnithinkumar/concourse,aabdin01/concourse,karthikprabhu17/concourse,remiemalik/concourse,prateek135/concourse,cinchapi/concourse,bigtreeljc/concourse,mAzurkovic/concourse,savanibharat/concourse,prateek135/concourse,kylycht/concourse,JerJohn15/concourse,remiemalik/concourse,hcuffy/concourse,JerJohn15/concourse,cinchapi/concourse,cinchapi/concourse,karthikprabhu17/concourse,kylycht/concourse,savanibharat/concourse,mAzurkovic/concourse,savanibharat/concourse,dubex/concourse,aabdin01/concourse,MattiasZurkovic/concourse,vrnithinkumar/concourse,JerJohn15/concourse,prateek135/concourse,mAzurkovic/concourse,MattiasZurkovic/concourse,chiranjeevjain/concourse,Qunzer/concourse,vrnithinkumar/concourse,JerJohn15/concourse,aabdin01/concourse,aabdin01/concourse,JerJohn15/concourse,bigtreeljc/concourse,kylycht/concourse,cinchapi/concourse,Qunzer/concourse,chiranjeevjain/concourse,karthikprabhu17/concourse,savanibharat/concourse,MattiasZurkovic/concourse,cinchapi/concourse,dubex/concourse,karthikprabhu17/concourse,bigtreeljc/concourse,hcuffy/concourse,MattiasZurkovic/concourse,hcuffy/concourse,karthikprabhu17/concourse,remiemalik/concourse,prateek135/concourse
/* * The MIT License (MIT) * * Copyright (c) 2013-2014 Jeff Nelson, Cinchapi Software Collective * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package org.cinchapi.concourse.util; import java.io.File; import org.apache.thrift.ProcessFunction; import org.cinchapi.concourse.server.GlobalState; import org.slf4j.LoggerFactory; import ch.qos.logback.classic.LoggerContext; import ch.qos.logback.classic.encoder.PatternLayoutEncoder; import ch.qos.logback.classic.spi.ILoggingEvent; import ch.qos.logback.core.ConsoleAppender; import ch.qos.logback.core.rolling.FixedWindowRollingPolicy; import ch.qos.logback.core.rolling.RollingFileAppender; import ch.qos.logback.core.rolling.SizeBasedTriggeringPolicy; /** * Contains methods to print log messages in the appropriate files. * * @author jnelson */ public final class Logger { /** * Print {@code message} with {@code params} to the INFO log. * * @param message * @param params */ public static void info(String message, Object... params) { INFO.info(message, params); } /** * Print {@code message} with {@code params} to the ERROR log. * * @param message * @param params */ public static void error(String message, Object... params) { ERROR.error(message, params); } /** * Print {@code message} with {@code params} to the WARN log. * * @param message * @param params */ public static void warn(String message, Object... params) { WARN.warn(message, params); } /** * Print {@code message} with {@code params} to the DEBUG log. * * @param message * @param params */ public static void debug(String message, Object... params) { DEBUG.debug(message, params); } private static String MAX_LOG_FILE_SIZE = "10MB"; private static final String LOG_DIRECTORY = "log"; private static final ch.qos.logback.classic.Logger ERROR = setup( "org.cinchapi.concourse.server.ErrorLogger", "error.log"); private static final ch.qos.logback.classic.Logger WARN = setup( "org.cinchapi.concourse.server.WarnLogger", "warn.log"); private static final ch.qos.logback.classic.Logger INFO = setup( "org.cinchapi.concourse.server.InfoLogger", "info.log"); private static final ch.qos.logback.classic.Logger DEBUG = setup( "org.cinchapi.concourse.server.DebugLogger", "debug.log"); static { // Capture logging from Thrift ProcessFunction and route it to our error // log so we have details on processing failures. setup(ProcessFunction.class.getName(), "error.log"); } /** * Setup logger {@code name} that prints to {@code file}. * * @param name * @param file * @return the logger */ private static ch.qos.logback.classic.Logger setup(String name, String file) { if(!GlobalState.ENABLE_CONSOLE_LOGGING) { ch.qos.logback.classic.Logger root = (ch.qos.logback.classic.Logger) LoggerFactory .getLogger(ch.qos.logback.classic.Logger.ROOT_LOGGER_NAME); root.detachAndStopAllAppenders(); } LoggerContext context = (LoggerContext) LoggerFactory .getILoggerFactory(); // Configure Pattern PatternLayoutEncoder encoder = new PatternLayoutEncoder(); encoder.setPattern("%date [%thread] %level - %msg%n"); encoder.setContext(context); encoder.start(); // Create File Appender RollingFileAppender<ILoggingEvent> appender = new RollingFileAppender<ILoggingEvent>(); appender.setFile(LOG_DIRECTORY + File.separator + file); appender.setContext(context); // Configure Rolling Policy FixedWindowRollingPolicy rolling = new FixedWindowRollingPolicy(); rolling.setMaxIndex(1); rolling.setMaxIndex(5); rolling.setContext(context); rolling.setFileNamePattern(LOG_DIRECTORY + File.separator + file + ".%i.zip"); rolling.setParent(appender); rolling.start(); // Configure Triggering Policy SizeBasedTriggeringPolicy<ILoggingEvent> triggering = new SizeBasedTriggeringPolicy<ILoggingEvent>(); triggering.setMaxFileSize(MAX_LOG_FILE_SIZE); triggering.start(); // Configure File Appender appender.setEncoder(encoder); appender.setRollingPolicy(rolling); appender.setTriggeringPolicy(triggering); appender.start(); // Get Logger ch.qos.logback.classic.Logger logger = (ch.qos.logback.classic.Logger) LoggerFactory .getLogger(name); logger.addAppender(appender); logger.setLevel(GlobalState.LOG_LEVEL); logger.setAdditive(true); return logger; } /** * Update the configuration of {@code logger} based on changes in the * underlying prefs file. * * @param logger */ @SuppressWarnings("unused") private static void update(ch.qos.logback.classic.Logger logger) { // TODO I need to actually reload the file from disk and check for // changes ch.qos.logback.classic.Logger root = (ch.qos.logback.classic.Logger) LoggerFactory .getLogger(ch.qos.logback.classic.Logger.ROOT_LOGGER_NAME); if(!GlobalState.ENABLE_CONSOLE_LOGGING) { root.detachAndStopAllAppenders(); } else { root.addAppender(new ConsoleAppender<ILoggingEvent>()); } logger.setLevel(GlobalState.LOG_LEVEL); } private Logger() {} /* utility class */ }
concourse-server/src/main/java/org/cinchapi/concourse/util/Logger.java
/* * The MIT License (MIT) * * Copyright (c) 2013-2014 Jeff Nelson, Cinchapi Software Collective * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package org.cinchapi.concourse.util; import java.io.File; import org.apache.thrift.ProcessFunction; import org.cinchapi.concourse.server.GlobalState; import org.slf4j.LoggerFactory; import ch.qos.logback.classic.LoggerContext; import ch.qos.logback.classic.encoder.PatternLayoutEncoder; import ch.qos.logback.classic.spi.ILoggingEvent; import ch.qos.logback.core.ConsoleAppender; import ch.qos.logback.core.rolling.FixedWindowRollingPolicy; import ch.qos.logback.core.rolling.RollingFileAppender; import ch.qos.logback.core.rolling.SizeBasedTriggeringPolicy; /** * Contains methods to print log messages in the appropriate files. * * @author jnelson */ public final class Logger { /** * Print {@code message} with {@code params} to the INFO log. * * @param message * @param params */ public static void info(String message, Object... params) { INFO.info(message, params); } /** * Print {@code message} with {@code params} to the ERROR log. * * @param message * @param params */ public static void error(String message, Object... params) { ERROR.error(message, params); } /** * Print {@code message} with {@code params} to the WARN log. * * @param message * @param params */ public static void warn(String message, Object... params) { WARN.warn(message, params); } /** * Print {@code message} with {@code params} to the DEBUG log. * * @param message * @param params */ public static void debug(String message, Object... params) { DEBUG.debug(message, params); } private static String MAX_LOG_FILE_SIZE = "10MB"; private static final String LOG_DIRECTORY = "log"; private static final ch.qos.logback.classic.Logger ERROR = setup( "org.cinchapi.concourse.server.ErrorLogger", "error.log"); private static final ch.qos.logback.classic.Logger WARN = setup( "org.cinchapi.concourse.server.WarnLogger", "warn.log"); private static final ch.qos.logback.classic.Logger INFO = setup( "org.cinchapi.concourse.server.InfoLogger", "info.log"); private static final ch.qos.logback.classic.Logger DEBUG = setup( "org.cinchapi.concourse.server.DebugLogger", "debug.log"); static { // Capture logging from Thrift ProcessFunction and route it to our error // log so we have details on processing failures. setup(ProcessFunction.class.getName(), "error.log"); } /** * Setup logger {@code name} that prints to {@code file}. * * @param name * @param file * @return the logger */ private static ch.qos.logback.classic.Logger setup(String name, String file) { if(!GlobalState.ENABLE_CONSOLE_LOGGING) { ch.qos.logback.classic.Logger root = (ch.qos.logback.classic.Logger) LoggerFactory .getLogger(ch.qos.logback.classic.Logger.ROOT_LOGGER_NAME); root.detachAndStopAllAppenders(); } LoggerContext context = (LoggerContext) LoggerFactory .getILoggerFactory(); // Configure Pattern PatternLayoutEncoder encoder = new PatternLayoutEncoder(); encoder.setPattern("%date [%thread] %level %class{36} - %msg%n"); encoder.setContext(context); encoder.start(); // Create File Appender RollingFileAppender<ILoggingEvent> appender = new RollingFileAppender<ILoggingEvent>(); appender.setFile(LOG_DIRECTORY + File.separator + file); appender.setContext(context); // Configure Rolling Policy FixedWindowRollingPolicy rolling = new FixedWindowRollingPolicy(); rolling.setMaxIndex(1); rolling.setMaxIndex(5); rolling.setContext(context); rolling.setFileNamePattern(LOG_DIRECTORY + File.separator + file + ".%i.zip"); rolling.setParent(appender); rolling.start(); // Configure Triggering Policy SizeBasedTriggeringPolicy<ILoggingEvent> triggering = new SizeBasedTriggeringPolicy<ILoggingEvent>(); triggering.setMaxFileSize(MAX_LOG_FILE_SIZE); triggering.start(); // Configure File Appender appender.setEncoder(encoder); appender.setRollingPolicy(rolling); appender.setTriggeringPolicy(triggering); appender.start(); // Get Logger ch.qos.logback.classic.Logger logger = (ch.qos.logback.classic.Logger) LoggerFactory .getLogger(name); logger.addAppender(appender); logger.setLevel(GlobalState.LOG_LEVEL); logger.setAdditive(true); return logger; } /** * Update the configuration of {@code logger} based on changes in the * underlying prefs file. * * @param logger */ @SuppressWarnings("unused") private static void update(ch.qos.logback.classic.Logger logger) { // TODO I need to actually reload the file from disk and check for // changes ch.qos.logback.classic.Logger root = (ch.qos.logback.classic.Logger) LoggerFactory .getLogger(ch.qos.logback.classic.Logger.ROOT_LOGGER_NAME); if(!GlobalState.ENABLE_CONSOLE_LOGGING) { root.detachAndStopAllAppenders(); } else { root.addAppender(new ConsoleAppender<ILoggingEvent>()); } logger.setLevel(GlobalState.LOG_LEVEL); } private Logger() {} /* utility class */ }
update Logger pattern
concourse-server/src/main/java/org/cinchapi/concourse/util/Logger.java
update Logger pattern
<ide><path>oncourse-server/src/main/java/org/cinchapi/concourse/util/Logger.java <ide> .getILoggerFactory(); <ide> // Configure Pattern <ide> PatternLayoutEncoder encoder = new PatternLayoutEncoder(); <del> encoder.setPattern("%date [%thread] %level %class{36} - %msg%n"); <add> encoder.setPattern("%date [%thread] %level - %msg%n"); <ide> encoder.setContext(context); <ide> encoder.start(); <ide>
Java
epl-1.0
8b3aa5263a221b9c11f67c03f6816c512902d760
0
mandeepdhami/controller,aryantaheri/monitoring-controller,mandeepdhami/controller,inocybe/odl-controller,my76128/controller,522986491/controller,my76128/controller,mandeepdhami/controller,tx1103mark/controller,tx1103mark/controller,my76128/controller,my76128/controller,inocybe/odl-controller,522986491/controller,opendaylight/controller,Sushma7785/OpenDayLight-Load-Balancer,aryantaheri/monitoring-controller,Johnson-Chou/test,aryantaheri/monitoring-controller,tx1103mark/controller,aryantaheri/monitoring-controller,mandeepdhami/controller,Sushma7785/OpenDayLight-Load-Balancer,tx1103mark/controller,Johnson-Chou/test
/* * Copyright (c) 2014 Cisco 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 */ package org.opendaylight.controller.cluster.raft; import akka.actor.ActorRef; import akka.actor.ActorSelection; import akka.japi.Procedure; import akka.persistence.RecoveryCompleted; import akka.persistence.SaveSnapshotFailure; import akka.persistence.SaveSnapshotSuccess; import akka.persistence.SnapshotOffer; import akka.persistence.SnapshotSelectionCriteria; import com.google.common.annotations.VisibleForTesting; import com.google.common.base.Optional; import com.google.common.base.Stopwatch; import com.google.protobuf.ByteString; import java.io.Serializable; import java.util.Map; import java.util.concurrent.TimeUnit; import org.opendaylight.controller.cluster.DataPersistenceProvider; import org.opendaylight.controller.cluster.common.actor.AbstractUntypedPersistentActor; import org.opendaylight.controller.cluster.notifications.RoleChanged; import org.opendaylight.controller.cluster.raft.base.messages.ApplyJournalEntries; import org.opendaylight.controller.cluster.raft.base.messages.ApplyLogEntries; import org.opendaylight.controller.cluster.raft.base.messages.ApplySnapshot; import org.opendaylight.controller.cluster.raft.base.messages.ApplyState; import org.opendaylight.controller.cluster.raft.base.messages.CaptureSnapshot; import org.opendaylight.controller.cluster.raft.base.messages.CaptureSnapshotReply; import org.opendaylight.controller.cluster.raft.base.messages.Replicate; import org.opendaylight.controller.cluster.raft.base.messages.SendInstallSnapshot; import org.opendaylight.controller.cluster.raft.behaviors.AbstractRaftActorBehavior; import org.opendaylight.controller.cluster.raft.behaviors.Follower; import org.opendaylight.controller.cluster.raft.behaviors.RaftActorBehavior; import org.opendaylight.controller.cluster.raft.client.messages.FindLeader; import org.opendaylight.controller.cluster.raft.client.messages.FindLeaderReply; import org.opendaylight.controller.cluster.raft.protobuff.client.messages.Payload; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * RaftActor encapsulates a state machine that needs to be kept synchronized * in a cluster. It implements the RAFT algorithm as described in the paper * <a href='https://ramcloud.stanford.edu/wiki/download/attachments/11370504/raft.pdf'> * In Search of an Understandable Consensus Algorithm</a> * <p/> * RaftActor has 3 states and each state has a certain behavior associated * with it. A Raft actor can behave as, * <ul> * <li> A Leader </li> * <li> A Follower (or) </li> * <li> A Candidate </li> * </ul> * <p/> * <p/> * A RaftActor MUST be a Leader in order to accept requests from clients to * change the state of it's encapsulated state machine. Once a RaftActor becomes * a Leader it is also responsible for ensuring that all followers ultimately * have the same log and therefore the same state machine as itself. * <p/> * <p/> * The current behavior of a RaftActor determines how election for leadership * is initiated and how peer RaftActors react to request for votes. * <p/> * <p/> * Each RaftActor also needs to know the current election term. It uses this * information for a couple of things. One is to simply figure out who it * voted for in the last election. Another is to figure out if the message * it received to update it's state is stale. * <p/> * <p/> * The RaftActor uses akka-persistence to store it's replicated log. * Furthermore through it's behaviors a Raft Actor determines * <p/> * <ul> * <li> when a log entry should be persisted </li> * <li> when a log entry should be applied to the state machine (and) </li> * <li> when a snapshot should be saved </li> * </ul> */ public abstract class RaftActor extends AbstractUntypedPersistentActor { private static final long APPLY_STATE_DELAY_THRESHOLD_IN_NANOS = TimeUnit.MILLISECONDS.toNanos(50L); // 50 millis protected final Logger LOG = LoggerFactory.getLogger(getClass()); /** * The current state determines the current behavior of a RaftActor * A Raft Actor always starts off in the Follower State */ private RaftActorBehavior currentBehavior; /** * This context should NOT be passed directly to any other actor it is * only to be consumed by the RaftActorBehaviors */ private final RaftActorContextImpl context; /** * The in-memory journal */ private ReplicatedLogImpl replicatedLog = new ReplicatedLogImpl(); private CaptureSnapshot captureSnapshot = null; private Stopwatch recoveryTimer; private int currentRecoveryBatchCount; public RaftActor(String id, Map<String, String> peerAddresses) { this(id, peerAddresses, Optional.<ConfigParams>absent()); } public RaftActor(String id, Map<String, String> peerAddresses, Optional<ConfigParams> configParams) { context = new RaftActorContextImpl(this.getSelf(), this.getContext(), id, new ElectionTermImpl(), -1, -1, replicatedLog, peerAddresses, (configParams.isPresent() ? configParams.get(): new DefaultConfigParamsImpl()), LOG); } private void initRecoveryTimer() { if(recoveryTimer == null) { recoveryTimer = Stopwatch.createStarted(); } } @Override public void preStart() throws Exception { LOG.info("Starting recovery for {} with journal batch size {}", persistenceId(), context.getConfigParams().getJournalRecoveryLogBatchSize()); super.preStart(); } @Override public void postStop() { if(currentBehavior != null) { try { currentBehavior.close(); } catch (Exception e) { LOG.debug("{}: Error closing behavior {}", persistenceId(), currentBehavior.state()); } } super.postStop(); } @Override public void handleRecover(Object message) { if(persistence().isRecoveryApplicable()) { if (message instanceof SnapshotOffer) { onRecoveredSnapshot((SnapshotOffer) message); } else if (message instanceof ReplicatedLogEntry) { onRecoveredJournalLogEntry((ReplicatedLogEntry) message); } else if (message instanceof ApplyLogEntries) { // Handle this message for backwards compatibility with pre-Lithium versions. onRecoveredApplyLogEntries(((ApplyLogEntries) message).getToIndex()); } else if (message instanceof ApplyJournalEntries) { onRecoveredApplyLogEntries(((ApplyJournalEntries) message).getToIndex()); } else if (message instanceof DeleteEntries) { replicatedLog.removeFrom(((DeleteEntries) message).getFromIndex()); } else if (message instanceof UpdateElectionTerm) { context.getTermInformation().update(((UpdateElectionTerm) message).getCurrentTerm(), ((UpdateElectionTerm) message).getVotedFor()); } else if (message instanceof RecoveryCompleted) { onRecoveryCompletedMessage(); } } else { if (message instanceof RecoveryCompleted) { // Delete all the messages from the akka journal so that we do not end up with consistency issues // Note I am not using the dataPersistenceProvider and directly using the akka api here deleteMessages(lastSequenceNr()); // Delete all the akka snapshots as they will not be needed deleteSnapshots(new SnapshotSelectionCriteria(scala.Long.MaxValue(), scala.Long.MaxValue())); onRecoveryComplete(); initializeBehavior(); } } } private void onRecoveredSnapshot(SnapshotOffer offer) { if(LOG.isDebugEnabled()) { LOG.debug("{}: SnapshotOffer called..", persistenceId()); } initRecoveryTimer(); Snapshot snapshot = (Snapshot) offer.snapshot(); // Create a replicated log with the snapshot information // The replicated log can be used later on to retrieve this snapshot // when we need to install it on a peer replicatedLog = new ReplicatedLogImpl(snapshot); context.setReplicatedLog(replicatedLog); context.setLastApplied(snapshot.getLastAppliedIndex()); context.setCommitIndex(snapshot.getLastAppliedIndex()); Stopwatch timer = Stopwatch.createStarted(); // Apply the snapshot to the actors state applyRecoverySnapshot(snapshot.getState()); timer.stop(); LOG.info("Recovery snapshot applied for {} in {}: snapshotIndex={}, snapshotTerm={}, journal-size=" + replicatedLog.size(), persistenceId(), timer.toString(), replicatedLog.getSnapshotIndex(), replicatedLog.getSnapshotTerm()); } private void onRecoveredJournalLogEntry(ReplicatedLogEntry logEntry) { if(LOG.isDebugEnabled()) { LOG.debug("{}: Received ReplicatedLogEntry for recovery: {}", persistenceId(), logEntry.getIndex()); } replicatedLog.append(logEntry); } private void onRecoveredApplyLogEntries(long toIndex) { if(LOG.isDebugEnabled()) { LOG.debug("{}: Received ApplyLogEntries for recovery, applying to state: {} to {}", persistenceId(), context.getLastApplied() + 1, toIndex); } for (long i = context.getLastApplied() + 1; i <= toIndex; i++) { batchRecoveredLogEntry(replicatedLog.get(i)); } context.setLastApplied(toIndex); context.setCommitIndex(toIndex); } private void batchRecoveredLogEntry(ReplicatedLogEntry logEntry) { initRecoveryTimer(); int batchSize = context.getConfigParams().getJournalRecoveryLogBatchSize(); if(currentRecoveryBatchCount == 0) { startLogRecoveryBatch(batchSize); } appendRecoveredLogEntry(logEntry.getData()); if(++currentRecoveryBatchCount >= batchSize) { endCurrentLogRecoveryBatch(); } } private void endCurrentLogRecoveryBatch() { applyCurrentLogRecoveryBatch(); currentRecoveryBatchCount = 0; } private void onRecoveryCompletedMessage() { if(currentRecoveryBatchCount > 0) { endCurrentLogRecoveryBatch(); } onRecoveryComplete(); String recoveryTime = ""; if(recoveryTimer != null) { recoveryTimer.stop(); recoveryTime = " in " + recoveryTimer.toString(); recoveryTimer = null; } LOG.info( "Recovery completed" + recoveryTime + " - Switching actor to Follower - " + "Persistence Id = " + persistenceId() + " Last index in log={}, snapshotIndex={}, snapshotTerm={}, " + "journal-size={}", replicatedLog.lastIndex(), replicatedLog.getSnapshotIndex(), replicatedLog.getSnapshotTerm(), replicatedLog.size()); initializeBehavior(); } protected void initializeBehavior(){ changeCurrentBehavior(new Follower(context)); } protected void changeCurrentBehavior(RaftActorBehavior newBehavior){ RaftActorBehavior oldBehavior = currentBehavior; currentBehavior = newBehavior; handleBehaviorChange(oldBehavior, currentBehavior); } @Override public void handleCommand(Object message) { if (message instanceof ApplyState){ ApplyState applyState = (ApplyState) message; long elapsedTime = (System.nanoTime() - applyState.getStartTime()); if(elapsedTime >= APPLY_STATE_DELAY_THRESHOLD_IN_NANOS){ LOG.warn("ApplyState took more time than expected. Elapsed Time = {} ms ApplyState = {}", TimeUnit.NANOSECONDS.toMillis(elapsedTime), applyState); } if(LOG.isDebugEnabled()) { LOG.debug("{}: Applying state for log index {} data {}", persistenceId(), applyState.getReplicatedLogEntry().getIndex(), applyState.getReplicatedLogEntry().getData()); } applyState(applyState.getClientActor(), applyState.getIdentifier(), applyState.getReplicatedLogEntry().getData()); } else if (message instanceof ApplyJournalEntries){ ApplyJournalEntries applyEntries = (ApplyJournalEntries) message; if(LOG.isDebugEnabled()) { LOG.debug("{}: Persisting ApplyLogEntries with index={}", persistenceId(), applyEntries.getToIndex()); } persistence().persist(applyEntries, new Procedure<ApplyJournalEntries>() { @Override public void apply(ApplyJournalEntries param) throws Exception { } }); } else if(message instanceof ApplySnapshot ) { Snapshot snapshot = ((ApplySnapshot) message).getSnapshot(); if(LOG.isDebugEnabled()) { LOG.debug("{}: ApplySnapshot called on Follower Actor " + "snapshotIndex:{}, snapshotTerm:{}", persistenceId(), snapshot.getLastAppliedIndex(), snapshot.getLastAppliedTerm() ); } applySnapshot(snapshot.getState()); //clears the followers log, sets the snapshot index to ensure adjusted-index works replicatedLog = new ReplicatedLogImpl(snapshot); context.setReplicatedLog(replicatedLog); context.setLastApplied(snapshot.getLastAppliedIndex()); } else if (message instanceof FindLeader) { getSender().tell( new FindLeaderReply(getLeaderAddress()), getSelf() ); } else if (message instanceof SaveSnapshotSuccess) { SaveSnapshotSuccess success = (SaveSnapshotSuccess) message; LOG.info("{}: SaveSnapshotSuccess received for snapshot", persistenceId()); long sequenceNumber = success.metadata().sequenceNr(); commitSnapshot(sequenceNumber); } else if (message instanceof SaveSnapshotFailure) { SaveSnapshotFailure saveSnapshotFailure = (SaveSnapshotFailure) message; LOG.error("{}: SaveSnapshotFailure received for snapshot Cause:", persistenceId(), saveSnapshotFailure.cause()); context.getReplicatedLog().snapshotRollback(); LOG.info("{}: Replicated Log rollbacked. Snapshot will be attempted in the next cycle." + "snapshotIndex:{}, snapshotTerm:{}, log-size:{}", persistenceId(), context.getReplicatedLog().getSnapshotIndex(), context.getReplicatedLog().getSnapshotTerm(), context.getReplicatedLog().size()); } else if (message instanceof CaptureSnapshot) { LOG.debug("{}: CaptureSnapshot received by actor: {}", persistenceId(), message); if(captureSnapshot == null) { captureSnapshot = (CaptureSnapshot)message; createSnapshot(); } } else if (message instanceof CaptureSnapshotReply){ handleCaptureSnapshotReply(((CaptureSnapshotReply) message).getSnapshot()); } else { RaftActorBehavior oldBehavior = currentBehavior; currentBehavior = currentBehavior.handleMessage(getSender(), message); handleBehaviorChange(oldBehavior, currentBehavior); } } private void handleBehaviorChange(RaftActorBehavior oldBehavior, RaftActorBehavior currentBehavior) { if (oldBehavior != currentBehavior){ onStateChanged(); } String oldBehaviorLeaderId = oldBehavior == null? null : oldBehavior.getLeaderId(); String oldBehaviorState = oldBehavior == null? null : oldBehavior.state().name(); // it can happen that the state has not changed but the leader has changed. onLeaderChanged(oldBehaviorLeaderId, currentBehavior.getLeaderId()); if (getRoleChangeNotifier().isPresent() && (oldBehavior == null || (oldBehavior.state() != currentBehavior.state()))) { getRoleChangeNotifier().get().tell( new RoleChanged(getId(), oldBehaviorState , currentBehavior.state().name()), getSelf()); } } /** * When a derived RaftActor needs to persist something it must call * persistData. * * @param clientActor * @param identifier * @param data */ protected void persistData(final ActorRef clientActor, final String identifier, final Payload data) { ReplicatedLogEntry replicatedLogEntry = new ReplicatedLogImplEntry( context.getReplicatedLog().lastIndex() + 1, context.getTermInformation().getCurrentTerm(), data); if(LOG.isDebugEnabled()) { LOG.debug("{}: Persist data {}", persistenceId(), replicatedLogEntry); } final RaftActorContext raftContext = getRaftActorContext(); replicatedLog .appendAndPersist(replicatedLogEntry, new Procedure<ReplicatedLogEntry>() { @Override public void apply(ReplicatedLogEntry replicatedLogEntry) throws Exception { if(!hasFollowers()){ // Increment the Commit Index and the Last Applied values raftContext.setCommitIndex(replicatedLogEntry.getIndex()); raftContext.setLastApplied(replicatedLogEntry.getIndex()); // Apply the state immediately applyState(clientActor, identifier, data); // Send a ApplyJournalEntries message so that we write the fact that we applied // the state to durable storage self().tell(new ApplyJournalEntries(replicatedLogEntry.getIndex()), self()); // Check if the "real" snapshot capture has been initiated. If no then do the fake snapshot if(!context.isSnapshotCaptureInitiated()){ raftContext.getReplicatedLog().snapshotPreCommit(raftContext.getLastApplied(), raftContext.getTermInformation().getCurrentTerm()); raftContext.getReplicatedLog().snapshotCommit(); } else { LOG.debug("{}: Skipping fake snapshotting for {} because real snapshotting is in progress", persistenceId(), getId()); } } else if (clientActor != null) { // Send message for replication currentBehavior.handleMessage(getSelf(), new Replicate(clientActor, identifier, replicatedLogEntry) ); } } }); } protected String getId() { return context.getId(); } /** * Derived actors can call the isLeader method to check if the current * RaftActor is the Leader or not * * @return true it this RaftActor is a Leader false otherwise */ protected boolean isLeader() { return context.getId().equals(currentBehavior.getLeaderId()); } /** * Derived actor can call getLeader if they need a reference to the Leader. * This would be useful for example in forwarding a request to an actor * which is the leader * * @return A reference to the leader if known, null otherwise */ protected ActorSelection getLeader(){ String leaderAddress = getLeaderAddress(); if(leaderAddress == null){ return null; } return context.actorSelection(leaderAddress); } /** * * @return the current leader's id */ protected String getLeaderId(){ return currentBehavior.getLeaderId(); } protected RaftState getRaftState() { return currentBehavior.state(); } protected ReplicatedLogEntry getLastLogEntry() { return replicatedLog.last(); } protected Long getCurrentTerm(){ return context.getTermInformation().getCurrentTerm(); } protected Long getCommitIndex(){ return context.getCommitIndex(); } protected Long getLastApplied(){ return context.getLastApplied(); } protected RaftActorContext getRaftActorContext() { return context; } protected void updateConfigParams(ConfigParams configParams) { context.setConfigParams(configParams); } /** * setPeerAddress sets the address of a known peer at a later time. * <p> * This is to account for situations where a we know that a peer * exists but we do not know an address up-front. This may also be used in * situations where a known peer starts off in a different location and we * need to change it's address * <p> * Note that if the peerId does not match the list of peers passed to * this actor during construction an IllegalStateException will be thrown. * * @param peerId * @param peerAddress */ protected void setPeerAddress(String peerId, String peerAddress){ context.setPeerAddress(peerId, peerAddress); } protected void commitSnapshot(long sequenceNumber) { context.getReplicatedLog().snapshotCommit(); // TODO: Not sure if we want to be this aggressive with trimming stuff trimPersistentData(sequenceNumber); } /** * The applyState method will be called by the RaftActor when some data * needs to be applied to the actor's state * * @param clientActor A reference to the client who sent this message. This * is the same reference that was passed to persistData * by the derived actor. clientActor may be null when * the RaftActor is behaving as a follower or during * recovery. * @param identifier The identifier of the persisted data. This is also * the same identifier that was passed to persistData by * the derived actor. identifier may be null when * the RaftActor is behaving as a follower or during * recovery * @param data A piece of data that was persisted by the persistData call. * This should NEVER be null. */ protected abstract void applyState(ActorRef clientActor, String identifier, Object data); /** * This method is called during recovery at the start of a batch of state entries. Derived * classes should perform any initialization needed to start a batch. */ protected abstract void startLogRecoveryBatch(int maxBatchSize); /** * This method is called during recovery to append state data to the current batch. This method * is called 1 or more times after {@link #startLogRecoveryBatch}. * * @param data the state data */ protected abstract void appendRecoveredLogEntry(Payload data); /** * This method is called during recovery to reconstruct the state of the actor. * * @param snapshotBytes A snapshot of the state of the actor */ protected abstract void applyRecoverySnapshot(byte[] snapshotBytes); /** * This method is called during recovery at the end of a batch to apply the current batched * log entries. This method is called after {@link #appendRecoveredLogEntry}. */ protected abstract void applyCurrentLogRecoveryBatch(); /** * This method is called when recovery is complete. */ protected abstract void onRecoveryComplete(); /** * This method will be called by the RaftActor when a snapshot needs to be * created. The derived actor should respond with its current state. * <p/> * During recovery the state that is returned by the derived actor will * be passed back to it by calling the applySnapshot method * * @return The current state of the actor */ protected abstract void createSnapshot(); /** * This method can be called at any other point during normal * operations when the derived actor is out of sync with it's peers * and the only way to bring it in sync is by applying a snapshot * * @param snapshotBytes A snapshot of the state of the actor */ protected abstract void applySnapshot(byte[] snapshotBytes); /** * This method will be called by the RaftActor when the state of the * RaftActor changes. The derived actor can then use methods like * isLeader or getLeader to do something useful */ protected abstract void onStateChanged(); protected abstract DataPersistenceProvider persistence(); /** * Notifier Actor for this RaftActor to notify when a role change happens * @return ActorRef - ActorRef of the notifier or Optional.absent if none. */ protected abstract Optional<ActorRef> getRoleChangeNotifier(); protected void onLeaderChanged(String oldLeader, String newLeader){}; private void trimPersistentData(long sequenceNumber) { // Trim akka snapshots // FIXME : Not sure how exactly the SnapshotSelectionCriteria is applied // For now guessing that it is ANDed. persistence().deleteSnapshots(new SnapshotSelectionCriteria( sequenceNumber - context.getConfigParams().getSnapshotBatchCount(), 43200000)); // Trim akka journal persistence().deleteMessages(sequenceNumber); } private String getLeaderAddress(){ if(isLeader()){ return getSelf().path().toString(); } String leaderId = currentBehavior.getLeaderId(); if (leaderId == null) { return null; } String peerAddress = context.getPeerAddress(leaderId); if(LOG.isDebugEnabled()) { LOG.debug("{}: getLeaderAddress leaderId = {} peerAddress = {}", persistenceId(), leaderId, peerAddress); } return peerAddress; } private void handleCaptureSnapshotReply(byte[] snapshotBytes) { LOG.debug("{}: CaptureSnapshotReply received by actor: snapshot size {}", persistenceId(), snapshotBytes.length); // create a snapshot object from the state provided and save it // when snapshot is saved async, SaveSnapshotSuccess is raised. Snapshot sn = Snapshot.create(snapshotBytes, context.getReplicatedLog().getFrom(captureSnapshot.getLastAppliedIndex() + 1), captureSnapshot.getLastIndex(), captureSnapshot.getLastTerm(), captureSnapshot.getLastAppliedIndex(), captureSnapshot.getLastAppliedTerm()); persistence().saveSnapshot(sn); LOG.info("{}: Persisting of snapshot done:{}", persistenceId(), sn.getLogMessage()); long dataThreshold = Runtime.getRuntime().totalMemory() * getRaftActorContext().getConfigParams().getSnapshotDataThresholdPercentage() / 100; if (context.getReplicatedLog().dataSize() > dataThreshold) { if(LOG.isDebugEnabled()) { LOG.debug("{}: dataSize {} exceeds dataThreshold {} - doing snapshotPreCommit with index {}", persistenceId(), context.getReplicatedLog().dataSize(), dataThreshold, captureSnapshot.getLastAppliedIndex()); } // if memory is less, clear the log based on lastApplied. // this could/should only happen if one of the followers is down // as normally we keep removing from the log when its replicated to all. context.getReplicatedLog().snapshotPreCommit(captureSnapshot.getLastAppliedIndex(), captureSnapshot.getLastAppliedTerm()); // Don't reset replicatedToAllIndex to -1 as this may prevent us from trimming the log after an // install snapshot to a follower. if(captureSnapshot.getReplicatedToAllIndex() >= 0) { getCurrentBehavior().setReplicatedToAllIndex(captureSnapshot.getReplicatedToAllIndex()); } } else if(captureSnapshot.getReplicatedToAllIndex() != -1){ // clear the log based on replicatedToAllIndex context.getReplicatedLog().snapshotPreCommit(captureSnapshot.getReplicatedToAllIndex(), captureSnapshot.getReplicatedToAllTerm()); getCurrentBehavior().setReplicatedToAllIndex(captureSnapshot.getReplicatedToAllIndex()); } else { // The replicatedToAllIndex was not found in the log // This means that replicatedToAllIndex never moved beyond -1 or that it is already in the snapshot. // In this scenario we may need to save the snapshot to the akka persistence // snapshot for recovery but we do not need to do the replicated log trimming. context.getReplicatedLog().snapshotPreCommit(replicatedLog.getSnapshotIndex(), replicatedLog.getSnapshotTerm()); } LOG.info("{}: Removed in-memory snapshotted entries, adjusted snaphsotIndex: {} " + "and term: {}", persistenceId(), replicatedLog.getSnapshotIndex(), replicatedLog.getSnapshotTerm()); if (isLeader() && captureSnapshot.isInstallSnapshotInitiated()) { // this would be call straight to the leader and won't initiate in serialization currentBehavior.handleMessage(getSelf(), new SendInstallSnapshot( ByteString.copyFrom(snapshotBytes))); } captureSnapshot = null; context.setSnapshotCaptureInitiated(false); } protected boolean hasFollowers(){ return getRaftActorContext().getPeerAddresses().keySet().size() > 0; } private class ReplicatedLogImpl extends AbstractReplicatedLogImpl { private static final int DATA_SIZE_DIVIDER = 5; private long dataSizeSinceLastSnapshot = 0; public ReplicatedLogImpl(Snapshot snapshot) { super(snapshot.getLastAppliedIndex(), snapshot.getLastAppliedTerm(), snapshot.getUnAppliedEntries()); } public ReplicatedLogImpl() { super(); } @Override public void removeFromAndPersist(long logEntryIndex) { int adjustedIndex = adjustedIndex(logEntryIndex); if (adjustedIndex < 0) { return; } // FIXME: Maybe this should be done after the command is saved journal.subList(adjustedIndex , journal.size()).clear(); persistence().persist(new DeleteEntries(adjustedIndex), new Procedure<DeleteEntries>() { @Override public void apply(DeleteEntries param) throws Exception { //FIXME : Doing nothing for now dataSize = 0; for (ReplicatedLogEntry entry : journal) { dataSize += entry.size(); } } }); } @Override public void appendAndPersist( final ReplicatedLogEntry replicatedLogEntry) { appendAndPersist(replicatedLogEntry, null); } public void appendAndPersist( final ReplicatedLogEntry replicatedLogEntry, final Procedure<ReplicatedLogEntry> callback) { if(LOG.isDebugEnabled()) { LOG.debug("{}: Append log entry and persist {} ", persistenceId(), replicatedLogEntry); } // FIXME : By adding the replicated log entry to the in-memory journal we are not truly ensuring durability of the logs journal.add(replicatedLogEntry); // When persisting events with persist it is guaranteed that the // persistent actor will not receive further commands between the // persist call and the execution(s) of the associated event // handler. This also holds for multiple persist calls in context // of a single command. persistence().persist(replicatedLogEntry, new Procedure<ReplicatedLogEntry>() { @Override public void apply(ReplicatedLogEntry evt) throws Exception { int logEntrySize = replicatedLogEntry.size(); dataSize += logEntrySize; long dataSizeForCheck = dataSize; dataSizeSinceLastSnapshot += logEntrySize; long journalSize = lastIndex() + 1; if(!hasFollowers()) { // When we do not have followers we do not maintain an in-memory log // due to this the journalSize will never become anything close to the // snapshot batch count. In fact will mostly be 1. // Similarly since the journal's dataSize depends on the entries in the // journal the journal's dataSize will never reach a value close to the // memory threshold. // By maintaining the dataSize outside the journal we are tracking essentially // what we have written to the disk however since we no longer are in // need of doing a snapshot just for the sake of freeing up memory we adjust // the real size of data by the DATA_SIZE_DIVIDER so that we do not snapshot as often // as if we were maintaining a real snapshot dataSizeForCheck = dataSizeSinceLastSnapshot / DATA_SIZE_DIVIDER; } long dataThreshold = Runtime.getRuntime().totalMemory() * getRaftActorContext().getConfigParams().getSnapshotDataThresholdPercentage() / 100; // when a snaphsot is being taken, captureSnapshot != null if (!context.isSnapshotCaptureInitiated() && ( journalSize % context.getConfigParams().getSnapshotBatchCount() == 0 || dataSizeForCheck > dataThreshold)) { dataSizeSinceLastSnapshot = 0; LOG.info("{}: Initiating Snapshot Capture, journalSize = {}, dataSizeForCheck = {}," + " dataThreshold = {}", persistenceId(), journalSize, dataSizeForCheck, dataThreshold); long lastAppliedIndex = -1; long lastAppliedTerm = -1; ReplicatedLogEntry lastAppliedEntry = get(context.getLastApplied()); if (!hasFollowers()) { lastAppliedIndex = replicatedLogEntry.getIndex(); lastAppliedTerm = replicatedLogEntry.getTerm(); } else if (lastAppliedEntry != null) { lastAppliedIndex = lastAppliedEntry.getIndex(); lastAppliedTerm = lastAppliedEntry.getTerm(); } if(LOG.isDebugEnabled()) { LOG.debug("{}: Snapshot Capture logSize: {}", persistenceId(), journal.size()); LOG.debug("{}: Snapshot Capture lastApplied:{} ", persistenceId(), context.getLastApplied()); LOG.debug("{}: Snapshot Capture lastAppliedIndex:{}", persistenceId(), lastAppliedIndex); LOG.debug("{}: Snapshot Capture lastAppliedTerm:{}", persistenceId(), lastAppliedTerm); } // send a CaptureSnapshot to self to make the expensive operation async. long replicatedToAllIndex = getCurrentBehavior().getReplicatedToAllIndex(); ReplicatedLogEntry replicatedToAllEntry = context.getReplicatedLog().get(replicatedToAllIndex); getSelf().tell(new CaptureSnapshot(lastIndex(), lastTerm(), lastAppliedIndex, lastAppliedTerm, (replicatedToAllEntry != null ? replicatedToAllEntry.getIndex() : -1), (replicatedToAllEntry != null ? replicatedToAllEntry.getTerm() : -1)), null); context.setSnapshotCaptureInitiated(true); } if (callback != null){ callback.apply(replicatedLogEntry); } } } ); } } static class DeleteEntries implements Serializable { private static final long serialVersionUID = 1L; private final int fromIndex; public DeleteEntries(int fromIndex) { this.fromIndex = fromIndex; } public int getFromIndex() { return fromIndex; } } private class ElectionTermImpl implements ElectionTerm { /** * Identifier of the actor whose election term information this is */ private long currentTerm = 0; private String votedFor = null; @Override public long getCurrentTerm() { return currentTerm; } @Override public String getVotedFor() { return votedFor; } @Override public void update(long currentTerm, String votedFor) { if(LOG.isDebugEnabled()) { LOG.debug("{}: Set currentTerm={}, votedFor={}", persistenceId(), currentTerm, votedFor); } this.currentTerm = currentTerm; this.votedFor = votedFor; } @Override public void updateAndPersist(long currentTerm, String votedFor){ update(currentTerm, votedFor); // FIXME : Maybe first persist then update the state persistence().persist(new UpdateElectionTerm(this.currentTerm, this.votedFor), new Procedure<UpdateElectionTerm>(){ @Override public void apply(UpdateElectionTerm param) throws Exception { } }); } } static class UpdateElectionTerm implements Serializable { private static final long serialVersionUID = 1L; private final long currentTerm; private final String votedFor; public UpdateElectionTerm(long currentTerm, String votedFor) { this.currentTerm = currentTerm; this.votedFor = votedFor; } public long getCurrentTerm() { return currentTerm; } public String getVotedFor() { return votedFor; } } protected class NonPersistentRaftDataProvider extends NonPersistentDataProvider { public NonPersistentRaftDataProvider(){ } /** * The way snapshotting works is, * <ol> * <li> RaftActor calls createSnapshot on the Shard * <li> Shard sends a CaptureSnapshotReply and RaftActor then calls saveSnapshot * <li> When saveSnapshot is invoked on the akka-persistence API it uses the SnapshotStore to save the snapshot. * The SnapshotStore sends SaveSnapshotSuccess or SaveSnapshotFailure. When the RaftActor gets SaveSnapshot * success it commits the snapshot to the in-memory journal. This commitSnapshot is mimicking what is done * in SaveSnapshotSuccess. * </ol> * @param o */ @Override public void saveSnapshot(Object o) { // Make saving Snapshot successful commitSnapshot(-1L); } } @VisibleForTesting void setCurrentBehavior(AbstractRaftActorBehavior behavior) { currentBehavior = behavior; } protected RaftActorBehavior getCurrentBehavior() { return currentBehavior; } }
opendaylight/md-sal/sal-akka-raft/src/main/java/org/opendaylight/controller/cluster/raft/RaftActor.java
/* * Copyright (c) 2014 Cisco 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 */ package org.opendaylight.controller.cluster.raft; import akka.actor.ActorRef; import akka.actor.ActorSelection; import akka.japi.Procedure; import akka.persistence.RecoveryCompleted; import akka.persistence.SaveSnapshotFailure; import akka.persistence.SaveSnapshotSuccess; import akka.persistence.SnapshotOffer; import akka.persistence.SnapshotSelectionCriteria; import com.google.common.annotations.VisibleForTesting; import com.google.common.base.Optional; import com.google.common.base.Stopwatch; import com.google.protobuf.ByteString; import java.io.Serializable; import java.util.Map; import java.util.concurrent.TimeUnit; import org.opendaylight.controller.cluster.DataPersistenceProvider; import org.opendaylight.controller.cluster.common.actor.AbstractUntypedPersistentActor; import org.opendaylight.controller.cluster.notifications.RoleChanged; import org.opendaylight.controller.cluster.raft.base.messages.ApplyJournalEntries; import org.opendaylight.controller.cluster.raft.base.messages.ApplyLogEntries; import org.opendaylight.controller.cluster.raft.base.messages.ApplySnapshot; import org.opendaylight.controller.cluster.raft.base.messages.ApplyState; import org.opendaylight.controller.cluster.raft.base.messages.CaptureSnapshot; import org.opendaylight.controller.cluster.raft.base.messages.CaptureSnapshotReply; import org.opendaylight.controller.cluster.raft.base.messages.Replicate; import org.opendaylight.controller.cluster.raft.base.messages.SendInstallSnapshot; import org.opendaylight.controller.cluster.raft.behaviors.AbstractRaftActorBehavior; import org.opendaylight.controller.cluster.raft.behaviors.Follower; import org.opendaylight.controller.cluster.raft.behaviors.RaftActorBehavior; import org.opendaylight.controller.cluster.raft.client.messages.FindLeader; import org.opendaylight.controller.cluster.raft.client.messages.FindLeaderReply; import org.opendaylight.controller.cluster.raft.protobuff.client.messages.Payload; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * RaftActor encapsulates a state machine that needs to be kept synchronized * in a cluster. It implements the RAFT algorithm as described in the paper * <a href='https://ramcloud.stanford.edu/wiki/download/attachments/11370504/raft.pdf'> * In Search of an Understandable Consensus Algorithm</a> * <p/> * RaftActor has 3 states and each state has a certain behavior associated * with it. A Raft actor can behave as, * <ul> * <li> A Leader </li> * <li> A Follower (or) </li> * <li> A Candidate </li> * </ul> * <p/> * <p/> * A RaftActor MUST be a Leader in order to accept requests from clients to * change the state of it's encapsulated state machine. Once a RaftActor becomes * a Leader it is also responsible for ensuring that all followers ultimately * have the same log and therefore the same state machine as itself. * <p/> * <p/> * The current behavior of a RaftActor determines how election for leadership * is initiated and how peer RaftActors react to request for votes. * <p/> * <p/> * Each RaftActor also needs to know the current election term. It uses this * information for a couple of things. One is to simply figure out who it * voted for in the last election. Another is to figure out if the message * it received to update it's state is stale. * <p/> * <p/> * The RaftActor uses akka-persistence to store it's replicated log. * Furthermore through it's behaviors a Raft Actor determines * <p/> * <ul> * <li> when a log entry should be persisted </li> * <li> when a log entry should be applied to the state machine (and) </li> * <li> when a snapshot should be saved </li> * </ul> */ public abstract class RaftActor extends AbstractUntypedPersistentActor { private static final long APPLY_STATE_DELAY_THRESHOLD_IN_NANOS = TimeUnit.MILLISECONDS.toNanos(50L); // 50 millis protected final Logger LOG = LoggerFactory.getLogger(getClass()); /** * The current state determines the current behavior of a RaftActor * A Raft Actor always starts off in the Follower State */ private RaftActorBehavior currentBehavior; /** * This context should NOT be passed directly to any other actor it is * only to be consumed by the RaftActorBehaviors */ private final RaftActorContextImpl context; /** * The in-memory journal */ private ReplicatedLogImpl replicatedLog = new ReplicatedLogImpl(); private CaptureSnapshot captureSnapshot = null; private Stopwatch recoveryTimer; private int currentRecoveryBatchCount; public RaftActor(String id, Map<String, String> peerAddresses) { this(id, peerAddresses, Optional.<ConfigParams>absent()); } public RaftActor(String id, Map<String, String> peerAddresses, Optional<ConfigParams> configParams) { context = new RaftActorContextImpl(this.getSelf(), this.getContext(), id, new ElectionTermImpl(), -1, -1, replicatedLog, peerAddresses, (configParams.isPresent() ? configParams.get(): new DefaultConfigParamsImpl()), LOG); } private void initRecoveryTimer() { if(recoveryTimer == null) { recoveryTimer = Stopwatch.createStarted(); } } @Override public void preStart() throws Exception { LOG.info("Starting recovery for {} with journal batch size {}", persistenceId(), context.getConfigParams().getJournalRecoveryLogBatchSize()); super.preStart(); } @Override public void postStop() { if(currentBehavior != null) { try { currentBehavior.close(); } catch (Exception e) { LOG.debug("{}: Error closing behavior {}", persistenceId(), currentBehavior.state()); } } super.postStop(); } @Override public void handleRecover(Object message) { if(persistence().isRecoveryApplicable()) { if (message instanceof SnapshotOffer) { onRecoveredSnapshot((SnapshotOffer) message); } else if (message instanceof ReplicatedLogEntry) { onRecoveredJournalLogEntry((ReplicatedLogEntry) message); } else if (message instanceof ApplyLogEntries) { // Handle this message for backwards compatibility with pre-Lithium versions. onRecoveredApplyLogEntries(((ApplyLogEntries) message).getToIndex()); } else if (message instanceof ApplyJournalEntries) { onRecoveredApplyLogEntries(((ApplyJournalEntries) message).getToIndex()); } else if (message instanceof DeleteEntries) { replicatedLog.removeFrom(((DeleteEntries) message).getFromIndex()); } else if (message instanceof UpdateElectionTerm) { context.getTermInformation().update(((UpdateElectionTerm) message).getCurrentTerm(), ((UpdateElectionTerm) message).getVotedFor()); } else if (message instanceof RecoveryCompleted) { onRecoveryCompletedMessage(); } } else { if (message instanceof RecoveryCompleted) { // Delete all the messages from the akka journal so that we do not end up with consistency issues // Note I am not using the dataPersistenceProvider and directly using the akka api here deleteMessages(lastSequenceNr()); // Delete all the akka snapshots as they will not be needed deleteSnapshots(new SnapshotSelectionCriteria(scala.Long.MaxValue(), scala.Long.MaxValue())); onRecoveryComplete(); initializeBehavior(); } } } private void onRecoveredSnapshot(SnapshotOffer offer) { if(LOG.isDebugEnabled()) { LOG.debug("{}: SnapshotOffer called..", persistenceId()); } initRecoveryTimer(); Snapshot snapshot = (Snapshot) offer.snapshot(); // Create a replicated log with the snapshot information // The replicated log can be used later on to retrieve this snapshot // when we need to install it on a peer replicatedLog = new ReplicatedLogImpl(snapshot); context.setReplicatedLog(replicatedLog); context.setLastApplied(snapshot.getLastAppliedIndex()); context.setCommitIndex(snapshot.getLastAppliedIndex()); Stopwatch timer = Stopwatch.createStarted(); // Apply the snapshot to the actors state applyRecoverySnapshot(snapshot.getState()); timer.stop(); LOG.info("Recovery snapshot applied for {} in {}: snapshotIndex={}, snapshotTerm={}, journal-size=" + replicatedLog.size(), persistenceId(), timer.toString(), replicatedLog.getSnapshotIndex(), replicatedLog.getSnapshotTerm()); } private void onRecoveredJournalLogEntry(ReplicatedLogEntry logEntry) { if(LOG.isDebugEnabled()) { LOG.debug("{}: Received ReplicatedLogEntry for recovery: {}", persistenceId(), logEntry.getIndex()); } replicatedLog.append(logEntry); } private void onRecoveredApplyLogEntries(long toIndex) { if(LOG.isDebugEnabled()) { LOG.debug("{}: Received ApplyLogEntries for recovery, applying to state: {} to {}", persistenceId(), context.getLastApplied() + 1, toIndex); } for (long i = context.getLastApplied() + 1; i <= toIndex; i++) { batchRecoveredLogEntry(replicatedLog.get(i)); } context.setLastApplied(toIndex); context.setCommitIndex(toIndex); } private void batchRecoveredLogEntry(ReplicatedLogEntry logEntry) { initRecoveryTimer(); int batchSize = context.getConfigParams().getJournalRecoveryLogBatchSize(); if(currentRecoveryBatchCount == 0) { startLogRecoveryBatch(batchSize); } appendRecoveredLogEntry(logEntry.getData()); if(++currentRecoveryBatchCount >= batchSize) { endCurrentLogRecoveryBatch(); } } private void endCurrentLogRecoveryBatch() { applyCurrentLogRecoveryBatch(); currentRecoveryBatchCount = 0; } private void onRecoveryCompletedMessage() { if(currentRecoveryBatchCount > 0) { endCurrentLogRecoveryBatch(); } onRecoveryComplete(); String recoveryTime = ""; if(recoveryTimer != null) { recoveryTimer.stop(); recoveryTime = " in " + recoveryTimer.toString(); recoveryTimer = null; } LOG.info( "Recovery completed" + recoveryTime + " - Switching actor to Follower - " + "Persistence Id = " + persistenceId() + " Last index in log={}, snapshotIndex={}, snapshotTerm={}, " + "journal-size={}", replicatedLog.lastIndex(), replicatedLog.getSnapshotIndex(), replicatedLog.getSnapshotTerm(), replicatedLog.size()); initializeBehavior(); } protected void initializeBehavior(){ changeCurrentBehavior(new Follower(context)); } protected void changeCurrentBehavior(RaftActorBehavior newBehavior){ RaftActorBehavior oldBehavior = currentBehavior; currentBehavior = newBehavior; handleBehaviorChange(oldBehavior, currentBehavior); } @Override public void handleCommand(Object message) { if (message instanceof ApplyState){ ApplyState applyState = (ApplyState) message; long elapsedTime = (System.nanoTime() - applyState.getStartTime()); if(elapsedTime >= APPLY_STATE_DELAY_THRESHOLD_IN_NANOS){ LOG.warn("ApplyState took more time than expected. Elapsed Time = {} ms ApplyState = {}", TimeUnit.NANOSECONDS.toMillis(elapsedTime), applyState); } if(LOG.isDebugEnabled()) { LOG.debug("{}: Applying state for log index {} data {}", persistenceId(), applyState.getReplicatedLogEntry().getIndex(), applyState.getReplicatedLogEntry().getData()); } applyState(applyState.getClientActor(), applyState.getIdentifier(), applyState.getReplicatedLogEntry().getData()); } else if (message instanceof ApplyJournalEntries){ ApplyJournalEntries applyEntries = (ApplyJournalEntries) message; if(LOG.isDebugEnabled()) { LOG.debug("{}: Persisting ApplyLogEntries with index={}", persistenceId(), applyEntries.getToIndex()); } persistence().persist(applyEntries, new Procedure<ApplyJournalEntries>() { @Override public void apply(ApplyJournalEntries param) throws Exception { } }); } else if(message instanceof ApplySnapshot ) { Snapshot snapshot = ((ApplySnapshot) message).getSnapshot(); if(LOG.isDebugEnabled()) { LOG.debug("{}: ApplySnapshot called on Follower Actor " + "snapshotIndex:{}, snapshotTerm:{}", persistenceId(), snapshot.getLastAppliedIndex(), snapshot.getLastAppliedTerm() ); } applySnapshot(snapshot.getState()); //clears the followers log, sets the snapshot index to ensure adjusted-index works replicatedLog = new ReplicatedLogImpl(snapshot); context.setReplicatedLog(replicatedLog); context.setLastApplied(snapshot.getLastAppliedIndex()); } else if (message instanceof FindLeader) { getSender().tell( new FindLeaderReply(getLeaderAddress()), getSelf() ); } else if (message instanceof SaveSnapshotSuccess) { SaveSnapshotSuccess success = (SaveSnapshotSuccess) message; LOG.info("{}: SaveSnapshotSuccess received for snapshot", persistenceId()); long sequenceNumber = success.metadata().sequenceNr(); commitSnapshot(sequenceNumber); } else if (message instanceof SaveSnapshotFailure) { SaveSnapshotFailure saveSnapshotFailure = (SaveSnapshotFailure) message; LOG.error("{}: SaveSnapshotFailure received for snapshot Cause:", persistenceId(), saveSnapshotFailure.cause()); context.getReplicatedLog().snapshotRollback(); LOG.info("{}: Replicated Log rollbacked. Snapshot will be attempted in the next cycle." + "snapshotIndex:{}, snapshotTerm:{}, log-size:{}", persistenceId(), context.getReplicatedLog().getSnapshotIndex(), context.getReplicatedLog().getSnapshotTerm(), context.getReplicatedLog().size()); } else if (message instanceof CaptureSnapshot) { LOG.info("{}: CaptureSnapshot received by actor", persistenceId()); if(captureSnapshot == null) { captureSnapshot = (CaptureSnapshot)message; createSnapshot(); } } else if (message instanceof CaptureSnapshotReply){ handleCaptureSnapshotReply(((CaptureSnapshotReply) message).getSnapshot()); } else { RaftActorBehavior oldBehavior = currentBehavior; currentBehavior = currentBehavior.handleMessage(getSender(), message); handleBehaviorChange(oldBehavior, currentBehavior); } } private void handleBehaviorChange(RaftActorBehavior oldBehavior, RaftActorBehavior currentBehavior) { if (oldBehavior != currentBehavior){ onStateChanged(); } String oldBehaviorLeaderId = oldBehavior == null? null : oldBehavior.getLeaderId(); String oldBehaviorState = oldBehavior == null? null : oldBehavior.state().name(); // it can happen that the state has not changed but the leader has changed. onLeaderChanged(oldBehaviorLeaderId, currentBehavior.getLeaderId()); if (getRoleChangeNotifier().isPresent() && (oldBehavior == null || (oldBehavior.state() != currentBehavior.state()))) { getRoleChangeNotifier().get().tell( new RoleChanged(getId(), oldBehaviorState , currentBehavior.state().name()), getSelf()); } } /** * When a derived RaftActor needs to persist something it must call * persistData. * * @param clientActor * @param identifier * @param data */ protected void persistData(final ActorRef clientActor, final String identifier, final Payload data) { ReplicatedLogEntry replicatedLogEntry = new ReplicatedLogImplEntry( context.getReplicatedLog().lastIndex() + 1, context.getTermInformation().getCurrentTerm(), data); if(LOG.isDebugEnabled()) { LOG.debug("{}: Persist data {}", persistenceId(), replicatedLogEntry); } final RaftActorContext raftContext = getRaftActorContext(); replicatedLog .appendAndPersist(replicatedLogEntry, new Procedure<ReplicatedLogEntry>() { @Override public void apply(ReplicatedLogEntry replicatedLogEntry) throws Exception { if(!hasFollowers()){ // Increment the Commit Index and the Last Applied values raftContext.setCommitIndex(replicatedLogEntry.getIndex()); raftContext.setLastApplied(replicatedLogEntry.getIndex()); // Apply the state immediately applyState(clientActor, identifier, data); // Send a ApplyJournalEntries message so that we write the fact that we applied // the state to durable storage self().tell(new ApplyJournalEntries(replicatedLogEntry.getIndex()), self()); // Check if the "real" snapshot capture has been initiated. If no then do the fake snapshot if(!context.isSnapshotCaptureInitiated()){ raftContext.getReplicatedLog().snapshotPreCommit(raftContext.getLastApplied(), raftContext.getTermInformation().getCurrentTerm()); raftContext.getReplicatedLog().snapshotCommit(); } else { LOG.debug("{}: Skipping fake snapshotting for {} because real snapshotting is in progress", persistenceId(), getId()); } } else if (clientActor != null) { // Send message for replication currentBehavior.handleMessage(getSelf(), new Replicate(clientActor, identifier, replicatedLogEntry) ); } } }); } protected String getId() { return context.getId(); } /** * Derived actors can call the isLeader method to check if the current * RaftActor is the Leader or not * * @return true it this RaftActor is a Leader false otherwise */ protected boolean isLeader() { return context.getId().equals(currentBehavior.getLeaderId()); } /** * Derived actor can call getLeader if they need a reference to the Leader. * This would be useful for example in forwarding a request to an actor * which is the leader * * @return A reference to the leader if known, null otherwise */ protected ActorSelection getLeader(){ String leaderAddress = getLeaderAddress(); if(leaderAddress == null){ return null; } return context.actorSelection(leaderAddress); } /** * * @return the current leader's id */ protected String getLeaderId(){ return currentBehavior.getLeaderId(); } protected RaftState getRaftState() { return currentBehavior.state(); } protected ReplicatedLogEntry getLastLogEntry() { return replicatedLog.last(); } protected Long getCurrentTerm(){ return context.getTermInformation().getCurrentTerm(); } protected Long getCommitIndex(){ return context.getCommitIndex(); } protected Long getLastApplied(){ return context.getLastApplied(); } protected RaftActorContext getRaftActorContext() { return context; } protected void updateConfigParams(ConfigParams configParams) { context.setConfigParams(configParams); } /** * setPeerAddress sets the address of a known peer at a later time. * <p> * This is to account for situations where a we know that a peer * exists but we do not know an address up-front. This may also be used in * situations where a known peer starts off in a different location and we * need to change it's address * <p> * Note that if the peerId does not match the list of peers passed to * this actor during construction an IllegalStateException will be thrown. * * @param peerId * @param peerAddress */ protected void setPeerAddress(String peerId, String peerAddress){ context.setPeerAddress(peerId, peerAddress); } protected void commitSnapshot(long sequenceNumber) { context.getReplicatedLog().snapshotCommit(); // TODO: Not sure if we want to be this aggressive with trimming stuff trimPersistentData(sequenceNumber); } /** * The applyState method will be called by the RaftActor when some data * needs to be applied to the actor's state * * @param clientActor A reference to the client who sent this message. This * is the same reference that was passed to persistData * by the derived actor. clientActor may be null when * the RaftActor is behaving as a follower or during * recovery. * @param identifier The identifier of the persisted data. This is also * the same identifier that was passed to persistData by * the derived actor. identifier may be null when * the RaftActor is behaving as a follower or during * recovery * @param data A piece of data that was persisted by the persistData call. * This should NEVER be null. */ protected abstract void applyState(ActorRef clientActor, String identifier, Object data); /** * This method is called during recovery at the start of a batch of state entries. Derived * classes should perform any initialization needed to start a batch. */ protected abstract void startLogRecoveryBatch(int maxBatchSize); /** * This method is called during recovery to append state data to the current batch. This method * is called 1 or more times after {@link #startLogRecoveryBatch}. * * @param data the state data */ protected abstract void appendRecoveredLogEntry(Payload data); /** * This method is called during recovery to reconstruct the state of the actor. * * @param snapshotBytes A snapshot of the state of the actor */ protected abstract void applyRecoverySnapshot(byte[] snapshotBytes); /** * This method is called during recovery at the end of a batch to apply the current batched * log entries. This method is called after {@link #appendRecoveredLogEntry}. */ protected abstract void applyCurrentLogRecoveryBatch(); /** * This method is called when recovery is complete. */ protected abstract void onRecoveryComplete(); /** * This method will be called by the RaftActor when a snapshot needs to be * created. The derived actor should respond with its current state. * <p/> * During recovery the state that is returned by the derived actor will * be passed back to it by calling the applySnapshot method * * @return The current state of the actor */ protected abstract void createSnapshot(); /** * This method can be called at any other point during normal * operations when the derived actor is out of sync with it's peers * and the only way to bring it in sync is by applying a snapshot * * @param snapshotBytes A snapshot of the state of the actor */ protected abstract void applySnapshot(byte[] snapshotBytes); /** * This method will be called by the RaftActor when the state of the * RaftActor changes. The derived actor can then use methods like * isLeader or getLeader to do something useful */ protected abstract void onStateChanged(); protected abstract DataPersistenceProvider persistence(); /** * Notifier Actor for this RaftActor to notify when a role change happens * @return ActorRef - ActorRef of the notifier or Optional.absent if none. */ protected abstract Optional<ActorRef> getRoleChangeNotifier(); protected void onLeaderChanged(String oldLeader, String newLeader){}; private void trimPersistentData(long sequenceNumber) { // Trim akka snapshots // FIXME : Not sure how exactly the SnapshotSelectionCriteria is applied // For now guessing that it is ANDed. persistence().deleteSnapshots(new SnapshotSelectionCriteria( sequenceNumber - context.getConfigParams().getSnapshotBatchCount(), 43200000)); // Trim akka journal persistence().deleteMessages(sequenceNumber); } private String getLeaderAddress(){ if(isLeader()){ return getSelf().path().toString(); } String leaderId = currentBehavior.getLeaderId(); if (leaderId == null) { return null; } String peerAddress = context.getPeerAddress(leaderId); if(LOG.isDebugEnabled()) { LOG.debug("{}: getLeaderAddress leaderId = {} peerAddress = {}", persistenceId(), leaderId, peerAddress); } return peerAddress; } private void handleCaptureSnapshotReply(byte[] snapshotBytes) { LOG.info("{}: CaptureSnapshotReply received by actor: snapshot size {}", persistenceId(), snapshotBytes.length); // create a snapshot object from the state provided and save it // when snapshot is saved async, SaveSnapshotSuccess is raised. Snapshot sn = Snapshot.create(snapshotBytes, context.getReplicatedLog().getFrom(captureSnapshot.getLastAppliedIndex() + 1), captureSnapshot.getLastIndex(), captureSnapshot.getLastTerm(), captureSnapshot.getLastAppliedIndex(), captureSnapshot.getLastAppliedTerm()); persistence().saveSnapshot(sn); LOG.info("{}: Persisting of snapshot done:{}", persistenceId(), sn.getLogMessage()); long dataThreshold = Runtime.getRuntime().totalMemory() * getRaftActorContext().getConfigParams().getSnapshotDataThresholdPercentage() / 100; if (context.getReplicatedLog().dataSize() > dataThreshold) { // if memory is less, clear the log based on lastApplied. // this could/should only happen if one of the followers is down // as normally we keep removing from the log when its replicated to all. context.getReplicatedLog().snapshotPreCommit(captureSnapshot.getLastAppliedIndex(), captureSnapshot.getLastAppliedTerm()); getCurrentBehavior().setReplicatedToAllIndex(captureSnapshot.getReplicatedToAllIndex()); } else if(captureSnapshot.getReplicatedToAllIndex() != -1){ // clear the log based on replicatedToAllIndex context.getReplicatedLog().snapshotPreCommit(captureSnapshot.getReplicatedToAllIndex(), captureSnapshot.getReplicatedToAllTerm()); getCurrentBehavior().setReplicatedToAllIndex(captureSnapshot.getReplicatedToAllIndex()); } else { // The replicatedToAllIndex was not found in the log // This means that replicatedToAllIndex never moved beyond -1 or that it is already in the snapshot. // In this scenario we may need to save the snapshot to the akka persistence // snapshot for recovery but we do not need to do the replicated log trimming. context.getReplicatedLog().snapshotPreCommit(replicatedLog.getSnapshotIndex(), replicatedLog.getSnapshotTerm()); } LOG.info("{}: Removed in-memory snapshotted entries, adjusted snaphsotIndex:{} " + "and term:{}", persistenceId(), captureSnapshot.getLastAppliedIndex(), captureSnapshot.getLastAppliedTerm()); if (isLeader() && captureSnapshot.isInstallSnapshotInitiated()) { // this would be call straight to the leader and won't initiate in serialization currentBehavior.handleMessage(getSelf(), new SendInstallSnapshot( ByteString.copyFrom(snapshotBytes))); } captureSnapshot = null; context.setSnapshotCaptureInitiated(false); } protected boolean hasFollowers(){ return getRaftActorContext().getPeerAddresses().keySet().size() > 0; } private class ReplicatedLogImpl extends AbstractReplicatedLogImpl { private static final int DATA_SIZE_DIVIDER = 5; private long dataSizeSinceLastSnapshot = 0; public ReplicatedLogImpl(Snapshot snapshot) { super(snapshot.getLastAppliedIndex(), snapshot.getLastAppliedTerm(), snapshot.getUnAppliedEntries()); } public ReplicatedLogImpl() { super(); } @Override public void removeFromAndPersist(long logEntryIndex) { int adjustedIndex = adjustedIndex(logEntryIndex); if (adjustedIndex < 0) { return; } // FIXME: Maybe this should be done after the command is saved journal.subList(adjustedIndex , journal.size()).clear(); persistence().persist(new DeleteEntries(adjustedIndex), new Procedure<DeleteEntries>() { @Override public void apply(DeleteEntries param) throws Exception { //FIXME : Doing nothing for now dataSize = 0; for (ReplicatedLogEntry entry : journal) { dataSize += entry.size(); } } }); } @Override public void appendAndPersist( final ReplicatedLogEntry replicatedLogEntry) { appendAndPersist(replicatedLogEntry, null); } public void appendAndPersist( final ReplicatedLogEntry replicatedLogEntry, final Procedure<ReplicatedLogEntry> callback) { if(LOG.isDebugEnabled()) { LOG.debug("{}: Append log entry and persist {} ", persistenceId(), replicatedLogEntry); } // FIXME : By adding the replicated log entry to the in-memory journal we are not truly ensuring durability of the logs journal.add(replicatedLogEntry); // When persisting events with persist it is guaranteed that the // persistent actor will not receive further commands between the // persist call and the execution(s) of the associated event // handler. This also holds for multiple persist calls in context // of a single command. persistence().persist(replicatedLogEntry, new Procedure<ReplicatedLogEntry>() { @Override public void apply(ReplicatedLogEntry evt) throws Exception { int logEntrySize = replicatedLogEntry.size(); dataSize += logEntrySize; long dataSizeForCheck = dataSize; dataSizeSinceLastSnapshot += logEntrySize; long journalSize = lastIndex() + 1; if(!hasFollowers()) { // When we do not have followers we do not maintain an in-memory log // due to this the journalSize will never become anything close to the // snapshot batch count. In fact will mostly be 1. // Similarly since the journal's dataSize depends on the entries in the // journal the journal's dataSize will never reach a value close to the // memory threshold. // By maintaining the dataSize outside the journal we are tracking essentially // what we have written to the disk however since we no longer are in // need of doing a snapshot just for the sake of freeing up memory we adjust // the real size of data by the DATA_SIZE_DIVIDER so that we do not snapshot as often // as if we were maintaining a real snapshot dataSizeForCheck = dataSizeSinceLastSnapshot / DATA_SIZE_DIVIDER; } long dataThreshold = Runtime.getRuntime().totalMemory() * getRaftActorContext().getConfigParams().getSnapshotDataThresholdPercentage() / 100; // when a snaphsot is being taken, captureSnapshot != null if (!context.isSnapshotCaptureInitiated() && ( journalSize % context.getConfigParams().getSnapshotBatchCount() == 0 || dataSizeForCheck > dataThreshold)) { dataSizeSinceLastSnapshot = 0; LOG.info("{}: Initiating Snapshot Capture, journalSize = {}, dataSizeForCheck = {}," + " dataThreshold = {}", persistenceId(), journalSize, dataSizeForCheck, dataThreshold); long lastAppliedIndex = -1; long lastAppliedTerm = -1; ReplicatedLogEntry lastAppliedEntry = get(context.getLastApplied()); if (!hasFollowers()) { lastAppliedIndex = replicatedLogEntry.getIndex(); lastAppliedTerm = replicatedLogEntry.getTerm(); } else if (lastAppliedEntry != null) { lastAppliedIndex = lastAppliedEntry.getIndex(); lastAppliedTerm = lastAppliedEntry.getTerm(); } if(LOG.isDebugEnabled()) { LOG.debug("{}: Snapshot Capture logSize: {}", persistenceId(), journal.size()); LOG.debug("{}: Snapshot Capture lastApplied:{} ", persistenceId(), context.getLastApplied()); LOG.debug("{}: Snapshot Capture lastAppliedIndex:{}", persistenceId(), lastAppliedIndex); LOG.debug("{}: Snapshot Capture lastAppliedTerm:{}", persistenceId(), lastAppliedTerm); } // send a CaptureSnapshot to self to make the expensive operation async. long replicatedToAllIndex = getCurrentBehavior().getReplicatedToAllIndex(); ReplicatedLogEntry replicatedToAllEntry = context.getReplicatedLog().get(replicatedToAllIndex); getSelf().tell(new CaptureSnapshot(lastIndex(), lastTerm(), lastAppliedIndex, lastAppliedTerm, (replicatedToAllEntry != null ? replicatedToAllEntry.getIndex() : -1), (replicatedToAllEntry != null ? replicatedToAllEntry.getTerm() : -1)), null); context.setSnapshotCaptureInitiated(true); } if (callback != null){ callback.apply(replicatedLogEntry); } } } ); } } static class DeleteEntries implements Serializable { private static final long serialVersionUID = 1L; private final int fromIndex; public DeleteEntries(int fromIndex) { this.fromIndex = fromIndex; } public int getFromIndex() { return fromIndex; } } private class ElectionTermImpl implements ElectionTerm { /** * Identifier of the actor whose election term information this is */ private long currentTerm = 0; private String votedFor = null; @Override public long getCurrentTerm() { return currentTerm; } @Override public String getVotedFor() { return votedFor; } @Override public void update(long currentTerm, String votedFor) { if(LOG.isDebugEnabled()) { LOG.debug("{}: Set currentTerm={}, votedFor={}", persistenceId(), currentTerm, votedFor); } this.currentTerm = currentTerm; this.votedFor = votedFor; } @Override public void updateAndPersist(long currentTerm, String votedFor){ update(currentTerm, votedFor); // FIXME : Maybe first persist then update the state persistence().persist(new UpdateElectionTerm(this.currentTerm, this.votedFor), new Procedure<UpdateElectionTerm>(){ @Override public void apply(UpdateElectionTerm param) throws Exception { } }); } } static class UpdateElectionTerm implements Serializable { private static final long serialVersionUID = 1L; private final long currentTerm; private final String votedFor; public UpdateElectionTerm(long currentTerm, String votedFor) { this.currentTerm = currentTerm; this.votedFor = votedFor; } public long getCurrentTerm() { return currentTerm; } public String getVotedFor() { return votedFor; } } protected class NonPersistentRaftDataProvider extends NonPersistentDataProvider { public NonPersistentRaftDataProvider(){ } /** * The way snapshotting works is, * <ol> * <li> RaftActor calls createSnapshot on the Shard * <li> Shard sends a CaptureSnapshotReply and RaftActor then calls saveSnapshot * <li> When saveSnapshot is invoked on the akka-persistence API it uses the SnapshotStore to save the snapshot. * The SnapshotStore sends SaveSnapshotSuccess or SaveSnapshotFailure. When the RaftActor gets SaveSnapshot * success it commits the snapshot to the in-memory journal. This commitSnapshot is mimicking what is done * in SaveSnapshotSuccess. * </ol> * @param o */ @Override public void saveSnapshot(Object o) { // Make saving Snapshot successful commitSnapshot(-1L); } } @VisibleForTesting void setCurrentBehavior(AbstractRaftActorBehavior behavior) { currentBehavior = behavior; } protected RaftActorBehavior getCurrentBehavior() { return currentBehavior; } }
Changes in RaftActor#handleCaptureSnapshotReply captureSnapshot.getReplicatedToAllIndex() is usually -1 (in fact I haven't yet been able to come with a test scenario where it isn't) and we shouldn't reset the behavior's replicatedToAllIndex history when we snapshot due to memory threshold exceeded. This prevents log trimming when a lagging follower is caught up via install snapshot. Eventually log trimming would catch up on subsequent replicates but I don't see a reason why we should reset it to -1. Also made a couple other logging changes. Change-Id: I6b9eafc84455a88c3bc1fc91608fe257c03b4093 Signed-off-by: Tom Pantelis <[email protected]>
opendaylight/md-sal/sal-akka-raft/src/main/java/org/opendaylight/controller/cluster/raft/RaftActor.java
Changes in RaftActor#handleCaptureSnapshotReply
<ide><path>pendaylight/md-sal/sal-akka-raft/src/main/java/org/opendaylight/controller/cluster/raft/RaftActor.java <ide> context.getReplicatedLog().size()); <ide> <ide> } else if (message instanceof CaptureSnapshot) { <del> LOG.info("{}: CaptureSnapshot received by actor", persistenceId()); <add> LOG.debug("{}: CaptureSnapshot received by actor: {}", persistenceId(), message); <ide> <ide> if(captureSnapshot == null) { <ide> captureSnapshot = (CaptureSnapshot)message; <ide> } <ide> <ide> private void handleCaptureSnapshotReply(byte[] snapshotBytes) { <del> LOG.info("{}: CaptureSnapshotReply received by actor: snapshot size {}", persistenceId(), snapshotBytes.length); <add> LOG.debug("{}: CaptureSnapshotReply received by actor: snapshot size {}", persistenceId(), snapshotBytes.length); <ide> <ide> // create a snapshot object from the state provided and save it <ide> // when snapshot is saved async, SaveSnapshotSuccess is raised. <ide> long dataThreshold = Runtime.getRuntime().totalMemory() * <ide> getRaftActorContext().getConfigParams().getSnapshotDataThresholdPercentage() / 100; <ide> if (context.getReplicatedLog().dataSize() > dataThreshold) { <add> <add> if(LOG.isDebugEnabled()) { <add> LOG.debug("{}: dataSize {} exceeds dataThreshold {} - doing snapshotPreCommit with index {}", <add> persistenceId(), context.getReplicatedLog().dataSize(), dataThreshold, <add> captureSnapshot.getLastAppliedIndex()); <add> } <add> <ide> // if memory is less, clear the log based on lastApplied. <ide> // this could/should only happen if one of the followers is down <ide> // as normally we keep removing from the log when its replicated to all. <ide> context.getReplicatedLog().snapshotPreCommit(captureSnapshot.getLastAppliedIndex(), <ide> captureSnapshot.getLastAppliedTerm()); <ide> <del> getCurrentBehavior().setReplicatedToAllIndex(captureSnapshot.getReplicatedToAllIndex()); <add> // Don't reset replicatedToAllIndex to -1 as this may prevent us from trimming the log after an <add> // install snapshot to a follower. <add> if(captureSnapshot.getReplicatedToAllIndex() >= 0) { <add> getCurrentBehavior().setReplicatedToAllIndex(captureSnapshot.getReplicatedToAllIndex()); <add> } <ide> } else if(captureSnapshot.getReplicatedToAllIndex() != -1){ <ide> // clear the log based on replicatedToAllIndex <ide> context.getReplicatedLog().snapshotPreCommit(captureSnapshot.getReplicatedToAllIndex(), <ide> } <ide> <ide> <del> LOG.info("{}: Removed in-memory snapshotted entries, adjusted snaphsotIndex:{} " + <del> "and term:{}", persistenceId(), captureSnapshot.getLastAppliedIndex(), <del> captureSnapshot.getLastAppliedTerm()); <add> LOG.info("{}: Removed in-memory snapshotted entries, adjusted snaphsotIndex: {} " + <add> "and term: {}", persistenceId(), replicatedLog.getSnapshotIndex(), <add> replicatedLog.getSnapshotTerm()); <ide> <ide> if (isLeader() && captureSnapshot.isInstallSnapshotInitiated()) { <ide> // this would be call straight to the leader and won't initiate in serialization
Java
bsd-2-clause
ed9249d1f30eea978044ce582e6eaf3b4063da06
0
Z-app/zmote,Z-app/zmote
package se.z_app.stb.api; import java.util.Observable; import java.util.Observer; import se.z_app.stb.STBEvent; /** * Class responsible for forwarding button presses to the RCProxyState implementation in use * * @author Leonard Jansson, Viktor von Zeipel, refractored by Rasmus Holm, Linus Back */ public class RCProxy implements Observer{ private RCProxyState state; /** * Creates and holds the singleton instance of the RC proxy * @author Rasmus Holm, Linus Back */ private static class SingletonHolder { public static final RCProxy INSTANCE = new RCProxy(); } /** * Request the singleton instance of the RC proxy * @return The instance of the RC proxy */ public static RCProxy instance(){ return SingletonHolder.INSTANCE; } /** * Private constructor that creates the singleton instance as a DefaultState and * adds it as a listener to STBListener */ private RCProxy() { state = new DefaultState(); STBListener.instance().addObserver(this); } /** * Sends the correct button enum for different states when up is pressed */ public void up() { state.up(); } /** * Sends the correct button enum for different states when down is pressed */ public void down() { state.down(); } /** * Sends the correct button enum for different states when right is pressed */ public void right() { state.right(); } /** * Sends the correct button enum for different states when left is pressed */ public void left() { state.left(); } /** * Sends the correct button enum for different states when ok is pressed */ public void ok() { state.ok(); } /** * Sends the correct button enum for different states when back is pressed */ public void back() { state.back(); } /** * Sends the correct button enum for different states when mute is pressed */ public void mute() { state.mute(); } /** * Sends the correct button enum for different states when info is pressed */ public void info() { state.info(); } /** * Sends the correct button enum for different states when menu is pressed */ public void menu() { state.menu(); } public void exit() { state.exit(); } /** * Get the current state */ public RCProxyState getState() { return state; } /** * Sets the state */ public void setState(RCProxyState state) { this.state = state; } @Override public void update(Observable observable, Object data) { /* * Code for setting different states depending on events sent from the box * should go here. */ if(data instanceof STBEvent){ } } }
src/se/z_app/stb/api/RCProxy.java
package se.z_app.stb.api; import java.util.Observable; import java.util.Observer; import se.z_app.stb.STBEvent; /** * needs a descirption here... * @author Leonard Jansson, Viktor von Zeipel, refractored by Rasmus Holm, Linus Back * TODO: Implementation. */ public class RCProxy implements Observer{ private RCProxyState state; //Singleton private static class SingletonHolder { public static final RCProxy INSTANCE = new RCProxy(); } public static RCProxy instance(){ return SingletonHolder.INSTANCE; } private RCProxy() { state = new DefaultState(); STBListener.instance().addObserver(this); } /** * Sends the correct button enum for different states when up is pressed */ public void up() { state.up(); } /** * Sends the correct button enum for different states when down is pressed */ public void down() { state.down(); } /** * Sends the correct button enum for different states when right is pressed */ public void right() { state.right(); } /** * Sends the correct button enum for different states when left is pressed */ public void left() { state.left(); } /** * Sends the correct button enum for different states when ok is pressed */ public void ok() { state.ok(); } /** * Sends the correct button enum for different states when back is pressed */ public void back() { state.back(); } /** * Sends the correct button enum for different states when mute is pressed */ public void mute() { state.mute(); } /** * Sends the correct button enum for different states when info is pressed */ public void info() { state.info(); } /** * Sends the correct button enum for different states when menu is pressed */ public void menu() { state.menu(); } public void exit() { state.exit(); } /** * Get the current state */ public RCProxyState getState() { return state; } /** * Sets the state */ public void setState(RCProxyState state) { this.state = state; } @Override public void update(Observable observable, Object data) { /* * Code for setting different states depending on events sent from the box * should go here. */ if(data instanceof STBEvent){ } } }
Added and improved javadoc comments for RCProxy
src/se/z_app/stb/api/RCProxy.java
Added and improved javadoc comments for RCProxy
<ide><path>rc/se/z_app/stb/api/RCProxy.java <ide> import se.z_app.stb.STBEvent; <ide> <ide> /** <del> * needs a descirption here... <add> * Class responsible for forwarding button presses to the RCProxyState implementation in use <add> * <ide> * @author Leonard Jansson, Viktor von Zeipel, refractored by Rasmus Holm, Linus Back <del> * TODO: Implementation. <ide> */ <ide> public class RCProxy implements Observer{ <ide> <ide> <ide> private RCProxyState state; <ide> <del> //Singleton <add> /** <add> * Creates and holds the singleton instance of the RC proxy <add> * @author Rasmus Holm, Linus Back <add> */ <ide> private static class SingletonHolder { <ide> public static final RCProxy INSTANCE = new RCProxy(); <ide> } <add> <add> /** <add> * Request the singleton instance of the RC proxy <add> * @return The instance of the RC proxy <add> */ <ide> public static RCProxy instance(){ <ide> return SingletonHolder.INSTANCE; <ide> } <ide> <add> /** <add> * Private constructor that creates the singleton instance as a DefaultState and <add> * adds it as a listener to STBListener <add> */ <ide> private RCProxy() { <ide> state = new DefaultState(); <ide> STBListener.instance().addObserver(this);
Java
apache-2.0
error: pathspec 'integration/src/main/java/uk/ac/ebi/biosamples/BigIntegration.java' did not match any file(s) known to git
f0074f4f27211bbee0333c8da6d91bb1dcdfae6b
1
EBIBioSamples/biosamples-v4,EBIBioSamples/biosamples-v4,EBIBioSamples/biosamples-v4,EBIBioSamples/biosamples-v4
package uk.ac.ebi.biosamples; import java.time.LocalDate; import java.time.LocalDateTime; import java.time.LocalTime; import java.util.ArrayList; import java.util.Collections; import java.util.List; import java.util.SortedSet; import java.util.TreeSet; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.context.annotation.Profile; import org.springframework.stereotype.Component; import uk.ac.ebi.biosamples.client.BioSamplesClient; import uk.ac.ebi.biosamples.model.Attribute; import uk.ac.ebi.biosamples.model.Relationship; import uk.ac.ebi.biosamples.model.Sample; @Component @Profile({"big"}) public class BigIntegration extends AbstractIntegration { private Logger log = LoggerFactory.getLogger(this.getClass()); //must be over 1000 private final int noSamples = 5000; public BigIntegration(BioSamplesClient client) { super(client); } @Override protected void phaseOne() { //generate a large number of samples List<Sample> samples = new ArrayList<>(); for (int i = 0; i < noSamples; i++) { Sample sample = generateSample(i, Collections.emptyList()); samples.add(sample); } //generate one sample to rule them all samples.add(generateSample(noSamples, samples)); //time how long it takes to submit them long startTime = System.nanoTime(); client.persistSamples(samples); long endTime = System.nanoTime(); double elapsedMs = (int) ((endTime-startTime)/1000000l); double msPerSample = elapsedMs/noSamples; log.info("Submitted "+noSamples+" samples in "+elapsedMs+"ms ("+msPerSample+"ms each)"); if (msPerSample > 15) { throw new RuntimeException("Took more than 15ms per sample to submit"); } } @Override protected void phaseTwo() { // time how long it takes to get the highly connected sample long startTime = System.nanoTime(); client.fetchSample("SAMbig"+noSamples); long endTime = System.nanoTime(); double elapsedMs = (int) ((endTime-startTime)/1000000l); if (elapsedMs > 1000) { throw new RuntimeException("Took more than 1000ms to fetch highly-connected sample"); } } @Override protected void phaseThree() { // TODO Auto-generated method stub } @Override protected void phaseFour() { // TODO Auto-generated method stub } @Override protected void phaseFive() { // TODO Auto-generated method stub } public Sample generateSample(int i, List<Sample> samples) { LocalDateTime update = LocalDateTime.of(LocalDate.of(2016, 5, 5), LocalTime.of(11, 36, 57, 0)); LocalDateTime release = LocalDateTime.of(LocalDate.of(2016, 4, 1), LocalTime.of(11, 36, 57, 0)); SortedSet<Attribute> attributes = new TreeSet<>(); attributes.add( Attribute.build("organism", "Homo sapiens", "http://purl.obolibrary.org/obo/NCBITaxon_9606", null)); SortedSet<Relationship> relationships = new TreeSet<>(); for (Sample other : samples) { relationships.add(Relationship.build("SAMbig"+i, "derived from", other.getAccession())); } Sample sample = Sample.build("big sample "+i, "SAMbig"+i, null, release, update, attributes, relationships, null); log.info("built "+sample.getAccession()); return sample; } }
integration/src/main/java/uk/ac/ebi/biosamples/BigIntegration.java
add big data integration test in big profile
integration/src/main/java/uk/ac/ebi/biosamples/BigIntegration.java
add big data integration test in big profile
<ide><path>ntegration/src/main/java/uk/ac/ebi/biosamples/BigIntegration.java <add>package uk.ac.ebi.biosamples; <add> <add>import java.time.LocalDate; <add>import java.time.LocalDateTime; <add>import java.time.LocalTime; <add>import java.util.ArrayList; <add>import java.util.Collections; <add>import java.util.List; <add>import java.util.SortedSet; <add>import java.util.TreeSet; <add> <add>import org.slf4j.Logger; <add>import org.slf4j.LoggerFactory; <add>import org.springframework.context.annotation.Profile; <add>import org.springframework.stereotype.Component; <add> <add>import uk.ac.ebi.biosamples.client.BioSamplesClient; <add>import uk.ac.ebi.biosamples.model.Attribute; <add>import uk.ac.ebi.biosamples.model.Relationship; <add>import uk.ac.ebi.biosamples.model.Sample; <add> <add>@Component <add>@Profile({"big"}) <add>public class BigIntegration extends AbstractIntegration { <add> <add> private Logger log = LoggerFactory.getLogger(this.getClass()); <add> <add> //must be over 1000 <add> private final int noSamples = 5000; <add> <add> <add> public BigIntegration(BioSamplesClient client) { <add> super(client); <add> } <add> <add> @Override <add> protected void phaseOne() { <add> <add> //generate a large number of samples <add> List<Sample> samples = new ArrayList<>(); <add> for (int i = 0; i < noSamples; i++) { <add> <add> Sample sample = generateSample(i, Collections.emptyList()); <add> samples.add(sample); <add> } <add> //generate one sample to rule them all <add> samples.add(generateSample(noSamples, samples)); <add> <add> //time how long it takes to submit them <add> <add> long startTime = System.nanoTime(); <add> client.persistSamples(samples); <add> long endTime = System.nanoTime(); <add> <add> double elapsedMs = (int) ((endTime-startTime)/1000000l); <add> double msPerSample = elapsedMs/noSamples; <add> log.info("Submitted "+noSamples+" samples in "+elapsedMs+"ms ("+msPerSample+"ms each)"); <add> if (msPerSample > 15) { <add> throw new RuntimeException("Took more than 15ms per sample to submit"); <add> } <add> <add> } <add> <add> @Override <add> protected void phaseTwo() { <add> // time how long it takes to get the highly connected sample <add> <add> long startTime = System.nanoTime(); <add> client.fetchSample("SAMbig"+noSamples); <add> long endTime = System.nanoTime(); <add> double elapsedMs = (int) ((endTime-startTime)/1000000l); <add> if (elapsedMs > 1000) { <add> throw new RuntimeException("Took more than 1000ms to fetch highly-connected sample"); <add> <add> } <add> <add> } <add> <add> @Override <add> protected void phaseThree() { <add> // TODO Auto-generated method stub <add> <add> } <add> <add> @Override <add> protected void phaseFour() { <add> // TODO Auto-generated method stub <add> <add> } <add> <add> @Override <add> protected void phaseFive() { <add> // TODO Auto-generated method stub <add> <add> } <add> <add> public Sample generateSample(int i, List<Sample> samples) { <add> <add> LocalDateTime update = LocalDateTime.of(LocalDate.of(2016, 5, 5), LocalTime.of(11, 36, 57, 0)); <add> LocalDateTime release = LocalDateTime.of(LocalDate.of(2016, 4, 1), LocalTime.of(11, 36, 57, 0)); <add> <add> SortedSet<Attribute> attributes = new TreeSet<>(); <add> attributes.add( <add> Attribute.build("organism", "Homo sapiens", "http://purl.obolibrary.org/obo/NCBITaxon_9606", null)); <add> <add> SortedSet<Relationship> relationships = new TreeSet<>(); <add> for (Sample other : samples) { <add> relationships.add(Relationship.build("SAMbig"+i, "derived from", other.getAccession())); <add> } <add> <add> Sample sample = Sample.build("big sample "+i, "SAMbig"+i, null, release, update, attributes, relationships, null); <add> <add> log.info("built "+sample.getAccession()); <add> return sample; <add> } <add> <add>}
Java
apache-2.0
19696708f42c60f27546dee22a10b6eb3aba038d
0
IMAGINARY/FormulaMorph
package com.moeyinc.formulamorph; import java.awt.*; import java.awt.event.*; import javax.swing.*; import javax.swing.event.*; import javax.swing.border.EmptyBorder; import java.util.EnumMap; import java.util.Hashtable; import java.util.Formatter; public class GUIController extends JPanel implements Parameter.ValueChangeListener, Parameter.ActivationStateListener { final static int maxSliderValue = 10000; //final static int sliderMajorTicks = 5; private EnumMap< Parameter, JSlider > p2s = new EnumMap< Parameter, JSlider >( Parameter.class ); public GUIController() { this.setLayout( new BoxLayout( this, BoxLayout.Y_AXIS ) ); this.setBorder( new EmptyBorder( 10, 0, 10, 0 ) ); JPanel panelForAllSliders = new JPanel(); Parameter last_param = null; for( Parameter param : Parameter.values() ) { if( last_param != null && last_param.getSurface() != param.getSurface() ) { JSeparator s = new JSeparator( JSeparator.VERTICAL ); s.setPreferredSize(new Dimension(5,200)); panelForAllSliders.add( s ); } last_param = param; final Parameter p = param; JPanel slider_panel = new JPanel(); slider_panel.setLayout( new BoxLayout( slider_panel, BoxLayout.Y_AXIS ) ); final JSlider s = new JSlider( JSlider.VERTICAL, 0, maxSliderValue, maxSliderValue / 2 ); s.addChangeListener( new ChangeListener() { public void stateChanged( ChangeEvent e ) { Main.robot().holdBack(); p.setInterpolatedValue( s.getValue() / (double) maxSliderValue ); } } ); slider_panel.add( s ); slider_panel.add( new JLabel( p.name() ) ); s.setMajorTickSpacing( maxSliderValue / 5 ); s.setMinorTickSpacing( maxSliderValue / 50 ); s.setPaintTicks(true); s.setPaintLabels( true ); p.addActivationStateListener( this ); p.addValueChangeListener( this ); p2s.put( p, s ); panelForAllSliders.add( slider_panel ); } this.add( panelForAllSliders, 0 ); JPanel lrButtonPanel = new JPanel(); lrButtonPanel.setLayout( new BoxLayout( lrButtonPanel, BoxLayout.X_AXIS ) ); String[] levels = { Gallery.Level.BASIC.name(), Gallery.Level.INTERMEDIATE.name(), Gallery.Level.ADVANCED.name() }; JComboBox levelsLeft = new JComboBox( levels ); levelsLeft.setMaximumSize( levelsLeft.getPreferredSize() ); levelsLeft.addActionListener( new ActionListener() { public void actionPerformed(ActionEvent e) { Main.robot().holdBack(); Main.gui().setLevel( Surface.F, Gallery.Level.valueOf( ( String ) ( ( JComboBox ) e.getSource() ).getSelectedItem() ) ); } } ); lrButtonPanel.add( levelsLeft ); JButton screenshotLeft = new JButton( "Screenshot Left" ); screenshotLeft.addActionListener( new ActionListener() { public void actionPerformed( ActionEvent ae ) { Main.robot().holdBack(); Main.gui().saveScreenShotLeft(); } } ); lrButtonPanel.add( screenshotLeft ); JButton reloadLeft = new JButton( "Reload Left" ); reloadLeft.addActionListener( new ActionListener() { public void actionPerformed( ActionEvent ae ) { Main.robot().holdBack(); try { Main.gui().reload( Surface.F ); } catch ( Exception e ) { System.err.println( "Unable to reload left surface." ); e.printStackTrace( System.err ); } } } ); lrButtonPanel.add( reloadLeft ); JButton prevLeft = new JButton( "Previous Left" ); prevLeft.addActionListener( new ActionListener() { public void actionPerformed( ActionEvent ae ) { Main.robot().holdBack(); Main.gui().previousSurface( Surface.F ); } } ); lrButtonPanel.add( prevLeft ); JButton nextLeft = new JButton( "Next Left" ); nextLeft.addActionListener( new ActionListener() { public void actionPerformed( ActionEvent ae ) { Main.robot().holdBack(); Main.gui().nextSurface( Surface.F ); } } ); lrButtonPanel.add( nextLeft ); lrButtonPanel.add( Box.createHorizontalGlue() ); JButton prevRight = new JButton( "Previous Right" ); prevRight.addActionListener( new ActionListener() { public void actionPerformed( ActionEvent ae ) { Main.robot().holdBack(); Main.gui().previousSurface( Surface.G ); } } ); lrButtonPanel.add( prevRight ); JButton nextRight = new JButton( "Next Right" ); nextRight.addActionListener( new ActionListener() { public void actionPerformed( ActionEvent ae ) { Main.robot().holdBack(); Main.gui().nextSurface( Surface.G ); } } ); lrButtonPanel.add( nextRight ); JButton reloadRight = new JButton( "Reload Right" ); reloadRight.addActionListener( new ActionListener() { public void actionPerformed( ActionEvent ae ) { Main.robot().holdBack(); try { Main.gui().reload( Surface.G ); } catch ( Exception e ) { System.err.println( "Unable to reload right surface." ); e.printStackTrace( System.err ); } } } ); lrButtonPanel.add( reloadRight ); JButton screenshotRight = new JButton( "Screenshot Right" ); screenshotRight.addActionListener( new ActionListener() { public void actionPerformed( ActionEvent ae ) { Main.robot().holdBack(); Main.gui().saveScreenShotRight(); } } ); lrButtonPanel.add( screenshotRight ); JComboBox levelsRight = new JComboBox( levels ); levelsRight.addActionListener( new ActionListener() { public void actionPerformed(ActionEvent e) { Main.robot().holdBack(); Main.gui().setLevel( Surface.G, Gallery.Level.valueOf( ( String ) ( ( JComboBox ) e.getSource() ).getSelectedItem() ) ); } } ); lrButtonPanel.add( levelsRight ); this.add( lrButtonPanel ); JPanel buttonPanel = new JPanel(); buttonPanel.setLayout( new BoxLayout( buttonPanel, BoxLayout.X_AXIS ) ); JButton pauseAnim = new JButton( "Pause" ); pauseAnim.addActionListener( new ActionListener() { public void actionPerformed( ActionEvent ae ) { Main.robot().holdBack(); Main.gui().pauseAnimation(); } } ); buttonPanel.add( pauseAnim ); JButton resumeAnim = new JButton( "Resume" ); resumeAnim.addActionListener( new ActionListener() { public void actionPerformed( ActionEvent ae ) { Main.robot().holdBack(); Main.gui().resumeAnimation(); } } ); buttonPanel.add( resumeAnim ); JButton fullscreenOn = new JButton( "Fullscreen ON" ); fullscreenOn.addActionListener( new ActionListener() { public void actionPerformed( ActionEvent ae ) { Main.robot().holdBack(); Main.gui().tryFullScreen(); } } ); buttonPanel.add( fullscreenOn ); JButton fullscreenOff = new JButton( "Fullscreen OFF" ); fullscreenOff.addActionListener( new ActionListener() { public void actionPerformed( ActionEvent ae ) { Main.robot().holdBack(); Main.gui().tryWindowed(); } } ); buttonPanel.add( fullscreenOff ); this.add( buttonPanel ); } public void valueChanged( final Parameter p ) { SwingUtilities.invokeLater( new Runnable() { public void run() { Hashtable< Integer, JLabel > labelTable = new Hashtable< Integer, JLabel >(); labelTable.put( new Integer( 0 ), new JLabel( String.format( "%.2f", Double.valueOf( p.getMin()))) ); labelTable.put( new Integer( maxSliderValue / 2 ), new JLabel( String.format( "%.2f", Double.valueOf((p.getMin()+p.getMax())/2))) ); labelTable.put( new Integer( maxSliderValue ), new JLabel( String.format( "%.2f", Double.valueOf( p.getMax() ) ) ) ); JSlider s = p2s.get( p ); s.setLabelTable( labelTable ); ChangeListener[] cls = s.getChangeListeners(); for( ChangeListener cl : cls ) s.removeChangeListener( cl ); s.setValue( (int) ( maxSliderValue * ( p.getValue() - p.getMin() ) / ( p.getMax() - p.getMin() ) ) ); for( ChangeListener cl : cls ) s.addChangeListener( cl ); } }); } public void stateChanged( final Parameter p ) { SwingUtilities.invokeLater( new Runnable() { public void run() { p2s.get( p ).setEnabled( p.isActive() ); } } ); } }
src/com/moeyinc/formulamorph/GUIController.java
package com.moeyinc.formulamorph; import java.awt.*; import java.awt.event.*; import javax.swing.*; import javax.swing.event.*; import javax.swing.border.EmptyBorder; import java.util.EnumMap; import java.util.Hashtable; import java.util.Formatter; public class GUIController extends JPanel implements Parameter.ValueChangeListener, Parameter.ActivationStateListener { final static int maxSliderValue = 10000; //final static int sliderMajorTicks = 5; private EnumMap< Parameter, JSlider > p2s = new EnumMap< Parameter, JSlider >( Parameter.class ); public GUIController() { this.setLayout( new BoxLayout( this, BoxLayout.Y_AXIS ) ); this.setBorder( new EmptyBorder( 10, 0, 10, 0 ) ); JPanel panelForAllSliders = new JPanel(); Parameter last_param = null; for( Parameter param : Parameter.values() ) { if( last_param != null && last_param.getSurface() != param.getSurface() ) { JSeparator s = new JSeparator( JSeparator.VERTICAL ); s.setPreferredSize(new Dimension(5,200)); panelForAllSliders.add( s ); } last_param = param; final Parameter p = param; JPanel slider_panel = new JPanel(); slider_panel.setLayout( new BoxLayout( slider_panel, BoxLayout.Y_AXIS ) ); final JSlider s = new JSlider( JSlider.VERTICAL, 0, maxSliderValue, maxSliderValue / 2 ); s.addChangeListener( new ChangeListener() { public void stateChanged( ChangeEvent e ) { Main.robot().holdBack(); p.setInterpolatedValue( s.getValue() / (double) maxSliderValue ); } } ); slider_panel.add( s ); slider_panel.add( new JLabel( p.name() ) ); s.setMajorTickSpacing( maxSliderValue / 5 ); s.setMinorTickSpacing( maxSliderValue / 50 ); s.setPaintTicks(true); s.setPaintLabels( true ); p.addActivationStateListener( this ); p.addValueChangeListener( this ); p2s.put( p, s ); panelForAllSliders.add( slider_panel ); } this.add( panelForAllSliders, 0 ); JPanel lrButtonPanel = new JPanel(); lrButtonPanel.setLayout( new BoxLayout( lrButtonPanel, BoxLayout.X_AXIS ) ); String[] levels = { Gallery.Level.BASIC.name(), Gallery.Level.INTERMEDIATE.name(), Gallery.Level.ADVANCED.name() }; JComboBox levelsLeft = new JComboBox( levels ); levelsLeft.setMaximumSize( levelsLeft.getPreferredSize() ); levelsLeft.addActionListener( new ActionListener() { public void actionPerformed(ActionEvent e) { Main.robot().holdBack(); Main.gui().setLevel( Surface.F, Gallery.Level.valueOf( ( String ) ( ( JComboBox ) e.getSource() ).getSelectedItem() ) ); } } ); lrButtonPanel.add( levelsLeft ); JButton screenshotLeft = new JButton( "Screenshot Left" ); screenshotLeft.addActionListener( new ActionListener() { public void actionPerformed( ActionEvent ae ) { Main.robot().holdBack(); Main.gui().saveScreenShotLeft(); } } ); lrButtonPanel.add( screenshotLeft ); JButton reloadLeft = new JButton( "Reload Left" ); reloadLeft.addActionListener( new ActionListener() { public void actionPerformed( ActionEvent ae ) { Main.robot().holdBack(); try { Main.gui().reload( Surface.F ); } catch ( Exception e ) { System.err.println( "Unable to reload left surface." ); e.printStackTrace( System.err ); } } } ); lrButtonPanel.add( reloadLeft ); JButton prevLeft = new JButton( "Previous Left" ); prevLeft.addActionListener( new ActionListener() { public void actionPerformed( ActionEvent ae ) { Main.robot().holdBack(); Main.gui().previousSurface( Surface.F ); } } ); lrButtonPanel.add( prevLeft ); JButton nextLeft = new JButton( "Next Left" ); nextLeft.addActionListener( new ActionListener() { public void actionPerformed( ActionEvent ae ) { Main.robot().holdBack(); Main.gui().nextSurface( Surface.F ); } } ); lrButtonPanel.add( nextLeft ); lrButtonPanel.add( Box.createHorizontalGlue() ); JButton prevRight = new JButton( "Previous Right" ); prevRight.addActionListener( new ActionListener() { public void actionPerformed( ActionEvent ae ) { Main.robot().holdBack(); Main.gui().previousSurface( Surface.G ); } } ); lrButtonPanel.add( prevRight ); JButton nextRight = new JButton( "Next Right" ); nextRight.addActionListener( new ActionListener() { public void actionPerformed( ActionEvent ae ) { Main.robot().holdBack(); Main.gui().nextSurface( Surface.G ); } } ); lrButtonPanel.add( nextRight ); JButton reloadRight = new JButton( "Reload Right" ); reloadRight.addActionListener( new ActionListener() { public void actionPerformed( ActionEvent ae ) { Main.robot().holdBack(); try { Main.gui().reload( Surface.G ); } catch ( Exception e ) { System.err.println( "Unable to reload right surface." ); e.printStackTrace( System.err ); } } } ); lrButtonPanel.add( reloadRight ); JButton screenshotRight = new JButton( "Screenshot Right" ); screenshotRight.addActionListener( new ActionListener() { public void actionPerformed( ActionEvent ae ) { Main.robot().holdBack(); Main.gui().saveScreenShotRight(); } } ); lrButtonPanel.add( screenshotRight ); JComboBox levelsRight = new JComboBox( levels ); levelsRight.addActionListener( new ActionListener() { public void actionPerformed(ActionEvent e) { Main.robot().holdBack(); Main.gui().setLevel( Surface.G, Gallery.Level.valueOf( ( String ) ( ( JComboBox ) e.getSource() ).getSelectedItem() ) ); } } ); lrButtonPanel.add( levelsRight ); this.add( lrButtonPanel ); JPanel buttonPanel = new JPanel(); buttonPanel.setLayout( new BoxLayout( buttonPanel, BoxLayout.X_AXIS ) ); JButton pauseAnim = new JButton( "Pause" ); pauseAnim.addActionListener( new ActionListener() { public void actionPerformed( ActionEvent ae ) { Main.robot().holdBack(); Main.gui().pauseAnimation(); } } ); buttonPanel.add( pauseAnim ); JButton resumeAnim = new JButton( "Resume" ); resumeAnim.addActionListener( new ActionListener() { public void actionPerformed( ActionEvent ae ) { Main.robot().holdBack(); Main.gui().resumeAnimation(); } } ); buttonPanel.add( resumeAnim ); JButton fullscreenOn = new JButton( "Fullscreen ON" ); fullscreenOn.addActionListener( new ActionListener() { public void actionPerformed( ActionEvent ae ) { Main.robot().holdBack(); Main.gui().tryFullScreen(); } } ); buttonPanel.add( fullscreenOn ); JButton fullscreenOff = new JButton( "Fullscreen OFF" ); fullscreenOff.addActionListener( new ActionListener() { public void actionPerformed( ActionEvent ae ) { Main.robot().holdBack(); Main.gui().tryWindowed(); } } ); buttonPanel.add( fullscreenOff ); this.add( buttonPanel ); } public synchronized void valueChanged( Parameter p ) { Hashtable< Integer, JLabel > labelTable = new Hashtable< Integer, JLabel >(); labelTable.put( new Integer( 0 ), new JLabel( String.format( "%.2f", Double.valueOf( p.getMin()))) ); labelTable.put( new Integer( maxSliderValue / 2 ), new JLabel( String.format( "%.2f", Double.valueOf((p.getMin()+p.getMax())/2))) ); labelTable.put( new Integer( maxSliderValue ), new JLabel( String.format( "%.2f", Double.valueOf( p.getMax() ) ) ) ); JSlider s = p2s.get( p ); s.setLabelTable( labelTable ); ChangeListener[] cls = s.getChangeListeners(); for( ChangeListener cl : cls ) s.removeChangeListener( cl ); s.setValue( (int) ( maxSliderValue * ( p.getValue() - p.getMin() ) / ( p.getMax() - p.getMin() ) ) ); for( ChangeListener cl : cls ) s.addChangeListener( cl ); } public synchronized void stateChanged( Parameter p ) { p2s.get( p ).setEnabled( p.isActive() ); } }
fixed deadlock related to robot and GUI controller
src/com/moeyinc/formulamorph/GUIController.java
fixed deadlock related to robot and GUI controller
<ide><path>rc/com/moeyinc/formulamorph/GUIController.java <ide> this.add( buttonPanel ); <ide> } <ide> <del> public synchronized void valueChanged( Parameter p ) <add> public void valueChanged( final Parameter p ) <ide> { <del> Hashtable< Integer, JLabel > labelTable = new Hashtable< Integer, JLabel >(); <del> labelTable.put( new Integer( 0 ), new JLabel( String.format( "%.2f", Double.valueOf( p.getMin()))) ); <del> labelTable.put( new Integer( maxSliderValue / 2 ), new JLabel( String.format( "%.2f", Double.valueOf((p.getMin()+p.getMax())/2))) ); <del> labelTable.put( new Integer( maxSliderValue ), new JLabel( String.format( "%.2f", Double.valueOf( p.getMax() ) ) ) ); <del> JSlider s = p2s.get( p ); <del> s.setLabelTable( labelTable ); <del> ChangeListener[] cls = s.getChangeListeners(); <del> for( ChangeListener cl : cls ) <del> s.removeChangeListener( cl ); <del> s.setValue( (int) ( maxSliderValue * ( p.getValue() - p.getMin() ) / ( p.getMax() - p.getMin() ) ) ); <del> for( ChangeListener cl : cls ) <del> s.addChangeListener( cl ); <add> SwingUtilities.invokeLater( new Runnable() <add> { <add> public void run() <add> { <add> Hashtable< Integer, JLabel > labelTable = new Hashtable< Integer, JLabel >(); <add> labelTable.put( new Integer( 0 ), new JLabel( String.format( "%.2f", Double.valueOf( p.getMin()))) ); <add> labelTable.put( new Integer( maxSliderValue / 2 ), new JLabel( String.format( "%.2f", Double.valueOf((p.getMin()+p.getMax())/2))) ); <add> labelTable.put( new Integer( maxSliderValue ), new JLabel( String.format( "%.2f", Double.valueOf( p.getMax() ) ) ) ); <add> JSlider s = p2s.get( p ); <add> s.setLabelTable( labelTable ); <add> ChangeListener[] cls = s.getChangeListeners(); <add> for( ChangeListener cl : cls ) <add> s.removeChangeListener( cl ); <add> s.setValue( (int) ( maxSliderValue * ( p.getValue() - p.getMin() ) / ( p.getMax() - p.getMin() ) ) ); <add> for( ChangeListener cl : cls ) <add> s.addChangeListener( cl ); <add> } <add> }); <ide> } <ide> <del> public synchronized void stateChanged( Parameter p ) <add> public void stateChanged( final Parameter p ) <ide> { <del> p2s.get( p ).setEnabled( p.isActive() ); <add> SwingUtilities.invokeLater( new Runnable() { public void run() { p2s.get( p ).setEnabled( p.isActive() ); } } ); <ide> } <ide> }
JavaScript
mit
360d68ee41d4dda39470bd042628650ff0db271d
0
KonradRolof/jacc
/* * jQuery jacc * Version 1 * Copyright (c) 2014 Konrad Rolof (http://www.konrad-rolof.de) * requires jQuery * build under jQuery 1.10.1 * Dual licensed under the MIT (below) * and GPL (http://www.gnu.org/licenses/gpl.txt) licenses. * MIT License Copyright (c) 2014 Konrad Rolof Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. * */ (function ($){ $.fn.jacc = function (options) { // compares user settings and default settings var ops = $.extend({}, $.fn.jacc.defaults, options); // add this object to ops array ops.elm = $(this); // start closing all togglerBoxes and may open one $.fn.jacc.startup(ops); // toggler click funktion ops.elm .children(ops.toggler) .click(function (e) { // prevent page switch if toggler is an anch e.preventDefault(); // set vars ops._this = $(this); ops.startOption = false; // starts function for closing and opening togglerBoxes $.fn.jacc.fxClose(ops); $.fn.jacc.fxOpen(ops); }); return this; }; // open selectet togglerBox an add current-classes $.fn.jacc.fxOpen = function (ops) { if( ops._this.next(ops.togglerBox).is(":hidden") === true ) { // add current class to toggler ops._this .addClass('current'); // add current class to toggler an opens it ops._this .next(ops.togglerBox) .stop() .addClass('current') .slideDown( { duration: ops.fxSpeed, easing: ops.easingIn, complete: function() { // callback option if( typeof (ops.slideComplete) == 'function' ) { ops.slideComplete(); } // document slide to current toggler if( ops.focusSlide === true && ops.startOption === false ) { $('html, body').animate({ scrollTop: ops._this .offset() .top + ops.focusOffset },ops.focusFxSpeed); } } }); } } // close togglerBoxes and remove current-classes $.fn.jacc.fxClose = function (ops) { // function parallel to slideUp if( typeof (ops.onSlideUp) == 'function' ) { ops.onSlideUp(); } // remove current class from toggler ops.elm .children(ops.toggler) .removeClass('current'); // remove current class of togglerBox and close them ops.elm .children(ops.togglerBox) .removeClass('current') .slideUp(ops.fxSpeed,ops.easingOut); }; // close all togglerBoxes on start $.fn.jacc.startup = function (ops) { // close all togglerBoxes ops.elm .children(ops.togglerBox) .hide(); ops._hash = window.location.hash; // opens first togglerBox or togglerBox of hash target // hash target = toggler if( ops._hash.match(/^#topic:/) ) { ops._hash = ops._hash.replace(/#topic:/,''); if( ops._hash !== '' ) { ops._this = ops.elm.children('#'+ops._hash); ops.startOption = false; $.fn.jacc.fxOpen(ops); } } // hash target = inside of togglerBox else if( ops.elm.find(ops._hash).length !== 0 ) { ops._this = $(ops._hash).closest(ops.togglerBox).prev(ops.toggler); ops.startOption = false; $.fn.jacc.fxOpen(ops); } // no hash target or outside of accordion and first open else if( ops.openFirst === true ) { ops._this = ops.elm.children(ops.toggler).eq(0); ops.startOption = true; $.fn.jacc.fxOpen(ops); } }; // default options $.fn.jacc.defaults = { toggler : '.toggler', // css class of toggler togglerBox : '.togglerBox', // css class of toggle container openFirst : false, // opens first togglerBox on start fxSpeed : 500, // speed of slideUp/Down animation easingIn : '', // jQuery easing for slideDown easingOut : '', // jQuery easing for slideUp focusSlide : false, // scroll document to current toggler focusOffset : -10, // move target point to scroll document focusFxSpeed : 500 // speed of scroll animation }; }(jQuery));
js/jacc.js
/* * jQuery jacc * Version 1 * Copyright (c) 2014 Konrad Rolof (http://www.konrad-rolof.de) * requires jQuery * build under jQuery 1.10.1 * Dual licensed under the MIT (below) * and GPL (http://www.gnu.org/licenses/gpl.txt) licenses. * MIT License Copyright (c) 2014 Konrad Rolof Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. * */ (function($){ $.fn.jacc = function(options) { // compares user settings and default settings var ops = $.extend({}, $.fn.jacc.defaults, options); // add this object to ops array ops.elm = $(this); // start closing all togglerBoxes and may open one $.fn.jacc.startup(ops); // toggler click funktion ops.elm .children(ops.toggler) .click(function(e){ // prevent page switch if toggler is an anch e.preventDefault(); // set vars ops._this = $(this); ops.startOption = false; // starts function for closing and opening togglerBoxes $.fn.jacc.fxClose(ops); $.fn.jacc.fxOpen(ops); }); return this; }; // open selectet togglerBox an add current-classes $.fn.jacc.fxOpen = function(ops) { if( ops._this.next(ops.togglerBox).is(":hidden") === true ) { // add current class to toggler ops._this .addClass('current'); // add current class to toggler an opens it ops._this .next(ops.togglerBox) .stop() .addClass('current') .slideDown( { duration: ops.fxSpeed, easing: ops.easingIn, complete: function() { // callback option if( typeof (ops.slideComplete) == 'function' ) { ops.slideComplete(); } // document slide to current toggler if( ops.focusSlide === true && ops.startOption === false ) { $('html, body').animate({ scrollTop: ops._this .offset() .top + ops.focusOffset },ops.focusFxSpeed); } } }); } } // close togglerBoxes and remove current-classes $.fn.jacc.fxClose = function(ops) { // function parallel to slideUp if( typeof (ops.onSlideUp) == 'function' ) { ops.onSlideUp(); } // remove current class from toggler ops.elm .children(ops.toggler) .removeClass('current'); // remove current class of togglerBox and close them ops.elm .children(ops.togglerBox) .removeClass('current') .slideUp(ops.fxSpeed,ops.easingOut); }; // close all togglerBoxes on start $.fn.jacc.startup = function(ops) { // close all togglerBoxes ops.elm .children(ops.togglerBox) .hide(); ops._hash = window.location.hash; console.log(ops._hash); // opens first togglerBox or togglerBox of hash target // hash target = toggler if( ops._hash.match(/^#topic:/) ) { ops._hash = ops._hash.replace(/#topic:/,''); if( ops._hash !== '' ) { ops._this = ops.elm.children('#'+ops._hash); ops.startOption = false; $.fn.jacc.fxOpen(ops); } } // hash target = inside of togglerBox else if( ops.elm.find(ops._hash).length !== 0 ) { ops._this = $(ops._hash).closest(ops.togglerBox).prev(ops.toggler); ops.startOption = false; $.fn.jacc.fxOpen(ops); } // no hash target or outside of accordion and first open else if( ops.openFirst === true ) { ops._this = ops.elm.children(ops.toggler).eq(0); ops.startOption = true; $.fn.jacc.fxOpen(ops); } }; // default options $.fn.jacc.defaults = { toggler : '.toggler', // css class of toggler togglerBox : '.togglerBox', // css class of toggle container openFirst : false, // opens first togglerBox on start fxSpeed : 500, // speed of slideUp/Down animation easingIn : '', // jQuery easing for slideDown easingOut : '', // jQuery easing for slideUp focusSlide : false, // scroll document to current toggler focusOffset : -10, // move target point to scroll document focusFxSpeed : 500 // speed of scroll animation }; }(jQuery));
formating code of jacc.js
js/jacc.js
formating code of jacc.js
<ide><path>s/jacc.js <ide> <ide> * <ide> */ <del>(function($){ <del> $.fn.jacc = function(options) <add>(function ($){ <add> $.fn.jacc = function (options) <ide> { <ide> // compares user settings and default settings <ide> var ops = $.extend({}, $.fn.jacc.defaults, options); <ide> // toggler click funktion <ide> ops.elm <ide> .children(ops.toggler) <del> .click(function(e){ <add> .click(function (e) <add> { <ide> // prevent page switch if toggler is an anch <ide> e.preventDefault(); <ide> // set vars <ide> return this; <ide> }; <ide> // open selectet togglerBox an add current-classes <del> $.fn.jacc.fxOpen = function(ops) <add> $.fn.jacc.fxOpen = function (ops) <ide> { <ide> if( ops._this.next(ops.togglerBox).is(":hidden") === true ) <ide> { <ide> } <ide> } <ide> // close togglerBoxes and remove current-classes <del> $.fn.jacc.fxClose = function(ops) <add> $.fn.jacc.fxClose = function (ops) <ide> { <ide> // function parallel to slideUp <ide> if( typeof (ops.onSlideUp) == 'function' ) <ide> .slideUp(ops.fxSpeed,ops.easingOut); <ide> }; <ide> // close all togglerBoxes on start <del> $.fn.jacc.startup = function(ops) <add> $.fn.jacc.startup = function (ops) <ide> { <ide> // close all togglerBoxes <ide> ops.elm <ide> .children(ops.togglerBox) <ide> .hide(); <del> <ide> ops._hash = window.location.hash; <del> console.log(ops._hash); <ide> <ide> // opens first togglerBox or togglerBox of hash target <ide> // hash target = toggler <ide> // default options <ide> $.fn.jacc.defaults = <ide> { <del> toggler : '.toggler', // css class of toggler <del> togglerBox : '.togglerBox', // css class of toggle container <del> openFirst : false, // opens first togglerBox on start <del> fxSpeed : 500, // speed of slideUp/Down animation <del> easingIn : '', // jQuery easing for slideDown <del> easingOut : '', // jQuery easing for slideUp <del> focusSlide : false, // scroll document to current toggler <del> focusOffset : -10, // move target point to scroll document <del> focusFxSpeed : 500 // speed of scroll animation <add> toggler : '.toggler', // css class of toggler <add> togglerBox : '.togglerBox', // css class of toggle container <add> openFirst : false, // opens first togglerBox on start <add> fxSpeed : 500, // speed of slideUp/Down animation <add> easingIn : '', // jQuery easing for slideDown <add> easingOut : '', // jQuery easing for slideUp <add> focusSlide : false, // scroll document to current toggler <add> focusOffset : -10, // move target point to scroll document <add> focusFxSpeed : 500 // speed of scroll animation <ide> }; <ide> }(jQuery));
Java
apache-2.0
error: pathspec 'src/com/github/suiteconfig/junit/filter/CompositeFilter.java' did not match any file(s) known to git
4ede0ed4dbf23205a9e2ad30975ff7abb38b57f8
1
mairbek/junit-suite-configurator
package com.github.suiteconfig.junit.filter; import com.google.common.collect.ImmutableSet; import org.junit.runner.Description; import org.junit.runner.manipulation.Filter; /** * Groups JUnit filters. * * @author Mairbek Khadikov */ public class CompositeFilter extends Filter { private final ImmutableSet<Filter> filters; public CompositeFilter(Iterable<Filter> filters) { this.filters = ImmutableSet.copyOf(filters); } @Override public boolean shouldRun(Description description) { for (Filter filter : filters) { if (!filter.shouldRun(description)) { return false; } } return true; } @Override public String describe() { return "CompositeFilter. Filters: " + filters; } }
src/com/github/suiteconfig/junit/filter/CompositeFilter.java
Composite filter introduced.
src/com/github/suiteconfig/junit/filter/CompositeFilter.java
Composite filter introduced.
<ide><path>rc/com/github/suiteconfig/junit/filter/CompositeFilter.java <add>package com.github.suiteconfig.junit.filter; <add> <add>import com.google.common.collect.ImmutableSet; <add>import org.junit.runner.Description; <add>import org.junit.runner.manipulation.Filter; <add> <add>/** <add> * Groups JUnit filters. <add> * <add> * @author Mairbek Khadikov <add> */ <add>public class CompositeFilter extends Filter { <add> private final ImmutableSet<Filter> filters; <add> <add> public CompositeFilter(Iterable<Filter> filters) { <add> this.filters = ImmutableSet.copyOf(filters); <add> } <add> <add> <add> @Override <add> public boolean shouldRun(Description description) { <add> for (Filter filter : filters) { <add> if (!filter.shouldRun(description)) { <add> return false; <add> } <add> } <add> return true; <add> } <add> <add> @Override <add> public String describe() { <add> return "CompositeFilter. Filters: " + filters; <add> } <add> <add>}
Java
mit
6d5072b7fc04757619c4842b01ef147df96487a4
0
grimes2/jabref,tobiasdiez/jabref,Mr-DLib/jabref,Mr-DLib/jabref,bartsch-dev/jabref,JabRef/jabref,bartsch-dev/jabref,zellerdev/jabref,Braunch/jabref,sauliusg/jabref,zellerdev/jabref,Braunch/jabref,Siedlerchr/jabref,tobiasdiez/jabref,tschechlovdev/jabref,ayanai1/jabref,sauliusg/jabref,sauliusg/jabref,motokito/jabref,Mr-DLib/jabref,shitikanth/jabref,ayanai1/jabref,tschechlovdev/jabref,mairdl/jabref,mredaelli/jabref,JabRef/jabref,obraliar/jabref,Braunch/jabref,mairdl/jabref,jhshinn/jabref,oscargus/jabref,jhshinn/jabref,Mr-DLib/jabref,grimes2/jabref,jhshinn/jabref,ayanai1/jabref,oscargus/jabref,bartsch-dev/jabref,tobiasdiez/jabref,JabRef/jabref,mredaelli/jabref,motokito/jabref,sauliusg/jabref,mairdl/jabref,jhshinn/jabref,oscargus/jabref,motokito/jabref,obraliar/jabref,ayanai1/jabref,oscargus/jabref,zellerdev/jabref,mairdl/jabref,grimes2/jabref,Siedlerchr/jabref,bartsch-dev/jabref,Braunch/jabref,tschechlovdev/jabref,obraliar/jabref,Siedlerchr/jabref,tschechlovdev/jabref,zellerdev/jabref,shitikanth/jabref,tschechlovdev/jabref,Braunch/jabref,tobiasdiez/jabref,motokito/jabref,jhshinn/jabref,shitikanth/jabref,bartsch-dev/jabref,JabRef/jabref,zellerdev/jabref,ayanai1/jabref,mairdl/jabref,shitikanth/jabref,obraliar/jabref,Siedlerchr/jabref,mredaelli/jabref,shitikanth/jabref,grimes2/jabref,mredaelli/jabref,motokito/jabref,oscargus/jabref,mredaelli/jabref,Mr-DLib/jabref,grimes2/jabref,obraliar/jabref
package net.sf.jabref.imports; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStream; import java.io.Reader; import java.io.UnsupportedEncodingException; import java.net.HttpURLConnection; import java.net.URL; import java.net.URLEncoder; import java.util.Date; import javax.swing.JOptionPane; import javax.swing.JPanel; import javax.xml.parsers.ParserConfigurationException; import javax.xml.parsers.SAXParser; import javax.xml.parsers.SAXParserFactory; import net.sf.jabref.BibtexEntry; import net.sf.jabref.BibtexEntryType; import net.sf.jabref.GUIGlobals; import net.sf.jabref.Globals; import net.sf.jabref.JabRefFrame; import net.sf.jabref.Util; import net.sf.jabref.gui.ImportInspectionDialog; import org.xml.sax.SAXException; import org.xml.sax.helpers.DefaultHandler; /** * * This class can be used to access any archive offering an OAI2 interface. By * default it will access ArXiv.org * * @author Ulrich St&auml;rk * @author Christian Kopf * * @version $Revision$ ($Date$) * */ public class OAI2Fetcher implements EntryFetcher, Runnable { public static final String OAI2_ARXIV_PREFIXIDENTIFIER = "oai%3AarXiv.org%3A"; public static final String OAI2_ARXIV_HOST = "arxiv.org"; public static final String OAI2_ARXIV_SCRIPT = "oai2"; public static final String OAI2_ARXIV_METADATAPREFIX = "arXiv"; public static final String OAI2_ARXIV_ARCHIVENAME = "ArXiv.org"; public static final String OAI2_IDENTIFIER_FIELD = "oai2identifier"; private SAXParserFactory parserFactory; private SAXParser saxParser; private String oai2Host; private String oai2Script; private String oai2MetaDataPrefix; private String oai2PrefixIdentifier; private String oai2ArchiveName; private boolean shouldContinue = true; private String query; private ImportInspectionDialog dialog; private JabRefFrame frame; /* some archives - like arxive.org - might expect of you to wait some time */ private boolean shouldWait() { return waitTime > 0; } private long waitTime = -1; private Date lastCall; /** * * * @param oai2Host * the host to query without leading http:// and without trailing / * @param oai2Script * the relative location of the oai2 interface without leading * and trailing / * @param oai2Metadataprefix * the urlencoded metadataprefix * @param oai2Prefixidentifier * the urlencoded prefix identifier * @param waitTimeMs * Time to wait in milliseconds between query-requests. */ public OAI2Fetcher(String oai2Host, String oai2Script, String oai2Metadataprefix, String oai2Prefixidentifier, String oai2ArchiveName, long waitTimeMs) { this.oai2Host = oai2Host; this.oai2Script = oai2Script; this.oai2MetaDataPrefix = oai2Metadataprefix; this.oai2PrefixIdentifier = oai2Prefixidentifier; this.oai2ArchiveName = oai2ArchiveName; this.waitTime = waitTimeMs; try { parserFactory = SAXParserFactory.newInstance(); saxParser = parserFactory.newSAXParser(); } catch (ParserConfigurationException e) { e.printStackTrace(); } catch (SAXException e) { e.printStackTrace(); } } /** * Default Constructor. The archive queried will be ArXiv.org * */ public OAI2Fetcher() { this(OAI2_ARXIV_HOST, OAI2_ARXIV_SCRIPT, OAI2_ARXIV_METADATAPREFIX, OAI2_ARXIV_PREFIXIDENTIFIER, OAI2_ARXIV_ARCHIVENAME, 20000L); } /** * Construct the query URL * * @param key * The key of the OAI2 entry that the url should poitn to. * * @return a String denoting the query URL */ public String constructUrl(String key) { String identifier = ""; try { identifier = URLEncoder.encode((String) key, "UTF-8"); } catch (UnsupportedEncodingException e) { return ""; } StringBuffer sb = new StringBuffer("http://").append(oai2Host).append("/"); sb.append(oai2Script).append("?"); sb.append("verb=GetRecord"); sb.append("&identifier="); sb.append(oai2PrefixIdentifier); sb.append(identifier); sb.append("&metadataPrefix=").append(oai2MetaDataPrefix); return sb.toString(); } /** * Strip subccategories from ArXiv key. * * @param key The key to fix. * @return Fixed key. */ public static String fixKey(String key){ int dot = key.indexOf('.'); int slash = key.indexOf('/'); if (dot > -1 && dot < slash) key = key.substring(0, dot) + key.substring(slash, key.length()); return key; } public static String correctLineBreaks(String s){ s = s.replaceAll("\\n(?!\\s*\\n)", " "); s = s.replaceAll("\\s*\\n\\s*", "\n"); return s.replaceAll(" {2,}", " ").replaceAll("(^\\s*|\\s+$)", ""); } /** * Import an entry from an OAI2 archive. The BibtexEntry provided has to * have the field OAI2_IDENTIFIER_FIELD set to the search string. * * @param key * The OAI2 key to fetch from ArXiv. * @return The imnported BibtexEntry or null if none. */ public BibtexEntry importOai2Entry(String key) { /** * Fix for problem reported in mailing-list: * https://sourceforge.net/forum/message.php?msg_id=4087158 */ key = fixKey(key); String url = constructUrl(key); try { URL oai2Url = new URL(url); HttpURLConnection oai2Connection = (HttpURLConnection) oai2Url.openConnection(); oai2Connection.setRequestProperty("User-Agent", "Jabref"); InputStream inputStream = oai2Connection.getInputStream(); /* create an empty BibtexEntry and set the oai2identifier field */ BibtexEntry be = new BibtexEntry(Util.createNeutralId(), BibtexEntryType.ARTICLE); be.setField(OAI2_IDENTIFIER_FIELD, key); DefaultHandler handlerBase = new OAI2Handler(be); /* parse the result */ saxParser.parse(inputStream, handlerBase); /* Correct line breaks and spacing */ Object[] fields = be.getAllFields(); for (int i = 0; i < fields.length; i++){ String name = fields[i].toString(); be.setField(name, correctLineBreaks(be.getField(name).toString())); } return be; } catch (IOException e) { JOptionPane.showMessageDialog(frame, Globals.lang( "An Exception ocurred while accessing '%0'", url) + "\n\n" + e.toString(), Globals.lang(getKeyName()), JOptionPane.ERROR_MESSAGE); } catch (SAXException e) { JOptionPane.showMessageDialog(frame, Globals.lang( "An SAXException ocurred while parsing '%0':", new String[]{url}) + "\n\n" + e.getMessage(), Globals.lang(getKeyName()), JOptionPane.ERROR_MESSAGE); } catch (RuntimeException e){ JOptionPane.showMessageDialog(frame, Globals.lang( "An Error occurred while fetching from OAI2 source (%0):", new String[]{url}) + "\n\n" + e.getMessage(), Globals.lang(getKeyName()), JOptionPane.ERROR_MESSAGE); } return null; } public String getHelpPage() { // there is no helppage return null; } public URL getIcon() { return GUIGlobals.getIconUrl("www"); } public String getKeyName() { return "Fetch " + oai2ArchiveName; } public JPanel getOptionsPanel() { // we have no additional options return null; } public String getTitle() { return Globals.menuTitle(getKeyName()); } public void processQuery(String query, ImportInspectionDialog dialog, JabRefFrame frame) { this.query = query; this.dialog = dialog; this.frame = frame; (new Thread(this)).start(); } public void cancelled() { shouldContinue = false; } public void done(int entriesImported) { // do nothing } public void stopFetching() { shouldContinue = false; } public void run() { try { dialog.setVisible(true); shouldContinue = true; /* multiple keys can be delimited by ; or space */ query = query.replaceAll(" ", ";"); String[] keys = query.split(";"); for (int i = 0; i < keys.length; i++) { String key = keys[i]; /* * some archives - like arxive.org - might expect of you to wait * some time */ if (shouldWait() && lastCall != null) { long elapsed = new Date().getTime() - lastCall.getTime(); while (elapsed < waitTime) { frame.output(Globals.lang("Waiting for ArXiv...") + ((waitTime - elapsed) / 1000) + " s"); Thread.sleep(1000); elapsed = new Date().getTime() - lastCall.getTime(); } } frame.output(Globals.lang("Processing ") + key); /* the cancel button has been hit */ if (!shouldContinue) break; /* query the archive and load the results into the BibtexEntry */ BibtexEntry be = importOai2Entry(key); if (shouldWait()) lastCall = new Date(); /* add the entry to the inspection dialog */ if (be != null) dialog.addEntry(be); /* update the dialogs progress bar */ dialog.setProgress(i + 1, keys.length); } /* inform the inspection dialog, that we're done */ dialog.entryListComplete(); frame.output(""); } catch (Exception e) { frame.output(Globals.lang("Error while fetching from OIA2: ") + e.getMessage()); e.printStackTrace(); } } }
src/java/net/sf/jabref/imports/OAI2Fetcher.java
package net.sf.jabref.imports; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStream; import java.io.Reader; import java.io.UnsupportedEncodingException; import java.net.HttpURLConnection; import java.net.URL; import java.net.URLEncoder; import java.util.Date; import javax.swing.JOptionPane; import javax.swing.JPanel; import javax.xml.parsers.ParserConfigurationException; import javax.xml.parsers.SAXParser; import javax.xml.parsers.SAXParserFactory; import net.sf.jabref.BibtexEntry; import net.sf.jabref.BibtexEntryType; import net.sf.jabref.GUIGlobals; import net.sf.jabref.Globals; import net.sf.jabref.JabRefFrame; import net.sf.jabref.Util; import net.sf.jabref.gui.ImportInspectionDialog; import org.xml.sax.SAXException; import org.xml.sax.helpers.DefaultHandler; /** * * This class can be used to access any archive offering an OAI2 interface. By * default it will access ArXiv.org * * @author Ulrich St&auml;rk * @author Christian Kopf * * @version $Revision$ ($Date$) * */ public class OAI2Fetcher implements EntryFetcher, Runnable { public static final String OAI2_ARXIV_PREFIXIDENTIFIER = "oai%3AarXiv.org%3A"; public static final String OAI2_ARXIV_HOST = "arxiv.org"; public static final String OAI2_ARXIV_SCRIPT = "oai2"; public static final String OAI2_ARXIV_METADATAPREFIX = "arXiv"; public static final String OAI2_ARXIV_ARCHIVENAME = "ArXiv.org"; public static final String OAI2_IDENTIFIER_FIELD = "oai2identifier"; private SAXParserFactory parserFactory; private SAXParser saxParser; private String oai2Host; private String oai2Script; private String oai2MetaDataPrefix; private String oai2PrefixIdentifier; private String oai2ArchiveName; private boolean shouldContinue = true; private String query; private ImportInspectionDialog dialog; private JabRefFrame frame; /* some archives - like arxive.org - might expect of you to wait some time */ private boolean shouldWait() { return waitTime > 0; } private long waitTime = -1; private Date lastCall; /** * * * @param oai2Host * the host to query without leading http:// and without trailing / * @param oai2Script * the relative location of the oai2 interface without leading * and trailing / * @param oai2Metadataprefix * the urlencoded metadataprefix * @param oai2Prefixidentifier * the urlencoded prefix identifier * @param waitTimeMs * Time to wait in milliseconds between query-requests. */ public OAI2Fetcher(String oai2Host, String oai2Script, String oai2Metadataprefix, String oai2Prefixidentifier, String oai2ArchiveName, long waitTimeMs) { this.oai2Host = oai2Host; this.oai2Script = oai2Script; this.oai2MetaDataPrefix = oai2Metadataprefix; this.oai2PrefixIdentifier = oai2Prefixidentifier; this.oai2ArchiveName = oai2ArchiveName; this.waitTime = waitTimeMs; try { parserFactory = SAXParserFactory.newInstance(); saxParser = parserFactory.newSAXParser(); } catch (ParserConfigurationException e) { e.printStackTrace(); } catch (SAXException e) { e.printStackTrace(); } } /** * Default Constructor. The archive queried will be ArXiv.org * */ public OAI2Fetcher() { this(OAI2_ARXIV_HOST, OAI2_ARXIV_SCRIPT, OAI2_ARXIV_METADATAPREFIX, OAI2_ARXIV_PREFIXIDENTIFIER, OAI2_ARXIV_ARCHIVENAME, 20000L); } /** * Construct the query URL * * @param key * The key of the OAI2 entry that the url should poitn to. * * @return a String denoting the query URL */ public String constructUrl(String key) { String identifier = ""; try { identifier = URLEncoder.encode((String) key, "UTF-8"); } catch (UnsupportedEncodingException e) { return ""; } StringBuffer sb = new StringBuffer("http://").append(oai2Host).append("/"); sb.append(oai2Script).append("?"); sb.append("verb=GetRecord"); sb.append("&identifier="); sb.append(oai2PrefixIdentifier); sb.append(identifier); sb.append("&metadataPrefix=").append(oai2MetaDataPrefix); return sb.toString(); } /** * Strip subccategories from ArXiv key. * * @param key The key to fix. * @return Fixed key. */ public static String fixKey(String key){ int dot = key.indexOf('.'); int slash = key.indexOf('/'); if (dot > -1 && dot < slash) key = key.substring(0, dot) + key.substring(slash, key.length()); return key; } public static String correctLineBreaks(String s){ s = s.replaceAll("\\n(?!\\s*\\n)", " "); s = s.replaceAll("\\s*\\n\\s*", "\n"); return s.replaceAll(" {2,}", " ").replaceAll("(^\\s*|\\s+$)", ""); } /** * Import an entry from an OAI2 archive. The BibtexEntry provided has to * have the field OAI2_IDENTIFIER_FIELD set to the search string. * * @param key * The OAI2 key to fetch from ArXiv. * @return The imnported BibtexEntry or null if none. */ public BibtexEntry importOai2Entry(String key) { /** * Fix for problem reported in mailing-list: * https://sourceforge.net/forum/message.php?msg_id=4087158 */ key = fixKey(key); String url = constructUrl(key); try { URL oai2Url = new URL(url); HttpURLConnection oai2Connection = (HttpURLConnection) oai2Url.openConnection(); oai2Connection.setRequestProperty("User-Agent", "Jabref"); InputStream inputStream = oai2Connection.getInputStream(); /* create an empty BibtexEntry and set the oai2identifier field */ BibtexEntry be = new BibtexEntry(Util.createNeutralId(), BibtexEntryType.ARTICLE); be.setField(OAI2_IDENTIFIER_FIELD, key); DefaultHandler handlerBase = new OAI2Handler(be); /* parse the result */ saxParser.parse(inputStream, handlerBase); /* Correct line breaks and spacing */ Object[] fields = be.getAllFields(); for (int i = 0; i < fields.length; i++){ String name = fields[i].toString(); be.setField(name, correctLineBreaks(be.getField(name).toString())); } return be; } catch (IOException e) { JOptionPane.showMessageDialog(frame, Globals.lang( "An Exception ocurred while accessing '%0'", url) + "\n\n" + e.toString(), Globals.lang(getKeyName()), JOptionPane.ERROR_MESSAGE); } catch (SAXException e) { JOptionPane.showMessageDialog(frame, Globals.lang( "An SAXException ocurred while parsing '%0':", new String[]{url}) + "\n\n" + e.getMessage(), Globals.lang(getKeyName()), JOptionPane.ERROR_MESSAGE); } catch (RuntimeException e){ JOptionPane.showMessageDialog(frame, Globals.lang( "An Error occurred while fetching from OAI2 source (%0):", new String[]{url}) + "\n\n" + e.getMessage(), Globals.lang(getKeyName()), JOptionPane.ERROR_MESSAGE); } return null; } public String getHelpPage() { // there is no helppage return null; } public URL getIcon() { return GUIGlobals.getIconUrl("www"); } public String getKeyName() { return "Fetch " + oai2ArchiveName; } public JPanel getOptionsPanel() { // we have no additional options return null; } public String getTitle() { return Globals.menuTitle(getKeyName()); } public void processQuery(String query, ImportInspectionDialog dialog, JabRefFrame frame) { this.query = query; this.dialog = dialog; this.frame = frame; (new Thread(this)).start(); } public void cancelled() { shouldContinue = false; } public void done(int entriesImported) { // do nothing } public void stopFetching() { shouldContinue = false; } public void run() { try { dialog.setVisible(true); shouldContinue = true; /* multiple keys can be delimited by ; or space */ query = query.replaceAll(" ", ";"); String[] keys = query.split(";"); for (int i = 0; i < keys.length; i++) { String key = keys[i]; /* * some archives - like arxive.org - might expect of you to wait * some time */ if (shouldWait() && lastCall != null) { long elapsed = new Date().getTime() - lastCall.getTime(); while (elapsed < waitTime) { frame.output("Waiting for ArXiv..." + ((waitTime - elapsed) / 1000) + " s"); Thread.sleep(1000); elapsed = new Date().getTime() - lastCall.getTime(); } } frame.output("Processing " + key); /* the cancel button has been hit */ if (!shouldContinue) break; /* query the archive and load the results into the BibtexEntry */ BibtexEntry be = importOai2Entry(key); if (shouldWait()) lastCall = new Date(); /* add the entry to the inspection dialog */ if (be != null) dialog.addEntry(be); /* update the dialogs progress bar */ dialog.setProgress(i + 1, keys.length); } /* inform the inspection dialog, that we're done */ dialog.entryListComplete(); frame.output(""); } catch (Exception e) { frame.output("Error while fetching from OIA2: " + e.getMessage()); e.printStackTrace(); } } }
Modified to enable string translation
src/java/net/sf/jabref/imports/OAI2Fetcher.java
Modified to enable string translation
<ide><path>rc/java/net/sf/jabref/imports/OAI2Fetcher.java <ide> */ <ide> public class OAI2Fetcher implements EntryFetcher, Runnable { <ide> <del> public static final String OAI2_ARXIV_PREFIXIDENTIFIER = "oai%3AarXiv.org%3A"; <del> <del> public static final String OAI2_ARXIV_HOST = "arxiv.org"; <del> <del> public static final String OAI2_ARXIV_SCRIPT = "oai2"; <del> <del> public static final String OAI2_ARXIV_METADATAPREFIX = "arXiv"; <del> <del> public static final String OAI2_ARXIV_ARCHIVENAME = "ArXiv.org"; <del> <del> public static final String OAI2_IDENTIFIER_FIELD = "oai2identifier"; <del> <del> private SAXParserFactory parserFactory; <del> <del> private SAXParser saxParser; <del> <del> private String oai2Host; <del> <del> private String oai2Script; <del> <del> private String oai2MetaDataPrefix; <del> <del> private String oai2PrefixIdentifier; <del> <del> private String oai2ArchiveName; <del> <del> private boolean shouldContinue = true; <del> <del> private String query; <del> <del> private ImportInspectionDialog dialog; <del> <del> private JabRefFrame frame; <del> <del> /* some archives - like arxive.org - might expect of you to wait some time */ <del> <del> private boolean shouldWait() { <del> return waitTime > 0; <del> } <del> <del> private long waitTime = -1; <del> <del> private Date lastCall; <del> <del> /** <del> * <del> * <del> * @param oai2Host <del> * the host to query without leading http:// and without trailing / <del> * @param oai2Script <del> * the relative location of the oai2 interface without leading <del> * and trailing / <del> * @param oai2Metadataprefix <del> * the urlencoded metadataprefix <del> * @param oai2Prefixidentifier <del> * the urlencoded prefix identifier <del> * @param waitTimeMs <del> * Time to wait in milliseconds between query-requests. <del> */ <del> public OAI2Fetcher(String oai2Host, String oai2Script, String oai2Metadataprefix, <del> String oai2Prefixidentifier, String oai2ArchiveName, long waitTimeMs) { <del> this.oai2Host = oai2Host; <del> this.oai2Script = oai2Script; <del> this.oai2MetaDataPrefix = oai2Metadataprefix; <del> this.oai2PrefixIdentifier = oai2Prefixidentifier; <del> this.oai2ArchiveName = oai2ArchiveName; <del> this.waitTime = waitTimeMs; <del> try { <del> parserFactory = SAXParserFactory.newInstance(); <del> saxParser = parserFactory.newSAXParser(); <del> } catch (ParserConfigurationException e) { <del> e.printStackTrace(); <del> } catch (SAXException e) { <del> e.printStackTrace(); <del> } <del> } <del> <del> /** <del> * Default Constructor. The archive queried will be ArXiv.org <del> * <del> */ <del> public OAI2Fetcher() { <del> this(OAI2_ARXIV_HOST, OAI2_ARXIV_SCRIPT, OAI2_ARXIV_METADATAPREFIX, <del> OAI2_ARXIV_PREFIXIDENTIFIER, OAI2_ARXIV_ARCHIVENAME, 20000L); <del> } <del> <del> /** <del> * Construct the query URL <del> * <del> * @param key <del> * The key of the OAI2 entry that the url should poitn to. <del> * <del> * @return a String denoting the query URL <del> */ <del> public String constructUrl(String key) { <del> String identifier = ""; <del> try { <del> identifier = URLEncoder.encode((String) key, "UTF-8"); <del> } catch (UnsupportedEncodingException e) { <del> return ""; <del> } <del> StringBuffer sb = new StringBuffer("http://").append(oai2Host).append("/"); <del> sb.append(oai2Script).append("?"); <del> sb.append("verb=GetRecord"); <del> sb.append("&identifier="); <del> sb.append(oai2PrefixIdentifier); <del> sb.append(identifier); <del> sb.append("&metadataPrefix=").append(oai2MetaDataPrefix); <del> return sb.toString(); <del> } <del> <del> /** <del> * Strip subccategories from ArXiv key. <del> * <del> * @param key The key to fix. <del> * @return Fixed key. <del> */ <del> public static String fixKey(String key){ <del> int dot = key.indexOf('.'); <del> int slash = key.indexOf('/'); <del> <del> if (dot > -1 && dot < slash) <del> key = key.substring(0, dot) + key.substring(slash, key.length()); <del> <del> return key; <del> } <del> <del> public static String correctLineBreaks(String s){ <del> s = s.replaceAll("\\n(?!\\s*\\n)", " "); <del> s = s.replaceAll("\\s*\\n\\s*", "\n"); <del> return s.replaceAll(" {2,}", " ").replaceAll("(^\\s*|\\s+$)", ""); <del> } <del> <del> /** <del> * Import an entry from an OAI2 archive. The BibtexEntry provided has to <del> * have the field OAI2_IDENTIFIER_FIELD set to the search string. <del> * <del> * @param key <del> * The OAI2 key to fetch from ArXiv. <del> * @return The imnported BibtexEntry or null if none. <del> */ <del> public BibtexEntry importOai2Entry(String key) { <del> /** <del> * Fix for problem reported in mailing-list: <del> * https://sourceforge.net/forum/message.php?msg_id=4087158 <del> */ <del> key = fixKey(key); <del> <del> String url = constructUrl(key); <del> try { <del> URL oai2Url = new URL(url); <del> HttpURLConnection oai2Connection = (HttpURLConnection) oai2Url.openConnection(); <del> oai2Connection.setRequestProperty("User-Agent", "Jabref"); <del> InputStream inputStream = oai2Connection.getInputStream(); <del> <del> /* create an empty BibtexEntry and set the oai2identifier field */ <del> BibtexEntry be = new BibtexEntry(Util.createNeutralId(), BibtexEntryType.ARTICLE); <del> be.setField(OAI2_IDENTIFIER_FIELD, key); <del> DefaultHandler handlerBase = new OAI2Handler(be); <del> /* parse the result */ <del> saxParser.parse(inputStream, handlerBase); <del> <del> /* Correct line breaks and spacing */ <del> Object[] fields = be.getAllFields(); <del> for (int i = 0; i < fields.length; i++){ <del> String name = fields[i].toString(); <del> <del> be.setField(name, correctLineBreaks(be.getField(name).toString())); <del> } <del> return be; <del> } catch (IOException e) { <del> JOptionPane.showMessageDialog(frame, Globals.lang( <del> "An Exception ocurred while accessing '%0'", url) <del> + "\n\n" + e.toString(), Globals.lang(getKeyName()), JOptionPane.ERROR_MESSAGE); <del> } catch (SAXException e) { <del> JOptionPane.showMessageDialog(frame, Globals.lang( <del> "An SAXException ocurred while parsing '%0':", new String[]{url}) <del> + "\n\n" + e.getMessage(), Globals.lang(getKeyName()), JOptionPane.ERROR_MESSAGE); <del> } catch (RuntimeException e){ <del> JOptionPane.showMessageDialog(frame, Globals.lang( <del> "An Error occurred while fetching from OAI2 source (%0):", new String[]{url}) <del> + "\n\n" + e.getMessage(), Globals.lang(getKeyName()), JOptionPane.ERROR_MESSAGE); <del> } <del> return null; <del> } <del> <del> public String getHelpPage() { <del> // there is no helppage <del> return null; <del> } <del> <del> public URL getIcon() { <del> return GUIGlobals.getIconUrl("www"); <del> } <del> <del> public String getKeyName() { <del> return "Fetch " + oai2ArchiveName; <del> } <del> <del> public JPanel getOptionsPanel() { <del> // we have no additional options <del> return null; <del> } <del> <del> public String getTitle() { <del> return Globals.menuTitle(getKeyName()); <del> } <del> <del> public void processQuery(String query, ImportInspectionDialog dialog, JabRefFrame frame) { <del> this.query = query; <del> this.dialog = dialog; <del> this.frame = frame; <del> (new Thread(this)).start(); <del> } <del> <del> public void cancelled() { <del> shouldContinue = false; <del> } <del> <del> public void done(int entriesImported) { <del> // do nothing <del> } <del> <del> public void stopFetching() { <del> shouldContinue = false; <del> } <del> <del> public void run() { <del> try { <del> dialog.setVisible(true); <del> shouldContinue = true; <del> /* multiple keys can be delimited by ; or space */ <del> query = query.replaceAll(" ", ";"); <del> String[] keys = query.split(";"); <del> for (int i = 0; i < keys.length; i++) { <del> String key = keys[i]; <del> /* <del> * some archives - like arxive.org - might expect of you to wait <del> * some time <del> */ <del> if (shouldWait() && lastCall != null) { <del> <del> long elapsed = new Date().getTime() - lastCall.getTime(); <del> <del> while (elapsed < waitTime) { <del> frame.output("Waiting for ArXiv..." + ((waitTime - elapsed) / 1000) + " s"); <del> Thread.sleep(1000); <del> elapsed = new Date().getTime() - lastCall.getTime(); <del> } <del> } <del> <del> frame.output("Processing " + key); <del> <del> /* the cancel button has been hit */ <del> if (!shouldContinue) <del> break; <del> <del> /* query the archive and load the results into the BibtexEntry */ <del> BibtexEntry be = importOai2Entry(key); <del> <del> if (shouldWait()) <del> lastCall = new Date(); <del> <del> /* add the entry to the inspection dialog */ <del> if (be != null) <del> dialog.addEntry(be); <del> <del> /* update the dialogs progress bar */ <del> dialog.setProgress(i + 1, keys.length); <del> } <del> /* inform the inspection dialog, that we're done */ <del> dialog.entryListComplete(); <del> frame.output(""); <del> } catch (Exception e) { <del> frame.output("Error while fetching from OIA2: " + e.getMessage()); <del> e.printStackTrace(); <del> } <del> } <add> public static final String OAI2_ARXIV_PREFIXIDENTIFIER = "oai%3AarXiv.org%3A"; <add> <add> public static final String OAI2_ARXIV_HOST = "arxiv.org"; <add> <add> public static final String OAI2_ARXIV_SCRIPT = "oai2"; <add> <add> public static final String OAI2_ARXIV_METADATAPREFIX = "arXiv"; <add> <add> public static final String OAI2_ARXIV_ARCHIVENAME = "ArXiv.org"; <add> <add> public static final String OAI2_IDENTIFIER_FIELD = "oai2identifier"; <add> <add> private SAXParserFactory parserFactory; <add> <add> private SAXParser saxParser; <add> <add> private String oai2Host; <add> <add> private String oai2Script; <add> <add> private String oai2MetaDataPrefix; <add> <add> private String oai2PrefixIdentifier; <add> <add> private String oai2ArchiveName; <add> <add> private boolean shouldContinue = true; <add> <add> private String query; <add> <add> private ImportInspectionDialog dialog; <add> <add> private JabRefFrame frame; <add> <add> /* some archives - like arxive.org - might expect of you to wait some time */ <add> <add> private boolean shouldWait() { <add> return waitTime > 0; <add> } <add> <add> private long waitTime = -1; <add> <add> private Date lastCall; <add> <add> /** <add> * <add> * <add> * @param oai2Host <add> * the host to query without leading http:// and without trailing / <add> * @param oai2Script <add> * the relative location of the oai2 interface without leading <add> * and trailing / <add> * @param oai2Metadataprefix <add> * the urlencoded metadataprefix <add> * @param oai2Prefixidentifier <add> * the urlencoded prefix identifier <add> * @param waitTimeMs <add> * Time to wait in milliseconds between query-requests. <add> */ <add> public OAI2Fetcher(String oai2Host, String oai2Script, String oai2Metadataprefix, <add> String oai2Prefixidentifier, String oai2ArchiveName, long waitTimeMs) { <add> this.oai2Host = oai2Host; <add> this.oai2Script = oai2Script; <add> this.oai2MetaDataPrefix = oai2Metadataprefix; <add> this.oai2PrefixIdentifier = oai2Prefixidentifier; <add> this.oai2ArchiveName = oai2ArchiveName; <add> this.waitTime = waitTimeMs; <add> try { <add> parserFactory = SAXParserFactory.newInstance(); <add> saxParser = parserFactory.newSAXParser(); <add> } catch (ParserConfigurationException e) { <add> e.printStackTrace(); <add> } catch (SAXException e) { <add> e.printStackTrace(); <add> } <add> } <add> <add> /** <add> * Default Constructor. The archive queried will be ArXiv.org <add> * <add> */ <add> public OAI2Fetcher() { <add> this(OAI2_ARXIV_HOST, OAI2_ARXIV_SCRIPT, OAI2_ARXIV_METADATAPREFIX, <add> OAI2_ARXIV_PREFIXIDENTIFIER, OAI2_ARXIV_ARCHIVENAME, 20000L); <add> } <add> <add> /** <add> * Construct the query URL <add> * <add> * @param key <add> * The key of the OAI2 entry that the url should poitn to. <add> * <add> * @return a String denoting the query URL <add> */ <add> public String constructUrl(String key) { <add> String identifier = ""; <add> try { <add> identifier = URLEncoder.encode((String) key, "UTF-8"); <add> } catch (UnsupportedEncodingException e) { <add> return ""; <add> } <add> StringBuffer sb = new StringBuffer("http://").append(oai2Host).append("/"); <add> sb.append(oai2Script).append("?"); <add> sb.append("verb=GetRecord"); <add> sb.append("&identifier="); <add> sb.append(oai2PrefixIdentifier); <add> sb.append(identifier); <add> sb.append("&metadataPrefix=").append(oai2MetaDataPrefix); <add> return sb.toString(); <add> } <add> <add> /** <add> * Strip subccategories from ArXiv key. <add> * <add> * @param key The key to fix. <add> * @return Fixed key. <add> */ <add> public static String fixKey(String key){ <add> int dot = key.indexOf('.'); <add> int slash = key.indexOf('/'); <add> <add> if (dot > -1 && dot < slash) <add> key = key.substring(0, dot) + key.substring(slash, key.length()); <add> <add> return key; <add> } <add> <add> public static String correctLineBreaks(String s){ <add> s = s.replaceAll("\\n(?!\\s*\\n)", " "); <add> s = s.replaceAll("\\s*\\n\\s*", "\n"); <add> return s.replaceAll(" {2,}", " ").replaceAll("(^\\s*|\\s+$)", ""); <add> } <add> <add> /** <add> * Import an entry from an OAI2 archive. The BibtexEntry provided has to <add> * have the field OAI2_IDENTIFIER_FIELD set to the search string. <add> * <add> * @param key <add> * The OAI2 key to fetch from ArXiv. <add> * @return The imnported BibtexEntry or null if none. <add> */ <add> public BibtexEntry importOai2Entry(String key) { <add> /** <add> * Fix for problem reported in mailing-list: <add> * https://sourceforge.net/forum/message.php?msg_id=4087158 <add> */ <add> key = fixKey(key); <add> <add> String url = constructUrl(key); <add> try { <add> URL oai2Url = new URL(url); <add> HttpURLConnection oai2Connection = (HttpURLConnection) oai2Url.openConnection(); <add> oai2Connection.setRequestProperty("User-Agent", "Jabref"); <add> InputStream inputStream = oai2Connection.getInputStream(); <add> <add> /* create an empty BibtexEntry and set the oai2identifier field */ <add> BibtexEntry be = new BibtexEntry(Util.createNeutralId(), BibtexEntryType.ARTICLE); <add> be.setField(OAI2_IDENTIFIER_FIELD, key); <add> DefaultHandler handlerBase = new OAI2Handler(be); <add> /* parse the result */ <add> saxParser.parse(inputStream, handlerBase); <add> <add> /* Correct line breaks and spacing */ <add> Object[] fields = be.getAllFields(); <add> for (int i = 0; i < fields.length; i++){ <add> String name = fields[i].toString(); <add> <add> be.setField(name, correctLineBreaks(be.getField(name).toString())); <add> } <add> return be; <add> } catch (IOException e) { <add> JOptionPane.showMessageDialog(frame, Globals.lang( <add> "An Exception ocurred while accessing '%0'", url) <add> + "\n\n" + e.toString(), Globals.lang(getKeyName()), JOptionPane.ERROR_MESSAGE); <add> } catch (SAXException e) { <add> JOptionPane.showMessageDialog(frame, Globals.lang( <add> "An SAXException ocurred while parsing '%0':", new String[]{url}) <add> + "\n\n" + e.getMessage(), Globals.lang(getKeyName()), JOptionPane.ERROR_MESSAGE); <add> } catch (RuntimeException e){ <add> JOptionPane.showMessageDialog(frame, Globals.lang( <add> "An Error occurred while fetching from OAI2 source (%0):", new String[]{url}) <add> + "\n\n" + e.getMessage(), Globals.lang(getKeyName()), JOptionPane.ERROR_MESSAGE); <add> } <add> return null; <add> } <add> <add> public String getHelpPage() { <add> // there is no helppage <add> return null; <add> } <add> <add> public URL getIcon() { <add> return GUIGlobals.getIconUrl("www"); <add> } <add> <add> public String getKeyName() { <add> return "Fetch " + oai2ArchiveName; <add> } <add> <add> public JPanel getOptionsPanel() { <add> // we have no additional options <add> return null; <add> } <add> <add> public String getTitle() { <add> return Globals.menuTitle(getKeyName()); <add> } <add> <add> public void processQuery(String query, ImportInspectionDialog dialog, JabRefFrame frame) { <add> this.query = query; <add> this.dialog = dialog; <add> this.frame = frame; <add> (new Thread(this)).start(); <add> } <add> <add> public void cancelled() { <add> shouldContinue = false; <add> } <add> <add> public void done(int entriesImported) { <add> // do nothing <add> } <add> <add> public void stopFetching() { <add> shouldContinue = false; <add> } <add> <add> public void run() { <add> try { <add> dialog.setVisible(true); <add> shouldContinue = true; <add> /* multiple keys can be delimited by ; or space */ <add> query = query.replaceAll(" ", ";"); <add> String[] keys = query.split(";"); <add> for (int i = 0; i < keys.length; i++) { <add> String key = keys[i]; <add> /* <add> * some archives - like arxive.org - might expect of you to wait <add> * some time <add> */ <add> if (shouldWait() && lastCall != null) { <add> <add> long elapsed = new Date().getTime() - lastCall.getTime(); <add> <add> while (elapsed < waitTime) { <add> frame.output(Globals.lang("Waiting for ArXiv...") + ((waitTime - elapsed) / 1000) + " s"); <add> Thread.sleep(1000); <add> elapsed = new Date().getTime() - lastCall.getTime(); <add> } <add> } <add> <add> frame.output(Globals.lang("Processing ") + key); <add> <add> /* the cancel button has been hit */ <add> if (!shouldContinue) <add> break; <add> <add> /* query the archive and load the results into the BibtexEntry */ <add> BibtexEntry be = importOai2Entry(key); <add> <add> if (shouldWait()) <add> lastCall = new Date(); <add> <add> /* add the entry to the inspection dialog */ <add> if (be != null) <add> dialog.addEntry(be); <add> <add> /* update the dialogs progress bar */ <add> dialog.setProgress(i + 1, keys.length); <add> } <add> /* inform the inspection dialog, that we're done */ <add> dialog.entryListComplete(); <add> frame.output(""); <add> } catch (Exception e) { <add> frame.output(Globals.lang("Error while fetching from OIA2: ") + e.getMessage()); <add> e.printStackTrace(); <add> } <add> } <ide> }
Java
apache-2.0
1cd579932a4b8c8f819c3e99d0f3d4786a840758
0
lakmali/product-apim,wso2/product-apim,rswijesena/product-apim,chamilaadhi/product-apim,sambaheerathan/product-apim,ChamNDeSilva/product-apim,wso2/product-apim,abimarank/product-apim,tharikaGitHub/product-apim,chamilaadhi/product-apim,chamilaadhi/product-apim,sambaheerathan/product-apim,dewmini/product-apim,dewmini/product-apim,jaadds/product-apim,ChamNDeSilva/product-apim,tharikaGitHub/product-apim,lakmali/product-apim,chamilaadhi/product-apim,dewmini/product-apim,rswijesena/product-apim,dewmini/product-apim,nu1silva/product-apim,jaadds/product-apim,nu1silva/product-apim,tharikaGitHub/product-apim,tharikaGitHub/product-apim,nu1silva/product-apim,nu1silva/product-apim,wso2/product-apim,wso2/product-apim,tharikaGitHub/product-apim,jaadds/product-apim,nu1silva/product-apim,jaadds/product-apim,wso2/product-apim,dewmini/product-apim,chamilaadhi/product-apim,abimarank/product-apim
/* * Copyright (c) 2015, WSO2 Inc. (http://www.wso2.org) All Rights Reserved. * * WSO2 Inc. 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.wso2.am.integration.tests.api.lifecycle; import org.testng.annotations.AfterClass; import org.testng.annotations.BeforeClass; import org.testng.annotations.Test; import org.wso2.am.integration.test.utils.APIManagerIntegrationTestException; import org.wso2.am.integration.test.utils.base.APIMIntegrationConstants; import org.wso2.am.integration.test.utils.bean.APICreationRequestBean; import org.wso2.am.integration.test.utils.clients.APIPublisherRestClient; import org.wso2.am.integration.test.utils.clients.APIStoreRestClient; import org.wso2.am.integration.tests.throttling.AdvancedThrottlingConfig; import org.wso2.carbon.apimgt.api.model.APIIdentifier; import org.wso2.carbon.automation.engine.annotations.ExecutionEnvironment; import org.wso2.carbon.automation.engine.annotations.SetEnvironment; import org.wso2.carbon.automation.engine.context.AutomationContext; import org.wso2.carbon.automation.engine.context.TestUserMode; import org.wso2.carbon.automation.test.utils.http.client.HttpRequestUtil; import org.wso2.carbon.automation.test.utils.http.client.HttpResponse; import org.wso2.carbon.integration.common.utils.mgt.ServerConfigurationManager; import javax.xml.xpath.XPathExpressionException; import java.io.File; import java.io.IOException; import java.net.MalformedURLException; import java.net.URL; import java.util.HashMap; import java.util.Map; import static org.testng.Assert.assertEquals; import static org.testng.Assert.assertTrue; /** * Publish a API under gold tier and test the invocation with throttling , then change the api tier to silver * and do a new silver subscription and test invocation under Silver tier. */ @SetEnvironment(executionEnvironments = {ExecutionEnvironment.STANDALONE }) public class ChangeAPITierAndTestInvokingTestCase extends APIManagerLifecycleBaseTest { private final String API_NAME = "ChangeAPITierAndTestInvokingTest"; private final String API_CONTEXT = "ChangeAPITierAndTestInvoking"; private final String API_TAGS = "testTag1, testTag2, testTag3"; private final String API_DESCRIPTION = "This is test API create by API manager integration test"; private final String API_END_POINT_METHOD = "customers/123"; private final String API_RESPONSE_DATA = "<id>123</id><name>John</name></Customer>"; private final String API_VERSION_1_0_0 = "1.0.0"; private final String APPLICATION_NAME = "ChangeAPITierAndTestInvokingTestCase"; private final String API_END_POINT_POSTFIX_URL = "jaxrs_basic/services/customers/customerservice/"; private String apiEndPointUrl; private String applicationNameGold; private String applicationNameSilver; private Map<String, String> requestHeadersGoldTier; private APIIdentifier apiIdentifier; private String providerName; private APICreationRequestBean apiCreationRequestBean; private APIPublisherRestClient apiPublisherClientUser1; private APIStoreRestClient apiStoreClientUser1; private boolean isInitialised = false; public void initialize() throws Exception { if (!isInitialised) { new AdvancedThrottlingConfig().disableAdvancedThrottling(); super.init(); apiEndPointUrl = getGatewayURLHttp() + API_END_POINT_POSTFIX_URL; providerName = user.getUserName(); String publisherURLHttp = getPublisherURLHttp(); String storeURLHttp = getStoreURLHttp(); apiPublisherClientUser1 = new APIPublisherRestClient(publisherURLHttp); apiStoreClientUser1 = new APIStoreRestClient(storeURLHttp); //Login to API Publisher with admin apiPublisherClientUser1.login(user.getUserName(), user.getPassword()); //Login to API Store with admin apiStoreClientUser1.login(user.getUserName(), user.getPassword()); apiIdentifier = new APIIdentifier(providerName, API_NAME, API_VERSION_1_0_0); isInitialised = true; } } @Test(groups = {"throttling"}, description = "test invocation of api under tier Gold.") public void testInvokingWithGoldTier() throws Exception { initialize(); applicationNameGold = APPLICATION_NAME + TIER_GOLD; apiStoreClientUser1 .addApplication(applicationNameGold, APIMIntegrationConstants.APPLICATION_TIER.UNLIMITED, "", ""); apiCreationRequestBean = new APICreationRequestBean(API_NAME, API_CONTEXT, API_VERSION_1_0_0, providerName, new URL(apiEndPointUrl)); apiCreationRequestBean.setTags(API_TAGS); apiCreationRequestBean.setDescription(API_DESCRIPTION); apiCreationRequestBean.setTier(TIER_GOLD); createPublishAndSubscribeToAPI( apiIdentifier, apiCreationRequestBean, apiPublisherClientUser1, apiStoreClientUser1, applicationNameGold); waitForAPIDeploymentSync(user.getUserName(), API_NAME, API_VERSION_1_0_0, APIMIntegrationConstants.IS_API_EXISTS); //get access token String accessToken = generateApplicationKeys(apiStoreClientUser1, applicationNameGold).getAccessToken(); // Create requestHeaders requestHeadersGoldTier = new HashMap<String, String>(); requestHeadersGoldTier.put("Authorization", "Bearer " + accessToken); requestHeadersGoldTier.put("accept", "text/xml"); long startTime = System.currentTimeMillis(); long currentTime; for (int invocationCount = 1; invocationCount <= GOLD_INVOCATION_LIMIT_PER_MIN; invocationCount++) { currentTime = System.currentTimeMillis(); //Invoke API HttpResponse invokeResponse = HttpRequestUtil.doGet(getAPIInvocationURLHttp(API_CONTEXT, API_VERSION_1_0_0) + "/" + API_END_POINT_METHOD, requestHeadersGoldTier); assertEquals(invokeResponse.getResponseCode(), HTTP_RESPONSE_CODE_OK, "Response code mismatched. Invocation attempt:" + invocationCount + " failed during :" + (currentTime - startTime) + " milliseconds under Gold API level tier"); assertTrue(invokeResponse.getData().contains(API_RESPONSE_DATA), "Response data mismatched. Invocation attempt:" + invocationCount + " failed during :" + (currentTime - startTime) + " milliseconds under Gold API level tier"); } currentTime = System.currentTimeMillis(); HttpResponse invokeResponse; invokeResponse = HttpRequestUtil.doGet(getAPIInvocationURLHttp(API_CONTEXT, API_VERSION_1_0_0) + "/" + API_END_POINT_METHOD, requestHeadersGoldTier); //send the request again if the test runs on a cluster. It will be 1 attempt more to get the api blocked. if (executionMode.equalsIgnoreCase(String.valueOf(ExecutionEnvironment.PLATFORM))) { invokeResponse = HttpRequestUtil.doGet(getAPIInvocationURLHttp(API_CONTEXT, API_VERSION_1_0_0) + "/" + API_END_POINT_METHOD, requestHeadersGoldTier); } assertEquals(invokeResponse.getResponseCode(), HTTP_RESPONSE_CODE_TOO_MANY_REQUESTS, "Response code mismatched. Invocation attempt:" + (GOLD_INVOCATION_LIMIT_PER_MIN + 1) + " passed during :" + (currentTime - startTime) + " milliseconds under Gold API level tier"); assertTrue(invokeResponse.getData().contains(MESSAGE_THROTTLED_OUT), "Response data mismatched. Invocation attempt:" + (GOLD_INVOCATION_LIMIT_PER_MIN + 1) + " passed during :" + (currentTime - startTime) + " milliseconds under Gold API level tier"); } @Test(groups = {"throttling"}, description = "test invocation of APi after expire the throttling block time.", dependsOnMethods = "testInvokingWithGoldTier") public void testInvokingAfterExpireThrottleExpireTime() throws Exception { initialize(); //wait millisecond to expire the throttling block Thread.sleep(THROTTLING_UNIT_TIME + THROTTLING_ADDITIONAL_WAIT_TIME); HttpResponse invokeResponse = HttpRequestUtil.doGet(getAPIInvocationURLHttp(API_CONTEXT, API_VERSION_1_0_0) + "/" + API_END_POINT_METHOD, requestHeadersGoldTier); assertEquals(invokeResponse.getResponseCode(), HTTP_RESPONSE_CODE_OK, "Response code mismatched, " + "Invocation fails after wait " + (THROTTLING_UNIT_TIME + THROTTLING_ADDITIONAL_WAIT_TIME) + "millisecond to expire the throttling block"); assertTrue(invokeResponse.getData().contains(API_RESPONSE_DATA), "Response data mismatched. " + "Invocation fails after wait " + (THROTTLING_UNIT_TIME + THROTTLING_ADDITIONAL_WAIT_TIME) + "millisecond to expire the throttling block"); } @Test(groups = {"throttling"}, description = "Test changing of the API Tier from Gold to Silver", dependsOnMethods = "testInvokingAfterExpireThrottleExpireTime") public void testEditAPITierToSilver() throws Exception { initialize(); apiCreationRequestBean = new APICreationRequestBean(API_NAME, API_CONTEXT, API_VERSION_1_0_0, providerName, new URL(apiEndPointUrl)); apiCreationRequestBean.setTags(API_TAGS); apiCreationRequestBean.setDescription(API_DESCRIPTION); apiCreationRequestBean.setTier(TIER_SILVER); apiCreationRequestBean.setTiersCollection(TIER_SILVER); //Update API with Edited information with Tier Silver HttpResponse updateAPIHTTPResponse = apiPublisherClientUser1.updateAPI(apiCreationRequestBean); waitForAPIDeployment(); assertEquals(updateAPIHTTPResponse.getResponseCode(), HTTP_RESPONSE_CODE_OK, "Update API Response Code is" + " invalid. Updating of API information fail" + getAPIIdentifierString(apiIdentifier)); assertEquals(getValueFromJSON(updateAPIHTTPResponse, "error"), "false", "Error in API Update in " + getAPIIdentifierString(apiIdentifier) + "Response Data:" + updateAPIHTTPResponse.getData()); } @Test(groups = {"throttling"}, description = "test invocation of api under tier Silver.", dependsOnMethods = "testEditAPITierToSilver") public void testInvokingWithSilverTier() throws Exception { initialize(); applicationNameSilver = APPLICATION_NAME + TIER_SILVER; // create new application apiStoreClientUser1 .addApplication(applicationNameSilver, APIMIntegrationConstants.APPLICATION_TIER.LARGE, "", ""); apiIdentifier.setTier(TIER_SILVER); // Do a API Silver subscription. subscribeToAPI(apiIdentifier, applicationNameSilver, apiStoreClientUser1); //get access token String accessToken = generateApplicationKeys(apiStoreClientUser1, applicationNameSilver).getAccessToken(); // Create requestHeaders Map<String, String> requestHeadersSilverTier = new HashMap<String, String>(); requestHeadersSilverTier.put("accept", "text/xml"); requestHeadersSilverTier.put("Authorization", "Bearer " + accessToken); //millisecond to expire the throttling block Thread.sleep(THROTTLING_UNIT_TIME + THROTTLING_ADDITIONAL_WAIT_TIME); long startTime = System.currentTimeMillis(); long currentTime; for (int invocationCount = 1; invocationCount <= SILVER_INVOCATION_LIMIT_PER_MIN; invocationCount++) { currentTime = System.currentTimeMillis(); //Invoke API HttpResponse invokeResponse = HttpRequestUtil.doGet(getAPIInvocationURLHttp(API_CONTEXT, API_VERSION_1_0_0) + "/" + API_END_POINT_METHOD, requestHeadersSilverTier); assertEquals(invokeResponse.getResponseCode(), HTTP_RESPONSE_CODE_OK, "Response code mismatched. " + "Invocation attempt:" + invocationCount + " failed during :" + (currentTime - startTime) + " milliseconds under Silver API level tier"); assertTrue(invokeResponse.getData().contains(API_RESPONSE_DATA), "Response data mismatched." + " Invocation attempt:" + invocationCount + " failed during :" + (currentTime - startTime) + " milliseconds under Silver API level tier"); } HttpResponse invokeResponse; currentTime = System.currentTimeMillis(); invokeResponse = HttpRequestUtil.doGet(getAPIInvocationURLHttp(API_CONTEXT, API_VERSION_1_0_0) + "/" + API_END_POINT_METHOD, requestHeadersSilverTier); if (executionMode.equalsIgnoreCase(String.valueOf(ExecutionEnvironment.PLATFORM))) { invokeResponse = HttpRequestUtil.doGet(getAPIInvocationURLHttp(API_CONTEXT, API_VERSION_1_0_0) + "/" + API_END_POINT_METHOD, requestHeadersSilverTier); } assertEquals(invokeResponse.getResponseCode(), HTTP_RESPONSE_CODE_TOO_MANY_REQUESTS, "Response code mismatched. Invocation attempt:" + (SILVER_INVOCATION_LIMIT_PER_MIN + 1) + " passed during :" + (currentTime - startTime) + " milliseconds under Silver API level tier"); assertTrue(invokeResponse.getData().contains(MESSAGE_THROTTLED_OUT), "Response data mismatched. Invocation attempt:" + (SILVER_INVOCATION_LIMIT_PER_MIN + 1) + " passed during :" + (currentTime - startTime) + " milliseconds under Silver API level tier"); } @AfterClass(alwaysRun = true) public void cleanUpArtifacts() throws Exception { apiStoreClientUser1.removeApplication(applicationNameGold); apiStoreClientUser1.removeApplication(applicationNameSilver); deleteAPI(apiIdentifier, apiPublisherClientUser1); } }
modules/integration/tests-integration/tests-backend/src/test/java/org/wso2/am/integration/tests/api/lifecycle/ChangeAPITierAndTestInvokingTestCase.java
/* * Copyright (c) 2015, WSO2 Inc. (http://www.wso2.org) All Rights Reserved. * * WSO2 Inc. 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.wso2.am.integration.tests.api.lifecycle; import org.testng.annotations.AfterClass; import org.testng.annotations.BeforeClass; import org.testng.annotations.Test; import org.wso2.am.integration.test.utils.APIManagerIntegrationTestException; import org.wso2.am.integration.test.utils.base.APIMIntegrationConstants; import org.wso2.am.integration.test.utils.bean.APICreationRequestBean; import org.wso2.am.integration.test.utils.clients.APIPublisherRestClient; import org.wso2.am.integration.test.utils.clients.APIStoreRestClient; import org.wso2.carbon.apimgt.api.model.APIIdentifier; import org.wso2.carbon.automation.engine.annotations.ExecutionEnvironment; import org.wso2.carbon.automation.engine.annotations.SetEnvironment; import org.wso2.carbon.automation.engine.context.AutomationContext; import org.wso2.carbon.automation.engine.context.TestUserMode; import org.wso2.carbon.automation.test.utils.http.client.HttpRequestUtil; import org.wso2.carbon.automation.test.utils.http.client.HttpResponse; import org.wso2.carbon.integration.common.utils.mgt.ServerConfigurationManager; import javax.xml.xpath.XPathExpressionException; import java.io.File; import java.io.IOException; import java.net.MalformedURLException; import java.net.URL; import java.util.HashMap; import java.util.Map; import static org.testng.Assert.assertEquals; import static org.testng.Assert.assertTrue; /** * Publish a API under gold tier and test the invocation with throttling , then change the api tier to silver * and do a new silver subscription and test invocation under Silver tier. */ @SetEnvironment(executionEnvironments = {ExecutionEnvironment.STANDALONE }) public class ChangeAPITierAndTestInvokingTestCase extends APIManagerLifecycleBaseTest { private final String API_NAME = "ChangeAPITierAndTestInvokingTest"; private final String API_CONTEXT = "ChangeAPITierAndTestInvoking"; private final String API_TAGS = "testTag1, testTag2, testTag3"; private final String API_DESCRIPTION = "This is test API create by API manager integration test"; private final String API_END_POINT_METHOD = "customers/123"; private final String API_RESPONSE_DATA = "<id>123</id><name>John</name></Customer>"; private final String API_VERSION_1_0_0 = "1.0.0"; private final String APPLICATION_NAME = "ChangeAPITierAndTestInvokingTestCase"; private final String API_END_POINT_POSTFIX_URL = "jaxrs_basic/services/customers/customerservice/"; private String apiEndPointUrl; private String applicationNameGold; private String applicationNameSilver; private Map<String, String> requestHeadersGoldTier; private APIIdentifier apiIdentifier; private String providerName; private APICreationRequestBean apiCreationRequestBean; private APIPublisherRestClient apiPublisherClientUser1; private APIStoreRestClient apiStoreClientUser1; private boolean isInitialised = false; public void initialize() throws Exception { if (!isInitialised) { super.init(); apiEndPointUrl = getGatewayURLHttp() + API_END_POINT_POSTFIX_URL; providerName = user.getUserName(); String publisherURLHttp = getPublisherURLHttp(); String storeURLHttp = getStoreURLHttp(); apiPublisherClientUser1 = new APIPublisherRestClient(publisherURLHttp); apiStoreClientUser1 = new APIStoreRestClient(storeURLHttp); //Login to API Publisher with admin apiPublisherClientUser1.login(user.getUserName(), user.getPassword()); //Login to API Store with admin apiStoreClientUser1.login(user.getUserName(), user.getPassword()); apiIdentifier = new APIIdentifier(providerName, API_NAME, API_VERSION_1_0_0); isInitialised = true; } } @Test(groups = {"throttling"}, description = "test invocation of api under tier Gold.") public void testInvokingWithGoldTier() throws Exception { initialize(); applicationNameGold = APPLICATION_NAME + TIER_GOLD; apiStoreClientUser1 .addApplication(applicationNameGold, APIMIntegrationConstants.APPLICATION_TIER.UNLIMITED, "", ""); apiCreationRequestBean = new APICreationRequestBean(API_NAME, API_CONTEXT, API_VERSION_1_0_0, providerName, new URL(apiEndPointUrl)); apiCreationRequestBean.setTags(API_TAGS); apiCreationRequestBean.setDescription(API_DESCRIPTION); apiCreationRequestBean.setTier(TIER_GOLD); createPublishAndSubscribeToAPI( apiIdentifier, apiCreationRequestBean, apiPublisherClientUser1, apiStoreClientUser1, applicationNameGold); waitForAPIDeploymentSync(user.getUserName(), API_NAME, API_VERSION_1_0_0, APIMIntegrationConstants.IS_API_EXISTS); //get access token String accessToken = generateApplicationKeys(apiStoreClientUser1, applicationNameGold).getAccessToken(); // Create requestHeaders requestHeadersGoldTier = new HashMap<String, String>(); requestHeadersGoldTier.put("Authorization", "Bearer " + accessToken); requestHeadersGoldTier.put("accept", "text/xml"); long startTime = System.currentTimeMillis(); long currentTime; for (int invocationCount = 1; invocationCount <= GOLD_INVOCATION_LIMIT_PER_MIN; invocationCount++) { currentTime = System.currentTimeMillis(); //Invoke API HttpResponse invokeResponse = HttpRequestUtil.doGet(getAPIInvocationURLHttp(API_CONTEXT, API_VERSION_1_0_0) + "/" + API_END_POINT_METHOD, requestHeadersGoldTier); assertEquals(invokeResponse.getResponseCode(), HTTP_RESPONSE_CODE_OK, "Response code mismatched. Invocation attempt:" + invocationCount + " failed during :" + (currentTime - startTime) + " milliseconds under Gold API level tier"); assertTrue(invokeResponse.getData().contains(API_RESPONSE_DATA), "Response data mismatched. Invocation attempt:" + invocationCount + " failed during :" + (currentTime - startTime) + " milliseconds under Gold API level tier"); } currentTime = System.currentTimeMillis(); HttpResponse invokeResponse; invokeResponse = HttpRequestUtil.doGet(getAPIInvocationURLHttp(API_CONTEXT, API_VERSION_1_0_0) + "/" + API_END_POINT_METHOD, requestHeadersGoldTier); //send the request again if the test runs on a cluster. It will be 1 attempt more to get the api blocked. if (executionMode.equalsIgnoreCase(String.valueOf(ExecutionEnvironment.PLATFORM))) { invokeResponse = HttpRequestUtil.doGet(getAPIInvocationURLHttp(API_CONTEXT, API_VERSION_1_0_0) + "/" + API_END_POINT_METHOD, requestHeadersGoldTier); } assertEquals(invokeResponse.getResponseCode(), HTTP_RESPONSE_CODE_TOO_MANY_REQUESTS, "Response code mismatched. Invocation attempt:" + (GOLD_INVOCATION_LIMIT_PER_MIN + 1) + " passed during :" + (currentTime - startTime) + " milliseconds under Gold API level tier"); assertTrue(invokeResponse.getData().contains(MESSAGE_THROTTLED_OUT), "Response data mismatched. Invocation attempt:" + (GOLD_INVOCATION_LIMIT_PER_MIN + 1) + " passed during :" + (currentTime - startTime) + " milliseconds under Gold API level tier"); } @Test(groups = {"throttling"}, description = "test invocation of APi after expire the throttling block time.", dependsOnMethods = "testInvokingWithGoldTier") public void testInvokingAfterExpireThrottleExpireTime() throws Exception { initialize(); //wait millisecond to expire the throttling block Thread.sleep(THROTTLING_UNIT_TIME + THROTTLING_ADDITIONAL_WAIT_TIME); HttpResponse invokeResponse = HttpRequestUtil.doGet(getAPIInvocationURLHttp(API_CONTEXT, API_VERSION_1_0_0) + "/" + API_END_POINT_METHOD, requestHeadersGoldTier); assertEquals(invokeResponse.getResponseCode(), HTTP_RESPONSE_CODE_OK, "Response code mismatched, " + "Invocation fails after wait " + (THROTTLING_UNIT_TIME + THROTTLING_ADDITIONAL_WAIT_TIME) + "millisecond to expire the throttling block"); assertTrue(invokeResponse.getData().contains(API_RESPONSE_DATA), "Response data mismatched. " + "Invocation fails after wait " + (THROTTLING_UNIT_TIME + THROTTLING_ADDITIONAL_WAIT_TIME) + "millisecond to expire the throttling block"); } @Test(groups = {"throttling"}, description = "Test changing of the API Tier from Gold to Silver", dependsOnMethods = "testInvokingAfterExpireThrottleExpireTime") public void testEditAPITierToSilver() throws Exception { initialize(); apiCreationRequestBean = new APICreationRequestBean(API_NAME, API_CONTEXT, API_VERSION_1_0_0, providerName, new URL(apiEndPointUrl)); apiCreationRequestBean.setTags(API_TAGS); apiCreationRequestBean.setDescription(API_DESCRIPTION); apiCreationRequestBean.setTier(TIER_SILVER); apiCreationRequestBean.setTiersCollection(TIER_SILVER); //Update API with Edited information with Tier Silver HttpResponse updateAPIHTTPResponse = apiPublisherClientUser1.updateAPI(apiCreationRequestBean); waitForAPIDeployment(); assertEquals(updateAPIHTTPResponse.getResponseCode(), HTTP_RESPONSE_CODE_OK, "Update API Response Code is" + " invalid. Updating of API information fail" + getAPIIdentifierString(apiIdentifier)); assertEquals(getValueFromJSON(updateAPIHTTPResponse, "error"), "false", "Error in API Update in " + getAPIIdentifierString(apiIdentifier) + "Response Data:" + updateAPIHTTPResponse.getData()); } @Test(groups = {"throttling"}, description = "test invocation of api under tier Silver.", dependsOnMethods = "testEditAPITierToSilver") public void testInvokingWithSilverTier() throws Exception { initialize(); applicationNameSilver = APPLICATION_NAME + TIER_SILVER; // create new application apiStoreClientUser1 .addApplication(applicationNameSilver, APIMIntegrationConstants.APPLICATION_TIER.LARGE, "", ""); apiIdentifier.setTier(TIER_SILVER); // Do a API Silver subscription. subscribeToAPI(apiIdentifier, applicationNameSilver, apiStoreClientUser1); //get access token String accessToken = generateApplicationKeys(apiStoreClientUser1, applicationNameSilver).getAccessToken(); // Create requestHeaders Map<String, String> requestHeadersSilverTier = new HashMap<String, String>(); requestHeadersSilverTier.put("accept", "text/xml"); requestHeadersSilverTier.put("Authorization", "Bearer " + accessToken); //millisecond to expire the throttling block Thread.sleep(THROTTLING_UNIT_TIME + THROTTLING_ADDITIONAL_WAIT_TIME); long startTime = System.currentTimeMillis(); long currentTime; for (int invocationCount = 1; invocationCount <= SILVER_INVOCATION_LIMIT_PER_MIN; invocationCount++) { currentTime = System.currentTimeMillis(); //Invoke API HttpResponse invokeResponse = HttpRequestUtil.doGet(getAPIInvocationURLHttp(API_CONTEXT, API_VERSION_1_0_0) + "/" + API_END_POINT_METHOD, requestHeadersSilverTier); assertEquals(invokeResponse.getResponseCode(), HTTP_RESPONSE_CODE_OK, "Response code mismatched. " + "Invocation attempt:" + invocationCount + " failed during :" + (currentTime - startTime) + " milliseconds under Silver API level tier"); assertTrue(invokeResponse.getData().contains(API_RESPONSE_DATA), "Response data mismatched." + " Invocation attempt:" + invocationCount + " failed during :" + (currentTime - startTime) + " milliseconds under Silver API level tier"); } HttpResponse invokeResponse; currentTime = System.currentTimeMillis(); invokeResponse = HttpRequestUtil.doGet(getAPIInvocationURLHttp(API_CONTEXT, API_VERSION_1_0_0) + "/" + API_END_POINT_METHOD, requestHeadersSilverTier); if (executionMode.equalsIgnoreCase(String.valueOf(ExecutionEnvironment.PLATFORM))) { invokeResponse = HttpRequestUtil.doGet(getAPIInvocationURLHttp(API_CONTEXT, API_VERSION_1_0_0) + "/" + API_END_POINT_METHOD, requestHeadersSilverTier); } assertEquals(invokeResponse.getResponseCode(), HTTP_RESPONSE_CODE_TOO_MANY_REQUESTS, "Response code mismatched. Invocation attempt:" + (SILVER_INVOCATION_LIMIT_PER_MIN + 1) + " passed during :" + (currentTime - startTime) + " milliseconds under Silver API level tier"); assertTrue(invokeResponse.getData().contains(MESSAGE_THROTTLED_OUT), "Response data mismatched. Invocation attempt:" + (SILVER_INVOCATION_LIMIT_PER_MIN + 1) + " passed during :" + (currentTime - startTime) + " milliseconds under Silver API level tier"); } @AfterClass(alwaysRun = true) public void cleanUpArtifacts() throws Exception { apiStoreClientUser1.removeApplication(applicationNameGold); apiStoreClientUser1.removeApplication(applicationNameSilver); deleteAPI(apiIdentifier, apiPublisherClientUser1); } }
Disable advanced throttling for the test case.
modules/integration/tests-integration/tests-backend/src/test/java/org/wso2/am/integration/tests/api/lifecycle/ChangeAPITierAndTestInvokingTestCase.java
Disable advanced throttling for the test case.
<ide><path>odules/integration/tests-integration/tests-backend/src/test/java/org/wso2/am/integration/tests/api/lifecycle/ChangeAPITierAndTestInvokingTestCase.java <ide> import org.wso2.am.integration.test.utils.bean.APICreationRequestBean; <ide> import org.wso2.am.integration.test.utils.clients.APIPublisherRestClient; <ide> import org.wso2.am.integration.test.utils.clients.APIStoreRestClient; <add>import org.wso2.am.integration.tests.throttling.AdvancedThrottlingConfig; <ide> import org.wso2.carbon.apimgt.api.model.APIIdentifier; <ide> import org.wso2.carbon.automation.engine.annotations.ExecutionEnvironment; <ide> import org.wso2.carbon.automation.engine.annotations.SetEnvironment; <ide> <ide> public void initialize() throws Exception { <ide> if (!isInitialised) { <add> new AdvancedThrottlingConfig().disableAdvancedThrottling(); <ide> super.init(); <ide> <ide> apiEndPointUrl = getGatewayURLHttp() + API_END_POINT_POSTFIX_URL;
JavaScript
mit
cb9028133f830ab416bceaa3944d57d0323c6279
0
johnhof/proxy-express
var request = require('request'); var _ = require('lodash'); var URL = require('url'); var async = require('async'); var colors = require('colors'); var helpers = require('./helpers'); //////////////////////////////////////////////////////////// // // Middleware setup // //////////////////////////////////////////////////////////// module.exports = function (host, options) { if (typeof host !== 'string') { throw new Error('proxy-express expects `host` to be a string'); } if (typeof options === 'string') { options = { prefix : options }; } else if (typeof options === 'RegExp') { // @todo typeof options will be 'object' if it's a RegExp; check with _.isRegExp() options = { restrict : { match : options } }; } var stream = buildStream(host, options); return buildResultingMiddleware(host, options, stream); }; //////////////////////////////////////////////////////////// // // Stream setup // //////////////////////////////////////////////////////////// // construct the async waterfall stream // // accept // buildStream(host) // OR // buildStream(host, secureBool) // OR // buildStream(host, secureBool) // OR // buildStream(host, prefix, secureBool) // OR // buildStream(host, optionsObj) // function buildStream (host, options, secure) { var stream = []; // accept options as a secure boolean if (options === true) { secure = true; } options = _.defaults(_.isObject(options) ? options : {}, { request : {}, response : {} }); function applyStreamFunctions (funcSet) { _.each(funcSet || [], function (middleware) { if (_.isFunction(middleware)) { // wrapper allows us to call the callback without passing proxyObj stream.push(function asyncWrapper (proxyObj, callback) { return middleware(proxyObj, function (error, _proxyObj) { return callback(error, _proxyObj || proxyObj); }) }); } }); } // if there is `pre` middleware var preSet = options.pre; if (preSet) { // accept raw functions, but wrap it in an array preSet = _.isFunction(preSet) ? [preSet] : preSet; applyStreamFunctions(preSet); } // push the core request stream.push(proxyReq); // if there is `post` middleware var postSet = options.post; if (postSet) { // accept raw functions, but wrap it in an array postSet = _.isFunction(postSet) ? [postSet] : postSet; applyStreamFunctions(postSet); } if (secure) { options.request.forceHttps = true; } return stream; } //////////////////////////////////////////////////////////// // // Resulting middleware // //////////////////////////////////////////////////////////// function buildResultingMiddleware (host, options, sharedStream) { return function proxyMiddleware (req, res, next) { var stream = _.clone(sharedStream, true); var reqUrl = URL.parse(req.url, true); var proxyUrl = { pathname : reqUrl.pathname, protocol : options.request.forceHttps ? 'https' : req.protocol, host : host }; // // Check user defined proxy conditions // var shouldProxy = true; // If there is a prefix, it must match the route to continue if (typeof options.prefix === 'string') { var prefix = options.prefix[0] == '/' ? options.prefix : '/' + options.prefix; // if thre prefix failed to match, set shouldProxy to false if ((reqUrl.pathname || '').indexOf(prefix) !== 0) { shouldProxy = false; // otherwise, remove the prefix and continue } else { proxyUrl.pathname = proxyUrl.pathname.replace(prefix, ''); } } if (typeof options.request.prepend === 'string') { proxyUrl.pathname = (/^\//.test(options.request.prepend) ? options.request.prepend : '/' + options.request.prepend) + (/^\//.test(proxyUrl.pathname) ? proxyUrl.pathname : '/' + proxyUrl.pathname); } // if there are restricts applied, and we havent failed out yet if (options.restrict && shouldProxy) { shouldProxy = !!_.find( _.isArray(options.restrict) ? options.restrict : [options.restrict], helpers.matchesRestriction.bind(helpers,req) ); } // if the current route isn't greenlit for the passthrough, bail out if (!shouldProxy) { return next(); } var encoding = undefined; //Handle Image Files if (/jpe?g|gif|png|ico|bmp|tiff/.test(req.url)) { encoding = null; } // // compile the request object used for the `request` module call // req.headers.host = host; var reqOpts = { url : URL.format(proxyUrl), method : req.method, form : _.defaults(options.request.form, req.body), qs : _.defaults({},options.request.query, req.query), headers : helpers.defaultHeaders(options.request.headers, req.headers), encoding: encoding, followAllRedirects : options.request.followRedirects !== false ? true : false, strictSSL: options.request.strictSSL !== undefined ? options.request.strictSSL : true }; // if the route is greenlit, add the proxy option builder to the stream stream.unshift(function (callback) { return callback(null, { req : req, res : res, reqOpts : reqOpts, options : options }); }); // header cleanup before request res.removeHeader("x-powered-by"); return async.waterfall(stream, respond(next)); } } //////////////////////////////////////////////////////////// // // Stream functions // //////////////////////////////////////////////////////////// // // async function to make the proxied request (fires between brefore `pre` and `post` functions) // function proxyReq (proxyObj, callback) { var proxyError = proxyObjErrors(proxyObj); if (proxyError) { return callback(new Error(proxyError)); } if (proxyObj.options.log) { logReqOpts(proxyObj.reqOpts) } // TESTING HELPER ONLY if (proxyObj.options.shortCircuit) { return callback(null, proxyObj); } // unless explicitly set, ignore encoding // THIS IS A HACK THAT MAY CAUSE ISSUES. I DON'T // KNOW OF AN IMMEDIATE WORKAROUND TO FIX IT. if (!proxyObj.options['accept-encoding']) { delete proxyObj.reqOpts.headers['accept-encoding']; } // make request request(proxyObj.reqOpts, function (error, response, body) { if (proxyObj.options.log) { logResponse(response, body); } // transfer result to resulting o proxyObj.res.set(helpers.defaultHeaders(proxyObj.options.response.headers, response ? response.headers : {})); proxyObj.result = { response : response, body : body }; return callback(error, proxyObj); }); } // // respond with proxied result (fires at the end of all middleware execution) // function respond (next) { return function sendResult (error, proxyObj) { if (error) { return next(error); } // TESTING HELPER ONLY if (proxyObj.options.shortCircuit) { return proxyObj.res.send({ result: 'proxy-express set to short circuit. If this is not expected, please check your config' }); } var proxyError = proxyObjErrors(proxyObj); if (proxyError) { return next(new Error(proxyError)); } else if (!(proxyObj.result && proxyObj.result.response)) { return next(new Error('Proxy to ' + proxyObj.reqOpts.url + ' failed for an unkown reason')); } else { proxyObj.res.status(proxyObj.result.response.statusCode || 400).send(proxyObj.result.body); } } } //////////////////////////////////////////////////////////// // // Helpers // //////////////////////////////////////////////////////////// function proxyObjErrors (proxyObj) { if (!proxyObj) { return '`proxyObj` not defined'; } var errors = ''; var expected = ['req', 'req', 'reqOpts', 'options']; _.each(expected, function (expect, index) { if (!proxyObj[expect]) { errors += (index ? ', ' : '') + 'Missing property: `' + expect + '`'; } }); return errors ? 'Errors found in `proxyObj`: [' + errors + ']' : false; } function logReqOpts (reqOpts) { reqOpts = reqOpts || {}; console.log('\n>>>>>>>> Request >>>>>>>\n'.cyan); console.log('===== URL =====\n'.yellow); console.log(' ' + (reqOpts.method || '').green + ' ' + (reqOpts.url || '')); console.log('\n===== Headers =====\n'.yellow); console.log(JSON.stringify(reqOpts.headers || {}, null, ' ')); console.log('\n===== Form =====\n'.yellow); console.log(JSON.stringify(reqOpts.form || {}, null, ' ') + '\n'); } function logResponse (response, body) { response = response || {}; console.log('\n<<<<<<<< Response <<<<<<<\n'.cyan); console.log('===== Status =====\n'.yellow); console.log(response.statusCode + '\n'); console.log('===== Headers =====\n'.yellow); console.log(JSON.stringify((response).headers || {}, null, ' ')); console.log('\n===== Body =====\n'.yellow); console.log(' type: [' + (typeof body) + ']\n'); }
lib/proxy.js
var request = require('request'); var _ = require('lodash'); var URL = require('url'); var async = require('async'); var colors = require('colors'); var helpers = require('./helpers'); //////////////////////////////////////////////////////////// // // Middleware setup // //////////////////////////////////////////////////////////// module.exports = function (host, options) { if (typeof host !== 'string') { throw new Error('proxy-express expects `host` to be a string'); } if (typeof options === 'string') { options = { prefix : options }; } else if (typeof options === 'RegExp') { // @todo typeof options will be 'object' if it's a RegExp; check with _.isRegExp() options = { restrict : { match : options } }; } var stream = buildStream(host, options); return buildResultingMiddleware(host, options, stream); }; //////////////////////////////////////////////////////////// // // Stream setup // //////////////////////////////////////////////////////////// // construct the async waterfall stream // // accept // buildStream(host) // OR // buildStream(host, secureBool) // OR // buildStream(host, secureBool) // OR // buildStream(host, prefix, secureBool) // OR // buildStream(host, optionsObj) // function buildStream (host, options, secure) { var stream = []; // accept options as a secure boolean if (options === true) { secure = true; } options = _.defaults(_.isObject(options) ? options : {}, { request : {}, response : {} }); function applyStreamFunctions (funcSet) { _.each(funcSet || [], function (middleware) { if (_.isFunction(middleware)) { // wrapper allows us to call the callback without passing proxyObj stream.push(function asyncWrapper (proxyObj, callback) { return middleware(proxyObj, function (error, _proxyObj) { return callback(error, _proxyObj || proxyObj); }) }); } }); } // if there is `pre` middleware var preSet = options.pre; if (preSet) { // accept raw functions, but wrap it in an array preSet = _.isFunction(preSet) ? [preSet] : preSet; applyStreamFunctions(preSet); } // push the core request stream.push(proxyReq); // if there is `post` middleware var postSet = options.post; if (postSet) { // accept raw functions, but wrap it in an array postSet = _.isFunction(postSet) ? [postSet] : postSet; applyStreamFunctions(postSet); } if (secure) { options.request.forceHttps = true; } return stream; } //////////////////////////////////////////////////////////// // // Resulting middleware // //////////////////////////////////////////////////////////// function buildResultingMiddleware (host, options, sharedStream) { return function proxyMiddleware (req, res, next) { var stream = _.clone(sharedStream, true); var reqUrl = URL.parse(req.url, true); var proxyUrl = { pathname : reqUrl.pathname, protocol : options.request.forceHttps ? 'https' : req.protocol, host : host }; // // Check user defined proxy conditions // var shouldProxy = true; // If there is a prefix, it must match the route to continue if (typeof options.prefix === 'string') { var prefix = options.prefix[0] == '/' ? options.prefix : '/' + options.prefix; // if thre prefix failed to match, set shouldProxy to false if ((reqUrl.pathname || '').indexOf(prefix) !== 0) { shouldProxy = false; // otherwise, remove the prefix and continue } else { proxyUrl.pathname = proxyUrl.pathname.replace(prefix, ''); } } if (typeof options.request.prepend === 'string') { proxyUrl.pathname = (/^\//.test(options.request.prepend) ? options.request.prepend : '/' + options.request.prepend) + (/^\//.test(proxyUrl.pathname) ? proxyUrl.pathname : '/' + proxyUrl.pathname); } // if there are restricts applied, and we havent failed out yet if (options.restrict && shouldProxy) { shouldProxy = !!_.find( _.isArray(options.restrict) ? options.restrict : [options.restrict], helpers.matchesRestriction.bind(helpers,req) ); } // if the current route isn't greenlit for the passthrough, bail out if (!shouldProxy) { return next(); } var encoding = undefined; //Handle Image Files if (/jpe?g|gif|png|ico|bmp|tiff/.test(req.url)) { encoding = null; } // // compile the request object used for the `request` module call // req.headers.host = host; var reqOpts = { url : URL.format(proxyUrl), method : req.method, form : _.defaults(options.request.form, req.body), qs : _.defaults(options.request.query, req.query), headers : helpers.defaultHeaders(options.request.headers, req.headers), encoding: encoding, followAllRedirects : options.request.followRedirects !== false ? true : false, strictSSL: options.request.strictSSL !== undefined ? options.request.strictSSL : true }; // if the route is greenlit, add the proxy option builder to the stream stream.unshift(function (callback) { return callback(null, { req : req, res : res, reqOpts : reqOpts, options : options }); }); // header cleanup before request res.removeHeader("x-powered-by"); return async.waterfall(stream, respond(next)); } } //////////////////////////////////////////////////////////// // // Stream functions // //////////////////////////////////////////////////////////// // // async function to make the proxied request (fires between brefore `pre` and `post` functions) // function proxyReq (proxyObj, callback) { var proxyError = proxyObjErrors(proxyObj); if (proxyError) { return callback(new Error(proxyError)); } if (proxyObj.options.log) { logReqOpts(proxyObj.reqOpts) } // TESTING HELPER ONLY if (proxyObj.options.shortCircuit) { return callback(null, proxyObj); } // unless explicitly set, ignore encoding // THIS IS A HACK THAT MAY CAUSE ISSUES. I DON'T // KNOW OF AN IMMEDIATE WORKAROUND TO FIX IT. if (!proxyObj.options['accept-encoding']) { delete proxyObj.reqOpts.headers['accept-encoding']; } // make request request(proxyObj.reqOpts, function (error, response, body) { if (proxyObj.options.log) { logResponse(response, body); } // transfer result to resulting o proxyObj.res.set(helpers.defaultHeaders(proxyObj.options.response.headers, response ? response.headers : {})); proxyObj.result = { response : response, body : body }; return callback(error, proxyObj); }); } // // respond with proxied result (fires at the end of all middleware execution) // function respond (next) { return function sendResult (error, proxyObj) { if (error) { return next(error); } // TESTING HELPER ONLY if (proxyObj.options.shortCircuit) { return proxyObj.res.send({ result: 'proxy-express set to short circuit. If this is not expected, please check your config' }); } var proxyError = proxyObjErrors(proxyObj); if (proxyError) { return next(new Error(proxyError)); } else if (!(proxyObj.result && proxyObj.result.response)) { return next(new Error('Proxy to ' + proxyObj.reqOpts.url + ' failed for an unkown reason')); } else { proxyObj.res.status(proxyObj.result.response.statusCode || 400).send(proxyObj.result.body); } } } //////////////////////////////////////////////////////////// // // Helpers // //////////////////////////////////////////////////////////// function proxyObjErrors (proxyObj) { if (!proxyObj) { return '`proxyObj` not defined'; } var errors = ''; var expected = ['req', 'req', 'reqOpts', 'options']; _.each(expected, function (expect, index) { if (!proxyObj[expect]) { errors += (index ? ', ' : '') + 'Missing property: `' + expect + '`'; } }); return errors ? 'Errors found in `proxyObj`: [' + errors + ']' : false; } function logReqOpts (reqOpts) { reqOpts = reqOpts || {}; console.log('\n>>>>>>>> Request >>>>>>>\n'.cyan); console.log('===== URL =====\n'.yellow); console.log(' ' + (reqOpts.method || '').green + ' ' + (reqOpts.url || '')); console.log('\n===== Headers =====\n'.yellow); console.log(JSON.stringify(reqOpts.headers || {}, null, ' ')); console.log('\n===== Form =====\n'.yellow); console.log(JSON.stringify(reqOpts.form || {}, null, ' ') + '\n'); } function logResponse (response, body) { response = response || {}; console.log('\n<<<<<<<< Response <<<<<<<\n'.cyan); console.log('===== Status =====\n'.yellow); console.log(response.statusCode + '\n'); console.log('===== Headers =====\n'.yellow); console.log(JSON.stringify((response).headers || {}, null, ' ')); console.log('\n===== Body =====\n'.yellow); console.log(' type: [' + (typeof body) + ']\n'); }
fixing reqOpts.qs defaults
lib/proxy.js
fixing reqOpts.qs defaults
<ide><path>ib/proxy.js <ide> url : URL.format(proxyUrl), <ide> method : req.method, <ide> form : _.defaults(options.request.form, req.body), <del> qs : _.defaults(options.request.query, req.query), <add> qs : _.defaults({},options.request.query, req.query), <ide> headers : helpers.defaultHeaders(options.request.headers, req.headers), <ide> encoding: encoding, <ide> followAllRedirects : options.request.followRedirects !== false ? true : false,
Java
apache-2.0
802a73d35df99edbfc41af2b40f0854cde50590b
0
awsdocs/aws-doc-sdk-examples,awsdocs/aws-doc-sdk-examples,awsdocs/aws-doc-sdk-examples,awsdocs/aws-doc-sdk-examples,awsdocs/aws-doc-sdk-examples,awsdocs/aws-doc-sdk-examples,awsdocs/aws-doc-sdk-examples,awsdocs/aws-doc-sdk-examples,awsdocs/aws-doc-sdk-examples,awsdocs/aws-doc-sdk-examples,awsdocs/aws-doc-sdk-examples,awsdocs/aws-doc-sdk-examples,awsdocs/aws-doc-sdk-examples,awsdocs/aws-doc-sdk-examples,awsdocs/aws-doc-sdk-examples
//snippet-sourcedescription:[DescribeLimits.java demonstrates how to display the shard limit and usage for a given account] //snippet-keyword:[Java] //snippet-sourcesyntax:[java] //snippet-keyword:[SDK for Java 2.0] //snippet-keyword:[Code Sample] //snippet-keyword:[Amazon Kinesis] //snippet-service:[kinesis] //snippet-sourcetype:[full-example] //snippet-sourcedate:3/26/2020] //snippet-sourceauthor:[scmacdon AWS] /* * Copyright Amazon.com, Inc. or its affiliates. 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. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file 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.example.kinesis; //snippet-start:[kinesis.java2.DescribeLimits.import] import software.amazon.awssdk.regions.Region; import software.amazon.awssdk.services.kinesis.KinesisClient; import software.amazon.awssdk.services.kinesis.model.DescribeLimitsRequest; import software.amazon.awssdk.services.kinesis.model.DescribeLimitsResponse; import software.amazon.awssdk.services.kinesis.model.KinesisException; //snippet-end:[kinesis.java2.DescribeLimits.import] public class DescribeLimits { public static void main(String[] args) { // snippet-start:[kinesis.java2.DescribeLimits.client] Region region = Region.US_EAST_1; KinesisClient kinesisClient = KinesisClient.builder() .region(region) .build(); describeKinLimits(kinesisClient); } public static void describeKinLimits(KinesisClient kinesisClient) { // snippet-end:[kinesis.java2.DescribeLimits.client] try { // snippet-start:[kinesis.java2.DescribeLimits.main] DescribeLimitsRequest request = DescribeLimitsRequest.builder() .build(); DescribeLimitsResponse response = kinesisClient.describeLimits(request); System.out.println("Number of open shards: " + response.openShardCount()); System.out.println("Maximum shards allowed: " + response.shardLimit()); } catch (KinesisException e) { System.err.println(e.getMessage()); System.exit(1); } System.out.println("Done"); // snippet-end:[kinesis.java2.DescribeLimits.main] } }
javav2/example_code/kinesis/src/main/java/com/example/kinesis/DescribeLimits.java
//snippet-sourcedescription:[DescribeLimits.java demonstrates how to display the shard limit and usage for a given account .] //snippet-keyword:[Java] //snippet-sourcesyntax:[java] //snippet-keyword:[SDK for Java 2.0] //snippet-keyword:[Code Sample] //snippet-keyword:[Amazon Kinesis] //snippet-service:[kinesis] //snippet-sourcetype:[full-example] //snippet-sourcedate:[2019-06-28] //snippet-sourceauthor:[jschwarzwalder AWS] /* * Copyright 2010-2019 Amazon.com, Inc. or its affiliates. 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. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file 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. */ //snippet-start:[kinesis.java2.DescribeLimits.complete] package com.example.kinesis; //snippet-start:[kinesis.java2.DescribeLimits.import] import software.amazon.awssdk.http.nio.netty.NettyNioAsyncHttpClient; import software.amazon.awssdk.services.kinesis.KinesisAsyncClient; import software.amazon.awssdk.services.kinesis.model.DescribeLimitsRequest; import software.amazon.awssdk.services.kinesis.model.DescribeLimitsResponse; import java.util.concurrent.ExecutionException; //snippet-end:[kinesis.java2.DescribeLimits.import] public class DescribeLimits { public static void main(String[] args) { // snippet-start:[kinesis.java2.DescribeLimits.client] KinesisAsyncClient client = KinesisAsyncClient.builder() .httpClientBuilder(NettyNioAsyncHttpClient.builder() .maxConcurrency(100) .maxPendingConnectionAcquires(10_000)) .build(); // snippet-end:[kinesis.java2.DescribeLimits.client] // snippet-start:[kinesis.java2.DescribeLimits.main] DescribeLimitsRequest request = DescribeLimitsRequest.builder() .build(); DescribeLimitsResponse response = client.describeLimits(request).join(); System.out.println("Number of open shards: " + response.openShardCount()); System.out.println("Maximum shards allowed: " + response.shardLimit()); // snippet-end:[kinesis.java2.DescribeLimits.main] } } //snippet-end:[kinesis.java2.DescribeLimits.complete]
Update DescribeLimits.java Refactored the code
javav2/example_code/kinesis/src/main/java/com/example/kinesis/DescribeLimits.java
Update DescribeLimits.java
<ide><path>avav2/example_code/kinesis/src/main/java/com/example/kinesis/DescribeLimits.java <del>//snippet-sourcedescription:[DescribeLimits.java demonstrates how to display the shard limit and usage for a given account .] <add>//snippet-sourcedescription:[DescribeLimits.java demonstrates how to display the shard limit and usage for a given account] <ide> //snippet-keyword:[Java] <ide> //snippet-sourcesyntax:[java] <ide> //snippet-keyword:[SDK for Java 2.0] <ide> //snippet-keyword:[Amazon Kinesis] <ide> //snippet-service:[kinesis] <ide> //snippet-sourcetype:[full-example] <del>//snippet-sourcedate:[2019-06-28] <del>//snippet-sourceauthor:[jschwarzwalder AWS] <add>//snippet-sourcedate:3/26/2020] <add>//snippet-sourceauthor:[scmacdon AWS] <ide> /* <del> * Copyright 2010-2019 Amazon.com, Inc. or its affiliates. All Rights Reserved. <add> * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. <ide> * <ide> * Licensed under the Apache License, Version 2.0 (the "License"). <ide> * You may not use this file except in compliance with the License. <ide> * express or implied. See the License for the specific language governing <ide> * permissions and limitations under the License. <ide> */ <del>//snippet-start:[kinesis.java2.DescribeLimits.complete] <ide> <ide> package com.example.kinesis; <ide> //snippet-start:[kinesis.java2.DescribeLimits.import] <del> <del>import software.amazon.awssdk.http.nio.netty.NettyNioAsyncHttpClient; <del>import software.amazon.awssdk.services.kinesis.KinesisAsyncClient; <add>import software.amazon.awssdk.regions.Region; <add>import software.amazon.awssdk.services.kinesis.KinesisClient; <ide> import software.amazon.awssdk.services.kinesis.model.DescribeLimitsRequest; <ide> import software.amazon.awssdk.services.kinesis.model.DescribeLimitsResponse; <del> <del>import java.util.concurrent.ExecutionException; <add>import software.amazon.awssdk.services.kinesis.model.KinesisException; <ide> //snippet-end:[kinesis.java2.DescribeLimits.import] <ide> <ide> public class DescribeLimits { <ide> <ide> public static void main(String[] args) { <ide> // snippet-start:[kinesis.java2.DescribeLimits.client] <del> KinesisAsyncClient client = KinesisAsyncClient.builder() <del> .httpClientBuilder(NettyNioAsyncHttpClient.builder() <del> .maxConcurrency(100) <del> .maxPendingConnectionAcquires(10_000)) <add> Region region = Region.US_EAST_1; <add> KinesisClient kinesisClient = KinesisClient.builder() <add> .region(region) <ide> .build(); <ide> <add> describeKinLimits(kinesisClient); <add> } <add> <add> public static void describeKinLimits(KinesisClient kinesisClient) { <add> <ide> // snippet-end:[kinesis.java2.DescribeLimits.client] <del> <del> <add> try { <ide> // snippet-start:[kinesis.java2.DescribeLimits.main] <ide> DescribeLimitsRequest request = DescribeLimitsRequest.builder() <del> .build(); <add> .build(); <ide> <del> <del> DescribeLimitsResponse response = client.describeLimits(request).join(); <add> DescribeLimitsResponse response = kinesisClient.describeLimits(request); <ide> <ide> System.out.println("Number of open shards: " + response.openShardCount()); <ide> System.out.println("Maximum shards allowed: " + response.shardLimit()); <del> <add> } catch (KinesisException e) { <add> System.err.println(e.getMessage()); <add> System.exit(1); <add> } <add> System.out.println("Done"); <ide> // snippet-end:[kinesis.java2.DescribeLimits.main] <ide> } <del> <ide> } <del>//snippet-end:[kinesis.java2.DescribeLimits.complete]
Java
apache-2.0
ebe017adfe5c813f137108800f3209239ede5a2f
0
DataSketches/sketches-core
package com.yahoo.sketches.kll; import org.testng.Assert; import org.testng.annotations.Test; /* A test record contains: 0. testIndex 1. K 2. N 3. stride (for generating the input) 4. numLevels 5. numSamples 6. hash of the retained samples */ /* These results are for the version that delays the rollup until the next value comes in. */ public class KllValidationTest { private static final long[] correctResultsWithReset = { 0, 200, 180, 3246533, 1, 180, 1098352976109474698L, 1, 200, 198, 8349603, 1, 198, 686681527497651888L, 2, 200, 217, 676491, 2, 117, 495856134049157644L, 3, 200, 238, 3204507, 2, 138, 44453438498725402L, 4, 200, 261, 2459373, 2, 161, 719830627391926938L, 5, 200, 287, 5902143, 2, 187, 389303173170515580L, 6, 200, 315, 5188793, 2, 215, 985218890825795000L, 7, 200, 346, 801923, 2, 246, 589362992166904413L, 8, 200, 380, 2466269, 2, 280, 1081848693781775853L, 9, 200, 418, 5968041, 2, 318, 533825689515788397L, 10, 200, 459, 3230027, 2, 243, 937332670315558786L, 11, 200, 504, 5125875, 2, 288, 1019197831515566845L, 12, 200, 554, 4195571, 3, 230, 797351479150148224L, 13, 200, 609, 2221181, 3, 285, 451246040374318529L, 14, 200, 669, 5865503, 3, 345, 253851269470815909L, 15, 200, 735, 831703, 3, 411, 491974970526372303L, 16, 200, 808, 4830785, 3, 327, 1032107507126916277L, 17, 200, 888, 1356257, 3, 407, 215225420986342944L, 18, 200, 976, 952071, 3, 417, 600280049738270697L, 19, 200, 1073, 6729833, 3, 397, 341758522977365969L, 20, 200, 1180, 6017925, 3, 406, 1080227312339182949L, 21, 200, 1298, 4229891, 3, 401, 1092460534756675086L, 22, 200, 1427, 7264889, 4, 320, 884533400696890024L, 23, 200, 1569, 5836327, 4, 462, 660575800011134382L, 24, 200, 1725, 5950087, 4, 416, 669373957401387528L, 25, 200, 1897, 2692555, 4, 406, 607308667566496888L, 26, 200, 2086, 1512443, 4, 459, 744260340112029032L, 27, 200, 2294, 2681171, 4, 434, 199120609113802485L, 28, 200, 2523, 3726521, 4, 450, 570993497599288304L, 29, 200, 2775, 2695247, 4, 442, 306717093329516310L, 30, 200, 3052, 5751175, 5, 400, 256024589545754217L, 31, 200, 3357, 1148897, 5, 514, 507276662329207479L, 32, 200, 3692, 484127, 5, 457, 1082660223488175122L, 33, 200, 4061, 6414559, 5, 451, 620820308918522117L, 34, 200, 4467, 5587461, 5, 466, 121975084804459305L, 35, 200, 4913, 1615017, 5, 483, 152986529342916376L, 36, 200, 5404, 6508535, 5, 492, 858526451332425960L, 37, 200, 5944, 2991657, 5, 492, 624906434274621995L, 38, 200, 6538, 6736565, 6, 511, 589153542019036049L, 39, 200, 7191, 1579893, 6, 507, 10255312374117907L, 40, 200, 7910, 412509, 6, 538, 570863587164194186L, 41, 200, 8701, 1112089, 6, 477, 553100668286355347L, 42, 200, 9571, 1258813, 6, 526, 344845406406036297L, 43, 200, 10528, 1980049, 6, 508, 411846569527905064L, 44, 200, 11580, 2167127, 6, 520, 966876726203675488L, 45, 200, 12738, 1975435, 7, 561, 724125506920592732L, 46, 200, 14011, 4289627, 7, 560, 753686005174215572L, 47, 200, 15412, 5384001, 7, 494, 551637841878573955L, 48, 200, 16953, 2902685, 7, 560, 94602851752354802L, 49, 200, 18648, 4806445, 7, 562, 597672400688514221L, 50, 200, 20512, 2085, 7, 529, 417280161591969960L, 51, 200, 22563, 6375939, 7, 558, 11300453985206678L, 52, 200, 24819, 7837057, 7, 559, 283668599967437754L, 53, 200, 27300, 6607975, 8, 561, 122183647493325363L, 54, 200, 30030, 1519191, 8, 550, 1145227891427321202L, 55, 200, 33033, 808061, 8, 568, 71070843834364939L, 56, 200, 36336, 2653529, 8, 570, 450311772805359006L, 57, 200, 39969, 2188957, 8, 561, 269670427054904115L, 58, 200, 43965, 5885655, 8, 539, 1039064186324091890L, 59, 200, 48361, 6185889, 8, 574, 178055275082387938L, 60, 200, 53197, 208767, 9, 579, 139766040442973048L, 61, 200, 58516, 2551345, 9, 569, 322655279254252950L, 62, 200, 64367, 1950873, 9, 569, 101542216315768285L, 63, 200, 70803, 2950429, 9, 582, 72294008568551853L, 64, 200, 77883, 3993977, 9, 572, 299014330559512530L, 65, 200, 85671, 428871, 9, 585, 491351721800568188L, 66, 200, 94238, 6740849, 9, 577, 656204268858348899L, 67, 200, 103661, 2315497, 9, 562, 829926273188300764L, 68, 200, 114027, 5212835, 10, 581, 542222554617639557L, 69, 200, 125429, 4213475, 10, 593, 713339189579860773L, 70, 200, 137971, 2411583, 10, 592, 649651658985845357L, 71, 200, 151768, 5243307, 10, 567, 1017459402785275179L, 72, 200, 166944, 2468367, 10, 593, 115034451827634398L, 73, 200, 183638, 2210923, 10, 583, 365735165000548572L, 74, 200, 202001, 321257, 10, 591, 928479940794929153L, 75, 200, 222201, 8185105, 11, 600, 780163958693677795L, 76, 200, 244421, 6205349, 11, 598, 132454307780236135L, 77, 200, 268863, 3165901, 11, 600, 369824066179493948L, 78, 200, 295749, 2831723, 11, 595, 80968411797441666L, 79, 200, 325323, 464193, 11, 594, 125773061716381917L, 80, 200, 357855, 7499035, 11, 576, 994150328579932916L, 81, 200, 393640, 1514479, 11, 596, 111092193875842594L, 82, 200, 433004, 668493, 12, 607, 497338041653302784L, 83, 200, 476304, 3174931, 12, 606, 845986926165673887L, 84, 200, 523934, 914611, 12, 605, 354993119685278556L, 85, 200, 576327, 7270385, 12, 602, 937679531753465428L, 86, 200, 633959, 1956979, 12, 598, 659413123921208266L, 87, 200, 697354, 3137635, 12, 606, 874228711599628459L, 88, 200, 767089, 214923, 12, 608, 1077644643342432307L, 89, 200, 843797, 3084545, 13, 612, 79317113064339979L, 90, 200, 928176, 7800899, 13, 612, 357414065779796772L, 91, 200, 1020993, 6717253, 13, 615, 532723577905833296L, 92, 200, 1123092, 5543015, 13, 614, 508695073250223746L, 93, 200, 1235401, 298785, 13, 616, 34344606952783179L, 94, 200, 1358941, 4530313, 13, 607, 169924026179364121L, 95, 200, 1494835, 4406457, 13, 612, 1026773494313671061L, 96, 200, 1644318, 1540983, 13, 614, 423454640036650614L, 97, 200, 1808749, 7999631, 14, 624, 466122870338520329L, 98, 200, 1989623, 4295537, 14, 621, 609309853701283445L, 99, 200, 2188585, 7379971, 14, 622, 141739898871015642L, 100, 200, 2407443, 6188931, 14, 621, 22515080776738923L, 101, 200, 2648187, 6701239, 14, 619, 257441864177795548L, 102, 200, 2913005, 2238709, 14, 623, 867028825821064773L, 103, 200, 3204305, 5371075, 14, 625, 1110615471273395112L, 104, 200, 3524735, 7017341, 15, 631, 619518037415974467L, 105, 200, 3877208, 323337, 15, 633, 513230912593541122L, 106, 200, 4264928, 6172471, 15, 628, 885861662583325072L, 107, 200, 4691420, 5653803, 15, 633, 754052473303005204L, 108, 200, 5160562, 1385265, 15, 630, 294993765757975100L, 109, 200, 5676618, 4350899, 15, 617, 1073144684944932303L, 110, 200, 6244279, 1272235, 15, 630, 308982934296855020L, 111, 200, 6868706, 1763939, 16, 638, 356231694823272867L, 112, 200, 7555576, 3703411, 16, 636, 20043268926300101L, 113, 200, 8311133, 6554171, 16, 637, 121111429906734123L, }; private static int[] makeInputArray(int n, int stride) { assert KllHelper.isOdd(stride); int mask = (1 << 23) - 1; // because library items are single-precision floats int cur = 0; int[] arr = new int[n]; for (int i = 0; i < n; i++) { cur += stride; cur &= mask; arr[i] = cur; } return arr; } private static long simpleHashOfSubArray(final float[] arr, final int start, final int subLength) { final long multiplier = 738219921; // an arbitrary odd 30-bit number final long mask60 = (1L << 60) - 1; long accum = 0; for (int i = start; i < start + subLength; i++) { accum += (long) arr[i]; accum *= multiplier; accum &= mask60; accum ^= accum >> 30; } return accum; } @Test public void testHash() { float[] array = { 907500, 944104, 807020, 219921, 678370, 955217, 426885 }; Assert.assertEquals(simpleHashOfSubArray(array, 1, 5), 1141543353991880193L); } @Test public void testMakeInputArray() { final int[] array = { 3654721, 7309442, 2575555, 6230276, 1496389, 5151110 }; Assert.assertEquals(makeInputArray(6, 3654721), array); } /* * Please note that this test should be run with a modified version of KllHelper * that chooses directions alternately instead of randomly. */ //@Test public void checkTestResults() { int numTests = correctResultsWithReset.length / 7; for (int testI = 0; testI < numTests; testI++) { KllHelper.nextOffset = 0; assert (int) correctResultsWithReset[7 * testI] == testI; int k = (int) correctResultsWithReset[7 * testI + 1]; int n = (int) correctResultsWithReset[7 * testI + 2]; int stride = (int) correctResultsWithReset[7 * testI + 3]; int[] inputArray = makeInputArray(n, stride); KllFloatsSketch sketch = new KllFloatsSketch(k); for (int i = 0; i < n; i++) { sketch.update(inputArray[i]); } int numLevels = sketch.getNumLevels(); int numSamples = sketch.getNumRetained(); int[] levels = sketch.getLevels(); long hashedSamples = simpleHashOfSubArray(sketch.getItems(), levels[0], numSamples); System.out.print(testI); assert correctResultsWithReset[7 * testI + 4] == numLevels; assert correctResultsWithReset[7 * testI + 5] == numSamples; //assert correctResults[7 * testI + 6] == hashedSamples; if (correctResultsWithReset[7 * testI + 6] == hashedSamples) { System.out.println(" pass"); } else { System.out.print(" " + correctResultsWithReset[7 * testI + 6] + " != " + hashedSamples); System.out.println(" fail"); System.out.println(sketch.toString(true, true)); break; } } } }
src/test/java/com/yahoo/sketches/kll/KllValidationTest.java
package com.yahoo.sketches.kll; import org.testng.Assert; import org.testng.annotations.Test; /* Please note that this test should be run with a modified version of KLL that chooses directions alternately instead of randomly. For details see the file intMerging.ml. */ /* A test record contains: 0. testIndex 1. K 2. N 3. stride (for generating the input) 4. numLevels 5. numSamples 6. hash of the retained samples */ /* These results are for the version that delays the rollup until the next value comes in. */ public class KllValidationTest { private static final long[] correctResults = { 0, 200, 180, 3246533, 1, 180, 1098352976109474698L, 1, 200, 198, 8349603, 1, 198, 686681527497651888L, 2, 200, 217, 676491, 2, 117, 495856134049157644L, 3, 200, 238, 3204507, 2, 138, 925892166244379188L, 4, 200, 261, 2459373, 2, 161, 719830627391926938L, 5, 200, 287, 5902143, 2, 187, 922808600797964238L, 6, 200, 315, 5188793, 2, 215, 985218890825795000L, 7, 200, 346, 801923, 2, 246, 599362290078799977L, 8, 200, 380, 2466269, 2, 280, 1081848693781775853L, 9, 200, 418, 5968041, 2, 318, 1056865679767133957L, 10, 200, 459, 3230027, 2, 243, 937332670315558786L, 11, 200, 504, 5125875, 2, 288, 1019197831515566845L, 12, 200, 554, 4195571, 3, 230, 797351479150148224L, 13, 200, 609, 2221181, 3, 285, 100453527456129865L, 14, 200, 669, 5865503, 3, 345, 253851269470815909L, 15, 200, 735, 831703, 3, 411, 286266734984944071L, 16, 200, 808, 4830785, 3, 327, 1032107507126916277L, 17, 200, 888, 1356257, 3, 407, 215225420986342944L, 18, 200, 976, 952071, 3, 417, 600280049738270697L, 19, 200, 1073, 6729833, 3, 397, 816002183204786896L, 20, 200, 1180, 6017925, 3, 406, 40802310002987712L, 21, 200, 1298, 4229891, 3, 401, 1092460534756675086L, 22, 200, 1427, 7264889, 4, 320, 861629484071698186L, 23, 200, 1569, 5836327, 4, 462, 660575800011134382L, 24, 200, 1725, 5950087, 4, 416, 2749030659811475L, 25, 200, 1897, 2692555, 4, 406, 607308667566496888L, 26, 200, 2086, 1512443, 4, 459, 718306179956509509L, 27, 200, 2294, 2681171, 4, 434, 199120609113802485L, 28, 200, 2523, 3726521, 4, 450, 570993497599288304L, 29, 200, 2775, 2695247, 4, 442, 709636425777623558L, 30, 200, 3052, 5751175, 5, 400, 1116178754759235213L, 31, 200, 3357, 1148897, 5, 514, 1054062479518989995L, 32, 200, 3692, 484127, 5, 457, 970986773031779651L, 33, 200, 4061, 6414559, 5, 451, 89870728775546041L, 34, 200, 4467, 5587461, 5, 466, 918747970426750879L, 35, 200, 4913, 1615017, 5, 483, 1079632976480026143L, 36, 200, 5404, 6508535, 5, 492, 858526451332425960L, 37, 200, 5944, 2991657, 5, 492, 783638545407098465L, 38, 200, 6538, 6736565, 6, 511, 1011050535742568276L, 39, 200, 7191, 1579893, 6, 507, 236606491390313069L, 40, 200, 7910, 412509, 6, 538, 570863587164194186L, 41, 200, 8701, 1112089, 6, 477, 553100668286355347L, 42, 200, 9571, 1258813, 6, 526, 344845406406036297L, 43, 200, 10528, 1980049, 6, 508, 411846569527905064L, 44, 200, 11580, 2167127, 6, 520, 583262488096572165L, 45, 200, 12738, 1975435, 7, 561, 143365748273901116L, 46, 200, 14011, 4289627, 7, 560, 753686005174215572L, 47, 200, 15412, 5384001, 7, 494, 551637841878573955L, 48, 200, 16953, 2902685, 7, 560, 94602851752354802L, 49, 200, 18648, 4806445, 7, 562, 597672400688514221L, 50, 200, 20512, 2085, 7, 529, 417280161591969960L, 51, 200, 22563, 6375939, 7, 558, 512816710736955723L, 52, 200, 24819, 7837057, 7, 559, 283668599967437754L, 53, 200, 27300, 6607975, 8, 561, 234505822935740765L, 54, 200, 30030, 1519191, 8, 550, 1145227891427321202L, 55, 200, 33033, 808061, 8, 568, 745340667560050089L, 56, 200, 36336, 2653529, 8, 570, 1142771901372520560L, 57, 200, 39969, 2188957, 8, 561, 42807878343220651L, 58, 200, 43965, 5885655, 8, 539, 265470907135768104L, 59, 200, 48361, 6185889, 8, 574, 178055275082387938L, 60, 200, 53197, 208767, 9, 579, 139766040442973048L, 61, 200, 58516, 2551345, 9, 569, 322655279254252950L, 62, 200, 64367, 1950873, 9, 569, 293408075767397113L, 63, 200, 70803, 2950429, 9, 582, 72294008568551853L, 64, 200, 77883, 3993977, 9, 572, 1096357087410425634L, 65, 200, 85671, 428871, 9, 585, 491351721800568188L, 66, 200, 94238, 6740849, 9, 577, 728498637567480595L, 67, 200, 103661, 2315497, 9, 562, 417290840592341928L, 68, 200, 114027, 5212835, 10, 581, 542222554617639557L, 69, 200, 125429, 4213475, 10, 593, 713339189579860773L, 70, 200, 137971, 2411583, 10, 592, 649651658985845357L, 71, 200, 151768, 5243307, 10, 567, 852222234486250291L, 72, 200, 166944, 2468367, 10, 593, 115034451827634398L, 73, 200, 183638, 2210923, 10, 583, 399907519423880955L, 74, 200, 202001, 321257, 10, 591, 928479940794929153L, 75, 200, 222201, 8185105, 11, 600, 780163958693677795L, 76, 200, 244421, 6205349, 11, 598, 132454307780236135L, 77, 200, 268863, 3165901, 11, 600, 850842123571583882L, 78, 200, 295749, 2831723, 11, 595, 792091177664243746L, 79, 200, 325323, 464193, 11, 594, 125773061716381917L, 80, 200, 357855, 7499035, 11, 576, 994150328579932916L, 81, 200, 393640, 1514479, 11, 596, 111092193875842594L, 82, 200, 433004, 668493, 12, 607, 472829092395324755L, 83, 200, 476304, 3174931, 12, 606, 1089178352763833216L, 84, 200, 523934, 914611, 12, 605, 575322201863013275L, 85, 200, 576327, 7270385, 12, 602, 754476234577732442L, 86, 200, 633959, 1956979, 12, 598, 984558130823541515L, 87, 200, 697354, 3137635, 12, 606, 648431915268248367L, 88, 200, 767089, 214923, 12, 608, 831559668277815062L, 89, 200, 843797, 3084545, 13, 612, 79317113064339979L, 90, 200, 928176, 7800899, 13, 612, 357414065779796772L, 91, 200, 1020993, 6717253, 13, 615, 532723577905833296L, 92, 200, 1123092, 5543015, 13, 614, 508695073250223746L, 93, 200, 1235401, 298785, 13, 616, 318983524777182162L, 94, 200, 1358941, 4530313, 13, 607, 668261825022875029L, 95, 200, 1494835, 4406457, 13, 612, 853074117050423072L, 96, 200, 1644318, 1540983, 13, 614, 423454640036650614L, 97, 200, 1808749, 7999631, 14, 624, 311031472444410705L, 98, 200, 1989623, 4295537, 14, 621, 609309853701283445L, 99, 200, 2188585, 7379971, 14, 622, 141739898871015642L, 100, 200, 2407443, 6188931, 14, 621, 22515080776738923L, 101, 200, 2648187, 6701239, 14, 619, 280015754832110288L, 102, 200, 2913005, 2238709, 14, 623, 867028825821064773L, 103, 200, 3204305, 5371075, 14, 625, 511609281729917909L, 104, 200, 3524735, 7017341, 15, 631, 619518037415974467L, 105, 200, 3877208, 323337, 15, 633, 513230912593541122L, 106, 200, 4264928, 6172471, 15, 628, 885861662583325072L, 107, 200, 4691420, 5653803, 15, 633, 754052473303005204L, 108, 200, 5160562, 1385265, 15, 630, 294993765757975100L, 109, 200, 5676618, 4350899, 15, 617, 1073144684944932303L, 110, 200, 6244279, 1272235, 15, 630, 1048761586710242423L, 111, 200, 6868706, 1763939, 16, 638, 849669745109069799L, 112, 200, 7555576, 3703411, 16, 636, 483585842503908268L, 113, 200, 8311133, 6554171, 16, 637, 121111429906734123L, }; private static final long[] correctResultsWithReset = { 0, 200, 180, 3246533, 1, 180, 1098352976109474698L, 1, 200, 198, 8349603, 1, 198, 686681527497651888L, 2, 200, 217, 676491, 2, 117, 495856134049157644L, 3, 200, 238, 3204507, 2, 138, 44453438498725402L, 4, 200, 261, 2459373, 2, 161, 719830627391926938L, 5, 200, 287, 5902143, 2, 187, 389303173170515580L, 6, 200, 315, 5188793, 2, 215, 985218890825795000L, 7, 200, 346, 801923, 2, 246, 589362992166904413L, 8, 200, 380, 2466269, 2, 280, 1081848693781775853L, 9, 200, 418, 5968041, 2, 318, 533825689515788397L, 10, 200, 459, 3230027, 2, 243, 937332670315558786L, 11, 200, 504, 5125875, 2, 288, 1019197831515566845L, 12, 200, 554, 4195571, 3, 230, 797351479150148224L, 13, 200, 609, 2221181, 3, 285, 451246040374318529L, 14, 200, 669, 5865503, 3, 345, 253851269470815909L, 15, 200, 735, 831703, 3, 411, 491974970526372303L, 16, 200, 808, 4830785, 3, 327, 1032107507126916277L, 17, 200, 888, 1356257, 3, 407, 215225420986342944L, 18, 200, 976, 952071, 3, 417, 600280049738270697L, 19, 200, 1073, 6729833, 3, 397, 341758522977365969L, 20, 200, 1180, 6017925, 3, 406, 1080227312339182949L, 21, 200, 1298, 4229891, 3, 401, 1092460534756675086L, 22, 200, 1427, 7264889, 4, 320, 884533400696890024L, 23, 200, 1569, 5836327, 4, 462, 660575800011134382L, 24, 200, 1725, 5950087, 4, 416, 669373957401387528L, 25, 200, 1897, 2692555, 4, 406, 607308667566496888L, 26, 200, 2086, 1512443, 4, 459, 744260340112029032L, 27, 200, 2294, 2681171, 4, 434, 199120609113802485L, 28, 200, 2523, 3726521, 4, 450, 570993497599288304L, 29, 200, 2775, 2695247, 4, 442, 306717093329516310L, 30, 200, 3052, 5751175, 5, 400, 256024589545754217L, 31, 200, 3357, 1148897, 5, 514, 507276662329207479L, 32, 200, 3692, 484127, 5, 457, 1082660223488175122L, 33, 200, 4061, 6414559, 5, 451, 620820308918522117L, 34, 200, 4467, 5587461, 5, 466, 121975084804459305L, 35, 200, 4913, 1615017, 5, 483, 152986529342916376L, 36, 200, 5404, 6508535, 5, 492, 858526451332425960L, 37, 200, 5944, 2991657, 5, 492, 624906434274621995L, 38, 200, 6538, 6736565, 6, 511, 589153542019036049L, 39, 200, 7191, 1579893, 6, 507, 10255312374117907L, 40, 200, 7910, 412509, 6, 538, 570863587164194186L, 41, 200, 8701, 1112089, 6, 477, 553100668286355347L, 42, 200, 9571, 1258813, 6, 526, 344845406406036297L, 43, 200, 10528, 1980049, 6, 508, 411846569527905064L, 44, 200, 11580, 2167127, 6, 520, 966876726203675488L, 45, 200, 12738, 1975435, 7, 561, 724125506920592732L, 46, 200, 14011, 4289627, 7, 560, 753686005174215572L, 47, 200, 15412, 5384001, 7, 494, 551637841878573955L, 48, 200, 16953, 2902685, 7, 560, 94602851752354802L, 49, 200, 18648, 4806445, 7, 562, 597672400688514221L, 50, 200, 20512, 2085, 7, 529, 417280161591969960L, 51, 200, 22563, 6375939, 7, 558, 11300453985206678L, 52, 200, 24819, 7837057, 7, 559, 283668599967437754L, 53, 200, 27300, 6607975, 8, 561, 122183647493325363L, 54, 200, 30030, 1519191, 8, 550, 1145227891427321202L, 55, 200, 33033, 808061, 8, 568, 71070843834364939L, 56, 200, 36336, 2653529, 8, 570, 450311772805359006L, 57, 200, 39969, 2188957, 8, 561, 269670427054904115L, 58, 200, 43965, 5885655, 8, 539, 1039064186324091890L, 59, 200, 48361, 6185889, 8, 574, 178055275082387938L, 60, 200, 53197, 208767, 9, 579, 139766040442973048L, 61, 200, 58516, 2551345, 9, 569, 322655279254252950L, 62, 200, 64367, 1950873, 9, 569, 101542216315768285L, 63, 200, 70803, 2950429, 9, 582, 72294008568551853L, 64, 200, 77883, 3993977, 9, 572, 299014330559512530L, 65, 200, 85671, 428871, 9, 585, 491351721800568188L, 66, 200, 94238, 6740849, 9, 577, 656204268858348899L, 67, 200, 103661, 2315497, 9, 562, 829926273188300764L, 68, 200, 114027, 5212835, 10, 581, 542222554617639557L, 69, 200, 125429, 4213475, 10, 593, 713339189579860773L, 70, 200, 137971, 2411583, 10, 592, 649651658985845357L, 71, 200, 151768, 5243307, 10, 567, 1017459402785275179L, 72, 200, 166944, 2468367, 10, 593, 115034451827634398L, 73, 200, 183638, 2210923, 10, 583, 365735165000548572L, 74, 200, 202001, 321257, 10, 591, 928479940794929153L, 75, 200, 222201, 8185105, 11, 600, 780163958693677795L, 76, 200, 244421, 6205349, 11, 598, 132454307780236135L, 77, 200, 268863, 3165901, 11, 600, 369824066179493948L, 78, 200, 295749, 2831723, 11, 595, 80968411797441666L, 79, 200, 325323, 464193, 11, 594, 125773061716381917L, 80, 200, 357855, 7499035, 11, 576, 994150328579932916L, 81, 200, 393640, 1514479, 11, 596, 111092193875842594L, 82, 200, 433004, 668493, 12, 607, 497338041653302784L, 83, 200, 476304, 3174931, 12, 606, 845986926165673887L, 84, 200, 523934, 914611, 12, 605, 354993119685278556L, 85, 200, 576327, 7270385, 12, 602, 937679531753465428L, 86, 200, 633959, 1956979, 12, 598, 659413123921208266L, 87, 200, 697354, 3137635, 12, 606, 874228711599628459L, 88, 200, 767089, 214923, 12, 608, 1077644643342432307L, 89, 200, 843797, 3084545, 13, 612, 79317113064339979L, 90, 200, 928176, 7800899, 13, 612, 357414065779796772L, 91, 200, 1020993, 6717253, 13, 615, 532723577905833296L, 92, 200, 1123092, 5543015, 13, 614, 508695073250223746L, 93, 200, 1235401, 298785, 13, 616, 34344606952783179L, 94, 200, 1358941, 4530313, 13, 607, 169924026179364121L, 95, 200, 1494835, 4406457, 13, 612, 1026773494313671061L, 96, 200, 1644318, 1540983, 13, 614, 423454640036650614L, 97, 200, 1808749, 7999631, 14, 624, 466122870338520329L, 98, 200, 1989623, 4295537, 14, 621, 609309853701283445L, 99, 200, 2188585, 7379971, 14, 622, 141739898871015642L, 100, 200, 2407443, 6188931, 14, 621, 22515080776738923L, 101, 200, 2648187, 6701239, 14, 619, 257441864177795548L, 102, 200, 2913005, 2238709, 14, 623, 867028825821064773L, 103, 200, 3204305, 5371075, 14, 625, 1110615471273395112L, 104, 200, 3524735, 7017341, 15, 631, 619518037415974467L, 105, 200, 3877208, 323337, 15, 633, 513230912593541122L, 106, 200, 4264928, 6172471, 15, 628, 885861662583325072L, 107, 200, 4691420, 5653803, 15, 633, 754052473303005204L, 108, 200, 5160562, 1385265, 15, 630, 294993765757975100L, 109, 200, 5676618, 4350899, 15, 617, 1073144684944932303L, 110, 200, 6244279, 1272235, 15, 630, 308982934296855020L, 111, 200, 6868706, 1763939, 16, 638, 356231694823272867L, 112, 200, 7555576, 3703411, 16, 636, 20043268926300101L, 113, 200, 8311133, 6554171, 16, 637, 121111429906734123L, }; private static int[] makeInputArray(int n, int stride) { assert KllHelper.isOdd(stride); int mask = (1 << 23) - 1; // because library items are single-precision floats int cur = 0; int[] arr = new int[n]; for (int i = 0; i < n; i++) { cur += stride; cur &= mask; arr[i] = cur; } return arr; } private static long simpleHashOfSubArray(final float[] arr, final int start, final int subLength) { final long multiplier = 738219921; // an arbitrary odd 30-bit number final long mask60 = (1L << 60) - 1; long accum = 0; for (int i = start; i < start + subLength; i++) { accum += (long) arr[i]; accum *= multiplier; accum &= mask60; accum ^= accum >> 30; } return accum; } @Test public void testHash() { float[] array = { 907500, 944104, 807020, 219921, 678370, 955217, 426885 }; Assert.assertEquals(simpleHashOfSubArray(array, 1, 5), 1141543353991880193L); } @Test public void testMakeInputArray() { final int[] array = { 3654721, 7309442, 2575555, 6230276, 1496389, 5151110 }; Assert.assertEquals(makeInputArray(6, 3654721), array); } //@Test public void checkTestResults() { int numTests = correctResultsWithReset.length / 7; for (int testI = 0; testI < numTests; testI++) { KllHelper.nextOffset = 0; assert (int) correctResultsWithReset[7 * testI] == testI; int k = (int) correctResultsWithReset[7 * testI + 1]; int n = (int) correctResultsWithReset[7 * testI + 2]; int stride = (int) correctResultsWithReset[7 * testI + 3]; int[] inputArray = makeInputArray(n, stride); KllFloatsSketch sketch = new KllFloatsSketch(k); for (int i = 0; i < n; i++) { sketch.update(inputArray[i]); } int numLevels = sketch.getNumLevels(); int numSamples = sketch.getNumRetained(); int[] levels = sketch.getLevels(); long hashedSamples = simpleHashOfSubArray(sketch.getItems(), levels[0], numSamples); System.out.print(testI); assert correctResultsWithReset[7 * testI + 4] == numLevels; assert correctResultsWithReset[7 * testI + 5] == numSamples; //assert correctResults[7 * testI + 6] == hashedSamples; if (correctResultsWithReset[7 * testI + 6] == hashedSamples) { System.out.println(" pass"); } else { System.out.print(" " + correctResultsWithReset[7 * testI + 6] + " != " + hashedSamples); System.out.println(" fail"); System.out.println(sketch.toString(true, true)); break; } } } }
removed unused data, moved comment for clarity
src/test/java/com/yahoo/sketches/kll/KllValidationTest.java
removed unused data, moved comment for clarity
<ide><path>rc/test/java/com/yahoo/sketches/kll/KllValidationTest.java <ide> <ide> import org.testng.Assert; <ide> import org.testng.annotations.Test; <del> <del>/* Please note that this test should be run with a modified version of KLL <del> that chooses directions alternately instead of randomly. <del> <del> For details see the file intMerging.ml. <del>*/ <ide> <ide> /* A test record contains: <ide> 0. testIndex <ide> <ide> /* These results are for the version that delays the rollup until the next value comes in. */ <ide> <del> <ide> public class KllValidationTest { <del> <del> private static final long[] correctResults = { <del> 0, 200, 180, 3246533, 1, 180, 1098352976109474698L, <del> 1, 200, 198, 8349603, 1, 198, 686681527497651888L, <del> 2, 200, 217, 676491, 2, 117, 495856134049157644L, <del> 3, 200, 238, 3204507, 2, 138, 925892166244379188L, <del> 4, 200, 261, 2459373, 2, 161, 719830627391926938L, <del> 5, 200, 287, 5902143, 2, 187, 922808600797964238L, <del> 6, 200, 315, 5188793, 2, 215, 985218890825795000L, <del> 7, 200, 346, 801923, 2, 246, 599362290078799977L, <del> 8, 200, 380, 2466269, 2, 280, 1081848693781775853L, <del> 9, 200, 418, 5968041, 2, 318, 1056865679767133957L, <del> 10, 200, 459, 3230027, 2, 243, 937332670315558786L, <del> 11, 200, 504, 5125875, 2, 288, 1019197831515566845L, <del> 12, 200, 554, 4195571, 3, 230, 797351479150148224L, <del> 13, 200, 609, 2221181, 3, 285, 100453527456129865L, <del> 14, 200, 669, 5865503, 3, 345, 253851269470815909L, <del> 15, 200, 735, 831703, 3, 411, 286266734984944071L, <del> 16, 200, 808, 4830785, 3, 327, 1032107507126916277L, <del> 17, 200, 888, 1356257, 3, 407, 215225420986342944L, <del> 18, 200, 976, 952071, 3, 417, 600280049738270697L, <del> 19, 200, 1073, 6729833, 3, 397, 816002183204786896L, <del> 20, 200, 1180, 6017925, 3, 406, 40802310002987712L, <del> 21, 200, 1298, 4229891, 3, 401, 1092460534756675086L, <del> 22, 200, 1427, 7264889, 4, 320, 861629484071698186L, <del> 23, 200, 1569, 5836327, 4, 462, 660575800011134382L, <del> 24, 200, 1725, 5950087, 4, 416, 2749030659811475L, <del> 25, 200, 1897, 2692555, 4, 406, 607308667566496888L, <del> 26, 200, 2086, 1512443, 4, 459, 718306179956509509L, <del> 27, 200, 2294, 2681171, 4, 434, 199120609113802485L, <del> 28, 200, 2523, 3726521, 4, 450, 570993497599288304L, <del> 29, 200, 2775, 2695247, 4, 442, 709636425777623558L, <del> 30, 200, 3052, 5751175, 5, 400, 1116178754759235213L, <del> 31, 200, 3357, 1148897, 5, 514, 1054062479518989995L, <del> 32, 200, 3692, 484127, 5, 457, 970986773031779651L, <del> 33, 200, 4061, 6414559, 5, 451, 89870728775546041L, <del> 34, 200, 4467, 5587461, 5, 466, 918747970426750879L, <del> 35, 200, 4913, 1615017, 5, 483, 1079632976480026143L, <del> 36, 200, 5404, 6508535, 5, 492, 858526451332425960L, <del> 37, 200, 5944, 2991657, 5, 492, 783638545407098465L, <del> 38, 200, 6538, 6736565, 6, 511, 1011050535742568276L, <del> 39, 200, 7191, 1579893, 6, 507, 236606491390313069L, <del> 40, 200, 7910, 412509, 6, 538, 570863587164194186L, <del> 41, 200, 8701, 1112089, 6, 477, 553100668286355347L, <del> 42, 200, 9571, 1258813, 6, 526, 344845406406036297L, <del> 43, 200, 10528, 1980049, 6, 508, 411846569527905064L, <del> 44, 200, 11580, 2167127, 6, 520, 583262488096572165L, <del> 45, 200, 12738, 1975435, 7, 561, 143365748273901116L, <del> 46, 200, 14011, 4289627, 7, 560, 753686005174215572L, <del> 47, 200, 15412, 5384001, 7, 494, 551637841878573955L, <del> 48, 200, 16953, 2902685, 7, 560, 94602851752354802L, <del> 49, 200, 18648, 4806445, 7, 562, 597672400688514221L, <del> 50, 200, 20512, 2085, 7, 529, 417280161591969960L, <del> 51, 200, 22563, 6375939, 7, 558, 512816710736955723L, <del> 52, 200, 24819, 7837057, 7, 559, 283668599967437754L, <del> 53, 200, 27300, 6607975, 8, 561, 234505822935740765L, <del> 54, 200, 30030, 1519191, 8, 550, 1145227891427321202L, <del> 55, 200, 33033, 808061, 8, 568, 745340667560050089L, <del> 56, 200, 36336, 2653529, 8, 570, 1142771901372520560L, <del> 57, 200, 39969, 2188957, 8, 561, 42807878343220651L, <del> 58, 200, 43965, 5885655, 8, 539, 265470907135768104L, <del> 59, 200, 48361, 6185889, 8, 574, 178055275082387938L, <del> 60, 200, 53197, 208767, 9, 579, 139766040442973048L, <del> 61, 200, 58516, 2551345, 9, 569, 322655279254252950L, <del> 62, 200, 64367, 1950873, 9, 569, 293408075767397113L, <del> 63, 200, 70803, 2950429, 9, 582, 72294008568551853L, <del> 64, 200, 77883, 3993977, 9, 572, 1096357087410425634L, <del> 65, 200, 85671, 428871, 9, 585, 491351721800568188L, <del> 66, 200, 94238, 6740849, 9, 577, 728498637567480595L, <del> 67, 200, 103661, 2315497, 9, 562, 417290840592341928L, <del> 68, 200, 114027, 5212835, 10, 581, 542222554617639557L, <del> 69, 200, 125429, 4213475, 10, 593, 713339189579860773L, <del> 70, 200, 137971, 2411583, 10, 592, 649651658985845357L, <del> 71, 200, 151768, 5243307, 10, 567, 852222234486250291L, <del> 72, 200, 166944, 2468367, 10, 593, 115034451827634398L, <del> 73, 200, 183638, 2210923, 10, 583, 399907519423880955L, <del> 74, 200, 202001, 321257, 10, 591, 928479940794929153L, <del> 75, 200, 222201, 8185105, 11, 600, 780163958693677795L, <del> 76, 200, 244421, 6205349, 11, 598, 132454307780236135L, <del> 77, 200, 268863, 3165901, 11, 600, 850842123571583882L, <del> 78, 200, 295749, 2831723, 11, 595, 792091177664243746L, <del> 79, 200, 325323, 464193, 11, 594, 125773061716381917L, <del> 80, 200, 357855, 7499035, 11, 576, 994150328579932916L, <del> 81, 200, 393640, 1514479, 11, 596, 111092193875842594L, <del> 82, 200, 433004, 668493, 12, 607, 472829092395324755L, <del> 83, 200, 476304, 3174931, 12, 606, 1089178352763833216L, <del> 84, 200, 523934, 914611, 12, 605, 575322201863013275L, <del> 85, 200, 576327, 7270385, 12, 602, 754476234577732442L, <del> 86, 200, 633959, 1956979, 12, 598, 984558130823541515L, <del> 87, 200, 697354, 3137635, 12, 606, 648431915268248367L, <del> 88, 200, 767089, 214923, 12, 608, 831559668277815062L, <del> 89, 200, 843797, 3084545, 13, 612, 79317113064339979L, <del> 90, 200, 928176, 7800899, 13, 612, 357414065779796772L, <del> 91, 200, 1020993, 6717253, 13, 615, 532723577905833296L, <del> 92, 200, 1123092, 5543015, 13, 614, 508695073250223746L, <del> 93, 200, 1235401, 298785, 13, 616, 318983524777182162L, <del> 94, 200, 1358941, 4530313, 13, 607, 668261825022875029L, <del> 95, 200, 1494835, 4406457, 13, 612, 853074117050423072L, <del> 96, 200, 1644318, 1540983, 13, 614, 423454640036650614L, <del> 97, 200, 1808749, 7999631, 14, 624, 311031472444410705L, <del> 98, 200, 1989623, 4295537, 14, 621, 609309853701283445L, <del> 99, 200, 2188585, 7379971, 14, 622, 141739898871015642L, <del> 100, 200, 2407443, 6188931, 14, 621, 22515080776738923L, <del> 101, 200, 2648187, 6701239, 14, 619, 280015754832110288L, <del> 102, 200, 2913005, 2238709, 14, 623, 867028825821064773L, <del> 103, 200, 3204305, 5371075, 14, 625, 511609281729917909L, <del> 104, 200, 3524735, 7017341, 15, 631, 619518037415974467L, <del> 105, 200, 3877208, 323337, 15, 633, 513230912593541122L, <del> 106, 200, 4264928, 6172471, 15, 628, 885861662583325072L, <del> 107, 200, 4691420, 5653803, 15, 633, 754052473303005204L, <del> 108, 200, 5160562, 1385265, 15, 630, 294993765757975100L, <del> 109, 200, 5676618, 4350899, 15, 617, 1073144684944932303L, <del> 110, 200, 6244279, 1272235, 15, 630, 1048761586710242423L, <del> 111, 200, 6868706, 1763939, 16, 638, 849669745109069799L, <del> 112, 200, 7555576, 3703411, 16, 636, 483585842503908268L, <del> 113, 200, 8311133, 6554171, 16, 637, 121111429906734123L, <del> }; <ide> <ide> private static final long[] correctResultsWithReset = { <ide> 0, 200, 180, 3246533, 1, 180, 1098352976109474698L, <ide> Assert.assertEquals(makeInputArray(6, 3654721), array); <ide> } <ide> <add> /* <add> * Please note that this test should be run with a modified version of KllHelper <add> * that chooses directions alternately instead of randomly. <add> */ <add> <ide> //@Test <ide> public void checkTestResults() { <ide> int numTests = correctResultsWithReset.length / 7;
Java
mit
ded0e545d92c952fd9574381413fd1134fbeb1b9
0
blay09/CookingForBlockheads
package net.blay09.mods.cookingforblockheads; import net.blay09.mods.cookingforblockheads.block.ModBlocks; import net.blay09.mods.cookingforblockheads.item.ModItems; import net.minecraft.init.Blocks; import net.minecraft.init.Items; import net.minecraft.item.ItemStack; import net.minecraftforge.common.config.Configuration; import net.minecraftforge.fml.common.registry.GameRegistry; import net.minecraftforge.oredict.OreDictionary; import net.minecraftforge.oredict.ShapedOreRecipe; import net.minecraftforge.oredict.ShapelessOreRecipe; public class ModRecipes { public static void load(Configuration config) { boolean noFilterEdition = config.getBoolean("NoFilter Edition", "items", true, ""); boolean craftingEdition = config.getBoolean("Cooking for Blockheads II", "items", true, ""); // #NoFilter Edition if(noFilterEdition) { GameRegistry.addShapelessRecipe(new ItemStack(ModItems.recipeBook, 1, 0), new ItemStack(ModItems.recipeBook, 1, 1)); } // Cooking for Blockheads I if(config.getBoolean("Cooking for Blockheads I", "items", true, "")) { GameRegistry.addSmelting(Items.BOOK, new ItemStack(ModItems.recipeBook, 1, 1), 0f); if (noFilterEdition) { GameRegistry.addShapelessRecipe(new ItemStack(ModItems.recipeBook, 1, 1), new ItemStack(ModItems.recipeBook, 1, 0)); } } // Cooking for Blockheads II if(craftingEdition) { GameRegistry.addRecipe(new ItemStack(ModItems.recipeBook, 1, 2), " D ", "CBC", " D ", 'C', Blocks.CRAFTING_TABLE, 'D', Items.DIAMOND, 'B', new ItemStack(ModItems.recipeBook, 1, 1)); GameRegistry.addRecipe(new ItemStack(ModItems.recipeBook, 1, 2), " C ", "DBD", " C ", 'C', Blocks.CRAFTING_TABLE, 'D', Items.DIAMOND, 'B', new ItemStack(ModItems.recipeBook, 1, 1)); } // Fridge if(config.getBoolean("Fridge", "blocks", true, "")) { GameRegistry.addShapelessRecipe(new ItemStack(ModBlocks.fridge), Blocks.CHEST, Items.IRON_DOOR); } // Sink if(config.getBoolean("Sink", "blocks", true, "")) { GameRegistry.addRecipe(new ShapedOreRecipe(new ItemStack(ModBlocks.sink), "III", "WBW", "WWW", 'I', "ingotIron", 'W', "logWood", 'B', Items.WATER_BUCKET)); } // Toaster if(config.getBoolean("Toaster", "blocks", true, "")) { GameRegistry.addRecipe(new ShapedOreRecipe(new ItemStack(ModBlocks.toaster), " B", "IDI", "ILI", 'I', "ingotIron", 'B', Blocks.STONE_BUTTON, 'D', Blocks.IRON_TRAPDOOR, 'L', Items.LAVA_BUCKET)); } // Spice Rack if(config.getBoolean("Spice Rack", "blocks", true, "")) { GameRegistry.addRecipe(new ShapelessOreRecipe(new ItemStack(ModBlocks.spiceRack), "slabWood")); } // Milk Jar if(config.getBoolean("Milk Jar", "blocks", true, "")) { GameRegistry.addRecipe(new ShapedOreRecipe(new ItemStack(ModBlocks.milkJar), "GPG", "GMG", "GGG", 'G', "blockGlass", 'P', "plankWood", 'M', Items.MILK_BUCKET)); } // Cooking Table if(config.getBoolean("Cooking Table", "blocks", true, "")) { if(craftingEdition) { GameRegistry.addRecipe(new ShapedOreRecipe(new ItemStack(ModBlocks.cookingTable), "CCC", "WBW", "WWW", 'B', new ItemStack(ModItems.recipeBook, 1, 2), 'W', "logWood", 'C', new ItemStack(Blocks.STAINED_HARDENED_CLAY, 1, 15))); } else { GameRegistry.addRecipe(new ShapedOreRecipe(new ItemStack(ModBlocks.cookingTable), "CCC", "WBW", "WWW", 'B', Items.BOOK, 'W', "logWood", 'C', new ItemStack(Blocks.STAINED_HARDENED_CLAY, 1, 15))); } } // Kitchen Counter if(config.getBoolean("Kitchen Counter", "blocks", true, "")) { GameRegistry.addRecipe(new ShapedOreRecipe(new ItemStack(ModBlocks.counter), "B", "C", 'B', new ItemStack(Blocks.STAINED_HARDENED_CLAY, 1, 15), 'C', Blocks.CHEST)); } // Cooking Oven if(config.getBoolean("Cooking Oven", "blocks", true, "")) { GameRegistry.addRecipe(new ShapedOreRecipe(new ItemStack(ModBlocks.oven), "GGG", "IFI", "III", 'G', new ItemStack(Blocks.STAINED_GLASS, 1, 15), 'I', "ingotIron", 'F', Blocks.FURNACE)); } // Tool Rack if(config.getBoolean("Tool Rack", "blocks", true, "")) { if(OreDictionary.getOres("nuggetIron", false).size() > 0) { GameRegistry.addRecipe(new ShapedOreRecipe(new ItemStack(ModBlocks.toolRack), "SSS", "I I", 'S', "slabWood", 'I', "nuggetIron")); } else { GameRegistry.addRecipe(new ShapedOreRecipe(new ItemStack(ModBlocks.toolRack), "SSS", "I I", 'S', "slabWood", 'I', Blocks.STONE_BUTTON)); } } } }
src/main/java/net/blay09/mods/cookingforblockheads/ModRecipes.java
package net.blay09.mods.cookingforblockheads; import net.blay09.mods.cookingforblockheads.block.ModBlocks; import net.blay09.mods.cookingforblockheads.item.ModItems; import net.minecraft.init.Blocks; import net.minecraft.init.Items; import net.minecraft.item.ItemStack; import net.minecraftforge.common.config.Configuration; import net.minecraftforge.fml.common.registry.GameRegistry; import net.minecraftforge.oredict.OreDictionary; import net.minecraftforge.oredict.ShapedOreRecipe; import net.minecraftforge.oredict.ShapelessOreRecipe; public class ModRecipes { public static void load(Configuration config) { boolean noFilterEdition = config.getBoolean("NoFilter Edition", "items", true, ""); boolean craftingEdition = config.getBoolean("Cooking for Blockheads II", "items", true, ""); // #NoFilter Edition if(noFilterEdition) { GameRegistry.addShapelessRecipe(new ItemStack(ModItems.recipeBook, 1, 0), new ItemStack(ModItems.recipeBook, 1, 1)); } // Cooking for Blockheads I if(config.getBoolean("Cooking for Blockheads I", "items", true, "")) { GameRegistry.addSmelting(Items.BOOK, new ItemStack(ModItems.recipeBook, 1, 1), 0f); if (noFilterEdition) { GameRegistry.addShapelessRecipe(new ItemStack(ModItems.recipeBook, 1, 1), new ItemStack(ModItems.recipeBook, 1, 0)); } } // Cooking for Blockheads II if(craftingEdition) { GameRegistry.addRecipe(new ItemStack(ModItems.recipeBook, 1, 2), " D ", "CBC", " D ", 'C', Blocks.CRAFTING_TABLE, 'D', Items.DIAMOND, 'B', new ItemStack(ModItems.recipeBook, 1, 1)); GameRegistry.addRecipe(new ItemStack(ModItems.recipeBook, 1, 2), " C ", "DBD", " C ", 'C', Blocks.CRAFTING_TABLE, 'D', Items.DIAMOND, 'B', new ItemStack(ModItems.recipeBook, 1, 1)); } // Fridge if(config.getBoolean("Fridge", "blocks", true, "")) { GameRegistry.addShapelessRecipe(new ItemStack(ModBlocks.fridge), Blocks.CHEST, Items.IRON_DOOR); } // Sink if(config.getBoolean("Sink", "blocks", true, "")) { GameRegistry.addRecipe(new ShapedOreRecipe(new ItemStack(ModBlocks.sink), "III", "WBW", "WWW", 'I', "ingotIron", 'W', "logWood", 'B', Items.WATER_BUCKET)); } // Toaster if(config.getBoolean("Toaster", "blocks", true, "")) { GameRegistry.addRecipe(new ShapedOreRecipe(new ItemStack(ModBlocks.toaster), " B", "IDI", "ILI", 'I', "ingotIron", 'B', Blocks.STONE_BUTTON, 'D', Blocks.IRON_TRAPDOOR, 'L', Items.LAVA_BUCKET)); } // Spice Rack if(config.getBoolean("Spice Rack", "blocks", true, "")) { GameRegistry.addRecipe(new ShapelessOreRecipe(new ItemStack(ModBlocks.spiceRack), "slabWood")); } // Milk Jar if(config.getBoolean("Milk Jar", "blocks", true, "")) { GameRegistry.addRecipe(new ShapedOreRecipe(new ItemStack(ModBlocks.milkJar), "GPG", "GMG", "GGG", 'G', "blockGlass", 'P', "plankWood", 'M', Items.MILK_BUCKET)); } // Cooking Table if(config.getBoolean("Cooking Table", "blocks", true, "")) { if(craftingEdition) { GameRegistry.addRecipe(new ShapedOreRecipe(new ItemStack(ModBlocks.cookingTable), "CCC", "WBW", "WWW", 'B', new ItemStack(ModItems.recipeBook, 1, 2), 'W', "logWood", 'C', new ItemStack(Blocks.STAINED_HARDENED_CLAY, 1, 15))); } else { GameRegistry.addRecipe(new ShapedOreRecipe(new ItemStack(ModBlocks.cookingTable), "CCC", "WBW", "WWW", 'B', Items.BOOK, 'W', "logWood", 'C', new ItemStack(Blocks.STAINED_HARDENED_CLAY, 1, 15))); } } // Kitchen Counter if(config.getBoolean("Kitchen Counter", "blocks", true, "")) { GameRegistry.addRecipe(new ShapedOreRecipe(new ItemStack(ModBlocks.cookingTable), "B", "C", 'B', new ItemStack(Blocks.STAINED_HARDENED_CLAY, 1, 15), 'C', Blocks.CHEST)); } // Cooking Oven if(config.getBoolean("Cooking Oven", "blocks", true, "")) { GameRegistry.addRecipe(new ShapedOreRecipe(new ItemStack(ModBlocks.oven), "GGG", "IFI", "III", 'G', new ItemStack(Blocks.STAINED_GLASS, 1, 15), 'I', "ingotIron", 'F', Blocks.FURNACE)); } // Tool Rack if(config.getBoolean("Tool Rack", "blocks", true, "")) { if(OreDictionary.getOres("nuggetIron", false).size() > 0) { GameRegistry.addRecipe(new ShapedOreRecipe(new ItemStack(ModBlocks.toolRack), "SSS", "I I", 'S', "slabWood", 'I', "nuggetIron")); } else { GameRegistry.addRecipe(new ShapedOreRecipe(new ItemStack(ModBlocks.toolRack), "SSS", "I I", 'S', "slabWood", 'I', Blocks.STONE_BUTTON)); } } } }
Fix kitchen counter recipe resulting in a cooking table.
src/main/java/net/blay09/mods/cookingforblockheads/ModRecipes.java
Fix kitchen counter recipe resulting in a cooking table.
<ide><path>rc/main/java/net/blay09/mods/cookingforblockheads/ModRecipes.java <ide> <ide> // Kitchen Counter <ide> if(config.getBoolean("Kitchen Counter", "blocks", true, "")) { <del> GameRegistry.addRecipe(new ShapedOreRecipe(new ItemStack(ModBlocks.cookingTable), "B", "C", 'B', new ItemStack(Blocks.STAINED_HARDENED_CLAY, 1, 15), 'C', Blocks.CHEST)); <add> GameRegistry.addRecipe(new ShapedOreRecipe(new ItemStack(ModBlocks.counter), "B", "C", 'B', new ItemStack(Blocks.STAINED_HARDENED_CLAY, 1, 15), 'C', Blocks.CHEST)); <ide> } <ide> <ide> // Cooking Oven
Java
bsd-3-clause
d23ed7200eeb3a9f944564ed43b2b4fbc24dd29c
0
uw-dims/tupelo,uw-dims/tupelo,uw-dims/tupelo,uw-dims/tupelo,uw-dims/tupelo
package edu.uw.apl.tupelo.utils; import java.io.File; import java.io.FileInputStream; import java.io.InputStream; import java.io.IOException; import java.util.Properties; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; /** * Class for getting application properties. <br> * * It checks the JVM arguments, files ~/.tupelo and /etc/tupelo.prp, and a classpath resource /tupelo.prp file, in that order. <br> * * JVM args are specified by using -Dtupelo.&lt;Property Name>=&lt;Value> */ public class Discovery { static final Log log = LogFactory.getLog( Discovery.class ); /** Locate a property value given a property name. We look in four places for the properties 'file', in this order: <br> 1: Specified as JVM arguments, prefixed with tupelo.* (Example: -Dtupelo.store=./test-store) <br> 2: In a real file name $(HOME)/.tupelo <br> 3: In a real file name /etc/tupelo.prp <br> 4: In a resource (classpath-based) named /tupelo.prp <br> The first match wins. <br> It is expected that applications can also override this discovery mechanism via e.g. cmd line options. */ static public String locatePropertyValue( String prpName ) { String result = null; // Search 1: System property result = System.getProperty("tupelo."+prpName); // Search 2: a fixed file = $HOME/.tupelo if( result == null ) { String userHome = System.getProperty( "user.home" ); File dir = new File( userHome ); File f = new File( dir, ".tupelo" ); if( f.isFile() && f.canRead() ) { log.info( "Searching in file " + f + " for property " + prpName ); try { FileInputStream fis = new FileInputStream( f ); Properties p = new Properties(); p.load( fis ); fis.close(); result = p.getProperty( prpName ); log.info( "Located " + result ); } catch( IOException ioe ) { log.info( ioe ); } } } // Search 3: file = /etc/tupelo.prp if(result == null){ File f = new File("/etc/tupelo.prp"); if(f.isFile() && f.canRead()){ log.info("Searching in file "+f+" for property "+prpName); try { FileInputStream fis = new FileInputStream(f); Properties p = new Properties(); p.load(fis); result = p.getProperty(prpName); log.info("Located "+result); } catch(Exception e){ log.info(e); } } } // Search 4: a classpath resource if( result == null ) { InputStream is = Discovery.class.getResourceAsStream ( "/tupelo.prp" ); if( is != null ) { try { log.info( "Searching in resource for property " + prpName ); Properties p = new Properties(); p.load( is ); result = p.getProperty( prpName ); log.info( "Located " + result ); is.close(); } catch( IOException ioe ) { log.info( ioe ); } } } return result; } } // eof
utils/src/main/java/edu/uw/apl/tupelo/utils/Discovery.java
package edu.uw.apl.tupelo.utils; import java.io.File; import java.io.FileInputStream; import java.io.InputStream; import java.io.IOException; import java.util.Properties; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; public class Discovery { static final Log log = LogFactory.getLog( Discovery.class ); /* Locate a property value given a property name. We look in two places for the properties 'file', in this order: 1: In a real file name $(HOME)/.tupelo 2: In a resource (classpath-based) named /tupelo.prp The first match wins. It is expected that applications can also override this discovery mechanism via e.g. cmd line options. */ static public String locatePropertyValue( String prpName ) { String result = null; // Search 1: a fixed file = $HOME/.tupelo if( result == null ) { String userHome = System.getProperty( "user.home" ); File dir = new File( userHome ); File f = new File( dir, ".tupelo" ); if( f.isFile() && f.canRead() ) { log.info( "Searching in file " + f + " for property " + prpName ); try { FileInputStream fis = new FileInputStream( f ); Properties p = new Properties(); p.load( fis ); fis.close(); result = p.getProperty( prpName ); log.info( "Located " + result ); } catch( IOException ioe ) { log.info( ioe ); } } } // Search 2: a fixed resource if( result == null ) { InputStream is = Discovery.class.getResourceAsStream ( "/tupelo.prp" ); if( is != null ) { try { log.info( "Searching in resource for property " + prpName ); Properties p = new Properties(); p.load( is ); result = p.getProperty( prpName ); log.info( "Located " + result ); is.close(); } catch( IOException ioe ) { log.info( ioe ); } } } return result; } } // eof
Update the Discovery class to cehck/etc/tupelo.prp and JVM args
utils/src/main/java/edu/uw/apl/tupelo/utils/Discovery.java
Update the Discovery class to cehck/etc/tupelo.prp and JVM args
<ide><path>tils/src/main/java/edu/uw/apl/tupelo/utils/Discovery.java <ide> import org.apache.commons.logging.Log; <ide> import org.apache.commons.logging.LogFactory; <ide> <add>/** <add> * Class for getting application properties. <br> <add> * <add> * It checks the JVM arguments, files ~/.tupelo and /etc/tupelo.prp, and a classpath resource /tupelo.prp file, in that order. <br> <add> * <add> * JVM args are specified by using -Dtupelo.&lt;Property Name>=&lt;Value> <add> */ <ide> public class Discovery { <del> <ide> static final Log log = LogFactory.getLog( Discovery.class ); <ide> <del> /* <del> Locate a property value given a property name. We look in two places <del> for the properties 'file', in this order: <add> /** <add> Locate a property value given a property name. We look in four places <add> for the properties 'file', in this order: <br> <ide> <del> 1: In a real file name $(HOME)/.tupelo <add> 1: Specified as JVM arguments, prefixed with tupelo.* (Example: -Dtupelo.store=./test-store) <br> <ide> <del> 2: In a resource (classpath-based) named /tupelo.prp <add> 2: In a real file name $(HOME)/.tupelo <br> <ide> <del> The first match wins. <add> 3: In a real file name /etc/tupelo.prp <br> <add> <add> 4: In a resource (classpath-based) named /tupelo.prp <br> <add> <add> The first match wins. <br> <ide> <ide> It is expected that applications can also override this discovery <ide> mechanism via e.g. cmd line options. <ide> */ <del> <ide> static public String locatePropertyValue( String prpName ) { <ide> <ide> String result = null; <ide> <del> // Search 1: a fixed file = $HOME/.tupelo <add> // Search 1: System property <add> result = System.getProperty("tupelo."+prpName); <add> <add> // Search 2: a fixed file = $HOME/.tupelo <ide> if( result == null ) { <ide> String userHome = System.getProperty( "user.home" ); <ide> File dir = new File( userHome ); <ide> } <ide> } <ide> <del> // Search 2: a fixed resource <add> // Search 3: file = /etc/tupelo.prp <add> if(result == null){ <add> File f = new File("/etc/tupelo.prp"); <add> if(f.isFile() && f.canRead()){ <add> log.info("Searching in file "+f+" for property "+prpName); <add> try { <add> FileInputStream fis = new FileInputStream(f); <add> Properties p = new Properties(); <add> p.load(fis); <add> result = p.getProperty(prpName); <add> log.info("Located "+result); <add> } catch(Exception e){ <add> log.info(e); <add> } <add> } <add> } <add> <add> // Search 4: a classpath resource <ide> if( result == null ) { <ide> InputStream is = Discovery.class.getResourceAsStream <ide> ( "/tupelo.prp" );
Java
apache-2.0
615570c4b0a29df6bba485ee49de9a2d69d9e11b
0
ham1/jmeter,etnetera/jmeter,benbenw/jmeter,apache/jmeter,apache/jmeter,benbenw/jmeter,etnetera/jmeter,ham1/jmeter,benbenw/jmeter,apache/jmeter,etnetera/jmeter,ham1/jmeter,benbenw/jmeter,apache/jmeter,apache/jmeter,etnetera/jmeter,ham1/jmeter,ham1/jmeter,etnetera/jmeter
/* * 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. * */ package org.apache.jmeter.protocol.jdbc; import java.io.IOException; import java.io.InputStream; import java.io.Reader; import java.io.UnsupportedEncodingException; import java.lang.reflect.Field; import java.math.BigDecimal; import java.nio.charset.StandardCharsets; import java.sql.Blob; import java.sql.CallableStatement; import java.sql.Clob; import java.sql.Connection; import java.sql.Date; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.ResultSetMetaData; import java.sql.SQLException; import java.sql.Statement; import java.sql.Time; import java.sql.Timestamp; import java.sql.Types; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import org.apache.commons.io.IOUtils; import org.apache.commons.lang3.StringUtils; import org.apache.jmeter.samplers.SampleResult; import org.apache.jmeter.save.CSVSaveService; import org.apache.jmeter.testelement.AbstractTestElement; import org.apache.jmeter.testelement.TestStateListener; import org.apache.jmeter.threads.JMeterVariables; import org.apache.jmeter.util.JMeterUtils; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * A base class for all JDBC test elements handling the basics of a SQL request. * */ public abstract class AbstractJDBCTestElement extends AbstractTestElement implements TestStateListener{ private static final long serialVersionUID = 235L; private static final Logger log = LoggerFactory.getLogger(AbstractJDBCTestElement.class); private static final String COMMA = ","; // $NON-NLS-1$ private static final char COMMA_CHAR = ','; private static final String UNDERSCORE = "_"; // $NON-NLS-1$ // String used to indicate a null value private static final String NULL_MARKER = JMeterUtils.getPropDefault("jdbcsampler.nullmarker","]NULL["); // $NON-NLS-1$ private static final String INOUT = "INOUT"; // $NON-NLS-1$ private static final String OUT = "OUT"; // $NON-NLS-1$ // TODO - should the encoding be configurable? protected static final String ENCODING = StandardCharsets.UTF_8.name(); // key: name (lowercase) from java.sql.Types; entry: corresponding int value private static final Map<String, Integer> mapJdbcNameToInt; // read-only after class init static { // based on e291. Getting the Name of a JDBC Type from javaalmanac.com // http://javaalmanac.com/egs/java.sql/JdbcInt2Str.html mapJdbcNameToInt = new HashMap<>(); //Get all fields in java.sql.Types and store the corresponding int values Field[] fields = java.sql.Types.class.getFields(); for (Field field : fields) { try { String name = field.getName(); Integer value = (Integer) field.get(null); mapJdbcNameToInt.put(name.toLowerCase(java.util.Locale.ENGLISH), value); } catch (IllegalAccessException e) { throw new RuntimeException(e); // should not happen } } } // Query types (used to communicate with GUI) // N.B. These must not be changed, as they are used in the JMX files static final String SELECT = "Select Statement"; // $NON-NLS-1$ static final String UPDATE = "Update Statement"; // $NON-NLS-1$ static final String CALLABLE = "Callable Statement"; // $NON-NLS-1$ static final String PREPARED_SELECT = "Prepared Select Statement"; // $NON-NLS-1$ static final String PREPARED_UPDATE = "Prepared Update Statement"; // $NON-NLS-1$ static final String COMMIT = "Commit"; // $NON-NLS-1$ static final String ROLLBACK = "Rollback"; // $NON-NLS-1$ static final String AUTOCOMMIT_FALSE = "AutoCommit(false)"; // $NON-NLS-1$ static final String AUTOCOMMIT_TRUE = "AutoCommit(true)"; // $NON-NLS-1$ static final String RS_STORE_AS_STRING = "Store as String"; // $NON-NLS-1$ static final String RS_STORE_AS_OBJECT = "Store as Object"; // $NON-NLS-1$ static final String RS_COUNT_RECORDS = "Count Records"; // $NON-NLS-1$ private String query = ""; // $NON-NLS-1$ private String dataSource = ""; // $NON-NLS-1$ private String queryType = SELECT; private String queryArguments = ""; // $NON-NLS-1$ private String queryArgumentsTypes = ""; // $NON-NLS-1$ private String variableNames = ""; // $NON-NLS-1$ private String resultSetHandler = RS_STORE_AS_STRING; private String resultVariable = ""; // $NON-NLS-1$ private String queryTimeout = ""; // $NON-NLS-1$ private static final int MAX_RETAIN_SIZE = JMeterUtils.getPropDefault("jdbcsampler.max_retain_result_size", 64 * 1024); /** * Creates a JDBCSampler. */ protected AbstractJDBCTestElement() { } /** * Execute the test element. * * @param conn a {@link Connection} * @return the result of the execute command * @throws SQLException if a database error occurs * @throws IOException when I/O error occurs * @throws UnsupportedOperationException if the user provided incorrect query type */ protected byte[] execute(Connection conn) throws SQLException, IOException, UnsupportedOperationException { // NOSONAR return execute(conn, new SampleResult()); } /** * Execute the test element. * Use the sample given as argument to set time to first byte in the "latency" field of the SampleResult. * * @param conn a {@link Connection} * @param sample a {@link SampleResult} to save the latency * @return the result of the execute command * @throws SQLException if a database error occurs * @throws IOException when I/O error occurs * @throws UnsupportedOperationException if the user provided incorrect query type */ protected byte[] execute(Connection conn, SampleResult sample) throws SQLException, IOException, UnsupportedOperationException { log.debug("executing jdbc:{}", getQuery()); // Based on query return value, get results String currentQueryType = getQueryType(); if (SELECT.equals(currentQueryType)) { try (Statement stmt = conn.createStatement()) { setQueryTimeout(stmt, getIntegerQueryTimeout()); ResultSet rs = null; try { rs = stmt.executeQuery(getQuery()); sample.latencyEnd(); return getStringFromResultSet(rs).getBytes(ENCODING); } finally { close(rs); } } } else if (CALLABLE.equals(currentQueryType)) { try (CallableStatement cstmt = getCallableStatement(conn)) { int[] out = setArguments(cstmt); // A CallableStatement can return more than 1 ResultSets // plus a number of update counts. boolean hasResultSet = cstmt.execute(); sample.latencyEnd(); String sb = resultSetsToString(cstmt,hasResultSet, out); return sb.getBytes(ENCODING); } } else if (UPDATE.equals(currentQueryType)) { try (Statement stmt = conn.createStatement()) { setQueryTimeout(stmt, getIntegerQueryTimeout()); stmt.executeUpdate(getQuery()); sample.latencyEnd(); int updateCount = stmt.getUpdateCount(); String results = updateCount + " updates"; return results.getBytes(ENCODING); } } else if (PREPARED_SELECT.equals(currentQueryType)) { try (PreparedStatement pstmt = getPreparedStatement(conn)) { setArguments(pstmt); ResultSet rs = null; try { rs = pstmt.executeQuery(); sample.latencyEnd(); return getStringFromResultSet(rs).getBytes(ENCODING); } finally { close(rs); } } } else if (PREPARED_UPDATE.equals(currentQueryType)) { try (PreparedStatement pstmt = getPreparedStatement(conn)) { setArguments(pstmt); pstmt.executeUpdate(); sample.latencyEnd(); String sb = resultSetsToString(pstmt,false,null); return sb.getBytes(ENCODING); } } else if (ROLLBACK.equals(currentQueryType)){ conn.rollback(); sample.latencyEnd(); return ROLLBACK.getBytes(ENCODING); } else if (COMMIT.equals(currentQueryType)){ conn.commit(); sample.latencyEnd(); return COMMIT.getBytes(ENCODING); } else if (AUTOCOMMIT_FALSE.equals(currentQueryType)){ conn.setAutoCommit(false); sample.latencyEnd(); return AUTOCOMMIT_FALSE.getBytes(ENCODING); } else if (AUTOCOMMIT_TRUE.equals(currentQueryType)){ conn.setAutoCommit(true); sample.latencyEnd(); return AUTOCOMMIT_TRUE.getBytes(ENCODING); } else { // User provided incorrect query type throw new UnsupportedOperationException("Unexpected query type: "+currentQueryType); } } private String resultSetsToString(PreparedStatement pstmt, boolean result, int[] out) throws SQLException, UnsupportedEncodingException { StringBuilder sb = new StringBuilder(); int updateCount = 0; boolean currentResult = result; if (!currentResult) { updateCount = pstmt.getUpdateCount(); } do { if (currentResult) { ResultSet rs = null; try { rs = pstmt.getResultSet(); sb.append(getStringFromResultSet(rs)).append("\n"); // $NON-NLS-1$ } finally { close(rs); } } else { sb.append(updateCount).append(" updates.\n"); } currentResult = pstmt.getMoreResults(); if (!currentResult) { updateCount = pstmt.getUpdateCount(); } } while (currentResult || (updateCount != -1)); if (out!=null && pstmt instanceof CallableStatement){ List<Object> outputValues = new ArrayList<>(); CallableStatement cs = (CallableStatement) pstmt; sb.append("Output variables by position:\n"); for(int i=0; i < out.length; i++){ if (out[i]!=java.sql.Types.NULL){ Object o = cs.getObject(i+1); outputValues.add(o); sb.append("["); sb.append(i+1); sb.append("] "); sb.append(o); if( o instanceof java.sql.ResultSet && RS_COUNT_RECORDS.equals(resultSetHandler)) { sb.append(" ").append(countRows((ResultSet) o)).append(" rows"); } sb.append("\n"); } } String[] varnames = getVariableNames().split(COMMA); if(varnames.length > 0) { JMeterVariables jmvars = getThreadContext().getVariables(); for(int i = 0; i < varnames.length && i < outputValues.size(); i++) { String name = varnames[i].trim(); if (name.length()>0){ // Save the value in the variable if present Object o = outputValues.get(i); if( o instanceof java.sql.ResultSet ) { putIntoVar(jmvars, name, (java.sql.ResultSet) o); } else if (o instanceof java.sql.Clob) { putIntoVar(jmvars, name, (java.sql.Clob) o); } else if (o instanceof java.sql.Blob) { putIntoVar(jmvars, name, (java.sql.Blob) o); } else { jmvars.put(name, o == null ? null : o.toString()); } } } } } return sb.toString(); } private void putIntoVar(final JMeterVariables jmvars, final String name, final ResultSet resultSet) throws SQLException { if (RS_STORE_AS_OBJECT.equals(resultSetHandler)) { jmvars.putObject(name, resultSet); } else if (RS_COUNT_RECORDS.equals(resultSetHandler)) { jmvars.put(name, resultSet.toString() + " " + countRows(resultSet) + " rows"); } else { jmvars.put(name, resultSet.toString()); } } private void putIntoVar(final JMeterVariables jmvars, final String name, final Clob clob) throws SQLException { try { if (clob.length() > MAX_RETAIN_SIZE) { try (Reader reader = clob.getCharacterStream(0,MAX_RETAIN_SIZE)) { jmvars.put( name, IOUtils.toString(reader) + "<result cut off, it is too big>"); } } else { try (Reader reader = clob.getCharacterStream()) { jmvars.put(name, IOUtils.toString(reader)); } } } catch (IOException e) { log.warn("Could not read CLOB into {}", name, e); } } private void putIntoVar(final JMeterVariables jmvars, final String name, final Blob blob) throws SQLException { if (RS_STORE_AS_OBJECT.equals(resultSetHandler)) { try { long length = Math.max(blob.length(), MAX_RETAIN_SIZE); jmvars.putObject(name, IOUtils.toByteArray(blob.getBinaryStream(0, length))); } catch (IOException e) { log.warn("Could not read BLOB into {} as object.", name, e); } } else if (RS_COUNT_RECORDS.equals(resultSetHandler)) { jmvars.put(name, blob.length() + " bytes"); } else { try { long length = Math.max(blob.length(), MAX_RETAIN_SIZE); try (InputStream is = blob.getBinaryStream(0, length)) { jmvars.put(name, IOUtils.toString(is, ENCODING)); } } catch (IOException e) { log.warn("Can't convert BLOB to String using {}", ENCODING, e); } } } /** * Count rows in result set * @param resultSet {@link ResultSet} * @return number of rows in resultSet * @throws SQLException */ private static int countRows(ResultSet resultSet) throws SQLException { return resultSet.last() ? resultSet.getRow() : 0; } private int[] setArguments(PreparedStatement pstmt) throws SQLException, IOException { if (getQueryArguments().trim().length()==0) { return new int[]{}; } String[] arguments = CSVSaveService.csvSplitString(getQueryArguments(), COMMA_CHAR); String[] argumentsTypes = getQueryArgumentsTypes().split(COMMA); if (arguments.length != argumentsTypes.length) { throw new SQLException("number of arguments ("+arguments.length+") and number of types ("+argumentsTypes.length+") are not equal"); } int[] outputs= new int[arguments.length]; for (int i = 0; i < arguments.length; i++) { String argument = arguments[i]; String argumentType = argumentsTypes[i]; String[] arg = argumentType.split(" "); String inputOutput=""; if (arg.length > 1) { argumentType = arg[1]; inputOutput=arg[0]; } int targetSqlType = getJdbcType(argumentType); try { if (!OUT.equalsIgnoreCase(inputOutput)){ if (argument.equals(NULL_MARKER)){ pstmt.setNull(i+1, targetSqlType); } else { setArgument(pstmt, argument, targetSqlType, i+1); } } if (OUT.equalsIgnoreCase(inputOutput)||INOUT.equalsIgnoreCase(inputOutput)) { CallableStatement cs = (CallableStatement) pstmt; cs.registerOutParameter(i+1, targetSqlType); outputs[i]=targetSqlType; } else { outputs[i]=java.sql.Types.NULL; // can't have an output parameter type null } } catch (NullPointerException e) { // thrown by Derby JDBC (at least) if there are no "?" markers in statement throw new SQLException("Could not set argument no: "+(i+1)+" - missing parameter marker?", e); } } return outputs; } private void setArgument(PreparedStatement pstmt, String argument, int targetSqlType, int index) throws SQLException { switch (targetSqlType) { case Types.INTEGER: pstmt.setInt(index, Integer.parseInt(argument)); break; case Types.DECIMAL: case Types.NUMERIC: pstmt.setBigDecimal(index, new BigDecimal(argument)); break; case Types.DOUBLE: case Types.FLOAT: pstmt.setDouble(index, Double.parseDouble(argument)); break; case Types.CHAR: case Types.LONGVARCHAR: case Types.VARCHAR: pstmt.setString(index, argument); break; case Types.BIT: case Types.BOOLEAN: pstmt.setBoolean(index, Boolean.parseBoolean(argument)); break; case Types.BIGINT: pstmt.setLong(index, Long.parseLong(argument)); break; case Types.DATE: pstmt.setDate(index, Date.valueOf(argument)); break; case Types.REAL: pstmt.setFloat(index, Float.parseFloat(argument)); break; case Types.TINYINT: pstmt.setByte(index, Byte.parseByte(argument)); break; case Types.SMALLINT: pstmt.setShort(index, Short.parseShort(argument)); break; case Types.TIMESTAMP: pstmt.setTimestamp(index, Timestamp.valueOf(argument)); break; case Types.TIME: pstmt.setTime(index, Time.valueOf(argument)); break; case Types.BINARY: case Types.VARBINARY: case Types.LONGVARBINARY: pstmt.setBytes(index, argument.getBytes()); break; case Types.NULL: pstmt.setNull(index, targetSqlType); break; default: pstmt.setObject(index, argument, targetSqlType); } } private static int getJdbcType(String jdbcType) throws SQLException { Integer entry = mapJdbcNameToInt.get(jdbcType.toLowerCase(java.util.Locale.ENGLISH)); if (entry == null) { try { entry = Integer.decode(jdbcType); } catch (NumberFormatException e) { throw new SQLException("Invalid data type: "+jdbcType, e); } } return entry.intValue(); } private CallableStatement getCallableStatement(Connection conn) throws SQLException { return (CallableStatement) getPreparedStatement(conn,true); } private PreparedStatement getPreparedStatement(Connection conn) throws SQLException { return getPreparedStatement(conn,false); } private PreparedStatement getPreparedStatement(Connection conn, boolean callable) throws SQLException { PreparedStatement pstmt; if (callable) { pstmt = conn.prepareCall(getQuery()); // NOSONAR closed by caller } else { pstmt = conn.prepareStatement(getQuery()); // NOSONAR closed by caller } setQueryTimeout(pstmt, getIntegerQueryTimeout()); return pstmt; } /** * @param stmt {@link Statement} Statement for which we want to set timeout * @param timeout int timeout value in seconds, if < 0 setQueryTimeout will not be called * @throws SQLException */ private static void setQueryTimeout(Statement stmt, int timeout) throws SQLException { if(timeout >= 0) { stmt.setQueryTimeout(timeout); } } /** * Gets a Data object from a ResultSet. * * @param rs * ResultSet passed in from a database query * @return a Data object * @throws java.sql.SQLException * @throws UnsupportedEncodingException */ private String getStringFromResultSet(ResultSet rs) throws SQLException, UnsupportedEncodingException { ResultSetMetaData meta = rs.getMetaData(); StringBuilder sb = new StringBuilder(); int numColumns = meta.getColumnCount(); for (int i = 1; i <= numColumns; i++) { sb.append(meta.getColumnLabel(i)); if (i==numColumns){ sb.append('\n'); } else { sb.append('\t'); } } JMeterVariables jmvars = getThreadContext().getVariables(); String[] varNames = getVariableNames().split(COMMA); String currentResultVariable = getResultVariable().trim(); List<Map<String, Object> > results = null; if(!currentResultVariable.isEmpty()) { results = new ArrayList<>(); jmvars.putObject(currentResultVariable, results); } int j = 0; while (rs.next()) { Map<String, Object> row = null; j++; for (int i = 1; i <= numColumns; i++) { Object o = rs.getObject(i); if(results != null) { if(row == null) { row = new HashMap<>(numColumns); results.add(row); } row.put(meta.getColumnLabel(i), o); } if (o instanceof byte[]) { o = new String((byte[]) o, ENCODING); } sb.append(o); if (i==numColumns){ sb.append('\n'); } else { sb.append('\t'); } if (i <= varNames.length) { // i starts at 1 String name = varNames[i - 1].trim(); if (name.length()>0){ // Save the value in the variable if present jmvars.put(name+UNDERSCORE+j, o == null ? null : o.toString()); } } } } // Remove any additional values from previous sample for (String varName : varNames) { String name = varName.trim(); if (name.length() > 0 && jmvars != null) { final String varCount = name + "_#"; // $NON-NLS-1$ // Get the previous count String prevCount = jmvars.get(varCount); if (prevCount != null) { int prev = Integer.parseInt(prevCount); for (int n = j + 1; n <= prev; n++) { jmvars.remove(name + UNDERSCORE + n); } } jmvars.put(varCount, Integer.toString(j)); // save the current count } } return sb.toString(); } public static void close(Connection c) { try { if (c != null) { c.close(); } } catch (SQLException e) { log.warn("Error closing Connection", e); } } public static void close(Statement s) { try { if (s != null) { s.close(); } } catch (SQLException e) { log.warn("Error closing Statement {}", s.toString(), e); } } public static void close(ResultSet rs) { try { if (rs != null) { rs.close(); } } catch (SQLException e) { log.warn("Error closing ResultSet", e); } } /** * @return the integer representation queryTimeout */ public int getIntegerQueryTimeout() { int timeout; if(StringUtils.isEmpty(queryTimeout)) { return 0; } else { try { timeout = Integer.parseInt(queryTimeout); } catch (NumberFormatException nfe) { timeout = 0; } } return timeout; } /** * @return the queryTimeout */ public String getQueryTimeout() { return queryTimeout ; } /** * @param queryTimeout query timeout in seconds */ public void setQueryTimeout(String queryTimeout) { this.queryTimeout = queryTimeout; } public String getQuery() { return query; } @Override public String toString() { StringBuilder sb = new StringBuilder(80); sb.append("["); // $NON-NLS-1$ sb.append(getQueryType()); sb.append("] "); // $NON-NLS-1$ sb.append(getQuery()); sb.append("\n"); sb.append(getQueryArguments()); sb.append("\n"); sb.append(getQueryArgumentsTypes()); return sb.toString(); } /** * @param query * The query to set. */ public void setQuery(String query) { this.query = query; } /** * @return Returns the dataSource. */ public String getDataSource() { return dataSource; } /** * @param dataSource * The dataSource to set. */ public void setDataSource(String dataSource) { this.dataSource = dataSource; } /** * @return Returns the queryType. */ public String getQueryType() { return queryType; } /** * @param queryType The queryType to set. */ public void setQueryType(String queryType) { this.queryType = queryType; } public String getQueryArguments() { return queryArguments; } public void setQueryArguments(String queryArguments) { this.queryArguments = queryArguments; } public String getQueryArgumentsTypes() { return queryArgumentsTypes; } public void setQueryArgumentsTypes(String queryArgumentsType) { this.queryArgumentsTypes = queryArgumentsType; } /** * @return the variableNames */ public String getVariableNames() { return variableNames; } /** * @param variableNames the variableNames to set */ public void setVariableNames(String variableNames) { this.variableNames = variableNames; } /** * @return the resultSetHandler */ public String getResultSetHandler() { return resultSetHandler; } /** * @param resultSetHandler the resultSetHandler to set */ public void setResultSetHandler(String resultSetHandler) { this.resultSetHandler = resultSetHandler; } /** * @return the resultVariable */ public String getResultVariable() { return resultVariable ; } /** * @param resultVariable the variable name in which results will be stored */ public void setResultVariable(String resultVariable) { this.resultVariable = resultVariable; } /** * {@inheritDoc} * @see org.apache.jmeter.testelement.TestStateListener#testStarted() */ @Override public void testStarted() { testStarted(""); } /** * {@inheritDoc} * @see org.apache.jmeter.testelement.TestStateListener#testStarted(java.lang.String) */ @Override public void testStarted(String host) { } /** * {@inheritDoc} * @see org.apache.jmeter.testelement.TestStateListener#testEnded() */ @Override public void testEnded() { testEnded(""); } /** * {@inheritDoc} * @see org.apache.jmeter.testelement.TestStateListener#testEnded(java.lang.String) */ @Override public void testEnded(String host) { } }
src/protocol/jdbc/org/apache/jmeter/protocol/jdbc/AbstractJDBCTestElement.java
/* * 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. * */ package org.apache.jmeter.protocol.jdbc; import java.io.IOException; import java.io.InputStream; import java.io.Reader; import java.io.UnsupportedEncodingException; import java.lang.reflect.Field; import java.math.BigDecimal; import java.nio.charset.StandardCharsets; import java.sql.Blob; import java.sql.CallableStatement; import java.sql.Clob; import java.sql.Connection; import java.sql.Date; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.ResultSetMetaData; import java.sql.SQLException; import java.sql.Statement; import java.sql.Time; import java.sql.Timestamp; import java.sql.Types; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import org.apache.commons.io.IOUtils; import org.apache.commons.lang3.StringUtils; import org.apache.jmeter.samplers.SampleResult; import org.apache.jmeter.save.CSVSaveService; import org.apache.jmeter.testelement.AbstractTestElement; import org.apache.jmeter.testelement.TestStateListener; import org.apache.jmeter.threads.JMeterVariables; import org.apache.jmeter.util.JMeterUtils; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * A base class for all JDBC test elements handling the basics of a SQL request. * */ public abstract class AbstractJDBCTestElement extends AbstractTestElement implements TestStateListener{ private static final long serialVersionUID = 235L; private static final Logger log = LoggerFactory.getLogger(AbstractJDBCTestElement.class); private static final String COMMA = ","; // $NON-NLS-1$ private static final char COMMA_CHAR = ','; private static final String UNDERSCORE = "_"; // $NON-NLS-1$ // String used to indicate a null value private static final String NULL_MARKER = JMeterUtils.getPropDefault("jdbcsampler.nullmarker","]NULL["); // $NON-NLS-1$ private static final String INOUT = "INOUT"; // $NON-NLS-1$ private static final String OUT = "OUT"; // $NON-NLS-1$ // TODO - should the encoding be configurable? protected static final String ENCODING = StandardCharsets.UTF_8.name(); // key: name (lowercase) from java.sql.Types; entry: corresponding int value private static final Map<String, Integer> mapJdbcNameToInt; // read-only after class init static { // based on e291. Getting the Name of a JDBC Type from javaalmanac.com // http://javaalmanac.com/egs/java.sql/JdbcInt2Str.html mapJdbcNameToInt = new HashMap<>(); //Get all fields in java.sql.Types and store the corresponding int values Field[] fields = java.sql.Types.class.getFields(); for (Field field : fields) { try { String name = field.getName(); Integer value = (Integer) field.get(null); mapJdbcNameToInt.put(name.toLowerCase(java.util.Locale.ENGLISH), value); } catch (IllegalAccessException e) { throw new RuntimeException(e); // should not happen } } } // Query types (used to communicate with GUI) // N.B. These must not be changed, as they are used in the JMX files static final String SELECT = "Select Statement"; // $NON-NLS-1$ static final String UPDATE = "Update Statement"; // $NON-NLS-1$ static final String CALLABLE = "Callable Statement"; // $NON-NLS-1$ static final String PREPARED_SELECT = "Prepared Select Statement"; // $NON-NLS-1$ static final String PREPARED_UPDATE = "Prepared Update Statement"; // $NON-NLS-1$ static final String COMMIT = "Commit"; // $NON-NLS-1$ static final String ROLLBACK = "Rollback"; // $NON-NLS-1$ static final String AUTOCOMMIT_FALSE = "AutoCommit(false)"; // $NON-NLS-1$ static final String AUTOCOMMIT_TRUE = "AutoCommit(true)"; // $NON-NLS-1$ static final String RS_STORE_AS_STRING = "Store as String"; // $NON-NLS-1$ static final String RS_STORE_AS_OBJECT = "Store as Object"; // $NON-NLS-1$ static final String RS_COUNT_RECORDS = "Count Records"; // $NON-NLS-1$ private String query = ""; // $NON-NLS-1$ private String dataSource = ""; // $NON-NLS-1$ private String queryType = SELECT; private String queryArguments = ""; // $NON-NLS-1$ private String queryArgumentsTypes = ""; // $NON-NLS-1$ private String variableNames = ""; // $NON-NLS-1$ private String resultSetHandler = RS_STORE_AS_STRING; private String resultVariable = ""; // $NON-NLS-1$ private String queryTimeout = ""; // $NON-NLS-1$ private static final int MAX_RETAIN_SIZE = JMeterUtils.getPropDefault("jdbcsampler.max_retain_result_size", 64 * 1024); /** * Creates a JDBCSampler. */ protected AbstractJDBCTestElement() { } /** * Execute the test element. * * @param conn a {@link Connection} * @return the result of the execute command * @throws SQLException if a database error occurs * @throws IOException when I/O error occurs * @throws UnsupportedOperationException if the user provided incorrect query type */ protected byte[] execute(Connection conn) throws SQLException, IOException, UnsupportedOperationException { // NOSONAR return execute(conn, new SampleResult()); } /** * Execute the test element. * Use the sample given as argument to set time to first byte in the "latency" field of the SampleResult. * * @param conn a {@link Connection} * @param sample a {@link SampleResult} to save the latency * @return the result of the execute command * @throws SQLException if a database error occurs * @throws IOException when I/O error occurs * @throws UnsupportedOperationException if the user provided incorrect query type */ protected byte[] execute(Connection conn, SampleResult sample) throws SQLException, IOException, UnsupportedOperationException { log.debug("executing jdbc:{}", getQuery()); // Based on query return value, get results String currentQueryType = getQueryType(); if (SELECT.equals(currentQueryType)) { try (Statement stmt = conn.createStatement()) { setQueryTimeout(stmt, getIntegerQueryTimeout()); ResultSet rs = null; try { rs = stmt.executeQuery(getQuery()); sample.latencyEnd(); return getStringFromResultSet(rs).getBytes(ENCODING); } finally { close(rs); } } } else if (CALLABLE.equals(currentQueryType)) { try (CallableStatement cstmt = getCallableStatement(conn)) { int[] out = setArguments(cstmt); // A CallableStatement can return more than 1 ResultSets // plus a number of update counts. boolean hasResultSet = cstmt.execute(); sample.latencyEnd(); String sb = resultSetsToString(cstmt,hasResultSet, out); return sb.getBytes(ENCODING); } } else if (UPDATE.equals(currentQueryType)) { try (Statement stmt = conn.createStatement()) { setQueryTimeout(stmt, getIntegerQueryTimeout()); stmt.executeUpdate(getQuery()); sample.latencyEnd(); int updateCount = stmt.getUpdateCount(); String results = updateCount + " updates"; return results.getBytes(ENCODING); } } else if (PREPARED_SELECT.equals(currentQueryType)) { try (PreparedStatement pstmt = getPreparedStatement(conn)) { setArguments(pstmt); ResultSet rs = null; try { rs = pstmt.executeQuery(); sample.latencyEnd(); return getStringFromResultSet(rs).getBytes(ENCODING); } finally { close(rs); } } } else if (PREPARED_UPDATE.equals(currentQueryType)) { try (PreparedStatement pstmt = getPreparedStatement(conn)) { setArguments(pstmt); pstmt.executeUpdate(); sample.latencyEnd(); String sb = resultSetsToString(pstmt,false,null); return sb.getBytes(ENCODING); } } else if (ROLLBACK.equals(currentQueryType)){ conn.rollback(); sample.latencyEnd(); return ROLLBACK.getBytes(ENCODING); } else if (COMMIT.equals(currentQueryType)){ conn.commit(); sample.latencyEnd(); return COMMIT.getBytes(ENCODING); } else if (AUTOCOMMIT_FALSE.equals(currentQueryType)){ conn.setAutoCommit(false); sample.latencyEnd(); return AUTOCOMMIT_FALSE.getBytes(ENCODING); } else if (AUTOCOMMIT_TRUE.equals(currentQueryType)){ conn.setAutoCommit(true); sample.latencyEnd(); return AUTOCOMMIT_TRUE.getBytes(ENCODING); } else { // User provided incorrect query type throw new UnsupportedOperationException("Unexpected query type: "+currentQueryType); } } private String resultSetsToString(PreparedStatement pstmt, boolean result, int[] out) throws SQLException, UnsupportedEncodingException { StringBuilder sb = new StringBuilder(); int updateCount = 0; boolean currentResult = result; if (!currentResult) { updateCount = pstmt.getUpdateCount(); } do { if (currentResult) { ResultSet rs = null; try { rs = pstmt.getResultSet(); sb.append(getStringFromResultSet(rs)).append("\n"); // $NON-NLS-1$ } finally { close(rs); } } else { sb.append(updateCount).append(" updates.\n"); } currentResult = pstmt.getMoreResults(); if (!currentResult) { updateCount = pstmt.getUpdateCount(); } } while (currentResult || (updateCount != -1)); if (out!=null && pstmt instanceof CallableStatement){ List<Object> outputValues = new ArrayList<>(); CallableStatement cs = (CallableStatement) pstmt; sb.append("Output variables by position:\n"); for(int i=0; i < out.length; i++){ if (out[i]!=java.sql.Types.NULL){ Object o = cs.getObject(i+1); outputValues.add(o); sb.append("["); sb.append(i+1); sb.append("] "); sb.append(o); if( o instanceof java.sql.ResultSet && RS_COUNT_RECORDS.equals(resultSetHandler)) { sb.append(" ").append(countRows((ResultSet) o)).append(" rows"); } sb.append("\n"); } } String[] varnames = getVariableNames().split(COMMA); if(varnames.length > 0) { JMeterVariables jmvars = getThreadContext().getVariables(); for(int i = 0; i < varnames.length && i < outputValues.size(); i++) { String name = varnames[i].trim(); if (name.length()>0){ // Save the value in the variable if present Object o = outputValues.get(i); if( o instanceof java.sql.ResultSet ) { putIntoVar(jmvars, name, (java.sql.ResultSet) o); } else if (o instanceof java.sql.Clob) { putIntoVar(jmvars, name, (java.sql.Clob) o); } else if (o instanceof java.sql.Blob) { putIntoVar(jmvars, name, (java.sql.Blob) o); } else { jmvars.put(name, o == null ? null : o.toString()); } } } } } return sb.toString(); } private void putIntoVar(final JMeterVariables jmvars, final String name, final ResultSet resultSet) throws SQLException { if (RS_STORE_AS_OBJECT.equals(resultSetHandler)) { jmvars.putObject(name, resultSet); } else if (RS_COUNT_RECORDS.equals(resultSetHandler)) { jmvars.put(name, resultSet.toString() + " " + countRows(resultSet) + " rows"); } else { jmvars.put(name, resultSet.toString()); } } private void putIntoVar(final JMeterVariables jmvars, final String name, final Clob clob) throws SQLException { try { if (clob.length() > MAX_RETAIN_SIZE) { try (Reader reader = clob.getCharacterStream(0,MAX_RETAIN_SIZE)) { jmvars.put( name, IOUtils.toString(reader) + "<result cut off, it is too big>"); } } else { try (Reader reader = clob.getCharacterStream()) { jmvars.put(name, IOUtils.toString(reader)); } } } catch (IOException e) { log.warn("Could not read CLOB into {}", name, e); } } private void putIntoVar(final JMeterVariables jmvars, final String name, final Blob blob) throws SQLException { if (RS_STORE_AS_OBJECT.equals(resultSetHandler)) { try { long length = Math.max(blob.length(), MAX_RETAIN_SIZE); jmvars.putObject(name, IOUtils.toByteArray(blob.getBinaryStream(0, length))); } catch (IOException e) { log.warn("Could not read BLOB into {} as object.", name, e); } } else if (RS_COUNT_RECORDS.equals(resultSetHandler)) { jmvars.put(name, blob.length() + " bytes"); } else { try { long length = Math.max(blob.length(), MAX_RETAIN_SIZE); try (InputStream is = blob.getBinaryStream(0, length)) { jmvars.put(name, IOUtils.toString(is, ENCODING)); } } catch (IOException e) { log.warn("Can't convert BLOB to String using {}", ENCODING, e); } } } /** * Count rows in result set * @param resultSet {@link ResultSet} * @return number of rows in resultSet * @throws SQLException */ private static int countRows(ResultSet resultSet) throws SQLException { return resultSet.last() ? resultSet.getRow() : 0; } private int[] setArguments(PreparedStatement pstmt) throws SQLException, IOException { if (getQueryArguments().trim().length()==0) { return new int[]{}; } String[] arguments = CSVSaveService.csvSplitString(getQueryArguments(), COMMA_CHAR); String[] argumentsTypes = getQueryArgumentsTypes().split(COMMA); if (arguments.length != argumentsTypes.length) { throw new SQLException("number of arguments ("+arguments.length+") and number of types ("+argumentsTypes.length+") are not equal"); } int[] outputs= new int[arguments.length]; for (int i = 0; i < arguments.length; i++) { String argument = arguments[i]; String argumentType = argumentsTypes[i]; String[] arg = argumentType.split(" "); String inputOutput=""; if (arg.length > 1) { argumentType = arg[1]; inputOutput=arg[0]; } int targetSqlType = getJdbcType(argumentType); try { if (!OUT.equalsIgnoreCase(inputOutput)){ if (argument.equals(NULL_MARKER)){ pstmt.setNull(i+1, targetSqlType); } else { setArgument(pstmt, argument, targetSqlType, i+1); } } if (OUT.equalsIgnoreCase(inputOutput)||INOUT.equalsIgnoreCase(inputOutput)) { CallableStatement cs = (CallableStatement) pstmt; cs.registerOutParameter(i+1, targetSqlType); outputs[i]=targetSqlType; } else { outputs[i]=java.sql.Types.NULL; // can't have an output parameter type null } } catch (NullPointerException e) { // thrown by Derby JDBC (at least) if there are no "?" markers in statement throw new SQLException("Could not set argument no: "+(i+1)+" - missing parameter marker?", e); } } return outputs; } private void setArgument(PreparedStatement pstmt, String argument, int targetSqlType, int index) throws SQLException { switch (targetSqlType) { case Types.INTEGER: pstmt.setInt(index, Integer.parseInt(argument)); break; case Types.DECIMAL: case Types.NUMERIC: pstmt.setBigDecimal(index, new BigDecimal(argument)); break; case Types.DOUBLE: case Types.FLOAT: pstmt.setDouble(index, Double.parseDouble(argument)); break; case Types.CHAR: case Types.LONGVARCHAR: case Types.VARCHAR: pstmt.setString(index, argument); break; case Types.BIT: case Types.BOOLEAN: pstmt.setBoolean(index, Boolean.parseBoolean(argument)); break; case Types.BIGINT: pstmt.setLong(index, Long.parseLong(argument)); break; case Types.DATE: pstmt.setDate(index, Date.valueOf(argument)); break; case Types.REAL: pstmt.setFloat(index, Float.parseFloat(argument)); break; case Types.TINYINT: pstmt.setByte(index, Byte.parseByte(argument)); break; case Types.SMALLINT: pstmt.setShort(index, Short.parseShort(argument)); break; case Types.TIMESTAMP: pstmt.setTimestamp(index, Timestamp.valueOf(argument)); break; case Types.TIME: pstmt.setTime(index, Time.valueOf(argument)); break; case Types.BINARY: case Types.VARBINARY: case Types.LONGVARBINARY: pstmt.setBytes(index, argument.getBytes()); break; case Types.NULL: pstmt.setNull(index, targetSqlType); break; default: pstmt.setObject(index, argument, targetSqlType); } } private static int getJdbcType(String jdbcType) throws SQLException { Integer entry = mapJdbcNameToInt.get(jdbcType.toLowerCase(java.util.Locale.ENGLISH)); if (entry == null) { try { entry = Integer.decode(jdbcType); } catch (NumberFormatException e) { throw new SQLException("Invalid data type: "+jdbcType, e); } } return entry.intValue(); } private CallableStatement getCallableStatement(Connection conn) throws SQLException { return (CallableStatement) getPreparedStatement(conn,true); } private PreparedStatement getPreparedStatement(Connection conn) throws SQLException { return getPreparedStatement(conn,false); } private PreparedStatement getPreparedStatement(Connection conn, boolean callable) throws SQLException { PreparedStatement pstmt; if (callable) { pstmt = conn.prepareCall(getQuery()); // NOSONAR closed by caller } else { pstmt = conn.prepareStatement(getQuery()); // NOSONAR closed by caller } setQueryTimeout(pstmt, getIntegerQueryTimeout()); return pstmt; } /** * @param stmt {@link Statement} Statement for which we want to set timeout * @param timeout int timeout value in seconds, if < 0 setQueryTimeout will not be called * @throws SQLException */ private static void setQueryTimeout(Statement stmt, int timeout) throws SQLException { if(timeout >= 0) { stmt.setQueryTimeout(timeout); } } /** * Gets a Data object from a ResultSet. * * @param rs * ResultSet passed in from a database query * @return a Data object * @throws java.sql.SQLException * @throws UnsupportedEncodingException */ private String getStringFromResultSet(ResultSet rs) throws SQLException, UnsupportedEncodingException { ResultSetMetaData meta = rs.getMetaData(); StringBuilder sb = new StringBuilder(); int numColumns = meta.getColumnCount(); for (int i = 1; i <= numColumns; i++) { sb.append(meta.getColumnLabel(i)); if (i==numColumns){ sb.append('\n'); } else { sb.append('\t'); } } JMeterVariables jmvars = getThreadContext().getVariables(); String[] varNames = getVariableNames().split(COMMA); String currentResultVariable = getResultVariable().trim(); List<Map<String, Object> > results = null; if(!currentResultVariable.isEmpty()) { results = new ArrayList<>(); jmvars.putObject(currentResultVariable, results); } int j = 0; while (rs.next()) { Map<String, Object> row = null; j++; for (int i = 1; i <= numColumns; i++) { Object o = rs.getObject(i); if(results != null) { if(row == null) { row = new HashMap<>(numColumns); results.add(row); } row.put(meta.getColumnLabel(i), o); } if (o instanceof byte[]) { o = new String((byte[]) o, ENCODING); } sb.append(o); if (i==numColumns){ sb.append('\n'); } else { sb.append('\t'); } if (i <= varNames.length) { // i starts at 1 String name = varNames[i - 1].trim(); if (name.length()>0){ // Save the value in the variable if present jmvars.put(name+UNDERSCORE+j, o == null ? null : o.toString()); } } } } // Remove any additional values from previous sample for (String varName : varNames) { String name = varName.trim(); if (name.length() > 0 && jmvars != null) { final String varCount = name + "_#"; // $NON-NLS-1$ // Get the previous count String prevCount = jmvars.get(varCount); if (prevCount != null) { int prev = Integer.parseInt(prevCount); for (int n = j + 1; n <= prev; n++) { jmvars.remove(name + UNDERSCORE + n); } } jmvars.put(varCount, Integer.toString(j)); // save the current count } } return sb.toString(); } public static void close(Connection c) { try { if (c != null) { c.close(); } } catch (SQLException e) { log.warn("Error closing Connection", e); } } public static void close(Statement s) { try { if (s != null) { s.close(); } } catch (SQLException e) { log.warn("Error closing Statement {}", s.toString(), e); } } public static void close(ResultSet rs) { try { if (rs != null) { rs.close(); } } catch (SQLException e) { log.warn("Error closing ResultSet", e); } } /** * @return the integer representation queryTimeout */ public int getIntegerQueryTimeout() { int timeout = 0; if(StringUtils.isEmpty(queryTimeout)) { return 0; } else { try { timeout = Integer.parseInt(queryTimeout); } catch (NumberFormatException nfe) { timeout = 0; } } return timeout; } /** * @return the queryTimeout */ public String getQueryTimeout() { return queryTimeout ; } /** * @param queryTimeout query timeout in seconds */ public void setQueryTimeout(String queryTimeout) { this.queryTimeout = queryTimeout; } public String getQuery() { return query; } @Override public String toString() { StringBuilder sb = new StringBuilder(80); sb.append("["); // $NON-NLS-1$ sb.append(getQueryType()); sb.append("] "); // $NON-NLS-1$ sb.append(getQuery()); sb.append("\n"); sb.append(getQueryArguments()); sb.append("\n"); sb.append(getQueryArgumentsTypes()); return sb.toString(); } /** * @param query * The query to set. */ public void setQuery(String query) { this.query = query; } /** * @return Returns the dataSource. */ public String getDataSource() { return dataSource; } /** * @param dataSource * The dataSource to set. */ public void setDataSource(String dataSource) { this.dataSource = dataSource; } /** * @return Returns the queryType. */ public String getQueryType() { return queryType; } /** * @param queryType The queryType to set. */ public void setQueryType(String queryType) { this.queryType = queryType; } public String getQueryArguments() { return queryArguments; } public void setQueryArguments(String queryArguments) { this.queryArguments = queryArguments; } public String getQueryArgumentsTypes() { return queryArgumentsTypes; } public void setQueryArgumentsTypes(String queryArgumentsType) { this.queryArgumentsTypes = queryArgumentsType; } /** * @return the variableNames */ public String getVariableNames() { return variableNames; } /** * @param variableNames the variableNames to set */ public void setVariableNames(String variableNames) { this.variableNames = variableNames; } /** * @return the resultSetHandler */ public String getResultSetHandler() { return resultSetHandler; } /** * @param resultSetHandler the resultSetHandler to set */ public void setResultSetHandler(String resultSetHandler) { this.resultSetHandler = resultSetHandler; } /** * @return the resultVariable */ public String getResultVariable() { return resultVariable ; } /** * @param resultVariable the variable name in which results will be stored */ public void setResultVariable(String resultVariable) { this.resultVariable = resultVariable; } /** * {@inheritDoc} * @see org.apache.jmeter.testelement.TestStateListener#testStarted() */ @Override public void testStarted() { testStarted(""); } /** * {@inheritDoc} * @see org.apache.jmeter.testelement.TestStateListener#testStarted(java.lang.String) */ @Override public void testStarted(String host) { } /** * {@inheritDoc} * @see org.apache.jmeter.testelement.TestStateListener#testEnded() */ @Override public void testEnded() { testEnded(""); } /** * {@inheritDoc} * @see org.apache.jmeter.testelement.TestStateListener#testEnded(java.lang.String) */ @Override public void testEnded(String host) { } }
Remove useless assignment , fix SONAR warning git-svn-id: https://svn.apache.org/repos/asf/jmeter/trunk@1849599 13f79535-47bb-0310-9956-ffa450edef68 Former-commit-id: 65b89e547a8645e661099e9fe05bd039db02a8c5
src/protocol/jdbc/org/apache/jmeter/protocol/jdbc/AbstractJDBCTestElement.java
Remove useless assignment , fix SONAR warning
<ide><path>rc/protocol/jdbc/org/apache/jmeter/protocol/jdbc/AbstractJDBCTestElement.java <ide> * @return the integer representation queryTimeout <ide> */ <ide> public int getIntegerQueryTimeout() { <del> int timeout = 0; <add> int timeout; <ide> if(StringUtils.isEmpty(queryTimeout)) { <ide> return 0; <ide> } else {
Java
bsd-3-clause
37ae7ce8c7ef911dbbb64cba9722f28b50af52c7
0
shelan/jcabi-github,prondzyn/jcabi-github,pecko/jcabi-github,cezarykluczynski/jcabi-github,cvrebert/typed-github,zygm0nt/jcabi-github,YamStranger/jcabi-github
/** * Copyright (c) 2013-2014, jcabi.com * 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) Neither the name of the jcabi.com 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 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. */ package com.jcabi.github.mock; import com.jcabi.aspects.Immutable; import com.jcabi.aspects.Loggable; import com.jcabi.github.Comments; import com.jcabi.github.Coordinates; import com.jcabi.github.Event; import com.jcabi.github.Issue; import com.jcabi.github.IssueLabels; import com.jcabi.github.Label; import com.jcabi.github.Repo; import java.io.IOException; import java.util.Collection; import java.util.LinkedList; import java.util.Map; import javax.json.Json; import javax.json.JsonArrayBuilder; import javax.json.JsonObject; import javax.json.JsonObjectBuilder; import javax.json.JsonValue; import javax.validation.constraints.NotNull; import lombok.EqualsAndHashCode; import lombok.ToString; /** * Mock Github issue. * * @author Yegor Bugayenko ([email protected]) * @version $Id$ * @since 0.5 * @checkstyle ClassDataAbstractionCoupling (500 lines) */ @Immutable @Loggable(Loggable.DEBUG) @ToString @EqualsAndHashCode(of = { "storage", "self", "coords", "num" }) final class MkIssue implements Issue { /** * Storage. */ private final transient MkStorage storage; /** * Login of the user logged in. */ private final transient String self; /** * Repo name. */ private final transient Coordinates coords; /** * Issue number. */ private final transient int num; /** * Public ctor. * @param stg Storage * @param login User to login * @param rep Repo * @param number Issue number * @checkstyle ParameterNumber (5 lines) */ MkIssue( @NotNull(message = "stg is never NULL") final MkStorage stg, @NotNull(message = "login is never NULL") final String login, @NotNull(message = "rep is never NULL") final Coordinates rep, final int number ) { this.storage = stg; this.self = login; this.coords = rep; this.num = number; } @Override @NotNull(message = "Repository is never NULL") public Repo repo() { return new MkRepo(this.storage, this.self, this.coords); } @Override public int number() { return this.num; } @Override @NotNull(message = "comments is never NULL") public Comments comments() { try { return new MkComments( this.storage, this.self, this.coords, this.num ); } catch (final IOException ex) { throw new IllegalStateException(ex); } } @Override @NotNull(message = "labels is never NULL") public IssueLabels labels() { try { return new MkIssueLabels( this.storage, this.self, this.coords, this.num ); } catch (final IOException ex) { throw new IllegalStateException(ex); } } @Override @NotNull(message = "Iterable of events is never NULL") public Iterable<Event> events() throws IOException { final Collection<Event> events = new LinkedList<Event>(); if (!new Issue.Smart(this).isOpen()) { events.add( new MkEvent( this.storage, this.self, this.coords, Event.CLOSED ) ); } return events; } @Override public boolean exists() throws IOException { return this.storage.xml().xpath( String.format("%s/number/text()", this.xpath()) ).size() == 1; } @Override public int compareTo( @NotNull(message = "issue should not be NULL") final Issue issue ) { return this.number() - issue.number(); } @Override public void patch( @NotNull(message = "json can't be NULL") final JsonObject json ) throws IOException { new JsonPatch(this.storage).patch(this.xpath(), json); } @Override @NotNull(message = "JSON is never NULL") public JsonObject json() throws IOException { final JsonObject obj = new JsonNode( this.storage.xml().nodes(this.xpath()).get(0) ).json(); final JsonObjectBuilder json = Json.createObjectBuilder(); for (final Map.Entry<String, JsonValue> val: obj.entrySet()) { json.add(val.getKey(), val.getValue()); } final JsonArrayBuilder array = Json.createArrayBuilder(); for (final Label label : this.labels().iterate()) { array.add( Json.createObjectBuilder().add("name", label.name()).build() ); } return json .add("labels", array) .add( "pull_request", Json.createObjectBuilder().addNull("html_url").build() ) .build(); } /** * XPath of this element in XML tree. * @return XPath */ @NotNull(message = "Xpath is never NULL") private String xpath() { return String.format( "/github/repos/repo[@coords='%s']/issues/issue[number='%d']", this.coords, this.num ); } }
src/main/java/com/jcabi/github/mock/MkIssue.java
/** * Copyright (c) 2013-2014, jcabi.com * 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) Neither the name of the jcabi.com 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 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. */ package com.jcabi.github.mock; import com.jcabi.aspects.Immutable; import com.jcabi.aspects.Loggable; import com.jcabi.github.Comments; import com.jcabi.github.Coordinates; import com.jcabi.github.Event; import com.jcabi.github.Issue; import com.jcabi.github.IssueLabels; import com.jcabi.github.Label; import com.jcabi.github.Repo; import java.io.IOException; import java.util.Collection; import java.util.LinkedList; import java.util.Map; import javax.json.Json; import javax.json.JsonArrayBuilder; import javax.json.JsonObject; import javax.json.JsonObjectBuilder; import javax.json.JsonValue; import javax.validation.constraints.NotNull; import lombok.EqualsAndHashCode; import lombok.ToString; /** * Mock Github issue. * * @todo #818 MkIssue#exists() is not implemented. * Let's implement it and remove this puzzle. * @author Yegor Bugayenko ([email protected]) * @version $Id$ * @since 0.5 * @checkstyle ClassDataAbstractionCoupling (500 lines) */ @Immutable @Loggable(Loggable.DEBUG) @ToString @EqualsAndHashCode(of = { "storage", "self", "coords", "num" }) final class MkIssue implements Issue { /** * Storage. */ private final transient MkStorage storage; /** * Login of the user logged in. */ private final transient String self; /** * Repo name. */ private final transient Coordinates coords; /** * Issue number. */ private final transient int num; /** * Public ctor. * @param stg Storage * @param login User to login * @param rep Repo * @param number Issue number * @checkstyle ParameterNumber (5 lines) */ MkIssue( @NotNull(message = "stg is never NULL") final MkStorage stg, @NotNull(message = "login is never NULL") final String login, @NotNull(message = "rep is never NULL") final Coordinates rep, final int number ) { this.storage = stg; this.self = login; this.coords = rep; this.num = number; } @Override @NotNull(message = "Repository is never NULL") public Repo repo() { return new MkRepo(this.storage, this.self, this.coords); } @Override public int number() { return this.num; } @Override @NotNull(message = "comments is never NULL") public Comments comments() { try { return new MkComments( this.storage, this.self, this.coords, this.num ); } catch (final IOException ex) { throw new IllegalStateException(ex); } } @Override @NotNull(message = "labels is never NULL") public IssueLabels labels() { try { return new MkIssueLabels( this.storage, this.self, this.coords, this.num ); } catch (final IOException ex) { throw new IllegalStateException(ex); } } @Override @NotNull(message = "Iterable of events is never NULL") public Iterable<Event> events() throws IOException { final Collection<Event> events = new LinkedList<Event>(); if (!new Issue.Smart(this).isOpen()) { events.add( new MkEvent( this.storage, this.self, this.coords, Event.CLOSED ) ); } return events; } @Override public boolean exists() throws IOException { return this.storage.xml().xpath( String.format("%s/number/text()", this.xpath()) ).size() == 1; } @Override public int compareTo( @NotNull(message = "issue should not be NULL") final Issue issue ) { return this.number() - issue.number(); } @Override public void patch( @NotNull(message = "json can't be NULL") final JsonObject json ) throws IOException { new JsonPatch(this.storage).patch(this.xpath(), json); } @Override @NotNull(message = "JSON is never NULL") public JsonObject json() throws IOException { final JsonObject obj = new JsonNode( this.storage.xml().nodes(this.xpath()).get(0) ).json(); final JsonObjectBuilder json = Json.createObjectBuilder(); for (final Map.Entry<String, JsonValue> val: obj.entrySet()) { json.add(val.getKey(), val.getValue()); } final JsonArrayBuilder array = Json.createArrayBuilder(); for (final Label label : this.labels().iterate()) { array.add( Json.createObjectBuilder().add("name", label.name()).build() ); } return json .add("labels", array) .add( "pull_request", Json.createObjectBuilder().addNull("html_url").build() ) .build(); } /** * XPath of this element in XML tree. * @return XPath */ @NotNull(message = "Xpath is never NULL") private String xpath() { return String.format( "/github/repos/repo[@coords='%s']/issues/issue[number='%d']", this.coords, this.num ); } }
Removed puzzle
src/main/java/com/jcabi/github/mock/MkIssue.java
Removed puzzle
<ide><path>rc/main/java/com/jcabi/github/mock/MkIssue.java <ide> /** <ide> * Mock Github issue. <ide> * <del> * @todo #818 MkIssue#exists() is not implemented. <del> * Let's implement it and remove this puzzle. <ide> * @author Yegor Bugayenko ([email protected]) <ide> * @version $Id$ <ide> * @since 0.5
Java
apache-2.0
error: pathspec 'JavaSource/nl/nn/adapterframework/pipes/FilenameSwitch.java' did not match any file(s) known to git
84b6ca61c8bd879456c9a56c56bd1cfe71e7ddbc
1
ibissource/iaf,ibissource/iaf,ibissource/iaf,ibissource/iaf,ibissource/iaf
/* * $Log: FilenameSwitch.java,v $ * Revision 1.1 2008-02-15 14:09:04 europe\L190409 * first version * */ package nl.nn.adapterframework.pipes; import nl.nn.adapterframework.configuration.ConfigurationException; import nl.nn.adapterframework.core.PipeForward; import nl.nn.adapterframework.core.PipeLineSession; import nl.nn.adapterframework.core.PipeRunException; import nl.nn.adapterframework.core.PipeRunResult; /** * Selects an exitState, based on the last (filename) part of the path that is the input. * * <p><b>Configuration:</b> * <table border="1"> * <tr><th>attributes</th><th>description</th><th>default</th></tr> * <tr><td>className</td><td>nl.nn.adapterframework.pipes.XmlSwitch</td><td>&nbsp;</td></tr> * <tr><td>{@link #setName(String) name}</td><td>name of the Pipe</td><td>&nbsp;</td></tr> * <tr><td>{@link #setGetInputFromSessionKey(String) getInputFromSessionKey}</td><td>when set, input is taken from this session key, instead of regular input</td><td>&nbsp;</td></tr> * <tr><td>{@link #setStoreResultInSessionKey(String) storeResultInSessionKey}</td><td>when set, the result is stored under this session key</td><td>&nbsp;</td></tr> * <tr><td>{@link #setNotFoundForwardName(String) notFoundForwardName}</td><td>Forward returned when the pipename derived from the stylesheet could not be found.</i></td><td>&nbsp;</td></tr> * <tr><td>{@link #setToLowercase(boolean) toLowercase}</td><td>convert the result to lowercase</td><td>true</td></tr> * </table> * </p> * <p><b>Exits:</b> * <table border="1"> * <tr><th>state</th><th>condition</th></tr> * <tr><td>&lt;filenname part of the path&gt;</td><td>default</td></tr> * </table> * </p> * @author Gerrit van Brakel * @since 4.8 * @version Id */ public class FilenameSwitch extends AbstractPipe { private String notFoundForwardName=null; private boolean toLowercase=true; public void configure() throws ConfigurationException { super.configure(); if (getNotFoundForwardName()!=null) { if (findForward(getNotFoundForwardName())==null){ log.warn(getLogPrefix(null)+"has a notFoundForwardName attribute. However, this forward ["+getNotFoundForwardName()+"] is not configured."); } } } public PipeRunResult doPipe(Object input, PipeLineSession session) throws PipeRunException { String forward=""; String sInput=(String) input; PipeForward pipeForward=null; int slashPos=sInput.lastIndexOf('/'); if (slashPos>0) { sInput=sInput.substring(slashPos+1); } slashPos=sInput.lastIndexOf('\\'); if (slashPos>0) { sInput=sInput.substring(slashPos+1); } forward=sInput; if (isToLowercase()) { forward=forward.toLowerCase(); } log.debug(getLogPrefix(session)+ "determined forward ["+forward+"]"); if (findForward(forward) != null) pipeForward=findForward(forward); else { log.info(getLogPrefix(session)+"determined forward ["+forward+"], which is not defined. Will use ["+getNotFoundForwardName()+"] instead"); pipeForward=findForward(getNotFoundForwardName()); } if (pipeForward==null) { throw new PipeRunException (this, getLogPrefix(session)+"cannot find forward or pipe named ["+forward+"]"); } return new PipeRunResult(pipeForward, input); } public void setNotFoundForwardName(String notFound){ notFoundForwardName=notFound; } public String getNotFoundForwardName(){ return notFoundForwardName; } public void setToLowercase(boolean b) { toLowercase = b; } public boolean isToLowercase() { return toLowercase; } }
JavaSource/nl/nn/adapterframework/pipes/FilenameSwitch.java
first version
JavaSource/nl/nn/adapterframework/pipes/FilenameSwitch.java
first version
<ide><path>avaSource/nl/nn/adapterframework/pipes/FilenameSwitch.java <add>/* <add> * $Log: FilenameSwitch.java,v $ <add> * Revision 1.1 2008-02-15 14:09:04 europe\L190409 <add> * first version <add> * <add> */ <add>package nl.nn.adapterframework.pipes; <add> <add>import nl.nn.adapterframework.configuration.ConfigurationException; <add>import nl.nn.adapterframework.core.PipeForward; <add>import nl.nn.adapterframework.core.PipeLineSession; <add>import nl.nn.adapterframework.core.PipeRunException; <add>import nl.nn.adapterframework.core.PipeRunResult; <add> <add> <add>/** <add> * Selects an exitState, based on the last (filename) part of the path that is the input. <add> * <add> * <p><b>Configuration:</b> <add> * <table border="1"> <add> * <tr><th>attributes</th><th>description</th><th>default</th></tr> <add> * <tr><td>className</td><td>nl.nn.adapterframework.pipes.XmlSwitch</td><td>&nbsp;</td></tr> <add> * <tr><td>{@link #setName(String) name}</td><td>name of the Pipe</td><td>&nbsp;</td></tr> <add> * <tr><td>{@link #setGetInputFromSessionKey(String) getInputFromSessionKey}</td><td>when set, input is taken from this session key, instead of regular input</td><td>&nbsp;</td></tr> <add> * <tr><td>{@link #setStoreResultInSessionKey(String) storeResultInSessionKey}</td><td>when set, the result is stored under this session key</td><td>&nbsp;</td></tr> <add> * <tr><td>{@link #setNotFoundForwardName(String) notFoundForwardName}</td><td>Forward returned when the pipename derived from the stylesheet could not be found.</i></td><td>&nbsp;</td></tr> <add> * <tr><td>{@link #setToLowercase(boolean) toLowercase}</td><td>convert the result to lowercase</td><td>true</td></tr> <add> * </table> <add> * </p> <add> * <p><b>Exits:</b> <add> * <table border="1"> <add> * <tr><th>state</th><th>condition</th></tr> <add> * <tr><td>&lt;filenname part of the path&gt;</td><td>default</td></tr> <add> * </table> <add> * </p> <add> * @author Gerrit van Brakel <add> * @since 4.8 <add> * @version Id <add> */ <add>public class FilenameSwitch extends AbstractPipe { <add> <add> private String notFoundForwardName=null; <add> private boolean toLowercase=true; <add> <add> public void configure() throws ConfigurationException { <add> super.configure(); <add> if (getNotFoundForwardName()!=null) { <add> if (findForward(getNotFoundForwardName())==null){ <add> log.warn(getLogPrefix(null)+"has a notFoundForwardName attribute. However, this forward ["+getNotFoundForwardName()+"] is not configured."); <add> } <add> } <add> } <add> <add> public PipeRunResult doPipe(Object input, PipeLineSession session) throws PipeRunException { <add> String forward=""; <add> String sInput=(String) input; <add> PipeForward pipeForward=null; <add> <add> int slashPos=sInput.lastIndexOf('/'); <add> if (slashPos>0) { <add> sInput=sInput.substring(slashPos+1); <add> } <add> slashPos=sInput.lastIndexOf('\\'); <add> if (slashPos>0) { <add> sInput=sInput.substring(slashPos+1); <add> } <add> forward=sInput; <add> if (isToLowercase()) { <add> forward=forward.toLowerCase(); <add> } <add> log.debug(getLogPrefix(session)+ "determined forward ["+forward+"]"); <add> <add> if (findForward(forward) != null) <add> pipeForward=findForward(forward); <add> else { <add> log.info(getLogPrefix(session)+"determined forward ["+forward+"], which is not defined. Will use ["+getNotFoundForwardName()+"] instead"); <add> pipeForward=findForward(getNotFoundForwardName()); <add> } <add> <add> if (pipeForward==null) { <add> throw new PipeRunException (this, getLogPrefix(session)+"cannot find forward or pipe named ["+forward+"]"); <add> } <add> return new PipeRunResult(pipeForward, input); <add> } <add> <add> <add> public void setNotFoundForwardName(String notFound){ <add> notFoundForwardName=notFound; <add> } <add> public String getNotFoundForwardName(){ <add> return notFoundForwardName; <add> } <add> <add> public void setToLowercase(boolean b) { <add> toLowercase = b; <add> } <add> public boolean isToLowercase() { <add> return toLowercase; <add> } <add> <add>}
JavaScript
mit
059c09be111f67bb8269de0842f6e0e5289864d7
0
bigeasy/arguable
var stream = require('stream') var events = require('events') var cadence = require('cadence') var Destructible = require('destructible') var coalesce = require('extant') var Arguable = require('./arguable') var rescue = require('rescue') var Signal = require('signal') var Child = require('./child') var Usage = require('./usage') module.exports = function () { // Variadic arguments. var vargs = [] vargs.push.apply(vargs, arguments) // First argument is always the module. var module = vargs.shift() // Usage source can be specified explicitly, or else it is sought in the // comments of the main module. var source = typeof vargs[0] == 'string' ? vargs.shift() : module.filename var usage = Usage(source) // Optional options that both configure Arguable and provide our dear user // with a means to specify production objects for production and mock // objects for testing. var definition = typeof vargs[0] == 'object' ? vargs.shift() : {} // The main method. var main = vargs.shift() // TODO How about an optinal method here for command line completion logic? module.exports = function (argv, invocation, callback) { var vargs = [] vargs.push.apply(vargs, arguments) var argv = vargs.shift() var options = {} for (var option in definition) { options[option] = definition[option] } for (var option in invocation) { options[option] = invocation[option] } var parameters = [] if (!Array.isArray(argv)) { argv = [ argv ] } argv = argv.slice() while (argv.length != 0) { var argument = argv.shift() switch (typeof argument) { case 'object': // TODO Probably want `Arguable.flatten({ name: 'a', value: 1 // }, ...)`. // TODO Flattening would require knowing from the parameters // whether or not they accepted arguments in the case of // switch arguments. if (Array.isArray(argument)) { argv.unshift.apply(argv, argument) } else { var unshift = [] for (var name in argument) { unshift.push('--' + name, argument[name].toString()) } argv.unshift(unshift) } break default: parameters.push(argument) break } } var callback = vargs.pop() var pipes = {} if (options.$pipes != null) { options.$pipes = {} for (var fd in coalesce(definition.$pipes, {})) { options.$pipes[fd] = definition.$pipes[fd] } for (var fd in coalesce(invocation.$pipes, {})) { options.$pipes[fd] = invocation.$pipes[fd] } for (var fd in coalesce(options.$pipes)) { if (options.$pipes[fd] instanceof require('stream').Stream) { pipes[fd] = options.$pipes[fd] } else { var socket = { fd: +fd } for (var property in options.$pipes[fd]) { socket[property] = options.$pipes[fd][property] } pipes[fd] = new require('net').Socket(socket) } } } var isMainModule = ('$isMainModule' in options) ? options.$isMainModule : process.mainModule === module var lang = coalesce(options.$lang, process.env.LANG && process.env.LANG.split('.')[0]) var destructible, identifier var identifier = ('$destructible' in options) ? typeof options.$destructible == 'boolean' ? module.filename : options.$destructible : module.filename var arguable = new Arguable(usage, parameters, { identifier: identifier, isMainModule: isMainModule, stdin: coalesce(options.$stdin, process.stdin), stdout: coalesce(options.$stdout, process.stdout), stderr: coalesce(options.$stderr, process.stderr), options: options, pipes: pipes, lang: lang }) var scram = coalesce(options.$scram, 10000) switch (typeof scram) { case 'object': var parameter = Object.keys(scram)[0] scram = { name: parameter, value: +coalesce(arguable.ultimate[parameter], scram[parameter]) } break case 'string': scram = { name: options.$scram, value: +coalesce(arguable.ultimate[options.$scram], scram) } break case 'number': scram = { name: null, value: scram } break } arguable.scram = scram.value var destructible = new Destructible(arguable.scram, identifier) var trap = { SIGINT: 'destroy', SIGTERM: 'destroy', SIGHUP: 'swallow' } var $trap = ('$trap' in options) ? options.$trap : {} var $untrap = ('$untrap' in options) ? options.$untrap : isMainModule ? false : true var signals = coalesce(options.$signals, process) switch (typeof $trap) { case 'boolean': if (!$trap) { trap = {} } break case 'string': for (var signal in trap) { trap[signal] = $trap } break default: for (var signal in $trap) { trap[signal] = $trap[signal] } break } var traps = [], listener for (var signal in trap) { switch (trap[signal]) { case 'destroy': traps.push({ signal: signal, listener: listener = function () { // We don't use `bind` because some signal handlers send // an argument and `destroy` asserts that it receives // none. destructible.destroy() } }) signals.on(signal, listener) break case 'swallow': traps.push({ signal: signal, listener: listener = function () {} }) signals.on(signal, listener) break case 'default': break } } var exit = new Signal var child = new Child(destructible, exit, options) destructible.completed.wait(function () { var vargs = [] vargs.push.apply(vargs, arguments) if ($untrap) { traps.forEach(function (trap) { signals.removeListener(trap.signal, trap.listener) }) } if (vargs[0]) { try { rescue([{ name: 'message', when: [ '..', /^bigeasy\.arguable#abend$/m, 'only' ] }])(function (rescued) { exit.unlatch(rescued.errors[0]) })(vargs[0]) } catch (error) { exit.unlatch(vargs[0]) } } else { var exitCode = coalesce(arguable.exitCode, process.exitCode, 0) exit.unlatch.apply(exit, [ null ].concat(exitCode, vargs.slice(1))) } }) var initialize = destructible.ephemeral('initialize') destructible.durable('main', cadence(function (async, destructible) { arguable.assert( scram.name == null || (Number.isInteger(scram.value) && scram.value > 0), scram.name + ' must be an integer greater than zero', scram.value) async([function () { main(destructible, arguable, async()) }, function (error) { initialize(error) throw error }], [], function (vargs) { initialize() return vargs.concat(child) }) }), function () { if (arguments[0] == null) { callback.apply(null, arguments) } else { destructible.destroy() exit.wait(callback) } }) } if (module === process.mainModule) { cadence(function (async, main, argv) { async(function () { main(argv, async()) }, function (child) { child.exit(async()) }) })(module.exports, process.argv.slice(2), require('./exit')(process)) } }
index.js
var stream = require('stream') var events = require('events') var cadence = require('cadence') var Destructible = require('destructible') var coalesce = require('extant') var Arguable = require('./arguable') var rescue = require('rescue') var Signal = require('signal') var Child = require('./child') var Usage = require('./usage') module.exports = function () { // Variadic arguments. var vargs = [] vargs.push.apply(vargs, arguments) // First argument is always the module. var module = vargs.shift() // Usage source can be specified explicitly, or else it is sought in the // comments of the main module. var source = typeof vargs[0] == 'string' ? vargs.shift() : module.filename var usage = Usage(source) // Optional options that both configure Arguable and provide our dear user // with a means to specify production objects for production and mock // objects for testing. var definition = typeof vargs[0] == 'object' ? vargs.shift() : {} // The main method. var main = vargs.shift() // TODO How about an optinal method here for command line completion logic? module.exports = function (argv, invocation, callback) { var vargs = [] vargs.push.apply(vargs, arguments) var argv = vargs.shift() var options = {} for (var option in definition) { options[option] = definition[option] } for (var option in invocation) { options[option] = invocation[option] } var parameters = [] if (!Array.isArray(argv)) { argv = [ argv ] } argv = argv.slice() while (argv.length != 0) { var argument = argv.shift() switch (typeof argument) { case 'object': // TODO Probably want `Arguable.flatten({ name: 'a', value: 1 // }, ...)`. // TODO Flattening would require knowing from the parameters // whether or not they accepted arguments in the case of // switch arguments. if (Array.isArray(argument)) { argv.unshift.apply(argv, argument) } else { var unshift = [] for (var name in argument) { unshift.push('--' + name, argument[name].toString()) } argv.unshift(unshift) } break default: parameters.push(argument) break } } var callback = vargs.pop() var pipes = {} if (options.$pipes != null) { options.$pipes = {} for (var fd in coalesce(definition.$pipes, {})) { options.$pipes[fd] = definition.$pipes[fd] } for (var fd in coalesce(invocation.$pipes, {})) { options.$pipes[fd] = invocation.$pipes[fd] } for (var fd in coalesce(options.$pipes)) { if (options.$pipes[fd] instanceof require('stream').Stream) { pipes[fd] = options.$pipes[fd] } else { var socket = { fd: +fd } for (var property in options.$pipes[fd]) { socket[property] = options.$pipes[fd][property] } pipes[fd] = new require('net').Socket(socket) } } } var isMainModule = ('$isMainModule' in options) ? options.$isMainModule : process.mainModule === module var lang = coalesce(options.$lang, process.env.LANG && process.env.LANG.split('.')[0]) var destructible, identifier var identifier = ('$destructible' in options) ? typeof options.$destructible == 'boolean' ? module.filename : options.$destructible : module.filename var arguable = new Arguable(usage, parameters, { identifier: identifier, isMainModule: isMainModule, stdin: coalesce(options.$stdin, process.stdin), stdout: coalesce(options.$stdout, process.stdout), stderr: coalesce(options.$stderr, process.stderr), options: options, pipes: pipes, lang: lang }) var scram = coalesce(options.$scram, 10000) switch (typeof scram) { case 'object': var parameter = Object.keys(scram)[0] scram = { name: parameter, value: +coalesce(arguable.ultimate[parameter], scram[parameter]) } break case 'string': scram = { name: options.$scram, value: +coalesce(arguable.ultimate[options.$scram], scram) } break case 'number': scram = { name: null, value: scram } break } arguable.scram = scram.value var destructible = new Destructible(scram, identifier) var trap = { SIGINT: 'destroy', SIGTERM: 'destroy', SIGHUP: 'swallow' } var $trap = ('$trap' in options) ? options.$trap : {} var $untrap = ('$untrap' in options) ? options.$untrap : isMainModule ? false : true var signals = coalesce(options.$signals, process) switch (typeof $trap) { case 'boolean': if (!$trap) { trap = {} } break case 'string': for (var signal in trap) { trap[signal] = $trap } break default: for (var signal in $trap) { trap[signal] = $trap[signal] } break } var traps = [], listener for (var signal in trap) { switch (trap[signal]) { case 'destroy': traps.push({ signal: signal, listener: listener = function () { // We don't use `bind` because some signal handlers send // an argument and `destroy` asserts that it receives // none. destructible.destroy() } }) signals.on(signal, listener) break case 'swallow': traps.push({ signal: signal, listener: listener = function () {} }) signals.on(signal, listener) break case 'default': break } } var exit = new Signal var child = new Child(destructible, exit, options) destructible.completed.wait(function () { var vargs = [] vargs.push.apply(vargs, arguments) if ($untrap) { traps.forEach(function (trap) { signals.removeListener(trap.signal, trap.listener) }) } if (vargs[0]) { try { rescue([{ name: 'message', when: [ '..', /^bigeasy\.arguable#abend$/m, 'only' ] }])(function (rescued) { exit.unlatch(rescued.errors[0]) })(vargs[0]) } catch (error) { exit.unlatch(vargs[0]) } } else { var exitCode = coalesce(arguable.exitCode, process.exitCode, 0) exit.unlatch.apply(exit, [ null ].concat(exitCode, vargs.slice(1))) } }) var initialize = destructible.ephemeral('initialize') destructible.durable('main', cadence(function (async, destructible) { arguable.assert( scram.name == null || (Number.isInteger(scram.value) && scram.value > 0), scram.name + ' must be an integer greater than zero', scram.value) async([function () { main(destructible, arguable, async()) }, function (error) { initialize(error) throw error }], [], function (vargs) { initialize() return vargs.concat(child) }) }), function () { if (arguments[0] == null) { callback.apply(null, arguments) } else { destructible.destroy() exit.wait(callback) } }) } if (module === process.mainModule) { cadence(function (async, main, argv) { async(function () { main(argv, async()) }, function (child) { child.exit(async()) }) })(module.exports, process.argv.slice(2), require('./exit')(process)) } }
Correctly set `Destructible` scram. Was passing the full hash and not the shutdown value.
index.js
Correctly set `Destructible` scram.
<ide><path>ndex.js <ide> <ide> arguable.scram = scram.value <ide> <del> var destructible = new Destructible(scram, identifier) <add> var destructible = new Destructible(arguable.scram, identifier) <ide> <ide> var trap = { SIGINT: 'destroy', SIGTERM: 'destroy', SIGHUP: 'swallow' } <ide> var $trap = ('$trap' in options) ? options.$trap : {}
Java
apache-2.0
6e332c335b07c6624aa38542cd234c39c849d8ae
0
baomidou/mybatis-plus,baomidou/mybatis-plus
/* * Copyright (c) 2011-2016, hubin ([email protected]). * <p> * 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 * <p> * http://www.apache.org/licenses/LICENSE-2.0 * <p> * 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.baomidou.mybatisplus.extension.service.impl; import java.io.Serializable; import java.util.Collection; import java.util.List; import java.util.Map; import java.util.Objects; import java.util.stream.Collectors; import org.apache.ibatis.binding.MapperMethod; import org.apache.ibatis.session.SqlSession; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.transaction.annotation.Transactional; import com.baomidou.mybatisplus.core.conditions.Wrapper; import com.baomidou.mybatisplus.core.enums.SqlMethod; import com.baomidou.mybatisplus.core.mapper.BaseMapper; import com.baomidou.mybatisplus.core.metadata.IPage; import com.baomidou.mybatisplus.core.metadata.TableInfo; import com.baomidou.mybatisplus.core.toolkit.CollectionUtils; import com.baomidou.mybatisplus.core.toolkit.Constants; import com.baomidou.mybatisplus.core.toolkit.ExceptionUtils; import com.baomidou.mybatisplus.core.toolkit.ObjectUtils; import com.baomidou.mybatisplus.core.toolkit.ReflectionKit; import com.baomidou.mybatisplus.core.toolkit.StringUtils; import com.baomidou.mybatisplus.core.toolkit.TableInfoHelper; import com.baomidou.mybatisplus.core.toolkit.sql.SqlHelper; import com.baomidou.mybatisplus.extension.service.IService; /** * <p> * IService 实现类( 泛型:M 是 mapper 对象,T 是实体 , PK 是主键泛型 ) * </p> * * @author hubin * @since 2018-06-23 */ @SuppressWarnings("unchecked") public class ServiceImpl<M extends BaseMapper<T>, T> implements IService<T> { @Autowired protected M baseMapper; /** * <p> * 判断数据库操作是否成功 * </p> * <p> * 注意!! 该方法为 Integer 判断,不可传入 int 基本类型 * </p> * * @param result 数据库操作返回影响条数 * @return boolean */ protected static boolean retBool(Integer result) { return SqlHelper.retBool(result); } protected Class<T> currentModelClass() { return ReflectionKit.getSuperClassGenericType(getClass(), 1); } /** * <p> * 批量操作 SqlSession * </p> */ protected SqlSession sqlSessionBatch() { return SqlHelper.sqlSessionBatch(currentModelClass()); } /** * 获取SqlStatement * * @param sqlMethod * @return */ protected String sqlStatement(SqlMethod sqlMethod) { return SqlHelper.table(currentModelClass()).getSqlStatement(sqlMethod.getMethod()); } @Override public boolean save(T entity) { return ServiceImpl.retBool(baseMapper.insert(entity)); } @Transactional(rollbackFor = Exception.class) @Override public boolean saveBatch(Collection<T> entityList) { return saveBatch(entityList, 30); } /** * 批量插入 * * @param entityList * @param batchSize * @return */ @Transactional(rollbackFor = Exception.class) @Override public boolean saveBatch(Collection<T> entityList, int batchSize) { if (CollectionUtils.isEmpty(entityList)) { throw new IllegalArgumentException("Error: entityList must not be empty"); } try (SqlSession batchSqlSession = sqlSessionBatch()) { int i = 0; String sqlStatement = sqlStatement(SqlMethod.INSERT_ONE); for (T anEntityList : entityList) { batchSqlSession.insert(sqlStatement, anEntityList); if (i >= 1 && i % batchSize == 0) { batchSqlSession.flushStatements(); } i++; } batchSqlSession.flushStatements(); } catch (Throwable e) { throw ExceptionUtils.mpe("Error: Cannot execute saveBatch Method. Cause", e); } return true; } /** * <p> * TableId 注解存在更新记录,否插入一条记录 * </p> * * @param entity 实体对象 * @return boolean */ @Override public boolean saveOrUpdate(T entity) { if (null != entity) { Class<?> cls = entity.getClass(); TableInfo tableInfo = TableInfoHelper.getTableInfo(cls); if (null != tableInfo && StringUtils.isNotEmpty(tableInfo.getKeyProperty())) { Object idVal = ReflectionKit.getMethodValue(cls, entity, tableInfo.getKeyProperty()); if (StringUtils.checkValNull(idVal)) { return save(entity); } else { /* * 更新成功直接返回,失败执行插入逻辑 */ return updateById(entity) || save(entity); } } else { throw ExceptionUtils.mpe("Error: Can not execute. Could not find @TableId."); } } return false; } @Transactional(rollbackFor = Exception.class) @Override public boolean saveOrUpdateBatch(Collection<T> entityList) { return saveOrUpdateBatch(entityList, 30); } @Transactional(rollbackFor = Exception.class) @Override public boolean saveOrUpdateBatch(Collection<T> entityList, int batchSize) { if (CollectionUtils.isEmpty(entityList)) { throw new IllegalArgumentException("Error: entityList must not be empty"); } try (SqlSession batchSqlSession = sqlSessionBatch()) { for (T anEntityList : entityList) { saveOrUpdate(anEntityList); } batchSqlSession.flushStatements(); } catch (Throwable e) { throw ExceptionUtils.mpe("Error: Cannot execute saveOrUpdateBatch Method. Cause", e); } return true; } @Override public boolean removeById(Serializable id) { return SqlHelper.delBool(baseMapper.deleteById(id)); } @Override public boolean removeByMap(Map<String, Object> columnMap) { if (ObjectUtils.isEmpty(columnMap)) { throw ExceptionUtils.mpe("removeByMap columnMap is empty."); } return SqlHelper.delBool(baseMapper.deleteByMap(columnMap)); } @Override public boolean remove(Wrapper<T> wrapper) { return SqlHelper.delBool(baseMapper.delete(wrapper)); } @Override public boolean removeByIds(Collection<? extends Serializable> idList) { return SqlHelper.delBool(baseMapper.deleteBatchIds(idList)); } @Override public boolean updateById(T entity) { return ServiceImpl.retBool(baseMapper.updateById(entity)); } @Override public boolean update(T entity, Wrapper<T> updateWrapper) { return ServiceImpl.retBool(baseMapper.update(entity, updateWrapper)); } @Transactional(rollbackFor = Exception.class) @Override public boolean updateBatchById(Collection<T> entityList) { return updateBatchById(entityList, 30); } @Transactional(rollbackFor = Exception.class) @Override public boolean updateBatchById(Collection<T> entityList, int batchSize) { if (CollectionUtils.isEmpty(entityList)) { throw new IllegalArgumentException("Error: entityList must not be empty"); } try (SqlSession batchSqlSession = sqlSessionBatch()) { int i = 0; String sqlStatement = sqlStatement(SqlMethod.UPDATE_BY_ID); for (T anEntityList : entityList) { MapperMethod.ParamMap<T> param = new MapperMethod.ParamMap<>(); param.put(Constants.ENTITY, anEntityList); batchSqlSession.update(sqlStatement, param); if (i >= 1 && i % batchSize == 0) { batchSqlSession.flushStatements(); } i++; } batchSqlSession.flushStatements(); } catch (Throwable e) { throw ExceptionUtils.mpe("Error: Cannot execute updateBatchById Method. Cause", e); } return true; } @Override public T getById(Serializable id) { return baseMapper.selectById(id); } @Override public Collection<T> listByIds(Collection<? extends Serializable> idList) { return baseMapper.selectBatchIds(idList); } @Override public Collection<T> listByMap(Map<String, Object> columnMap) { return baseMapper.selectByMap(columnMap); } @Override public T getOne(Wrapper<T> queryWrapper) { return SqlHelper.getObject(baseMapper.selectList(queryWrapper)); } @Override public Map<String, Object> getMap(Wrapper<T> queryWrapper) { return SqlHelper.getObject(baseMapper.selectMaps(queryWrapper)); } @Override public Object getObj(Wrapper<T> queryWrapper) { return SqlHelper.getObject(baseMapper.selectObjs(queryWrapper)); } @Override public int count(Wrapper<T> queryWrapper) { return SqlHelper.retCount(baseMapper.selectCount(queryWrapper)); } @Override public List<T> list(Wrapper<T> queryWrapper) { return baseMapper.selectList(queryWrapper); } @Override public IPage<T> page(IPage<T> page, Wrapper<T> queryWrapper) { queryWrapper = (Wrapper<T>) SqlHelper.fillWrapper(page, queryWrapper); return baseMapper.selectPage(page, queryWrapper); } @Override public List<Map<String, Object>> listMaps(Wrapper<T> queryWrapper) { return baseMapper.selectMaps(queryWrapper); } @Override public List<Object> listObjs(Wrapper<T> queryWrapper) { return baseMapper.selectObjs(queryWrapper).stream().filter(Objects::nonNull).collect(Collectors.toList()); } @Override public IPage<Map<String, Object>> pageMaps(IPage<T> page, Wrapper<T> queryWrapper) { queryWrapper = (Wrapper<T>) SqlHelper.fillWrapper(page, queryWrapper); return baseMapper.selectMapsPage(page, queryWrapper); } }
mybatis-plus-extension/src/main/java/com/baomidou/mybatisplus/extension/service/impl/ServiceImpl.java
/* * Copyright (c) 2011-2016, hubin ([email protected]). * <p> * 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 * <p> * http://www.apache.org/licenses/LICENSE-2.0 * <p> * 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.baomidou.mybatisplus.extension.service.impl; import java.io.Serializable; import java.util.Collection; import java.util.List; import java.util.Map; import org.apache.ibatis.binding.MapperMethod; import org.apache.ibatis.session.SqlSession; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.transaction.annotation.Transactional; import com.baomidou.mybatisplus.core.conditions.Wrapper; import com.baomidou.mybatisplus.core.enums.SqlMethod; import com.baomidou.mybatisplus.core.mapper.BaseMapper; import com.baomidou.mybatisplus.core.metadata.IPage; import com.baomidou.mybatisplus.core.metadata.TableInfo; import com.baomidou.mybatisplus.core.toolkit.CollectionUtils; import com.baomidou.mybatisplus.core.toolkit.Constants; import com.baomidou.mybatisplus.core.toolkit.ExceptionUtils; import com.baomidou.mybatisplus.core.toolkit.ObjectUtils; import com.baomidou.mybatisplus.core.toolkit.ReflectionKit; import com.baomidou.mybatisplus.core.toolkit.StringUtils; import com.baomidou.mybatisplus.core.toolkit.TableInfoHelper; import com.baomidou.mybatisplus.core.toolkit.sql.SqlHelper; import com.baomidou.mybatisplus.extension.service.IService; /** * <p> * IService 实现类( 泛型:M 是 mapper 对象,T 是实体 , PK 是主键泛型 ) * </p> * * @author hubin * @since 2018-06-23 */ @SuppressWarnings("unchecked") public class ServiceImpl<M extends BaseMapper<T>, T> implements IService<T> { @Autowired protected M baseMapper; /** * <p> * 判断数据库操作是否成功 * </p> * <p> * 注意!! 该方法为 Integer 判断,不可传入 int 基本类型 * </p> * * @param result 数据库操作返回影响条数 * @return boolean */ protected static boolean retBool(Integer result) { return SqlHelper.retBool(result); } protected Class<T> currentModelClass() { return ReflectionKit.getSuperClassGenericType(getClass(), 1); } /** * <p> * 批量操作 SqlSession * </p> */ protected SqlSession sqlSessionBatch() { return SqlHelper.sqlSessionBatch(currentModelClass()); } /** * 获取SqlStatement * * @param sqlMethod * @return */ protected String sqlStatement(SqlMethod sqlMethod) { return SqlHelper.table(currentModelClass()).getSqlStatement(sqlMethod.getMethod()); } @Override public boolean save(T entity) { return ServiceImpl.retBool(baseMapper.insert(entity)); } @Transactional(rollbackFor = Exception.class) @Override public boolean saveBatch(Collection<T> entityList) { return saveBatch(entityList, 30); } /** * 批量插入 * * @param entityList * @param batchSize * @return */ @Transactional(rollbackFor = Exception.class) @Override public boolean saveBatch(Collection<T> entityList, int batchSize) { if (CollectionUtils.isEmpty(entityList)) { throw new IllegalArgumentException("Error: entityList must not be empty"); } try (SqlSession batchSqlSession = sqlSessionBatch()) { int i = 0; String sqlStatement = sqlStatement(SqlMethod.INSERT_ONE); for (T anEntityList : entityList) { batchSqlSession.insert(sqlStatement, anEntityList); if (i >= 1 && i % batchSize == 0) { batchSqlSession.flushStatements(); } i++; } batchSqlSession.flushStatements(); } catch (Throwable e) { throw ExceptionUtils.mpe("Error: Cannot execute saveBatch Method. Cause", e); } return true; } /** * <p> * TableId 注解存在更新记录,否插入一条记录 * </p> * * @param entity 实体对象 * @return boolean */ @Override public boolean saveOrUpdate(T entity) { if (null != entity) { Class<?> cls = entity.getClass(); TableInfo tableInfo = TableInfoHelper.getTableInfo(cls); if (null != tableInfo && StringUtils.isNotEmpty(tableInfo.getKeyProperty())) { Object idVal = ReflectionKit.getMethodValue(cls, entity, tableInfo.getKeyProperty()); if (StringUtils.checkValNull(idVal)) { return save(entity); } else { /* * 更新成功直接返回,失败执行插入逻辑 */ return updateById(entity) || save(entity); } } else { throw ExceptionUtils.mpe("Error: Can not execute. Could not find @TableId."); } } return false; } @Transactional(rollbackFor = Exception.class) @Override public boolean saveOrUpdateBatch(Collection<T> entityList) { return saveOrUpdateBatch(entityList, 30); } @Transactional(rollbackFor = Exception.class) @Override public boolean saveOrUpdateBatch(Collection<T> entityList, int batchSize) { if (CollectionUtils.isEmpty(entityList)) { throw new IllegalArgumentException("Error: entityList must not be empty"); } try (SqlSession batchSqlSession = sqlSessionBatch()) { for (T anEntityList : entityList) { saveOrUpdate(anEntityList); } batchSqlSession.flushStatements(); } catch (Throwable e) { throw ExceptionUtils.mpe("Error: Cannot execute saveOrUpdateBatch Method. Cause", e); } return true; } @Override public boolean removeById(Serializable id) { return SqlHelper.delBool(baseMapper.deleteById(id)); } @Override public boolean removeByMap(Map<String, Object> columnMap) { if (ObjectUtils.isEmpty(columnMap)) { throw ExceptionUtils.mpe("removeByMap columnMap is empty."); } return SqlHelper.delBool(baseMapper.deleteByMap(columnMap)); } @Override public boolean remove(Wrapper<T> wrapper) { return SqlHelper.delBool(baseMapper.delete(wrapper)); } @Override public boolean removeByIds(Collection<? extends Serializable> idList) { return SqlHelper.delBool(baseMapper.deleteBatchIds(idList)); } @Override public boolean updateById(T entity) { return ServiceImpl.retBool(baseMapper.updateById(entity)); } @Override public boolean update(T entity, Wrapper<T> updateWrapper) { return ServiceImpl.retBool(baseMapper.update(entity, updateWrapper)); } @Transactional(rollbackFor = Exception.class) @Override public boolean updateBatchById(Collection<T> entityList) { return updateBatchById(entityList, 30); } @Transactional(rollbackFor = Exception.class) @Override public boolean updateBatchById(Collection<T> entityList, int batchSize) { if (CollectionUtils.isEmpty(entityList)) { throw new IllegalArgumentException("Error: entityList must not be empty"); } try (SqlSession batchSqlSession = sqlSessionBatch()) { int i = 0; String sqlStatement = sqlStatement(SqlMethod.UPDATE_BY_ID); for (T anEntityList : entityList) { MapperMethod.ParamMap<T> param = new MapperMethod.ParamMap<>(); param.put(Constants.ENTITY, anEntityList); batchSqlSession.update(sqlStatement, param); if (i >= 1 && i % batchSize == 0) { batchSqlSession.flushStatements(); } i++; } batchSqlSession.flushStatements(); } catch (Throwable e) { throw ExceptionUtils.mpe("Error: Cannot execute updateBatchById Method. Cause", e); } return true; } @Override public T getById(Serializable id) { return baseMapper.selectById(id); } @Override public Collection<T> listByIds(Collection<? extends Serializable> idList) { return baseMapper.selectBatchIds(idList); } @Override public Collection<T> listByMap(Map<String, Object> columnMap) { return baseMapper.selectByMap(columnMap); } @Override public T getOne(Wrapper<T> queryWrapper) { return SqlHelper.getObject(baseMapper.selectList(queryWrapper)); } @Override public Map<String, Object> getMap(Wrapper<T> queryWrapper) { return SqlHelper.getObject(baseMapper.selectMaps(queryWrapper)); } @Override public Object getObj(Wrapper<T> queryWrapper) { return SqlHelper.getObject(baseMapper.selectObjs(queryWrapper)); } @Override public int count(Wrapper<T> queryWrapper) { return SqlHelper.retCount(baseMapper.selectCount(queryWrapper)); } @Override public List<T> list(Wrapper<T> queryWrapper) { return baseMapper.selectList(queryWrapper); } @Override public IPage<T> page(IPage<T> page, Wrapper<T> queryWrapper) { queryWrapper = (Wrapper<T>) SqlHelper.fillWrapper(page, queryWrapper); return baseMapper.selectPage(page, queryWrapper); } @Override public List<Map<String, Object>> listMaps(Wrapper<T> queryWrapper) { return baseMapper.selectMaps(queryWrapper); } @Override public List<Object> listObjs(Wrapper<T> queryWrapper) { return baseMapper.selectObjs(queryWrapper); } @Override public IPage<Map<String, Object>> pageMaps(IPage<T> page, Wrapper<T> queryWrapper) { queryWrapper = (Wrapper<T>) SqlHelper.fillWrapper(page, queryWrapper); return baseMapper.selectMapsPage(page, queryWrapper); } }
过滤掉selectObjs查询结果集为空的情况
mybatis-plus-extension/src/main/java/com/baomidou/mybatisplus/extension/service/impl/ServiceImpl.java
过滤掉selectObjs查询结果集为空的情况
<ide><path>ybatis-plus-extension/src/main/java/com/baomidou/mybatisplus/extension/service/impl/ServiceImpl.java <ide> import java.util.Collection; <ide> import java.util.List; <ide> import java.util.Map; <add>import java.util.Objects; <add>import java.util.stream.Collectors; <ide> <ide> import org.apache.ibatis.binding.MapperMethod; <ide> import org.apache.ibatis.session.SqlSession; <ide> <ide> @Override <ide> public List<Object> listObjs(Wrapper<T> queryWrapper) { <del> return baseMapper.selectObjs(queryWrapper); <add> return baseMapper.selectObjs(queryWrapper).stream().filter(Objects::nonNull).collect(Collectors.toList()); <ide> } <ide> <ide> @Override
JavaScript
apache-2.0
858066b80384d35d5030c7c8473816d4ce83b452
0
quisquous/cactbot,quisquous/cactbot,quisquous/cactbot,quisquous/cactbot,quisquous/cactbot,quisquous/cactbot
import ZoneId from '../../../../../resources/zone_id.js'; export default { zoneId: ZoneId.EdensPromiseUmbra, damageWarn: { 'E9N The Art Of Darkness 1': '5223', // left-right cleave 'E9N The Art Of Darkness 2': '5224', // left-right cleave 'E9N Wide-Angle Particle Beam': '5AFF', // frontal cleave tutorial mechanic 'E9N Wide-Angle Phaser': '55E1', // wide-angle "sides" 'E9N Bad Vibrations': '55E6', // tethered outside giant tree ground aoes 'E9N Earth-Shattering Particle Beam': '5225', // missing towers? 'E9N Anti-Air Particle Beam': '55DC', // "get out" during panels 'E9N Zero-Form Particle Beam 2': '55DB', // Clone line aoes w/ Anti-Air Particle Beam }, damageFail: { 'E9N Withdraw': '5534', // Slow to break seed chain, get sucked back in yikes 'E9N Aetherosynthesis': '5535', // Standing on seeds during explosion (possibly via Withdraw) }, shareWarn: { 'E9N Zero-Form Particle Beam 1': '55EB', // tank laser with marker }, };
ui/oopsyraidsy/data/05-shb/raid/e9n.js
import ZoneId from '../../../../../resources/zone_id.js'; export default { zoneId: ZoneId.EdensPromiseUmbra, damageWarn: { }, damageFail: { }, };
oopsy: add e9n warnings (#2255)
ui/oopsyraidsy/data/05-shb/raid/e9n.js
oopsy: add e9n warnings (#2255)
<ide><path>i/oopsyraidsy/data/05-shb/raid/e9n.js <ide> export default { <ide> zoneId: ZoneId.EdensPromiseUmbra, <ide> damageWarn: { <add> 'E9N The Art Of Darkness 1': '5223', // left-right cleave <add> 'E9N The Art Of Darkness 2': '5224', // left-right cleave <add> 'E9N Wide-Angle Particle Beam': '5AFF', // frontal cleave tutorial mechanic <add> 'E9N Wide-Angle Phaser': '55E1', // wide-angle "sides" <add> 'E9N Bad Vibrations': '55E6', // tethered outside giant tree ground aoes <add> 'E9N Earth-Shattering Particle Beam': '5225', // missing towers? <add> 'E9N Anti-Air Particle Beam': '55DC', // "get out" during panels <add> 'E9N Zero-Form Particle Beam 2': '55DB', // Clone line aoes w/ Anti-Air Particle Beam <ide> }, <ide> damageFail: { <add> 'E9N Withdraw': '5534', // Slow to break seed chain, get sucked back in yikes <add> 'E9N Aetherosynthesis': '5535', // Standing on seeds during explosion (possibly via Withdraw) <add> }, <add> shareWarn: { <add> 'E9N Zero-Form Particle Beam 1': '55EB', // tank laser with marker <ide> }, <ide> };
Java
mit
014296298cb7cf319c8532f58f9a3b600249f961
0
EricSzla/Assignment_3,EricSzla/Assignment_3
package erpam; import processing.core.*; import processing.core.PImage; import processing.video.*; import processing.serial.*; import oscP5.*; /** * Created by Eryk Szlachetka and Pamela Sabio on 14/03/2016. **/ public class Main extends PApplet { // For Arduino connection Serial myPort; RemoteControl BT; Kinect kinect; PImage erpam; // Menu image int x = 0; // Used for animation in menu int choice = 0; // User choice (menu) float rightspeed = 0; // Right speed of the motor float leftspeed = 0; // Left speed of the motor char currentGear = 'N'; // Use this code if HeadSet connected // muse-io --device Muse --osc osc.udp://localhost:5000 OscP5 oscp5; float cVar = 0; // Concetration data float aVar = 0; // Accelometer data float checkA = 800; String passVar = ""; HeadSet headSet; float checkcVar = 0; int pdir = 0; int sdir = 0; int wdir = 0; public void settings() { size(displayWidth, displayHeight); } public void setup() { rectMode(CENTER); printArray(Serial.list()); // Prints the serial lists // Start the Bluetooth port String portName = Serial.list()[2]; //change the 0 to a 1 or 2 etc. to match your port try { myPort = new Serial(this, portName, 9600); // Initialize myPort and set the bit rate }catch (RuntimeException e) { e.printStackTrace(); } frameRate(60); erpam = loadImage("erpam.png"); BT = new RemoteControl(this); smooth(); kinect = new Kinect(this); // Headset Connection try { oscp5 = new OscP5(this, 5000); headSet = new HeadSet(this); }catch (RuntimeException e) { e.printStackTrace(); } } public void draw() { switch (choice) { case 0: textSize(12); menu(); break; case 1: BT.render(currentGear); break; case 2: background(0); fill(255); text("Press any key to start..", width/2,height/2); rect(width/10,height/10,200,50); fill(0); text("Menu",width/10,height/10 + 10); break; case 3: headSet.updateSpeedo(sdir); headSet.updatePetrol(pdir); headSet.render(); fill(255); rect(width/10,height/10,200,50); fill(0); text("Menu",width/10,height/10 + 10); break; case 4: kinect.render(); kinect.control(); default: menu(); } } public void mouseClicked() { if(choice == 0) { if (mouseX >= width / 2 - 100 && mouseX <= width / 2 + 100) // Check if mouse is in the middle { if (mouseY >= height / 2 - 25 && mouseY <= height / 2 + 25) // Check if mouse is in the first square { choice = 1; } else if (mouseY >= height / 2 + 75 && mouseY <= height / 2 + 125) { choice = 2; } else if (mouseY >= height / 2 + 175 && mouseY <= height / 2 + 225) { choice = 3; } } }else { // If go back to menu button pressed, change the choice. if(mouseX < width/10 + 100 && mouseX > width/10 - 100) { if(mouseY < height/10 +25 && mouseY > height/10 - 25) { choice = 0; } } } } public void menu() { background(0); BT.leftMotorSlider.hide(); BT.rightMotorSlider.hide(); image(erpam, width/2,erpam.height); if (x < width / 6) { x += 10; } fill(255); text("---> TERRITORY MAPPING", x, height / 3); rect(width/2,height/2,200,50); rect(width/2,height/2 + 100, 200, 50); rect(width/2,height/2 + 200, 200, 50); rect(width/2,height/2 + 300, 200, 50); fill(0); textAlign(CENTER); text("Bluetooth Control", width/2,height/2); text("AI Robot", width/2, height/2 + 100); text("Headset Control", width/2, height/2 + 200); text("Kinect Control", width/2, height/2 + 300); } public void keyPressed() { if(choice == 2) { myPort.write("2ff,"); } if (choice == 1) { if (keyCode == 'W') { acceleration('W'); } else if (keyCode == 'S') { acceleration('S'); } else if (keyCode == 'A') { turning('A'); } else if (keyCode == 'D') { turning('D'); } else { leftspeed = 0; rightspeed = 0; } myPort.write("1L" + leftspeed + ","); myPort.write("1R" + rightspeed + ","); BT.update(rightspeed, leftspeed); }else if(choice == 3) { // Emergency stop for headSet myPort.write("1L" + 0 + ","); myPort.write("1R" + 0 + ","); } } public void turning(char value) { if (value == 'A') { if (rightspeed >= 0 && leftspeed >= 50) { rightspeed = 250; leftspeed -= 50; } else if (rightspeed < 0 && leftspeed < 0) { rightspeed = -230; leftspeed += 50; } } else if (value == 'D') { if (rightspeed >= 50 && leftspeed >= 0) { leftspeed = 200; rightspeed -= 50; } else if (rightspeed < 0 && leftspeed < 0) { leftspeed = -200; rightspeed += 50; } } } public void acceleration(char value) { if (value == 'W') // Go forward { if (rightspeed < 0 || leftspeed < 0) { rightspeed = 0; leftspeed = 0; currentGear = 'N'; } else { rightspeed = 250; leftspeed = 200; currentGear = 'D'; } } else if (value == 'S') // Go backward { if (rightspeed <= 0 && leftspeed <= 0) { rightspeed = -230; leftspeed = -200; currentGear = 'R'; } else { rightspeed = 0; leftspeed = 0; currentGear = 'N'; } } } public void movieEvent(Movie m) { m.read(); } public static void main(String[] args) { PApplet.main(Main.class.getName()); } // Use this code if HeadSet connected public void oscEvent(OscMessage msg) { if (choice == 3) { if (msg.checkAddrPattern("/muse/elements/experimental/concentration") == true) { cVar = msg.get(0).floatValue(); System.out.println("C: " + cVar); } if(headSet.petrol == false) { if (msg.checkAddrPattern("/muse/elements/experimental/mellow") == true) { System.out.println("Petrol: " + headSet.petrol); float mVar = msg.get(0).floatValue(); // if (headSet.petrol == false) { System.out.println("Mellow: " + mVar); if (mVar == 1) { pdir = 1; } else { pdir = 3; } // } } } if (cVar > 0.3 && headSet.petrol == true ) { myPort.clear(); pdir = 0; sdir = 1; headSet.checkPetrol = true; if (msg.checkAddrPattern("/muse/acc") == true) { aVar = msg.get(2).floatValue(); if ((aVar < -100 && (checkA > -150 && checkA < 150) || (aVar < -150 && checkA > 150) || ((aVar > -150 && aVar < 150) && checkA < -150) || (aVar > -150 && aVar < 150) && checkA > 150) || (aVar > 150 && (checkA < 150 && checkA > -150)) || (aVar > 150 && checkA < -150)) { passVar = "3A" + aVar + ","; headSet.pass(myPort, passVar); checkA = aVar; checkcVar = cVar; headSet.updateWheel(aVar); } } } else if ((cVar < 0.3 && checkcVar > 0.3 || (headSet.petrol == false && headSet.checkPetrol == true) ) ){ // sdir = 0; pdir = 3; myPort.write("1L" + 0 + ","); myPort.write("1R" + 0 + ","); checkcVar = cVar; checkA = 500; currentGear = 'N'; if((headSet.petrol == false && headSet.checkPetrol == true)) { headSet.checkPetrol = false; } } } } }
Processing/src/erpam/Main.java
package erpam; import processing.core.*; import processing.core.PImage; import processing.video.*; import processing.serial.*; import oscP5.*; /** * Created by Eryk Szlachetka and Pamela Sabio on 14/03/2016. **/ public class Main extends PApplet { // For Arduino connection Serial myPort; RemoteControl BT; Kinect kinect; PImage erpam; // Menu image int x = 0; // Used for animation in menu int choice = 0; // User choice (menu) float rightspeed = 0; // Right speed of the motor float leftspeed = 0; // Left speed of the motor char currentGear = 'N'; // Use this code if HeadSet connected // muse-io --device Muse --osc osc.udp://localhost:5000 OscP5 oscp5; float cVar = 0; // Concetration data float aVar = 0; // Accelometer data float checkA = 800; String passVar = ""; HeadSet headSet; float checkcVar = 0; int pdir = 0; int sdir = 0; int wdir = 0; public void settings() { size(displayWidth, displayHeight); } public void setup() { rectMode(CENTER); printArray(Serial.list()); // Prints the serial lists // Start the Bluetooth port String portName = Serial.list()[2]; //change the 0 to a 1 or 2 etc. to match your port try { myPort = new Serial(this, portName, 9600); // Initialize myPort and set the bit rate }catch (RuntimeException e) { e.printStackTrace(); } frameRate(60); erpam = loadImage("erpam.png"); BT = new RemoteControl(this); smooth(); kinect = new Kinect(this); // Headset Connection try { oscp5 = new OscP5(this, 5000); headSet = new HeadSet(this); }catch (RuntimeException e) { e.printStackTrace(); } } public void draw() { switch (choice) { case 0: textSize(12); menu(); break; case 1: BT.render(currentGear); break; case 2: background(0); fill(255); text("Press any key to start..", width/2,height/2); rect(width/10,height/10,200,50); fill(0); text("Menu",width/10,height/10 + 10); break; case 3: headSet.updateSpeedo(sdir); headSet.updatePetrol(pdir); headSet.render(); fill(255); rect(width/10,height/10,200,50); fill(0); text("Menu",width/10,height/10 + 10); break; case 4: kinect.render(); default: menu(); } } public void mouseClicked() { if(choice == 0) { if (mouseX >= width / 2 - 100 && mouseX <= width / 2 + 100) // Check if mouse is in the middle { if (mouseY >= height / 2 - 25 && mouseY <= height / 2 + 25) // Check if mouse is in the first square { choice = 1; } else if (mouseY >= height / 2 + 75 && mouseY <= height / 2 + 125) { choice = 2; } else if (mouseY >= height / 2 + 175 && mouseY <= height / 2 + 225) { choice = 3; } } }else { // If go back to menu button pressed, change the choice. if(mouseX < width/10 + 100 && mouseX > width/10 - 100) { if(mouseY < height/10 +25 && mouseY > height/10 - 25) { choice = 0; } } } } public void menu() { background(0); BT.leftMotorSlider.hide(); BT.rightMotorSlider.hide(); image(erpam, width/2,erpam.height); if (x < width / 6) { x += 10; } fill(255); text("---> TERRITORY MAPPING", x, height / 3); rect(width/2,height/2,200,50); rect(width/2,height/2 + 100, 200, 50); rect(width/2,height/2 + 200, 200, 50); fill(0); textAlign(CENTER); text("Bluetooth Control", width/2,height/2); text("AI Robot", width/2, height/2 + 100); text("Headset Control", width/2, height/2 + 200); } public void keyPressed() { if(choice == 2) { myPort.write("2ff,"); } if (choice == 1) { if (keyCode == 'W') { acceleration('W'); } else if (keyCode == 'S') { acceleration('S'); } else if (keyCode == 'A') { turning('A'); } else if (keyCode == 'D') { turning('D'); } else { leftspeed = 0; rightspeed = 0; } myPort.write("1L" + leftspeed + ","); myPort.write("1R" + rightspeed + ","); BT.update(rightspeed, leftspeed); }else if(choice == 3) { // Emergency stop for headSet myPort.write("1L" + 0 + ","); myPort.write("1R" + 0 + ","); } } public void turning(char value) { if (value == 'A') { if (rightspeed >= 0 && leftspeed >= 50) { rightspeed = 250; leftspeed -= 50; } else if (rightspeed < 0 && leftspeed < 0) { rightspeed = -230; leftspeed += 50; } } else if (value == 'D') { if (rightspeed >= 50 && leftspeed >= 0) { leftspeed = 200; rightspeed -= 50; } else if (rightspeed < 0 && leftspeed < 0) { leftspeed = -200; rightspeed += 50; } } } public void acceleration(char value) { if (value == 'W') // Go forward { if (rightspeed < 0 || leftspeed < 0) { rightspeed = 0; leftspeed = 0; currentGear = 'N'; } else { rightspeed = 250; leftspeed = 200; currentGear = 'D'; } } else if (value == 'S') // Go backward { if (rightspeed <= 0 && leftspeed <= 0) { rightspeed = -230; leftspeed = -200; currentGear = 'R'; } else { rightspeed = 0; leftspeed = 0; currentGear = 'N'; } } } public void movieEvent(Movie m) { m.read(); } public static void main(String[] args) { PApplet.main(Main.class.getName()); } // Use this code if HeadSet connected public void oscEvent(OscMessage msg) { if (choice == 3) { if (msg.checkAddrPattern("/muse/elements/experimental/concentration") == true) { cVar = msg.get(0).floatValue(); System.out.println("C: " + cVar); } if(headSet.petrol == false) { if (msg.checkAddrPattern("/muse/elements/experimental/mellow") == true) { System.out.println("Petrol: " + headSet.petrol); float mVar = msg.get(0).floatValue(); // if (headSet.petrol == false) { System.out.println("Mellow: " + mVar); if (mVar == 1) { pdir = 1; } else { pdir = 3; } // } } } if (cVar > 0.3 && headSet.petrol == true ) { myPort.clear(); pdir = 0; sdir = 1; headSet.checkPetrol = true; if (msg.checkAddrPattern("/muse/acc") == true) { aVar = msg.get(2).floatValue(); if ((aVar < -100 && (checkA > -150 && checkA < 150) || (aVar < -150 && checkA > 150) || ((aVar > -150 && aVar < 150) && checkA < -150) || (aVar > -150 && aVar < 150) && checkA > 150) || (aVar > 150 && (checkA < 150 && checkA > -150)) || (aVar > 150 && checkA < -150)) { passVar = "3A" + aVar + ","; headSet.pass(myPort, passVar); checkA = aVar; checkcVar = cVar; headSet.updateWheel(aVar); } } } else if ((cVar < 0.3 && checkcVar > 0.3 || (headSet.petrol == false && headSet.checkPetrol == true) ) ){ // sdir = 0; pdir = 3; myPort.write("1L" + 0 + ","); myPort.write("1R" + 0 + ","); checkcVar = cVar; checkA = 500; currentGear = 'N'; if((headSet.petrol == false && headSet.checkPetrol == true)) { headSet.checkPetrol = false; } } } } }
Added kinect for menu and in switch statement
Processing/src/erpam/Main.java
Added kinect for menu and in switch statement
<ide><path>rocessing/src/erpam/Main.java <ide> break; <ide> case 4: <ide> kinect.render(); <add> kinect.control(); <ide> default: <ide> menu(); <ide> } <ide> rect(width/2,height/2,200,50); <ide> rect(width/2,height/2 + 100, 200, 50); <ide> rect(width/2,height/2 + 200, 200, 50); <add> rect(width/2,height/2 + 300, 200, 50); <ide> <ide> fill(0); <ide> textAlign(CENTER); <ide> text("Bluetooth Control", width/2,height/2); <ide> text("AI Robot", width/2, height/2 + 100); <ide> text("Headset Control", width/2, height/2 + 200); <add> text("Kinect Control", width/2, height/2 + 300); <ide> } <ide> <ide> public void keyPressed() {
Java
bsd-3-clause
b4e6c5bcc3855cee834bb6c4edc6592e78f4f866
0
kkorolyov/SimpleTools
package dev.kkorolyov.simpleopts; import java.util.Comparator; import java.util.Set; import java.util.TreeSet; /** * A set of {@code Option} objects. */ public class Options { private static final Comparator<Option> optionComparator = new Comparator<Option>() { @Override public int compare(Option o1, Option o2) { return o1.longName().compareTo(o2.longName()); } }; private Set<Option> options = new TreeSet<>(optionComparator); /** * Constructs an empty {@code Options}. */ public Options() { this(null); } /** * Constructs a new {@code Options} for the specified set of options. * @param options supported options in this options set */ public Options(Option[] options) { addAll(options); } /** * Checks if this {@code Options} contains the specified option. * @param toCheck option to check * @return {@code true} if this {@code Options} contains the specified option */ public boolean contains(Option toCheck) { return options.contains(toCheck); } /** * Adds a new option to this options set. * @param toAdd option to add * @return {@code true} if this options set did not already contain the specified option */ public boolean add(Option toAdd) { return options.add(toAdd); } /** * Adds an array of options to this options set. * @param toAdd array to add * @return number of options added */ public int addAll(Option[] toAdd) { int addedCounter = 0; for (Option option : toAdd) { if (options.add(option)) addedCounter++; } return addedCounter; } /** * Removes an option from this options set. * @param toRemove option to remove * @return {@code true} if this options set contained the specified option */ public boolean remove(Option toRemove) { return options.remove(toRemove); } /** @return all options */ public Set<Option> getAllOptions() { return options; } }
src/dev/kkorolyov/simpleopts/Options.java
package dev.kkorolyov.simpleopts; import java.util.HashMap; import java.util.Map; import java.util.Set; import java.util.TreeSet; /** * A set of {@code Option} objects. */ public class Options { private Set<Option> options = new TreeSet<>(); /** * Constructs a new {@code Options} for the specified set of options. * @param options supported options */ public Options(Option[] options) { parse(); } private void parse() { int counter = 0; while (counter < args.length) { Option currentOption = Option.getOption(args[counter]); if (currentOption.requiresArg()) { options.put(currentOption, args[counter + 1]); counter += 2; } else { options.put(currentOption, null); counter += 1; } } } /** @return help string */ public static String help() { StringBuilder toStringBuilder = new StringBuilder("USAGE" + System.lineSeparator()); for (Option option : Option.values()) { toStringBuilder.append(option.description()).append(System.lineSeparator()); } return toStringBuilder.toString(); } /** * Checks if this {@code Options} contains the specified option. * @param toCheck option to check * @return {@code true} if this {@code Options} contains the specified option */ public boolean contains(Option toCheck) { return options.containsKey(toCheck); } /** * Retrieves the argument for a specific option. * @param key option to get argument for * @return option's argument, or {@code null} if does not exist */ public String get(Option key) { return options.get(key); } /** @return all used options */ public Option[] getAllOptions() { return options.keySet().toArray(new Option[options.size()]); } }
Complete Options
src/dev/kkorolyov/simpleopts/Options.java
Complete Options
<ide><path>rc/dev/kkorolyov/simpleopts/Options.java <ide> package dev.kkorolyov.simpleopts; <ide> <del>import java.util.HashMap; <del>import java.util.Map; <add>import java.util.Comparator; <ide> import java.util.Set; <ide> import java.util.TreeSet; <ide> <ide> * A set of {@code Option} objects. <ide> */ <ide> public class Options { <del> private Set<Option> options = new TreeSet<>(); <add> private static final Comparator<Option> optionComparator = new Comparator<Option>() { <add> @Override <add> public int compare(Option o1, Option o2) { <add> return o1.longName().compareTo(o2.longName()); <add> } <add> }; <add> <add> private Set<Option> options = new TreeSet<>(optionComparator); <ide> <ide> /** <add> * Constructs an empty {@code Options}. <add> */ <add> public Options() { <add> this(null); <add> } <add> /** <ide> * Constructs a new {@code Options} for the specified set of options. <del> * @param options supported options <add> * @param options supported options in this options set <ide> */ <ide> public Options(Option[] options) { <del> <del> parse(); <del> } <del> private void parse() { <del> int counter = 0; <del> while (counter < args.length) { <del> Option currentOption = Option.getOption(args[counter]); <del> <del> if (currentOption.requiresArg()) { <del> options.put(currentOption, args[counter + 1]); <del> counter += 2; <del> } <del> else { <del> options.put(currentOption, null); <del> counter += 1; <del> } <del> } <del> } <del> <del> /** @return help string */ <del> public static String help() { <del> StringBuilder toStringBuilder = new StringBuilder("USAGE" + System.lineSeparator()); <del> <del> for (Option option : Option.values()) { <del> toStringBuilder.append(option.description()).append(System.lineSeparator()); <del> } <del> return toStringBuilder.toString(); <add> addAll(options); <ide> } <ide> <ide> /** <ide> * @return {@code true} if this {@code Options} contains the specified option <ide> */ <ide> public boolean contains(Option toCheck) { <del> return options.containsKey(toCheck); <add> return options.contains(toCheck); <ide> } <ide> /** <del> * Retrieves the argument for a specific option. <del> * @param key option to get argument for <del> * @return option's argument, or {@code null} if does not exist <add> * Adds a new option to this options set. <add> * @param toAdd option to add <add> * @return {@code true} if this options set did not already contain the specified option <ide> */ <del> public String get(Option key) { <del> return options.get(key); <add> public boolean add(Option toAdd) { <add> return options.add(toAdd); <add> } <add> /** <add> * Adds an array of options to this options set. <add> * @param toAdd array to add <add> * @return number of options added <add> */ <add> public int addAll(Option[] toAdd) { <add> int addedCounter = 0; <add> <add> for (Option option : toAdd) { <add> if (options.add(option)) <add> addedCounter++; <add> } <add> return addedCounter; <add> } <add> /** <add> * Removes an option from this options set. <add> * @param toRemove option to remove <add> * @return {@code true} if this options set contained the specified option <add> */ <add> public boolean remove(Option toRemove) { <add> return options.remove(toRemove); <ide> } <ide> <del> /** @return all used options */ <del> public Option[] getAllOptions() { <del> return options.keySet().toArray(new Option[options.size()]); <add> /** @return all options */ <add> public Set<Option> getAllOptions() { <add> return options; <ide> } <ide> }
Java
apache-2.0
fd1c58a37d23d05089269d4213f8fffe83eafe19
0
reportportal/commons-dao
/* * Copyright 2019 EPAM Systems * * 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.epam.ta.reportportal.commons; import com.epam.ta.reportportal.entity.project.ProjectRole; import com.epam.ta.reportportal.entity.user.UserRole; import com.epam.ta.reportportal.exception.ReportPortalException; import com.epam.ta.reportportal.ws.model.ErrorType; import com.fasterxml.jackson.annotation.JsonProperty; import org.springframework.security.core.GrantedAuthority; import org.springframework.security.core.authority.SimpleGrantedAuthority; import org.springframework.security.core.userdetails.User; import org.springframework.security.core.userdetails.UserDetails; import java.io.Serializable; import java.util.Collection; import java.util.Collections; import java.util.Map; import java.util.stream.Collectors; /** * ReportPortal user representation * * @author <a href="mailto:[email protected]">Andrei Varabyeu</a> */ public class ReportPortalUser extends User { private Long userId; private UserRole userRole; private String email; private Map<String, ProjectDetails> projectDetails; private ReportPortalUser(String username, String password, Collection<? extends GrantedAuthority> authorities, Long userId, UserRole role, Map<String, ProjectDetails> projectDetails, String email) { super(username, password, authorities); this.userId = userId; this.userRole = role; this.projectDetails = projectDetails; this.email = email; } public Long getUserId() { return userId; } public void setUserId(Long userId) { this.userId = userId; } public UserRole getUserRole() { return userRole; } public void setUserRole(UserRole userRole) { this.userRole = userRole; } public String getEmail() { return email; } public void setEmail(String email) { this.email = email; } public Map<String, ProjectDetails> getProjectDetails() { return projectDetails; } public void setProjectDetails(Map<String, ProjectDetails> projectDetails) { this.projectDetails = projectDetails; } public static ReportPortalUserBuilder userBuilder() { return new ReportPortalUserBuilder(); } public static class ProjectDetails implements Serializable { @JsonProperty(value = "id") private Long projectId; @JsonProperty(value = "name") private String projectName; @JsonProperty("role") private ProjectRole projectRole; public ProjectDetails(Long projectId, String projectName, ProjectRole projectRole) { this.projectId = projectId; this.projectName = projectName; this.projectRole = projectRole; } public Long getProjectId() { return projectId; } public String getProjectName() { return projectName; } public ProjectRole getProjectRole() { return projectRole; } public static ProjectDetailsBuilder builder() { return new ProjectDetailsBuilder(); } public static class ProjectDetailsBuilder { private Long projectId; private String projectName; private ProjectRole projectRole; private ProjectDetailsBuilder() { } public ProjectDetailsBuilder withProjectId(Long projectId) { this.projectId = projectId; return this; } public ProjectDetailsBuilder withProjectName(String projectName) { this.projectName = projectName; return this; } public ProjectDetailsBuilder withProjectRole(String projectRole) { this.projectRole = ProjectRole.forName(projectRole) .orElseThrow(() -> new ReportPortalException(ErrorType.ROLE_NOT_FOUND, projectRole)); return this; } public ProjectDetails build() { return new ProjectDetails(projectId, projectName, projectRole); } } } public static class ReportPortalUserBuilder { private String username; private String password; private Long userId; private UserRole userRole; private String email; private Map<String, ProjectDetails> projectDetails; private Collection<? extends GrantedAuthority> authorities; private ReportPortalUserBuilder() { } public ReportPortalUserBuilder withUserName(String userName) { this.username = userName; return this; } public ReportPortalUserBuilder withPassword(String password) { this.password = password; return this; } public ReportPortalUserBuilder withAuthorities(Collection<? extends GrantedAuthority> authorities) { this.authorities = authorities; return this; } public ReportPortalUserBuilder withUserDetails(UserDetails userDetails) { this.username = userDetails.getUsername(); this.password = userDetails.getPassword(); this.authorities = userDetails.getAuthorities(); return this; } public ReportPortalUserBuilder withUserId(Long userId) { this.userId = userId; return this; } public ReportPortalUserBuilder withUserRole(UserRole userRole) { this.userRole = userRole; return this; } public ReportPortalUserBuilder withEmail(String email) { this.email = email; return this; } public ReportPortalUserBuilder withProjectDetails(Map<String, ProjectDetails> projectDetails) { this.projectDetails = projectDetails; return this; } public ReportPortalUser fromUser(com.epam.ta.reportportal.entity.user.User user) { this.username = user.getLogin(); this.email = user.getPassword(); this.userId = user.getId(); this.userRole = user.getRole(); this.authorities = Collections.singletonList(new SimpleGrantedAuthority(user.getRole().getAuthority())); this.projectDetails = user.getProjects().stream().collect(Collectors.toMap( it -> it.getProject().getName(), it -> ProjectDetails.builder() .withProjectId(it.getProject().getId()) .withProjectRole(it.getProjectRole().name()) .withProjectName(it.getProject().getName()) .build() )); return build(); } public ReportPortalUser build() { return new ReportPortalUser(username, password, authorities, userId, userRole, projectDetails, email); } } }
src/main/java/com/epam/ta/reportportal/commons/ReportPortalUser.java
/* * Copyright 2019 EPAM Systems * * 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.epam.ta.reportportal.commons; import com.epam.ta.reportportal.entity.project.ProjectRole; import com.epam.ta.reportportal.entity.user.UserRole; import com.epam.ta.reportportal.exception.ReportPortalException; import com.epam.ta.reportportal.ws.model.ErrorType; import com.fasterxml.jackson.annotation.JsonProperty; import org.springframework.security.core.GrantedAuthority; import org.springframework.security.core.userdetails.User; import org.springframework.security.core.userdetails.UserDetails; import java.io.Serializable; import java.util.Collection; import java.util.Map; /** * ReportPortal user representation * * @author <a href="mailto:[email protected]">Andrei Varabyeu</a> */ public class ReportPortalUser extends User { private Long userId; private UserRole userRole; private String email; private Map<String, ProjectDetails> projectDetails; private ReportPortalUser(String username, String password, Collection<? extends GrantedAuthority> authorities, Long userId, UserRole role, Map<String, ProjectDetails> projectDetails, String email) { super(username, password, authorities); this.userId = userId; this.userRole = role; this.projectDetails = projectDetails; this.email = email; } public Long getUserId() { return userId; } public void setUserId(Long userId) { this.userId = userId; } public UserRole getUserRole() { return userRole; } public void setUserRole(UserRole userRole) { this.userRole = userRole; } public String getEmail() { return email; } public void setEmail(String email) { this.email = email; } public Map<String, ProjectDetails> getProjectDetails() { return projectDetails; } public void setProjectDetails(Map<String, ProjectDetails> projectDetails) { this.projectDetails = projectDetails; } public static ReportPortalUserBuilder userBuilder() { return new ReportPortalUserBuilder(); } public static class ProjectDetails implements Serializable { @JsonProperty(value = "id") private Long projectId; @JsonProperty(value = "name") private String projectName; @JsonProperty("role") private ProjectRole projectRole; public ProjectDetails(Long projectId, String projectName, ProjectRole projectRole) { this.projectId = projectId; this.projectName = projectName; this.projectRole = projectRole; } public Long getProjectId() { return projectId; } public String getProjectName() { return projectName; } public ProjectRole getProjectRole() { return projectRole; } public static ProjectDetailsBuilder builder() { return new ProjectDetailsBuilder(); } public static class ProjectDetailsBuilder { private Long projectId; private String projectName; private ProjectRole projectRole; private ProjectDetailsBuilder() { } public ProjectDetailsBuilder withProjectId(Long projectId) { this.projectId = projectId; return this; } public ProjectDetailsBuilder withProjectName(String projectName) { this.projectName = projectName; return this; } public ProjectDetailsBuilder withProjectRole(String projectRole) { this.projectRole = ProjectRole.forName(projectRole) .orElseThrow(() -> new ReportPortalException(ErrorType.ROLE_NOT_FOUND, projectRole)); return this; } public ProjectDetails build() { return new ProjectDetails(projectId, projectName, projectRole); } } } public static class ReportPortalUserBuilder { private String username; private String password; private Long userId; private UserRole userRole; private String email; private Map<String, ProjectDetails> projectDetails; private Collection<? extends GrantedAuthority> authorities; private ReportPortalUserBuilder() { } public ReportPortalUserBuilder withUserName(String userName) { this.username = userName; return this; } public ReportPortalUserBuilder withPassword(String password) { this.password = password; return this; } public ReportPortalUserBuilder withAuthorities(Collection<? extends GrantedAuthority> authorities) { this.authorities = authorities; return this; } public ReportPortalUserBuilder withUserDetails(UserDetails userDetails) { this.username = userDetails.getUsername(); this.password = userDetails.getPassword(); this.authorities = userDetails.getAuthorities(); return this; } public ReportPortalUserBuilder withUserId(Long userId) { this.userId = userId; return this; } public ReportPortalUserBuilder withUserRole(UserRole userRole) { this.userRole = userRole; return this; } public ReportPortalUserBuilder withEmail(String email) { this.email = email; return this; } public ReportPortalUserBuilder withProjectDetails(Map<String, ProjectDetails> projectDetails) { this.projectDetails = projectDetails; return this; } public ReportPortalUser build() { return new ReportPortalUser(username, password, authorities, userId, userRole, projectDetails, email); } } }
rp-user building from user added
src/main/java/com/epam/ta/reportportal/commons/ReportPortalUser.java
rp-user building from user added
<ide><path>rc/main/java/com/epam/ta/reportportal/commons/ReportPortalUser.java <ide> import com.epam.ta.reportportal.ws.model.ErrorType; <ide> import com.fasterxml.jackson.annotation.JsonProperty; <ide> import org.springframework.security.core.GrantedAuthority; <add>import org.springframework.security.core.authority.SimpleGrantedAuthority; <ide> import org.springframework.security.core.userdetails.User; <ide> import org.springframework.security.core.userdetails.UserDetails; <ide> <ide> import java.io.Serializable; <ide> import java.util.Collection; <add>import java.util.Collections; <ide> import java.util.Map; <add>import java.util.stream.Collectors; <ide> <ide> /** <ide> * ReportPortal user representation <ide> return this; <ide> } <ide> <add> public ReportPortalUser fromUser(com.epam.ta.reportportal.entity.user.User user) { <add> this.username = user.getLogin(); <add> this.email = user.getPassword(); <add> this.userId = user.getId(); <add> this.userRole = user.getRole(); <add> this.authorities = Collections.singletonList(new SimpleGrantedAuthority(user.getRole().getAuthority())); <add> this.projectDetails = user.getProjects().stream().collect(Collectors.toMap( <add> it -> it.getProject().getName(), <add> it -> ProjectDetails.builder() <add> .withProjectId(it.getProject().getId()) <add> .withProjectRole(it.getProjectRole().name()) <add> .withProjectName(it.getProject().getName()) <add> .build() <add> )); <add> return build(); <add> } <add> <ide> public ReportPortalUser build() { <ide> return new ReportPortalUser(username, password, authorities, userId, userRole, projectDetails, email); <ide> }
Java
mit
106a95a98da327743501ce6fb658d0c3d90071de
0
markovandooren/jnome
package jnome.core.expression; import java.util.ArrayList; import java.util.Collection; import java.util.List; import java.util.Set; import jnome.core.language.Java; import jnome.core.method.JavaVarargsOrder; import jnome.core.type.ArrayType; import jnome.core.type.JavaTypeReference; import jnome.core.variable.MultiFormalParameter; import org.rejuse.association.OrderedMultiAssociation; import org.rejuse.association.SingleAssociation; import org.rejuse.logic.ternary.Ternary; import org.rejuse.predicate.UnsafePredicate; import chameleon.core.declaration.Declaration; import chameleon.core.declaration.Signature; import chameleon.core.expression.InvocationTarget; import chameleon.core.lookup.DeclarationSelector; import chameleon.core.lookup.LookupException; import chameleon.core.method.MethodHeader; import chameleon.core.reference.CrossReference; import chameleon.core.relation.WeakPartialOrder; import chameleon.core.type.Type; import chameleon.core.type.TypeReference; import chameleon.core.type.generics.ActualTypeArgument; import chameleon.core.type.generics.BasicTypeArgument; import chameleon.core.type.generics.ExtendsWildCard; import chameleon.core.type.generics.InstantiatedTypeParameter; import chameleon.core.type.generics.SuperWildCard; import chameleon.core.type.generics.TypeParameter; import chameleon.core.variable.FormalParameter; import chameleon.oo.language.ObjectOrientedLanguage; import chameleon.support.member.MoreSpecificTypesOrder; import chameleon.support.member.simplename.SimpleNameMethodSignature; import chameleon.support.member.simplename.method.NormalMethod; import chameleon.support.member.simplename.method.RegularMethodInvocation; public class JavaMethodInvocation extends RegularMethodInvocation<JavaMethodInvocation> { public JavaMethodInvocation(String name, InvocationTarget target) { super(name, target); } public class JavaMethodSelector extends DeclarationSelector<NormalMethod> { public boolean selectedRegardlessOfName(NormalMethod declaration) throws LookupException { boolean result = declaration.is(language(ObjectOrientedLanguage.class).CONSTRUCTOR) != Ternary.TRUE; if(result) { Signature signature = declaration.signature(); if(signature instanceof SimpleNameMethodSignature) { SimpleNameMethodSignature sig = (SimpleNameMethodSignature)signature; List<Type> actuals = getActualParameterTypes(); List<FormalParameter> formals = declaration.formalParameters(); List<Type> formalTypes = sig.parameterTypes(); int nbActuals = actuals.size(); int nbFormals = formals.size(); if(nbActuals == nbFormals){ // POTENTIALLY result = MoreSpecificTypesOrder.create().contains(actuals,formalTypes); } else if // varargs rubbish ( (formals.get(nbFormals - 1) instanceof MultiFormalParameter) && (nbActuals >= nbFormals - 1) ) { // POTENTIALLY result = JavaVarargsOrder.create().contains(actuals,formalTypes); } else { result = false; } if(result) { List<ActualTypeArgument> actualTypeArguments = typeArguments(); int actualTypeArgumentsSize = actualTypeArguments.size(); if(actualTypeArgumentsSize > 0) { List<TypeParameter> formalTypeParameters = declaration.typeParameters(); result = actualTypeArgumentsSize == formalTypeParameters.size(); if(result) { for(int i=0; result && i < actualTypeArgumentsSize; i++) { result = formalTypeParameters.get(i).canBeAssigned(actualTypeArguments.get(i)); } } } } } } return result; } @Override public boolean selectedBasedOnName(Signature signature) throws LookupException { boolean result = false; if(signature instanceof SimpleNameMethodSignature) { SimpleNameMethodSignature sig = (SimpleNameMethodSignature)signature; result = sig.name().equals(name()); } return result; } @Override public WeakPartialOrder<NormalMethod> order() { return new WeakPartialOrder<NormalMethod>() { @Override public boolean contains(NormalMethod first, NormalMethod second) throws LookupException { return MoreSpecificTypesOrder.create().contains(((MethodHeader) first.header()).getParameterTypes(), ((MethodHeader) second.header()).getParameterTypes()); } }; } @Override public Class<NormalMethod> selectedClass() { return NormalMethod.class; } @Override public String selectionName() { return name(); } } public static class ConstraintSet { private OrderedMultiAssociation<ConstraintSet, Constraint> _constraints = new OrderedMultiAssociation<ConstraintSet, Constraint>(this); public List<Constraint> constraints() { return _constraints.getOtherEnds(); } public void add(Constraint constraint) { if(constraint != null) { _constraints.add(constraint.parentLink()); } } public void remove(Constraint constraint) { if(constraint != null) { _constraints.remove(constraint.parentLink()); } } public void replace(Constraint oldConstraint, Constraint newConstraint) { if(oldConstraint != null && newConstraint != null) { _constraints.replace(oldConstraint.parentLink(), newConstraint.parentLink()); } } public List<TypeParameter> typeParameters() { return _typeParameters; } private List<TypeParameter> _typeParameters; } private static class Constraint { private SingleAssociation<Constraint, ConstraintSet> _parentLink = new SingleAssociation<Constraint, ConstraintSet>(this); public SingleAssociation<Constraint, ConstraintSet> parentLink() { return _parentLink; } public ConstraintSet parent() { return _parentLink.getOtherEnd(); } // resolve() } /** * A = type() * F = typeReference() * * @author Marko van Dooren */ private abstract static class FirstPhaseConstraint extends Constraint { /** * * @param type * @param tref */ public FirstPhaseConstraint(Type type, JavaTypeReference tref) { _type = type; _typeReference = tref; } private Type _type; public Type type() { return _type; } private JavaTypeReference _typeReference; public JavaTypeReference typeReference() { return _typeReference; } public List<SecondPhaseConstraint> process() throws LookupException { List<SecondPhaseConstraint> result = new ArrayList<SecondPhaseConstraint>(); if(! type().equals(type().language(ObjectOrientedLanguage.class).getNullType())) { result.addAll(processSpecifics()); } return result; } public abstract List<SecondPhaseConstraint> processSpecifics() throws LookupException; public boolean involvesTypeParameter(TypeReference tref) throws LookupException { return ! involvedTypeParameters(tref).isEmpty(); } public List<TypeParameter> involvedTypeParameters(TypeReference tref) throws LookupException { List<CrossReference> list = tref.descendants(CrossReference.class, new UnsafePredicate<CrossReference, LookupException>() { @Override public boolean eval(CrossReference object) throws LookupException { return parent().typeParameters().contains(object.getDeclarator()); } }); List<TypeParameter> parameters = new ArrayList<TypeParameter>(); for(CrossReference cref: list) { parameters.add((TypeParameter) cref.getElement()); } return parameters; } public Java language() { return type().language(Java.class); } protected Type typeWithSameBaseTypeAs(Type example, Collection<Type> toBeSearched) { Type baseType = example.baseType(); for(Type type:toBeSearched) { if(type.baseType().equals(baseType)) { return type; } } return null; } } /** * A << F * * Type << JavaTypeReference * * @author Marko van Dooren */ private static class SSConstraint extends FirstPhaseConstraint { public SSConstraint(Type type, JavaTypeReference tref) { super(type,tref); } @Override public List<SecondPhaseConstraint> processSpecifics() throws LookupException { List<SecondPhaseConstraint> result = new ArrayList<SecondPhaseConstraint>(); Declaration declarator = typeReference().getDeclarator(); Type type = type(); if(type().is(language().PRIMITIVE_TYPE) == Ternary.TRUE) { // If A is a primitive type, then A is converted to a reference type U via // boxing conversion and this algorithm is applied recursively to the constraint // U << F SSConstraint recursive = new SSConstraint(language().box(type()), typeReference()); result.addAll(recursive.process()); } else if(parent().typeParameters().contains(declarator)) { // Otherwise, if F=Tj, then the constraint Tj :> A is implied. result.add(new SupertypeConstraint((TypeParameter) declarator, type())); } else if(typeReference().arrayDimension() > 0) { // If F=U[], where the type U involves Tj, then if A is an array type V[], or // a type variable with an upper bound that is an array type V[], where V is a // reference type, this algorithm is applied recursively to the constraint V<<U // The "involves Tj" condition for U is the same as "involves Tj" for F. if(type instanceof ArrayType && involvesTypeParameter(typeReference())) { Type componentType = ((ArrayType)type).componentType(); if(componentType.is(language().REFERENCE_TYPE) == Ternary.TRUE) { JavaTypeReference componentTypeReference = typeReference().clone(); componentTypeReference.setUniParent(typeReference()); componentTypeReference.decreaseArrayDimension(1); SSConstraint recursive = new SSConstraint(componentType, componentTypeReference); result.addAll(recursive.process()); // FIXME: can't we unwrap the entire array dimension at once? This seems rather inefficient. } } } else { List<ActualTypeArgument> actuals = typeReference().typeArguments(); Set<Type> supers = type().getAllSuperTypes(); Type G = typeWithSameBaseTypeAs(type(), supers); if(G != null) { // i is the index of the parameter we are processing. // V= the type reference of the i-th type parameter of some supertype G of A. int i = 0; for(ActualTypeArgument typeArgumentOfFormalParameter: typeReference().typeArguments()) { i++; TypeParameter ithTypeParameterOfG = G.parameters().get(i); if(typeArgumentOfFormalParameter instanceof BasicTypeArgument) { caseSSFormalBasic(result, (BasicTypeArgument)typeArgumentOfFormalParameter, ithTypeParameterOfG); } else if(typeArgumentOfFormalParameter instanceof ExtendsWildCard) { caseSSFormalExtends(result, typeArgumentOfFormalParameter, ithTypeParameterOfG); } else if(typeArgumentOfFormalParameter instanceof SuperWildCard) { } } } } return result; } /** * */ private void caseSSFormalExtends(List<SecondPhaseConstraint> result, ActualTypeArgument typeArgumentOfFormalParameter, TypeParameter ithTypeParameterOfG) throws LookupException { ExtendsWildCard extend = (ExtendsWildCard)typeArgumentOfFormalParameter; JavaTypeReference U = (JavaTypeReference) extend.typeReference(); if(involvesTypeParameter(U)) { if(ithTypeParameterOfG instanceof InstantiatedTypeParameter) { ActualTypeArgument arg = ((InstantiatedTypeParameter)ithTypeParameterOfG).argument(); if(arg instanceof BasicTypeArgument) { Type V = arg.type(); SSConstraint recursive = new SSConstraint(V, U); result.addAll(recursive.process()); } else if (arg instanceof ExtendsWildCard) { Type V = ((ExtendsWildCard)arg).upperBound(); SSConstraint recursive = new SSConstraint(V, U); result.addAll(recursive.process()); } // Otherwise, no constraint is implied on Tj. } } } /** * If F has the form G<...,Yk-1,U,Yk+1....>, 1<=k<=n where U is a type expression that involves Tj, * the in A has a supertype of the form G<...,Xk-1,V,Xk+1,...> where V is a type expression, this algorithm * is applied recursively to the constraint V = U. */ private void caseSSFormalBasic(List<SecondPhaseConstraint> result, BasicTypeArgument typeArgumentOfFormalParameter, TypeParameter ithTypeParameterOfG) throws LookupException { // U = basic.typeReference() JavaTypeReference U = (JavaTypeReference) typeArgumentOfFormalParameter.typeReference(); if(involvesTypeParameter(U)) { // Get the i-th type parameter of zuppa: V. if(ithTypeParameterOfG instanceof InstantiatedTypeParameter) { ActualTypeArgument arg = ((InstantiatedTypeParameter)ithTypeParameterOfG).argument(); if(arg instanceof BasicTypeArgument) { Type V = arg.type(); EQConstraint recursive = new EQConstraint(V, U); result.addAll(recursive.process()); } } } } } private static class GGConstraint extends FirstPhaseConstraint { public GGConstraint(Type type, JavaTypeReference tref) { super(type,tref); } @Override public List<SecondPhaseConstraint> processSpecifics() throws LookupException { return null; } } private static class EQConstraint extends FirstPhaseConstraint { public EQConstraint(Type type, JavaTypeReference tref) { super(type,tref); } @Override public List<SecondPhaseConstraint> processSpecifics() throws LookupException { return null; } } private abstract static class SecondPhaseConstraint extends Constraint { public SecondPhaseConstraint(TypeParameter param, Type type) { _type = type; _typeParameter = param; } private Type _type; public Type type() { return _type; } private TypeParameter _typeParameter; public TypeParameter typeParameter() { return _typeParameter; } } private static class EqualTypeConstraint extends SecondPhaseConstraint { public EqualTypeConstraint(TypeParameter param, Type type) { super(param,type); } } private static class SubtypeConstraint extends SecondPhaseConstraint { public SubtypeConstraint(TypeParameter param, Type type) { super(param,type); } } private static class SupertypeConstraint extends SecondPhaseConstraint { public SupertypeConstraint(TypeParameter param, Type type) { super(param,type); } } }
src/jnome/core/expression/JavaMethodInvocation.java
package jnome.core.expression; import java.util.ArrayList; import java.util.List; import java.util.Set; import jnome.core.language.Java; import jnome.core.method.JavaVarargsOrder; import jnome.core.type.ArrayType; import jnome.core.type.JavaTypeReference; import jnome.core.variable.MultiFormalParameter; import org.rejuse.association.OrderedMultiAssociation; import org.rejuse.association.SingleAssociation; import org.rejuse.logic.ternary.Ternary; import org.rejuse.predicate.UnsafePredicate; import chameleon.core.declaration.Declaration; import chameleon.core.declaration.Signature; import chameleon.core.expression.InvocationTarget; import chameleon.core.lookup.DeclarationSelector; import chameleon.core.lookup.LookupException; import chameleon.core.method.MethodHeader; import chameleon.core.reference.CrossReference; import chameleon.core.relation.WeakPartialOrder; import chameleon.core.type.Type; import chameleon.core.type.TypeReference; import chameleon.core.type.generics.ActualTypeArgument; import chameleon.core.type.generics.BasicTypeArgument; import chameleon.core.type.generics.ExtendsWildCard; import chameleon.core.type.generics.SuperWildCard; import chameleon.core.type.generics.TypeParameter; import chameleon.core.variable.FormalParameter; import chameleon.oo.language.ObjectOrientedLanguage; import chameleon.support.member.MoreSpecificTypesOrder; import chameleon.support.member.simplename.SimpleNameMethodSignature; import chameleon.support.member.simplename.method.NormalMethod; import chameleon.support.member.simplename.method.RegularMethodInvocation; public class JavaMethodInvocation extends RegularMethodInvocation<JavaMethodInvocation> { public JavaMethodInvocation(String name, InvocationTarget target) { super(name, target); } public class JavaMethodSelector extends DeclarationSelector<NormalMethod> { public boolean selectedRegardlessOfName(NormalMethod declaration) throws LookupException { boolean result = declaration.is(language(ObjectOrientedLanguage.class).CONSTRUCTOR) != Ternary.TRUE; if(result) { Signature signature = declaration.signature(); if(signature instanceof SimpleNameMethodSignature) { SimpleNameMethodSignature sig = (SimpleNameMethodSignature)signature; List<Type> actuals = getActualParameterTypes(); List<FormalParameter> formals = declaration.formalParameters(); List<Type> formalTypes = sig.parameterTypes(); int nbActuals = actuals.size(); int nbFormals = formals.size(); if(nbActuals == nbFormals){ // POTENTIALLY result = MoreSpecificTypesOrder.create().contains(actuals,formalTypes); } else if // varargs rubbish ( (formals.get(nbFormals - 1) instanceof MultiFormalParameter) && (nbActuals >= nbFormals - 1) ) { // POTENTIALLY result = JavaVarargsOrder.create().contains(actuals,formalTypes); } else { result = false; } if(result) { List<ActualTypeArgument> actualTypeArguments = typeArguments(); int actualTypeArgumentsSize = actualTypeArguments.size(); if(actualTypeArgumentsSize > 0) { List<TypeParameter> formalTypeParameters = declaration.typeParameters(); result = actualTypeArgumentsSize == formalTypeParameters.size(); if(result) { for(int i=0; result && i < actualTypeArgumentsSize; i++) { result = formalTypeParameters.get(i).canBeAssigned(actualTypeArguments.get(i)); } } } } } } return result; } @Override public boolean selectedBasedOnName(Signature signature) throws LookupException { boolean result = false; if(signature instanceof SimpleNameMethodSignature) { SimpleNameMethodSignature sig = (SimpleNameMethodSignature)signature; result = sig.name().equals(name()); } return result; } @Override public WeakPartialOrder<NormalMethod> order() { return new WeakPartialOrder<NormalMethod>() { @Override public boolean contains(NormalMethod first, NormalMethod second) throws LookupException { return MoreSpecificTypesOrder.create().contains(((MethodHeader) first.header()).getParameterTypes(), ((MethodHeader) second.header()).getParameterTypes()); } }; } @Override public Class<NormalMethod> selectedClass() { return NormalMethod.class; } @Override public String selectionName() { return name(); } } public static class ConstraintSet { private OrderedMultiAssociation<ConstraintSet, Constraint> _constraints = new OrderedMultiAssociation<ConstraintSet, Constraint>(this); public List<Constraint> constraints() { return _constraints.getOtherEnds(); } public void add(Constraint constraint) { if(constraint != null) { _constraints.add(constraint.parentLink()); } } public void remove(Constraint constraint) { if(constraint != null) { _constraints.remove(constraint.parentLink()); } } public void replace(Constraint oldConstraint, Constraint newConstraint) { if(oldConstraint != null && newConstraint != null) { _constraints.replace(oldConstraint.parentLink(), newConstraint.parentLink()); } } public List<TypeParameter> typeParameters() { return _typeParameters; } private List<TypeParameter> _typeParameters; } private static class Constraint { private SingleAssociation<Constraint, ConstraintSet> _parentLink = new SingleAssociation<Constraint, ConstraintSet>(this); public SingleAssociation<Constraint, ConstraintSet> parentLink() { return _parentLink; } public ConstraintSet parent() { return _parentLink.getOtherEnd(); } // resolve() } private abstract static class FirstPhaseConstraint extends Constraint { public FirstPhaseConstraint(Type type, JavaTypeReference tref) { _type = type; _typeReference = tref; } private Type _type; public Type type() { return _type; } private JavaTypeReference _typeReference; public JavaTypeReference typeReference() { return _typeReference; } public List<SecondPhaseConstraint> process() throws LookupException { List<SecondPhaseConstraint> result = new ArrayList<SecondPhaseConstraint>(); if(! type().equals(type().language(ObjectOrientedLanguage.class).getNullType())) { result.addAll(processSpecifics()); } return result; } public abstract List<SecondPhaseConstraint> processSpecifics() throws LookupException; public boolean involvesTypeParameter(TypeReference tref) throws LookupException { return ! involvedTypeParameters(tref).isEmpty(); } public List<TypeParameter> involvedTypeParameters(TypeReference tref) throws LookupException { List<CrossReference> list = tref.descendants(CrossReference.class, new UnsafePredicate<CrossReference, LookupException>() { @Override public boolean eval(CrossReference object) throws LookupException { return parent().typeParameters().contains(object.getDeclarator()); } }); List<TypeParameter> parameters = new ArrayList<TypeParameter>(); for(CrossReference cref: list) { parameters.add((TypeParameter) cref.getElement()); } return parameters; } public Java language() { return type().language(Java.class); } } /** * A << F * * Type << JavaTypeReference * * @author Marko van Dooren */ private static class SSConstraint extends FirstPhaseConstraint { public SSConstraint(Type type, JavaTypeReference tref) { super(type,tref); } @Override public List<SecondPhaseConstraint> processSpecifics() throws LookupException { List<SecondPhaseConstraint> result = new ArrayList<SecondPhaseConstraint>(); Declaration declarator = typeReference().getDeclarator(); Type type = type(); if(type().is(language().PRIMITIVE_TYPE) == Ternary.TRUE) { // If A is a primitive type, then A is converted to a reference type U via // boxing conversion and this algorithm is applied recursively to the constraint // U << F SSConstraint recursive = new SSConstraint(language().box(type()), typeReference()); result.addAll(recursive.process()); } else if(parent().typeParameters().contains(declarator)) { // Otherwise, if F=Tj, then the constraint Tj :> A is implied. result.add(new SupertypeConstraint((TypeParameter) declarator, type())); } else if(typeReference().arrayDimension() > 0) { // If F=U[], where the type U involves Tj, then if A is an array type V[], or // a type variable with an upper bound that is an array type V[], where V is a // reference type, this algorithm is applied recursively to the constraint V<<U // The "involves Tj" condition for U is the same as "involves Tj" for F. if(type instanceof ArrayType && involvesTypeParameter(typeReference())) { Type componentType = ((ArrayType)type).componentType(); if(componentType.is(language().REFERENCE_TYPE) == Ternary.TRUE) { JavaTypeReference componentTypeReference = typeReference().clone(); componentTypeReference.setUniParent(typeReference()); componentTypeReference.decreaseArrayDimension(1); SSConstraint recursive = new SSConstraint(componentType, componentTypeReference); result.addAll(recursive.process()); // FIXME: can't we unwrap the entire array dimension at once? This seems rather inefficient. } } } else { List<ActualTypeArgument> actuals = typeReference().typeArguments(); for(ActualTypeArgument argument: actuals) { if(argument instanceof BasicTypeArgument) { BasicTypeArgument basic = (BasicTypeArgument)argument; if(involvesTypeParameter(basic.typeReference())) { Set<Type> supers = type().getAllSuperTypes(); } } else if(argument instanceof ExtendsWildCard) { } else if(argument instanceof SuperWildCard) { } } } return result; } } private static class GGConstraint extends FirstPhaseConstraint { public GGConstraint(Type type, JavaTypeReference tref) { super(type,tref); } @Override public List<SecondPhaseConstraint> processSpecifics() throws LookupException { return null; } } private static class EQConstraint extends FirstPhaseConstraint { public EQConstraint(Type type, JavaTypeReference tref) { super(type,tref); } @Override public List<SecondPhaseConstraint> processSpecifics() throws LookupException { return null; } } private abstract static class SecondPhaseConstraint extends Constraint { public SecondPhaseConstraint(TypeParameter param, Type type) { _type = type; _typeParameter = param; } private Type _type; public Type type() { return _type; } private TypeParameter _typeParameter; public TypeParameter typeParameter() { return _typeParameter; } } private static class EqualTypeConstraint extends SecondPhaseConstraint { public EqualTypeConstraint(TypeParameter param, Type type) { super(param,type); } } private static class SubtypeConstraint extends SecondPhaseConstraint { public SubtypeConstraint(TypeParameter param, Type type) { super(param,type); } } private static class SupertypeConstraint extends SecondPhaseConstraint { public SupertypeConstraint(TypeParameter param, Type type) { super(param,type); } } }
more work on type inference for generic method calls
src/jnome/core/expression/JavaMethodInvocation.java
more work on type inference for generic method calls
<ide><path>rc/jnome/core/expression/JavaMethodInvocation.java <ide> package jnome.core.expression; <ide> <ide> import java.util.ArrayList; <add>import java.util.Collection; <ide> import java.util.List; <ide> import java.util.Set; <ide> <ide> import chameleon.core.type.generics.ActualTypeArgument; <ide> import chameleon.core.type.generics.BasicTypeArgument; <ide> import chameleon.core.type.generics.ExtendsWildCard; <add>import chameleon.core.type.generics.InstantiatedTypeParameter; <ide> import chameleon.core.type.generics.SuperWildCard; <ide> import chameleon.core.type.generics.TypeParameter; <ide> import chameleon.core.variable.FormalParameter; <ide> // resolve() <ide> } <ide> <add> /** <add> * A = type() <add> * F = typeReference() <add> * <add> * @author Marko van Dooren <add> */ <ide> private abstract static class FirstPhaseConstraint extends Constraint { <ide> <add> /** <add> * <add> * @param type <add> * @param tref <add> */ <ide> public FirstPhaseConstraint(Type type, JavaTypeReference tref) { <ide> _type = type; <ide> _typeReference = tref; <ide> public Java language() { <ide> return type().language(Java.class); <ide> } <add> <add> protected Type typeWithSameBaseTypeAs(Type example, Collection<Type> toBeSearched) { <add> Type baseType = example.baseType(); <add> for(Type type:toBeSearched) { <add> if(type.baseType().equals(baseType)) { <add> return type; <add> } <add> } <add> return null; <add> } <add> <ide> } <ide> /** <ide> * A << F <ide> } <ide> } else { <ide> List<ActualTypeArgument> actuals = typeReference().typeArguments(); <del> for(ActualTypeArgument argument: actuals) { <del> if(argument instanceof BasicTypeArgument) { <del> BasicTypeArgument basic = (BasicTypeArgument)argument; <del> if(involvesTypeParameter(basic.typeReference())) { <del> Set<Type> supers = type().getAllSuperTypes(); <add> Set<Type> supers = type().getAllSuperTypes(); <add> Type G = typeWithSameBaseTypeAs(type(), supers); <add> if(G != null) { <add> // i is the index of the parameter we are processing. <add> // V= the type reference of the i-th type parameter of some supertype G of A. <add> int i = 0; <add> for(ActualTypeArgument typeArgumentOfFormalParameter: typeReference().typeArguments()) { <add> i++; <add> TypeParameter ithTypeParameterOfG = G.parameters().get(i); <add> if(typeArgumentOfFormalParameter instanceof BasicTypeArgument) { <add> caseSSFormalBasic(result, (BasicTypeArgument)typeArgumentOfFormalParameter, ithTypeParameterOfG); <add> } else if(typeArgumentOfFormalParameter instanceof ExtendsWildCard) { <add> caseSSFormalExtends(result, typeArgumentOfFormalParameter, ithTypeParameterOfG); <add> } else if(typeArgumentOfFormalParameter instanceof SuperWildCard) { <add> <ide> } <del> } else if(argument instanceof ExtendsWildCard) { <del> <del> } else if(argument instanceof SuperWildCard) { <del> <ide> } <ide> } <ide> } <ide> return result; <ide> } <del> <del> } <add> <add> /** <add> * <add> */ <add> private void caseSSFormalExtends(List<SecondPhaseConstraint> result, ActualTypeArgument typeArgumentOfFormalParameter, <add> TypeParameter ithTypeParameterOfG) throws LookupException { <add> ExtendsWildCard extend = (ExtendsWildCard)typeArgumentOfFormalParameter; <add> JavaTypeReference U = (JavaTypeReference) extend.typeReference(); <add> if(involvesTypeParameter(U)) { <add> if(ithTypeParameterOfG instanceof InstantiatedTypeParameter) { <add> ActualTypeArgument arg = ((InstantiatedTypeParameter)ithTypeParameterOfG).argument(); <add> if(arg instanceof BasicTypeArgument) { <add> Type V = arg.type(); <add> SSConstraint recursive = new SSConstraint(V, U); <add> result.addAll(recursive.process()); <add> } else if (arg instanceof ExtendsWildCard) { <add> Type V = ((ExtendsWildCard)arg).upperBound(); <add> SSConstraint recursive = new SSConstraint(V, U); <add> result.addAll(recursive.process()); <add> } <add> // Otherwise, no constraint is implied on Tj. <add> } <add> } <add> } <add> <add> /** <add> * If F has the form G<...,Yk-1,U,Yk+1....>, 1<=k<=n where U is a type expression that involves Tj, <add> * the in A has a supertype of the form G<...,Xk-1,V,Xk+1,...> where V is a type expression, this algorithm <add> * is applied recursively to the constraint V = U. <add> */ <add> private void caseSSFormalBasic(List<SecondPhaseConstraint> result, BasicTypeArgument typeArgumentOfFormalParameter, <add> TypeParameter ithTypeParameterOfG) throws LookupException { <add> // U = basic.typeReference() <add> JavaTypeReference U = (JavaTypeReference) typeArgumentOfFormalParameter.typeReference(); <add> if(involvesTypeParameter(U)) { <add> // Get the i-th type parameter of zuppa: V. <add> if(ithTypeParameterOfG instanceof InstantiatedTypeParameter) { <add> ActualTypeArgument arg = ((InstantiatedTypeParameter)ithTypeParameterOfG).argument(); <add> if(arg instanceof BasicTypeArgument) { <add> Type V = arg.type(); <add> EQConstraint recursive = new EQConstraint(V, U); <add> result.addAll(recursive.process()); <add> } <add> } <add> } <add> } <add> <add> } <add> <ide> <ide> private static class GGConstraint extends FirstPhaseConstraint { <ide>
Java
apache-2.0
1b56d951ba82cf6d45e73ace9dacab17b585678d
0
statsbiblioteket/summa,statsbiblioteket/summa,statsbiblioteket/summa,statsbiblioteket/summa
/* * 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 dk.statsbiblioteket.summa.common.legacy; import dk.statsbiblioteket.summa.common.MarcAnnotations; import dk.statsbiblioteket.summa.common.Record; import dk.statsbiblioteket.summa.common.configuration.Configuration; import dk.statsbiblioteket.summa.common.configuration.Resolver; import dk.statsbiblioteket.summa.common.filter.Filter; import dk.statsbiblioteket.summa.common.filter.Payload; import dk.statsbiblioteket.summa.common.filter.object.ObjectFilter; import dk.statsbiblioteket.summa.common.util.PayloadMatcher; import dk.statsbiblioteket.util.xml.DOM; import junit.framework.Test; import junit.framework.TestCase; import junit.framework.TestSuite; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import java.io.IOException; import java.util.ArrayList; import java.util.Arrays; import java.util.List; public class MarcMultiVolumeMergerTest extends TestCase implements ObjectFilter { private static Log log = LogFactory.getLog(MarcMultiVolumeMergerTest.class); private List<Record> records; public MarcMultiVolumeMergerTest(String name) { super(name); } @Override public void setUp() throws Exception { super.setUp(); } private void makeSampleHorizon() throws IOException { Record parent = createRecord("parent_book1.xml"); List<Record> children = new ArrayList<>(4); Record child1 = createRecord("child_book1.xml"); child1.getMeta().put(MarcAnnotations.META_MULTI_VOLUME_TYPE, MarcAnnotations.MultiVolumeType.BIND.toString()); children.add(child1); Record child2 = createRecord("child_book2.xml"); child2.getMeta().put(MarcAnnotations.META_MULTI_VOLUME_TYPE, MarcAnnotations.MultiVolumeType.BIND.toString()); children.add(child2); Record child4 = createRecord("child_book4.xml"); child4.getMeta().put(MarcAnnotations.META_MULTI_VOLUME_TYPE, MarcAnnotations.MultiVolumeType.SEKTION.toString()); Record subChild1 = createRecord("subchild_book1.xml"); subChild1.getMeta().put(MarcAnnotations.META_MULTI_VOLUME_TYPE, MarcAnnotations.MultiVolumeType.BIND.toString()); child4.setChildren(Arrays.asList(subChild1)); children.add(child4); parent.setChildren(children); records = new ArrayList<>(1); records.add(parent); } private void makeSampleAleph() throws IOException { Record parent = createAlephRecord("aleph_parent.xml"); Record middle = createAlephRecord("aleph_middle.xml"); middle.getMeta().put(MarcAnnotations.META_MULTI_VOLUME_TYPE, MarcAnnotations.MultiVolumeType.BIND.toString()); Record child = createAlephRecord("aleph_child.xml"); child.getMeta().put(MarcAnnotations.META_MULTI_VOLUME_TYPE, MarcAnnotations.MultiVolumeType.BIND.toString()); middle.setChildren(Arrays.asList(child)); parent.setChildren(Arrays.asList(middle)); records = new ArrayList<>(1); records.add(parent); } private Record createRecord(String filename) throws IOException { //noinspection DuplicateStringLiteralInspection return new Record(filename, "Dummy", Resolver.getUTF8Content( "common/horizon/" + filename).getBytes("utf-8")); } private Record createAlephRecord(String filename) throws IOException { //noinspection DuplicateStringLiteralInspection return new Record(filename, "aleph", Resolver.getUTF8Content( "common/aleph/" + filename).getBytes("utf-8")); } @Override public void tearDown() throws Exception { super.tearDown(); records.clear(); } public static Test suite() { return new TestSuite(MarcMultiVolumeMergerTest.class); } @SuppressWarnings({"DuplicateStringLiteralInspection"}) public void testMerge() throws Exception { makeSampleHorizon(); MarcMultiVolumeMerger merger = new MarcMultiVolumeMerger(Configuration.newMemoryBased()); merger.setSource(this); String processed = merger.next().getRecord().getContentAsUTF8(); // log.info("Processed:\n" + processed); // FIXME: Convert this to a proper XML-assert as the attribute order depends on Java version assertContains(processed, // BIND "<datafield ind2=\"0\" ind1=\"0\" tag=\"248\">" + "<subfield code=\"a\">Kaoskyllingens endeligt</subfield>"); assertContains(processed, // SECTION "<datafield ind2=\"0\" ind1=\"0\" tag=\"247\">" + "<subfield code=\"a\">Kaoskyllingens rige</subfield>"); assertContains(processed, // HOVEDPOST "<datafield tag=\"245\" ind1=\"0\" ind2=\"0\">" + "<subfield code=\"a\">Kaoskyllingen</subfield>"); assertContains(processed, // Correct close tag "</record>"); } public void testDeleteDiscard() throws IOException { makeSampleHorizon(); markAsDeleted("child_book1.xml"); // child1: Den apokalyptiske Kaoskylling MarcMultiVolumeMerger merger = new MarcMultiVolumeMerger(Configuration.newMemoryBased()); merger.setSource(this); String processed = merger.next().getRecord().getContentAsUTF8(); assertFalse("The result should not contain the deleted record\n" + processed, processed.contains("Den apokalyptiske Kaoskylling")); } @SuppressWarnings("SameParameterValue") private void markAsDeleted(String id) { for (Record record: records) { if (id.equals(record.getId())) { record.setDeleted(true); return; } if (record.hasChildren()) { for (Record sub : record.getChildren()) { if (id.equals(sub.getId())) { sub.setDeleted(true); return; } } } if (record.hasParents()) { for (Record sup : record.getParents()) { if (id.equals(sup.getId())) { sup.setDeleted(true); return; } } } } fail("Unable to locate record with ID '" + id + "' intended for delete marker"); } // <datafieldind2="0"ind1="0"tag="248"><subfieldcode="a">Kaoskyllingensendeligt</subfield> // <datafieldtag="248"ind2="0"ind1="0"><subfieldcode="a">Kaoskyllingensendeligt</subfield> public void testMergeAleph() throws Exception { makeSampleAleph(); MarcMultiVolumeMerger merger = new MarcMultiVolumeMerger( Configuration.newMemoryBased()); merger.setSource(this); String processed = merger.next().getRecord().getContentAsUTF8(); assertNotNull("DOM-parsing should succeed for\n" + countTestCases(), DOM.stringToDOM(processed)); assertTrue("The result should contain 'Frühe'\n" + processed, processed.contains("Frühe")); } public void testExtraContent() throws Exception { makeSampleAleph(); List<Record> children = records.get(0).getChildren(); children.add(new Record("Dummy", "bar", new byte[10])); records.get(0).setChildren(children); Configuration conf = Configuration.newMemoryBased(); Configuration ignoreConf = conf.createSubConfiguration( MarcMultiVolumeMerger.CONF_MERGE_RECORDS); ignoreConf.set(PayloadMatcher.CONF_BASE_REGEX, "aleph"); MarcMultiVolumeMerger merger = new MarcMultiVolumeMerger(conf); merger.setSource(this); String processed = merger.next().getRecord().getContentAsUTF8(); assertNotNull("DOM-parsing should succeed for\n" + countTestCases(), DOM.stringToDOM(processed)); assertTrue("The result should contain 'Frühe'\n" + processed, processed.contains("Frühe")); } private void assertContains(String main, String sub) { boolean contains = flatten(main).contains(flatten(sub)); assertTrue("The String '" + sub + "' should exist in the main String\n" + main, contains); } private String flatten(String str) { return str.replace(" ", "").replace("\n", ""); } /* simple ObjectFilter implementation */ @Override public boolean hasNext() { return !records.isEmpty(); } @Override public void setSource(Filter filter) { // Nada } @Override public boolean pump() throws IOException { return hasNext() && next() != null && hasNext(); } @Override public void close(boolean success) { records.clear(); } @Override public Payload next() { return new Payload(records.remove(0)); } @Override public void remove() { // Nada } }
Core/src/test/java/dk/statsbiblioteket/summa/common/legacy/MarcMultiVolumeMergerTest.java
/* * 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 dk.statsbiblioteket.summa.common.legacy; import dk.statsbiblioteket.summa.common.MarcAnnotations; import dk.statsbiblioteket.summa.common.Record; import dk.statsbiblioteket.summa.common.configuration.Configuration; import dk.statsbiblioteket.summa.common.configuration.Resolver; import dk.statsbiblioteket.summa.common.filter.Filter; import dk.statsbiblioteket.summa.common.filter.Payload; import dk.statsbiblioteket.summa.common.filter.object.ObjectFilter; import dk.statsbiblioteket.summa.common.util.PayloadMatcher; import dk.statsbiblioteket.util.xml.DOM; import junit.framework.Test; import junit.framework.TestCase; import junit.framework.TestSuite; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import java.io.IOException; import java.util.ArrayList; import java.util.Arrays; import java.util.List; public class MarcMultiVolumeMergerTest extends TestCase implements ObjectFilter { private static Log log = LogFactory.getLog(MarcMultiVolumeMergerTest.class); private List<Record> records; public MarcMultiVolumeMergerTest(String name) { super(name); } @Override public void setUp() throws Exception { super.setUp(); } private void makeSampleHorizon() throws IOException { Record parent = createRecord("parent_book1.xml"); List<Record> children = new ArrayList<>(4); Record child1 = createRecord("child_book1.xml"); child1.getMeta().put(MarcAnnotations.META_MULTI_VOLUME_TYPE, MarcAnnotations.MultiVolumeType.BIND.toString()); children.add(child1); Record child2 = createRecord("child_book2.xml"); child2.getMeta().put(MarcAnnotations.META_MULTI_VOLUME_TYPE, MarcAnnotations.MultiVolumeType.BIND.toString()); children.add(child2); Record child4 = createRecord("child_book4.xml"); child4.getMeta().put(MarcAnnotations.META_MULTI_VOLUME_TYPE, MarcAnnotations.MultiVolumeType.SEKTION.toString()); Record subChild1 = createRecord("subchild_book1.xml"); subChild1.getMeta().put(MarcAnnotations.META_MULTI_VOLUME_TYPE, MarcAnnotations.MultiVolumeType.BIND.toString()); child4.setChildren(Arrays.asList(subChild1)); children.add(child4); parent.setChildren(children); records = new ArrayList<>(1); records.add(parent); } private void makeSampleAleph() throws IOException { Record parent = createAlephRecord("aleph_parent.xml"); Record middle = createAlephRecord("aleph_middle.xml"); middle.getMeta().put(MarcAnnotations.META_MULTI_VOLUME_TYPE, MarcAnnotations.MultiVolumeType.BIND.toString()); Record child = createAlephRecord("aleph_child.xml"); child.getMeta().put(MarcAnnotations.META_MULTI_VOLUME_TYPE, MarcAnnotations.MultiVolumeType.BIND.toString()); middle.setChildren(Arrays.asList(child)); parent.setChildren(Arrays.asList(middle)); records = new ArrayList<>(1); records.add(parent); } private Record createRecord(String filename) throws IOException { //noinspection DuplicateStringLiteralInspection return new Record(filename, "Dummy", Resolver.getUTF8Content( "common/horizon/" + filename).getBytes("utf-8")); } private Record createAlephRecord(String filename) throws IOException { //noinspection DuplicateStringLiteralInspection return new Record(filename, "aleph", Resolver.getUTF8Content( "common/aleph/" + filename).getBytes("utf-8")); } @Override public void tearDown() throws Exception { super.tearDown(); records.clear(); } public static Test suite() { return new TestSuite(MarcMultiVolumeMergerTest.class); } @SuppressWarnings({"DuplicateStringLiteralInspection"}) public void testMerge() throws Exception { makeSampleHorizon(); MarcMultiVolumeMerger merger = new MarcMultiVolumeMerger(Configuration.newMemoryBased()); merger.setSource(this); String processed = merger.next().getRecord().getContentAsUTF8(); // log.info("Processed:\n" + processed); // FIXME: Convert this to a proper XML-assert as the attribute order depends on Java version assertContains(processed, // BIND "<datafield ind2=\"0\" ind1=\"0\" tag=\"248\">" + "<subfield code=\"a\">Kaoskyllingens endeligt</subfield>"); assertContains(processed, // SECTION "<datafield ind2=\"0\" ind1=\"0\" tag=\"247\">" + "<subfield code=\"a\">Kaoskyllingens rige</subfield>"); assertContains(processed, // HOVEDPOST "<datafield tag=\"245\" ind1=\"0\" ind2=\"0\">" + "<subfield code=\"a\">Kaoskyllingen</subfield>"); assertContains(processed, // Correct close tag "</record>"); } public void testDeleteDiscard() throws IOException { makeSampleHorizon(); markAsDeleted("child_book1.xml"); // child1: Den apokalyptiske Kaoskylling MarcMultiVolumeMerger merger = new MarcMultiVolumeMerger(Configuration.newMemoryBased()); merger.setSource(this); String processed = merger.next().getRecord().getContentAsUTF8(); assertFalse("The result should not contain the deleted record\n" + processed, processed.contains("Den apokalyptiske Kaoskylling")); } @SuppressWarnings("SameParameterValue") private void markAsDeleted(String id) { for (Record record: records) { if (id.equals(record.getId())) { record.setDeleted(true); return; } for (Record sub: record.getChildren()) { if (id.equals(sub.getId())) { sub.setDeleted(true); return; } } for (Record sup: record.getParents()) { if (id.equals(sup.getId())) { sup.setDeleted(true); return; } } } fail("Unable to locate record with ID '" + id + "' intended for delete marker"); } // <datafieldind2="0"ind1="0"tag="248"><subfieldcode="a">Kaoskyllingensendeligt</subfield> // <datafieldtag="248"ind2="0"ind1="0"><subfieldcode="a">Kaoskyllingensendeligt</subfield> public void testMergeAleph() throws Exception { makeSampleAleph(); MarcMultiVolumeMerger merger = new MarcMultiVolumeMerger( Configuration.newMemoryBased()); merger.setSource(this); String processed = merger.next().getRecord().getContentAsUTF8(); assertNotNull("DOM-parsing should succeed for\n" + countTestCases(), DOM.stringToDOM(processed)); assertTrue("The result should contain 'Frühe'\n" + processed, processed.contains("Frühe")); } public void testExtraContent() throws Exception { makeSampleAleph(); List<Record> children = records.get(0).getChildren(); children.add(new Record("Dummy", "bar", new byte[10])); records.get(0).setChildren(children); Configuration conf = Configuration.newMemoryBased(); Configuration ignoreConf = conf.createSubConfiguration( MarcMultiVolumeMerger.CONF_MERGE_RECORDS); ignoreConf.set(PayloadMatcher.CONF_BASE_REGEX, "aleph"); MarcMultiVolumeMerger merger = new MarcMultiVolumeMerger(conf); merger.setSource(this); String processed = merger.next().getRecord().getContentAsUTF8(); assertNotNull("DOM-parsing should succeed for\n" + countTestCases(), DOM.stringToDOM(processed)); assertTrue("The result should contain 'Frühe'\n" + processed, processed.contains("Frühe")); } private void assertContains(String main, String sub) { boolean contains = flatten(main).contains(flatten(sub)); assertTrue("The String '" + sub + "' should exist in the main String\n" + main, contains); } private String flatten(String str) { return str.replace(" ", "").replace("\n", ""); } /* simple ObjectFilter implementation */ @Override public boolean hasNext() { return !records.isEmpty(); } @Override public void setSource(Filter filter) { // Nada } @Override public boolean pump() throws IOException { return hasNext() && next() != null && hasNext(); } @Override public void close(boolean success) { records.clear(); } @Override public Payload next() { return new Payload(records.remove(0)); } @Override public void remove() { // Nada } }
Testing: Slight hardening of test code to be more accepting of tweaks
Core/src/test/java/dk/statsbiblioteket/summa/common/legacy/MarcMultiVolumeMergerTest.java
Testing: Slight hardening of test code to be more accepting of tweaks
<ide><path>ore/src/test/java/dk/statsbiblioteket/summa/common/legacy/MarcMultiVolumeMergerTest.java <ide> import java.util.Arrays; <ide> import java.util.List; <ide> <del>public class MarcMultiVolumeMergerTest extends TestCase implements <del> ObjectFilter { <add>public class MarcMultiVolumeMergerTest extends TestCase implements ObjectFilter { <ide> private static Log log = LogFactory.getLog(MarcMultiVolumeMergerTest.class); <ide> <ide> private List<Record> records; <ide> record.setDeleted(true); <ide> return; <ide> } <del> for (Record sub: record.getChildren()) { <del> if (id.equals(sub.getId())) { <del> sub.setDeleted(true); <del> return; <add> if (record.hasChildren()) { <add> for (Record sub : record.getChildren()) { <add> if (id.equals(sub.getId())) { <add> sub.setDeleted(true); <add> return; <add> } <ide> } <ide> } <del> for (Record sup: record.getParents()) { <del> if (id.equals(sup.getId())) { <del> sup.setDeleted(true); <del> return; <add> if (record.hasParents()) { <add> for (Record sup : record.getParents()) { <add> if (id.equals(sup.getId())) { <add> sup.setDeleted(true); <add> return; <add> } <ide> } <ide> } <ide> }
JavaScript
agpl-3.0
de182ec8819e3efbb3e0754f7f6bf7cc734eebd6
0
yanovich/pcs-web,yanovich/pcs-web,sergeygaychuk/pcs-web,sergeygaychuk/pcs-web,sergeygaychuk/pcs-web,yanovich/pcs-web
/* test/browser/device_controllers_test.js -- test Device angular controllers * Copyright 2014 Sergei Ianovich * * Licensed under AGPL-3.0 or later, see LICENSE * Process Control Service Web Interface */ 'use strict' describe("Device Controllers", function() { beforeEach(function() { angular.mock.module('pcs.services'); angular.mock.module('pcs.controllers'); }); var httpBackend; beforeEach(inject(function($httpBackend) { httpBackend = $httpBackend; })); afterEach(function(){ httpBackend.verifyNoOutstandingExpectation(); }); describe("NewDeviceCtrl", function() { var scope, location, controller; beforeEach(inject(function($location, $controller) { location = $location; controller = $controller; scope = { page: sinon.spy(), setNewURL: sinon.spy(), }; })); it("should clear pager", function() { controller('NewDeviceCtrl', { $scope: scope }); expect(scope.page).to.have.been.calledWith(1, 1, 0); }); it("should clear setNewURL", function() { controller('NewDeviceCtrl', { $scope: scope }); expect(scope.setNewURL).to.have.been.calledWith(null); }); it("should create device in scope", function() { controller('NewDeviceCtrl', { $scope: scope }); expect(scope.device).to.exist(); }); describe("#save", function() { beforeEach(function() { scope.deviceForm = { $setPristine: sinon.spy(), }; httpBackend.expectPOST('/devices', { name: "hello" }).respond({_id: 2, name: "hello"}); controller('NewDeviceCtrl', { $scope: scope }); scope.device.name = "hello"; }); it("should save device", function() { scope.save(); }); it("should set the form pristine", function() { scope.save(); httpBackend.flush(); expect(scope.deviceForm.$setPristine).to.have.been.called; }); it("should change location path", function() { scope.save(); httpBackend.flush(); expect(location.path()).to.equal('/devices/2'); }); }); }); describe("DevicesCtrl", function() { var scope, controller; beforeEach(inject(function($controller) { controller = $controller; scope = { page: sinon.spy(), setNewURL: sinon.spy(), }; })); it("should setup pager", function() { httpBackend.expectGET('/devices?page=1').respond([{_id: 1}, {_id: 2}, {count: 2}]); controller('DevicesCtrl', { $scope: scope }); httpBackend.flush(); expect(scope.page).to.have.been.calledWith(1, 25, 2); }); }); }); // vim:ts=2 sts=2 sw=2 et:
test/browser/device_controllers_test.js
/* test/browser/device_controllers_test.js -- test Device angular controllers * Copyright 2014 Sergei Ianovich * * Licensed under AGPL-3.0 or later, see LICENSE * Process Control Service Web Interface */ 'use strict' describe("Device Controllers", function() { beforeEach(function() { angular.mock.module('pcs.services'); angular.mock.module('pcs.controllers'); }); var httpBackend; beforeEach(inject(function($httpBackend) { httpBackend = $httpBackend; })); afterEach(function(){ httpBackend.verifyNoOutstandingExpectation(); }); describe("NewDeviceCtrl", function() { var scope, location, controller; beforeEach(inject(function($location, $controller) { location = $location; controller = $controller; scope = { page: sinon.spy(), setNewURL: sinon.spy(), }; })); it("should clear pager", function() { controller('NewDeviceCtrl', { $scope: scope }); expect(scope.page).to.have.been.calledWith(1, 1, 0); }); it("should clear setNewURL", function() { controller('NewDeviceCtrl', { $scope: scope }); expect(scope.setNewURL).to.have.been.calledWith(null); }); it("should create device in scope", function() { controller('NewDeviceCtrl', { $scope: scope }); expect(scope.device).to.exist(); }); describe("#save", function() { beforeEach(function() { scope.deviceForm = { $setPristine: sinon.spy(), }; httpBackend.expectPOST('/devices', { name: "hello" }).respond({_id: 2, name: "hello"}); controller('NewDeviceCtrl', { $scope: scope }); scope.device.name = "hello"; }); it("should save device", function() { scope.save(); }); it("should set the form pristine", function() { scope.save(); httpBackend.flush(); expect(scope.deviceForm.$setPristine).to.have.been.called; }); it("should change location path", function() { scope.save(); httpBackend.flush(); expect(location.path()).to.equal('/devices/2'); }); }); }); }); // vim:ts=2 sts=2 sw=2 et:
tests: ajax: device index pager handling Signed-off-by: Sergei Ianovich <[email protected]>
test/browser/device_controllers_test.js
tests: ajax: device index pager handling
<ide><path>est/browser/device_controllers_test.js <ide> }); <ide> }); <ide> }); <add> <add> describe("DevicesCtrl", function() { <add> var scope, controller; <add> <add> beforeEach(inject(function($controller) { <add> controller = $controller; <add> scope = { <add> page: sinon.spy(), <add> setNewURL: sinon.spy(), <add> }; <add> })); <add> <add> it("should setup pager", function() { <add> httpBackend.expectGET('/devices?page=1').respond([{_id: 1}, {_id: 2}, {count: 2}]); <add> controller('DevicesCtrl', { $scope: scope }); <add> httpBackend.flush(); <add> expect(scope.page).to.have.been.calledWith(1, 25, 2); <add> }); <add> }); <ide> }); <ide> // vim:ts=2 sts=2 sw=2 et:
Java
apache-2.0
4658347a21fcea3d4b93d4400444308727f88225
0
apache/airavata,apache/airavata,apache/airavata,apache/airavata,apache/airavata,apache/airavata,apache/airavata,apache/airavata
/** * * 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. */ package org.apache.airavata.sharing.registry.migrator.airavata; import org.apache.airavata.common.exception.ApplicationSettingsException; import org.apache.airavata.common.utils.AiravataUtils; import org.apache.airavata.common.utils.ServerSettings; import org.apache.airavata.credential.store.client.CredentialStoreClientFactory; import org.apache.airavata.credential.store.cpi.CredentialStoreService; import org.apache.airavata.credential.store.exception.CredentialStoreException; import org.apache.airavata.model.appcatalog.appdeployment.ApplicationDeploymentDescription; import org.apache.airavata.model.appcatalog.computeresource.ComputeResourceDescription; import org.apache.airavata.model.appcatalog.gatewaygroups.GatewayGroups; import org.apache.airavata.model.appcatalog.gatewayprofile.ComputeResourcePreference; import org.apache.airavata.model.appcatalog.gatewayprofile.GatewayResourceProfile; import org.apache.airavata.model.appcatalog.groupresourceprofile.ComputeResourcePolicy; import org.apache.airavata.model.appcatalog.groupresourceprofile.GroupComputeResourcePreference; import org.apache.airavata.model.appcatalog.groupresourceprofile.GroupResourceProfile; import org.apache.airavata.model.credential.store.CredentialSummary; import org.apache.airavata.model.credential.store.PasswordCredential; import org.apache.airavata.model.credential.store.SummaryType; import org.apache.airavata.model.group.ResourcePermissionType; import org.apache.airavata.model.group.ResourceType; import org.apache.airavata.registry.api.RegistryService; import org.apache.airavata.registry.api.client.RegistryServiceClientFactory; import org.apache.airavata.registry.api.exception.RegistryServiceException; import org.apache.airavata.service.profile.iam.admin.services.core.impl.TenantManagementKeycloakImpl; import org.apache.airavata.sharing.registry.models.*; import org.apache.airavata.sharing.registry.server.SharingRegistryServerHandler; import org.apache.thrift.TException; import java.sql.Connection; import java.sql.ResultSet; import java.sql.SQLException; import java.sql.Statement; import java.util.*; import java.util.stream.Collectors; public class AiravataDataMigrator { public static void main(String[] args) throws SQLException, ClassNotFoundException, TException, ApplicationSettingsException { String gatewayId = null; if (args.length > 0) { gatewayId = args[0]; } String gatewayWhereClause = ""; if (gatewayId != null) { System.out.println("Running sharing data migration for " + gatewayId); gatewayWhereClause = " WHERE GATEWAY_ID = '" + gatewayId + "'"; } else { System.out.println("Running sharing data migration for all gateways"); } Connection expCatConnection = ConnectionFactory.getInstance().getExpCatConnection(); SharingRegistryServerHandler sharingRegistryServerHandler = new SharingRegistryServerHandler(); CredentialStoreService.Client credentialStoreServiceClient = getCredentialStoreServiceClient(); String query = "SELECT * FROM GATEWAY" + gatewayWhereClause; Statement statement = expCatConnection.createStatement(); ResultSet rs = statement.executeQuery(query); while (rs.next()) { try{ //Creating domain entries Domain domain = new Domain(); domain.setDomainId(rs.getString("GATEWAY_ID")); domain.setName(rs.getString("GATEWAY_ID")); domain.setDescription("Domain entry for " + domain.name); if (!sharingRegistryServerHandler.isDomainExists(domain.domainId)) sharingRegistryServerHandler.createDomain(domain); //Creating Entity Types for each domain EntityType entityType = new EntityType(); entityType.setEntityTypeId(domain.domainId+":PROJECT"); entityType.setDomainId(domain.domainId); entityType.setName("PROJECT"); entityType.setDescription("Project entity type"); if (!sharingRegistryServerHandler.isEntityTypeExists(entityType.domainId, entityType.entityTypeId)) sharingRegistryServerHandler.createEntityType(entityType); entityType = new EntityType(); entityType.setEntityTypeId(domain.domainId+":EXPERIMENT"); entityType.setDomainId(domain.domainId); entityType.setName("EXPERIMENT"); entityType.setDescription("Experiment entity type"); if (!sharingRegistryServerHandler.isEntityTypeExists(entityType.domainId, entityType.entityTypeId)) sharingRegistryServerHandler.createEntityType(entityType); entityType = new EntityType(); entityType.setEntityTypeId(domain.domainId+":FILE"); entityType.setDomainId(domain.domainId); entityType.setName("FILE"); entityType.setDescription("File entity type"); if (!sharingRegistryServerHandler.isEntityTypeExists(entityType.domainId, entityType.entityTypeId)) sharingRegistryServerHandler.createEntityType(entityType); entityType = new EntityType(); entityType.setEntityTypeId(domain.domainId+":"+ ResourceType.APPLICATION_DEPLOYMENT.name()); entityType.setDomainId(domain.domainId); entityType.setName("APPLICATION-DEPLOYMENT"); entityType.setDescription("Application Deployment entity type"); if (!sharingRegistryServerHandler.isEntityTypeExists(entityType.domainId, entityType.entityTypeId)) sharingRegistryServerHandler.createEntityType(entityType); entityType = new EntityType(); entityType.setEntityTypeId(domain.domainId+":"+ResourceType.GROUP_RESOURCE_PROFILE.name()); entityType.setDomainId(domain.domainId); entityType.setName(ResourceType.GROUP_RESOURCE_PROFILE.name()); entityType.setDescription("Group Resource Profile entity type"); if (!sharingRegistryServerHandler.isEntityTypeExists(entityType.domainId, entityType.entityTypeId)) sharingRegistryServerHandler.createEntityType(entityType); entityType = new EntityType(); entityType.setEntityTypeId(domain.domainId+":"+ResourceType.CREDENTIAL_TOKEN.name()); entityType.setDomainId(domain.domainId); entityType.setName(ResourceType.CREDENTIAL_TOKEN.name()); entityType.setDescription("Credential Store Token entity type"); if (!sharingRegistryServerHandler.isEntityTypeExists(entityType.domainId, entityType.entityTypeId)) sharingRegistryServerHandler.createEntityType(entityType); //Creating Permission Types for each domain PermissionType permissionType = new PermissionType(); permissionType.setPermissionTypeId(domain.domainId+":READ"); permissionType.setDomainId(domain.domainId); permissionType.setName("READ"); permissionType.setDescription("Read permission type"); if (!sharingRegistryServerHandler.isPermissionExists(permissionType.domainId, permissionType.permissionTypeId)) sharingRegistryServerHandler.createPermissionType(permissionType); permissionType = new PermissionType(); permissionType.setPermissionTypeId(domain.domainId+":WRITE"); permissionType.setDomainId(domain.domainId); permissionType.setName("WRITE"); permissionType.setDescription("Write permission type"); if (!sharingRegistryServerHandler.isPermissionExists(permissionType.domainId, permissionType.permissionTypeId)) sharingRegistryServerHandler.createPermissionType(permissionType); }catch (Exception ex){ ex.printStackTrace(); } } //Creating user entries query = "SELECT * FROM USERS" + gatewayWhereClause; statement = expCatConnection.createStatement(); rs = statement.executeQuery(query); while(rs.next()){ try{ User user = new User(); user.setUserId(rs.getString("AIRAVATA_INTERNAL_USER_ID")); user.setDomainId(rs.getString("GATEWAY_ID")); user.setUserName(rs.getString("USER_NAME")); if (!sharingRegistryServerHandler.isUserExists(user.domainId, user.userId)) sharingRegistryServerHandler.createUser(user); }catch (Exception ex){ ex.printStackTrace(); } } //Map to reuse the domain ID and owner for creating application-deployment entities Map<String, String> domainOwnerMap = new HashMap<>(); Map<String, GatewayGroups> gatewayGroupsMap = new HashMap<>(); //Creating the gateway groups List<Domain> domainList = sharingRegistryServerHandler.getDomains(0, -1); final RegistryService.Client registryServiceClient = getRegistryServiceClient(); for (Domain domain : domainList) { // If we're only running migration for gatewayId, then skip other gateways if (gatewayId != null && !gatewayId.equals(domain.domainId)) { continue; } String ownerId = getAdminOwnerUser(domain, sharingRegistryServerHandler, credentialStoreServiceClient, registryServiceClient); if (ownerId != null) { domainOwnerMap.put(domain.domainId, ownerId); } else { continue; } if (registryServiceClient.isGatewayGroupsExists(domain.domainId)) { GatewayGroups gatewayGroups = registryServiceClient.getGatewayGroups(domain.domainId); gatewayGroupsMap.put(domain.domainId, gatewayGroups); } else { GatewayGroups gatewayGroups = migrateRolesToGatewayGroups(domain, ownerId, sharingRegistryServerHandler, registryServiceClient); gatewayGroupsMap.put(domain.domainId, gatewayGroups); } } //Creating project entries query = "SELECT * FROM PROJECT" + gatewayWhereClause; statement = expCatConnection.createStatement(); rs = statement.executeQuery(query); List<Entity> projectEntities = new ArrayList<>(); while(rs.next()){ try{ Entity entity = new Entity(); entity.setEntityId(rs.getString("PROJECT_ID")); entity.setDomainId(rs.getString("GATEWAY_ID")); entity.setEntityTypeId(rs.getString("GATEWAY_ID") + ":PROJECT"); entity.setOwnerId(rs.getString("USER_NAME") + "@" + rs.getString("GATEWAY_ID")); entity.setName(rs.getString("PROJECT_NAME")); entity.setDescription(rs.getString("DESCRIPTION")); if(entity.getDescription() == null) entity.setFullText(entity.getName()); else entity.setFullText(entity.getName() + " " + entity.getDescription()); // Map<String, String> metadata = new HashMap<>(); // metadata.put("CREATION_TIME", rs.getDate("CREATION_TIME").toString()); projectEntities.add(entity); }catch (Exception ex) { ex.printStackTrace(); } } //Creating experiment entries query = "SELECT * FROM EXPERIMENT" + gatewayWhereClause; statement = expCatConnection.createStatement(); rs = statement.executeQuery(query); List<Entity> experimentEntities = new ArrayList<>(); while(rs.next()){ try { Entity entity = new Entity(); entity.setEntityId(rs.getString("EXPERIMENT_ID")); entity.setDomainId(rs.getString("GATEWAY_ID")); entity.setEntityTypeId(rs.getString("GATEWAY_ID") + ":EXPERIMENT"); entity.setOwnerId(rs.getString("USER_NAME") + "@" + rs.getString("GATEWAY_ID")); entity.setParentEntityId(rs.getString("PROJECT_ID")); entity.setName(rs.getString("EXPERIMENT_NAME")); entity.setDescription(rs.getString("DESCRIPTION")); if(entity.getDescription() == null) entity.setFullText(entity.getName()); else entity.setFullText(entity.getName() + " " + entity.getDescription()); // Map<String, String> metadata = new HashMap<>(); // metadata.put("CREATION_TIME", rs.getDate("CREATION_TIME").toString()); // metadata.put("EXPERIMENT_TYPE", rs.getString("EXPERIMENT_TYPE")); // metadata.put("EXECUTION_ID", rs.getString("EXECUTION_ID")); // metadata.put("GATEWAY_EXECUTION_ID", rs.getString("GATEWAY_EXECUTION_ID")); // metadata.put("ENABLE_EMAIL_NOTIFICATION", rs.getString("ENABLE_EMAIL_NOTIFICATION")); // metadata.put("EMAIL_ADDRESSES", rs.getString("EMAIL_ADDRESSES")); // metadata.put("GATEWAY_INSTANCE_ID", rs.getString("GATEWAY_INSTANCE_ID")); // metadata.put("ARCHIVE", rs.getString("ARCHIVE")); experimentEntities.add(entity); }catch (Exception ex){ ex.printStackTrace(); } } for (Entity entity : projectEntities) { if (!sharingRegistryServerHandler.isEntityExists(entity.domainId, entity.entityId)) { sharingRegistryServerHandler.createEntity(entity); } } for (Entity entity : experimentEntities) { if (!sharingRegistryServerHandler.isEntityExists(entity.domainId, entity.entityId)) { if (!sharingRegistryServerHandler.isEntityExists(entity.domainId, entity.parentEntityId)) { System.out.println("Warning: project entity does exist for experiment entity " + entity.entityId + " in gateway " + entity.domainId); continue; } else { sharingRegistryServerHandler.createEntity(entity); } } if (gatewayGroupsMap.containsKey(entity.domainId)) { shareEntityWithAdminGatewayGroups(sharingRegistryServerHandler, entity, gatewayGroupsMap.get(entity.domainId), false); } else { System.out.println("Warning: no Admin gateway groups to share experiment entity " + entity.entityId + " in gateway " + entity.domainId); } } //Creating application deployment entries for (String domainID : domainOwnerMap.keySet()) { GatewayGroups gatewayGroups = gatewayGroupsMap.get(domainID); List<ApplicationDeploymentDescription> applicationDeploymentDescriptionList = registryServiceClient.getAllApplicationDeployments(domainID); for (ApplicationDeploymentDescription description : applicationDeploymentDescriptionList) { Entity entity = new Entity(); entity.setEntityId(description.getAppDeploymentId()); entity.setDomainId(domainID); entity.setEntityTypeId(entity.domainId + ":" + ResourceType.APPLICATION_DEPLOYMENT.name()); entity.setOwnerId(domainOwnerMap.get(domainID) + "@" + entity.domainId); entity.setName(description.getAppDeploymentId()); entity.setDescription(description.getAppDeploymentDescription()); if (entity.getDescription() == null) entity.setDescription(entity.getName()); else entity.setFullText(entity.getName() + " " + entity.getDescription()); if (!sharingRegistryServerHandler.isEntityExists(entity.domainId, entity.entityId)) sharingRegistryServerHandler.createEntity(entity); shareEntityWithGatewayGroups(sharingRegistryServerHandler, entity, gatewayGroups, false); } } // Migrating from GatewayResourceProfile to GroupResourceProfile for (String domainID : domainOwnerMap.keySet()) { GatewayGroups gatewayGroups = gatewayGroupsMap.get(domainID); if (needsGroupResourceProfileMigration(domainID, registryServiceClient)) { GroupResourceProfile groupResourceProfile = migrateGatewayResourceProfileToGroupResourceProfile(domainID, registryServiceClient); // create GroupResourceProfile entity in sharing registry Entity entity = new Entity(); entity.setEntityId(groupResourceProfile.getGroupResourceProfileId()); entity.setDomainId(domainID); entity.setEntityTypeId(entity.domainId + ":" + ResourceType.GROUP_RESOURCE_PROFILE.name()); entity.setOwnerId(domainOwnerMap.get(domainID)); entity.setName(groupResourceProfile.getGroupResourceProfileName()); entity.setDescription(groupResourceProfile.getGroupResourceProfileName() + " Group Resource Profile"); if (!sharingRegistryServerHandler.isEntityExists(entity.domainId, entity.entityId)) sharingRegistryServerHandler.createEntity(entity); shareEntityWithGatewayGroups(sharingRegistryServerHandler, entity, gatewayGroups, false); } } // Creating credential store token entries (GATEWAY SSH tokens) for (String domainID : domainOwnerMap.keySet()) { List<CredentialSummary> gatewayCredentialSummaries = credentialStoreServiceClient.getAllCredentialSummaryForGateway(SummaryType.SSH, domainID); for (CredentialSummary credentialSummary : gatewayCredentialSummaries) { Entity entity = new Entity(); entity.setEntityId(credentialSummary.getToken()); entity.setDomainId(domainID); entity.setEntityTypeId(entity.domainId + ":" + ResourceType.CREDENTIAL_TOKEN.name()); entity.setOwnerId(domainOwnerMap.get(domainID)); entity.setName(credentialSummary.getToken()); entity.setDescription(credentialSummary.getDescription()); if (!sharingRegistryServerHandler.isEntityExists(entity.domainId, entity.entityId)) sharingRegistryServerHandler.createEntity(entity); if (gatewayGroupsMap.containsKey(entity.domainId)) { shareEntityWithAdminGatewayGroups(sharingRegistryServerHandler, entity, gatewayGroupsMap.get(entity.domainId), false); } } } // Creating credential store token entries (USER SSH tokens) for (String domainID : domainOwnerMap.keySet()) { List<User> sharingUsers = sharingRegistryServerHandler.getUsers(domainID, 0, Integer.MAX_VALUE); for (User sharingUser : sharingUsers) { String userId = sharingUser.getUserId(); int index = userId.lastIndexOf("@"); if (index <= 0) { System.out.println("Skipping credentials for user " + userId + " since sharing user id is improperly formed"); continue; } String username = userId.substring(0, userId.lastIndexOf("@")); List<CredentialSummary> gatewayCredentialSummaries = credentialStoreServiceClient.getAllCredentialSummaryForUserInGateway(SummaryType.SSH, domainID, username); for (CredentialSummary credentialSummary : gatewayCredentialSummaries) { Entity entity = new Entity(); entity.setEntityId(credentialSummary.getToken()); entity.setDomainId(domainID); entity.setEntityTypeId(entity.domainId + ":" + ResourceType.CREDENTIAL_TOKEN.name()); entity.setOwnerId(userId); entity.setName(credentialSummary.getToken()); entity.setDescription(credentialSummary.getDescription()); if (!sharingRegistryServerHandler.isEntityExists(entity.domainId, entity.entityId)) sharingRegistryServerHandler.createEntity(entity); if (gatewayGroupsMap.containsKey(entity.domainId)) { shareEntityWithAdminGatewayGroups(sharingRegistryServerHandler, entity, gatewayGroupsMap.get(entity.domainId), false); } } } } // Creating credential store token entries (GATEWAY PWD tokens) for (String domainID : domainOwnerMap.keySet()) { Map<String, String> gatewayPasswords = credentialStoreServiceClient.getAllPWDCredentialsForGateway(domainID); for (Map.Entry<String, String> gatewayPasswordEntry : gatewayPasswords.entrySet()) { Entity entity = new Entity(); entity.setEntityId(gatewayPasswordEntry.getKey()); entity.setDomainId(domainID); entity.setEntityTypeId(entity.domainId + ":" + ResourceType.CREDENTIAL_TOKEN.name()); entity.setOwnerId(domainOwnerMap.get(domainID)); entity.setName(gatewayPasswordEntry.getKey()); entity.setDescription(gatewayPasswordEntry.getValue()); if (!sharingRegistryServerHandler.isEntityExists(entity.domainId, entity.entityId)) sharingRegistryServerHandler.createEntity(entity); if (gatewayGroupsMap.containsKey(entity.domainId)) { shareEntityWithAdminGatewayGroups(sharingRegistryServerHandler, entity, gatewayGroupsMap.get(entity.domainId), false); } } } expCatConnection.close(); System.out.println("Completed!"); System.exit(0); } private static void shareEntityWithGatewayGroups(SharingRegistryServerHandler sharingRegistryServerHandler, Entity entity, GatewayGroups gatewayGroups, boolean cascadePermission) throws TException { // Give default Gateway Users group READ access sharingRegistryServerHandler.shareEntityWithGroups(entity.domainId, entity.entityId, Arrays.asList(gatewayGroups.getDefaultGatewayUsersGroupId()), entity.domainId + ":" + ResourcePermissionType.READ, cascadePermission); shareEntityWithAdminGatewayGroups(sharingRegistryServerHandler, entity, gatewayGroups, cascadePermission); } private static void shareEntityWithAdminGatewayGroups(SharingRegistryServerHandler sharingRegistryServerHandler, Entity entity, GatewayGroups gatewayGroups, boolean cascadePermission) throws TException { // Give Admins group and Read Only Admins group READ access sharingRegistryServerHandler.shareEntityWithGroups(entity.domainId, entity.entityId, Arrays.asList(gatewayGroups.getAdminsGroupId(), gatewayGroups.getReadOnlyAdminsGroupId()), entity.domainId + ":" + ResourcePermissionType.READ, cascadePermission); // Give Admins group WRITE access sharingRegistryServerHandler.shareEntityWithGroups(entity.domainId, entity.entityId, Arrays.asList(gatewayGroups.getAdminsGroupId()), entity.domainId + ":" + ResourcePermissionType.WRITE, cascadePermission); } private static GatewayGroups migrateRolesToGatewayGroups(Domain domain, String ownerId, SharingRegistryServerHandler sharingRegistryServerHandler, RegistryService.Client registryServiceClient) throws TException, ApplicationSettingsException { GatewayGroups gatewayGroups = new GatewayGroups(); gatewayGroups.setGatewayId(domain.domainId); // Migrate roles to groups List<String> usernames = sharingRegistryServerHandler.getUsers(domain.domainId, 0, -1) .stream() // Filter out bad ids that don't have an "@" in them .filter(user -> user.getUserId().lastIndexOf("@") > 0) .map(user -> user.getUserId().substring(0, user.getUserId().lastIndexOf("@"))) .collect(Collectors.toList()); Map<String, List<String>> roleMap = loadRolesForUsers(domain.domainId, usernames); UserGroup gatewayUsersGroup = createGroup(sharingRegistryServerHandler, domain, ownerId, "Gateway Users", "Default group for users of the gateway.", roleMap.containsKey("gateway-user") ? roleMap.get("gateway-user") : Collections.emptyList()); gatewayGroups.setDefaultGatewayUsersGroupId(gatewayUsersGroup.groupId); UserGroup adminUsersGroup = createGroup(sharingRegistryServerHandler, domain, ownerId, "Admin Users", "Admin users group.", roleMap.containsKey("admin") ? roleMap.get("admin") : Collections.emptyList()); gatewayGroups.setAdminsGroupId(adminUsersGroup.groupId); UserGroup readOnlyAdminsGroup = createGroup(sharingRegistryServerHandler, domain, ownerId, "Read Only Admin Users", "Group of admin users with read-only access.", roleMap.containsKey("admin-read-only") ? roleMap.get("admin-read-only") : Collections.emptyList()); gatewayGroups.setReadOnlyAdminsGroupId(readOnlyAdminsGroup.groupId); registryServiceClient.createGatewayGroups(gatewayGroups); return gatewayGroups; } private static String getAdminOwnerUser(Domain domain, SharingRegistryServerHandler sharingRegistryServerHandler, CredentialStoreService.Client credentialStoreServiceClient, RegistryService.Client registryServiceClient) throws TException { GatewayResourceProfile gatewayResourceProfile = null; try { gatewayResourceProfile = registryServiceClient.getGatewayResourceProfile(domain.domainId); } catch (Exception e) { System.out.println("Skipping creating group based auth migration for " + domain.domainId + " because it doesn't have a GatewayResourceProfile"); return null; } if (gatewayResourceProfile.getIdentityServerPwdCredToken() == null) { System.out.println("Skipping creating group based auth migration for " + domain.domainId + " because it doesn't have an identity server pwd credential token"); return null; } String groupOwner = null; try { PasswordCredential credential = credentialStoreServiceClient.getPasswordCredential( gatewayResourceProfile.getIdentityServerPwdCredToken(), gatewayResourceProfile.getGatewayID()); groupOwner = credential.getLoginUserName(); } catch (Exception e) { System.out.println("Skipping creating group based auth migration for " + domain.domainId + " because the identity server pwd credential could not be retrieved."); return null; } String ownerId = groupOwner + "@" + domain.domainId; if (!sharingRegistryServerHandler.isUserExists(domain.domainId, ownerId)) { System.out.println("Skipping creating group based auth migration for " + domain.domainId + " because admin user doesn't exist in sharing registry."); return null; } return ownerId; } private static Map<String,List<String>> loadRolesForUsers(String gatewayId, List<String> usernames) throws TException, ApplicationSettingsException { TenantManagementKeycloakImpl tenantManagementKeycloak = new TenantManagementKeycloakImpl(); PasswordCredential tenantAdminPasswordCredential = getTenantAdminPasswordCredential(gatewayId); Map<String, List<String>> roleMap = new HashMap<>(); for (String username : usernames) { try { List<String> roles = tenantManagementKeycloak.getUserRoles(tenantAdminPasswordCredential, gatewayId, username); if (roles != null) { for (String role : roles) { if (!roleMap.containsKey(role)) { roleMap.put(role, new ArrayList<>()); } roleMap.get(role).add(username); } } else { System.err.println("Warning: user [" + username + "] in tenant [" + gatewayId + "] has no roles."); } } catch (Exception e) { System.err.println("Error: unable to load roles for user [" + username + "] in tenant [" + gatewayId + "]."); e.printStackTrace(); } } return roleMap; } private static PasswordCredential getTenantAdminPasswordCredential(String tenantId) throws TException, ApplicationSettingsException { GatewayResourceProfile gwrp = getRegistryServiceClient().getGatewayResourceProfile(tenantId); CredentialStoreService.Client csClient = getCredentialStoreServiceClient(); return csClient.getPasswordCredential(gwrp.getIdentityServerPwdCredToken(), gwrp.getGatewayID()); } private static UserGroup createGroup(SharingRegistryServerHandler sharingRegistryServerHandler, Domain domain, String ownerId, String groupName, String groupDescription, List<String> usernames) throws TException { UserGroup userGroup = new UserGroup(); userGroup.setGroupId(AiravataUtils.getId(groupName)); userGroup.setDomainId(domain.domainId); userGroup.setGroupCardinality(GroupCardinality.MULTI_USER); userGroup.setCreatedTime(System.currentTimeMillis()); userGroup.setUpdatedTime(System.currentTimeMillis()); userGroup.setName(groupName); userGroup.setDescription(groupDescription); userGroup.setOwnerId(ownerId); userGroup.setGroupType(GroupType.DOMAIN_LEVEL_GROUP); sharingRegistryServerHandler.createGroup(userGroup); List<String> userIds = usernames.stream() .map(username -> username + "@" + domain.domainId) .collect(Collectors.toList()); sharingRegistryServerHandler.addUsersToGroup(domain.domainId, userIds, userGroup.getGroupId()); return userGroup; } private static boolean needsGroupResourceProfileMigration(String gatewayId, RegistryService.Client registryServiceClient) throws TException { // Return true if GatewayResourceProfile has at least one ComputeResourcePreference and there is no GroupResourceProfile List<ComputeResourcePreference> computeResourcePreferences = registryServiceClient.getAllGatewayComputeResourcePreferences(gatewayId); List<GroupResourceProfile> groupResourceProfiles = registryServiceClient.getGroupResourceList(gatewayId, Collections.emptyList()); return !computeResourcePreferences.isEmpty() && groupResourceProfiles.isEmpty(); } private static GroupResourceProfile migrateGatewayResourceProfileToGroupResourceProfile(String gatewayId, RegistryService.Client registryServiceClient) throws TException { GroupResourceProfile groupResourceProfile = new GroupResourceProfile(); groupResourceProfile.setGatewayId(gatewayId); groupResourceProfile.setGroupResourceProfileName("Default"); List<GroupComputeResourcePreference> groupComputeResourcePreferences = new ArrayList<>(); List<ComputeResourcePolicy> computeResourcePolicies = new ArrayList<>(); List<ComputeResourcePreference> computeResourcePreferences = registryServiceClient.getAllGatewayComputeResourcePreferences(gatewayId); Map<String, String> allComputeResourceNames = registryServiceClient.getAllComputeResourceNames(); for (ComputeResourcePreference computeResourcePreference : computeResourcePreferences) { if (!allComputeResourceNames.containsKey(computeResourcePreference.getComputeResourceId())) { System.out.println("Warning: compute resource " + computeResourcePreference.getComputeResourceId() + " does not exist, skipping converting its ComputeResourcePreference for " + gatewayId); continue; } GroupComputeResourcePreference groupComputeResourcePreference = convertComputeResourcePreferenceToGroupComputeResourcePreference(groupResourceProfile.getGroupResourceProfileId(), computeResourcePreference); ComputeResourcePolicy computeResourcePolicy = createDefaultComputeResourcePolicy(groupResourceProfile.getGroupResourceProfileId(), computeResourcePreference.getComputeResourceId(), registryServiceClient); groupComputeResourcePreferences.add(groupComputeResourcePreference); computeResourcePolicies.add(computeResourcePolicy); } groupResourceProfile.setComputePreferences(groupComputeResourcePreferences); groupResourceProfile.setComputeResourcePolicies(computeResourcePolicies); String groupResourceProfileId = registryServiceClient.createGroupResourceProfile(groupResourceProfile); groupResourceProfile.setGroupResourceProfileId(groupResourceProfileId); return groupResourceProfile; } private static GroupComputeResourcePreference convertComputeResourcePreferenceToGroupComputeResourcePreference(String groupResourceProfileId, ComputeResourcePreference computeResourcePreference) { GroupComputeResourcePreference groupComputeResourcePreference = new GroupComputeResourcePreference(); groupComputeResourcePreference.setGroupResourceProfileId(groupResourceProfileId); groupComputeResourcePreference.setComputeResourceId(computeResourcePreference.getComputeResourceId()); groupComputeResourcePreference.setOverridebyAiravata(computeResourcePreference.isOverridebyAiravata()); groupComputeResourcePreference.setLoginUserName(computeResourcePreference.getLoginUserName()); groupComputeResourcePreference.setPreferredJobSubmissionProtocol(computeResourcePreference.getPreferredJobSubmissionProtocol()); groupComputeResourcePreference.setPreferredDataMovementProtocol(computeResourcePreference.getPreferredDataMovementProtocol()); groupComputeResourcePreference.setPreferredBatchQueue(computeResourcePreference.getPreferredBatchQueue()); groupComputeResourcePreference.setScratchLocation(computeResourcePreference.getScratchLocation()); groupComputeResourcePreference.setAllocationProjectNumber(computeResourcePreference.getAllocationProjectNumber()); groupComputeResourcePreference.setResourceSpecificCredentialStoreToken(computeResourcePreference.getResourceSpecificCredentialStoreToken()); groupComputeResourcePreference.setUsageReportingGatewayId(computeResourcePreference.getUsageReportingGatewayId()); groupComputeResourcePreference.setQualityOfService(computeResourcePreference.getQualityOfService()); // Note: skipping copying of reservation time and ssh account provisioner configuration for now return groupComputeResourcePreference; } private static ComputeResourcePolicy createDefaultComputeResourcePolicy(String groupResourceProfileId, String computeResourceId, RegistryService.Client registryServiceClient) throws TException { ComputeResourcePolicy computeResourcePolicy = new ComputeResourcePolicy(); computeResourcePolicy.setComputeResourceId(computeResourceId); computeResourcePolicy.setGroupResourceProfileId(groupResourceProfileId); ComputeResourceDescription computeResourceDescription = registryServiceClient.getComputeResource(computeResourceId); List<String> batchQueueNames = computeResourceDescription.getBatchQueues().stream().map(bq -> bq.getQueueName()).collect(Collectors.toList()); computeResourcePolicy.setAllowedBatchQueues(batchQueueNames); return computeResourcePolicy; } private static CredentialStoreService.Client getCredentialStoreServiceClient() throws TException, ApplicationSettingsException { final int serverPort = Integer.parseInt(ServerSettings.getCredentialStoreServerPort()); final String serverHost = ServerSettings.getCredentialStoreServerHost(); try { return CredentialStoreClientFactory.createAiravataCSClient(serverHost, serverPort); } catch (CredentialStoreException e) { throw new TException("Unable to create credential store client...", e); } } private static RegistryService.Client getRegistryServiceClient() throws TException, ApplicationSettingsException { final int serverPort = Integer.parseInt(ServerSettings.getRegistryServerPort()); final String serverHost = ServerSettings.getRegistryServerHost(); try { return RegistryServiceClientFactory.createRegistryClient(serverHost, serverPort); } catch (RegistryServiceException e) { throw new TException("Unable to create registry client...", e); } } }
modules/sharing-registry/sharing-data-migrator/src/main/java/org/apache/airavata/sharing/registry/migrator/airavata/AiravataDataMigrator.java
/** * * 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. */ package org.apache.airavata.sharing.registry.migrator.airavata; import org.apache.airavata.common.exception.ApplicationSettingsException; import org.apache.airavata.common.utils.AiravataUtils; import org.apache.airavata.common.utils.ServerSettings; import org.apache.airavata.credential.store.client.CredentialStoreClientFactory; import org.apache.airavata.credential.store.cpi.CredentialStoreService; import org.apache.airavata.credential.store.exception.CredentialStoreException; import org.apache.airavata.model.appcatalog.appdeployment.ApplicationDeploymentDescription; import org.apache.airavata.model.appcatalog.computeresource.ComputeResourceDescription; import org.apache.airavata.model.appcatalog.gatewaygroups.GatewayGroups; import org.apache.airavata.model.appcatalog.gatewayprofile.ComputeResourcePreference; import org.apache.airavata.model.appcatalog.gatewayprofile.GatewayResourceProfile; import org.apache.airavata.model.appcatalog.groupresourceprofile.ComputeResourcePolicy; import org.apache.airavata.model.appcatalog.groupresourceprofile.GroupComputeResourcePreference; import org.apache.airavata.model.appcatalog.groupresourceprofile.GroupResourceProfile; import org.apache.airavata.model.credential.store.CredentialSummary; import org.apache.airavata.model.credential.store.PasswordCredential; import org.apache.airavata.model.credential.store.SummaryType; import org.apache.airavata.model.group.ResourcePermissionType; import org.apache.airavata.model.group.ResourceType; import org.apache.airavata.registry.api.RegistryService; import org.apache.airavata.registry.api.client.RegistryServiceClientFactory; import org.apache.airavata.registry.api.exception.RegistryServiceException; import org.apache.airavata.service.profile.iam.admin.services.core.impl.TenantManagementKeycloakImpl; import org.apache.airavata.sharing.registry.models.*; import org.apache.airavata.sharing.registry.server.SharingRegistryServerHandler; import org.apache.thrift.TException; import java.sql.Connection; import java.sql.ResultSet; import java.sql.SQLException; import java.sql.Statement; import java.util.*; import java.util.stream.Collectors; public class AiravataDataMigrator { public static void main(String[] args) throws SQLException, ClassNotFoundException, TException, ApplicationSettingsException { String gatewayId = null; if (args.length > 0) { gatewayId = args[0]; } String gatewayWhereClause = ""; if (gatewayId != null) { System.out.println("Running sharing data migration for " + gatewayId); gatewayWhereClause = " WHERE GATEWAY_ID = '" + gatewayId + "'"; } else { System.out.println("Running sharing data migration for all gateways"); } Connection expCatConnection = ConnectionFactory.getInstance().getExpCatConnection(); SharingRegistryServerHandler sharingRegistryServerHandler = new SharingRegistryServerHandler(); CredentialStoreService.Client credentialStoreServiceClient = getCredentialStoreServiceClient(); String query = "SELECT * FROM GATEWAY" + gatewayWhereClause; Statement statement = expCatConnection.createStatement(); ResultSet rs = statement.executeQuery(query); while (rs.next()) { try{ //Creating domain entries Domain domain = new Domain(); domain.setDomainId(rs.getString("GATEWAY_ID")); domain.setName(rs.getString("GATEWAY_ID")); domain.setDescription("Domain entry for " + domain.name); if (!sharingRegistryServerHandler.isDomainExists(domain.domainId)) sharingRegistryServerHandler.createDomain(domain); //Creating Entity Types for each domain EntityType entityType = new EntityType(); entityType.setEntityTypeId(domain.domainId+":PROJECT"); entityType.setDomainId(domain.domainId); entityType.setName("PROJECT"); entityType.setDescription("Project entity type"); if (!sharingRegistryServerHandler.isEntityTypeExists(entityType.domainId, entityType.entityTypeId)) sharingRegistryServerHandler.createEntityType(entityType); entityType = new EntityType(); entityType.setEntityTypeId(domain.domainId+":EXPERIMENT"); entityType.setDomainId(domain.domainId); entityType.setName("EXPERIMENT"); entityType.setDescription("Experiment entity type"); if (!sharingRegistryServerHandler.isEntityTypeExists(entityType.domainId, entityType.entityTypeId)) sharingRegistryServerHandler.createEntityType(entityType); entityType = new EntityType(); entityType.setEntityTypeId(domain.domainId+":FILE"); entityType.setDomainId(domain.domainId); entityType.setName("FILE"); entityType.setDescription("File entity type"); if (!sharingRegistryServerHandler.isEntityTypeExists(entityType.domainId, entityType.entityTypeId)) sharingRegistryServerHandler.createEntityType(entityType); entityType = new EntityType(); entityType.setEntityTypeId(domain.domainId+":"+ ResourceType.APPLICATION_DEPLOYMENT.name()); entityType.setDomainId(domain.domainId); entityType.setName("APPLICATION-DEPLOYMENT"); entityType.setDescription("Application Deployment entity type"); if (!sharingRegistryServerHandler.isEntityTypeExists(entityType.domainId, entityType.entityTypeId)) sharingRegistryServerHandler.createEntityType(entityType); entityType = new EntityType(); entityType.setEntityTypeId(domain.domainId+":"+ResourceType.GROUP_RESOURCE_PROFILE.name()); entityType.setDomainId(domain.domainId); entityType.setName(ResourceType.GROUP_RESOURCE_PROFILE.name()); entityType.setDescription("Group Resource Profile entity type"); if (!sharingRegistryServerHandler.isEntityTypeExists(entityType.domainId, entityType.entityTypeId)) sharingRegistryServerHandler.createEntityType(entityType); entityType = new EntityType(); entityType.setEntityTypeId(domain.domainId+":"+ResourceType.CREDENTIAL_TOKEN.name()); entityType.setDomainId(domain.domainId); entityType.setName(ResourceType.CREDENTIAL_TOKEN.name()); entityType.setDescription("Credential Store Token entity type"); if (!sharingRegistryServerHandler.isEntityTypeExists(entityType.domainId, entityType.entityTypeId)) sharingRegistryServerHandler.createEntityType(entityType); //Creating Permission Types for each domain PermissionType permissionType = new PermissionType(); permissionType.setPermissionTypeId(domain.domainId+":READ"); permissionType.setDomainId(domain.domainId); permissionType.setName("READ"); permissionType.setDescription("Read permission type"); if (!sharingRegistryServerHandler.isPermissionExists(permissionType.domainId, permissionType.permissionTypeId)) sharingRegistryServerHandler.createPermissionType(permissionType); permissionType = new PermissionType(); permissionType.setPermissionTypeId(domain.domainId+":WRITE"); permissionType.setDomainId(domain.domainId); permissionType.setName("WRITE"); permissionType.setDescription("Write permission type"); if (!sharingRegistryServerHandler.isPermissionExists(permissionType.domainId, permissionType.permissionTypeId)) sharingRegistryServerHandler.createPermissionType(permissionType); }catch (Exception ex){ ex.printStackTrace(); } } //Creating user entries query = "SELECT * FROM USERS" + gatewayWhereClause; statement = expCatConnection.createStatement(); rs = statement.executeQuery(query); while(rs.next()){ try{ User user = new User(); user.setUserId(rs.getString("AIRAVATA_INTERNAL_USER_ID")); user.setDomainId(rs.getString("GATEWAY_ID")); user.setUserName(rs.getString("USER_NAME")); if (!sharingRegistryServerHandler.isUserExists(user.domainId, user.userId)) sharingRegistryServerHandler.createUser(user); }catch (Exception ex){ ex.printStackTrace(); } } //Map to reuse the domain ID and owner for creating application-deployment entities Map<String, String> domainOwnerMap = new HashMap<>(); Map<String, GatewayGroups> gatewayGroupsMap = new HashMap<>(); //Creating the gateway groups List<Domain> domainList = sharingRegistryServerHandler.getDomains(0, -1); final RegistryService.Client registryServiceClient = getRegistryServiceClient(); for (Domain domain : domainList) { // If we're only running migration for gatewayId, then skip other gateways if (gatewayId != null && !gatewayId.equals(domain.domainId)) { continue; } String ownerId = getAdminOwnerUser(domain, sharingRegistryServerHandler, credentialStoreServiceClient, registryServiceClient); if (ownerId != null) { domainOwnerMap.put(domain.domainId, ownerId); } else { continue; } if (registryServiceClient.isGatewayGroupsExists(domain.domainId)) { GatewayGroups gatewayGroups = registryServiceClient.getGatewayGroups(domain.domainId); gatewayGroupsMap.put(domain.domainId, gatewayGroups); } else { GatewayGroups gatewayGroups = migrateRolesToGatewayGroups(domain, ownerId, sharingRegistryServerHandler, registryServiceClient); gatewayGroupsMap.put(domain.domainId, gatewayGroups); } } //Creating project entries query = "SELECT * FROM PROJECT" + gatewayWhereClause; statement = expCatConnection.createStatement(); rs = statement.executeQuery(query); List<Entity> projectEntities = new ArrayList<>(); while(rs.next()){ try{ Entity entity = new Entity(); entity.setEntityId(rs.getString("PROJECT_ID")); entity.setDomainId(rs.getString("GATEWAY_ID")); entity.setEntityTypeId(rs.getString("GATEWAY_ID") + ":PROJECT"); entity.setOwnerId(rs.getString("USER_NAME") + "@" + rs.getString("GATEWAY_ID")); entity.setName(rs.getString("PROJECT_NAME")); entity.setDescription(rs.getString("DESCRIPTION")); if(entity.getDescription() == null) entity.setFullText(entity.getName()); else entity.setFullText(entity.getName() + " " + entity.getDescription()); // Map<String, String> metadata = new HashMap<>(); // metadata.put("CREATION_TIME", rs.getDate("CREATION_TIME").toString()); projectEntities.add(entity); }catch (Exception ex) { ex.printStackTrace(); } } //Creating experiment entries query = "SELECT * FROM EXPERIMENT" + gatewayWhereClause; statement = expCatConnection.createStatement(); rs = statement.executeQuery(query); List<Entity> experimentEntities = new ArrayList<>(); while(rs.next()){ try { Entity entity = new Entity(); entity.setEntityId(rs.getString("EXPERIMENT_ID")); entity.setDomainId(rs.getString("GATEWAY_ID")); entity.setEntityTypeId(rs.getString("GATEWAY_ID") + ":EXPERIMENT"); entity.setOwnerId(rs.getString("USER_NAME") + "@" + rs.getString("GATEWAY_ID")); entity.setParentEntityId(rs.getString("PROJECT_ID")); entity.setName(rs.getString("EXPERIMENT_NAME")); entity.setDescription(rs.getString("DESCRIPTION")); if(entity.getDescription() == null) entity.setFullText(entity.getName()); else entity.setFullText(entity.getName() + " " + entity.getDescription()); // Map<String, String> metadata = new HashMap<>(); // metadata.put("CREATION_TIME", rs.getDate("CREATION_TIME").toString()); // metadata.put("EXPERIMENT_TYPE", rs.getString("EXPERIMENT_TYPE")); // metadata.put("EXECUTION_ID", rs.getString("EXECUTION_ID")); // metadata.put("GATEWAY_EXECUTION_ID", rs.getString("GATEWAY_EXECUTION_ID")); // metadata.put("ENABLE_EMAIL_NOTIFICATION", rs.getString("ENABLE_EMAIL_NOTIFICATION")); // metadata.put("EMAIL_ADDRESSES", rs.getString("EMAIL_ADDRESSES")); // metadata.put("GATEWAY_INSTANCE_ID", rs.getString("GATEWAY_INSTANCE_ID")); // metadata.put("ARCHIVE", rs.getString("ARCHIVE")); experimentEntities.add(entity); }catch (Exception ex){ ex.printStackTrace(); } } for (Entity entity : projectEntities) { if (!sharingRegistryServerHandler.isEntityExists(entity.domainId, entity.entityId)) { sharingRegistryServerHandler.createEntity(entity); } } for (Entity entity : experimentEntities) { if (!sharingRegistryServerHandler.isEntityExists(entity.domainId, entity.entityId)) { if (!sharingRegistryServerHandler.isEntityExists(entity.domainId, entity.parentEntityId)) { System.out.println("Warning: project entity does exist for experiment entity " + entity.entityId + " in gateway " + entity.domainId); continue; } else { sharingRegistryServerHandler.createEntity(entity); } } if (gatewayGroupsMap.containsKey(entity.domainId)) { shareEntityWithAdminGatewayGroups(sharingRegistryServerHandler, entity, gatewayGroupsMap.get(entity.domainId), false); } else { System.out.println("Warning: no Admin gateway groups to share experiment entity " + entity.entityId + " in gateway " + entity.domainId); } } //Creating application deployment entries for (String domainID : domainOwnerMap.keySet()) { GatewayGroups gatewayGroups = gatewayGroupsMap.get(domainID); List<ApplicationDeploymentDescription> applicationDeploymentDescriptionList = registryServiceClient.getAllApplicationDeployments(domainID); for (ApplicationDeploymentDescription description : applicationDeploymentDescriptionList) { Entity entity = new Entity(); entity.setEntityId(description.getAppDeploymentId()); entity.setDomainId(domainID); entity.setEntityTypeId(entity.domainId + ":" + ResourceType.APPLICATION_DEPLOYMENT.name()); entity.setOwnerId(domainOwnerMap.get(domainID) + "@" + entity.domainId); entity.setName(description.getAppDeploymentId()); entity.setDescription(description.getAppDeploymentDescription()); if (entity.getDescription() == null) entity.setDescription(entity.getName()); else entity.setFullText(entity.getName() + " " + entity.getDescription()); if (!sharingRegistryServerHandler.isEntityExists(entity.domainId, entity.entityId)) sharingRegistryServerHandler.createEntity(entity); shareEntityWithGatewayGroups(sharingRegistryServerHandler, entity, gatewayGroups, false); } } // Migrating from GatewayResourceProfile to GroupResourceProfile for (String domainID : domainOwnerMap.keySet()) { GatewayGroups gatewayGroups = gatewayGroupsMap.get(domainID); if (needsGroupResourceProfileMigration(domainID, registryServiceClient)) { GroupResourceProfile groupResourceProfile = migrateGatewayResourceProfileToGroupResourceProfile(domainID, registryServiceClient); // create GroupResourceProfile entity in sharing registry Entity entity = new Entity(); entity.setEntityId(groupResourceProfile.getGroupResourceProfileId()); entity.setDomainId(domainID); entity.setEntityTypeId(entity.domainId + ":" + ResourceType.GROUP_RESOURCE_PROFILE.name()); entity.setOwnerId(domainOwnerMap.get(domainID)); entity.setName(groupResourceProfile.getGroupResourceProfileName()); entity.setDescription(groupResourceProfile.getGroupResourceProfileName() + " Group Resource Profile"); if (!sharingRegistryServerHandler.isEntityExists(entity.domainId, entity.entityId)) sharingRegistryServerHandler.createEntity(entity); shareEntityWithGatewayGroups(sharingRegistryServerHandler, entity, gatewayGroups, false); } } // Creating credential store token entries (GATEWAY SSH tokens) for (String domainID : domainOwnerMap.keySet()) { List<CredentialSummary> gatewayCredentialSummaries = credentialStoreServiceClient.getAllCredentialSummaryForGateway(SummaryType.SSH, domainID); for (CredentialSummary credentialSummary : gatewayCredentialSummaries) { Entity entity = new Entity(); entity.setEntityId(credentialSummary.getToken()); entity.setDomainId(domainID); entity.setEntityTypeId(entity.domainId + ":" + ResourceType.CREDENTIAL_TOKEN.name()); entity.setOwnerId(domainOwnerMap.get(domainID)); entity.setName(credentialSummary.getToken()); entity.setDescription(credentialSummary.getDescription()); if (!sharingRegistryServerHandler.isEntityExists(entity.domainId, entity.entityId)) sharingRegistryServerHandler.createEntity(entity); if (gatewayGroupsMap.containsKey(entity.domainId)) { shareEntityWithAdminGatewayGroups(sharingRegistryServerHandler, entity, gatewayGroupsMap.get(entity.domainId), false); } } } // Creating credential store token entries (USER SSH tokens) for (String domainID : domainOwnerMap.keySet()) { List<User> sharingUsers = sharingRegistryServerHandler.getUsers(domainID, 0, Integer.MAX_VALUE); for (User sharingUser : sharingUsers) { String userId = sharingUser.getUserId(); String username = userId.substring(0, userId.lastIndexOf("@")); List<CredentialSummary> gatewayCredentialSummaries = credentialStoreServiceClient.getAllCredentialSummaryForUserInGateway(SummaryType.SSH, domainID, username); for (CredentialSummary credentialSummary : gatewayCredentialSummaries) { Entity entity = new Entity(); entity.setEntityId(credentialSummary.getToken()); entity.setDomainId(domainID); entity.setEntityTypeId(entity.domainId + ":" + ResourceType.CREDENTIAL_TOKEN.name()); entity.setOwnerId(userId); entity.setName(credentialSummary.getToken()); entity.setDescription(credentialSummary.getDescription()); if (!sharingRegistryServerHandler.isEntityExists(entity.domainId, entity.entityId)) sharingRegistryServerHandler.createEntity(entity); if (gatewayGroupsMap.containsKey(entity.domainId)) { shareEntityWithAdminGatewayGroups(sharingRegistryServerHandler, entity, gatewayGroupsMap.get(entity.domainId), false); } } } } // Creating credential store token entries (GATEWAY PWD tokens) for (String domainID : domainOwnerMap.keySet()) { Map<String, String> gatewayPasswords = credentialStoreServiceClient.getAllPWDCredentialsForGateway(domainID); for (Map.Entry<String, String> gatewayPasswordEntry : gatewayPasswords.entrySet()) { Entity entity = new Entity(); entity.setEntityId(gatewayPasswordEntry.getKey()); entity.setDomainId(domainID); entity.setEntityTypeId(entity.domainId + ":" + ResourceType.CREDENTIAL_TOKEN.name()); entity.setOwnerId(domainOwnerMap.get(domainID)); entity.setName(gatewayPasswordEntry.getKey()); entity.setDescription(gatewayPasswordEntry.getValue()); if (!sharingRegistryServerHandler.isEntityExists(entity.domainId, entity.entityId)) sharingRegistryServerHandler.createEntity(entity); if (gatewayGroupsMap.containsKey(entity.domainId)) { shareEntityWithAdminGatewayGroups(sharingRegistryServerHandler, entity, gatewayGroupsMap.get(entity.domainId), false); } } } expCatConnection.close(); System.out.println("Completed!"); System.exit(0); } private static void shareEntityWithGatewayGroups(SharingRegistryServerHandler sharingRegistryServerHandler, Entity entity, GatewayGroups gatewayGroups, boolean cascadePermission) throws TException { // Give default Gateway Users group READ access sharingRegistryServerHandler.shareEntityWithGroups(entity.domainId, entity.entityId, Arrays.asList(gatewayGroups.getDefaultGatewayUsersGroupId()), entity.domainId + ":" + ResourcePermissionType.READ, cascadePermission); shareEntityWithAdminGatewayGroups(sharingRegistryServerHandler, entity, gatewayGroups, cascadePermission); } private static void shareEntityWithAdminGatewayGroups(SharingRegistryServerHandler sharingRegistryServerHandler, Entity entity, GatewayGroups gatewayGroups, boolean cascadePermission) throws TException { // Give Admins group and Read Only Admins group READ access sharingRegistryServerHandler.shareEntityWithGroups(entity.domainId, entity.entityId, Arrays.asList(gatewayGroups.getAdminsGroupId(), gatewayGroups.getReadOnlyAdminsGroupId()), entity.domainId + ":" + ResourcePermissionType.READ, cascadePermission); // Give Admins group WRITE access sharingRegistryServerHandler.shareEntityWithGroups(entity.domainId, entity.entityId, Arrays.asList(gatewayGroups.getAdminsGroupId()), entity.domainId + ":" + ResourcePermissionType.WRITE, cascadePermission); } private static GatewayGroups migrateRolesToGatewayGroups(Domain domain, String ownerId, SharingRegistryServerHandler sharingRegistryServerHandler, RegistryService.Client registryServiceClient) throws TException, ApplicationSettingsException { GatewayGroups gatewayGroups = new GatewayGroups(); gatewayGroups.setGatewayId(domain.domainId); // Migrate roles to groups List<String> usernames = sharingRegistryServerHandler.getUsers(domain.domainId, 0, -1) .stream() // Filter out bad ids that don't have an "@" in them .filter(user -> user.getUserId().lastIndexOf("@") > 0) .map(user -> user.getUserId().substring(0, user.getUserId().lastIndexOf("@"))) .collect(Collectors.toList()); Map<String, List<String>> roleMap = loadRolesForUsers(domain.domainId, usernames); UserGroup gatewayUsersGroup = createGroup(sharingRegistryServerHandler, domain, ownerId, "Gateway Users", "Default group for users of the gateway.", roleMap.containsKey("gateway-user") ? roleMap.get("gateway-user") : Collections.emptyList()); gatewayGroups.setDefaultGatewayUsersGroupId(gatewayUsersGroup.groupId); UserGroup adminUsersGroup = createGroup(sharingRegistryServerHandler, domain, ownerId, "Admin Users", "Admin users group.", roleMap.containsKey("admin") ? roleMap.get("admin") : Collections.emptyList()); gatewayGroups.setAdminsGroupId(adminUsersGroup.groupId); UserGroup readOnlyAdminsGroup = createGroup(sharingRegistryServerHandler, domain, ownerId, "Read Only Admin Users", "Group of admin users with read-only access.", roleMap.containsKey("admin-read-only") ? roleMap.get("admin-read-only") : Collections.emptyList()); gatewayGroups.setReadOnlyAdminsGroupId(readOnlyAdminsGroup.groupId); registryServiceClient.createGatewayGroups(gatewayGroups); return gatewayGroups; } private static String getAdminOwnerUser(Domain domain, SharingRegistryServerHandler sharingRegistryServerHandler, CredentialStoreService.Client credentialStoreServiceClient, RegistryService.Client registryServiceClient) throws TException { GatewayResourceProfile gatewayResourceProfile = null; try { gatewayResourceProfile = registryServiceClient.getGatewayResourceProfile(domain.domainId); } catch (Exception e) { System.out.println("Skipping creating group based auth migration for " + domain.domainId + " because it doesn't have a GatewayResourceProfile"); return null; } if (gatewayResourceProfile.getIdentityServerPwdCredToken() == null) { System.out.println("Skipping creating group based auth migration for " + domain.domainId + " because it doesn't have an identity server pwd credential token"); return null; } String groupOwner = null; try { PasswordCredential credential = credentialStoreServiceClient.getPasswordCredential( gatewayResourceProfile.getIdentityServerPwdCredToken(), gatewayResourceProfile.getGatewayID()); groupOwner = credential.getLoginUserName(); } catch (Exception e) { System.out.println("Skipping creating group based auth migration for " + domain.domainId + " because the identity server pwd credential could not be retrieved."); return null; } String ownerId = groupOwner + "@" + domain.domainId; if (!sharingRegistryServerHandler.isUserExists(domain.domainId, ownerId)) { System.out.println("Skipping creating group based auth migration for " + domain.domainId + " because admin user doesn't exist in sharing registry."); return null; } return ownerId; } private static Map<String,List<String>> loadRolesForUsers(String gatewayId, List<String> usernames) throws TException, ApplicationSettingsException { TenantManagementKeycloakImpl tenantManagementKeycloak = new TenantManagementKeycloakImpl(); PasswordCredential tenantAdminPasswordCredential = getTenantAdminPasswordCredential(gatewayId); Map<String, List<String>> roleMap = new HashMap<>(); for (String username : usernames) { try { List<String> roles = tenantManagementKeycloak.getUserRoles(tenantAdminPasswordCredential, gatewayId, username); if (roles != null) { for (String role : roles) { if (!roleMap.containsKey(role)) { roleMap.put(role, new ArrayList<>()); } roleMap.get(role).add(username); } } else { System.err.println("Warning: user [" + username + "] in tenant [" + gatewayId + "] has no roles."); } } catch (Exception e) { System.err.println("Error: unable to load roles for user [" + username + "] in tenant [" + gatewayId + "]."); e.printStackTrace(); } } return roleMap; } private static PasswordCredential getTenantAdminPasswordCredential(String tenantId) throws TException, ApplicationSettingsException { GatewayResourceProfile gwrp = getRegistryServiceClient().getGatewayResourceProfile(tenantId); CredentialStoreService.Client csClient = getCredentialStoreServiceClient(); return csClient.getPasswordCredential(gwrp.getIdentityServerPwdCredToken(), gwrp.getGatewayID()); } private static UserGroup createGroup(SharingRegistryServerHandler sharingRegistryServerHandler, Domain domain, String ownerId, String groupName, String groupDescription, List<String> usernames) throws TException { UserGroup userGroup = new UserGroup(); userGroup.setGroupId(AiravataUtils.getId(groupName)); userGroup.setDomainId(domain.domainId); userGroup.setGroupCardinality(GroupCardinality.MULTI_USER); userGroup.setCreatedTime(System.currentTimeMillis()); userGroup.setUpdatedTime(System.currentTimeMillis()); userGroup.setName(groupName); userGroup.setDescription(groupDescription); userGroup.setOwnerId(ownerId); userGroup.setGroupType(GroupType.DOMAIN_LEVEL_GROUP); sharingRegistryServerHandler.createGroup(userGroup); List<String> userIds = usernames.stream() .map(username -> username + "@" + domain.domainId) .collect(Collectors.toList()); sharingRegistryServerHandler.addUsersToGroup(domain.domainId, userIds, userGroup.getGroupId()); return userGroup; } private static boolean needsGroupResourceProfileMigration(String gatewayId, RegistryService.Client registryServiceClient) throws TException { // Return true if GatewayResourceProfile has at least one ComputeResourcePreference and there is no GroupResourceProfile List<ComputeResourcePreference> computeResourcePreferences = registryServiceClient.getAllGatewayComputeResourcePreferences(gatewayId); List<GroupResourceProfile> groupResourceProfiles = registryServiceClient.getGroupResourceList(gatewayId, Collections.emptyList()); return !computeResourcePreferences.isEmpty() && groupResourceProfiles.isEmpty(); } private static GroupResourceProfile migrateGatewayResourceProfileToGroupResourceProfile(String gatewayId, RegistryService.Client registryServiceClient) throws TException { GroupResourceProfile groupResourceProfile = new GroupResourceProfile(); groupResourceProfile.setGatewayId(gatewayId); groupResourceProfile.setGroupResourceProfileName("Default"); List<GroupComputeResourcePreference> groupComputeResourcePreferences = new ArrayList<>(); List<ComputeResourcePolicy> computeResourcePolicies = new ArrayList<>(); List<ComputeResourcePreference> computeResourcePreferences = registryServiceClient.getAllGatewayComputeResourcePreferences(gatewayId); Map<String, String> allComputeResourceNames = registryServiceClient.getAllComputeResourceNames(); for (ComputeResourcePreference computeResourcePreference : computeResourcePreferences) { if (!allComputeResourceNames.containsKey(computeResourcePreference.getComputeResourceId())) { System.out.println("Warning: compute resource " + computeResourcePreference.getComputeResourceId() + " does not exist, skipping converting its ComputeResourcePreference for " + gatewayId); continue; } GroupComputeResourcePreference groupComputeResourcePreference = convertComputeResourcePreferenceToGroupComputeResourcePreference(groupResourceProfile.getGroupResourceProfileId(), computeResourcePreference); ComputeResourcePolicy computeResourcePolicy = createDefaultComputeResourcePolicy(groupResourceProfile.getGroupResourceProfileId(), computeResourcePreference.getComputeResourceId(), registryServiceClient); groupComputeResourcePreferences.add(groupComputeResourcePreference); computeResourcePolicies.add(computeResourcePolicy); } groupResourceProfile.setComputePreferences(groupComputeResourcePreferences); groupResourceProfile.setComputeResourcePolicies(computeResourcePolicies); String groupResourceProfileId = registryServiceClient.createGroupResourceProfile(groupResourceProfile); groupResourceProfile.setGroupResourceProfileId(groupResourceProfileId); return groupResourceProfile; } private static GroupComputeResourcePreference convertComputeResourcePreferenceToGroupComputeResourcePreference(String groupResourceProfileId, ComputeResourcePreference computeResourcePreference) { GroupComputeResourcePreference groupComputeResourcePreference = new GroupComputeResourcePreference(); groupComputeResourcePreference.setGroupResourceProfileId(groupResourceProfileId); groupComputeResourcePreference.setComputeResourceId(computeResourcePreference.getComputeResourceId()); groupComputeResourcePreference.setOverridebyAiravata(computeResourcePreference.isOverridebyAiravata()); groupComputeResourcePreference.setLoginUserName(computeResourcePreference.getLoginUserName()); groupComputeResourcePreference.setPreferredJobSubmissionProtocol(computeResourcePreference.getPreferredJobSubmissionProtocol()); groupComputeResourcePreference.setPreferredDataMovementProtocol(computeResourcePreference.getPreferredDataMovementProtocol()); groupComputeResourcePreference.setPreferredBatchQueue(computeResourcePreference.getPreferredBatchQueue()); groupComputeResourcePreference.setScratchLocation(computeResourcePreference.getScratchLocation()); groupComputeResourcePreference.setAllocationProjectNumber(computeResourcePreference.getAllocationProjectNumber()); groupComputeResourcePreference.setResourceSpecificCredentialStoreToken(computeResourcePreference.getResourceSpecificCredentialStoreToken()); groupComputeResourcePreference.setUsageReportingGatewayId(computeResourcePreference.getUsageReportingGatewayId()); groupComputeResourcePreference.setQualityOfService(computeResourcePreference.getQualityOfService()); // Note: skipping copying of reservation time and ssh account provisioner configuration for now return groupComputeResourcePreference; } private static ComputeResourcePolicy createDefaultComputeResourcePolicy(String groupResourceProfileId, String computeResourceId, RegistryService.Client registryServiceClient) throws TException { ComputeResourcePolicy computeResourcePolicy = new ComputeResourcePolicy(); computeResourcePolicy.setComputeResourceId(computeResourceId); computeResourcePolicy.setGroupResourceProfileId(groupResourceProfileId); ComputeResourceDescription computeResourceDescription = registryServiceClient.getComputeResource(computeResourceId); List<String> batchQueueNames = computeResourceDescription.getBatchQueues().stream().map(bq -> bq.getQueueName()).collect(Collectors.toList()); computeResourcePolicy.setAllowedBatchQueues(batchQueueNames); return computeResourcePolicy; } private static CredentialStoreService.Client getCredentialStoreServiceClient() throws TException, ApplicationSettingsException { final int serverPort = Integer.parseInt(ServerSettings.getCredentialStoreServerPort()); final String serverHost = ServerSettings.getCredentialStoreServerHost(); try { return CredentialStoreClientFactory.createAiravataCSClient(serverHost, serverPort); } catch (CredentialStoreException e) { throw new TException("Unable to create credential store client...", e); } } private static RegistryService.Client getRegistryServiceClient() throws TException, ApplicationSettingsException { final int serverPort = Integer.parseInt(ServerSettings.getRegistryServerPort()); final String serverHost = ServerSettings.getRegistryServerHost(); try { return RegistryServiceClientFactory.createRegistryClient(serverHost, serverPort); } catch (RegistryServiceException e) { throw new TException("Unable to create registry client...", e); } } }
AIRAVATA-2840 Skipping sharing users with bad userIds
modules/sharing-registry/sharing-data-migrator/src/main/java/org/apache/airavata/sharing/registry/migrator/airavata/AiravataDataMigrator.java
AIRAVATA-2840 Skipping sharing users with bad userIds
<ide><path>odules/sharing-registry/sharing-data-migrator/src/main/java/org/apache/airavata/sharing/registry/migrator/airavata/AiravataDataMigrator.java <ide> for (User sharingUser : sharingUsers) { <ide> <ide> String userId = sharingUser.getUserId(); <add> int index = userId.lastIndexOf("@"); <add> if (index <= 0) { <add> System.out.println("Skipping credentials for user " + userId + " since sharing user id is improperly formed"); <add> continue; <add> } <ide> String username = userId.substring(0, userId.lastIndexOf("@")); <ide> List<CredentialSummary> gatewayCredentialSummaries = credentialStoreServiceClient.getAllCredentialSummaryForUserInGateway(SummaryType.SSH, domainID, username); <ide> for (CredentialSummary credentialSummary : gatewayCredentialSummaries) {
Java
mit
d82ecb4fee1ed1a501f38d5a8ed64bb4b8ce2061
0
Innovimax-SARL/mix-them
package innovimax.mixthem.io; import java.io.File; import java.io.BufferedReader; import java.io.IOException; import java.nio.charset.StandardCharsets; import java.nio.file.Files; import java.nio.file.Path; /** * <p>Reads characters from a character-input file.</p> * <p>This is the default implementation of IInputChar.</p> * @see IInputChar * @author Innovimax * @version 1.0 */ public class DefaultCharReader implements IInputChar { private final Path path; private final BufferedReader reader; private boolean jump; /** * Creates a character reader. * @param input The input file to be read * @param first True is this reader is the first one for mixing * @throws IOException - If an I/O error occurs */ public DefaultCharReader(File input, boolean first) throws IOException { this.path = input.toPath(); this.reader = Files.newBufferedReader(path, StandardCharsets.UTF_8); this.jump = !first; } /** * Creates a character reader. * @param input The input file to be read * @throws IOException - If an I/O error occurs */ public DefaultCharReader(File input) throws IOException { this(input, true); } @Override public boolean hasCharacter() throws IOException { return this.reader.ready(); } @Override public int nextCharacter(ReadType type) throws IOException { int c = -1; if (hasCharacter()) { switch (type) { case _REGULAR: c = this.reader.read(); break; case _ALT_SIMPLE: if (!this.jump) { c = this.reader.read(); } else { this.reader.read(); } this.jump = !this.jump; break; } } return c; } @Override public int nextCharacters(char[] buffer, int len) throws IOException { return this.reader.read(buffer, 0, len); } @Override public void close() throws IOException { this.reader.close(); } }
src/main/java/innovimax/mixthem/io/DefaultCharReader.java
package innovimax.mixthem.io; import innovimax.mixthem.interfaces.IInputChar; import java.io.File; import java.io.BufferedReader; import java.io.IOException; import java.nio.charset.StandardCharsets; import java.nio.file.Files; import java.nio.file.Path; /** * <p>Reads characters from a character-input file.</p> * <p>This is the default implementation of IInputChar.</p> * @see IInputChar * @author Innovimax * @version 1.0 */ public class DefaultCharReader implements IInputChar { private final Path path; private final BufferedReader reader; private boolean jump; /** * Creates a character reader. * @param input The input file to be read * @param first True is this reader is the first one for mixing * @throws IOException - If an I/O error occurs */ public DefaultCharReader(File input, boolean first) throws IOException { this.path = input.toPath(); this.reader = Files.newBufferedReader(path, StandardCharsets.UTF_8); this.jump = !first; } /** * Creates a character reader. * @param input The input file to be read * @throws IOException - If an I/O error occurs */ public DefaultCharReader(File input) throws IOException { this(input, true); } @Override public boolean hasCharacter() throws IOException { return this.reader.ready(); } @Override public int nextCharacter(ReadType type) throws IOException { int c = -1; if (hasCharacter()) { switch (type) { case _REGULAR: c = this.reader.read(); break; case _ALT_SIMPLE: if (!this.jump) { c = this.reader.read(); } else { this.reader.read(); } this.jump = !this.jump; break; } } return c; } @Override public int nextCharacters(char[] buffer, int len) throws IOException { return this.reader.read(buffer, 0, len); } @Override public void close() throws IOException { this.reader.close(); } }
remove import
src/main/java/innovimax/mixthem/io/DefaultCharReader.java
remove import
<ide><path>rc/main/java/innovimax/mixthem/io/DefaultCharReader.java <ide> package innovimax.mixthem.io; <del> <del>import innovimax.mixthem.interfaces.IInputChar; <ide> <ide> import java.io.File; <ide> import java.io.BufferedReader;
Java
bsd-3-clause
7330836874c5559f164bff8d734844d848df7c35
0
sahara-labs/scheduling-server,sahara-labs/scheduling-server,sahara-labs/scheduling-server,jeking3/scheduling-server,jeking3/scheduling-server,sahara-labs/scheduling-server,jeking3/scheduling-server,sahara-labs/scheduling-server,sahara-labs/scheduling-server,jeking3/scheduling-server,jeking3/scheduling-server,jeking3/scheduling-server
/** * SAHARA Scheduling Server * * Schedules and assigns local laboratory rigs. * * @license See LICENSE in the top level directory for complete license terms. * * Copyright (c) 2010, University of Technology, Sydney * 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 University of Technology, Sydney 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 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. * * @author Michael Diponio (mdiponio) * @date 8th April 2010 */ package au.edu.uts.eng.remotelabs.schedserver.session.impl; import java.util.Date; import java.util.List; import org.hibernate.Criteria; import org.hibernate.HibernateException; import org.hibernate.criterion.Restrictions; import au.edu.uts.eng.remotelabs.schedserver.bookings.BookingEngineService; import au.edu.uts.eng.remotelabs.schedserver.dataaccess.DataAccessActivator; import au.edu.uts.eng.remotelabs.schedserver.dataaccess.entities.ResourcePermission; import au.edu.uts.eng.remotelabs.schedserver.dataaccess.entities.Session; import au.edu.uts.eng.remotelabs.schedserver.logger.Logger; import au.edu.uts.eng.remotelabs.schedserver.logger.LoggerActivator; import au.edu.uts.eng.remotelabs.schedserver.queuer.QueueInfo; import au.edu.uts.eng.remotelabs.schedserver.rigoperations.RigNotifier; import au.edu.uts.eng.remotelabs.schedserver.rigoperations.RigReleaser; import au.edu.uts.eng.remotelabs.schedserver.session.SessionActivator; /** * Either expires or extends the time of all sessions which are close to * the session duration duration. */ public class SessionExpiryChecker implements Runnable { /** Minimum extension duration. */ public static final int TIME_EXT = 300; /** Logger. */ private Logger logger; /** Flag to specify if this is a test run. */ private boolean notTest = true; public SessionExpiryChecker() { this.logger = LoggerActivator.getLogger(); } @SuppressWarnings("unchecked") @Override public void run() { org.hibernate.Session db = null; try { if ((db = DataAccessActivator.getNewSession()) == null) { this.logger.warn("Unable to obtain a database session, for rig session status checker. Ensure the " + "SchedulingServer-DataAccess bundle is installed and active."); return; } boolean kicked = false; Criteria query = db.createCriteria(Session.class); query.add(Restrictions.eq("active", Boolean.TRUE)) .add(Restrictions.isNotNull("assignmentTime")); Date now = new Date(); List<Session> sessions = query.list(); for (Session ses : sessions) { ResourcePermission perm = ses.getResourcePermission(); int remaining = ses.getDuration() + // The session time (perm.getAllowedExtensions() - ses.getExtensions()) * perm.getExtensionDuration() - // Extension time Math.round((System.currentTimeMillis() - ses.getAssignmentTime().getTime()) / 1000); // In session time int extension = perm.getSessionDuration() - ses.getDuration() >= TIME_EXT ? TIME_EXT : perm.getExtensionDuration(); /****************************************************************** * For sessions that have been marked for termination, terminate * * those that have no more remaining time. * ******************************************************************/ if (ses.isInGrace()) { if (remaining <= 0) { ses.setActive(false); ses.setRemovalTime(now); db.beginTransaction(); db.flush(); db.getTransaction().commit(); this.logger.info("Terminating session for " + ses.getUserNamespace() + ':' + ses.getUserName() + " on " + ses.getAssignedRigName() + " because it is expired and the grace period has elapsed."); if (this.notTest) new RigReleaser().release(ses, db); } } /****************************************************************** * For sessions with remaining time less than the grace duration: * * 1) If the session has no remaining extensions, mark it for * * termination. * * 2) Else, if the session rig is queued, mark it for * * termination. * * 3) Else, extend the sessions time. * ******************************************************************/ else if (remaining < ses.getRig().getRigType().getLogoffGraceDuration()) { BookingEngineService service; /* Need to make a decision whether to extend time or set for termination. */ if (ses.getExtensions() <= 0 && ses.getDuration() >= perm.getSessionDuration()) { this.logger.info("Session for " + ses.getUserNamespace() + ':' + ses.getUserName() + " on " + "rig " + ses.getAssignedRigName() + " is expired and cannot be extended. Marking " + "session for expiry and giving a grace period."); ses.setInGrace(true); ses.setRemovalReason("No more session time extensions."); db.beginTransaction(); db.flush(); db.getTransaction().commit(); /* Notification warning. */ if (this.notTest) new RigNotifier().notify("Your session will expire in " + remaining + " seconds. " + "Please finish and exit.", ses, db); } else if (QueueInfo.isQueued(ses.getRig(), db) || ((service = SessionActivator.getBookingService()) != null && !service.extendQueuedSession(ses.getRig(), ses, extension, db))) { this.logger.info("Session for " + ses.getUserNamespace() + ':' + ses.getUserName() + " on " + "rig " + ses.getAssignedRigName() + " is expired and the rig is queued or booked. " + "Marking session for expiry and giving a grace period."); ses.setInGrace(true); ses.setRemovalReason("Rig is queued or booked."); db.beginTransaction(); db.flush(); db.getTransaction().commit(); /* Notification warning. */ if (this.notTest) new RigNotifier().notify("Your session will end in " + remaining + " seconds. " + "After this you be removed, so please logoff.", ses, db); } else { this.logger.info("Session for " + ses.getUserNamespace() + ':' + ses.getUserName() + " on " + "rig " + ses.getAssignedRigName() + " is expired and is having its session time " + "extended by " + extension + " seconds."); if (perm.getSessionDuration() - ses.getDuration() >= TIME_EXT) { ses.setDuration(ses.getDuration() + extension); } else { ses.setExtensions((short)(ses.getExtensions() - 1)); } db.beginTransaction(); db.flush(); db.getTransaction().commit(); } } /****************************************************************** * For sessions created with a user class that can be kicked off, * * if the rig is queued, the user is kicked off immediately. * ******************************************************************/ /* DODGY The 'kicked' flag is to only allow a single kick per * pass. This is allow time for the rig to be released and take the * queued session. This is a hack at best, but should be addressed * by a released - cleaning up meta state. */ else if (!kicked && QueueInfo.isQueued(ses.getRig(), db) && perm.getUserClass().isKickable()) { kicked = true; /* No grace is being given. */ this.logger.info("A kickable user is using a rig that is queued for, so they are being removed."); ses.setActive(false); ses.setRemovalTime(now); ses.setRemovalReason("Resource was queued and user was kickable."); db.beginTransaction(); db.flush(); db.getTransaction().commit(); if (this.notTest) new RigReleaser().release(ses, db); } /****************************************************************** * Finally, for sessions with time still remaining, check * * session activity timeout - if it is not ignored and is ready * * for use. * ******************************************************************/ else if (ses.isReady() && ses.getResourcePermission().isActivityDetected() && (System.currentTimeMillis() - ses.getActivityLastUpdated().getTime()) / 1000 > perm.getSessionActivityTimeout()) { /* Check activity. */ if (this.notTest) new SessionIdleKicker().kickIfIdle(ses, db); } } } catch (HibernateException hex) { this.logger.error("Failed to query database to expired sessions (Exception: " + hex.getClass().getName() + ", Message:" + hex.getMessage() + ")."); if (db != null && db.getTransaction() != null) { try { db.getTransaction().rollback(); } catch (HibernateException ex) { this.logger.error("Exception rolling back session expiry transaction (Exception: " + ex.getClass().getName() + "," + " Message: " + ex.getMessage() + ")."); } } } catch (Throwable thr) { this.logger.error("Caught unchecked exception in session expirty checker. Exception: " + thr.getClass() + ", message: " + thr.getMessage() + '.'); } finally { try { if (db != null) db.close(); } catch (HibernateException ex) { this.logger.error("Exception cleaning up database session (Exception: " + ex.getClass().getName() + "," + " Message: " + ex.getMessage() + ")."); } } } }
Session/src/au/edu/uts/eng/remotelabs/schedserver/session/impl/SessionExpiryChecker.java
/** * SAHARA Scheduling Server * * Schedules and assigns local laboratory rigs. * * @license See LICENSE in the top level directory for complete license terms. * * Copyright (c) 2010, University of Technology, Sydney * 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 University of Technology, Sydney 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 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. * * @author Michael Diponio (mdiponio) * @date 8th April 2010 */ package au.edu.uts.eng.remotelabs.schedserver.session.impl; import java.util.Date; import java.util.List; import org.hibernate.Criteria; import org.hibernate.HibernateException; import org.hibernate.criterion.Restrictions; import au.edu.uts.eng.remotelabs.schedserver.bookings.BookingEngineService; import au.edu.uts.eng.remotelabs.schedserver.dataaccess.DataAccessActivator; import au.edu.uts.eng.remotelabs.schedserver.dataaccess.entities.ResourcePermission; import au.edu.uts.eng.remotelabs.schedserver.dataaccess.entities.Session; import au.edu.uts.eng.remotelabs.schedserver.logger.Logger; import au.edu.uts.eng.remotelabs.schedserver.logger.LoggerActivator; import au.edu.uts.eng.remotelabs.schedserver.queuer.QueueInfo; import au.edu.uts.eng.remotelabs.schedserver.rigoperations.RigNotifier; import au.edu.uts.eng.remotelabs.schedserver.rigoperations.RigReleaser; import au.edu.uts.eng.remotelabs.schedserver.session.SessionActivator; /** * Either expires or extends the time of all sessions which are close to * the session duration duration. */ public class SessionExpiryChecker implements Runnable { /** Minimum extension duration. */ public static final int TIME_EXT = 300; /** Logger. */ private Logger logger; /** Flag to specify if this is a test run. */ private boolean notTest = true; public SessionExpiryChecker() { this.logger = LoggerActivator.getLogger(); } @SuppressWarnings("unchecked") @Override public void run() { org.hibernate.Session db = null; try { if ((db = DataAccessActivator.getNewSession()) == null) { this.logger.warn("Unable to obtain a database session, for rig session status checker. Ensure the " + "SchedulingServer-DataAccess bundle is installed and active."); return; } boolean kicked = false; Criteria query = db.createCriteria(Session.class); query.add(Restrictions.eq("active", Boolean.TRUE)) .add(Restrictions.isNotNull("assignmentTime")); Date now = new Date(); List<Session> sessions = query.list(); for (Session ses : sessions) { ResourcePermission perm = ses.getResourcePermission(); int remaining = ses.getDuration() + // The session time (perm.getAllowedExtensions() - ses.getExtensions()) * perm.getExtensionDuration() - // Extension time Math.round((System.currentTimeMillis() - ses.getAssignmentTime().getTime()) / 1000); // In session time int extension = perm.getSessionDuration() - ses.getDuration() >= TIME_EXT ? TIME_EXT : perm.getExtensionDuration(); /****************************************************************** * For sessions that have been marked for termination, terminate * * those that have no more remaining time. * ******************************************************************/ if (ses.isInGrace()) { if (remaining <= 0) { ses.setActive(false); ses.setRemovalTime(now); db.beginTransaction(); db.flush(); db.getTransaction().commit(); this.logger.info("Terminating session for " + ses.getUserNamespace() + ':' + ses.getUserName() + " on " + ses.getAssignedRigName() + " because it is expired and the grace period has elapsed."); if (this.notTest) new RigReleaser().release(ses, db); } } /****************************************************************** * For sessions with remaining time less than the grace duration: * * 1) If the session has no remaining extensions, mark it for * * termination. * * 2) Else, if the session rig is queued, mark it for * * termination. * * 3) Else, extend the sessions time. * ******************************************************************/ else if (remaining < ses.getRig().getRigType().getLogoffGraceDuration()) { BookingEngineService service; /* Need to make a decision whether to extend time or set for termination. */ if (ses.getExtensions() == 0 && ses.getDuration() == perm.getSessionDuration()) { this.logger.info("Session for " + ses.getUserNamespace() + ':' + ses.getUserName() + " on " + "rig " + ses.getAssignedRigName() + " is expired and cannot be extended. Marking " + "session for expiry and giving a grace period."); ses.setInGrace(true); ses.setRemovalReason("No more session time extensions."); db.beginTransaction(); db.flush(); db.getTransaction().commit(); /* Notification warning. */ if (this.notTest) new RigNotifier().notify("Your session will expire in " + remaining + " seconds. " + "Please finish and exit.", ses, db); } else if (QueueInfo.isQueued(ses.getRig(), db) || ((service = SessionActivator.getBookingService()) != null && !service.extendQueuedSession(ses.getRig(), ses, extension, db))) { this.logger.info("Session for " + ses.getUserNamespace() + ':' + ses.getUserName() + " on " + "rig " + ses.getAssignedRigName() + " is expired and the rig is queued or booked. " + "Marking session for expiry and giving a grace period."); ses.setInGrace(true); ses.setRemovalReason("Rig is queued or booked."); db.beginTransaction(); db.flush(); db.getTransaction().commit(); /* Notification warning. */ if (this.notTest) new RigNotifier().notify("Your session will end in " + remaining + " seconds. " + "After this you be removed, so please logoff.", ses, db); } else { this.logger.info("Session for " + ses.getUserNamespace() + ':' + ses.getUserName() + " on " + "rig " + ses.getAssignedRigName() + " is expired and is having its session time " + "extended by " + extension + " seconds."); if (perm.getSessionDuration() - ses.getDuration() >= TIME_EXT) { ses.setDuration(ses.getDuration() + extension); } else { ses.setExtensions((short)(ses.getExtensions() - 1)); } db.beginTransaction(); db.flush(); db.getTransaction().commit(); } } /****************************************************************** * For sessions created with a user class that can be kicked off, * * if the rig is queued, the user is kicked off immediately. * ******************************************************************/ /* DODGY The 'kicked' flag is to only allow a single kick per * pass. This is allow time for the rig to be released and take the * queued session. This is a hack at best, but should be addressed * by a released - cleaning up meta state. */ else if (!kicked && QueueInfo.isQueued(ses.getRig(), db) && perm.getUserClass().isKickable()) { kicked = true; /* No grace is being given. */ this.logger.info("A kickable user is using a rig that is queued for, so they are being removed."); ses.setActive(false); ses.setRemovalTime(now); ses.setRemovalReason("Resource was queued and user was kickable."); db.beginTransaction(); db.flush(); db.getTransaction().commit(); if (this.notTest) new RigReleaser().release(ses, db); } /****************************************************************** * Finally, for sessions with time still remaining, check * * session activity timeout - if it is not ignored and is ready * * for use. * ******************************************************************/ else if (ses.isReady() && ses.getResourcePermission().isActivityDetected() && (System.currentTimeMillis() - ses.getActivityLastUpdated().getTime()) / 1000 > perm.getSessionActivityTimeout()) { /* Check activity. */ if (this.notTest) new SessionIdleKicker().kickIfIdle(ses, db); } } } catch (HibernateException hex) { this.logger.error("Failed to query database to expired sessions (Exception: " + hex.getClass().getName() + ", Message:" + hex.getMessage() + ")."); if (db != null && db.getTransaction() != null) { try { db.getTransaction().rollback(); } catch (HibernateException ex) { this.logger.error("Exception rolling back session expiry transaction (Exception: " + ex.getClass().getName() + "," + " Message: " + ex.getMessage() + ")."); } } } catch (Throwable thr) { this.logger.error("Caught unchecked exception in session expirty checker. Exception: " + thr.getClass() + ", message: " + thr.getMessage() + '.'); } finally { try { if (db != null) db.close(); } catch (HibernateException ex) { this.logger.error("Exception cleaning up database session (Exception: " + ex.getClass().getName() + "," + " Message: " + ex.getMessage() + ")."); } } } }
Fix for bug#298 git-svn-id: 3da949d34a212f3817abd22d3ea35103e5c5a817@2472 7ee224fa-57ca-4419-87f9-1f4314938d77
Session/src/au/edu/uts/eng/remotelabs/schedserver/session/impl/SessionExpiryChecker.java
Fix for bug#298
<ide><path>ession/src/au/edu/uts/eng/remotelabs/schedserver/session/impl/SessionExpiryChecker.java <ide> BookingEngineService service; <ide> <ide> /* Need to make a decision whether to extend time or set for termination. */ <del> if (ses.getExtensions() == 0 && ses.getDuration() == perm.getSessionDuration()) <add> if (ses.getExtensions() <= 0 && ses.getDuration() >= perm.getSessionDuration()) <ide> { <ide> this.logger.info("Session for " + ses.getUserNamespace() + ':' + ses.getUserName() + " on " + <ide> "rig " + ses.getAssignedRigName() + " is expired and cannot be extended. Marking " +
JavaScript
mit
cdf09febb0e0ac2edc5b2a07492c23cb5a337510
0
ivyjs/framework
let HttpHash = require('http-hash'), ControllerDispatcher = require('./ControllerDispatcher'); class Router { constructor() { this.GETRoutes = HttpHash(); this.POSTRoutes = HttpHash(); this.PUTRoutes = HttpHash(); this.DELETERoutes = HttpHash(); this.routesList = []; } /** * Creates a binding for a new route. * * @param method * @param routeUrl * @param binding * @param options */ _registerRoute(method, routeUrl, binding, options) { this[method + 'Routes'].set(routeUrl, {closure: binding, options: options}); this.routesList.push({ method: method, path: routeUrl, options: options, closure: typeof binding === 'function' ? 'Function' : binding }); } /** * Creates a get route. * * @param routeUrl * @param binding * @param options * @return {*} */ get(routeUrl, binding, options) { return this._registerRoute('GET', routeUrl, binding, options); } /** * Creates a post route. * * @param routeUrl * @param binding * @param options * @return {*} */ post(routeUrl, binding, options) { return this._registerRoute('POST', routeUrl, binding, options); } /** * Creates a put route. * * @param routeUrl * @param binding * @param options * @return {*} */ put(routeUrl, binding, options) { return this._registerRoute('PUT', routeUrl, binding, options); } /** * Creates a delete route. * * @param routeUrl * @param binding * @param options * @return {*} */ delete(routeUrl, binding, options) { return this._registerRoute('DELETE', routeUrl, binding, options); } /** * Resolve a given route. * * @param request * @param response */ resolveRoute(request, response) { let route = this.findMatchingRoute(request.method, request.url); if (route.handler) return Router.goThroughMiddleware(route, request, response); response.writeHead(404); return response.end('Route not found'); } /** * Find the matching route. * * @param method * @param route */ findMatchingRoute(method, route) { return this[method + 'Routes'].get(route); } /** * Pipe data through the middlewares. * * @param route * @param request * @param response * @return {*} */ static goThroughMiddleware(route, request, response) { if (!Router.hasMiddlewareOption(route)) return Router.dispatchRoute(route, response); let middlewareContainer = use('Ivy/MiddlewareContainer'), Pipe = use('Ivy/Pipe'); let middlewaresList = middlewareContainer.parse(route.handler.options.middleware); return Pipe.data({route: route, request: request, response: response}) .through(middlewaresList) .catch((err) => { console.error(err); response.writeHead(500); return response.end('Error piping through middleware. ' + err); }).then((data) => { return Router.dispatchRoute(data.route, data.response); }); } /** * Check if route has middleware to go through. * * @param route * @return {string|string} */ static hasMiddlewareOption(route) { return route.handler.options && route.handler.options.middleware; } /** * Dispatch a request to the handler. * * @param route * @param response * @return {*} */ static dispatchRoute(route, response) { let handler = route.handler.closure; let handlerResponse = typeof handler === 'string' ? ControllerDispatcher.dispatchRoute(handler, route.params) : handler(route.params); return Router.respondToRoute(handlerResponse, response); } /** * Make a response to the request. * * @param handlerAnswer * @param response * @return {*} */ static respondToRoute(handlerAnswer, response) { if (!handlerAnswer) return response.end(); if (typeof handlerAnswer === "string") return response.end(handlerAnswer); if (handlerAnswer['toString'] && typeof handlerAnswer !== 'object') return response.end(handlerAnswer.toString()); try { response.setHeader('content-type', 'application/json'); return response.end(JSON.stringify(handlerAnswer, null, 4)); } catch (e) { console.error('Error while trying to stringify JSON object. ' + e); response.writeHead(500); return response.end('Server error.'); } } /** * Creates a new resource. * * @param resourceName * @param controllerHandler * @param options */ resource(resourceName, controllerHandler, options = {}) { this.get(resourceName, `${controllerHandler}@index`, options); this.get(`${resourceName}/:id`, `${controllerHandler}@show`, options); this.post(`${resourceName}`, `${controllerHandler}@create`, options); this.put(`${resourceName}/:id`, `${controllerHandler}@update`, options); this.delete(`${resourceName}/:id`, `${controllerHandler}@remove`, options); } } module.exports = Router;
src/Router/index.js
let HttpHash = require('http-hash'), ControllerDispatcher = require('./ControllerDispatcher'); class Router { constructor() { this.GETRoutes = HttpHash(); this.POSTRoutes = HttpHash(); this.PUTRoutes = HttpHash(); this.DELETERoutes = HttpHash(); this.routesList = []; } /** * Creates a binding for a new route. * * @param method * @param routeUrl * @param binding * @param options */ _registerRoute(method, routeUrl, binding, options) { this[method + 'Routes'].set(routeUrl, {closure: binding, options: options}); this.routesList.push({ method: method, path: routeUrl, options: options, closure: typeof binding === 'function' ? 'Function' : binding }); } /** * Creates a get route. * * @param routeUrl * @param binding * @param options * @return {*} */ get(routeUrl, binding, options) { return this._registerRoute('GET', routeUrl, binding, options); } /** * Creates a post route. * * @param routeUrl * @param binding * @param options * @return {*} */ post(routeUrl, binding, options) { return this._registerRoute('POST', routeUrl, binding, options); } /** * Creates a put route. * * @param routeUrl * @param binding * @param options * @return {*} */ put(routeUrl, binding, options) { return this._registerRoute('PUT', routeUrl, binding, options); } /** * Creates a delete route. * * @param routeUrl * @param binding * @param options * @return {*} */ delete(routeUrl, binding, options) { return this._registerRoute('DELETE', routeUrl, binding, options); } /** * Resolve a given route. * * @param request * @param response */ resolveRoute(request, response) { let route = this.findMatchingRoute(request.method, request.url); if (route.handler) return Router.goThroughMiddleware(route, request, response); response.writeHead(404); return response.end('Route not found'); } /** * Find the matching route. * * @param method * @param route */ findMatchingRoute(method, route) { return this[method + 'Routes'].get(route); } /** * Pipe data through the middlewares. * * @param route * @param request * @param response * @return {*} */ static goThroughMiddleware(route, request, response) { if (!Router.hasMiddlewareOption(route)) return Router.dispatchRoute(route, response); let middlewareContainer = use('Ivy/MiddlewareContainer'), Pipe = use('Ivy/Pipe'); let middlewaresList = middlewareContainer.parse(route.handler.options.middleware); return Pipe.data({route: route, request: request, response: response}) .through(middlewaresList) .catch((err) => { console.error(err); response.writeHead(500); return response.end('Error piping through middleware. ' + err); }).then((data) => { return Router.dispatchRoute(data.route, data.response); }); } /** * Check if route has middleware to go through. * * @param route * @return {string|string} */ static hasMiddlewareOption(route) { return route.handler.options && route.handler.options.middleware; } /** * Dispatch a request to the handler. * * @param route * @param response * @return {*} */ static dispatchRoute(route, response) { let handler = route.handler.closure; let handlerResponse = typeof handler === 'string' ? ControllerDispatcher.dispatchRoute(handler, route.params) : handler(route.params); return Router.respondToRoute(handlerResponse, response); } /** * Make a response to the request. * * @param handlerAnswer * @param response * @return {*} */ static respondToRoute(handlerAnswer, response) { if (!handlerAnswer) return response.end(); if (typeof handlerAnswer === "string") return response.end(handlerAnswer); if (handlerAnswer['toString'] && typeof handlerAnswer !== 'object') return response.end(handlerAnswer.toString()); try { response.setHeader('content-type', 'application/json'); return response.end(JSON.stringify(handlerAnswer, null, 4)); } catch (e) { console.error('Error while trying to stringify JSON object. ' + e); response.writeHead(500); return response.end('Server error.'); } } /** * Creates a new resource. * * @param resourceName * @param controllerHandler */ resource(resourceName, controllerHandler) { this.get(resourceName, `${controllerHandler}@index`); this.get(`${resourceName}/:id`, `${controllerHandler}@show`); this.post(`${resourceName}`, `${controllerHandler}@create`); this.put(`${resourceName}/:id`, `${controllerHandler}@update`); this.delete(`${resourceName}/:id`, `${controllerHandler}@remove`); } } module.exports = Router;
added route options for resource
src/Router/index.js
added route options for resource
<ide><path>rc/Router/index.js <ide> * <ide> * @param resourceName <ide> * @param controllerHandler <del> */ <del> resource(resourceName, controllerHandler) { <del> this.get(resourceName, `${controllerHandler}@index`); <del> this.get(`${resourceName}/:id`, `${controllerHandler}@show`); <del> this.post(`${resourceName}`, `${controllerHandler}@create`); <del> this.put(`${resourceName}/:id`, `${controllerHandler}@update`); <del> this.delete(`${resourceName}/:id`, `${controllerHandler}@remove`); <add> * @param options <add> */ <add> resource(resourceName, controllerHandler, options = {}) { <add> this.get(resourceName, `${controllerHandler}@index`, options); <add> this.get(`${resourceName}/:id`, `${controllerHandler}@show`, options); <add> this.post(`${resourceName}`, `${controllerHandler}@create`, options); <add> this.put(`${resourceName}/:id`, `${controllerHandler}@update`, options); <add> this.delete(`${resourceName}/:id`, `${controllerHandler}@remove`, options); <ide> } <ide> } <ide>
Java
apache-2.0
a8f56524142bebcaf33e7583b84fd2d8d86ce32c
0
shybovycha/buck,facebook/buck,shs96c/buck,brettwooldridge/buck,zpao/buck,romanoid/buck,shs96c/buck,clonetwin26/buck,ilya-klyuchnikov/buck,rmaz/buck,ilya-klyuchnikov/buck,rmaz/buck,nguyentruongtho/buck,shs96c/buck,brettwooldridge/buck,JoelMarcey/buck,shs96c/buck,romanoid/buck,LegNeato/buck,ilya-klyuchnikov/buck,romanoid/buck,nguyentruongtho/buck,Addepar/buck,JoelMarcey/buck,ilya-klyuchnikov/buck,brettwooldridge/buck,rmaz/buck,LegNeato/buck,clonetwin26/buck,JoelMarcey/buck,shs96c/buck,romanoid/buck,Addepar/buck,facebook/buck,Addepar/buck,shybovycha/buck,romanoid/buck,Addepar/buck,shs96c/buck,LegNeato/buck,zpao/buck,rmaz/buck,SeleniumHQ/buck,clonetwin26/buck,shybovycha/buck,ilya-klyuchnikov/buck,romanoid/buck,zpao/buck,LegNeato/buck,clonetwin26/buck,clonetwin26/buck,brettwooldridge/buck,rmaz/buck,nguyentruongtho/buck,ilya-klyuchnikov/buck,shybovycha/buck,SeleniumHQ/buck,rmaz/buck,kageiit/buck,SeleniumHQ/buck,SeleniumHQ/buck,Addepar/buck,clonetwin26/buck,romanoid/buck,LegNeato/buck,JoelMarcey/buck,zpao/buck,JoelMarcey/buck,nguyentruongtho/buck,romanoid/buck,shs96c/buck,ilya-klyuchnikov/buck,JoelMarcey/buck,Addepar/buck,zpao/buck,clonetwin26/buck,brettwooldridge/buck,SeleniumHQ/buck,clonetwin26/buck,romanoid/buck,brettwooldridge/buck,rmaz/buck,SeleniumHQ/buck,kageiit/buck,kageiit/buck,rmaz/buck,brettwooldridge/buck,facebook/buck,JoelMarcey/buck,Addepar/buck,facebook/buck,SeleniumHQ/buck,kageiit/buck,JoelMarcey/buck,shybovycha/buck,shs96c/buck,romanoid/buck,clonetwin26/buck,shybovycha/buck,SeleniumHQ/buck,LegNeato/buck,shybovycha/buck,JoelMarcey/buck,shs96c/buck,SeleniumHQ/buck,LegNeato/buck,romanoid/buck,shs96c/buck,Addepar/buck,zpao/buck,ilya-klyuchnikov/buck,Addepar/buck,shybovycha/buck,kageiit/buck,clonetwin26/buck,rmaz/buck,JoelMarcey/buck,brettwooldridge/buck,shs96c/buck,shybovycha/buck,shs96c/buck,brettwooldridge/buck,ilya-klyuchnikov/buck,facebook/buck,romanoid/buck,nguyentruongtho/buck,shs96c/buck,Addepar/buck,shybovycha/buck,brettwooldridge/buck,Addepar/buck,zpao/buck,SeleniumHQ/buck,clonetwin26/buck,Addepar/buck,brettwooldridge/buck,LegNeato/buck,shybovycha/buck,JoelMarcey/buck,ilya-klyuchnikov/buck,rmaz/buck,facebook/buck,brettwooldridge/buck,Addepar/buck,rmaz/buck,LegNeato/buck,ilya-klyuchnikov/buck,rmaz/buck,clonetwin26/buck,rmaz/buck,SeleniumHQ/buck,LegNeato/buck,nguyentruongtho/buck,nguyentruongtho/buck,kageiit/buck,SeleniumHQ/buck,kageiit/buck,romanoid/buck,clonetwin26/buck,shybovycha/buck,ilya-klyuchnikov/buck,SeleniumHQ/buck,facebook/buck,ilya-klyuchnikov/buck,brettwooldridge/buck,LegNeato/buck,JoelMarcey/buck,LegNeato/buck,shybovycha/buck,LegNeato/buck,JoelMarcey/buck
/* * Copyright 2012-present Facebook, Inc. * * 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.facebook.buck.android; import com.facebook.buck.android.packageable.AndroidPackageable; import com.facebook.buck.io.ProjectFilesystem; import com.facebook.buck.jvm.java.ConfiguredCompilerFactory; import com.facebook.buck.jvm.java.DefaultJavaLibrary; import com.facebook.buck.jvm.java.DefaultJavaLibraryBuilder; import com.facebook.buck.jvm.java.JarBuildStepsFactory; import com.facebook.buck.jvm.java.JavaBuckConfig; import com.facebook.buck.jvm.java.JavaLibraryDescription; import com.facebook.buck.jvm.java.JavacOptions; import com.facebook.buck.model.BuildTarget; import com.facebook.buck.rules.AddToRuleKey; import com.facebook.buck.rules.BuildRule; import com.facebook.buck.rules.BuildRuleParams; import com.facebook.buck.rules.BuildRuleResolver; import com.facebook.buck.rules.CellPathResolver; import com.facebook.buck.rules.SourcePath; import com.facebook.buck.rules.SourcePathResolver; import com.facebook.buck.rules.TargetGraph; import com.facebook.buck.util.DependencyMode; import com.facebook.buck.util.RichStream; import com.google.common.annotations.VisibleForTesting; import com.google.common.base.Preconditions; import com.google.common.collect.ImmutableSortedSet; import com.google.common.collect.Iterables; import com.google.common.collect.Ordering; import java.util.Optional; import java.util.SortedSet; import javax.annotation.Nullable; public class AndroidLibrary extends DefaultJavaLibrary implements AndroidPackageable { /** * Manifest to associate with this rule. Ultimately, this will be used with the upcoming manifest * generation logic. */ @AddToRuleKey private final Optional<SourcePath> manifestFile; public static Builder builder( TargetGraph targetGraph, BuildTarget buildTarget, ProjectFilesystem projectFilesystem, BuildRuleParams params, BuildRuleResolver buildRuleResolver, CellPathResolver cellRoots, JavaBuckConfig javaBuckConfig, JavacOptions javacOptions, AndroidLibraryDescription.CoreArg args, ConfiguredCompilerFactory compilerFactory) { return new Builder( targetGraph, buildTarget, projectFilesystem, params, buildRuleResolver, cellRoots, javaBuckConfig, javacOptions, args, compilerFactory); } @VisibleForTesting AndroidLibrary( BuildTarget buildTarget, ProjectFilesystem projectFilesystem, ImmutableSortedSet<BuildRule> buildDeps, SourcePathResolver resolver, JarBuildStepsFactory jarBuildStepsFactory, Optional<SourcePath> proguardConfig, SortedSet<BuildRule> fullJarDeclaredDeps, ImmutableSortedSet<BuildRule> fullJarExportedDeps, ImmutableSortedSet<BuildRule> fullJarProvidedDeps, @Nullable BuildTarget abiJar, Optional<String> mavenCoords, Optional<SourcePath> manifestFile, ImmutableSortedSet<BuildTarget> tests, boolean requiredForSourceAbi) { super( buildTarget, projectFilesystem, buildDeps, resolver, jarBuildStepsFactory, proguardConfig, fullJarDeclaredDeps, fullJarExportedDeps, fullJarProvidedDeps, abiJar, mavenCoords, tests, requiredForSourceAbi); this.manifestFile = manifestFile; } public Optional<SourcePath> getManifestFile() { return manifestFile; } public static class Builder extends DefaultJavaLibraryBuilder { private final AndroidLibraryDescription.CoreArg args; private Optional<SourcePath> androidManifest = Optional.empty(); protected Builder( TargetGraph targetGraph, BuildTarget buildTarget, ProjectFilesystem projectFilesystem, BuildRuleParams params, BuildRuleResolver buildRuleResolver, CellPathResolver cellRoots, JavaBuckConfig javaBuckConfig, JavacOptions javacOptions, AndroidLibraryDescription.CoreArg args, ConfiguredCompilerFactory compilerFactory) { super( targetGraph, buildTarget, projectFilesystem, params, buildRuleResolver, cellRoots, compilerFactory, javaBuckConfig); this.args = args; setJavacOptions(javacOptions); setArgs(args); } @Override public DefaultJavaLibraryBuilder setArgs(JavaLibraryDescription.CoreArg args) { super.setArgs(args); AndroidLibraryDescription.CoreArg androidArgs = (AndroidLibraryDescription.CoreArg) args; return setManifestFile(androidArgs.getManifest()); } @Override public DefaultJavaLibraryBuilder setManifestFile(Optional<SourcePath> manifestFile) { androidManifest = manifestFile; return this; } public DummyRDotJava buildDummyRDotJava() { return newHelper().buildDummyRDotJava(); } public Optional<DummyRDotJava> getDummyRDotJava() { return newHelper().getDummyRDotJava(); } @Override protected BuilderHelper newHelper() { return new BuilderHelper(); } protected class BuilderHelper extends DefaultJavaLibraryBuilder.BuilderHelper { @Nullable private AndroidLibraryGraphEnhancer graphEnhancer; @Override protected DefaultJavaLibrary build() { AndroidLibrary result = new AndroidLibrary( libraryTarget, projectFilesystem, getFinalBuildDeps(), sourcePathResolver, getJarBuildStepsFactory(), proguardConfig, getFinalFullJarDeclaredDeps(), Preconditions.checkNotNull(deps).getExportedDeps(), Preconditions.checkNotNull(deps).getProvidedDeps(), getAbiJar(), mavenCoords, androidManifest, tests, getRequiredForSourceAbi()); return result; } protected DummyRDotJava buildDummyRDotJava() { return getGraphEnhancer().getBuildableForAndroidResources(buildRuleResolver, true).get(); } protected Optional<DummyRDotJava> getDummyRDotJava() { return getGraphEnhancer().getBuildableForAndroidResources(buildRuleResolver, false); } protected AndroidLibraryGraphEnhancer getGraphEnhancer() { if (graphEnhancer == null) { graphEnhancer = new AndroidLibraryGraphEnhancer( libraryTarget, projectFilesystem, ImmutableSortedSet.copyOf( Iterables.concat( Preconditions.checkNotNull(deps).getDeps(), Preconditions.checkNotNull(deps).getProvidedDeps())), getJavac(), getJavacOptions(), DependencyMode.FIRST_ORDER, /* forceFinalResourceIds */ false, args.getResourceUnionPackage(), args.getFinalRName(), false); } return graphEnhancer; } @Override protected ImmutableSortedSet<BuildRule> buildFinalFullJarDeclaredDeps() { return RichStream.from(super.buildFinalFullJarDeclaredDeps()) .concat(RichStream.from(getDummyRDotJava())) .toImmutableSortedSet(Ordering.natural()); } } } }
src/com/facebook/buck/android/AndroidLibrary.java
/* * Copyright 2012-present Facebook, Inc. * * 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.facebook.buck.android; import com.facebook.buck.android.packageable.AndroidPackageable; import com.facebook.buck.io.ProjectFilesystem; import com.facebook.buck.jvm.java.ConfiguredCompilerFactory; import com.facebook.buck.jvm.java.DefaultJavaLibrary; import com.facebook.buck.jvm.java.DefaultJavaLibraryBuilder; import com.facebook.buck.jvm.java.JarBuildStepsFactory; import com.facebook.buck.jvm.java.JavaBuckConfig; import com.facebook.buck.jvm.java.JavaLibraryDescription; import com.facebook.buck.jvm.java.JavacOptions; import com.facebook.buck.model.BuildTarget; import com.facebook.buck.rules.AddToRuleKey; import com.facebook.buck.rules.BuildRule; import com.facebook.buck.rules.BuildRuleParams; import com.facebook.buck.rules.BuildRuleResolver; import com.facebook.buck.rules.CellPathResolver; import com.facebook.buck.rules.SourcePath; import com.facebook.buck.rules.SourcePathResolver; import com.facebook.buck.rules.TargetGraph; import com.facebook.buck.util.DependencyMode; import com.facebook.buck.util.RichStream; import com.google.common.annotations.VisibleForTesting; import com.google.common.base.Preconditions; import com.google.common.collect.ImmutableSortedSet; import com.google.common.collect.Iterables; import com.google.common.collect.Ordering; import java.util.Optional; import java.util.SortedSet; import javax.annotation.Nullable; public class AndroidLibrary extends DefaultJavaLibrary implements AndroidPackageable { /** * Manifest to associate with this rule. Ultimately, this will be used with the upcoming manifest * generation logic. */ @AddToRuleKey private final Optional<SourcePath> manifestFile; public static Builder builder( TargetGraph targetGraph, BuildTarget buildTarget, ProjectFilesystem projectFilesystem, BuildRuleParams params, BuildRuleResolver buildRuleResolver, CellPathResolver cellRoots, JavaBuckConfig javaBuckConfig, JavacOptions javacOptions, AndroidLibraryDescription.CoreArg args, ConfiguredCompilerFactory compilerFactory) { return new Builder( targetGraph, buildTarget, projectFilesystem, params, buildRuleResolver, cellRoots, javaBuckConfig, javacOptions, args, compilerFactory); } @VisibleForTesting AndroidLibrary( BuildTarget buildTarget, ProjectFilesystem projectFilesystem, ImmutableSortedSet<BuildRule> buildDeps, SourcePathResolver resolver, JarBuildStepsFactory jarBuildStepsFactory, Optional<SourcePath> proguardConfig, SortedSet<BuildRule> fullJarDeclaredDeps, ImmutableSortedSet<BuildRule> fullJarExportedDeps, ImmutableSortedSet<BuildRule> fullJarProvidedDeps, @Nullable BuildTarget abiJar, Optional<String> mavenCoords, Optional<SourcePath> manifestFile, ImmutableSortedSet<BuildTarget> tests, boolean requiredForSourceAbi) { super( buildTarget, projectFilesystem, buildDeps, resolver, jarBuildStepsFactory, proguardConfig, fullJarDeclaredDeps, fullJarExportedDeps, fullJarProvidedDeps, abiJar, mavenCoords, tests, requiredForSourceAbi); this.manifestFile = manifestFile; } public Optional<SourcePath> getManifestFile() { return manifestFile; } public static class Builder extends DefaultJavaLibraryBuilder { private final AndroidLibraryDescription.CoreArg args; private Optional<SourcePath> androidManifest = Optional.empty(); protected Builder( TargetGraph targetGraph, BuildTarget buildTarget, ProjectFilesystem projectFilesystem, BuildRuleParams params, BuildRuleResolver buildRuleResolver, CellPathResolver cellRoots, JavaBuckConfig javaBuckConfig, JavacOptions javacOptions, AndroidLibraryDescription.CoreArg args, ConfiguredCompilerFactory compilerFactory) { super( targetGraph, buildTarget, projectFilesystem, params, buildRuleResolver, cellRoots, compilerFactory, javaBuckConfig); this.args = args; setJavacOptions(javacOptions); setArgs(args); } @Override public DefaultJavaLibraryBuilder setArgs(JavaLibraryDescription.CoreArg args) { super.setArgs(args); AndroidLibraryDescription.CoreArg androidArgs = (AndroidLibraryDescription.CoreArg) args; return setManifestFile(androidArgs.getManifest()); } @Override public DefaultJavaLibraryBuilder setManifestFile(Optional<SourcePath> manifestFile) { androidManifest = manifestFile; return this; } public DummyRDotJava buildDummyRDotJava() { return newHelper().buildDummyRDotJava(); } public Optional<DummyRDotJava> getDummyRDotJava() { return newHelper().getDummyRDotJava(); } @Override protected BuilderHelper newHelper() { return new BuilderHelper(); } protected class BuilderHelper extends DefaultJavaLibraryBuilder.BuilderHelper { @Nullable private AndroidLibraryGraphEnhancer graphEnhancer; @Override protected DefaultJavaLibrary build() { AndroidLibrary result = new AndroidLibrary( libraryTarget, projectFilesystem, getFinalBuildDeps(), sourcePathResolver, getJarBuildStepsFactory(), proguardConfig, getFinalFullJarDeclaredDeps(), Preconditions.checkNotNull(deps).getExportedDeps(), Preconditions.checkNotNull(deps).getProvidedDeps(), getAbiJar(), mavenCoords, androidManifest, tests, getRequiredForSourceAbi()); return result; } protected DummyRDotJava buildDummyRDotJava() { return getGraphEnhancer().getBuildableForAndroidResources(buildRuleResolver, true).get(); } protected Optional<DummyRDotJava> getDummyRDotJava() { return getGraphEnhancer().getBuildableForAndroidResources(buildRuleResolver, false); } protected AndroidLibraryGraphEnhancer getGraphEnhancer() { if (graphEnhancer == null) { graphEnhancer = new AndroidLibraryGraphEnhancer( libraryTarget, projectFilesystem, ImmutableSortedSet.copyOf( Iterables.concat( Preconditions.checkNotNull(deps).getDeps(), Preconditions.checkNotNull(deps).getProvidedDeps(), getConfiguredCompiler().getDeclaredDeps(ruleFinder))), getJavac(), getJavacOptions(), DependencyMode.FIRST_ORDER, /* forceFinalResourceIds */ false, args.getResourceUnionPackage(), args.getFinalRName(), false); } return graphEnhancer; } @Override protected ImmutableSortedSet<BuildRule> buildFinalFullJarDeclaredDeps() { return RichStream.from(super.buildFinalFullJarDeclaredDeps()) .concat(RichStream.from(getDummyRDotJava())) .toImmutableSortedSet(Ordering.natural()); } } } }
AndroidLibrary: Don't look for resources in compiler dependencies Summary: There are no known compilers that expect you to generate your own `R.java` for resources that they provide, and removing this makes it easier to hoist the construction of `AndroidLibraryGraphEnhancer` out of this location. Test Plan: CI Reviewed By: dreiss fbshipit-source-id: 4c471c8
src/com/facebook/buck/android/AndroidLibrary.java
AndroidLibrary: Don't look for resources in compiler dependencies
<ide><path>rc/com/facebook/buck/android/AndroidLibrary.java <ide> ImmutableSortedSet.copyOf( <ide> Iterables.concat( <ide> Preconditions.checkNotNull(deps).getDeps(), <del> Preconditions.checkNotNull(deps).getProvidedDeps(), <del> getConfiguredCompiler().getDeclaredDeps(ruleFinder))), <add> Preconditions.checkNotNull(deps).getProvidedDeps())), <ide> getJavac(), <ide> getJavacOptions(), <ide> DependencyMode.FIRST_ORDER,
Java
apache-2.0
fbb048317aadc9a4285fea0a2734c002359e9d08
0
Apelon-VA/ISAAC,DongwonChoi/ISAAC,Apelon-VA/va-isaac-gui,DongwonChoi/ISAAC,Apelon-VA/va-isaac-gui,vaskaloidis/va-isaac-gui,Apelon-VA/ISAAC,DongwonChoi/ISAAC,Apelon-VA/ISAAC,vaskaloidis/va-isaac-gui
package gov.va.isaac.gui.mapping; import gov.va.isaac.AppContext; import gov.va.isaac.gui.SimpleDisplayConcept; import gov.va.isaac.gui.mapping.data.MappingItem; import gov.va.isaac.gui.mapping.data.MappingItemDAO; import gov.va.isaac.gui.mapping.data.MappingObject; import gov.va.isaac.gui.mapping.data.MappingSet; import gov.va.isaac.gui.mapping.data.MappingSetDAO; import gov.va.isaac.gui.util.CustomClipboard; import gov.va.isaac.gui.util.FxUtils; import gov.va.isaac.gui.util.Images; import gov.va.isaac.interfaces.utility.DialogResponse; import gov.va.isaac.util.CommonMenus; import gov.va.isaac.util.CommonMenusNIdProvider; import gov.va.isaac.util.OTFUtility; import gov.va.isaac.util.Utility; import java.io.IOException; import java.net.URL; import java.util.Arrays; import java.util.Collection; import java.util.UUID; import javafx.application.Platform; import javafx.beans.property.SimpleObjectProperty; import javafx.beans.property.SimpleStringProperty; import javafx.beans.value.ChangeListener; import javafx.beans.value.ObservableValue; import javafx.collections.FXCollections; import javafx.collections.ListChangeListener; import javafx.collections.ObservableList; import javafx.event.ActionEvent; import javafx.event.EventHandler; import javafx.fxml.FXML; import javafx.fxml.FXMLLoader; import javafx.geometry.Insets; import javafx.geometry.Pos; import javafx.scene.Node; import javafx.scene.control.Button; import javafx.scene.control.ComboBox; import javafx.scene.control.ContextMenu; import javafx.scene.control.Label; import javafx.scene.control.MenuItem; import javafx.scene.control.ProgressBar; import javafx.scene.control.SelectionMode; import javafx.scene.control.TableCell; import javafx.scene.control.TableColumn; import javafx.scene.control.Tooltip; import javafx.scene.control.TableColumn.CellDataFeatures; import javafx.scene.control.TableView; import javafx.scene.control.Toggle; import javafx.scene.control.ToggleButton; import javafx.scene.control.ToggleGroup; import javafx.scene.image.ImageView; import javafx.scene.layout.AnchorPane; import javafx.scene.layout.StackPane; import javafx.scene.text.Text; import javafx.util.Callback; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * Controller class for the Mapping View. * * @author dtriglianos * @author <a href="mailto:[email protected]">David Triglianos</a> */ public class MappingController { private static final Logger LOG = LoggerFactory.getLogger(MappingController.class); @FXML private AnchorPane mainPane; @FXML private AnchorPane mappingPane; @FXML private AnchorPane listPane; @FXML private ToggleButton activeOnlyToggle; @FXML private ToggleButton stampToggle; @FXML private Button refreshButton; @FXML private Button plusMappingSetButton; @FXML private Button minusMappingSetButton; @FXML private Button editMappingSetButton; @FXML private Label mappingItemListTitleLabel; @FXML private Button plusMappingItemButton; @FXML private Button minusMappingItemButton; @FXML private Button editMappingItemButton; @FXML private Button commentButton; @FXML private Label mappingSetSummaryLabel; @FXML private Label mappingItemSummaryLabel; @FXML private TableView<MappingSet> mappingSetTableView; @FXML private TableView<MappingItem> mappingItemTableView; @FXML private TableColumn<MappingSet, ?> mappingSetSTableColumn; @FXML private TableColumn<MappingSet, ?> mappingSetNameTableColumn; @FXML private TableColumn<MappingSet, ?> mappingSetDescriptionTableColumn; @FXML private TableColumn<MappingSet, ?> mappingSetPurposeTableColumn; @FXML private TableColumn<MappingSet, ?> mappingSetEditorStatusTableColumn; @FXML private TableColumn<MappingSet, ?> mappingSetSTAMPTableColumn; @FXML private TableColumn<MappingSet, ?> mappingSetStatusTableColumn; @FXML private TableColumn<MappingSet, ?> mappingSetTimeTableColumn; @FXML private TableColumn<MappingSet, ?> mappingSetAuthorTableColumn; @FXML private TableColumn<MappingSet, ?> mappingSetModuleTableColumn; @FXML private TableColumn<MappingSet, ?> mappingSetPathTableColumn; @FXML private TableColumn<MappingItem, ?> mappingItemSTableColumn; @FXML private TableColumn<MappingItem, ?> mappingItemSourceTableColumn; @FXML private TableColumn<MappingItem, ?> mappingItemTargetTableColumn; @FXML private TableColumn<MappingItem, ?> mappingItemQualifierTableColumn; @FXML private TableColumn<MappingItem, ?> mappingItemCommentsTableColumn; @FXML private TableColumn<MappingItem, ?> mappingItemEditorStatusTableColumn; @FXML private TableColumn<MappingItem, ?> mappingItemSTAMPTableColumn; @FXML private TableColumn<MappingItem, ?> mappingItemStatusTableColumn; @FXML private TableColumn<MappingItem, ?> mappingItemTimeTableColumn; @FXML private TableColumn<MappingItem, ?> mappingItemAuthorTableColumn; @FXML private TableColumn<MappingItem, ?> mappingItemModuleTableColumn; @FXML private TableColumn<MappingItem, ?> mappingItemPathTableColumn; public static MappingController init() throws IOException { // Load from FXML. URL resource = MappingController.class.getResource("Mapping.fxml"); FXMLLoader loader = new FXMLLoader(resource); loader.load(); return loader.getController(); } @FXML public void initialize() { assert mappingSetTableView != null : "fx:id=\"mappingSetTableView\" was not injected: check your FXML file 'Mapping.fxml'."; assert mappingSetNameTableColumn != null : "fx:id=\"mappingSetNameTableColumn\" was not injected: check your FXML file 'Mapping.fxml'."; assert mappingSetSTableColumn != null : "fx:id=\"mappingSetSTableColumn\" was not injected: check your FXML file 'Mapping.fxml'."; assert commentButton != null : "fx:id=\"commentButton\" was not injected: check your FXML file 'Mapping.fxml'."; assert mappingSetModuleTableColumn != null : "fx:id=\"mappingSetModuleTableColumn\" was not injected: check your FXML file 'Mapping.fxml'."; assert mappingSetDescriptionTableColumn != null : "fx:id=\"mappingSetDescriptionTableColumn\" was not injected: check your FXML file 'Mapping.fxml'."; assert mappingItemAuthorTableColumn != null : "fx:id=\"mappingItemAuthorTableColumn\" was not injected: check your FXML file 'Mapping.fxml'."; assert mappingItemSourceTableColumn != null : "fx:id=\"mappingItemSourceTableColumn\" was not injected: check your FXML file 'Mapping.fxml'."; assert mappingSetStatusTableColumn != null : "fx:id=\"mappingSetActiveTableColumn\" was not injected: check your FXML file 'Mapping.fxml'."; assert minusMappingSetButton != null : "fx:id=\"minusMappingSetButton\" was not injected: check your FXML file 'Mapping.fxml'."; assert mappingSetEditorStatusTableColumn != null : "fx:id=\"mappingSetEditorStatusTableColumn\" was not injected: check your FXML file 'Mapping.fxml'."; assert mappingSetPathTableColumn != null : "fx:id=\"mappingSetPathTableColumn\" was not injected: check your FXML file 'Mapping.fxml'."; assert editMappingSetButton != null : "fx:id=\"editMappingSetButton\" was not injected: check your FXML file 'Mapping.fxml'."; assert mappingItemListTitleLabel != null : "fx:id=\"mappingItemListTitleLabel\" was not injected: check your FXML file 'Mapping.fxml'."; assert listPane != null : "fx:id=\"listPane\" was not injected: check your FXML file 'Mapping.fxml'."; assert plusMappingSetButton != null : "fx:id=\"plusMappingSetButton\" was not injected: check your FXML file 'Mapping.fxml'."; assert mappingItemTargetTableColumn != null : "fx:id=\"mappingItemTargetTableColumn\" was not injected: check your FXML file 'Mapping.fxml'."; assert mappingItemEditorStatusTableColumn != null : "fx:id=\"mappingItemEditorStatusTableColumn\" was not injected: check your FXML file 'Mapping.fxml'."; assert mappingSetTimeTableColumn != null : "fx:id=\"mappingSetTimeTableColumn\" was not injected: check your FXML file 'Mapping.fxml'."; assert mappingItemTimeTableColumn != null : "fx:id=\"mappingItemTimeTableColumn\" was not injected: check your FXML file 'Mapping.fxml'."; assert mappingItemTableView != null : "fx:id=\"mappingItemTableView\" was not injected: check your FXML file 'Mapping.fxml'."; assert mappingSetSTAMPTableColumn != null : "fx:id=\"mappingSetSTAMPTableColumn\" was not injected: check your FXML file 'Mapping.fxml'."; assert mappingItemSTableColumn != null : "fx:id=\"mappingItemSTableColumn\" was not injected: check your FXML file 'Mapping.fxml'."; assert mappingItemModuleTableColumn != null : "fx:id=\"mappingItemModuleTableColumn\" was not injected: check your FXML file 'Mapping.fxml'."; assert mappingSetAuthorTableColumn != null : "fx:id=\"mappingSetAuthorTableColumn\" was not injected: check your FXML file 'Mapping.fxml'."; assert plusMappingItemButton != null : "fx:id=\"plusMappingItemButton\" was not injected: check your FXML file 'Mapping.fxml'."; assert minusMappingItemButton != null : "fx:id=\"minusMappingItemButton\" was not injected: check your FXML file 'Mapping.fxml'."; assert mappingItemSTAMPTableColumn != null : "fx:id=\"mappingItemSTAMPTableColumn\" was not injected: check your FXML file 'Mapping.fxml'."; assert editMappingItemButton != null : "fx:id=\"editMappingItemButton\" was not injected: check your FXML file 'Mapping.fxml'."; assert mappingItemStatusTableColumn != null : "fx:id=\"mappingItemActiveTableColumn\" was not injected: check your FXML file 'Mapping.fxml'."; assert mappingSetSummaryLabel != null : "fx:id=\"mappingSetSummaryLabel\" was not injected: check your FXML file 'Mapping.fxml'."; assert activeOnlyToggle != null : "fx:id=\"activeOnlyToggle\" was not injected: check your FXML file 'Mapping.fxml'."; assert stampToggle != null : "fx:id=\"stampToggleToggle\" was not injected: check your FXML file 'Mapping.fxml'."; assert mappingItemQualifierTableColumn != null : "fx:id=\"mappingItemQualifierTableColumn\" was not injected: check your FXML file 'Mapping.fxml'."; assert mappingItemPathTableColumn != null : "fx:id=\"mappingItemPathTableColumn\" was not injected: check your FXML file 'Mapping.fxml'."; assert mainPane != null : "fx:id=\"mainPane\" was not injected: check your FXML file 'Mapping.fxml'."; assert mappingSetPurposeTableColumn != null : "fx:id=\"mappingSetPurposeTableColumn\" was not injected: check your FXML file 'Mapping.fxml'."; assert mappingItemCommentsTableColumn != null : "fx:id=\"mappingItemCommentsTableColumn\" was not injected: check your FXML file 'Mapping.fxml'."; assert mappingItemSummaryLabel != null : "fx:id=\"mappingItemSummaryLabel\" was not injected: check your FXML file 'Mapping.fxml'."; assert refreshButton != null : "fx:id=\"refreshButton\" was not injected: check your FXML file 'Mapping.fxml'."; mainPane.getStylesheets().add(MappingController.class.getResource("/isaac-shared-styles.css").toString()); FxUtils.assignImageToButton(activeOnlyToggle, Images.FILTER_16.createImageView(), "Show Active Only / Show All"); FxUtils.assignImageToButton(stampToggle, Images.STAMP.createImageView(), "Show/Hide STAMP Columns"); FxUtils.assignImageToButton(refreshButton, Images.SYNC_GREEN.createImageView(), "Refresh"); FxUtils.assignImageToButton(plusMappingSetButton, Images.PLUS.createImageView(), "Create Mapping Set"); FxUtils.assignImageToButton(minusMappingSetButton, Images.MINUS.createImageView(), "Retire/Unretire Mapping Set"); FxUtils.assignImageToButton(editMappingSetButton, Images.EDIT.createImageView(), "Edit Mapping Set"); FxUtils.assignImageToButton(plusMappingItemButton, Images.PLUS.createImageView(), "Create Mapping"); FxUtils.assignImageToButton(minusMappingItemButton, Images.MINUS.createImageView(), "Retire Mapping"); FxUtils.assignImageToButton(editMappingItemButton, Images.EDIT.createImageView(), "Edit Mapping Item"); FxUtils.assignImageToButton(commentButton, Images.BALLOON.createImageView(), "View Comments"); setupColumnTypes(); setupGlobalButtons(); setupMappingSetButtons(); setupMappingItemButtons(); setupMappingSetTable(); setupMappingItemTable(); mappingSetSummaryLabel.setText(""); mappingItemSummaryLabel.setText(""); mappingItemListTitleLabel.setText("(no Mapping Set selected)"); mappingSetTableView.setPlaceholder(new Label("There are no Mapping Sets in the database.")); clearMappingItems(); } private void updateMappingItemsList(MappingSet mappingSet) { clearMappingItems(); if (mappingSet != null) { mappingItemTableView.setPlaceholder(new ProgressBar(-1.0)); Utility.execute(() -> { ObservableList<MappingItem> mappingItems = FXCollections.observableList(mappingSet.getMappingItems(activeOnlyToggle.isSelected())); Platform.runLater(() -> { mappingItemTableView.setItems(mappingItems); mappingItemTableView.setPlaceholder(new Label("The selected Mapping Set contains no Mapping Items.")); mappingItemListTitleLabel.setText(mappingSet.getName()); plusMappingItemButton.setDisable(false); minusMappingSetButton.setDisable(false); editMappingSetButton.setDisable(false); mappingSetSummaryLabel.setText(mappingSet.getSummary(activeOnlyToggle.isSelected())); }); }); } } private MappingSet getSelectedMappingSet() { return (MappingSet)mappingSetTableView.getSelectionModel().getSelectedItem(); } private MappingItem getSelectedMappingItem() { return mappingItemTableView.getSelectionModel().getSelectedItem(); } private ObservableList<MappingItem> getSelectedMappingItems() { return mappingItemTableView.getSelectionModel().getSelectedItems(); } public AnchorPane getRoot() { return mainPane; } protected void refreshMappingSets() { ObservableList<MappingSet> mappingSets; boolean activeOnly = activeOnlyToggle.isSelected(); try { mappingSets = FXCollections.observableList(MappingSetDAO.getMappingSets(activeOnly)); } catch (IOException e) { LOG.error("unexpected", e); //TODO GUI prompt; mappingSets = FXCollections.observableArrayList(); } mappingSetTableView.setItems(mappingSets); // TODO maybe come up with a way to preserve the selection, if possible. mappingSetTableView.getSelectionModel().clearSelection(); refreshMappingItems(); } protected void refreshMappingItems() { MappingSet selectedMappingSet = getSelectedMappingSet(); updateMappingItemsList(selectedMappingSet); } protected void clearMappingItems() { mappingItemTableView.getItems().clear(); mappingItemTableView.setPlaceholder(new Label("No Mapping Set is selected.")); } private void setupMappingSetTable() { setMappingSetTableFactories(mappingSetTableView.getColumns()); mappingSetTableView.getSelectionModel().getSelectedItems().addListener(new ListChangeListener<MappingSet>() { @Override public void onChanged(javafx.collections.ListChangeListener.Change<? extends MappingSet> c) { updateMappingItemsList(getSelectedMappingSet()); } }); mappingSetSTAMPTableColumn.setVisible(false); } private void setupMappingItemTable() { setMappingItemTableFactories(mappingItemTableView.getColumns()); mappingItemTableView.getSelectionModel().getSelectedItems().addListener(new ListChangeListener<MappingItem>() { @Override public void onChanged(javafx.collections.ListChangeListener.Change<? extends MappingItem> c) { MappingItem selectedMappingItem = getSelectedMappingItem(); if (c.getList().size() >= 1) { selectedMappingItem = (MappingItem) c.getList().get(0); } else { selectedMappingItem = null; } minusMappingItemButton.setDisable(selectedMappingItem == null); editMappingItemButton.setDisable(selectedMappingItem == null); commentButton.setDisable(selectedMappingItem == null); mappingItemSummaryLabel.setText((selectedMappingItem == null)? "" : selectedMappingItem.getSummary()); } }); mappingItemTableView.getSelectionModel().setSelectionMode(SelectionMode.MULTIPLE); mappingItemSTAMPTableColumn.setVisible(false); } @SuppressWarnings("unchecked") private void setMappingSetTableFactories(ObservableList<TableColumn<MappingSet,?>> tableColumns) { for (TableColumn<MappingSet, ?> tableColumn : tableColumns) { TableColumn<MappingSet, MappingSet> mappingItemTableColumn = (TableColumn<MappingSet, MappingSet>)tableColumn; mappingItemTableColumn.setCellValueFactory(mappingSetCellValueFactory); mappingItemTableColumn.setCellFactory(mappingSetCellFactory); ObservableList<TableColumn<MappingSet,?>> nestedTableColumns = mappingItemTableColumn.getColumns(); if (nestedTableColumns.size() > 0) { setMappingSetTableFactories(nestedTableColumns); } } } @SuppressWarnings("unchecked") private void setMappingItemTableFactories(ObservableList<TableColumn<MappingItem,?>> tableColumns) { for (TableColumn<MappingItem, ?> tableColumn : tableColumns) { TableColumn<MappingItem, MappingItem> mappingItemTableColumn = (TableColumn<MappingItem, MappingItem>)tableColumn; mappingItemTableColumn.setCellValueFactory(mappingItemCellValueFactory); mappingItemTableColumn.setCellFactory(mappingItemCellFactory); ObservableList<TableColumn<MappingItem,?>> nestedTableColumns = mappingItemTableColumn.getColumns(); if (nestedTableColumns.size() > 0) { setMappingItemTableFactories(nestedTableColumns); } } } private void updateCell(TableCell<?, ?> cell, MappingObject mappingObject) { if (!cell.isEmpty() && mappingObject != null) { ContextMenu cm = new ContextMenu(); cell.setContextMenu(cm); SimpleStringProperty property = null; int conceptNid = 0; MappingColumnType columnType = (MappingColumnType) cell.getTableColumn().getUserData(); cell.setText(null); cell.setGraphic(null); switch (columnType) { case STATUS_CONDENSED: StackPane sp = new StackPane(); sp.setPrefSize(25, 25); String tooltipText = mappingObject.isActive()? "Active" : "Inactive"; ImageView image = mappingObject.isActive()? Images.BLACK_DOT.createImageView() : Images.GREY_DOT.createImageView(); sizeAndPosition(image, sp, Pos.CENTER); cell.setTooltip(new Tooltip(tooltipText)); cell.setGraphic(sp); break; case NAME: property = ((MappingSet)mappingObject).getNameProperty(); break; case PURPOSE: property = ((MappingSet)mappingObject).getPurposeProperty(); break; case DESCRIPTION: property = ((MappingSet)mappingObject).getDescriptionProperty(); break; case SOURCE: property = ((MappingItem)mappingObject).getSourceConceptProperty(); conceptNid = ((MappingItem)mappingObject).getSourceConceptNid(); break; case TARGET: property = ((MappingItem)mappingObject).getTargetConceptProperty(); conceptNid = ((MappingItem)mappingObject).getTargetConceptNid(); break; case QUALIFIER: property = ((MappingItem)mappingObject).getQualifierConceptProperty(); conceptNid = ((MappingItem)mappingObject).getQualifierConceptNid(); break; case COMMENTS: property = ((MappingItem)mappingObject).getCommentsProperty(); break; case EDITOR_STATUS: property = mappingObject.getEditorStatusConceptProperty(); conceptNid = mappingObject.getEditorStatusConceptNid(); break; case STATUS_STRING: property = mappingObject.getStatusProperty(); break; case TIME: property = mappingObject.getTimeProperty(); break; case AUTHOR: property = mappingObject.getAuthorProperty(); conceptNid = mappingObject.getAuthorNid(); break; case MODULE: property = mappingObject.getModuleProperty(); conceptNid = mappingObject.getModuleNid(); break; case PATH: property = mappingObject.getPathProperty(); conceptNid = mappingObject.getPathNid(); break; default: // Nothing } if (property != null) { Text text = new Text(); text.textProperty().bind(property); text.wrappingWidthProperty().bind(cell.getTableColumn().widthProperty()); cell.setGraphic(text); MenuItem mi = new MenuItem("Copy Value"); mi.setOnAction(new EventHandler<ActionEvent>() { @Override public void handle(ActionEvent arg0) { CustomClipboard.set(((Text)cell.getGraphic()).getText()); } }); mi.setGraphic(Images.COPY.createImageView()); cm.getItems().add(mi); if (columnType.isConcept() && conceptNid != 0) { final int nid = conceptNid; CommonMenus.addCommonMenus(cm, new CommonMenusNIdProvider() { @Override public Collection<Integer> getNIds() { return Arrays.asList(new Integer[] {nid}); } }); } } } else { cell.setText(null); cell.setGraphic(null); } } private void setupMappingSetButtons() { editMappingSetButton.setOnAction(new EventHandler<ActionEvent>() { @Override public void handle(ActionEvent e) { MappingSet selectedMappingSet = getSelectedMappingSet(); if (selectedMappingSet != null) { CreateMappingSetView cv = AppContext.getService(CreateMappingSetView.class); cv.setMappingSet(selectedMappingSet); cv.showView(getRoot().getScene().getWindow()); } } }); plusMappingSetButton.setOnAction(new EventHandler<ActionEvent>() { @Override public void handle(ActionEvent e) { CreateMappingSetView cv = AppContext.getService(CreateMappingSetView.class); cv.showView(getRoot().getScene().getWindow()); } }); minusMappingSetButton.setOnAction(new EventHandler<ActionEvent>() { @Override public void handle(ActionEvent e) { MappingSet selectedMappingSet = getSelectedMappingSet(); if (selectedMappingSet != null) { String verb = (selectedMappingSet.isActive())? "retire" : "unretire"; DialogResponse response = AppContext.getCommonDialogs().showYesNoDialog("Please Confirm", "Are you sure you want to " + verb + " " + selectedMappingSet.getName() + "?"); if (response == DialogResponse.YES) { try { if (selectedMappingSet.isActive()) { MappingSetDAO.retireMappingSet(selectedMappingSet.getPrimordialUUID()); } else { MappingSetDAO.unRetireMappingSet(selectedMappingSet.getPrimordialUUID()); } } catch (IOException e1) { // TODO Auto-generated catch block e1.printStackTrace(); } refreshMappingSets(); } } } }); } private void setupMappingItemButtons() { plusMappingItemButton.setOnAction(new EventHandler<ActionEvent>() { @Override public void handle(ActionEvent e) { MappingSet selectedMappingSet = getSelectedMappingSet(); if (selectedMappingSet != null) { MappingItem selectedMappingItem = getSelectedMappingItem(); CreateMappingItemView itemView = AppContext.getService(CreateMappingItemView.class); itemView.setMappingSet(selectedMappingSet); if (selectedMappingItem != null) { itemView.setSourceConcept(selectedMappingItem.getSourceConcept()); } itemView.showView(null); } } }); minusMappingItemButton.setOnAction(new EventHandler<ActionEvent>() { @Override public void handle(ActionEvent e) { ObservableList<MappingItem> selectedMappingItems = getSelectedMappingItems(); if (selectedMappingItems.size() >= 0) { if (selectedMappingItems.size() == 1 && !selectedMappingItems.get(0).isActive()) { // One inactive item selected; unretire DialogResponse response = AppContext.getCommonDialogs().showYesNoDialog("Please Confirm", "Are you sure you want to unretire this Mapping Item?"); if (response == DialogResponse.YES) { try { MappingItemDAO.unRetireMappingItem(selectedMappingItems.get(0).getPrimordialUUID()); } catch (IOException e1) { //TODO prompt e1.printStackTrace(); } updateMappingItemsList(getSelectedMappingSet()); } } else { String clause = (selectedMappingItems.size() == 1) ? "this Mapping Item" : "these " + Integer.toString(selectedMappingItems.size()) + " Mapping Items"; DialogResponse response = AppContext.getCommonDialogs().showYesNoDialog("Please Confirm", "Are you sure you want to retire " + clause + "?"); if (response == DialogResponse.YES) { for (MappingItem mappingItem : selectedMappingItems) { if (mappingItem.isActive()) { // Don't bother trying to retire inactive items try { MappingItemDAO.retireMappingItem(mappingItem.getPrimordialUUID()); } catch (IOException e1) { // TODO Auto-generated catch block e1.printStackTrace(); } } } updateMappingItemsList(getSelectedMappingSet()); } } } } }); editMappingItemButton.setOnAction(new EventHandler<ActionEvent>() { @Override public void handle(ActionEvent e) { MappingItem selectedMappingItem = getSelectedMappingItem(); if (selectedMappingItem != null) { EditMappingItemView cv = AppContext.getService(EditMappingItemView.class); cv.setMappingItem(selectedMappingItem); cv.showView(getRoot().getScene().getWindow()); } } }); commentButton.setOnAction(new EventHandler<ActionEvent>() { @Override public void handle(ActionEvent e) { MappingSet selectedMappingSet = getSelectedMappingSet(); MappingItem selectedMappingItem = getSelectedMappingItem(); if (selectedMappingItem != null && selectedMappingSet != null) { CommentDialogView commentView = AppContext.getService(CommentDialogView.class); commentView.setMappingSetAndItem(selectedMappingSet, selectedMappingItem); commentView.showView(getRoot().getScene().getWindow()); } } }); } private void setupGlobalButtons() { ToggleGroup activeOnlyToggleGroup = new ToggleGroup(); activeOnlyToggle.setToggleGroup(activeOnlyToggleGroup); activeOnlyToggle.setSelected(true); activeOnlyToggleGroup.selectedToggleProperty().addListener(new ChangeListener<Toggle>() { @Override public void changed(ObservableValue<? extends Toggle> ov, Toggle toggle, Toggle new_toggle) { refreshMappingSets(); } }); ToggleGroup showStampToggleGroup = new ToggleGroup(); stampToggle.setToggleGroup(showStampToggleGroup); stampToggle.setSelected(false); showStampToggleGroup.selectedToggleProperty().addListener(new ChangeListener<Toggle>() { @Override public void changed(ObservableValue<? extends Toggle> ov, Toggle toggle, Toggle new_toggle) { boolean showStampFields = stampToggle.isSelected(); mappingSetSTAMPTableColumn.setVisible(showStampFields); mappingItemSTAMPTableColumn.setVisible(showStampFields); } }); refreshButton.setOnAction((event) -> { refreshMappingSets(); }); } private void setupColumnTypes() { mappingSetSTableColumn.setUserData(MappingColumnType.STATUS_CONDENSED); mappingSetNameTableColumn.setUserData(MappingColumnType.NAME); mappingSetDescriptionTableColumn.setUserData(MappingColumnType.DESCRIPTION); mappingSetPurposeTableColumn.setUserData(MappingColumnType.PURPOSE); mappingSetEditorStatusTableColumn.setUserData(MappingColumnType.EDITOR_STATUS); mappingSetSTAMPTableColumn.setUserData(MappingColumnType.STAMP); mappingSetStatusTableColumn.setUserData(MappingColumnType.STATUS_STRING); mappingSetTimeTableColumn.setUserData(MappingColumnType.TIME); mappingSetAuthorTableColumn.setUserData(MappingColumnType.AUTHOR); mappingSetModuleTableColumn.setUserData(MappingColumnType.MODULE); mappingSetPathTableColumn.setUserData(MappingColumnType.PATH); mappingItemSTableColumn.setUserData(MappingColumnType.STATUS_CONDENSED); mappingItemSourceTableColumn.setUserData(MappingColumnType.SOURCE); mappingItemTargetTableColumn.setUserData(MappingColumnType.TARGET); mappingItemQualifierTableColumn.setUserData(MappingColumnType.QUALIFIER); mappingItemCommentsTableColumn.setUserData(MappingColumnType.COMMENTS); mappingItemEditorStatusTableColumn.setUserData(MappingColumnType.EDITOR_STATUS); mappingItemSTAMPTableColumn.setUserData(MappingColumnType.STAMP); mappingItemStatusTableColumn.setUserData(MappingColumnType.STATUS_STRING); mappingItemTimeTableColumn.setUserData(MappingColumnType.TIME); mappingItemAuthorTableColumn.setUserData(MappingColumnType.AUTHOR); mappingItemModuleTableColumn.setUserData(MappingColumnType.MODULE); mappingItemPathTableColumn.setUserData(MappingColumnType.PATH); } public static void sizeAndPosition(Node node, StackPane sp, Pos position) { if (node instanceof ImageView) { ((ImageView)node).setFitHeight(12); ((ImageView)node).setFitWidth(12); } Insets insets; switch (position) { case TOP_LEFT: insets = new Insets(0,0,0,0); break; case TOP_RIGHT: insets = new Insets(0,0,0,13); break; case BOTTOM_LEFT: insets = new Insets(13,0,0,0); break; case BOTTOM_RIGHT: insets = new Insets(13,0,0,13); break; case CENTER: insets = new Insets(5,0,0,5); break; default: insets = new Insets(0,0,0,0); } StackPane.setMargin(node, insets); sp.getChildren().add(node); StackPane.setAlignment(node, Pos.TOP_LEFT); } private Callback<TableColumn.CellDataFeatures<MappingItem, MappingItem>, ObservableValue<MappingItem>> mappingItemCellValueFactory = new Callback<TableColumn.CellDataFeatures<MappingItem, MappingItem>, ObservableValue<MappingItem>>() { @Override public ObservableValue<MappingItem> call(CellDataFeatures<MappingItem, MappingItem> param) { return new SimpleObjectProperty<MappingItem>(param.getValue()); } }; private Callback<TableColumn.CellDataFeatures<MappingSet, MappingSet>, ObservableValue<MappingSet>> mappingSetCellValueFactory = new Callback<TableColumn.CellDataFeatures<MappingSet, MappingSet>, ObservableValue<MappingSet>>() { @Override public ObservableValue<MappingSet> call(CellDataFeatures<MappingSet, MappingSet> param) { return new SimpleObjectProperty<MappingSet>(param.getValue()); } }; private Callback<TableColumn<MappingItem, MappingItem>, TableCell<MappingItem, MappingItem>> mappingItemCellFactory = new Callback<TableColumn<MappingItem, MappingItem>, TableCell<MappingItem, MappingItem>>() { @Override public TableCell<MappingItem, MappingItem> call(TableColumn<MappingItem, MappingItem> param) { return new TableCell<MappingItem, MappingItem>() { @Override public void updateItem(final MappingItem mappingItem, boolean empty) { super.updateItem(mappingItem, empty); updateCell(this, mappingItem); } }; } }; private Callback<TableColumn<MappingSet, MappingSet>, TableCell<MappingSet, MappingSet>> mappingSetCellFactory = new Callback<TableColumn<MappingSet, MappingSet>, TableCell<MappingSet, MappingSet>>() { @Override public TableCell<MappingSet, MappingSet> call(TableColumn<MappingSet, MappingSet> param) { return new TableCell<MappingSet, MappingSet>() { @Override public void updateItem(final MappingSet mappingSet, boolean empty) { super.updateItem(mappingSet, empty); updateCell(this, mappingSet); } }; } }; public static void setComboSelection(ComboBox<SimpleDisplayConcept> combo, String selectValue, int defaultIndex) { boolean found = false; if (selectValue != null && !selectValue.trim().equals("")) { for (SimpleDisplayConcept sdc : combo.getItems()) { if (sdc.getDescription().equals(selectValue)) { combo.getSelectionModel().select(sdc); found = true; break; } } } if (!found && defaultIndex >= 0 && defaultIndex < combo.getItems().size()) { combo.getSelectionModel().select(0); } } }
mapping/src/main/java/gov/va/isaac/gui/mapping/MappingController.java
package gov.va.isaac.gui.mapping; import gov.va.isaac.AppContext; import gov.va.isaac.gui.SimpleDisplayConcept; import gov.va.isaac.gui.mapping.data.MappingItem; import gov.va.isaac.gui.mapping.data.MappingItemDAO; import gov.va.isaac.gui.mapping.data.MappingObject; import gov.va.isaac.gui.mapping.data.MappingSet; import gov.va.isaac.gui.mapping.data.MappingSetDAO; import gov.va.isaac.gui.util.CustomClipboard; import gov.va.isaac.gui.util.FxUtils; import gov.va.isaac.gui.util.Images; import gov.va.isaac.interfaces.utility.DialogResponse; import gov.va.isaac.util.CommonMenus; import gov.va.isaac.util.CommonMenusNIdProvider; import gov.va.isaac.util.OTFUtility; import gov.va.isaac.util.Utility; import java.io.IOException; import java.net.URL; import java.util.Arrays; import java.util.Collection; import java.util.UUID; import javafx.application.Platform; import javafx.beans.property.SimpleObjectProperty; import javafx.beans.property.SimpleStringProperty; import javafx.beans.value.ChangeListener; import javafx.beans.value.ObservableValue; import javafx.collections.FXCollections; import javafx.collections.ListChangeListener; import javafx.collections.ObservableList; import javafx.event.ActionEvent; import javafx.event.EventHandler; import javafx.fxml.FXML; import javafx.fxml.FXMLLoader; import javafx.geometry.Insets; import javafx.geometry.Pos; import javafx.scene.Node; import javafx.scene.control.Button; import javafx.scene.control.ComboBox; import javafx.scene.control.ContextMenu; import javafx.scene.control.Label; import javafx.scene.control.MenuItem; import javafx.scene.control.ProgressBar; import javafx.scene.control.SelectionMode; import javafx.scene.control.TableCell; import javafx.scene.control.TableColumn; import javafx.scene.control.Tooltip; import javafx.scene.control.TableColumn.CellDataFeatures; import javafx.scene.control.TableView; import javafx.scene.control.Toggle; import javafx.scene.control.ToggleButton; import javafx.scene.control.ToggleGroup; import javafx.scene.image.ImageView; import javafx.scene.layout.AnchorPane; import javafx.scene.layout.StackPane; import javafx.scene.text.Text; import javafx.util.Callback; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * Controller class for the Mapping View. * * @author dtriglianos * @author <a href="mailto:[email protected]">David Triglianos</a> */ public class MappingController { private static final Logger LOG = LoggerFactory.getLogger(MappingController.class); @FXML private AnchorPane mainPane; @FXML private AnchorPane mappingPane; @FXML private AnchorPane listPane; @FXML private ToggleButton activeOnlyToggle; @FXML private ToggleButton stampToggle; @FXML private Button refreshButton; @FXML private Button plusMappingSetButton; @FXML private Button minusMappingSetButton; @FXML private Button editMappingSetButton; @FXML private Label mappingItemListTitleLabel; @FXML private Button plusMappingItemButton; @FXML private Button minusMappingItemButton; @FXML private Button editMappingItemButton; @FXML private Button commentButton; @FXML private Label mappingSetSummaryLabel; @FXML private Label mappingItemSummaryLabel; @FXML private TableView<MappingSet> mappingSetTableView; @FXML private TableView<MappingItem> mappingItemTableView; @FXML private TableColumn<MappingSet, ?> mappingSetSTableColumn; @FXML private TableColumn<MappingSet, ?> mappingSetNameTableColumn; @FXML private TableColumn<MappingSet, ?> mappingSetDescriptionTableColumn; @FXML private TableColumn<MappingSet, ?> mappingSetPurposeTableColumn; @FXML private TableColumn<MappingSet, ?> mappingSetEditorStatusTableColumn; @FXML private TableColumn<MappingSet, ?> mappingSetSTAMPTableColumn; @FXML private TableColumn<MappingSet, ?> mappingSetStatusTableColumn; @FXML private TableColumn<MappingSet, ?> mappingSetTimeTableColumn; @FXML private TableColumn<MappingSet, ?> mappingSetAuthorTableColumn; @FXML private TableColumn<MappingSet, ?> mappingSetModuleTableColumn; @FXML private TableColumn<MappingSet, ?> mappingSetPathTableColumn; @FXML private TableColumn<MappingItem, ?> mappingItemSTableColumn; @FXML private TableColumn<MappingItem, ?> mappingItemSourceTableColumn; @FXML private TableColumn<MappingItem, ?> mappingItemTargetTableColumn; @FXML private TableColumn<MappingItem, ?> mappingItemQualifierTableColumn; @FXML private TableColumn<MappingItem, ?> mappingItemCommentsTableColumn; @FXML private TableColumn<MappingItem, ?> mappingItemEditorStatusTableColumn; @FXML private TableColumn<MappingItem, ?> mappingItemSTAMPTableColumn; @FXML private TableColumn<MappingItem, ?> mappingItemStatusTableColumn; @FXML private TableColumn<MappingItem, ?> mappingItemTimeTableColumn; @FXML private TableColumn<MappingItem, ?> mappingItemAuthorTableColumn; @FXML private TableColumn<MappingItem, ?> mappingItemModuleTableColumn; @FXML private TableColumn<MappingItem, ?> mappingItemPathTableColumn; public static MappingController init() throws IOException { // Load from FXML. URL resource = MappingController.class.getResource("Mapping.fxml"); FXMLLoader loader = new FXMLLoader(resource); loader.load(); return loader.getController(); } @FXML public void initialize() { assert mappingSetTableView != null : "fx:id=\"mappingSetTableView\" was not injected: check your FXML file 'Mapping.fxml'."; assert mappingSetNameTableColumn != null : "fx:id=\"mappingSetNameTableColumn\" was not injected: check your FXML file 'Mapping.fxml'."; assert mappingSetSTableColumn != null : "fx:id=\"mappingSetSTableColumn\" was not injected: check your FXML file 'Mapping.fxml'."; assert commentButton != null : "fx:id=\"commentButton\" was not injected: check your FXML file 'Mapping.fxml'."; assert mappingSetModuleTableColumn != null : "fx:id=\"mappingSetModuleTableColumn\" was not injected: check your FXML file 'Mapping.fxml'."; assert mappingSetDescriptionTableColumn != null : "fx:id=\"mappingSetDescriptionTableColumn\" was not injected: check your FXML file 'Mapping.fxml'."; assert mappingItemAuthorTableColumn != null : "fx:id=\"mappingItemAuthorTableColumn\" was not injected: check your FXML file 'Mapping.fxml'."; assert mappingItemSourceTableColumn != null : "fx:id=\"mappingItemSourceTableColumn\" was not injected: check your FXML file 'Mapping.fxml'."; assert mappingSetStatusTableColumn != null : "fx:id=\"mappingSetActiveTableColumn\" was not injected: check your FXML file 'Mapping.fxml'."; assert minusMappingSetButton != null : "fx:id=\"minusMappingSetButton\" was not injected: check your FXML file 'Mapping.fxml'."; assert mappingSetEditorStatusTableColumn != null : "fx:id=\"mappingSetEditorStatusTableColumn\" was not injected: check your FXML file 'Mapping.fxml'."; assert mappingSetPathTableColumn != null : "fx:id=\"mappingSetPathTableColumn\" was not injected: check your FXML file 'Mapping.fxml'."; assert editMappingSetButton != null : "fx:id=\"editMappingSetButton\" was not injected: check your FXML file 'Mapping.fxml'."; assert mappingItemListTitleLabel != null : "fx:id=\"mappingItemListTitleLabel\" was not injected: check your FXML file 'Mapping.fxml'."; assert listPane != null : "fx:id=\"listPane\" was not injected: check your FXML file 'Mapping.fxml'."; assert plusMappingSetButton != null : "fx:id=\"plusMappingSetButton\" was not injected: check your FXML file 'Mapping.fxml'."; assert mappingItemTargetTableColumn != null : "fx:id=\"mappingItemTargetTableColumn\" was not injected: check your FXML file 'Mapping.fxml'."; assert mappingItemEditorStatusTableColumn != null : "fx:id=\"mappingItemEditorStatusTableColumn\" was not injected: check your FXML file 'Mapping.fxml'."; assert mappingSetTimeTableColumn != null : "fx:id=\"mappingSetTimeTableColumn\" was not injected: check your FXML file 'Mapping.fxml'."; assert mappingItemTimeTableColumn != null : "fx:id=\"mappingItemTimeTableColumn\" was not injected: check your FXML file 'Mapping.fxml'."; assert mappingItemTableView != null : "fx:id=\"mappingItemTableView\" was not injected: check your FXML file 'Mapping.fxml'."; assert mappingSetSTAMPTableColumn != null : "fx:id=\"mappingSetSTAMPTableColumn\" was not injected: check your FXML file 'Mapping.fxml'."; assert mappingItemSTableColumn != null : "fx:id=\"mappingItemSTableColumn\" was not injected: check your FXML file 'Mapping.fxml'."; assert mappingItemModuleTableColumn != null : "fx:id=\"mappingItemModuleTableColumn\" was not injected: check your FXML file 'Mapping.fxml'."; assert mappingSetAuthorTableColumn != null : "fx:id=\"mappingSetAuthorTableColumn\" was not injected: check your FXML file 'Mapping.fxml'."; assert plusMappingItemButton != null : "fx:id=\"plusMappingItemButton\" was not injected: check your FXML file 'Mapping.fxml'."; assert minusMappingItemButton != null : "fx:id=\"minusMappingItemButton\" was not injected: check your FXML file 'Mapping.fxml'."; assert mappingItemSTAMPTableColumn != null : "fx:id=\"mappingItemSTAMPTableColumn\" was not injected: check your FXML file 'Mapping.fxml'."; assert editMappingItemButton != null : "fx:id=\"editMappingItemButton\" was not injected: check your FXML file 'Mapping.fxml'."; assert mappingItemStatusTableColumn != null : "fx:id=\"mappingItemActiveTableColumn\" was not injected: check your FXML file 'Mapping.fxml'."; assert mappingSetSummaryLabel != null : "fx:id=\"mappingSetSummaryLabel\" was not injected: check your FXML file 'Mapping.fxml'."; assert activeOnlyToggle != null : "fx:id=\"activeOnlyToggle\" was not injected: check your FXML file 'Mapping.fxml'."; assert stampToggle != null : "fx:id=\"stampToggleToggle\" was not injected: check your FXML file 'Mapping.fxml'."; assert mappingItemQualifierTableColumn != null : "fx:id=\"mappingItemQualifierTableColumn\" was not injected: check your FXML file 'Mapping.fxml'."; assert mappingItemPathTableColumn != null : "fx:id=\"mappingItemPathTableColumn\" was not injected: check your FXML file 'Mapping.fxml'."; assert mainPane != null : "fx:id=\"mainPane\" was not injected: check your FXML file 'Mapping.fxml'."; assert mappingSetPurposeTableColumn != null : "fx:id=\"mappingSetPurposeTableColumn\" was not injected: check your FXML file 'Mapping.fxml'."; assert mappingItemCommentsTableColumn != null : "fx:id=\"mappingItemCommentsTableColumn\" was not injected: check your FXML file 'Mapping.fxml'."; assert mappingItemSummaryLabel != null : "fx:id=\"mappingItemSummaryLabel\" was not injected: check your FXML file 'Mapping.fxml'."; assert refreshButton != null : "fx:id=\"refreshButton\" was not injected: check your FXML file 'Mapping.fxml'."; mainPane.getStylesheets().add(MappingController.class.getResource("/isaac-shared-styles.css").toString()); FxUtils.assignImageToButton(activeOnlyToggle, Images.FILTER_16.createImageView(), "Show Active Only / Show All"); FxUtils.assignImageToButton(stampToggle, Images.STAMP.createImageView(), "Show/Hide STAMP Columns"); FxUtils.assignImageToButton(refreshButton, Images.SYNC_GREEN.createImageView(), "Refresh"); FxUtils.assignImageToButton(plusMappingSetButton, Images.PLUS.createImageView(), "Create Mapping Set"); FxUtils.assignImageToButton(minusMappingSetButton, Images.MINUS.createImageView(), "Retire/Unretire Mapping Set"); FxUtils.assignImageToButton(editMappingSetButton, Images.EDIT.createImageView(), "Edit Mapping Set"); FxUtils.assignImageToButton(plusMappingItemButton, Images.PLUS.createImageView(), "Create Mapping"); FxUtils.assignImageToButton(minusMappingItemButton, Images.MINUS.createImageView(), "Retire Mapping"); FxUtils.assignImageToButton(editMappingItemButton, Images.EDIT.createImageView(), "Edit Mapping Item"); FxUtils.assignImageToButton(commentButton, Images.BALLOON.createImageView(), "View Comments"); setupColumnTypes(); setupGlobalButtons(); setupMappingSetButtons(); setupMappingItemButtons(); setupMappingSetTable(); setupMappingItemTable(); mappingSetSummaryLabel.setText(""); mappingItemSummaryLabel.setText(""); mappingItemListTitleLabel.setText("(no Mapping Set selected)"); mappingSetTableView.setPlaceholder(new Label("There are no Mapping Sets in the database.")); clearMappingItems(); } private void updateMappingItemsList(MappingSet mappingSet) { clearMappingItems(); if (mappingSet != null) { mappingItemTableView.setPlaceholder(new ProgressBar(-1.0)); Utility.execute(() -> { ObservableList<MappingItem> mappingItems = FXCollections.observableList(mappingSet.getMappingItems(activeOnlyToggle.isSelected())); Platform.runLater(() -> { mappingItemTableView.setItems(mappingItems); mappingItemTableView.setPlaceholder(new Label("The selected Mapping Set contains no Mapping Items.")); mappingItemListTitleLabel.setText("Members of " + mappingSet.getName()); plusMappingItemButton.setDisable(false); minusMappingSetButton.setDisable(false); editMappingSetButton.setDisable(false); mappingSetSummaryLabel.setText(mappingSet.getSummary(activeOnlyToggle.isSelected())); }); }); } } private MappingSet getSelectedMappingSet() { return (MappingSet)mappingSetTableView.getSelectionModel().getSelectedItem(); } private MappingItem getSelectedMappingItem() { return mappingItemTableView.getSelectionModel().getSelectedItem(); } private ObservableList<MappingItem> getSelectedMappingItems() { return mappingItemTableView.getSelectionModel().getSelectedItems(); } public AnchorPane getRoot() { return mainPane; } protected void refreshMappingSets() { ObservableList<MappingSet> mappingSets; boolean activeOnly = activeOnlyToggle.isSelected(); try { mappingSets = FXCollections.observableList(MappingSetDAO.getMappingSets(activeOnly)); } catch (IOException e) { LOG.error("unexpected", e); //TODO GUI prompt; mappingSets = FXCollections.observableArrayList(); } mappingSetTableView.setItems(mappingSets); // TODO maybe come up with a way to preserve the selection, if possible. mappingSetTableView.getSelectionModel().clearSelection(); mappingSetSTableColumn.setVisible(!activeOnly); mappingItemSTableColumn.setVisible(!activeOnly); refreshMappingItems(); } protected void refreshMappingItems() { MappingSet selectedMappingSet = getSelectedMappingSet(); updateMappingItemsList(selectedMappingSet); } protected void clearMappingItems() { mappingItemTableView.getItems().clear(); mappingItemTableView.setPlaceholder(new Label("No Mapping Set is selected.")); } private void setupMappingSetTable() { setMappingSetTableFactories(mappingSetTableView.getColumns()); mappingSetTableView.getSelectionModel().getSelectedItems().addListener(new ListChangeListener<MappingSet>() { @Override public void onChanged(javafx.collections.ListChangeListener.Change<? extends MappingSet> c) { updateMappingItemsList(getSelectedMappingSet()); } }); mappingSetSTableColumn.setVisible(false); mappingSetSTAMPTableColumn.setVisible(false); } private void setupMappingItemTable() { setMappingItemTableFactories(mappingItemTableView.getColumns()); mappingItemTableView.getSelectionModel().getSelectedItems().addListener(new ListChangeListener<MappingItem>() { @Override public void onChanged(javafx.collections.ListChangeListener.Change<? extends MappingItem> c) { MappingItem selectedMappingItem = getSelectedMappingItem(); if (c.getList().size() >= 1) { selectedMappingItem = (MappingItem) c.getList().get(0); } else { selectedMappingItem = null; } minusMappingItemButton.setDisable(selectedMappingItem == null); editMappingItemButton.setDisable(selectedMappingItem == null); commentButton.setDisable(selectedMappingItem == null); mappingItemSummaryLabel.setText((selectedMappingItem == null)? "" : selectedMappingItem.getSummary()); } }); mappingItemTableView.getSelectionModel().setSelectionMode(SelectionMode.MULTIPLE); mappingItemSTableColumn.setVisible(false); mappingItemSTAMPTableColumn.setVisible(false); } @SuppressWarnings("unchecked") private void setMappingSetTableFactories(ObservableList<TableColumn<MappingSet,?>> tableColumns) { for (TableColumn<MappingSet, ?> tableColumn : tableColumns) { TableColumn<MappingSet, MappingSet> mappingItemTableColumn = (TableColumn<MappingSet, MappingSet>)tableColumn; mappingItemTableColumn.setCellValueFactory(mappingSetCellValueFactory); mappingItemTableColumn.setCellFactory(mappingSetCellFactory); ObservableList<TableColumn<MappingSet,?>> nestedTableColumns = mappingItemTableColumn.getColumns(); if (nestedTableColumns.size() > 0) { setMappingSetTableFactories(nestedTableColumns); } } } @SuppressWarnings("unchecked") private void setMappingItemTableFactories(ObservableList<TableColumn<MappingItem,?>> tableColumns) { for (TableColumn<MappingItem, ?> tableColumn : tableColumns) { TableColumn<MappingItem, MappingItem> mappingItemTableColumn = (TableColumn<MappingItem, MappingItem>)tableColumn; mappingItemTableColumn.setCellValueFactory(mappingItemCellValueFactory); mappingItemTableColumn.setCellFactory(mappingItemCellFactory); ObservableList<TableColumn<MappingItem,?>> nestedTableColumns = mappingItemTableColumn.getColumns(); if (nestedTableColumns.size() > 0) { setMappingItemTableFactories(nestedTableColumns); } } } private void updateCell(TableCell<?, ?> cell, MappingObject mappingObject) { if (!cell.isEmpty() && mappingObject != null) { ContextMenu cm = new ContextMenu(); cell.setContextMenu(cm); SimpleStringProperty property = null; int conceptNid = 0; MappingColumnType columnType = (MappingColumnType) cell.getTableColumn().getUserData(); cell.setText(null); cell.setGraphic(null); switch (columnType) { case STATUS_CONDENSED: StackPane sp = new StackPane(); sp.setPrefSize(25, 25); String tooltipText = mappingObject.isActive()? "Active" : "Inactive"; ImageView image = mappingObject.isActive()? Images.BLACK_DOT.createImageView() : Images.GREY_DOT.createImageView(); sizeAndPosition(image, sp, Pos.CENTER); cell.setTooltip(new Tooltip(tooltipText)); cell.setGraphic(sp); break; case NAME: property = ((MappingSet)mappingObject).getNameProperty(); break; case PURPOSE: property = ((MappingSet)mappingObject).getPurposeProperty(); break; case DESCRIPTION: property = ((MappingSet)mappingObject).getDescriptionProperty(); break; case SOURCE: property = ((MappingItem)mappingObject).getSourceConceptProperty(); conceptNid = ((MappingItem)mappingObject).getSourceConceptNid(); break; case TARGET: property = ((MappingItem)mappingObject).getTargetConceptProperty(); conceptNid = ((MappingItem)mappingObject).getTargetConceptNid(); break; case QUALIFIER: property = ((MappingItem)mappingObject).getQualifierConceptProperty(); conceptNid = ((MappingItem)mappingObject).getQualifierConceptNid(); break; case COMMENTS: property = ((MappingItem)mappingObject).getCommentsProperty(); break; case EDITOR_STATUS: property = mappingObject.getEditorStatusConceptProperty(); conceptNid = mappingObject.getEditorStatusConceptNid(); break; case STATUS_STRING: property = mappingObject.getStatusProperty(); break; case TIME: property = mappingObject.getTimeProperty(); break; case AUTHOR: property = mappingObject.getAuthorProperty(); conceptNid = mappingObject.getAuthorNid(); break; case MODULE: property = mappingObject.getModuleProperty(); conceptNid = mappingObject.getModuleNid(); break; case PATH: property = mappingObject.getPathProperty(); conceptNid = mappingObject.getPathNid(); break; default: // Nothing } if (property != null) { Text text = new Text(); text.textProperty().bind(property); text.wrappingWidthProperty().bind(cell.getTableColumn().widthProperty()); cell.setGraphic(text); MenuItem mi = new MenuItem("Copy Value"); mi.setOnAction(new EventHandler<ActionEvent>() { @Override public void handle(ActionEvent arg0) { CustomClipboard.set(((Text)cell.getGraphic()).getText()); } }); mi.setGraphic(Images.COPY.createImageView()); cm.getItems().add(mi); if (columnType.isConcept() && conceptNid != 0) { final int nid = conceptNid; CommonMenus.addCommonMenus(cm, new CommonMenusNIdProvider() { @Override public Collection<Integer> getNIds() { return Arrays.asList(new Integer[] {nid}); } }); } } } else { cell.setText(null); cell.setGraphic(null); } } private void setupMappingSetButtons() { editMappingSetButton.setOnAction(new EventHandler<ActionEvent>() { @Override public void handle(ActionEvent e) { MappingSet selectedMappingSet = getSelectedMappingSet(); if (selectedMappingSet != null) { CreateMappingSetView cv = AppContext.getService(CreateMappingSetView.class); cv.setMappingSet(selectedMappingSet); cv.showView(getRoot().getScene().getWindow()); } } }); plusMappingSetButton.setOnAction(new EventHandler<ActionEvent>() { @Override public void handle(ActionEvent e) { CreateMappingSetView cv = AppContext.getService(CreateMappingSetView.class); cv.showView(getRoot().getScene().getWindow()); } }); minusMappingSetButton.setOnAction(new EventHandler<ActionEvent>() { @Override public void handle(ActionEvent e) { MappingSet selectedMappingSet = getSelectedMappingSet(); if (selectedMappingSet != null) { String verb = (selectedMappingSet.isActive())? "retire" : "unretire"; DialogResponse response = AppContext.getCommonDialogs().showYesNoDialog("Please Confirm", "Are you sure you want to " + verb + " " + selectedMappingSet.getName() + "?"); if (response == DialogResponse.YES) { try { if (selectedMappingSet.isActive()) { MappingSetDAO.retireMappingSet(selectedMappingSet.getPrimordialUUID()); } else { MappingSetDAO.unRetireMappingSet(selectedMappingSet.getPrimordialUUID()); } } catch (IOException e1) { // TODO Auto-generated catch block e1.printStackTrace(); } refreshMappingSets(); } } } }); } private void setupMappingItemButtons() { plusMappingItemButton.setOnAction(new EventHandler<ActionEvent>() { @Override public void handle(ActionEvent e) { MappingSet selectedMappingSet = getSelectedMappingSet(); if (selectedMappingSet != null) { MappingItem selectedMappingItem = getSelectedMappingItem(); CreateMappingItemView itemView = AppContext.getService(CreateMappingItemView.class); itemView.setMappingSet(selectedMappingSet); if (selectedMappingItem != null) { itemView.setSourceConcept(selectedMappingItem.getSourceConcept()); } itemView.showView(null); } } }); minusMappingItemButton.setOnAction(new EventHandler<ActionEvent>() { @Override public void handle(ActionEvent e) { ObservableList<MappingItem> selectedMappingItems = getSelectedMappingItems(); if (selectedMappingItems.size() >= 0) { if (selectedMappingItems.size() == 1 && !selectedMappingItems.get(0).isActive()) { // One inactive item selected; unretire DialogResponse response = AppContext.getCommonDialogs().showYesNoDialog("Please Confirm", "Are you sure you want to unretire this Mapping Item?"); if (response == DialogResponse.YES) { try { MappingItemDAO.unRetireMappingItem(selectedMappingItems.get(0).getPrimordialUUID()); } catch (IOException e1) { //TODO prompt e1.printStackTrace(); } updateMappingItemsList(getSelectedMappingSet()); } } else { String clause = (selectedMappingItems.size() == 1) ? "this Mapping Item" : "these " + Integer.toString(selectedMappingItems.size()) + " Mapping Items"; DialogResponse response = AppContext.getCommonDialogs().showYesNoDialog("Please Confirm", "Are you sure you want to retire " + clause + "?"); if (response == DialogResponse.YES) { for (MappingItem mappingItem : selectedMappingItems) { if (mappingItem.isActive()) { // Don't bother trying to retire inactive items try { MappingItemDAO.retireMappingItem(mappingItem.getPrimordialUUID()); } catch (IOException e1) { // TODO Auto-generated catch block e1.printStackTrace(); } } } updateMappingItemsList(getSelectedMappingSet()); } } } } }); editMappingItemButton.setOnAction(new EventHandler<ActionEvent>() { @Override public void handle(ActionEvent e) { MappingItem selectedMappingItem = getSelectedMappingItem(); if (selectedMappingItem != null) { EditMappingItemView cv = AppContext.getService(EditMappingItemView.class); cv.setMappingItem(selectedMappingItem); cv.showView(getRoot().getScene().getWindow()); } } }); commentButton.setOnAction(new EventHandler<ActionEvent>() { @Override public void handle(ActionEvent e) { MappingSet selectedMappingSet = getSelectedMappingSet(); MappingItem selectedMappingItem = getSelectedMappingItem(); if (selectedMappingItem != null && selectedMappingSet != null) { CommentDialogView commentView = AppContext.getService(CommentDialogView.class); commentView.setMappingSetAndItem(selectedMappingSet, selectedMappingItem); commentView.showView(getRoot().getScene().getWindow()); } } }); } private void setupGlobalButtons() { ToggleGroup activeOnlyToggleGroup = new ToggleGroup(); activeOnlyToggle.setToggleGroup(activeOnlyToggleGroup); activeOnlyToggle.setSelected(true); activeOnlyToggleGroup.selectedToggleProperty().addListener(new ChangeListener<Toggle>() { @Override public void changed(ObservableValue<? extends Toggle> ov, Toggle toggle, Toggle new_toggle) { refreshMappingSets(); } }); ToggleGroup showStampToggleGroup = new ToggleGroup(); stampToggle.setToggleGroup(showStampToggleGroup); stampToggle.setSelected(false); showStampToggleGroup.selectedToggleProperty().addListener(new ChangeListener<Toggle>() { @Override public void changed(ObservableValue<? extends Toggle> ov, Toggle toggle, Toggle new_toggle) { boolean showStampFields = stampToggle.isSelected(); mappingSetSTAMPTableColumn.setVisible(showStampFields); mappingItemSTAMPTableColumn.setVisible(showStampFields); } }); refreshButton.setOnAction((event) -> { refreshMappingSets(); }); } private void setupColumnTypes() { mappingSetSTableColumn.setUserData(MappingColumnType.STATUS_CONDENSED); mappingSetNameTableColumn.setUserData(MappingColumnType.NAME); mappingSetDescriptionTableColumn.setUserData(MappingColumnType.DESCRIPTION); mappingSetPurposeTableColumn.setUserData(MappingColumnType.PURPOSE); mappingSetEditorStatusTableColumn.setUserData(MappingColumnType.EDITOR_STATUS); mappingSetSTAMPTableColumn.setUserData(MappingColumnType.STAMP); mappingSetStatusTableColumn.setUserData(MappingColumnType.STATUS_STRING); mappingSetTimeTableColumn.setUserData(MappingColumnType.TIME); mappingSetAuthorTableColumn.setUserData(MappingColumnType.AUTHOR); mappingSetModuleTableColumn.setUserData(MappingColumnType.MODULE); mappingSetPathTableColumn.setUserData(MappingColumnType.PATH); mappingItemSTableColumn.setUserData(MappingColumnType.STATUS_CONDENSED); mappingItemSourceTableColumn.setUserData(MappingColumnType.SOURCE); mappingItemTargetTableColumn.setUserData(MappingColumnType.TARGET); mappingItemQualifierTableColumn.setUserData(MappingColumnType.QUALIFIER); mappingItemCommentsTableColumn.setUserData(MappingColumnType.COMMENTS); mappingItemEditorStatusTableColumn.setUserData(MappingColumnType.EDITOR_STATUS); mappingItemSTAMPTableColumn.setUserData(MappingColumnType.STAMP); mappingItemStatusTableColumn.setUserData(MappingColumnType.STATUS_STRING); mappingItemTimeTableColumn.setUserData(MappingColumnType.TIME); mappingItemAuthorTableColumn.setUserData(MappingColumnType.AUTHOR); mappingItemModuleTableColumn.setUserData(MappingColumnType.MODULE); mappingItemPathTableColumn.setUserData(MappingColumnType.PATH); } public static void sizeAndPosition(Node node, StackPane sp, Pos position) { if (node instanceof ImageView) { ((ImageView)node).setFitHeight(12); ((ImageView)node).setFitWidth(12); } Insets insets; switch (position) { case TOP_LEFT: insets = new Insets(0,0,0,0); break; case TOP_RIGHT: insets = new Insets(0,0,0,13); break; case BOTTOM_LEFT: insets = new Insets(13,0,0,0); break; case BOTTOM_RIGHT: insets = new Insets(13,0,0,13); break; case CENTER: insets = new Insets(5,0,0,5); break; default: insets = new Insets(0,0,0,0); } StackPane.setMargin(node, insets); sp.getChildren().add(node); StackPane.setAlignment(node, Pos.TOP_LEFT); } private Callback<TableColumn.CellDataFeatures<MappingItem, MappingItem>, ObservableValue<MappingItem>> mappingItemCellValueFactory = new Callback<TableColumn.CellDataFeatures<MappingItem, MappingItem>, ObservableValue<MappingItem>>() { @Override public ObservableValue<MappingItem> call(CellDataFeatures<MappingItem, MappingItem> param) { return new SimpleObjectProperty<MappingItem>(param.getValue()); } }; private Callback<TableColumn.CellDataFeatures<MappingSet, MappingSet>, ObservableValue<MappingSet>> mappingSetCellValueFactory = new Callback<TableColumn.CellDataFeatures<MappingSet, MappingSet>, ObservableValue<MappingSet>>() { @Override public ObservableValue<MappingSet> call(CellDataFeatures<MappingSet, MappingSet> param) { return new SimpleObjectProperty<MappingSet>(param.getValue()); } }; private Callback<TableColumn<MappingItem, MappingItem>, TableCell<MappingItem, MappingItem>> mappingItemCellFactory = new Callback<TableColumn<MappingItem, MappingItem>, TableCell<MappingItem, MappingItem>>() { @Override public TableCell<MappingItem, MappingItem> call(TableColumn<MappingItem, MappingItem> param) { return new TableCell<MappingItem, MappingItem>() { @Override public void updateItem(final MappingItem mappingItem, boolean empty) { super.updateItem(mappingItem, empty); updateCell(this, mappingItem); } }; } }; private Callback<TableColumn<MappingSet, MappingSet>, TableCell<MappingSet, MappingSet>> mappingSetCellFactory = new Callback<TableColumn<MappingSet, MappingSet>, TableCell<MappingSet, MappingSet>>() { @Override public TableCell<MappingSet, MappingSet> call(TableColumn<MappingSet, MappingSet> param) { return new TableCell<MappingSet, MappingSet>() { @Override public void updateItem(final MappingSet mappingSet, boolean empty) { super.updateItem(mappingSet, empty); updateCell(this, mappingSet); } }; } }; public static void setComboSelection(ComboBox<SimpleDisplayConcept> combo, String selectValue, int defaultIndex) { boolean found = false; if (selectValue != null && !selectValue.trim().equals("")) { for (SimpleDisplayConcept sdc : combo.getItems()) { if (sdc.getDescription().equals(selectValue)) { combo.getSelectionModel().select(sdc); found = true; break; } } } if (!found && defaultIndex >= 0 && defaultIndex < combo.getItems().size()) { combo.getSelectionModel().select(0); } } }
Always show compressed status column
mapping/src/main/java/gov/va/isaac/gui/mapping/MappingController.java
Always show compressed status column
<ide><path>apping/src/main/java/gov/va/isaac/gui/mapping/MappingController.java <ide> mappingItemTableView.setItems(mappingItems); <ide> mappingItemTableView.setPlaceholder(new Label("The selected Mapping Set contains no Mapping Items.")); <ide> <del> mappingItemListTitleLabel.setText("Members of " + mappingSet.getName()); <add> mappingItemListTitleLabel.setText(mappingSet.getName()); <ide> plusMappingItemButton.setDisable(false); <ide> minusMappingSetButton.setDisable(false); <ide> editMappingSetButton.setDisable(false); <ide> // TODO maybe come up with a way to preserve the selection, if possible. <ide> mappingSetTableView.getSelectionModel().clearSelection(); <ide> <del> mappingSetSTableColumn.setVisible(!activeOnly); <del> mappingItemSTableColumn.setVisible(!activeOnly); <del> <ide> refreshMappingItems(); <ide> } <ide> <ide> } <ide> }); <ide> <del> mappingSetSTableColumn.setVisible(false); <ide> mappingSetSTAMPTableColumn.setVisible(false); <ide> <ide> } <ide> <ide> mappingItemTableView.getSelectionModel().setSelectionMode(SelectionMode.MULTIPLE); <ide> <del> mappingItemSTableColumn.setVisible(false); <ide> mappingItemSTAMPTableColumn.setVisible(false); <ide> <ide> }
JavaScript
mit
1d815b99960c5d39d703165dfddc20548a9cef83
0
chrisle/brackets,ScalaInc/brackets,richmondgozarin/brackets,Jonavin/brackets,macdg/brackets,zhukaixy/brackets,2youyouo2/cocoslite,fvntr/brackets,ralic/brackets,MahadevanSrinivasan/brackets,treejames/brackets,jmarkina/brackets,Cartman0/brackets,weebygames/brackets,ashleygwilliams/brackets,pratts/brackets,srinivashappy/brackets,goldcase/brackets,netlams/brackets,cosmosgenius/brackets,ropik/brackets,siddharta1337/brackets,gwynndesign/brackets,MahadevanSrinivasan/brackets,albertinad/brackets,pkdevbox/brackets,alicoding/nimble,kolipka/brackets,kolipka/brackets,robertkarlsson/brackets,sophiacaspar/brackets,Live4Code/brackets,NickersF/brackets,youprofit/brackets,sgupta7857/brackets,simon66/brackets,wesleifreitas/brackets,adrianhartanto0/brackets,bidle/brackets,phillipalexander/brackets,udhayam/brackets,udhayam/brackets,Andrey-Pavlov/brackets,NGHGithub/brackets,show0017/brackets,m66n/brackets,veveykocute/brackets,Rynaro/brackets,thr0w/brackets,kilroy23/brackets,zaggino/brackets-electron,zLeonjo/brackets,mcanthony/brackets,Cartman0/brackets,sedge/nimble,ChaofengZhou/brackets,jacobnash/brackets,jiawenbo/brackets,pratts/brackets,RamirezWillow/brackets,MarcelGerber/brackets,jiimaho/brackets,chrismoulton/brackets,82488059/brackets,veveykocute/brackets,cdot-brackets-extensions/nimble-htmlLint,Wikunia/brackets,NickersF/brackets,mat-mcloughlin/brackets,zLeonjo/brackets,phillipalexander/brackets,SidBala/brackets,fcjailybo/brackets,alexkid64/brackets,chambej/brackets,jiimaho/brackets,L0g1k/brackets,Wikunia/brackets,dangkhue27/brackets,zaggino/brackets-electron,adobe/brackets,chambej/brackets,stowball/brackets,ficristo/brackets,NKcentinel/brackets,RamirezWillow/brackets,kilroy23/brackets,Denisov21/brackets,chinnyannieb/brackets,mcanthony/brackets,revi/brackets,revi/brackets,Mosoc/brackets,albertinad/brackets,pomadgw/brackets,SidBala/brackets,ls2uper/brackets,iamchathu/brackets,StephanieMak/brackets,abhisekp/brackets,GHackAnonymous/brackets,bidle/brackets,adobe/brackets,wakermahmud/brackets,dangkhue27/brackets,SidBala/brackets,tan9/brackets,humphd/brackets,sophiacaspar/brackets,andrewnc/brackets,thehogfather/brackets,Rajat-dhyani/brackets,jmarkina/brackets,show0017/brackets,JordanTheriault/brackets,petetnt/brackets,m66n/brackets,mcanthony/brackets,uwsd/brackets,Mosoc/brackets,eric-stanley/brackets,NGHGithub/brackets,mcanthony/brackets,zLeonjo/brackets,CapeSepias/brackets,mat-mcloughlin/brackets,dangkhue27/brackets,ForkedRepos/brackets,resir014/brackets,shal1y/brackets,gcommetti/brackets,m66n/brackets,cosmosgenius/brackets,wesleifreitas/brackets,Th30/brackets,youprofit/brackets,ecwebservices/brackets,lunode/brackets,robertkarlsson/brackets,srinivashappy/brackets,raygervais/brackets,fashionsun/brackets,MantisWare/brackets,chrisle/brackets,jiimaho/brackets,Denisov21/brackets,adrianhartanto0/brackets,arduino-org/ArduinoStudio,falcon1812/brackets,zLeonjo/brackets,rafaelstz/brackets,chrismoulton/brackets,shal1y/brackets,nucliweb/brackets,wangjun/brackets,FTG-003/brackets,hanmichael/brackets,ggusman/present,karevn/brackets,malinkie/brackets,lovewitty/brackets,robertkarlsson/brackets,wangjun/brackets,NGHGithub/brackets,Rynaro/brackets,TylerL-uxai/brackets,kolipka/brackets,dtcom/MyPSDBracket,riselabs-ufba/RiPLE-HC-ExperimentalData,lovewitty/brackets,Free-Technology-Guild/brackets,zhukaixy/brackets,Lojsan123/brackets,srinivashappy/brackets,chinnyannieb/brackets,netlams/brackets,andrewnc/brackets,agreco/brackets,Free-Technology-Guild/brackets,Rajat-dhyani/brackets,baig/brackets,weebygames/brackets,jiawenbo/brackets,gideonthomas/brackets,alicoding/nimble,Rynaro/brackets,ashleygwilliams/brackets,fastrde/brackets,wangjun/brackets,CapeSepias/brackets,Pomax/brackets,dangkhue27/brackets,GHackAnonymous/brackets,sprintr/brackets,ricciozhang/brackets,michaeljayt/brackets,goldcase/brackets,busykai/brackets,dangkhue27/brackets,TylerL-uxai/brackets,Rajat-dhyani/brackets,IAmAnubhavSaini/brackets,wesleifreitas/brackets,siddharta1337/brackets,Free-Technology-Guild/brackets,srhbinion/brackets,show0017/brackets,shal1y/brackets,sophiacaspar/brackets,dtcom/MyPSDBracket,ChaofengZhou/brackets,RamirezWillow/brackets,GHackAnonymous/brackets,SebastianBoyd/sebastianboyd.github.io-OLD,fabricadeaplicativos/brackets,JordanTheriault/brackets,emanziano/brackets,baig/brackets,gideonthomas/brackets,alexkid64/brackets,ficristo/brackets,srinivashappy/brackets,arduino-org/ArduinoStudio,kilroy23/brackets,Jonavin/brackets,abhisekp/brackets,rlugojr/brackets,massimiliano76/brackets,raygervais/brackets,fvntr/brackets,fcjailybo/brackets,cdot-brackets-extensions/nimble-htmlLint,fastrde/brackets,Pomax/brackets,fcjailybo/brackets,alicoding/nimble,revi/brackets,raygervais/brackets,keir-rex/brackets,gideonthomas/brackets,rlugojr/brackets,fabricadeaplicativos/brackets,gideonthomas/brackets,alexkid64/brackets,xantage/brackets,rafaelstz/brackets,eric-stanley/brackets,humphd/brackets,albertinad/brackets,falcon1812/brackets,ForkedRepos/brackets,fastrde/brackets,malinkie/brackets,fronzec/brackets,mozilla/brackets,Andrey-Pavlov/brackets,NGHGithub/brackets,Real-Currents/brackets,rafaelstz/brackets,CapeSepias/brackets,Denisov21/brackets,MantisWare/brackets,zaggino/brackets-electron,jmarkina/brackets,richmondgozarin/brackets,busykai/brackets,humphd/brackets,robertkarlsson/brackets,ecwebservices/brackets,gupta-tarun/brackets,ricciozhang/brackets,andrewnc/brackets,tan9/brackets,sophiacaspar/brackets,youprofit/brackets,jacobnash/brackets,jacobnash/brackets,chrismoulton/brackets,macdg/brackets,rafaelstz/brackets,revi/brackets,mozilla/brackets,brianjking/brackets,MantisWare/brackets,baig/brackets,NGHGithub/brackets,chrisle/brackets,shiyamkumar/brackets,Mosoc/brackets,mjurczyk/brackets,lovewitty/brackets,stowball/brackets,fronzec/brackets,fabricadeaplicativos/brackets,adrianhartanto0/brackets,sprintr/brackets,pkdevbox/brackets,Th30/brackets,quasto/ArduinoStudio,sedge/nimble,ficristo/brackets,ls2uper/brackets,kilroy23/brackets,chinnyannieb/brackets,brianjking/brackets,IAmAnubhavSaini/brackets,2youyouo2/cocoslite,show0017/brackets,phillipalexander/brackets,alexkid64/brackets,petetnt/brackets,hanmichael/brackets,ggusman/present,albertinad/brackets,thr0w/brackets,Andrey-Pavlov/brackets,RobertJGabriel/brackets,chrisle/brackets,RamirezWillow/brackets,JordanTheriault/brackets,agreco/brackets,ggusman/present,ralic/brackets,riselabs-ufba/RiPLE-HC-ExperimentalData,udhayam/brackets,iamchathu/brackets,Fcmam5/brackets,cosmosgenius/brackets,pomadgw/brackets,Free-Technology-Guild/brackets,revi/brackets,emanziano/brackets,gcommetti/brackets,IAmAnubhavSaini/brackets,alexkid64/brackets,netlams/brackets,Lojsan123/brackets,ecwebservices/brackets,fabricadeaplicativos/brackets,Wikunia/brackets,wakermahmud/brackets,sprintr/brackets,Fcmam5/brackets,Real-Currents/brackets,gcommetti/brackets,zLeonjo/brackets,chambej/brackets,gupta-tarun/brackets,Pomax/brackets,fvntr/brackets,ScalaInc/brackets,richmondgozarin/brackets,No9/brackets,fabricadeaplicativos/brackets,richmondgozarin/brackets,MarcelGerber/brackets,ForkedRepos/brackets,SidBala/brackets,ggusman/present,riselabs-ufba/RiPLE-HC-ExperimentalData,fastrde/brackets,NickersF/brackets,2youyouo2/cocoslite,sgupta7857/brackets,No9/brackets,goldcase/brackets,Real-Currents/brackets,wangjun/brackets,amrelnaggar/brackets,andrewnc/brackets,ecwebservices/brackets,NickersF/brackets,veveykocute/brackets,emanziano/brackets,flukeout/brackets,pomadgw/brackets,MarcelGerber/brackets,TylerL-uxai/brackets,stowball/brackets,Denisov21/brackets,ScalaInc/brackets,wakermahmud/brackets,adobe/brackets,massimiliano76/brackets,RobertJGabriel/brackets,cosmosgenius/brackets,falcon1812/brackets,siddharta1337/brackets,riselabs-ufba/RiPLE-HC-ExperimentalData,L0g1k/brackets,alicoding/nimble,pkdevbox/brackets,Rajat-dhyani/brackets,quasto/ArduinoStudio,chinnyannieb/brackets,nucliweb/brackets,raygervais/brackets,sgupta7857/brackets,Denisov21/brackets,falcon1812/brackets,stowball/brackets,ashleygwilliams/brackets,jacobnash/brackets,MantisWare/brackets,dtcom/MyPSDBracket,massimiliano76/brackets,simon66/brackets,NKcentinel/brackets,quasto/ArduinoStudio,Live4Code/brackets,Cartman0/brackets,adobe/brackets,kolipka/brackets,udhayam/brackets,simon66/brackets,chinnyannieb/brackets,busykai/brackets,veveykocute/brackets,Th30/brackets,srhbinion/brackets,rlugojr/brackets,wakermahmud/brackets,StephanieMak/brackets,TylerL-uxai/brackets,hanmichael/brackets,sgupta7857/brackets,lunode/brackets,mozilla/brackets,karevn/brackets,emanziano/brackets,shiyamkumar/brackets,karevn/brackets,macdg/brackets,abhisekp/brackets,FTG-003/brackets,lunode/brackets,resir014/brackets,brianjking/brackets,thehogfather/brackets,Cartman0/brackets,ForkedRepos/brackets,zhukaixy/brackets,wesleifreitas/brackets,m66n/brackets,eric-stanley/brackets,Cartman0/brackets,wakermahmud/brackets,fronzec/brackets,chrismoulton/brackets,Live4Code/brackets,iamchathu/brackets,goldcase/brackets,xantage/brackets,kilroy23/brackets,lunode/brackets,Lojsan123/brackets,amrelnaggar/brackets,Wikunia/brackets,thr0w/brackets,ralic/brackets,resir014/brackets,jiawenbo/brackets,srhbinion/brackets,udhayam/brackets,tan9/brackets,uwsd/brackets,IAmAnubhavSaini/brackets,Th30/brackets,busykai/brackets,y12uc231/brackets,SebastianBoyd/sebastianboyd.github.io-OLD,phillipalexander/brackets,richmondgozarin/brackets,emanziano/brackets,pomadgw/brackets,mjurczyk/brackets,srhbinion/brackets,Rynaro/brackets,jiimaho/brackets,ecwebservices/brackets,sedge/nimble,RobertJGabriel/brackets,lovewitty/brackets,treejames/brackets,fvntr/brackets,GHackAnonymous/brackets,falcon1812/brackets,fashionsun/brackets,ChaofengZhou/brackets,StephanieMak/brackets,ChaofengZhou/brackets,abhisekp/brackets,arduino-org/ArduinoStudio,Th30/brackets,pkdevbox/brackets,CapeSepias/brackets,82488059/brackets,y12uc231/brackets,xantage/brackets,malinkie/brackets,sprintr/brackets,mozilla/brackets,Pomax/brackets,adrianhartanto0/brackets,fvntr/brackets,Wikunia/brackets,ForkedRepos/brackets,amrelnaggar/brackets,GHackAnonymous/brackets,rlugojr/brackets,robertkarlsson/brackets,petetnt/brackets,SebastianBoyd/sebastianboyd.github.io-OLD,weebygames/brackets,mcanthony/brackets,gwynndesign/brackets,abhisekp/brackets,wangjun/brackets,ScalaInc/brackets,nucliweb/brackets,riselabs-ufba/RiPLE-HC-ExperimentalData,andrewnc/brackets,No9/brackets,mat-mcloughlin/brackets,nucliweb/brackets,srinivashappy/brackets,goldcase/brackets,cdot-brackets-extensions/nimble-htmlLint,StephanieMak/brackets,2youyouo2/cocoslite,shal1y/brackets,gwynndesign/brackets,Live4Code/brackets,sprintr/brackets,brianjking/brackets,keir-rex/brackets,youprofit/brackets,weebygames/brackets,L0g1k/brackets,eric-stanley/brackets,michaeljayt/brackets,pratts/brackets,Free-Technology-Guild/brackets,wesleifreitas/brackets,NKcentinel/brackets,tan9/brackets,mozilla/brackets,adobe/brackets,ricciozhang/brackets,NickersF/brackets,fashionsun/brackets,thehogfather/brackets,ashleygwilliams/brackets,veveykocute/brackets,weebygames/brackets,fcjailybo/brackets,treejames/brackets,Lojsan123/brackets,michaeljayt/brackets,L0g1k/brackets,fashionsun/brackets,MahadevanSrinivasan/brackets,CapeSepias/brackets,fashionsun/brackets,zaggino/brackets-electron,ficristo/brackets,netlams/brackets,Andrey-Pavlov/brackets,stowball/brackets,ChaofengZhou/brackets,shiyamkumar/brackets,NKcentinel/brackets,jiimaho/brackets,iamchathu/brackets,resir014/brackets,jmarkina/brackets,ropik/brackets,ropik/brackets,srhbinion/brackets,sophiacaspar/brackets,brianjking/brackets,thr0w/brackets,simon66/brackets,uwsd/brackets,ricciozhang/brackets,humphd/brackets,RobertJGabriel/brackets,busykai/brackets,m66n/brackets,mjurczyk/brackets,thr0w/brackets,cdot-brackets-extensions/nimble-htmlLint,marcominetti/brackets,mjurczyk/brackets,Lojsan123/brackets,treejames/brackets,ralic/brackets,zaggino/brackets-electron,zhukaixy/brackets,JordanTheriault/brackets,fronzec/brackets,flukeout/brackets,mjurczyk/brackets,Pomax/brackets,michaeljayt/brackets,y12uc231/brackets,gupta-tarun/brackets,bidle/brackets,gcommetti/brackets,ls2uper/brackets,fronzec/brackets,thehogfather/brackets,FTG-003/brackets,petetnt/brackets,malinkie/brackets,2youyouo2/cocoslite,thehogfather/brackets,netlams/brackets,rlugojr/brackets,dtcom/MyPSDBracket,baig/brackets,jiawenbo/brackets,82488059/brackets,keir-rex/brackets,Jonavin/brackets,82488059/brackets,Fcmam5/brackets,petetnt/brackets,karevn/brackets,flukeout/brackets,agreco/brackets,massimiliano76/brackets,macdg/brackets,quasto/ArduinoStudio,arduino-org/ArduinoStudio,lovewitty/brackets,arduino-org/ArduinoStudio,ficristo/brackets,massimiliano76/brackets,ls2uper/brackets,zaggino/brackets-electron,shiyamkumar/brackets,Real-Currents/brackets,amrelnaggar/brackets,youprofit/brackets,ralic/brackets,bidle/brackets,simon66/brackets,fastrde/brackets,pratts/brackets,MahadevanSrinivasan/brackets,siddharta1337/brackets,chambej/brackets,chambej/brackets,jmarkina/brackets,StephanieMak/brackets,RamirezWillow/brackets,SebastianBoyd/sebastianboyd.github.io-OLD,MantisWare/brackets,humphd/brackets,phillipalexander/brackets,Fcmam5/brackets,uwsd/brackets,keir-rex/brackets,resir014/brackets,fcjailybo/brackets,jacobnash/brackets,ricciozhang/brackets,Live4Code/brackets,siddharta1337/brackets,keir-rex/brackets,gupta-tarun/brackets,tan9/brackets,kolipka/brackets,riselabs-ufba/RiPLE-HC-ExperimentalData,shal1y/brackets,Jonavin/brackets,IAmAnubhavSaini/brackets,chrisle/brackets,agreco/brackets,pratts/brackets,marcominetti/brackets,MahadevanSrinivasan/brackets,y12uc231/brackets,flukeout/brackets,Real-Currents/brackets,sedge/nimble,Jonavin/brackets,RobertJGabriel/brackets,bidle/brackets,No9/brackets,nucliweb/brackets,hanmichael/brackets,iamchathu/brackets,pomadgw/brackets,uwsd/brackets,gcommetti/brackets,xantage/brackets,MarcelGerber/brackets,ashleygwilliams/brackets,y12uc231/brackets,gwynndesign/brackets,FTG-003/brackets,Rynaro/brackets,82488059/brackets,sgupta7857/brackets,malinkie/brackets,gupta-tarun/brackets,SidBala/brackets,xantage/brackets,quasto/ArduinoStudio,zhukaixy/brackets,gideonthomas/brackets,pkdevbox/brackets,chrismoulton/brackets,Fcmam5/brackets,Rajat-dhyani/brackets,raygervais/brackets,Mosoc/brackets,treejames/brackets,hanmichael/brackets,ropik/brackets,sedge/nimble,mat-mcloughlin/brackets,macdg/brackets,JordanTheriault/brackets,Mosoc/brackets,ScalaInc/brackets,lunode/brackets,eric-stanley/brackets,amrelnaggar/brackets,rafaelstz/brackets,karevn/brackets,NKcentinel/brackets,TylerL-uxai/brackets,ls2uper/brackets,SebastianBoyd/sebastianboyd.github.io-OLD,albertinad/brackets,Real-Currents/brackets,FTG-003/brackets,MarcelGerber/brackets,baig/brackets,No9/brackets,adrianhartanto0/brackets,michaeljayt/brackets,flukeout/brackets,jiawenbo/brackets,shiyamkumar/brackets,Andrey-Pavlov/brackets
/* * Copyright (c) 2013 Adobe Systems Incorporated. All rights reserved. * * Permission is hereby granted, free of charge, to any person obtaining a * copy of this software and associated documentation files (the "Software"), * to deal in the Software without restriction, including without limitation * the rights to use, copy, modify, merge, publish, distribute, sublicense, * and/or sell copies of the Software, and to permit persons to whom the * Software is furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER * DEALINGS IN THE SOFTWARE. * */ /*jslint vars: true, plusplus: true, devel: true, nomen: true, regexp: true, indent: 4, maxerr: 50 */ /*global define, $, setTimeout */ define(function (require, exports, module) { "use strict"; var Directory = require("filesystem/Directory"), File = require("filesystem/File"), FileIndex = require("filesystem/FileIndex"); /** * Constructor. FileSystem objects should not be constructed directly. * Use FileSystemManager.createFileSystem() instead. * The FileSystem is not usable until init() signals its callback. * @param {!FileSystemImpl} impl Low-level file system implementation to use. */ function FileSystem(impl, system) { this._impl = impl; this._system = system; // Create a file index this._index = new FileIndex(); // Initialize the set of watched roots this._watchedRoots = {}; // Initialize the watch/unwatch request queue this._watchRequests = []; } /** * The low-level file system implementation used by this object. * This is set in the constructor and cannot be changed. */ FileSystem.prototype._impl = null; /** * The name of the low-level file system implementation used by this object. * This is set in the constructor and cannot be changed. */ FileSystem.prototype._system = null; /** * The FileIndex used by this object. This is initialized in the constructor. */ FileSystem.prototype._index = null; /** * The queue of pending watch/unwatch requests. * @type {Array.<{fn: function(), cb: function()}>} */ FileSystem.prototype._watchRequests = null; /** * Dequeue and process all pending watch/unwatch requests */ FileSystem.prototype._dequeueWatchRequest = function () { if (this._watchRequests.length > 0) { var request = this._watchRequests[0]; request.fn.call(null, function () { // Apply the given callback var callbackArgs = arguments; setTimeout(function () { request.cb.apply(null, callbackArgs); }, 0); // Process the remaining watch/unwatch requests this._watchRequests.shift(); this._dequeueWatchRequest(); }.bind(this)); } }; /** * Enqueue a new watch/unwatch request. * * @param {function()} fn - The watch/unwatch request function. * @param {callback()} cb - The callback for the provided watch/unwatch * request function. */ FileSystem.prototype._enqueueWatchRequest = function (fn, cb) { // Enqueue the given watch/unwatch request this._watchRequests.push({fn: fn, cb: cb}); // Begin processing the queue if it is not already being processed if (this._watchRequests.length === 1) { this._dequeueWatchRequest(); } }; /** * The set of watched roots, encoded as a mapping from full paths to objects * which contain a file entry, filter function, and change handler function. * * @type{Object.<string, Object.<entry: FileSystemEntry, * filter: function(entry): boolean, * handleChange: function(entry)>>} */ FileSystem.prototype._watchedRoots = null; /** * Watch a filesystem entry beneath a given watchedRoot. * * @param {FileSystemEntry} entry - The FileSystemEntry to watch. Must be a * non-strict descendent of watchedRoot.entry. * @param {Object} watchedRoot - See FileSystem._watchedRoots. * @param {function(?string)} callback - A function that is called once the * watch is complete. */ FileSystem.prototype._watchEntry = function (entry, watchedRoot, callback) { var watchFn = entry.visit.bind(entry, function (child) { if (child.isDirectory() || child === watchedRoot.entry) { this._impl.watchPath(child.fullPath); } return watchedRoot.filter(child); }.bind(this)); this._enqueueWatchRequest(watchFn, callback); }; /** * Unwatch a filesystem entry beneath a given watchedRoot. * * @param {FileSystemEntry} entry - The FileSystemEntry to watch. Must be a * non-strict descendent of watchedRoot.entry. * @param {Object} watchedRoot - See FileSystem._watchedRoots. * @param {function(?string)} callback - A function that is called once the * watch is complete. */ FileSystem.prototype._unwatchEntry = function (entry, watchedRoot, callback) { var watchFn = entry.visit.bind(entry, function (child) { if (child.isDirectory() || child === watchedRoot.entry) { this._impl.unwatchPath(child.fullPath); } this._index.removeEntry(child); return watchedRoot.filter(child); }.bind(this)); this._enqueueWatchRequest(watchFn, callback); }; /** * @param {function(?err)} callback */ FileSystem.prototype.init = function (callback) { this._impl.init(callback); // Initialize watchers this._impl.initWatchers(this._watcherCallback.bind(this)); }; /** * The name of the low-level file system implementation used by this object. */ FileSystem.prototype.getSystemName = function () { return this._system; }; /** * Close a file system. Clear all caches, indexes, and file watchers. */ FileSystem.prototype.close = function () { this._impl.unwatchAll(); this._index.clear(); }; /** * Returns false for files and directories that are not commonly useful to display. * * @param {string} path File or directory to filter * @return boolean true if the file should be displayed */ var _exclusionListRegEx = /\.pyc$|^\.git$|^\.gitignore$|^\.gitmodules$|^\.svn$|^\.DS_Store$|^Thumbs\.db$|^\.hg$|^CVS$|^\.cvsignore$|^\.gitattributes$|^\.hgtags$|^\.hgignore$/; FileSystem.prototype.shouldShow = function (path) { var name = path.substr(path.lastIndexOf("/") + 1); return !name.match(_exclusionListRegEx); }; /** * Returns a canonical version of the path: no duplicated "/"es, no ".."s, * and directories guaranteed to end in a trailing "/" * @param {!string} path Absolute path, using "/" as path separator * @param {boolean=} isDirectory * @return {!string} */ function _normalizePath(path, isDirectory) { console.assert(path[0] === "/" || path[1] === ":"); // expect only absolute paths // Remove duplicated "/"es path = path.replace(/\/{2,}/g, "/"); // Remove ".." segments if (path.indexOf("..") !== -1) { var segments = path.split("/"), i; for (i = 1; i < segments.length; i++) { if (segments[i] === "..") { if (i < 2) { throw new Error("Invalid absolute path: '" + path + "'"); } segments.splice(i - 1, 2); i -= 2; // compensate so we start on the right index next iteration } } path = segments.join("/"); } if (isDirectory) { // Make sure path DOES include trailing slash if (path[path.length - 1] !== "/") { path += "/"; } } return path; } /** * Return a File object for the specified path. * * @param {string} path Path of file. * * @return {File} The File object. This file may not yet exist on disk. */ FileSystem.prototype.getFileForPath = function (path) { path = _normalizePath(path, false); var file = this._index.getEntry(path); if (!file) { file = new File(path, this); this._index.addEntry(file); } return file; }; /** * Return a Directory object for the specified path. * * @param {string} path Path of directory. Pass NULL to get the root directory. * * @return {Directory} The Directory object. This directory may not yet exist on disk. */ FileSystem.prototype.getDirectoryForPath = function (path) { path = _normalizePath(path, true); var directory = this._index.getEntry(path); if (!directory) { directory = new Directory(path, this); this._index.addEntry(directory); } return directory; }; /** * Resolve a path. * * @param {string} path The path to resolve * @param {function (err, object)} callback */ FileSystem.prototype.resolve = function (path, callback) { // No need to normalize path here: assume underlying stat() does it internally, // and it will be normalized anyway when ingested by get*ForPath() afterward this._impl.stat(path, function (err, stat) { var item; if (!err) { if (stat.isFile()) { item = this.getFileForPath(path); } else { item = this.getDirectoryForPath(path); } } callback(err, item); }.bind(this)); }; /** * @private * Notify the system when an entry name has changed. * * @param {string} oldName * @param {string} newName * @param {boolean} isDirectory */ FileSystem.prototype._entryRenamed = function (oldName, newName, isDirectory) { // Update all affected entries in the index this._index.entryRenamed(oldName, newName, isDirectory); $(this).trigger("rename", [oldName, newName]); console.log("rename: ", oldName, newName); }; /** * Show an "Open" dialog and return the file(s)/directories selected by the user. * * @param {boolean} allowMultipleSelection Allows selecting more than one file at a time * @param {boolean} chooseDirectories Allows directories to be opened * @param {string} title The title of the dialog * @param {string} initialPath The folder opened inside the window initially. If initialPath * is not set, or it doesn't exist, the window would show the last * browsed folder depending on the OS preferences * @param {Array.<string>} fileTypes List of extensions that are allowed to be opened. A null value * allows any extension to be selected. * @param {function (number, array)} callback Callback resolved with the selected file(s)/directories. */ FileSystem.prototype.showOpenDialog = function (allowMultipleSelection, chooseDirectories, title, initialPath, fileTypes, callback) { this._impl.showOpenDialog(allowMultipleSelection, chooseDirectories, title, initialPath, fileTypes, callback); }; /** * Show a "Save" dialog and return the path of the file to save. * * @param {string} title The title of the dialog. * @param {string} initialPath The folder opened inside the window initially. If initialPath * is not set, or it doesn't exist, the window would show the last * browsed folder depending on the OS preferences. * @param {string} proposedNewFilename Provide a new file name for the user. This could be based on * on the current file name plus an additional suffix * @param {function (number, string)} callback Callback that is called with the name of the file to save. */ FileSystem.prototype.showSaveDialog = function (title, initialPath, proposedNewFilename, callback) { this._impl.showSaveDialog(title, initialPath, proposedNewFilename, callback); }; /** * @private * Callback for file/directory watchers. This is called by the low-level implementation * whenever a directory or file is changed. * * @param {string} path The path that changed. This could be a file or a directory. * @param {stat=} stat Optional stat for the item that changed. This param is not always * passed. */ FileSystem.prototype._watcherCallback = function (path, stat) { if (!this._index) { return; } path = _normalizePath(path, false); var entry = this._index.getEntry(path); var fireChangeEvent = function () { // Trigger a change event $(this).trigger("change", entry); console.log("change: ", entry); }.bind(this); if (entry) { if (entry.isFile()) { // Update stat and clear contents, but only if out of date if (!stat || !entry._stat || (stat.mtime !== entry._stat.mtime)) { entry._stat = stat; entry._contents = undefined; } fireChangeEvent(); } else { var oldContents = entry._contents || []; // Clear out old contents entry._contents = undefined; var watchedRootPath = null, allWatchedRootPaths = Object.keys(this._watchedRoots), isRootWatched = allWatchedRootPaths.some(function (rootPath) { if (entry.fullPath.indexOf(rootPath) === 0) { watchedRootPath = rootPath; return true; } }), watchedRoot = isRootWatched ? this._watchedRoots[watchedRootPath] : null; if (!watchedRoot) { console.warn("Received change notification for unwatched path: ", path); return; } // Update changed entries entry.getContents(function (err, contents) { var addNewEntries = function (callback) { // Check for added directories and scan to add to index // Re-scan this directory to add any new contents var entriesToAdd = contents.filter(function (entry) { return oldContents.indexOf(entry) === -1; }); var addCounter = entriesToAdd.length; if (addCounter === 0) { callback(); } else { entriesToAdd.forEach(function (entry) { this._watchEntry(entry, watchedRoot, function (err) { if (--addCounter === 0) { callback(); } }); }, this); } }.bind(this); var removeOldEntries = function (callback) { var entriesToRemove = oldContents.filter(function (entry) { return contents.indexOf(entry) === -1; }); var removeCounter = entriesToRemove.length; if (removeCounter === 0) { callback(); } else { entriesToRemove.forEach(function (entry) { this._unwatchEntry(entry, watchedRoot, function (err) { if (--removeCounter === 0) { callback(); } }); }, this); } }.bind(this); if (err) { console.warn("Unable to get contents of changed directory: ", path, err); } else { removeOldEntries(function () { addNewEntries(fireChangeEvent); }); } }.bind(this)); } } }; /** * Start watching a filesystem root entry. * * @param {FileSystemEntry} entry - The root entry to watch. If entry is a directory, * all subdirectories that aren't explicitly filtered will also be watched. * @param {function(FileSystemEntry): boolean} filter - A function to determine whether * a particular FileSystemEntry should be watched or ignored. * @param {function(FileSystemEntry)} handleChange - A function that is called whenever * a particular FileSystemEntry is changed. * @param {function(?string)} callback - A function that is called when the watch has * completed. If the watch fails, the function will have a non-null parameter * that describes the error. */ FileSystem.prototype.watch = function (entry, filter, handleChange, callback) { var fullPath = entry.fullPath, watchedRoot = { entry: entry, filter: filter, handleChange: handleChange }; var watchingParentRoot = Object.keys(this._watchedRoots).some(function (path) { var watchedRoot = this._watchedRoots[path], watchedPath = watchedRoot.entry.fullPath; return fullPath.indexOf(watchedPath) === 0; }, this); if (watchingParentRoot) { callback("A parent of this root is already watched"); return; } var watchingChildRoot = Object.keys(this._watchedRoots).some(function (path) { var watchedRoot = this._watchedRoots[path], watchedPath = watchedRoot.entry.fullPath; return watchedPath.indexOf(fullPath) === 0; }, this); if (watchingChildRoot) { callback("A child of this root is already watched"); return; } this._watchedRoots[fullPath] = watchedRoot; this._watchEntry(entry, watchedRoot, function (err) { if (err) { console.warn("Failed to watch root: ", entry.fullPath, err); return; } callback(null); }.bind(this)); }; /** * Stop watching a filesystem root entry. * * @param {FileSystemEntry} entry - The root entry to stop watching. The unwatch will * if the entry is not currently being watched. * @param {function(?string)} callback - A function that is called when the unwatch has * completed. If the unwatch fails, the function will have a non-null parameter * that describes the error. */ FileSystem.prototype.unwatch = function (entry, callback) { var fullPath = entry.fullPath, watchedRoot = this._watchedRoots[fullPath]; if (!watchedRoot) { callback("Root is not watched."); return; } delete this._watchedRoots[fullPath]; this._unwatchEntry(entry, watchedRoot, function (err) { if (err) { console.warn("Failed to unwatch root: ", entry.fullPath, err); callback(err); return; } callback(null); }.bind(this)); }; // Export the FileSystem class module.exports = FileSystem; });
src/filesystem/FileSystem.js
/* * Copyright (c) 2013 Adobe Systems Incorporated. All rights reserved. * * Permission is hereby granted, free of charge, to any person obtaining a * copy of this software and associated documentation files (the "Software"), * to deal in the Software without restriction, including without limitation * the rights to use, copy, modify, merge, publish, distribute, sublicense, * and/or sell copies of the Software, and to permit persons to whom the * Software is furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER * DEALINGS IN THE SOFTWARE. * */ /*jslint vars: true, plusplus: true, devel: true, nomen: true, regexp: true, indent: 4, maxerr: 50 */ /*global define, $, setTimeout */ define(function (require, exports, module) { "use strict"; var Directory = require("filesystem/Directory"), File = require("filesystem/File"), FileIndex = require("filesystem/FileIndex"); /** * Constructor. FileSystem objects should not be constructed directly. * Use FileSystemManager.createFileSystem() instead. * The FileSystem is not usable until init() signals its callback. * @param {!FileSystemImpl} impl Low-level file system implementation to use. */ function FileSystem(impl, system) { this._impl = impl; this._system = system; // Create a file index this._index = new FileIndex(); // Initialize the set of watched roots this._watchedRoots = {}; // Initialize the watch/unwatch request queue this._watchRequests = []; } /** * The low-level file system implementation used by this object. * This is set in the constructor and cannot be changed. */ FileSystem.prototype._impl = null; /** * The name of the low-level file system implementation used by this object. * This is set in the constructor and cannot be changed. */ FileSystem.prototype._system = null; /** * The FileIndex used by this object. This is initialized in the constructor. */ FileSystem.prototype._index = null; /** * The queue of pending watch/unwatch requests. * @type {Array.<{fn: function(), cb: function()}>} */ FileSystem.prototype._watchRequests = null; /** * Dequeue and process all pending watch/unwatch requests */ FileSystem.prototype._dequeueWatchRequest = function () { if (this._watchRequests.length > 0) { var request = this._watchRequests[0]; request.fn.call(null, function () { // Apply the given callback var callbackArgs = arguments; setTimeout(function () { request.cb.apply(null, callbackArgs); }, 0); // Process the remaining watch/unwatch requests this._watchRequests.shift(); this._dequeueWatchRequest(); }.bind(this)); } }; /** * Enqueue a new watch/unwatch request. * * @param {function()} fn - The watch/unwatch request function. * @param {callback()} cb - The callback for the provided watch/unwatch * request function. */ FileSystem.prototype._enqueueWatchRequest = function (fn, cb) { // Enqueue the given watch/unwatch request this._watchRequests.push({fn: fn, cb: cb}); // Begin processing the queue if it is not already being processed if (this._watchRequests.length === 1) { this._dequeueWatchRequest(); } }; /** * The set of watched roots, encoded as a mapping from full paths to objects * which contain a file entry, filter function, and change handler function. * * @type{Object.<string, Object.<entry: FileSystemEntry, * filter: function(entry): boolean, * handleChange: function(entry)>>} */ FileSystem.prototype._watchedRoots = null; /** * Watch a filesystem entry beneath a given watchedRoot. * * @param {FileSystemEntry} entry - The FileSystemEntry to watch. Must be a * non-strict descendent of watchedRoot.entry. * @param {Object} watchedRoot - See FileSystem._watchedRoots. * @param {function(?string)} callback - A function that is called once the * watch is complete. */ FileSystem.prototype._watchEntry = function (entry, watchedRoot, callback) { var watchFn = entry.visit.bind(entry, function (child) { if (child.isDirectory() || child === watchedRoot.entry) { this._impl.watchPath(child.fullPath); } return watchedRoot.filter(child); }.bind(this)); this._enqueueWatchRequest(watchFn, callback); }; /** * Unwatch a filesystem entry beneath a given watchedRoot. * * @param {FileSystemEntry} entry - The FileSystemEntry to watch. Must be a * non-strict descendent of watchedRoot.entry. * @param {Object} watchedRoot - See FileSystem._watchedRoots. * @param {function(?string)} callback - A function that is called once the * watch is complete. */ FileSystem.prototype._unwatchEntry = function (entry, watchedRoot, callback) { var watchFn = entry.visit.bind(entry, function (child) { if (child.isDirectory() || child === watchedRoot.entry) { this._impl.unwatchPath(child.fullPath); } this._index.removeEntry(child); return watchedRoot.filter(child); }.bind(this)); this._enqueueWatchRequest(watchFn, callback); }; /** * @param {function(?err)} callback */ FileSystem.prototype.init = function (callback) { this._impl.init(callback); // Initialize watchers this._impl.initWatchers(this._watcherCallback.bind(this)); }; /** * The name of the low-level file system implementation used by this object. */ FileSystem.prototype.getSystemName = function () { return this._system; }; /** * Close a file system. Clear all caches, indexes, and file watchers. */ FileSystem.prototype.close = function () { this._impl.unwatchAll(); this._index.clear(); }; /** * Returns false for files and directories that are not commonly useful to display. * * @param {string} path File or directory to filter * @return boolean true if the file should be displayed */ var _exclusionListRegEx = /\.pyc$|^\.git$|^\.gitignore$|^\.gitmodules$|^\.svn$|^\.DS_Store$|^Thumbs\.db$|^\.hg$|^CVS$|^\.cvsignore$|^\.gitattributes$|^\.hgtags$|^\.hgignore$/; FileSystem.prototype.shouldShow = function (path) { var name = path.substr(path.lastIndexOf("/") + 1); return !name.match(_exclusionListRegEx); }; /** * Returns a canonical version of the path: no duplicated "/"es, no ".."s, * and directories guaranteed to end in a trailing "/" * @param {!string} path Absolute path, using "/" as path separator * @param {boolean=} isDirectory * @return {!string} */ function _normalizePath(path, isDirectory) { console.assert(path[0] === "/" || path[1] === ":"); // expect only absolute paths // Remove duplicated "/"es path = path.replace(/\/{2,}/g, "/"); // Remove ".." segments if (path.indexOf("..") !== -1) { var segments = path.split("/"), i; for (i = 1; i < segments.length; i++) { if (segments[i] === "..") { if (i < 2) { throw new Error("Invalid absolute path: '" + path + "'"); } segments.splice(i - 1, 2); i -= 2; // compensate so we start on the right index next iteration } } path = segments.join("/"); } if (isDirectory) { // Make sure path DOES include trailing slash if (path[path.length - 1] !== "/") { path += "/"; } } return path; } /** * Return a File object for the specified path. * * @param {string} path Path of file. * * @return {File} The File object. This file may not yet exist on disk. */ FileSystem.prototype.getFileForPath = function (path) { path = _normalizePath(path, false); var file = this._index.getEntry(path); if (!file) { file = new File(path, this); this._index.addEntry(file); } return file; }; /** * Return a Directory object for the specified path. * * @param {string} path Path of directory. Pass NULL to get the root directory. * * @return {Directory} The Directory object. This directory may not yet exist on disk. */ FileSystem.prototype.getDirectoryForPath = function (path) { path = _normalizePath(path, true); var directory = this._index.getEntry(path); if (!directory) { directory = new Directory(path, this); this._index.addEntry(directory); } return directory; }; /** * Resolve a path. * * @param {string} path The path to resolve * @param {function (err, object)} callback */ FileSystem.prototype.resolve = function (path, callback) { // No need to normalize path here: assume underlying stat() does it internally, // and it will be normalized anyway when ingested by get*ForPath() afterward this._impl.stat(path, function (err, stat) { var item; if (!err) { if (stat.isFile()) { item = this.getFileForPath(path); } else { item = this.getDirectoryForPath(path); } } callback(err, item); }.bind(this)); }; /** * @private * Notify the system when an entry name has changed. * * @param {string} oldName * @param {string} newName * @param {boolean} isDirectory */ FileSystem.prototype._entryRenamed = function (oldName, newName, isDirectory) { // Update all affected entries in the index this._index.entryRenamed(oldName, newName, isDirectory); $(this).trigger("rename", [oldName, newName]); console.log("rename: ", oldName, newName); }; /** * Show an "Open" dialog and return the file(s)/directories selected by the user. * * @param {boolean} allowMultipleSelection Allows selecting more than one file at a time * @param {boolean} chooseDirectories Allows directories to be opened * @param {string} title The title of the dialog * @param {string} initialPath The folder opened inside the window initially. If initialPath * is not set, or it doesn't exist, the window would show the last * browsed folder depending on the OS preferences * @param {Array.<string>} fileTypes List of extensions that are allowed to be opened. A null value * allows any extension to be selected. * @param {function (number, array)} callback Callback resolved with the selected file(s)/directories. */ FileSystem.prototype.showOpenDialog = function (allowMultipleSelection, chooseDirectories, title, initialPath, fileTypes, callback) { this._impl.showOpenDialog(allowMultipleSelection, chooseDirectories, title, initialPath, fileTypes, callback); }; /** * Show a "Save" dialog and return the path of the file to save. * * @param {string} title The title of the dialog. * @param {string} initialPath The folder opened inside the window initially. If initialPath * is not set, or it doesn't exist, the window would show the last * browsed folder depending on the OS preferences. * @param {string} proposedNewFilename Provide a new file name for the user. This could be based on * on the current file name plus an additional suffix * @param {function (number, string)} callback Callback that is called with the name of the file to save. */ FileSystem.prototype.showSaveDialog = function (title, initialPath, proposedNewFilename, callback) { this._impl.showSaveDialog(title, initialPath, proposedNewFilename, callback); }; /** * @private * Callback for file/directory watchers. This is called by the low-level implementation * whenever a directory or file is changed. * * @param {string} path The path that changed. This could be a file or a directory. * @param {stat=} stat Optional stat for the item that changed. This param is not always * passed. */ FileSystem.prototype._watcherCallback = function (path, stat) { if (!this._index) { return; } var entry = this._index.getEntry(path); var fireChangeEvent = function () { // Trigger a change event $(this).trigger("change", entry); console.log("change: ", entry); }.bind(this); if (entry) { if (entry.isFile()) { // Update stat and clear contents, but only if out of date if (!stat || !entry._stat || (stat.mtime !== entry._stat.mtime)) { entry._stat = stat; entry._contents = undefined; } fireChangeEvent(); } else { var oldContents = entry._contents || []; // Clear out old contents entry._contents = undefined; var watchedRootPath = null, allWatchedRootPaths = Object.keys(this._watchedRoots), isRootWatched = allWatchedRootPaths.some(function (rootPath) { if (entry.fullPath.indexOf(rootPath) === 0) { watchedRootPath = rootPath; return true; } }), watchedRoot = isRootWatched ? this._watchedRoots[watchedRootPath] : null; if (!watchedRoot) { console.warn("Received change notification for unwatched path: ", path); return; } // Update changed entries entry.getContents(function (err, contents) { var addNewEntries = function (callback) { // Check for added directories and scan to add to index // Re-scan this directory to add any new contents var entriesToAdd = contents.filter(function (entry) { return oldContents.indexOf(entry) === -1; }); var addCounter = entriesToAdd.length; if (addCounter === 0) { callback(); } else { entriesToAdd.forEach(function (entry) { this._watchEntry(entry, watchedRoot, function (err) { if (--addCounter === 0) { callback(); } }); }, this); } }.bind(this); var removeOldEntries = function (callback) { var entriesToRemove = oldContents.filter(function (entry) { return contents.indexOf(entry) === -1; }); var removeCounter = entriesToRemove.length; if (removeCounter === 0) { callback(); } else { entriesToRemove.forEach(function (entry) { this._unwatchEntry(entry, watchedRoot, function (err) { if (--removeCounter === 0) { callback(); } }); }, this); } }.bind(this); if (err) { console.warn("Unable to get contents of changed directory: ", path, err); } else { removeOldEntries(function () { addNewEntries(fireChangeEvent); }); } }.bind(this)); } } }; /** * Start watching a filesystem root entry. * * @param {FileSystemEntry} entry - The root entry to watch. If entry is a directory, * all subdirectories that aren't explicitly filtered will also be watched. * @param {function(FileSystemEntry): boolean} filter - A function to determine whether * a particular FileSystemEntry should be watched or ignored. * @param {function(FileSystemEntry)} handleChange - A function that is called whenever * a particular FileSystemEntry is changed. * @param {function(?string)} callback - A function that is called when the watch has * completed. If the watch fails, the function will have a non-null parameter * that describes the error. */ FileSystem.prototype.watch = function (entry, filter, handleChange, callback) { var fullPath = entry.fullPath, watchedRoot = { entry: entry, filter: filter, handleChange: handleChange }; var watchingParentRoot = Object.keys(this._watchedRoots).some(function (path) { var watchedRoot = this._watchedRoots[path], watchedPath = watchedRoot.entry.fullPath; return fullPath.indexOf(watchedPath) === 0; }, this); if (watchingParentRoot) { callback("A parent of this root is already watched"); return; } var watchingChildRoot = Object.keys(this._watchedRoots).some(function (path) { var watchedRoot = this._watchedRoots[path], watchedPath = watchedRoot.entry.fullPath; return watchedPath.indexOf(fullPath) === 0; }, this); if (watchingChildRoot) { callback("A child of this root is already watched"); return; } this._watchedRoots[fullPath] = watchedRoot; this._watchEntry(entry, watchedRoot, function (err) { if (err) { console.warn("Failed to watch root: ", entry.fullPath, err); return; } callback(null); }.bind(this)); }; /** * Stop watching a filesystem root entry. * * @param {FileSystemEntry} entry - The root entry to stop watching. The unwatch will * if the entry is not currently being watched. * @param {function(?string)} callback - A function that is called when the unwatch has * completed. If the unwatch fails, the function will have a non-null parameter * that describes the error. */ FileSystem.prototype.unwatch = function (entry, callback) { var fullPath = entry.fullPath, watchedRoot = this._watchedRoots[fullPath]; if (!watchedRoot) { callback("Root is not watched."); return; } delete this._watchedRoots[fullPath]; this._unwatchEntry(entry, watchedRoot, function (err) { if (err) { console.warn("Failed to unwatch root: ", entry.fullPath, err); callback(err); return; } callback(null); }.bind(this)); }; // Export the FileSystem class module.exports = FileSystem; });
Fix *file* watching on Windows: normalize out doubled "/"es in paths received from Node-side watcher impl
src/filesystem/FileSystem.js
Fix *file* watching on Windows: normalize out doubled "/"es in paths received from Node-side watcher impl
<ide><path>rc/filesystem/FileSystem.js <ide> return; <ide> } <ide> <add> path = _normalizePath(path, false); <ide> var entry = this._index.getEntry(path); <ide> <ide> var fireChangeEvent = function () {
Java
mpl-2.0
e6d1cb8cd2b2505434859cc3b22dd224ec0cd23b
0
msteinhoff/hello-world
6c75db9c-cb8e-11e5-bb9d-00264a111016
src/main/java/HelloWorld.java
6c6a18ab-cb8e-11e5-b816-00264a111016
Introduced random NullPointerException bug
src/main/java/HelloWorld.java
Introduced random NullPointerException bug
<ide><path>rc/main/java/HelloWorld.java <del>6c6a18ab-cb8e-11e5-b816-00264a111016 <add>6c75db9c-cb8e-11e5-bb9d-00264a111016
Java
apache-2.0
72c1a847503e19942b46f4e4b1b8c8d6fb60fb4f
0
Apache9/hbase,ndimiduk/hbase,mahak/hbase,Apache9/hbase,mahak/hbase,ndimiduk/hbase,Apache9/hbase,mahak/hbase,mahak/hbase,Apache9/hbase,ndimiduk/hbase,Apache9/hbase,Apache9/hbase,ndimiduk/hbase,ndimiduk/hbase,Apache9/hbase,ndimiduk/hbase,Apache9/hbase,ndimiduk/hbase,mahak/hbase,Apache9/hbase,ndimiduk/hbase,mahak/hbase,mahak/hbase,ndimiduk/hbase,mahak/hbase,mahak/hbase,mahak/hbase,ndimiduk/hbase,Apache9/hbase
/* * 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. */ package org.apache.hadoop.hbase.regionserver; import static org.apache.hadoop.hbase.regionserver.Store.NO_PRIORITY; import static org.apache.hadoop.hbase.regionserver.Store.PRIORITY_USER; import java.io.IOException; import java.io.PrintWriter; import java.io.StringWriter; import java.util.Comparator; import java.util.Iterator; import java.util.Optional; import java.util.Set; import java.util.concurrent.BlockingQueue; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.Executors; import java.util.concurrent.RejectedExecutionException; import java.util.concurrent.ThreadPoolExecutor; import java.util.concurrent.TimeUnit; import java.util.concurrent.atomic.AtomicInteger; import java.util.function.IntSupplier; import org.apache.hadoop.conf.Configuration; import org.apache.hadoop.hbase.conf.ConfigurationManager; import org.apache.hadoop.hbase.conf.PropagatingConfigurationObserver; import org.apache.hadoop.hbase.quotas.RegionServerSpaceQuotaManager; import org.apache.hadoop.hbase.regionserver.compactions.CompactionContext; import org.apache.hadoop.hbase.regionserver.compactions.CompactionLifeCycleTracker; import org.apache.hadoop.hbase.regionserver.compactions.CompactionRequestImpl; import org.apache.hadoop.hbase.regionserver.compactions.CompactionRequester; import org.apache.hadoop.hbase.regionserver.throttle.CompactionThroughputControllerFactory; import org.apache.hadoop.hbase.regionserver.throttle.ThroughputController; import org.apache.hadoop.hbase.security.Superusers; import org.apache.hadoop.hbase.security.User; import org.apache.hadoop.hbase.util.EnvironmentEdgeManager; import org.apache.hadoop.hbase.util.StealJobQueue; import org.apache.hadoop.ipc.RemoteException; import org.apache.hadoop.util.StringUtils; import org.apache.yetus.audience.InterfaceAudience; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.apache.hbase.thirdparty.com.google.common.base.Preconditions; import org.apache.hbase.thirdparty.com.google.common.util.concurrent.ThreadFactoryBuilder; /** * Compact region on request and then run split if appropriate */ @InterfaceAudience.Private public class CompactSplit implements CompactionRequester, PropagatingConfigurationObserver { private static final Logger LOG = LoggerFactory.getLogger(CompactSplit.class); // Configuration key for the large compaction threads. public final static String LARGE_COMPACTION_THREADS = "hbase.regionserver.thread.compaction.large"; public final static int LARGE_COMPACTION_THREADS_DEFAULT = 1; // Configuration key for the small compaction threads. public final static String SMALL_COMPACTION_THREADS = "hbase.regionserver.thread.compaction.small"; public final static int SMALL_COMPACTION_THREADS_DEFAULT = 1; // Configuration key for split threads public final static String SPLIT_THREADS = "hbase.regionserver.thread.split"; public final static int SPLIT_THREADS_DEFAULT = 1; public static final String REGION_SERVER_REGION_SPLIT_LIMIT = "hbase.regionserver.regionSplitLimit"; public static final int DEFAULT_REGION_SERVER_REGION_SPLIT_LIMIT = 1000; public static final String HBASE_REGION_SERVER_ENABLE_COMPACTION = "hbase.regionserver.compaction.enabled"; private final HRegionServer server; private final Configuration conf; private volatile ThreadPoolExecutor longCompactions; private volatile ThreadPoolExecutor shortCompactions; private volatile ThreadPoolExecutor splits; private volatile ThroughputController compactionThroughputController; private volatile Set<String> underCompactionStores = ConcurrentHashMap.newKeySet(); private volatile boolean compactionsEnabled; /** * Splitting should not take place if the total number of regions exceed this. This is not a hard * limit to the number of regions but it is a guideline to stop splitting after number of online * regions is greater than this. */ private int regionSplitLimit; CompactSplit(HRegionServer server) { this.server = server; this.conf = server.getConfiguration(); this.compactionsEnabled = this.conf.getBoolean(HBASE_REGION_SERVER_ENABLE_COMPACTION, true); createCompactionExecutors(); createSplitExcecutors(); // compaction throughput controller this.compactionThroughputController = CompactionThroughputControllerFactory.create(server, conf); } // only for test public CompactSplit(Configuration conf) { this.server = null; this.conf = conf; this.compactionsEnabled = this.conf.getBoolean(HBASE_REGION_SERVER_ENABLE_COMPACTION, true); createCompactionExecutors(); createSplitExcecutors(); } private void createSplitExcecutors() { final String n = Thread.currentThread().getName(); int splitThreads = conf.getInt(SPLIT_THREADS, SPLIT_THREADS_DEFAULT); this.splits = (ThreadPoolExecutor) Executors.newFixedThreadPool(splitThreads, new ThreadFactoryBuilder().setNameFormat(n + "-splits-%d").setDaemon(true).build()); } private void createCompactionExecutors() { this.regionSplitLimit = conf.getInt(REGION_SERVER_REGION_SPLIT_LIMIT, DEFAULT_REGION_SERVER_REGION_SPLIT_LIMIT); int largeThreads = Math.max(1, conf.getInt(LARGE_COMPACTION_THREADS, LARGE_COMPACTION_THREADS_DEFAULT)); int smallThreads = conf.getInt(SMALL_COMPACTION_THREADS, SMALL_COMPACTION_THREADS_DEFAULT); // if we have throttle threads, make sure the user also specified size Preconditions.checkArgument(largeThreads > 0 && smallThreads > 0); final String n = Thread.currentThread().getName(); StealJobQueue<Runnable> stealJobQueue = new StealJobQueue<Runnable>(COMPARATOR); // Since the StealJobQueue inner uses the PriorityBlockingQueue, // which is an unbounded blocking queue, we remove the RejectedExecutionHandler for // the long and short compaction thread pool executors since HBASE-27332. // If anyone who what to change the StealJobQueue to a bounded queue, // please add the rejection handler back. this.longCompactions = new ThreadPoolExecutor(largeThreads, largeThreads, 60, TimeUnit.SECONDS, stealJobQueue, new ThreadFactoryBuilder().setNameFormat(n + "-longCompactions-%d").setDaemon(true).build()); this.longCompactions.prestartAllCoreThreads(); this.shortCompactions = new ThreadPoolExecutor(smallThreads, smallThreads, 60, TimeUnit.SECONDS, stealJobQueue.getStealFromQueue(), new ThreadFactoryBuilder().setNameFormat(n + "-shortCompactions-%d").setDaemon(true).build()); } @Override public String toString() { return "compactionQueue=(longCompactions=" + longCompactions.getQueue().size() + ":shortCompactions=" + shortCompactions.getQueue().size() + ")" + ", splitQueue=" + splits.getQueue().size(); } public String dumpQueue() { StringBuilder queueLists = new StringBuilder(); queueLists.append("Compaction/Split Queue dump:\n"); queueLists.append(" LargeCompation Queue:\n"); BlockingQueue<Runnable> lq = longCompactions.getQueue(); Iterator<Runnable> it = lq.iterator(); while (it.hasNext()) { queueLists.append(" " + it.next().toString()); queueLists.append("\n"); } if (shortCompactions != null) { queueLists.append("\n"); queueLists.append(" SmallCompation Queue:\n"); lq = shortCompactions.getQueue(); it = lq.iterator(); while (it.hasNext()) { queueLists.append(" " + it.next().toString()); queueLists.append("\n"); } } queueLists.append("\n"); queueLists.append(" Split Queue:\n"); lq = splits.getQueue(); it = lq.iterator(); while (it.hasNext()) { queueLists.append(" " + it.next().toString()); queueLists.append("\n"); } return queueLists.toString(); } public synchronized boolean requestSplit(final Region r) { // Don't split regions that are blocking is the default behavior. // But in some circumstances, split here is needed to prevent the region size from // continuously growing, as well as the number of store files, see HBASE-26242. HRegion hr = (HRegion) r; try { if (shouldSplitRegion() && hr.getCompactPriority() >= PRIORITY_USER) { byte[] midKey = hr.checkSplit().orElse(null); if (midKey != null) { requestSplit(r, midKey); return true; } } } catch (IndexOutOfBoundsException e) { // We get this sometimes. Not sure why. Catch and return false; no split request. LOG.warn("Catching out-of-bounds; region={}, policy={}", hr == null ? null : hr.getRegionInfo(), hr == null ? "null" : hr.getCompactPriority(), e); } return false; } private synchronized void requestSplit(final Region r, byte[] midKey) { requestSplit(r, midKey, null); } /* * The User parameter allows the split thread to assume the correct user identity */ private synchronized void requestSplit(final Region r, byte[] midKey, User user) { if (midKey == null) { LOG.debug("Region " + r.getRegionInfo().getRegionNameAsString() + " not splittable because midkey=null"); return; } try { this.splits.execute(new SplitRequest(r, midKey, this.server, user)); if (LOG.isDebugEnabled()) { LOG.debug("Splitting " + r + ", " + this); } } catch (RejectedExecutionException ree) { LOG.info("Could not execute split for " + r, ree); } } private void interrupt() { longCompactions.shutdownNow(); shortCompactions.shutdownNow(); } private void reInitializeCompactionsExecutors() { createCompactionExecutors(); } // set protected for test protected interface CompactionCompleteTracker { default void completed(Store store) { } } private static final CompactionCompleteTracker DUMMY_COMPLETE_TRACKER = new CompactionCompleteTracker() { }; private static final class AggregatingCompleteTracker implements CompactionCompleteTracker { private final CompactionLifeCycleTracker tracker; private final AtomicInteger remaining; public AggregatingCompleteTracker(CompactionLifeCycleTracker tracker, int numberOfStores) { this.tracker = tracker; this.remaining = new AtomicInteger(numberOfStores); } @Override public void completed(Store store) { if (remaining.decrementAndGet() == 0) { tracker.completed(); } } } private CompactionCompleteTracker getCompleteTracker(CompactionLifeCycleTracker tracker, IntSupplier numberOfStores) { if (tracker == CompactionLifeCycleTracker.DUMMY) { // a simple optimization to avoid creating unnecessary objects as usually we do not care about // the life cycle of a compaction. return DUMMY_COMPLETE_TRACKER; } else { return new AggregatingCompleteTracker(tracker, numberOfStores.getAsInt()); } } @Override public synchronized void requestCompaction(HRegion region, String why, int priority, CompactionLifeCycleTracker tracker, User user) throws IOException { requestCompactionInternal(region, why, priority, true, tracker, getCompleteTracker(tracker, () -> region.getTableDescriptor().getColumnFamilyCount()), user); } @Override public synchronized void requestCompaction(HRegion region, HStore store, String why, int priority, CompactionLifeCycleTracker tracker, User user) throws IOException { requestCompactionInternal(region, store, why, priority, true, tracker, getCompleteTracker(tracker, () -> 1), user); } @Override public void switchCompaction(boolean onOrOff) { if (onOrOff) { // re-create executor pool if compactions are disabled. if (!isCompactionsEnabled()) { LOG.info("Re-Initializing compactions because user switched on compactions"); reInitializeCompactionsExecutors(); } } else { LOG.info("Interrupting running compactions because user switched off compactions"); interrupt(); } setCompactionsEnabled(onOrOff); } private void requestCompactionInternal(HRegion region, String why, int priority, boolean selectNow, CompactionLifeCycleTracker tracker, CompactionCompleteTracker completeTracker, User user) throws IOException { // request compaction on all stores for (HStore store : region.stores.values()) { requestCompactionInternal(region, store, why, priority, selectNow, tracker, completeTracker, user); } } // set protected for test protected void requestCompactionInternal(HRegion region, HStore store, String why, int priority, boolean selectNow, CompactionLifeCycleTracker tracker, CompactionCompleteTracker completeTracker, User user) throws IOException { if ( this.server.isStopped() || (region.getTableDescriptor() != null && !region.getTableDescriptor().isCompactionEnabled()) ) { return; } RegionServerSpaceQuotaManager spaceQuotaManager = this.server.getRegionServerSpaceQuotaManager(); if ( user != null && !Superusers.isSuperUser(user) && spaceQuotaManager != null && spaceQuotaManager.areCompactionsDisabled(region.getTableDescriptor().getTableName()) ) { // Enter here only when: // It's a user generated req, the user is super user, quotas enabled, compactions disabled. String reason = "Ignoring compaction request for " + region + " as an active space quota violation " + " policy disallows compactions."; tracker.notExecuted(store, reason); completeTracker.completed(store); LOG.debug(reason); return; } CompactionContext compaction; if (selectNow) { Optional<CompactionContext> c = selectCompaction(region, store, priority, tracker, completeTracker, user); if (!c.isPresent()) { // message logged inside return; } compaction = c.get(); } else { compaction = null; } ThreadPoolExecutor pool; if (selectNow) { // compaction.get is safe as we will just return if selectNow is true but no compaction is // selected pool = store.throttleCompaction(compaction.getRequest().getSize()) ? longCompactions : shortCompactions; } else { // We assume that most compactions are small. So, put system compactions into small // pool; we will do selection there, and move to large pool if necessary. pool = shortCompactions; } // A simple implementation for under compaction marks. // Since this method is always called in the synchronized methods, we do not need to use the // boolean result to make sure that exactly the one that added here will be removed // in the next steps. underCompactionStores.add(getStoreNameForUnderCompaction(store)); pool.execute( new CompactionRunner(store, region, compaction, tracker, completeTracker, pool, user)); if (LOG.isDebugEnabled()) { LOG.debug( "Add compact mark for store {}, priority={}, current under compaction " + "store size is {}", getStoreNameForUnderCompaction(store), priority, underCompactionStores.size()); } region.incrementCompactionsQueuedCount(); if (LOG.isDebugEnabled()) { String type = (pool == shortCompactions) ? "Small " : "Large "; LOG.debug(type + "Compaction requested: " + (selectNow ? compaction.toString() : "system") + (why != null && !why.isEmpty() ? "; Because: " + why : "") + "; " + this); } } public synchronized void requestSystemCompaction(HRegion region, String why) throws IOException { requestCompactionInternal(region, why, NO_PRIORITY, false, CompactionLifeCycleTracker.DUMMY, DUMMY_COMPLETE_TRACKER, null); } public void requestSystemCompaction(HRegion region, HStore store, String why) throws IOException { requestSystemCompaction(region, store, why, false); } public synchronized void requestSystemCompaction(HRegion region, HStore store, String why, boolean giveUpIfRequestedOrCompacting) throws IOException { if (giveUpIfRequestedOrCompacting && isUnderCompaction(store)) { LOG.debug("Region {} store {} is under compaction now, skip to request compaction", region, store.getColumnFamilyName()); return; } requestCompactionInternal(region, store, why, NO_PRIORITY, false, CompactionLifeCycleTracker.DUMMY, DUMMY_COMPLETE_TRACKER, null); } private Optional<CompactionContext> selectCompaction(HRegion region, HStore store, int priority, CompactionLifeCycleTracker tracker, CompactionCompleteTracker completeTracker, User user) throws IOException { // don't even select for compaction if disableCompactions is set to true if (!isCompactionsEnabled()) { LOG.info(String.format("User has disabled compactions")); return Optional.empty(); } Optional<CompactionContext> compaction = store.requestCompaction(priority, tracker, user); if (!compaction.isPresent() && region.getRegionInfo() != null) { String reason = "Not compacting " + region.getRegionInfo().getRegionNameAsString() + " because compaction request was cancelled"; tracker.notExecuted(store, reason); completeTracker.completed(store); LOG.debug(reason); } return compaction; } /** * Only interrupt once it's done with a run through the work loop. */ void interruptIfNecessary() { splits.shutdown(); longCompactions.shutdown(); shortCompactions.shutdown(); } private void waitFor(ThreadPoolExecutor t, String name) { boolean done = false; while (!done) { try { done = t.awaitTermination(60, TimeUnit.SECONDS); LOG.info("Waiting for " + name + " to finish..."); if (!done) { t.shutdownNow(); } } catch (InterruptedException ie) { LOG.warn("Interrupted waiting for " + name + " to finish..."); t.shutdownNow(); } } } void join() { waitFor(splits, "Split Thread"); waitFor(longCompactions, "Large Compaction Thread"); waitFor(shortCompactions, "Small Compaction Thread"); } /** * Returns the current size of the queue containing regions that are processed. * @return The current size of the regions queue. */ public int getCompactionQueueSize() { return longCompactions.getQueue().size() + shortCompactions.getQueue().size(); } public int getLargeCompactionQueueSize() { return longCompactions.getQueue().size(); } public int getSmallCompactionQueueSize() { return shortCompactions.getQueue().size(); } public int getSplitQueueSize() { return splits.getQueue().size(); } private boolean shouldSplitRegion() { if (server.getNumberOfOnlineRegions() > 0.9 * regionSplitLimit) { LOG.warn("Total number of regions is approaching the upper limit " + regionSplitLimit + ". " + "Please consider taking a look at http://hbase.apache.org/book.html#ops.regionmgt"); } return (regionSplitLimit > server.getNumberOfOnlineRegions()); } /** Returns the regionSplitLimit */ public int getRegionSplitLimit() { return this.regionSplitLimit; } /** * Check if this store is under compaction */ public boolean isUnderCompaction(final HStore s) { return underCompactionStores.contains(getStoreNameForUnderCompaction(s)); } private static final Comparator<Runnable> COMPARATOR = new Comparator<Runnable>() { private int compare(CompactionRequestImpl r1, CompactionRequestImpl r2) { if (r1 == r2) { return 0; // they are the same request } // less first int cmp = Integer.compare(r1.getPriority(), r2.getPriority()); if (cmp != 0) { return cmp; } cmp = Long.compare(r1.getSelectionTime(), r2.getSelectionTime()); if (cmp != 0) { return cmp; } // break the tie based on hash code return System.identityHashCode(r1) - System.identityHashCode(r2); } @Override public int compare(Runnable r1, Runnable r2) { // CompactionRunner first if (r1 instanceof CompactionRunner) { if (!(r2 instanceof CompactionRunner)) { return -1; } } else { if (r2 instanceof CompactionRunner) { return 1; } else { // break the tie based on hash code return System.identityHashCode(r1) - System.identityHashCode(r2); } } CompactionRunner o1 = (CompactionRunner) r1; CompactionRunner o2 = (CompactionRunner) r2; // less first int cmp = Integer.compare(o1.queuedPriority, o2.queuedPriority); if (cmp != 0) { return cmp; } CompactionContext c1 = o1.compaction; CompactionContext c2 = o2.compaction; if (c1 != null) { return c2 != null ? compare(c1.getRequest(), c2.getRequest()) : -1; } else { return c2 != null ? 1 : 0; } } }; private final class CompactionRunner implements Runnable { private final HStore store; private final HRegion region; private final CompactionContext compaction; private final CompactionLifeCycleTracker tracker; private final CompactionCompleteTracker completeTracker; private int queuedPriority; private ThreadPoolExecutor parent; private User user; private long time; public CompactionRunner(HStore store, HRegion region, CompactionContext compaction, CompactionLifeCycleTracker tracker, CompactionCompleteTracker completeTracker, ThreadPoolExecutor parent, User user) { this.store = store; this.region = region; this.compaction = compaction; this.tracker = tracker; this.completeTracker = completeTracker; this.queuedPriority = compaction != null ? compaction.getRequest().getPriority() : store.getCompactPriority(); this.parent = parent; this.user = user; this.time = EnvironmentEdgeManager.currentTime(); } @Override public String toString() { if (compaction != null) { return "Request=" + compaction.getRequest(); } else { return "region=" + region.toString() + ", storeName=" + store.toString() + ", priority=" + queuedPriority + ", startTime=" + time; } } private void doCompaction(User user) { CompactionContext c; // Common case - system compaction without a file selection. Select now. if (compaction == null) { int oldPriority = this.queuedPriority; this.queuedPriority = this.store.getCompactPriority(); if (this.queuedPriority > oldPriority) { // Store priority decreased while we were in queue (due to some other compaction?), // requeue with new priority to avoid blocking potential higher priorities. this.parent.execute(this); return; } Optional<CompactionContext> selected; try { selected = selectCompaction(this.region, this.store, queuedPriority, tracker, completeTracker, user); } catch (IOException ex) { LOG.error("Compaction selection failed " + this, ex); server.checkFileSystem(); region.decrementCompactionsQueuedCount(); return; } if (!selected.isPresent()) { region.decrementCompactionsQueuedCount(); return; // nothing to do } c = selected.get(); assert c.hasSelection(); // Now see if we are in correct pool for the size; if not, go to the correct one. // We might end up waiting for a while, so cancel the selection. ThreadPoolExecutor pool = store.throttleCompaction(c.getRequest().getSize()) ? longCompactions : shortCompactions; // Long compaction pool can process small job // Short compaction pool should not process large job if (this.parent == shortCompactions && pool == longCompactions) { this.store.cancelRequestedCompaction(c); this.parent = pool; this.parent.execute(this); return; } } else { c = compaction; } // Finally we can compact something. assert c != null; tracker.beforeExecution(store); try { // Note: please don't put single-compaction logic here; // put it into region/store/etc. This is CST logic. long start = EnvironmentEdgeManager.currentTime(); boolean completed = region.compact(c, store, compactionThroughputController, user); long now = EnvironmentEdgeManager.currentTime(); LOG.info(((completed) ? "Completed" : "Aborted") + " compaction " + this + "; duration=" + StringUtils.formatTimeDiff(now, start)); if (completed) { // degenerate case: blocked regions require recursive enqueues if ( region.getCompactPriority() < Store.PRIORITY_USER && store.getCompactPriority() <= 0 ) { requestSystemCompaction(region, store, "Recursive enqueue"); } else { // see if the compaction has caused us to exceed max region size if (!requestSplit(region) && store.getCompactPriority() <= 0) { requestSystemCompaction(region, store, "Recursive enqueue"); } } } } catch (IOException ex) { IOException remoteEx = ex instanceof RemoteException ? ((RemoteException) ex).unwrapRemoteException() : ex; LOG.error("Compaction failed " + this, remoteEx); if (remoteEx != ex) { LOG.info("Compaction failed at original callstack: " + formatStackTrace(ex)); } region.reportCompactionRequestFailure(); server.checkFileSystem(); } catch (Exception ex) { LOG.error("Compaction failed " + this, ex); region.reportCompactionRequestFailure(); server.checkFileSystem(); } finally { tracker.afterExecution(store); completeTracker.completed(store); region.decrementCompactionsQueuedCount(); LOG.debug("Status {}", CompactSplit.this); } } @Override public void run() { try { Preconditions.checkNotNull(server); if ( server.isStopped() || (region.getTableDescriptor() != null && !region.getTableDescriptor().isCompactionEnabled()) ) { region.decrementCompactionsQueuedCount(); return; } doCompaction(user); } finally { if (LOG.isDebugEnabled()) { LOG.debug("Remove under compaction mark for store: {}", store.getHRegion().getRegionInfo().getEncodedName() + ":" + store.getColumnFamilyName()); } underCompactionStores.remove(getStoreNameForUnderCompaction(store)); } } private String formatStackTrace(Exception ex) { StringWriter sw = new StringWriter(); PrintWriter pw = new PrintWriter(sw); ex.printStackTrace(pw); pw.flush(); return sw.toString(); } } /** * {@inheritDoc} */ @Override public void onConfigurationChange(Configuration newConf) { // Check if number of large / small compaction threads has changed, and then // adjust the core pool size of the thread pools, by using the // setCorePoolSize() method. According to the javadocs, it is safe to // change the core pool size on-the-fly. We need to reset the maximum // pool size, as well. int largeThreads = Math.max(1, newConf.getInt(LARGE_COMPACTION_THREADS, LARGE_COMPACTION_THREADS_DEFAULT)); if (this.longCompactions.getCorePoolSize() != largeThreads) { LOG.info("Changing the value of " + LARGE_COMPACTION_THREADS + " from " + this.longCompactions.getCorePoolSize() + " to " + largeThreads); if (this.longCompactions.getCorePoolSize() < largeThreads) { this.longCompactions.setMaximumPoolSize(largeThreads); this.longCompactions.setCorePoolSize(largeThreads); } else { this.longCompactions.setCorePoolSize(largeThreads); this.longCompactions.setMaximumPoolSize(largeThreads); } } int smallThreads = newConf.getInt(SMALL_COMPACTION_THREADS, SMALL_COMPACTION_THREADS_DEFAULT); if (this.shortCompactions.getCorePoolSize() != smallThreads) { LOG.info("Changing the value of " + SMALL_COMPACTION_THREADS + " from " + this.shortCompactions.getCorePoolSize() + " to " + smallThreads); if (this.shortCompactions.getCorePoolSize() < smallThreads) { this.shortCompactions.setMaximumPoolSize(smallThreads); this.shortCompactions.setCorePoolSize(smallThreads); } else { this.shortCompactions.setCorePoolSize(smallThreads); this.shortCompactions.setMaximumPoolSize(smallThreads); } } int splitThreads = newConf.getInt(SPLIT_THREADS, SPLIT_THREADS_DEFAULT); if (this.splits.getCorePoolSize() != splitThreads) { LOG.info("Changing the value of " + SPLIT_THREADS + " from " + this.splits.getCorePoolSize() + " to " + splitThreads); if (this.splits.getCorePoolSize() < splitThreads) { this.splits.setMaximumPoolSize(splitThreads); this.splits.setCorePoolSize(splitThreads); } else { this.splits.setCorePoolSize(splitThreads); this.splits.setMaximumPoolSize(splitThreads); } } ThroughputController old = this.compactionThroughputController; if (old != null) { old.stop("configuration change"); } this.compactionThroughputController = CompactionThroughputControllerFactory.create(server, newConf); // We change this atomically here instead of reloading the config in order that upstream // would be the only one with the flexibility to reload the config. this.conf.reloadConfiguration(); } protected int getSmallCompactionThreadNum() { return this.shortCompactions.getCorePoolSize(); } protected int getLargeCompactionThreadNum() { return this.longCompactions.getCorePoolSize(); } protected int getSplitThreadNum() { return this.splits.getCorePoolSize(); } /** * {@inheritDoc} */ @Override public void registerChildren(ConfigurationManager manager) { // No children to register. } /** * {@inheritDoc} */ @Override public void deregisterChildren(ConfigurationManager manager) { // No children to register } public ThroughputController getCompactionThroughputController() { return compactionThroughputController; } /** * Shutdown the long compaction thread pool. Should only be used in unit test to prevent long * compaction thread pool from stealing job from short compaction queue */ void shutdownLongCompactions() { this.longCompactions.shutdown(); } public void clearLongCompactionsQueue() { longCompactions.getQueue().clear(); } public void clearShortCompactionsQueue() { shortCompactions.getQueue().clear(); } public boolean isCompactionsEnabled() { return compactionsEnabled; } public void setCompactionsEnabled(boolean compactionsEnabled) { this.compactionsEnabled = compactionsEnabled; this.conf.set(HBASE_REGION_SERVER_ENABLE_COMPACTION, String.valueOf(compactionsEnabled)); } /** Returns the longCompactions thread pool executor */ ThreadPoolExecutor getLongCompactions() { return longCompactions; } /** Returns the shortCompactions thread pool executor */ ThreadPoolExecutor getShortCompactions() { return shortCompactions; } private String getStoreNameForUnderCompaction(HStore store) { return String.format("%s:%s", store.getHRegion() != null ? store.getHRegion().getRegionInfo().getEncodedName() : "", store.getColumnFamilyName()); } }
hbase-server/src/main/java/org/apache/hadoop/hbase/regionserver/CompactSplit.java
/* * 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. */ package org.apache.hadoop.hbase.regionserver; import static org.apache.hadoop.hbase.regionserver.Store.NO_PRIORITY; import static org.apache.hadoop.hbase.regionserver.Store.PRIORITY_USER; import java.io.IOException; import java.io.PrintWriter; import java.io.StringWriter; import java.util.Comparator; import java.util.Iterator; import java.util.Optional; import java.util.Set; import java.util.concurrent.BlockingQueue; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.Executors; import java.util.concurrent.RejectedExecutionException; import java.util.concurrent.RejectedExecutionHandler; import java.util.concurrent.ThreadPoolExecutor; import java.util.concurrent.TimeUnit; import java.util.concurrent.atomic.AtomicInteger; import java.util.function.IntSupplier; import org.apache.hadoop.conf.Configuration; import org.apache.hadoop.hbase.conf.ConfigurationManager; import org.apache.hadoop.hbase.conf.PropagatingConfigurationObserver; import org.apache.hadoop.hbase.quotas.RegionServerSpaceQuotaManager; import org.apache.hadoop.hbase.regionserver.compactions.CompactionContext; import org.apache.hadoop.hbase.regionserver.compactions.CompactionLifeCycleTracker; import org.apache.hadoop.hbase.regionserver.compactions.CompactionRequestImpl; import org.apache.hadoop.hbase.regionserver.compactions.CompactionRequester; import org.apache.hadoop.hbase.regionserver.throttle.CompactionThroughputControllerFactory; import org.apache.hadoop.hbase.regionserver.throttle.ThroughputController; import org.apache.hadoop.hbase.security.Superusers; import org.apache.hadoop.hbase.security.User; import org.apache.hadoop.hbase.util.EnvironmentEdgeManager; import org.apache.hadoop.hbase.util.StealJobQueue; import org.apache.hadoop.ipc.RemoteException; import org.apache.hadoop.util.StringUtils; import org.apache.yetus.audience.InterfaceAudience; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.apache.hbase.thirdparty.com.google.common.base.Preconditions; import org.apache.hbase.thirdparty.com.google.common.util.concurrent.ThreadFactoryBuilder; /** * Compact region on request and then run split if appropriate */ @InterfaceAudience.Private public class CompactSplit implements CompactionRequester, PropagatingConfigurationObserver { private static final Logger LOG = LoggerFactory.getLogger(CompactSplit.class); // Configuration key for the large compaction threads. public final static String LARGE_COMPACTION_THREADS = "hbase.regionserver.thread.compaction.large"; public final static int LARGE_COMPACTION_THREADS_DEFAULT = 1; // Configuration key for the small compaction threads. public final static String SMALL_COMPACTION_THREADS = "hbase.regionserver.thread.compaction.small"; public final static int SMALL_COMPACTION_THREADS_DEFAULT = 1; // Configuration key for split threads public final static String SPLIT_THREADS = "hbase.regionserver.thread.split"; public final static int SPLIT_THREADS_DEFAULT = 1; public static final String REGION_SERVER_REGION_SPLIT_LIMIT = "hbase.regionserver.regionSplitLimit"; public static final int DEFAULT_REGION_SERVER_REGION_SPLIT_LIMIT = 1000; public static final String HBASE_REGION_SERVER_ENABLE_COMPACTION = "hbase.regionserver.compaction.enabled"; private final HRegionServer server; private final Configuration conf; private volatile ThreadPoolExecutor longCompactions; private volatile ThreadPoolExecutor shortCompactions; private volatile ThreadPoolExecutor splits; private volatile ThroughputController compactionThroughputController; private volatile Set<String> underCompactionStores = ConcurrentHashMap.newKeySet(); private volatile boolean compactionsEnabled; /** * Splitting should not take place if the total number of regions exceed this. This is not a hard * limit to the number of regions but it is a guideline to stop splitting after number of online * regions is greater than this. */ private int regionSplitLimit; CompactSplit(HRegionServer server) { this.server = server; this.conf = server.getConfiguration(); this.compactionsEnabled = this.conf.getBoolean(HBASE_REGION_SERVER_ENABLE_COMPACTION, true); createCompactionExecutors(); createSplitExcecutors(); // compaction throughput controller this.compactionThroughputController = CompactionThroughputControllerFactory.create(server, conf); } // only for test public CompactSplit(Configuration conf) { this.server = null; this.conf = conf; this.compactionsEnabled = this.conf.getBoolean(HBASE_REGION_SERVER_ENABLE_COMPACTION, true); createCompactionExecutors(); createSplitExcecutors(); } private void createSplitExcecutors() { final String n = Thread.currentThread().getName(); int splitThreads = conf.getInt(SPLIT_THREADS, SPLIT_THREADS_DEFAULT); this.splits = (ThreadPoolExecutor) Executors.newFixedThreadPool(splitThreads, new ThreadFactoryBuilder().setNameFormat(n + "-splits-%d").setDaemon(true).build()); } private void createCompactionExecutors() { this.regionSplitLimit = conf.getInt(REGION_SERVER_REGION_SPLIT_LIMIT, DEFAULT_REGION_SERVER_REGION_SPLIT_LIMIT); int largeThreads = Math.max(1, conf.getInt(LARGE_COMPACTION_THREADS, LARGE_COMPACTION_THREADS_DEFAULT)); int smallThreads = conf.getInt(SMALL_COMPACTION_THREADS, SMALL_COMPACTION_THREADS_DEFAULT); // if we have throttle threads, make sure the user also specified size Preconditions.checkArgument(largeThreads > 0 && smallThreads > 0); final String n = Thread.currentThread().getName(); StealJobQueue<Runnable> stealJobQueue = new StealJobQueue<Runnable>(COMPARATOR); this.longCompactions = new ThreadPoolExecutor(largeThreads, largeThreads, 60, TimeUnit.SECONDS, stealJobQueue, new ThreadFactoryBuilder().setNameFormat(n + "-longCompactions-%d").setDaemon(true).build()); this.longCompactions.setRejectedExecutionHandler(new Rejection()); this.longCompactions.prestartAllCoreThreads(); this.shortCompactions = new ThreadPoolExecutor(smallThreads, smallThreads, 60, TimeUnit.SECONDS, stealJobQueue.getStealFromQueue(), new ThreadFactoryBuilder().setNameFormat(n + "-shortCompactions-%d").setDaemon(true).build()); this.shortCompactions.setRejectedExecutionHandler(new Rejection()); } @Override public String toString() { return "compactionQueue=(longCompactions=" + longCompactions.getQueue().size() + ":shortCompactions=" + shortCompactions.getQueue().size() + ")" + ", splitQueue=" + splits.getQueue().size(); } public String dumpQueue() { StringBuilder queueLists = new StringBuilder(); queueLists.append("Compaction/Split Queue dump:\n"); queueLists.append(" LargeCompation Queue:\n"); BlockingQueue<Runnable> lq = longCompactions.getQueue(); Iterator<Runnable> it = lq.iterator(); while (it.hasNext()) { queueLists.append(" " + it.next().toString()); queueLists.append("\n"); } if (shortCompactions != null) { queueLists.append("\n"); queueLists.append(" SmallCompation Queue:\n"); lq = shortCompactions.getQueue(); it = lq.iterator(); while (it.hasNext()) { queueLists.append(" " + it.next().toString()); queueLists.append("\n"); } } queueLists.append("\n"); queueLists.append(" Split Queue:\n"); lq = splits.getQueue(); it = lq.iterator(); while (it.hasNext()) { queueLists.append(" " + it.next().toString()); queueLists.append("\n"); } return queueLists.toString(); } public synchronized boolean requestSplit(final Region r) { // Don't split regions that are blocking is the default behavior. // But in some circumstances, split here is needed to prevent the region size from // continuously growing, as well as the number of store files, see HBASE-26242. HRegion hr = (HRegion) r; try { if (shouldSplitRegion() && hr.getCompactPriority() >= PRIORITY_USER) { byte[] midKey = hr.checkSplit().orElse(null); if (midKey != null) { requestSplit(r, midKey); return true; } } } catch (IndexOutOfBoundsException e) { // We get this sometimes. Not sure why. Catch and return false; no split request. LOG.warn("Catching out-of-bounds; region={}, policy={}", hr == null ? null : hr.getRegionInfo(), hr == null ? "null" : hr.getCompactPriority(), e); } return false; } private synchronized void requestSplit(final Region r, byte[] midKey) { requestSplit(r, midKey, null); } /* * The User parameter allows the split thread to assume the correct user identity */ private synchronized void requestSplit(final Region r, byte[] midKey, User user) { if (midKey == null) { LOG.debug("Region " + r.getRegionInfo().getRegionNameAsString() + " not splittable because midkey=null"); return; } try { this.splits.execute(new SplitRequest(r, midKey, this.server, user)); if (LOG.isDebugEnabled()) { LOG.debug("Splitting " + r + ", " + this); } } catch (RejectedExecutionException ree) { LOG.info("Could not execute split for " + r, ree); } } private void interrupt() { longCompactions.shutdownNow(); shortCompactions.shutdownNow(); } private void reInitializeCompactionsExecutors() { createCompactionExecutors(); } // set protected for test protected interface CompactionCompleteTracker { default void completed(Store store) { } } private static final CompactionCompleteTracker DUMMY_COMPLETE_TRACKER = new CompactionCompleteTracker() { }; private static final class AggregatingCompleteTracker implements CompactionCompleteTracker { private final CompactionLifeCycleTracker tracker; private final AtomicInteger remaining; public AggregatingCompleteTracker(CompactionLifeCycleTracker tracker, int numberOfStores) { this.tracker = tracker; this.remaining = new AtomicInteger(numberOfStores); } @Override public void completed(Store store) { if (remaining.decrementAndGet() == 0) { tracker.completed(); } } } private CompactionCompleteTracker getCompleteTracker(CompactionLifeCycleTracker tracker, IntSupplier numberOfStores) { if (tracker == CompactionLifeCycleTracker.DUMMY) { // a simple optimization to avoid creating unnecessary objects as usually we do not care about // the life cycle of a compaction. return DUMMY_COMPLETE_TRACKER; } else { return new AggregatingCompleteTracker(tracker, numberOfStores.getAsInt()); } } @Override public synchronized void requestCompaction(HRegion region, String why, int priority, CompactionLifeCycleTracker tracker, User user) throws IOException { requestCompactionInternal(region, why, priority, true, tracker, getCompleteTracker(tracker, () -> region.getTableDescriptor().getColumnFamilyCount()), user); } @Override public synchronized void requestCompaction(HRegion region, HStore store, String why, int priority, CompactionLifeCycleTracker tracker, User user) throws IOException { requestCompactionInternal(region, store, why, priority, true, tracker, getCompleteTracker(tracker, () -> 1), user); } @Override public void switchCompaction(boolean onOrOff) { if (onOrOff) { // re-create executor pool if compactions are disabled. if (!isCompactionsEnabled()) { LOG.info("Re-Initializing compactions because user switched on compactions"); reInitializeCompactionsExecutors(); } } else { LOG.info("Interrupting running compactions because user switched off compactions"); interrupt(); } setCompactionsEnabled(onOrOff); } private void requestCompactionInternal(HRegion region, String why, int priority, boolean selectNow, CompactionLifeCycleTracker tracker, CompactionCompleteTracker completeTracker, User user) throws IOException { // request compaction on all stores for (HStore store : region.stores.values()) { requestCompactionInternal(region, store, why, priority, selectNow, tracker, completeTracker, user); } } // set protected for test protected void requestCompactionInternal(HRegion region, HStore store, String why, int priority, boolean selectNow, CompactionLifeCycleTracker tracker, CompactionCompleteTracker completeTracker, User user) throws IOException { if ( this.server.isStopped() || (region.getTableDescriptor() != null && !region.getTableDescriptor().isCompactionEnabled()) ) { return; } RegionServerSpaceQuotaManager spaceQuotaManager = this.server.getRegionServerSpaceQuotaManager(); if ( user != null && !Superusers.isSuperUser(user) && spaceQuotaManager != null && spaceQuotaManager.areCompactionsDisabled(region.getTableDescriptor().getTableName()) ) { // Enter here only when: // It's a user generated req, the user is super user, quotas enabled, compactions disabled. String reason = "Ignoring compaction request for " + region + " as an active space quota violation " + " policy disallows compactions."; tracker.notExecuted(store, reason); completeTracker.completed(store); LOG.debug(reason); return; } CompactionContext compaction; if (selectNow) { Optional<CompactionContext> c = selectCompaction(region, store, priority, tracker, completeTracker, user); if (!c.isPresent()) { // message logged inside return; } compaction = c.get(); } else { compaction = null; } ThreadPoolExecutor pool; if (selectNow) { // compaction.get is safe as we will just return if selectNow is true but no compaction is // selected pool = store.throttleCompaction(compaction.getRequest().getSize()) ? longCompactions : shortCompactions; } else { // We assume that most compactions are small. So, put system compactions into small // pool; we will do selection there, and move to large pool if necessary. pool = shortCompactions; } // A simple implementation for under compaction marks. // Since this method is always called in the synchronized methods, we do not need to use the // boolean result to make sure that exactly the one that added here will be removed // in the next steps. underCompactionStores.add(getStoreNameForUnderCompaction(store)); pool.execute( new CompactionRunner(store, region, compaction, tracker, completeTracker, pool, user)); if (LOG.isDebugEnabled()) { LOG.debug( "Add compact mark for store {}, priority={}, current under compaction " + "store size is {}", getStoreNameForUnderCompaction(store), priority, underCompactionStores.size()); } region.incrementCompactionsQueuedCount(); if (LOG.isDebugEnabled()) { String type = (pool == shortCompactions) ? "Small " : "Large "; LOG.debug(type + "Compaction requested: " + (selectNow ? compaction.toString() : "system") + (why != null && !why.isEmpty() ? "; Because: " + why : "") + "; " + this); } } public synchronized void requestSystemCompaction(HRegion region, String why) throws IOException { requestCompactionInternal(region, why, NO_PRIORITY, false, CompactionLifeCycleTracker.DUMMY, DUMMY_COMPLETE_TRACKER, null); } public void requestSystemCompaction(HRegion region, HStore store, String why) throws IOException { requestSystemCompaction(region, store, why, false); } public synchronized void requestSystemCompaction(HRegion region, HStore store, String why, boolean giveUpIfRequestedOrCompacting) throws IOException { if (giveUpIfRequestedOrCompacting && isUnderCompaction(store)) { LOG.debug("Region {} store {} is under compaction now, skip to request compaction", region, store.getColumnFamilyName()); return; } requestCompactionInternal(region, store, why, NO_PRIORITY, false, CompactionLifeCycleTracker.DUMMY, DUMMY_COMPLETE_TRACKER, null); } private Optional<CompactionContext> selectCompaction(HRegion region, HStore store, int priority, CompactionLifeCycleTracker tracker, CompactionCompleteTracker completeTracker, User user) throws IOException { // don't even select for compaction if disableCompactions is set to true if (!isCompactionsEnabled()) { LOG.info(String.format("User has disabled compactions")); return Optional.empty(); } Optional<CompactionContext> compaction = store.requestCompaction(priority, tracker, user); if (!compaction.isPresent() && region.getRegionInfo() != null) { String reason = "Not compacting " + region.getRegionInfo().getRegionNameAsString() + " because compaction request was cancelled"; tracker.notExecuted(store, reason); completeTracker.completed(store); LOG.debug(reason); } return compaction; } /** * Only interrupt once it's done with a run through the work loop. */ void interruptIfNecessary() { splits.shutdown(); longCompactions.shutdown(); shortCompactions.shutdown(); } private void waitFor(ThreadPoolExecutor t, String name) { boolean done = false; while (!done) { try { done = t.awaitTermination(60, TimeUnit.SECONDS); LOG.info("Waiting for " + name + " to finish..."); if (!done) { t.shutdownNow(); } } catch (InterruptedException ie) { LOG.warn("Interrupted waiting for " + name + " to finish..."); t.shutdownNow(); } } } void join() { waitFor(splits, "Split Thread"); waitFor(longCompactions, "Large Compaction Thread"); waitFor(shortCompactions, "Small Compaction Thread"); } /** * Returns the current size of the queue containing regions that are processed. * @return The current size of the regions queue. */ public int getCompactionQueueSize() { return longCompactions.getQueue().size() + shortCompactions.getQueue().size(); } public int getLargeCompactionQueueSize() { return longCompactions.getQueue().size(); } public int getSmallCompactionQueueSize() { return shortCompactions.getQueue().size(); } public int getSplitQueueSize() { return splits.getQueue().size(); } private boolean shouldSplitRegion() { if (server.getNumberOfOnlineRegions() > 0.9 * regionSplitLimit) { LOG.warn("Total number of regions is approaching the upper limit " + regionSplitLimit + ". " + "Please consider taking a look at http://hbase.apache.org/book.html#ops.regionmgt"); } return (regionSplitLimit > server.getNumberOfOnlineRegions()); } /** Returns the regionSplitLimit */ public int getRegionSplitLimit() { return this.regionSplitLimit; } /** * Check if this store is under compaction */ public boolean isUnderCompaction(final HStore s) { return underCompactionStores.contains(getStoreNameForUnderCompaction(s)); } private static final Comparator<Runnable> COMPARATOR = new Comparator<Runnable>() { private int compare(CompactionRequestImpl r1, CompactionRequestImpl r2) { if (r1 == r2) { return 0; // they are the same request } // less first int cmp = Integer.compare(r1.getPriority(), r2.getPriority()); if (cmp != 0) { return cmp; } cmp = Long.compare(r1.getSelectionTime(), r2.getSelectionTime()); if (cmp != 0) { return cmp; } // break the tie based on hash code return System.identityHashCode(r1) - System.identityHashCode(r2); } @Override public int compare(Runnable r1, Runnable r2) { // CompactionRunner first if (r1 instanceof CompactionRunner) { if (!(r2 instanceof CompactionRunner)) { return -1; } } else { if (r2 instanceof CompactionRunner) { return 1; } else { // break the tie based on hash code return System.identityHashCode(r1) - System.identityHashCode(r2); } } CompactionRunner o1 = (CompactionRunner) r1; CompactionRunner o2 = (CompactionRunner) r2; // less first int cmp = Integer.compare(o1.queuedPriority, o2.queuedPriority); if (cmp != 0) { return cmp; } CompactionContext c1 = o1.compaction; CompactionContext c2 = o2.compaction; if (c1 != null) { return c2 != null ? compare(c1.getRequest(), c2.getRequest()) : -1; } else { return c2 != null ? 1 : 0; } } }; private final class CompactionRunner implements Runnable { private final HStore store; private final HRegion region; private final CompactionContext compaction; private final CompactionLifeCycleTracker tracker; private final CompactionCompleteTracker completeTracker; private int queuedPriority; private ThreadPoolExecutor parent; private User user; private long time; public CompactionRunner(HStore store, HRegion region, CompactionContext compaction, CompactionLifeCycleTracker tracker, CompactionCompleteTracker completeTracker, ThreadPoolExecutor parent, User user) { this.store = store; this.region = region; this.compaction = compaction; this.tracker = tracker; this.completeTracker = completeTracker; this.queuedPriority = compaction != null ? compaction.getRequest().getPriority() : store.getCompactPriority(); this.parent = parent; this.user = user; this.time = EnvironmentEdgeManager.currentTime(); } @Override public String toString() { if (compaction != null) { return "Request=" + compaction.getRequest(); } else { return "region=" + region.toString() + ", storeName=" + store.toString() + ", priority=" + queuedPriority + ", startTime=" + time; } } private void doCompaction(User user) { CompactionContext c; // Common case - system compaction without a file selection. Select now. if (compaction == null) { int oldPriority = this.queuedPriority; this.queuedPriority = this.store.getCompactPriority(); if (this.queuedPriority > oldPriority) { // Store priority decreased while we were in queue (due to some other compaction?), // requeue with new priority to avoid blocking potential higher priorities. this.parent.execute(this); return; } Optional<CompactionContext> selected; try { selected = selectCompaction(this.region, this.store, queuedPriority, tracker, completeTracker, user); } catch (IOException ex) { LOG.error("Compaction selection failed " + this, ex); server.checkFileSystem(); region.decrementCompactionsQueuedCount(); return; } if (!selected.isPresent()) { region.decrementCompactionsQueuedCount(); return; // nothing to do } c = selected.get(); assert c.hasSelection(); // Now see if we are in correct pool for the size; if not, go to the correct one. // We might end up waiting for a while, so cancel the selection. ThreadPoolExecutor pool = store.throttleCompaction(c.getRequest().getSize()) ? longCompactions : shortCompactions; // Long compaction pool can process small job // Short compaction pool should not process large job if (this.parent == shortCompactions && pool == longCompactions) { this.store.cancelRequestedCompaction(c); this.parent = pool; this.parent.execute(this); return; } } else { c = compaction; } // Finally we can compact something. assert c != null; tracker.beforeExecution(store); try { // Note: please don't put single-compaction logic here; // put it into region/store/etc. This is CST logic. long start = EnvironmentEdgeManager.currentTime(); boolean completed = region.compact(c, store, compactionThroughputController, user); long now = EnvironmentEdgeManager.currentTime(); LOG.info(((completed) ? "Completed" : "Aborted") + " compaction " + this + "; duration=" + StringUtils.formatTimeDiff(now, start)); if (completed) { // degenerate case: blocked regions require recursive enqueues if ( region.getCompactPriority() < Store.PRIORITY_USER && store.getCompactPriority() <= 0 ) { requestSystemCompaction(region, store, "Recursive enqueue"); } else { // see if the compaction has caused us to exceed max region size if (!requestSplit(region) && store.getCompactPriority() <= 0) { requestSystemCompaction(region, store, "Recursive enqueue"); } } } } catch (IOException ex) { IOException remoteEx = ex instanceof RemoteException ? ((RemoteException) ex).unwrapRemoteException() : ex; LOG.error("Compaction failed " + this, remoteEx); if (remoteEx != ex) { LOG.info("Compaction failed at original callstack: " + formatStackTrace(ex)); } region.reportCompactionRequestFailure(); server.checkFileSystem(); } catch (Exception ex) { LOG.error("Compaction failed " + this, ex); region.reportCompactionRequestFailure(); server.checkFileSystem(); } finally { tracker.afterExecution(store); completeTracker.completed(store); region.decrementCompactionsQueuedCount(); LOG.debug("Status {}", CompactSplit.this); } } @Override public void run() { try { Preconditions.checkNotNull(server); if ( server.isStopped() || (region.getTableDescriptor() != null && !region.getTableDescriptor().isCompactionEnabled()) ) { region.decrementCompactionsQueuedCount(); return; } doCompaction(user); } finally { if (LOG.isDebugEnabled()) { LOG.debug("Remove under compaction mark for store: {}", store.getHRegion().getRegionInfo().getEncodedName() + ":" + store.getColumnFamilyName()); } underCompactionStores.remove(getStoreNameForUnderCompaction(store)); } } private String formatStackTrace(Exception ex) { StringWriter sw = new StringWriter(); PrintWriter pw = new PrintWriter(sw); ex.printStackTrace(pw); pw.flush(); return sw.toString(); } } /** * Cleanup class to use when rejecting a compaction request from the queue. */ private static class Rejection implements RejectedExecutionHandler { @Override public void rejectedExecution(Runnable runnable, ThreadPoolExecutor pool) { if (runnable instanceof CompactionRunner) { CompactionRunner runner = (CompactionRunner) runnable; LOG.debug("Compaction Rejected: " + runner); if (runner.compaction != null) { runner.store.cancelRequestedCompaction(runner.compaction); } } } } /** * {@inheritDoc} */ @Override public void onConfigurationChange(Configuration newConf) { // Check if number of large / small compaction threads has changed, and then // adjust the core pool size of the thread pools, by using the // setCorePoolSize() method. According to the javadocs, it is safe to // change the core pool size on-the-fly. We need to reset the maximum // pool size, as well. int largeThreads = Math.max(1, newConf.getInt(LARGE_COMPACTION_THREADS, LARGE_COMPACTION_THREADS_DEFAULT)); if (this.longCompactions.getCorePoolSize() != largeThreads) { LOG.info("Changing the value of " + LARGE_COMPACTION_THREADS + " from " + this.longCompactions.getCorePoolSize() + " to " + largeThreads); if (this.longCompactions.getCorePoolSize() < largeThreads) { this.longCompactions.setMaximumPoolSize(largeThreads); this.longCompactions.setCorePoolSize(largeThreads); } else { this.longCompactions.setCorePoolSize(largeThreads); this.longCompactions.setMaximumPoolSize(largeThreads); } } int smallThreads = newConf.getInt(SMALL_COMPACTION_THREADS, SMALL_COMPACTION_THREADS_DEFAULT); if (this.shortCompactions.getCorePoolSize() != smallThreads) { LOG.info("Changing the value of " + SMALL_COMPACTION_THREADS + " from " + this.shortCompactions.getCorePoolSize() + " to " + smallThreads); if (this.shortCompactions.getCorePoolSize() < smallThreads) { this.shortCompactions.setMaximumPoolSize(smallThreads); this.shortCompactions.setCorePoolSize(smallThreads); } else { this.shortCompactions.setCorePoolSize(smallThreads); this.shortCompactions.setMaximumPoolSize(smallThreads); } } int splitThreads = newConf.getInt(SPLIT_THREADS, SPLIT_THREADS_DEFAULT); if (this.splits.getCorePoolSize() != splitThreads) { LOG.info("Changing the value of " + SPLIT_THREADS + " from " + this.splits.getCorePoolSize() + " to " + splitThreads); if (this.splits.getCorePoolSize() < splitThreads) { this.splits.setMaximumPoolSize(splitThreads); this.splits.setCorePoolSize(splitThreads); } else { this.splits.setCorePoolSize(splitThreads); this.splits.setMaximumPoolSize(splitThreads); } } ThroughputController old = this.compactionThroughputController; if (old != null) { old.stop("configuration change"); } this.compactionThroughputController = CompactionThroughputControllerFactory.create(server, newConf); // We change this atomically here instead of reloading the config in order that upstream // would be the only one with the flexibility to reload the config. this.conf.reloadConfiguration(); } protected int getSmallCompactionThreadNum() { return this.shortCompactions.getCorePoolSize(); } protected int getLargeCompactionThreadNum() { return this.longCompactions.getCorePoolSize(); } protected int getSplitThreadNum() { return this.splits.getCorePoolSize(); } /** * {@inheritDoc} */ @Override public void registerChildren(ConfigurationManager manager) { // No children to register. } /** * {@inheritDoc} */ @Override public void deregisterChildren(ConfigurationManager manager) { // No children to register } public ThroughputController getCompactionThroughputController() { return compactionThroughputController; } /** * Shutdown the long compaction thread pool. Should only be used in unit test to prevent long * compaction thread pool from stealing job from short compaction queue */ void shutdownLongCompactions() { this.longCompactions.shutdown(); } public void clearLongCompactionsQueue() { longCompactions.getQueue().clear(); } public void clearShortCompactionsQueue() { shortCompactions.getQueue().clear(); } public boolean isCompactionsEnabled() { return compactionsEnabled; } public void setCompactionsEnabled(boolean compactionsEnabled) { this.compactionsEnabled = compactionsEnabled; this.conf.set(HBASE_REGION_SERVER_ENABLE_COMPACTION, String.valueOf(compactionsEnabled)); } /** Returns the longCompactions thread pool executor */ ThreadPoolExecutor getLongCompactions() { return longCompactions; } /** Returns the shortCompactions thread pool executor */ ThreadPoolExecutor getShortCompactions() { return shortCompactions; } private String getStoreNameForUnderCompaction(HStore store) { return String.format("%s:%s", store.getHRegion() != null ? store.getHRegion().getRegionInfo().getEncodedName() : "", store.getColumnFamilyName()); } }
HBASE-27332 Remove RejectedExecutionHandler for long/short compaction thread pools (#4731) Signed-off-by: Duo Zhang <[email protected]>
hbase-server/src/main/java/org/apache/hadoop/hbase/regionserver/CompactSplit.java
HBASE-27332 Remove RejectedExecutionHandler for long/short compaction thread pools (#4731)
<ide><path>base-server/src/main/java/org/apache/hadoop/hbase/regionserver/CompactSplit.java <ide> import java.util.concurrent.ConcurrentHashMap; <ide> import java.util.concurrent.Executors; <ide> import java.util.concurrent.RejectedExecutionException; <del>import java.util.concurrent.RejectedExecutionHandler; <ide> import java.util.concurrent.ThreadPoolExecutor; <ide> import java.util.concurrent.TimeUnit; <ide> import java.util.concurrent.atomic.AtomicInteger; <ide> final String n = Thread.currentThread().getName(); <ide> <ide> StealJobQueue<Runnable> stealJobQueue = new StealJobQueue<Runnable>(COMPARATOR); <add> // Since the StealJobQueue inner uses the PriorityBlockingQueue, <add> // which is an unbounded blocking queue, we remove the RejectedExecutionHandler for <add> // the long and short compaction thread pool executors since HBASE-27332. <add> // If anyone who what to change the StealJobQueue to a bounded queue, <add> // please add the rejection handler back. <ide> this.longCompactions = new ThreadPoolExecutor(largeThreads, largeThreads, 60, TimeUnit.SECONDS, <ide> stealJobQueue, <ide> new ThreadFactoryBuilder().setNameFormat(n + "-longCompactions-%d").setDaemon(true).build()); <del> this.longCompactions.setRejectedExecutionHandler(new Rejection()); <ide> this.longCompactions.prestartAllCoreThreads(); <ide> this.shortCompactions = new ThreadPoolExecutor(smallThreads, smallThreads, 60, TimeUnit.SECONDS, <ide> stealJobQueue.getStealFromQueue(), <ide> new ThreadFactoryBuilder().setNameFormat(n + "-shortCompactions-%d").setDaemon(true).build()); <del> this.shortCompactions.setRejectedExecutionHandler(new Rejection()); <ide> } <ide> <ide> @Override <ide> } <ide> <ide> /** <del> * Cleanup class to use when rejecting a compaction request from the queue. <del> */ <del> private static class Rejection implements RejectedExecutionHandler { <del> @Override <del> public void rejectedExecution(Runnable runnable, ThreadPoolExecutor pool) { <del> if (runnable instanceof CompactionRunner) { <del> CompactionRunner runner = (CompactionRunner) runnable; <del> LOG.debug("Compaction Rejected: " + runner); <del> if (runner.compaction != null) { <del> runner.store.cancelRequestedCompaction(runner.compaction); <del> } <del> } <del> } <del> } <del> <del> /** <ide> * {@inheritDoc} <ide> */ <ide> @Override
Java
apache-2.0
4f04fa641aa886f95d604bf8d65c6ba141d61bb1
0
eXcomm/autopsy,karlmortensen/autopsy,esaunders/autopsy,APriestman/autopsy,mhmdfy/autopsy,narfindustries/autopsy,rcordovano/autopsy,maxrp/autopsy,wschaeferB/autopsy,mhmdfy/autopsy,maxrp/autopsy,rcordovano/autopsy,wschaeferB/autopsy,eXcomm/autopsy,APriestman/autopsy,rcordovano/autopsy,esaunders/autopsy,APriestman/autopsy,wschaeferB/autopsy,dgrove727/autopsy,mhmdfy/autopsy,rcordovano/autopsy,wschaeferB/autopsy,esaunders/autopsy,rcordovano/autopsy,APriestman/autopsy,narfindustries/autopsy,esaunders/autopsy,APriestman/autopsy,APriestman/autopsy,karlmortensen/autopsy,eXcomm/autopsy,wschaeferB/autopsy,rcordovano/autopsy,millmanorama/autopsy,dgrove727/autopsy,narfindustries/autopsy,mhmdfy/autopsy,karlmortensen/autopsy,APriestman/autopsy,millmanorama/autopsy,millmanorama/autopsy,dgrove727/autopsy,maxrp/autopsy,maxrp/autopsy,karlmortensen/autopsy,eXcomm/autopsy,esaunders/autopsy,millmanorama/autopsy
/* * * Autopsy Forensic Browser * * Copyright 2012-15 Basis Technology Corp. * * Copyright 2012 42six Solutions. * Contact: aebadirad <at> 42six <dot> com * Project Contact/Architect: carrier <at> sleuthkit <dot> org * * 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.sleuthkit.autopsy.coreutils; import com.google.common.io.Files; import java.awt.Image; import java.awt.image.BufferedImage; import java.io.BufferedInputStream; import java.io.File; import java.io.IOException; import java.io.InputStream; import java.nio.file.Paths; import java.util.Arrays; import java.util.Collections; import java.util.List; import java.util.Objects; import static java.util.Objects.isNull; import java.util.SortedSet; import java.util.TreeSet; import java.util.concurrent.Executor; import java.util.concurrent.Executors; import java.util.logging.Level; import javax.annotation.Nonnull; import javax.annotation.Nullable; import javax.imageio.ImageIO; import org.apache.commons.lang3.StringUtils; import org.apache.commons.lang3.concurrent.BasicThreadFactory; import org.opencv.core.Core; import org.sleuthkit.autopsy.casemodule.Case; import org.sleuthkit.autopsy.corelibs.ScalrWrapper; import org.sleuthkit.autopsy.modules.filetypeid.FileTypeDetector; import org.sleuthkit.autopsy.modules.filetypeid.FileTypeDetector.FileTypeDetectorInitException; import org.sleuthkit.datamodel.AbstractFile; import org.sleuthkit.datamodel.Content; import org.sleuthkit.datamodel.ReadContentInputStream; import org.sleuthkit.datamodel.TskCoreException; /** * * Utilities for working with Images and creating thumbnails. Reuses thumbnails * by storing them in the case's cache directory. */ public class ImageUtils { private static final Logger LOGGER = Logger.getLogger(ImageUtils.class.getName()); /** save thumbnails to disk as this format */ private static final String FORMAT = "png"; //NON-NLS public static final int ICON_SIZE_SMALL = 50; public static final int ICON_SIZE_MEDIUM = 100; public static final int ICON_SIZE_LARGE = 200; private static final Logger logger = LOGGER; private static final BufferedImage DEFAULT_THUMBNAIL; private static final List<String> SUPPORTED_IMAGE_EXTENSIONS; private static final TreeSet<String> SUPPORTED_IMAGE_MIME_TYPES; private static final List<String> CONDITIONAL_MIME_TYPES = Arrays.asList("audio/x-aiff", "application/octet-stream"); private static final boolean openCVLoaded; static { ImageIO.scanForPlugins(); BufferedImage tempImage; try { tempImage = ImageIO.read(ImageUtils.class.getResourceAsStream("/org/sleuthkit/autopsy/images/file-icon.png"));//NON-NLS } catch (IOException ex) { LOGGER.log(Level.SEVERE, "Failed to load default icon.", ex); tempImage = null; } DEFAULT_THUMBNAIL = tempImage; //load opencv libraries boolean openCVLoadedTemp; try { System.loadLibrary(Core.NATIVE_LIBRARY_NAME); if (System.getProperty("os.arch").equals("amd64") || System.getProperty("os.arch").equals("x86_64")) { System.loadLibrary("opencv_ffmpeg248_64"); } else { System.loadLibrary("opencv_ffmpeg248"); } openCVLoadedTemp = true; } catch (UnsatisfiedLinkError e) { openCVLoadedTemp = false; LOGGER.log(Level.SEVERE, "OpenCV Native code library failed to load", e); //TODO: show warning bubble } openCVLoaded = openCVLoadedTemp; SUPPORTED_IMAGE_EXTENSIONS = Arrays.asList(ImageIO.getReaderFileSuffixes()); SUPPORTED_IMAGE_MIME_TYPES = new TreeSet<>(Arrays.asList(ImageIO.getReaderMIMETypes())); /* special cases and variants that we support, but don't get registered * with ImageIO automatically */ SUPPORTED_IMAGE_MIME_TYPES.addAll(Arrays.asList( "image/x-rgb", "image/x-ms-bmp", "image/x-portable-graymap", "image/x-portable-bitmap", "application/x-123")); SUPPORTED_IMAGE_MIME_TYPES.removeIf("application/octet-stream"::equals); } /** initialized lazily */ private static FileTypeDetector fileTypeDetector; /** thread that saves generated thumbnails to disk in the background */ private static final Executor imageSaver = Executors.newSingleThreadExecutor(new BasicThreadFactory.Builder() .namingPattern("icon saver-%d").build()); private ImageUtils() { } public static List<String> getSupportedImageExtensions() { return Collections.unmodifiableList(SUPPORTED_IMAGE_EXTENSIONS); } public static SortedSet<String> getSupportedImageMimeTypes() { return Collections.unmodifiableSortedSet(SUPPORTED_IMAGE_MIME_TYPES); } /** * Get the default thumbnail, which is the icon for a file. Used when we can * not * generate content based thumbnail. * * @return * * @deprecated use {@link #getDefaultThumbnail() } instead. */ @Deprecated public static Image getDefaultIcon() { return getDefaultThumbnail(); } /** * Get the default thumbnail, which is the icon for a file. Used when we can * not generate content based thumbnail. * * @return the default thumbnail */ public static Image getDefaultThumbnail() { return DEFAULT_THUMBNAIL; } /** * Can a thumbnail be generated for the content? * * @param content * * @return * */ public static boolean thumbnailSupported(Content content) { if (content.getSize() == 0) { return false; } if (!(content instanceof AbstractFile)) { return false; } AbstractFile file = (AbstractFile) content; return VideoUtils.isVideoThumbnailSupported(file) || isImageThumbnailSupported(file); } public static boolean isImageThumbnailSupported(AbstractFile file) { return isMediaThumbnailSupported(file, SUPPORTED_IMAGE_MIME_TYPES, SUPPORTED_IMAGE_EXTENSIONS, CONDITIONAL_MIME_TYPES) || hasImageFileHeader(file); } /** * Check if a file is "supported" by checking it mimetype and extension * * //TODO: this should move to a better place. Should ImageUtils and * VideoUtils both implement/extend some base interface/abstract class. That * would be the natural place to put this. * * @param file * @param supportedMimeTypes a set of mimetypes that the could have to be * supported * @param supportedExtension a set of extensions a file could have to be * supported if the mime lookup fails or is * inconclusive * @param conditionalMimes a set of mimetypes that a file could have to be * supoprted if it also has a supported extension * * @return true if a thumbnail can be generated for the given file with the * given lists of supported mimetype and extensions */ static boolean isMediaThumbnailSupported(AbstractFile file, final SortedSet<String> supportedMimeTypes, final List<String> supportedExtension, List<String> conditionalMimes) { if (file.getSize() == 0) { return false; } final String extension = file.getNameExtension(); try { String mimeType = getFileTypeDetector().getFileType(file); if (Objects.nonNull(mimeType)) { return supportedMimeTypes.contains(mimeType) || (conditionalMimes.contains(mimeType.toLowerCase()) && supportedExtension.contains(extension)); } } catch (FileTypeDetector.FileTypeDetectorInitException | TskCoreException ex) { LOGGER.log(Level.WARNING, "Failed to look up mimetype for " + file.getName() + " using FileTypeDetector. Fallingback on AbstractFile.isMimeType", ex); AbstractFile.MimeMatchEnum mimeMatch = file.isMimeType(supportedMimeTypes); if (mimeMatch == AbstractFile.MimeMatchEnum.TRUE) { return true; } else if (mimeMatch == AbstractFile.MimeMatchEnum.FALSE) { return false; } } // if we have an extension, check it return StringUtils.isNotBlank(extension) && supportedExtension.contains(extension); } /** * returns a lazily instatiated FileTypeDetector * * @return a FileTypeDetector * * @throws FileTypeDetectorInitException if a initializing the * FileTypeDetector failed. */ synchronized private static FileTypeDetector getFileTypeDetector() throws FileTypeDetector.FileTypeDetectorInitException { if (fileTypeDetector == null) { fileTypeDetector = new FileTypeDetector(); } return fileTypeDetector; } /** * Get a thumbnail of a specified size. Generates the image if it is * not already cached. * * @param content * @param iconSize * * * @return a thumbnail for the given image or a default one if there was a * problem making a thumbnail. * * @deprecated use {@link #getThumbnail(org.sleuthkit.datamodel.Content, int) * } instead. * */ @Nonnull @Deprecated public static Image getIcon(Content content, int iconSize) { return getThumbnail(content, iconSize); } /** * Get a thumbnail of a specified size. Generates the image if it is * not already cached. * * @param content * @param iconSize * * @return a thumbnail for the given image or a default one if there was a * problem making a thumbnail. */ public static Image getThumbnail(Content content, int iconSize) { if (content instanceof AbstractFile) { AbstractFile file = (AbstractFile) content; // If a thumbnail file is already saved locally File cacheFile = getCachedThumbnailLocation(content.getId()); if (cacheFile.exists()) { try { BufferedImage thumbnail = ImageIO.read(cacheFile); if (isNull(thumbnail) || thumbnail.getWidth() != iconSize) { return generateAndSaveThumbnail(file, iconSize, cacheFile); } else { return thumbnail; } } catch (Exception ex) { LOGGER.log(Level.WARNING, "Error while reading image: " + content.getName(), ex); //NON-NLS return generateAndSaveThumbnail(file, iconSize, cacheFile); } } else { return generateAndSaveThumbnail(file, iconSize, cacheFile); } } else { return DEFAULT_THUMBNAIL; } } /** * Get a thumbnail of a specified size. Generates the image if it is * not already cached. * * @param content * @param iconSize * * @return File object for cached image. Is guaranteed to exist, as long as * there was not an error generating or saving the thumbnail. * * @deprecated use {@link #getCachedThumbnailFile(org.sleuthkit.datamodel.Content, int) * } instead. * */ @Nullable @Deprecated public static File getIconFile(Content content, int iconSize) { return getCachedThumbnailFile(content, iconSize); } /** * * Get a thumbnail of a specified size. Generates the image if it is * not already cached. * * @param content * @param iconSize * * @return File object for cached image. Is guaranteed to exist, as long as * there was not an error generating or saving the thumbnail. */ @Nullable public static File getCachedThumbnailFile(Content content, int iconSize) { getThumbnail(content, iconSize); return getCachedThumbnailLocation(content.getId()); } /** * Get a file object for where the cached icon should exist. The returned * file may not exist. * * @param id * * @return * * * @deprecated use {@link #getCachedThumbnailLocation(long) } instead */ @Deprecated public static File getFile(long id) { return getCachedThumbnailLocation(id); } /** * Get a file object for where the cached icon should exist. The returned * file may not exist. * * @param fileID * * @return * */ private static File getCachedThumbnailLocation(long fileID) { return Paths.get(Case.getCurrentCase().getCacheDirectory(), "thumbnails", fileID + ".png").toFile(); } public static boolean hasImageFileHeader(AbstractFile file) { return isJpegFileHeader(file) || isPngFileHeader(file); } /** * Check if the given file is a jpeg based on header. * * @param file * * @return true if jpeg file, false otherwise */ public static boolean isJpegFileHeader(AbstractFile file) { if (file.getSize() < 100) { return false; } try { byte[] fileHeaderBuffer = readHeader(file, 2); /* Check for the JPEG header. Since Java bytes are signed, we cast * them to an int first. */ return (((fileHeaderBuffer[0] & 0xff) == 0xff) && ((fileHeaderBuffer[1] & 0xff) == 0xd8)); } catch (TskCoreException ex) { //ignore if can't read the first few bytes, not a JPEG return false; } } /** * Check if the given file is a png based on header. * * @param file * * @return true if png file, false otherwise */ public static boolean isPngFileHeader(AbstractFile file) { if (file.getSize() < 10) { return false; } try { byte[] fileHeaderBuffer = readHeader(file, 8); /* Check for the png header. Since Java bytes are signed, we cast * them to an int first. */ return (((fileHeaderBuffer[1] & 0xff) == 0x50) && ((fileHeaderBuffer[2] & 0xff) == 0x4E) && ((fileHeaderBuffer[3] & 0xff) == 0x47) && ((fileHeaderBuffer[4] & 0xff) == 0x0D) && ((fileHeaderBuffer[5] & 0xff) == 0x0A) && ((fileHeaderBuffer[6] & 0xff) == 0x1A) && ((fileHeaderBuffer[7] & 0xff) == 0x0A)); } catch (TskCoreException ex) { //ignore if can't read the first few bytes, not an png return false; } } private static byte[] readHeader(AbstractFile file, int buffLength) throws TskCoreException { byte[] fileHeaderBuffer = new byte[buffLength]; int bytesRead = file.read(fileHeaderBuffer, 0, buffLength); if (bytesRead != buffLength) { //ignore if can't read the first few bytes, not an image throw new TskCoreException("Could not read " + buffLength + " bytes from " + file.getName()); } return fileHeaderBuffer; } /** * Generate an icon and save it to specified location. * * @param file File to generate icon for * @param iconSize * @param cacheFile Location to save thumbnail to * * @return Generated icon or null on error */ private static Image generateAndSaveThumbnail(AbstractFile file, int iconSize, File cacheFile) { BufferedImage thumbnail = null; try { if (VideoUtils.isVideoThumbnailSupported(file)) { if (openCVLoaded) { thumbnail = VideoUtils.generateVideoThumbnail(file, iconSize); } else { return DEFAULT_THUMBNAIL; } } else { thumbnail = generateImageThumbnail(file, iconSize); } if (thumbnail == null) { return DEFAULT_THUMBNAIL; } else { BufferedImage toSave = thumbnail; imageSaver.execute(() -> { try { Files.createParentDirs(cacheFile); if (cacheFile.exists()) { cacheFile.delete(); } ImageIO.write(toSave, FORMAT, cacheFile); } catch (IllegalArgumentException | IOException ex1) { LOGGER.log(Level.WARNING, "Could not write cache thumbnail: " + file, ex1); //NON-NLS } }); } } catch (NullPointerException ex) { logger.log(Level.WARNING, "Could not write cache thumbnail: " + file, ex); //NON-NLS } return thumbnail; } /** * * Generate and return a scaled image * * @param content * @param iconSize * * @return a Thumbnail of the given content at the given size, or null if * there was a problem. */ @Nullable private static BufferedImage generateImageThumbnail(Content content, int iconSize) { try (InputStream inputStream = new BufferedInputStream(new ReadContentInputStream(content));) { BufferedImage bi = ImageIO.read(inputStream); if (bi == null) { LOGGER.log(Level.WARNING, "No image reader for file: {0}", content.getName()); //NON-NLS return null; } try { return ScalrWrapper.resizeFast(bi, iconSize); } catch (IllegalArgumentException e) { // if resizing does not work due to extreme aspect ratio, // crop the image instead. return ScalrWrapper.cropImage(bi, Math.min(iconSize, bi.getWidth()), Math.min(iconSize, bi.getHeight())); } } catch (OutOfMemoryError e) { LOGGER.log(Level.WARNING, "Could not scale image (too large): " + content.getName(), e); //NON-NLS return null; } catch (Exception e) { LOGGER.log(Level.WARNING, "Could not load image: " + content.getName(), e); //NON-NLS return null; } } }
Core/src/org/sleuthkit/autopsy/coreutils/ImageUtils.java
/* * * Autopsy Forensic Browser * * Copyright 2012-15 Basis Technology Corp. * * Copyright 2012 42six Solutions. * Contact: aebadirad <at> 42six <dot> com * Project Contact/Architect: carrier <at> sleuthkit <dot> org * * 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.sleuthkit.autopsy.coreutils; import com.google.common.io.Files; import java.awt.Image; import java.awt.image.BufferedImage; import java.io.BufferedInputStream; import java.io.File; import java.io.IOException; import java.io.InputStream; import java.nio.file.Paths; import java.util.Arrays; import java.util.Collections; import java.util.List; import java.util.Objects; import static java.util.Objects.isNull; import java.util.SortedSet; import java.util.TreeSet; import java.util.concurrent.Executor; import java.util.concurrent.Executors; import java.util.logging.Level; import javax.annotation.Nonnull; import javax.annotation.Nullable; import javax.imageio.ImageIO; import org.apache.commons.lang3.StringUtils; import org.apache.commons.lang3.concurrent.BasicThreadFactory; import org.opencv.core.Core; import org.sleuthkit.autopsy.casemodule.Case; import org.sleuthkit.autopsy.corelibs.ScalrWrapper; import org.sleuthkit.autopsy.modules.filetypeid.FileTypeDetector; import org.sleuthkit.autopsy.modules.filetypeid.FileTypeDetector.FileTypeDetectorInitException; import org.sleuthkit.datamodel.AbstractFile; import org.sleuthkit.datamodel.Content; import org.sleuthkit.datamodel.ReadContentInputStream; import org.sleuthkit.datamodel.TskCoreException; /** * * Utilities for working with Images and creating thumbnails. Reuses thumbnails * by storing them in the case's cache directory. */ public class ImageUtils { private static final Logger LOGGER = Logger.getLogger(ImageUtils.class.getName()); /** save thumbnails to disk as this format */ private static final String FORMAT = "png"; //NON-NLS public static final int ICON_SIZE_SMALL = 50; public static final int ICON_SIZE_MEDIUM = 100; public static final int ICON_SIZE_LARGE = 200; private static final Logger logger = LOGGER; private static final BufferedImage DEFAULT_THUMBNAIL; private static final List<String> SUPPORTED_IMAGE_EXTENSIONS; private static final TreeSet<String> SUPPORTED_IMAGE_MIME_TYPES; private static final List<String> CONDITIONAL_MIME_TYPES = Arrays.asList("audio/x-aiff", "application/octet-stream"); private static final boolean openCVLoaded; static { ImageIO.scanForPlugins(); BufferedImage tempImage; try { tempImage = ImageIO.read(ImageUtils.class.getResourceAsStream("/org/sleuthkit/autopsy/images/file-icon.png"));//NON-NLS } catch (IOException ex) { LOGGER.log(Level.SEVERE, "Failed to load default icon.", ex); tempImage = null; } DEFAULT_THUMBNAIL = tempImage; //load opencv libraries boolean openCVLoadedTemp; try { System.loadLibrary(Core.NATIVE_LIBRARY_NAME); if (System.getProperty("os.arch").equals("amd64") || System.getProperty("os.arch").equals("x86_64")) { System.loadLibrary("opencv_ffmpeg248_64"); } else { System.loadLibrary("opencv_ffmpeg248"); } openCVLoadedTemp = true; } catch (UnsatisfiedLinkError e) { openCVLoadedTemp = false; LOGGER.log(Level.SEVERE, "OpenCV Native code library failed to load", e); //TODO: show warning bubble } openCVLoaded = openCVLoadedTemp; SUPPORTED_IMAGE_EXTENSIONS = Arrays.asList(ImageIO.getReaderFileSuffixes()); SUPPORTED_IMAGE_MIME_TYPES = new TreeSet<>(Arrays.asList(ImageIO.getReaderMIMETypes())); /* special cases and variants that we support, but don't get registered * with ImageIO automatically */ SUPPORTED_IMAGE_MIME_TYPES.addAll(Arrays.asList( "image/x-rgb", "image/x-ms-bmp", "application/x-123")); SUPPORTED_IMAGE_MIME_TYPES.removeIf("application/octet-stream"::equals); } /** initialized lazily */ private static FileTypeDetector fileTypeDetector; /** thread that saves generated thumbnails to disk in the background */ private static final Executor imageSaver = Executors.newSingleThreadExecutor(new BasicThreadFactory.Builder() .namingPattern("icon saver-%d").build()); private ImageUtils() { } public static List<String> getSupportedImageExtensions() { return Collections.unmodifiableList(SUPPORTED_IMAGE_EXTENSIONS); } public static SortedSet<String> getSupportedImageMimeTypes() { return Collections.unmodifiableSortedSet(SUPPORTED_IMAGE_MIME_TYPES); } /** * Get the default thumbnail, which is the icon for a file. Used when we can * not * generate content based thumbnail. * * @return * * @deprecated use {@link #getDefaultThumbnail() } instead. */ @Deprecated public static Image getDefaultIcon() { return getDefaultThumbnail(); } /** * Get the default thumbnail, which is the icon for a file. Used when we can * not generate content based thumbnail. * * @return the default thumbnail */ public static Image getDefaultThumbnail() { return DEFAULT_THUMBNAIL; } /** * Can a thumbnail be generated for the content? * * @param content * * @return * */ public static boolean thumbnailSupported(Content content) { if (content.getSize() == 0) { return false; } if (!(content instanceof AbstractFile)) { return false; } AbstractFile file = (AbstractFile) content; return VideoUtils.isVideoThumbnailSupported(file) || isImageThumbnailSupported(file); } public static boolean isImageThumbnailSupported(AbstractFile file) { return isMediaThumbnailSupported(file, SUPPORTED_IMAGE_MIME_TYPES, SUPPORTED_IMAGE_EXTENSIONS, CONDITIONAL_MIME_TYPES) || hasImageFileHeader(file); } /** * Check if a file is "supported" by checking it mimetype and extension * * //TODO: this should move to a better place. Should ImageUtils and * VideoUtils both implement/extend some base interface/abstract class. That * would be the natural place to put this. * * @param file * @param supportedMimeTypes a set of mimetypes that the could have to be * supported * @param supportedExtension a set of extensions a file could have to be * supported if the mime lookup fails or is * inconclusive * @param conditionalMimes a set of mimetypes that a file could have to be * supoprted if it also has a supported extension * * @return true if a thumbnail can be generated for the given file with the * given lists of supported mimetype and extensions */ static boolean isMediaThumbnailSupported(AbstractFile file, final SortedSet<String> supportedMimeTypes, final List<String> supportedExtension, List<String> conditionalMimes) { if (file.getSize() == 0) { return false; } final String extension = file.getNameExtension(); try { String mimeType = getFileTypeDetector().getFileType(file); if (Objects.nonNull(mimeType)) { return supportedMimeTypes.contains(mimeType) || (conditionalMimes.contains(mimeType.toLowerCase()) && supportedExtension.contains(extension)); } } catch (FileTypeDetector.FileTypeDetectorInitException | TskCoreException ex) { LOGGER.log(Level.WARNING, "Failed to look up mimetype for " + file.getName() + " using FileTypeDetector. Fallingback on AbstractFile.isMimeType", ex); AbstractFile.MimeMatchEnum mimeMatch = file.isMimeType(supportedMimeTypes); if (mimeMatch == AbstractFile.MimeMatchEnum.TRUE) { return true; } else if (mimeMatch == AbstractFile.MimeMatchEnum.FALSE) { return false; } } // if we have an extension, check it return StringUtils.isNotBlank(extension) && supportedExtension.contains(extension); } /** * returns a lazily instatiated FileTypeDetector * * @return a FileTypeDetector * * @throws FileTypeDetectorInitException if a initializing the * FileTypeDetector failed. */ synchronized private static FileTypeDetector getFileTypeDetector() throws FileTypeDetector.FileTypeDetectorInitException { if (fileTypeDetector == null) { fileTypeDetector = new FileTypeDetector(); } return fileTypeDetector; } /** * Get a thumbnail of a specified size. Generates the image if it is * not already cached. * * @param content * @param iconSize * * * @return a thumbnail for the given image or a default one if there was a * problem making a thumbnail. * * @deprecated use {@link #getThumbnail(org.sleuthkit.datamodel.Content, int) * } instead. * */ @Nonnull @Deprecated public static Image getIcon(Content content, int iconSize) { return getThumbnail(content, iconSize); } /** * Get a thumbnail of a specified size. Generates the image if it is * not already cached. * * @param content * @param iconSize * * @return a thumbnail for the given image or a default one if there was a * problem making a thumbnail. */ public static Image getThumbnail(Content content, int iconSize) { if (content instanceof AbstractFile) { AbstractFile file = (AbstractFile) content; // If a thumbnail file is already saved locally File cacheFile = getCachedThumbnailLocation(content.getId()); if (cacheFile.exists()) { try { BufferedImage thumbnail = ImageIO.read(cacheFile); if (isNull(thumbnail) || thumbnail.getWidth() != iconSize) { return generateAndSaveThumbnail(file, iconSize, cacheFile); } else { return thumbnail; } } catch (Exception ex) { LOGGER.log(Level.WARNING, "Error while reading image: " + content.getName(), ex); //NON-NLS return generateAndSaveThumbnail(file, iconSize, cacheFile); } } else { return generateAndSaveThumbnail(file, iconSize, cacheFile); } } else { return DEFAULT_THUMBNAIL; } } /** * Get a thumbnail of a specified size. Generates the image if it is * not already cached. * * @param content * @param iconSize * * @return File object for cached image. Is guaranteed to exist, as long as * there was not an error generating or saving the thumbnail. * * @deprecated use {@link #getCachedThumbnailFile(org.sleuthkit.datamodel.Content, int) * } instead. * */ @Nullable @Deprecated public static File getIconFile(Content content, int iconSize) { return getCachedThumbnailFile(content, iconSize); } /** * * Get a thumbnail of a specified size. Generates the image if it is * not already cached. * * @param content * @param iconSize * * @return File object for cached image. Is guaranteed to exist, as long as * there was not an error generating or saving the thumbnail. */ @Nullable public static File getCachedThumbnailFile(Content content, int iconSize) { getThumbnail(content, iconSize); return getCachedThumbnailLocation(content.getId()); } /** * Get a file object for where the cached icon should exist. The returned * file may not exist. * * @param id * * @return * * * @deprecated use {@link #getCachedThumbnailLocation(long) } instead */ @Deprecated public static File getFile(long id) { return getCachedThumbnailLocation(id); } /** * Get a file object for where the cached icon should exist. The returned * file may not exist. * * @param fileID * * @return * */ private static File getCachedThumbnailLocation(long fileID) { return Paths.get(Case.getCurrentCase().getCacheDirectory(), "thumbnails", fileID + ".png").toFile(); } public static boolean hasImageFileHeader(AbstractFile file) { return isJpegFileHeader(file) || isPngFileHeader(file); } /** * Check if the given file is a jpeg based on header. * * @param file * * @return true if jpeg file, false otherwise */ public static boolean isJpegFileHeader(AbstractFile file) { if (file.getSize() < 100) { return false; } try { byte[] fileHeaderBuffer = readHeader(file, 2); /* Check for the JPEG header. Since Java bytes are signed, we cast * them to an int first. */ return (((fileHeaderBuffer[0] & 0xff) == 0xff) && ((fileHeaderBuffer[1] & 0xff) == 0xd8)); } catch (TskCoreException ex) { //ignore if can't read the first few bytes, not a JPEG return false; } } /** * Check if the given file is a png based on header. * * @param file * * @return true if png file, false otherwise */ public static boolean isPngFileHeader(AbstractFile file) { if (file.getSize() < 10) { return false; } try { byte[] fileHeaderBuffer = readHeader(file, 8); /* Check for the png header. Since Java bytes are signed, we cast * them to an int first. */ return (((fileHeaderBuffer[1] & 0xff) == 0x50) && ((fileHeaderBuffer[2] & 0xff) == 0x4E) && ((fileHeaderBuffer[3] & 0xff) == 0x47) && ((fileHeaderBuffer[4] & 0xff) == 0x0D) && ((fileHeaderBuffer[5] & 0xff) == 0x0A) && ((fileHeaderBuffer[6] & 0xff) == 0x1A) && ((fileHeaderBuffer[7] & 0xff) == 0x0A)); } catch (TskCoreException ex) { //ignore if can't read the first few bytes, not an png return false; } } private static byte[] readHeader(AbstractFile file, int buffLength) throws TskCoreException { byte[] fileHeaderBuffer = new byte[buffLength]; int bytesRead = file.read(fileHeaderBuffer, 0, buffLength); if (bytesRead != buffLength) { //ignore if can't read the first few bytes, not an image throw new TskCoreException("Could not read " + buffLength + " bytes from " + file.getName()); } return fileHeaderBuffer; } /** * Generate an icon and save it to specified location. * * @param file File to generate icon for * @param iconSize * @param cacheFile Location to save thumbnail to * * @return Generated icon or null on error */ private static Image generateAndSaveThumbnail(AbstractFile file, int iconSize, File cacheFile) { BufferedImage thumbnail = null; try { if (VideoUtils.isVideoThumbnailSupported(file)) { if (openCVLoaded) { thumbnail = VideoUtils.generateVideoThumbnail(file, iconSize); } else { return DEFAULT_THUMBNAIL; } } else { thumbnail = generateImageThumbnail(file, iconSize); } if (thumbnail == null) { return DEFAULT_THUMBNAIL; } else { BufferedImage toSave = thumbnail; imageSaver.execute(() -> { try { Files.createParentDirs(cacheFile); if (cacheFile.exists()) { cacheFile.delete(); } ImageIO.write(toSave, FORMAT, cacheFile); } catch (IllegalArgumentException | IOException ex1) { LOGGER.log(Level.WARNING, "Could not write cache thumbnail: " + file, ex1); //NON-NLS } }); } } catch (NullPointerException ex) { logger.log(Level.WARNING, "Could not write cache thumbnail: " + file, ex); //NON-NLS } return thumbnail; } /** * * Generate and return a scaled image * * @param content * @param iconSize * * @return a Thumbnail of the given content at the given size, or null if * there was a problem. */ @Nullable private static BufferedImage generateImageThumbnail(Content content, int iconSize) { try (InputStream inputStream = new BufferedInputStream(new ReadContentInputStream(content));) { BufferedImage bi = ImageIO.read(inputStream); if (bi == null) { LOGGER.log(Level.WARNING, "No image reader for file: {0}", content.getName()); //NON-NLS return null; } try { return ScalrWrapper.resizeFast(bi, iconSize); } catch (IllegalArgumentException e) { // if resizing does not work due to extreme aspect ratio, // crop the image instead. return ScalrWrapper.cropImage(bi, Math.min(iconSize, bi.getWidth()), Math.min(iconSize, bi.getHeight())); } } catch (OutOfMemoryError e) { LOGGER.log(Level.WARNING, "Could not scale image (too large): " + content.getName(), e); //NON-NLS return null; } catch (Exception e) { LOGGER.log(Level.WARNING, "Could not load image: " + content.getName(), e); //NON-NLS return null; } } }
add mimetypes that are supported but seam to be missing from the ones reported.
Core/src/org/sleuthkit/autopsy/coreutils/ImageUtils.java
add mimetypes that are supported but seam to be missing from the ones reported.
<ide><path>ore/src/org/sleuthkit/autopsy/coreutils/ImageUtils.java <ide> SUPPORTED_IMAGE_MIME_TYPES.addAll(Arrays.asList( <ide> "image/x-rgb", <ide> "image/x-ms-bmp", <add> "image/x-portable-graymap", <add> "image/x-portable-bitmap", <ide> "application/x-123")); <ide> SUPPORTED_IMAGE_MIME_TYPES.removeIf("application/octet-stream"::equals); <ide> }
Java
apache-2.0
0a5a7da23e9352e85975ce74228cb12875617dec
0
deveth0/bitcointrader,deveth0/bitcointrader,deveth0/bitcointrader
//$URL$ //$Id$ package de.dev.eth0.bitcointrader.ui.fragments; import android.app.Activity; import android.content.BroadcastReceiver; import android.content.Context; import android.content.Intent; import android.content.IntentFilter; import android.content.SharedPreferences; import android.os.Bundle; import android.preference.PreferenceManager; import android.support.v4.content.LocalBroadcastManager; import android.text.TextUtils; import android.util.Log; import android.view.LayoutInflater; import android.view.View; import android.view.View.OnClickListener; import android.view.ViewGroup; import android.widget.Button; import de.dev.eth0.bitcointrader.BitcoinTraderApplication; import de.dev.eth0.bitcointrader.Constants; import de.dev.eth0.bitcointrader.R; import de.dev.eth0.bitcointrader.ui.AbstractBitcoinTraderActivity; import de.dev.eth0.bitcointrader.ui.TrailingStopLossActivity; import de.dev.eth0.bitcointrader.util.FormatHelper; import org.joda.money.BigMoney; /** * @author Alexander Muthmann */ public class TrailingStopLossActionsFragment extends AbstractBitcoinTraderFragment { private static final String TAG = TrailingStopLossActionsFragment.class.getSimpleName(); private AbstractBitcoinTraderActivity activity; private BitcoinTraderApplication application; private Button activateStopLossButton; private BroadcastReceiver broadcastReceiver; private LocalBroadcastManager broadcastManager; @Override public void onResume() { super.onResume(); broadcastReceiver = new BroadcastReceiver() { @Override public void onReceive(Context context, Intent intent) { Log.d(TAG, ".onReceive"); updateView(); } }; broadcastManager = LocalBroadcastManager.getInstance(application); broadcastManager.registerReceiver(broadcastReceiver, new IntentFilter(Constants.TRAILING_LOSS_ALIGNMENT_EVENT)); broadcastManager.registerReceiver(broadcastReceiver, new IntentFilter(Constants.TRAILING_LOSS_EVENT)); broadcastManager.registerReceiver(broadcastReceiver, new IntentFilter(Constants.CURRENCY_CHANGE_EVENT)); updateView(); } @Override public void onPause() { super.onPause(); if (broadcastReceiver != null) { broadcastManager.unregisterReceiver(broadcastReceiver); broadcastReceiver = null; } } @Override public void onAttach(Activity activity) { super.onAttach(activity); this.activity = (AbstractBitcoinTraderActivity)getActivity(); this.application = this.activity.getBitcoinTraderApplication(); } @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { View view = inflater.inflate(R.layout.trailing_stop_actions_fragment, container); activateStopLossButton = (Button)view.findViewById(R.id.trailing_stop_actions_stop_loss_button); updateView(); return view; } private void updateView() { SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(getActivity()); Float threashold = prefs.getFloat(Constants.PREFS_TRAILING_STOP_THREASHOLD, Float.MIN_VALUE); String value = prefs.getString(Constants.PREFS_TRAILING_STOP_VALUE, ""); if (threashold == Float.MIN_VALUE) { activateStopLossButton.setOnClickListener(new OnClickListener() { public void onClick(View v) { activity.startActivity(new Intent(activity, TrailingStopLossActivity.class)); } }); activateStopLossButton.setText(R.string.trailing_stop_activate_stop_loss); } else { activateStopLossButton.setOnClickListener(new OnClickListener() { public void onClick(View v) { SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(getActivity()); prefs.edit().remove(Constants.PREFS_TRAILING_STOP_THREASHOLD).apply(); updateView(); } }); if (getExchangeService() != null && !TextUtils.isEmpty(getExchangeService().getCurrency())) { BigMoney valueBM = BigMoney.parse(getExchangeService().getCurrency() + " " + value); activateStopLossButton.setText(getString(R.string.trailing_stop_cancel_stop_loss, threashold, FormatHelper.formatBigMoney(FormatHelper.DISPLAY_MODE.CURRENCY_CODE, valueBM)) + "%)"); } } } }
BitcoinTrader/src/de/dev/eth0/bitcointrader/ui/fragments/TrailingStopLossActionsFragment.java
//$URL$ //$Id$ package de.dev.eth0.bitcointrader.ui.fragments; import android.app.Activity; import android.content.BroadcastReceiver; import android.content.Context; import android.content.Intent; import android.content.IntentFilter; import android.content.SharedPreferences; import android.os.Bundle; import android.preference.PreferenceManager; import android.support.v4.content.LocalBroadcastManager; import android.util.Log; import android.view.LayoutInflater; import android.view.View; import android.view.View.OnClickListener; import android.view.ViewGroup; import android.widget.Button; import de.dev.eth0.bitcointrader.BitcoinTraderApplication; import de.dev.eth0.bitcointrader.Constants; import de.dev.eth0.bitcointrader.R; import de.dev.eth0.bitcointrader.ui.AbstractBitcoinTraderActivity; import de.dev.eth0.bitcointrader.ui.TrailingStopLossActivity; import de.dev.eth0.bitcointrader.util.FormatHelper; import org.joda.money.BigMoney; /** * @author Alexander Muthmann */ public class TrailingStopLossActionsFragment extends AbstractBitcoinTraderFragment { private static final String TAG = TrailingStopLossActionsFragment.class.getSimpleName(); private AbstractBitcoinTraderActivity activity; private BitcoinTraderApplication application; private Button activateStopLossButton; private BroadcastReceiver broadcastReceiver; private LocalBroadcastManager broadcastManager; @Override public void onResume() { super.onResume(); broadcastReceiver = new BroadcastReceiver() { @Override public void onReceive(Context context, Intent intent) { Log.d(TAG, ".onReceive"); updateView(); } }; broadcastManager = LocalBroadcastManager.getInstance(application); broadcastManager.registerReceiver(broadcastReceiver, new IntentFilter(Constants.TRAILING_LOSS_ALIGNMENT_EVENT)); broadcastManager.registerReceiver(broadcastReceiver, new IntentFilter(Constants.TRAILING_LOSS_EVENT)); broadcastManager.registerReceiver(broadcastReceiver, new IntentFilter(Constants.CURRENCY_CHANGE_EVENT)); updateView(); } @Override public void onPause() { super.onPause(); if (broadcastReceiver != null) { broadcastManager.unregisterReceiver(broadcastReceiver); broadcastReceiver = null; } } @Override public void onAttach(Activity activity) { super.onAttach(activity); this.activity = (AbstractBitcoinTraderActivity)getActivity(); this.application = this.activity.getBitcoinTraderApplication(); } @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { View view = inflater.inflate(R.layout.trailing_stop_actions_fragment, container); activateStopLossButton = (Button)view.findViewById(R.id.trailing_stop_actions_stop_loss_button); updateView(); return view; } private void updateView() { SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(getActivity()); Float threashold = prefs.getFloat(Constants.PREFS_TRAILING_STOP_THREASHOLD, Float.MIN_VALUE); String value = prefs.getString(Constants.PREFS_TRAILING_STOP_VALUE, ""); if (threashold == Float.MIN_VALUE) { activateStopLossButton.setOnClickListener(new OnClickListener() { public void onClick(View v) { activity.startActivity(new Intent(activity, TrailingStopLossActivity.class)); } }); activateStopLossButton.setText(R.string.trailing_stop_activate_stop_loss); } else { activateStopLossButton.setOnClickListener(new OnClickListener() { public void onClick(View v) { SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(getActivity()); prefs.edit().remove(Constants.PREFS_TRAILING_STOP_THREASHOLD).apply(); updateView(); } }); BigMoney valueBM = BigMoney.parse(getExchangeService().getCurrency() + " " + value); activateStopLossButton.setText(getString(R.string.trailing_stop_cancel_stop_loss, threashold, FormatHelper.formatBigMoney(FormatHelper.DISPLAY_MODE.CURRENCY_CODE, valueBM)) + "%)"); } } }
Bitcointrader: fixes #127 (NPE ) git-svn-id: a355d1b694e879546a774084536e9dc3bacb52b5@293 46fdfbd1-27fd-a4d1-f970-16196c59cddc
BitcoinTrader/src/de/dev/eth0/bitcointrader/ui/fragments/TrailingStopLossActionsFragment.java
Bitcointrader: fixes #127 (NPE )
<ide><path>itcoinTrader/src/de/dev/eth0/bitcointrader/ui/fragments/TrailingStopLossActionsFragment.java <ide> import android.os.Bundle; <ide> import android.preference.PreferenceManager; <ide> import android.support.v4.content.LocalBroadcastManager; <add>import android.text.TextUtils; <ide> import android.util.Log; <ide> import android.view.LayoutInflater; <ide> import android.view.View; <ide> updateView(); <ide> } <ide> }); <del> BigMoney valueBM = BigMoney.parse(getExchangeService().getCurrency() + " " + value); <del> activateStopLossButton.setText(getString(R.string.trailing_stop_cancel_stop_loss, threashold, FormatHelper.formatBigMoney(FormatHelper.DISPLAY_MODE.CURRENCY_CODE, valueBM)) + "%)"); <add> if (getExchangeService() != null && !TextUtils.isEmpty(getExchangeService().getCurrency())) { <add> BigMoney valueBM = BigMoney.parse(getExchangeService().getCurrency() + " " + value); <add> activateStopLossButton.setText(getString(R.string.trailing_stop_cancel_stop_loss, threashold, FormatHelper.formatBigMoney(FormatHelper.DISPLAY_MODE.CURRENCY_CODE, valueBM)) + "%)"); <add> } <ide> } <ide> } <ide> }
Java
apache-2.0
7079795b811bc8bbff3b280c9ba88ba263ca8356
0
SpineEventEngine/core-java,SpineEventEngine/core-java,SpineEventEngine/core-java
/* * Copyright 2020, TeamDev. All rights reserved. * * Redistribution and use in source and/or binary forms, with or without * modification, must retain the above copyright notice and the following * disclaimer. * * 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 io.spine.client; import com.google.common.annotations.VisibleForTesting; import com.google.protobuf.Message; import io.grpc.ManagedChannel; import io.grpc.stub.StreamObserver; import io.spine.base.Identifier; import io.spine.client.grpc.SubscriptionServiceGrpc; import io.spine.client.grpc.SubscriptionServiceGrpc.SubscriptionServiceBlockingStub; import io.spine.client.grpc.SubscriptionServiceGrpc.SubscriptionServiceStub; import java.util.Collection; import java.util.HashSet; import java.util.Iterator; import java.util.Set; import static com.google.common.base.Preconditions.checkNotNull; import static java.lang.String.format; import static java.util.Collections.synchronizedSet; /** * Maintains the list of the <strong>active</strong> subscriptions created by the {@link Client}. * * <p>Subscriptions are created when a client application: * <ul> * <li>{@linkplain ClientRequest#subscribeToEvent(Class) subscribes to events}; * <li>{@linkplain ClientRequest#subscribeTo(Class) subscribes to entity states}; * <li>{@linkplain CommandRequest#post() posts a command}. * </ul> * * <p>The subscriptions should be {@linkplain Subscriptions#cancel(Subscription) cancelled} after * an update is delivered to the client and no further updates are expected. * * <p>All remaining subscriptions are {@linkplain #cancelAll() cancelled} by the {@code Client} * when it {@linkplain Client#close() closes}. * * @see ClientRequest#subscribeTo(Class) * @see ClientRequest#subscribeToEvent(Class) * @see CommandRequest#post() */ public final class Subscriptions { /** * The format of all {@linkplain SubscriptionId Subscription identifiers}. */ private static final String SUBSCRIPTION_ID_FORMAT = "s-%s"; /** * The format for convenient subscription printing in logs and error messages. */ static final String SUBSCRIPTION_PRINT_FORMAT = "(ID: %s, target: %s)"; private final SubscriptionServiceStub subscriptionService; private final SubscriptionServiceBlockingStub blockingSubscriptionService; private final Set<Subscription> subscriptions; Subscriptions(ManagedChannel channel) { this.subscriptionService = SubscriptionServiceGrpc.newStub(channel); this.blockingSubscriptionService = SubscriptionServiceGrpc.newBlockingStub(channel); this.subscriptions = synchronizedSet(new HashSet<>()); } /** * Generates a new subscription identifier. * * <p>The result is based upon UUID generation. * * @return new subscription identifier. */ public static SubscriptionId generateId() { String formattedId = format(SUBSCRIPTION_ID_FORMAT, Identifier.newUuid()); return newId(formattedId); } /** * Wraps a given {@code String} as a subscription identifier. * * <p>Should not be used in production. Use {@linkplain #generateId() automatic generation} * instead. * * @return new subscription identifier. */ public static SubscriptionId newId(String value) { return SubscriptionId.newBuilder() .setValue(value) .build(); } public static Subscription from(Topic topic) { checkNotNull(topic); SubscriptionId id = generateId(); Subscription subscription = Subscription .newBuilder() .setId(id) .setTopic(topic) .vBuild(); return subscription; } /** * Obtains a short printable form of subscription. * * <p>Standard {@link Subscription#toString()} includes all subscription data and thus its * output is too huge to use in short log messages and stack traces. * * @return a printable {@code String} with core subscription data * @deprecated please use {@link Subscription#toShortString()} */ @Deprecated public static String toShortString(Subscription subscription) { return subscription.toShortString(); } /** * Subscribes the given {@link StreamObserver} to the given topic and activates * the subscription. * * @param topic * the topic to subscribe to * @param observer * the observer to subscribe * @param <M> * the type of the result messages * @return the activated subscription * @see #cancel(Subscription) */ <M extends Message> Subscription subscribeTo(Topic topic, StreamObserver<M> observer) { Subscription subscription = blockingSubscriptionService.subscribe(topic); subscriptionService.activate(subscription, new SubscriptionObserver<>(observer)); add(subscription); return subscription; } /** Adds all the passed subscriptions. */ void addAll(Collection<Subscription> newSubscriptions) { newSubscriptions.forEach(this::add); } /** Remembers the passed subscription for future use. */ private void add(Subscription s) { subscriptions.add(checkNotNull(s)); } /** * Cancels the passed subscription. * * @return {@code true} if the subscription was previously made */ public boolean cancel(Subscription subscription) { checkNotNull(subscription); requestCancellation(subscription); return subscriptions.remove(subscription); } private void requestCancellation(Subscription subscription) { //TODO:2020-04-17:alexander.yevsyukov: Check response and report the error. blockingSubscriptionService.cancel(subscription); } /** Cancels all the subscriptions. */ public void cancelAll() { Iterator<Subscription> iterator = subscriptions.iterator(); while (iterator.hasNext()) { Subscription subscription = iterator.next(); requestCancellation(subscription); iterator.remove(); } } @VisibleForTesting boolean contains(Subscription s) { return subscriptions.contains(s); } /** * Verifies if there are any active subscriptions. */ public boolean isEmpty() { return subscriptions.isEmpty(); } }
client/src/main/java/io/spine/client/Subscriptions.java
/* * Copyright 2020, TeamDev. All rights reserved. * * Redistribution and use in source and/or binary forms, with or without * modification, must retain the above copyright notice and the following * disclaimer. * * 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 io.spine.client; import com.google.common.annotations.VisibleForTesting; import com.google.protobuf.Message; import io.grpc.ManagedChannel; import io.grpc.stub.StreamObserver; import io.spine.base.Identifier; import io.spine.client.grpc.SubscriptionServiceGrpc; import io.spine.client.grpc.SubscriptionServiceGrpc.SubscriptionServiceBlockingStub; import io.spine.client.grpc.SubscriptionServiceGrpc.SubscriptionServiceStub; import java.util.Collection; import java.util.HashSet; import java.util.Iterator; import java.util.Set; import static com.google.common.base.Preconditions.checkNotNull; import static java.lang.String.format; import static java.util.Collections.synchronizedSet; /** * Maintains the list of the <strong>active</strong> subscriptions created by the {@link Client}. * * <p>Subscriptions are created when a client application: * <ul> * <li>{@linkplain ClientRequest#subscribeToEvent(Class) subscribes to events}; * <li>{@linkplain ClientRequest#subscribeTo(Class) subscribes to entity states}; * <li>{@linkplain CommandRequest#post() posts a command}. * </ul> * * <p>The subscriptions should be {@linkplain Subscriptions#cancel(Subscription) cancelled} after * an update is delivered to the client and no further updates are expected. * * <p>All remaining subscriptions are {@linkplain #cancelAll() cancelled} by the {@code Client} * when it {@linkplain Client#close() closes}. * * @see ClientRequest#subscribeTo(Class) * @see ClientRequest#subscribeToEvent(Class) * @see CommandRequest#post() */ public final class Subscriptions { /** * The format of all {@linkplain SubscriptionId Subscription identifiers}. */ private static final String SUBSCRIPTION_ID_FORMAT = "s-%s"; /** * The format for convenient subscription printing in logs and error messages. */ static final String SUBSCRIPTION_PRINT_FORMAT = "(ID: %s, target: %s)"; private final SubscriptionServiceStub subscriptionService; private final SubscriptionServiceBlockingStub blockingSubscriptionService; private final Set<Subscription> subscriptions; Subscriptions(ManagedChannel channel) { this.subscriptionService = SubscriptionServiceGrpc.newStub(channel); this.blockingSubscriptionService = SubscriptionServiceGrpc.newBlockingStub(channel); this.subscriptions = synchronizedSet(new HashSet<>()); } /** * Generates a new subscription identifier. * * <p>The result is based upon UUID generation. * * @return new subscription identifier. */ public static SubscriptionId generateId() { String formattedId = format(SUBSCRIPTION_ID_FORMAT, Identifier.newUuid()); return newId(formattedId); } /** * Wraps a given {@code String} as a subscription identifier. * * <p>Should not be used in production. Use {@linkplain #generateId() automatic generation} * instead. * * @return new subscription identifier. */ public static SubscriptionId newId(String value) { return SubscriptionId.newBuilder() .setValue(value) .build(); } public static Subscription from(Topic topic) { checkNotNull(topic); SubscriptionId id = generateId(); Subscription subscription = Subscription .newBuilder() .setId(id) .setTopic(topic) .vBuild(); return subscription; } /** * Obtains a short printable form of subscription. * * <p>Standard {@link Subscription#toString()} includes all subscription data and thus its * output is too huge to use in short log messages and stack traces. * * @return a printable {@code String} with core subscription data * @deprecated please use {@link Subscription#toShortString()} */ @Deprecated public static String toShortString(Subscription subscription) { return subscription.toShortString(); } /** * Subscribes the given {@link StreamObserver} to the given topic and activates * the subscription. * * @param topic * the topic to subscribe to * @param observer * the observer to subscribe * @param <M> * the type of the result messages * @return the activated subscription * @see #cancel(Subscription) */ <M extends Message> Subscription subscribeTo(Topic topic, StreamObserver<M> observer) { Subscription subscription = blockingSubscriptionService.subscribe(topic); subscriptionService.activate(subscription, new SubscriptionObserver<>(observer)); add(subscription); return subscription; } /** Adds all the passed subscriptions. */ void addAll(Collection<Subscription> newSubscriptions) { newSubscriptions.forEach(this::add); } /** Remembers the passed subscription for future use. */ private void add(Subscription s) { subscriptions.add(checkNotNull(s)); } /** * Cancels the passed subscription. * * @return {@code true} if the subscription was previously made */ public boolean cancel(Subscription subscription) { checkNotNull(subscription); requestCancellation(subscription); return subscriptions.remove(subscription); } private void requestCancellation(Subscription subscription) { blockingSubscriptionService.cancel(subscription); } /** Cancels all the subscriptions. */ public void cancelAll() { Iterator<Subscription> iterator = subscriptions.iterator(); while (iterator.hasNext()) { Subscription subscription = iterator.next(); requestCancellation(subscription); iterator.remove(); } } @VisibleForTesting boolean contains(Subscription s) { return subscriptions.contains(s); } /** * Verifies if there are any active subscriptions. */ public boolean isEmpty() { return subscriptions.isEmpty(); } }
Restore a TODO
client/src/main/java/io/spine/client/Subscriptions.java
Restore a TODO
<ide><path>lient/src/main/java/io/spine/client/Subscriptions.java <ide> } <ide> <ide> private void requestCancellation(Subscription subscription) { <add> //TODO:2020-04-17:alexander.yevsyukov: Check response and report the error. <ide> blockingSubscriptionService.cancel(subscription); <ide> } <ide>
Java
mit
0ac5cd5b3f92e97d4e64193e8350e2d8e69820fd
0
YaseenAlk/mechanical_turk,YaseenAlk/mechanical_turk
package org.neu.ccs.mechanical_turk; import java.applet.Applet; import java.awt.Color; import java.awt.Graphics; import java.awt.MouseInfo; import java.awt.Point; import java.awt.event.MouseEvent; import java.awt.event.MouseListener; import java.awt.image.BufferedImage; import java.io.File; import java.io.IOException; import java.net.URL; import java.util.Timer; import java.util.TimerTask; import javax.imageio.ImageIO; import javax.swing.JApplet; /** * * @author Yaseen Alkhafaji <[email protected]> * @author Michael Barbini * */ public class TurkApplet extends JApplet implements MouseListener { private Timer timer; private TimerTask task; private Point press, release; private BufferedImage img; public void init() { timer = new Timer(); addMouseListener(this); loadImage(); //will we need to receive any parameters? } public void paint(Graphics g) { super.paint(g); drawImage(img, g); g.setColor(Color.GREEN); if (press != null && release != null) { System.out.println("Drawing..."); int topLeftX, topLeftY, width, height; topLeftX = (int) ((press.getX() < release.getX()) ? press.getX() : release.getX()); topLeftY = (int) ((press.getY() < release.getY()) ? press.getY() : release.getY()); width = (int) Math.abs(press.getX() - release.getX()); height = (int) Math.abs(press.getY() - release.getY()); g.drawRect(topLeftX, topLeftY, width, height); } } @Override public void mouseClicked(MouseEvent e) {} @Override public void mouseEntered(MouseEvent e) {} @Override public void mouseExited(MouseEvent e) {} @Override public void mousePressed(MouseEvent e) { press = getMousePosition(); task = new Updater(); timer.scheduleAtFixedRate(task, 0, 10); } @Override public void mouseReleased(MouseEvent e) { task.cancel(); } private class Updater extends TimerTask { @Override public void run() { release = getMousePosition(); repaint(); } } private void loadImage() { try { img = ImageIO.read(new URL("http://images.media-allrecipes.com/userphotos/250x250/00/64/20/642001.jpg")); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } private void drawImage(BufferedImage img, Graphics g) { g.drawImage(img, 0, 0, null); } }
mechanical_turk/src/org/neu/ccs/mechanical_turk/TurkApplet.java
package org.neu.ccs.mechanical_turk; import java.applet.Applet; import java.awt.Color; import java.awt.Graphics; import java.awt.MouseInfo; import java.awt.Point; import java.awt.event.MouseEvent; import java.awt.event.MouseListener; import java.awt.image.BufferedImage; import java.io.File; import java.io.IOException; import java.net.URL; import java.util.Timer; import java.util.TimerTask; import javax.imageio.ImageIO; import javax.swing.JApplet; /** * * @author Yaseen Alkhafaji <[email protected]> * @author Michael Barbini * */ public class TurkApplet extends JApplet implements MouseListener { private Timer timer; private TimerTask task; private Point press, release; private BufferedImage img; private boolean repaintImage; public void init() { timer = new Timer(); addMouseListener(this); loadImage(); //will we need to receive any parameters? } public void paint(Graphics g) { super.paint(g); if (repaintImage) //oh god why drawImage(img, g); g.setColor(Color.GREEN); if (press != null && release != null) { System.out.println("Drawing..."); int topLeftX, topLeftY, width, height; topLeftX = (int) ((press.getX() < release.getX()) ? press.getX() : release.getX()); topLeftY = (int) ((press.getY() < release.getY()) ? press.getY() : release.getY()); width = (int) Math.abs(press.getX() - release.getX()); height = (int) Math.abs(press.getY() - release.getY()); g.drawRect(topLeftX, topLeftY, width, height); } } @Override public void mouseClicked(MouseEvent e) {} @Override public void mouseEntered(MouseEvent e) {} @Override public void mouseExited(MouseEvent e) {} @Override public void mousePressed(MouseEvent e) { press = getMousePosition(); task = new Updater(); timer.scheduleAtFixedRate(task, 0, 10); } @Override public void mouseReleased(MouseEvent e) { task.cancel(); } private class Updater extends TimerTask { @Override public void run() { release = getMousePosition(); repaint(); } } private void loadImage() { try { img = ImageIO.read(new URL("http://images.media-allrecipes.com/userphotos/250x250/00/64/20/642001.jpg")); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } repaintImage = true; } private void drawImage(BufferedImage img, Graphics g) { g.drawImage(img, 0, 0, null); repaintImage = false; } }
Remove repaintImage stuff
mechanical_turk/src/org/neu/ccs/mechanical_turk/TurkApplet.java
Remove repaintImage stuff
<ide><path>echanical_turk/src/org/neu/ccs/mechanical_turk/TurkApplet.java <ide> <ide> private BufferedImage img; <ide> <del> private boolean repaintImage; <del> <ide> public void init() { <ide> timer = new Timer(); <ide> addMouseListener(this); <ide> <ide> public void paint(Graphics g) { <ide> super.paint(g); <del> if (repaintImage) //oh god why <del> drawImage(img, g); <add> drawImage(img, g); <ide> g.setColor(Color.GREEN); <ide> if (press != null && release != null) { <ide> System.out.println("Drawing..."); <ide> // TODO Auto-generated catch block <ide> e.printStackTrace(); <ide> } <del> repaintImage = true; <ide> } <ide> <ide> private void drawImage(BufferedImage img, Graphics g) { <del> <ide> g.drawImage(img, 0, 0, null); <del> repaintImage = false; <ide> } <ide> <ide> }
Java
apache-2.0
5eaeea76ef87e0484be2d431e0ff382df197f641
0
tresvecesseis/ExoPlayer,tresvecesseis/ExoPlayer,tresvecesseis/ExoPlayer
/* * Copyright (C) 2016 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.google.android.exoplayer.ext.flac; import com.google.android.exoplayer.C; import com.google.android.exoplayer.extractor.ExtractorInput; import java.io.IOException; import java.nio.ByteBuffer; /** * JNI wrapper for the libflac Flac decoder. */ /* package */ final class FlacJni { /** * Whether the underlying libflac library is available. */ public static final boolean IS_AVAILABLE; static { boolean isAvailable; try { System.loadLibrary("flacJNI"); isAvailable = true; } catch (UnsatisfiedLinkError exception) { isAvailable = false; } IS_AVAILABLE = isAvailable; } private static final int TEMP_BUFFER_SIZE = 8192; // The same buffer size which libflac has private final long nativeDecoderContext; private ByteBuffer byteBufferData; private ExtractorInput extractorInput; private boolean endOfExtractorInput; private byte[] tempBuffer; public FlacJni() throws FlacDecoderException { nativeDecoderContext = flacInit(); if (nativeDecoderContext == 0) { throw new FlacDecoderException("Failed to initialize decoder"); } } /** * Sets data to be parsed by libflac. * @param byteBufferData Source {@link ByteBuffer} */ public void setData(ByteBuffer byteBufferData) { this.byteBufferData = byteBufferData; this.extractorInput = null; this.tempBuffer = null; } /** * Sets data to be parsed by libflac. * @param extractorInput Source {@link ExtractorInput} */ public void setData(ExtractorInput extractorInput) { this.byteBufferData = null; this.extractorInput = extractorInput; if (tempBuffer == null) { this.tempBuffer = new byte[TEMP_BUFFER_SIZE]; } endOfExtractorInput = false; } public boolean isEndOfData() { if (byteBufferData != null) { return byteBufferData.remaining() == 0; } else if (extractorInput != null) { return endOfExtractorInput; } return true; } /** * Reads up to {@code length} bytes from the data source. * <p> * This method blocks until at least one byte of data can be read, the end of the input is * detected or an exception is thrown. * <p> * This method is called from the native code. * * @param target A target {@link ByteBuffer} into which data should be written. * @return Returns the number of bytes read, or -1 on failure. It's not an error if this returns * zero; it just means all the data read from the source. */ public int read(ByteBuffer target) throws IOException, InterruptedException { int byteCount = target.remaining(); if (byteBufferData != null) { byteCount = Math.min(byteCount, byteBufferData.remaining()); int originalLimit = byteBufferData.limit(); byteBufferData.limit(byteBufferData.position() + byteCount); target.put(byteBufferData); byteBufferData.limit(originalLimit); } else if (extractorInput != null) { byteCount = Math.min(byteCount, TEMP_BUFFER_SIZE); int read = readFromExtractorInput(0, byteCount); if (read < 4) { // Reading less than 4 bytes, most of the time, happens because of getting the bytes left in // the buffer of the input. Do another read to reduce the number of calls to this method // from the native code. read += readFromExtractorInput(read, byteCount - read); } byteCount = read; target.put(tempBuffer, 0, byteCount); } else { return -1; } return byteCount; } public FlacStreamInfo decodeMetadata() { return flacDecodeMetadata(nativeDecoderContext); } public int decodeSample(ByteBuffer output) { return output.isDirect() ? flacDecodeToBuffer(nativeDecoderContext, output) : flacDecodeToArray(nativeDecoderContext, output.array()); } public long getLastSampleTimestamp() { return flacGetLastTimestamp(nativeDecoderContext); } /** * Maps a seek position in microseconds to a corresponding position (byte offset) in the flac * stream. * * @param timeUs A seek position in microseconds. * @return The corresponding position (byte offset) in the flac stream or -1 if the stream doesn't * have a seek table. */ public long getSeekPosition(long timeUs) { return flacGetSeekPosition(nativeDecoderContext, timeUs); } public void flush() { flacFlush(nativeDecoderContext); } public void release() { flacRelease(nativeDecoderContext); } private int readFromExtractorInput(int offset, int length) throws IOException, InterruptedException { int read = extractorInput.read(tempBuffer, offset, length); if (read == C.RESULT_END_OF_INPUT) { endOfExtractorInput = true; read = 0; } return read; } private native long flacInit(); private native FlacStreamInfo flacDecodeMetadata(long context); private native int flacDecodeToBuffer(long context, ByteBuffer outputBuffer); private native int flacDecodeToArray(long context, byte[] outputArray); private native long flacGetLastTimestamp(long context); private native long flacGetSeekPosition(long context, long timeUs); private native void flacFlush(long context); private native void flacRelease(long context); }
extensions/flac/src/main/java/com/google/android/exoplayer/ext/flac/FlacJni.java
/* * Copyright (C) 2016 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.google.android.exoplayer.ext.flac; import com.google.android.exoplayer.C; import com.google.android.exoplayer.extractor.ExtractorInput; import java.io.IOException; import java.nio.ByteBuffer; /** * JNI wrapper for the libflac Flac decoder. */ /* package */ final class FlacJni { /** * Whether the underlying libflac library is available. */ public static final boolean IS_AVAILABLE; static { boolean isAvailable; try { System.loadLibrary("flacJNI"); isAvailable = true; } catch (UnsatisfiedLinkError exception) { isAvailable = false; } IS_AVAILABLE = isAvailable; } private static final int TEMP_BUFFER_SIZE = 8192; // The same buffer size which libflac has private final long nativeDecoderContext; private ByteBuffer byteBufferData; private ExtractorInput extractorInput; private boolean endOfExtractorInput; private byte[] tempBuffer; public FlacJni() throws FlacDecoderException { nativeDecoderContext = flacInit(); if (nativeDecoderContext == 0) { throw new FlacDecoderException("Failed to initialize decoder"); } } /** * Sets data to be parsed by libflac. * @param byteBufferData Source {@link ByteBuffer} */ public void setData(ByteBuffer byteBufferData) { this.byteBufferData = byteBufferData; this.extractorInput = null; this.tempBuffer = null; } /** * Sets data to be parsed by libflac. * @param extractorInput Source {@link ExtractorInput} */ public void setData(ExtractorInput extractorInput) { this.byteBufferData = null; this.extractorInput = extractorInput; if (tempBuffer == null) { this.tempBuffer = new byte[TEMP_BUFFER_SIZE]; } endOfExtractorInput = false; } public boolean isEndOfData() { if (byteBufferData != null) { return byteBufferData.remaining() == 0; } else if (extractorInput != null) { return endOfExtractorInput; } return true; } /** * Reads up to {@code length} bytes from the data source. * <p> * This method blocks until at least one byte of data can be read, the end of the input is * detected or an exception is thrown. * * @param target A target {@link ByteBuffer} into which data should be written. * @return Returns the number of bytes read, or -1 on failure. It's not an error if this returns * zero; it just means all the data read from the source. */ public int read(ByteBuffer target) throws IOException, InterruptedException { int byteCount = target.remaining(); if (byteBufferData != null) { byteCount = Math.min(byteCount, byteBufferData.remaining()); int originalLimit = byteBufferData.limit(); byteBufferData.limit(byteBufferData.position() + byteCount); target.put(byteBufferData); byteBufferData.limit(originalLimit); } else if (extractorInput != null) { byteCount = Math.min(byteCount, TEMP_BUFFER_SIZE); byteCount = extractorInput.read(tempBuffer, 0, byteCount); if (byteCount == C.RESULT_END_OF_INPUT) { endOfExtractorInput = true; return 0; } target.put(tempBuffer, 0, byteCount); } else { return -1; } return byteCount; } public FlacStreamInfo decodeMetadata() { return flacDecodeMetadata(nativeDecoderContext); } public int decodeSample(ByteBuffer output) { return output.isDirect() ? flacDecodeToBuffer(nativeDecoderContext, output) : flacDecodeToArray(nativeDecoderContext, output.array()); } public long getLastSampleTimestamp() { return flacGetLastTimestamp(nativeDecoderContext); } /** * Maps a seek position in microseconds to a corresponding position (byte offset) in the flac * stream. * * @param timeUs A seek position in microseconds. * @return The corresponding position (byte offset) in the flac stream or -1 if the stream doesn't * have a seek table. */ public long getSeekPosition(long timeUs) { return flacGetSeekPosition(nativeDecoderContext, timeUs); } public void flush() { flacFlush(nativeDecoderContext); } public void release() { flacRelease(nativeDecoderContext); } private native long flacInit(); private native FlacStreamInfo flacDecodeMetadata(long context); private native int flacDecodeToBuffer(long context, ByteBuffer outputBuffer); private native int flacDecodeToArray(long context, byte[] outputArray); private native long flacGetLastTimestamp(long context); private native long flacGetSeekPosition(long context, long timeUs); private native void flacFlush(long context); private native void flacRelease(long context); }
FLAC - reduce read calls from native code. When there is not enough bytes to read a word Libflac keeps the left bytes in the read buffer and does a read with a reduced length by 1 to 3 bytes. This results to reading 8191, 1, 8191, 1, 8191... bytes. ------------- Created by MOE: https://github.com/google/moe MOE_MIGRATED_REVID=119048705
extensions/flac/src/main/java/com/google/android/exoplayer/ext/flac/FlacJni.java
FLAC - reduce read calls from native code.
<ide><path>xtensions/flac/src/main/java/com/google/android/exoplayer/ext/flac/FlacJni.java <ide> * <p> <ide> * This method blocks until at least one byte of data can be read, the end of the input is <ide> * detected or an exception is thrown. <add> * <p> <add> * This method is called from the native code. <ide> * <ide> * @param target A target {@link ByteBuffer} into which data should be written. <ide> * @return Returns the number of bytes read, or -1 on failure. It's not an error if this returns <ide> byteBufferData.limit(originalLimit); <ide> } else if (extractorInput != null) { <ide> byteCount = Math.min(byteCount, TEMP_BUFFER_SIZE); <del> byteCount = extractorInput.read(tempBuffer, 0, byteCount); <del> if (byteCount == C.RESULT_END_OF_INPUT) { <del> endOfExtractorInput = true; <del> return 0; <add> int read = readFromExtractorInput(0, byteCount); <add> if (read < 4) { <add> // Reading less than 4 bytes, most of the time, happens because of getting the bytes left in <add> // the buffer of the input. Do another read to reduce the number of calls to this method <add> // from the native code. <add> read += readFromExtractorInput(read, byteCount - read); <ide> } <add> byteCount = read; <ide> target.put(tempBuffer, 0, byteCount); <ide> } else { <ide> return -1; <ide> flacRelease(nativeDecoderContext); <ide> } <ide> <add> private int readFromExtractorInput(int offset, int length) <add> throws IOException, InterruptedException { <add> int read = extractorInput.read(tempBuffer, offset, length); <add> if (read == C.RESULT_END_OF_INPUT) { <add> endOfExtractorInput = true; <add> read = 0; <add> } <add> return read; <add> } <add> <ide> private native long flacInit(); <ide> <ide> private native FlacStreamInfo flacDecodeMetadata(long context);
JavaScript
apache-2.0
fb6ab5221512beb5462a943ba2788333e6d0b31a
0
with-regard/regard-website
"use strict"; var express = require('express'); var app = express(); // Routes app.get('/', function(req, res){ if(req.isAuthenticated()){ console.dir(req.user); res.sendfile('index.html', {root: __dirname }); } else { res.redirect('/login'); } }); app.use(express.static(__dirname + '/js')); module.exports = app;
portal/server.js
"use strict"; var express = require('express'); var app = express(); // Routes app.get('/', function(req, res){ console.dir(req.user); res.sendfile('index.html', {root: __dirname }) }); app.use(express.static(__dirname + '/js')); module.exports = app;
Check user is authenticated when accessing the portal
portal/server.js
Check user is authenticated when accessing the portal
<ide><path>ortal/server.js <ide> <ide> // Routes <ide> app.get('/', function(req, res){ <del> console.dir(req.user); <del> res.sendfile('index.html', {root: __dirname }) <add> if(req.isAuthenticated()){ <add> console.dir(req.user); <add> res.sendfile('index.html', {root: __dirname }); <add> } else { <add> res.redirect('/login'); <add> } <ide> }); <ide> <ide> app.use(express.static(__dirname + '/js'));
JavaScript
mit
5348e5dfe6aaff9b72be2ba4dde23d3f939a3435
0
ConorOBrien-Foxx/Spacewar-KotH
"use strict"; var renderLoop; (function($){ $(document).ready(function (){ console.log("main.js"); init(); setup(); renderLoop = setInterval(update, 30); $(document).keydown(handleInput); $(document).keyup(handleInput); $('#gravityCheck').on('change', function(){ gravityStrength = this.checked*6000; }); }); })(jQuery); var SCALE = 1.0; window["red"] = {"color":"red"}; window["blue"] = {"color":"blue"}; var teams = [window["red"], window["blue"]]; var shipShapes = { 'full ship': [[-8,16],[0,-8],[8,16]], 'left wing': [[-8,16],[0,-8],[4,4],[0,8],[0,16]], 'right wing':[[-4,4],[0,-8],[8,16],[0,16],[0,8]], 'nose only': [[-4,4],[0,-8],[4,4],[0,8]]} var field; var fieldWidth = 800; var fieldHeight = 600; window["sun"] = {"cx":fieldWidth/2, "cy":fieldHeight/2, "r":5, "points":[]} for (var i=0; i<8; i++) { var px = sun.cx+sun.r*Math.cos(i*Math.PI/4); var py = sun.cy+sun.r*Math.sin(i*Math.PI/4); sun.points.push([px,py]); } var missileTimeout = 2250; var fireRateLimit = 100; var gravityStrength = 1*6000; var speedLimit = 15; //engine propulsion var maxSpeed = 40; //gravity-boosted var engineThrust = 0.35; Math.radians = function(degrees) { return degrees * Math.PI / 180; }; Math.degrees = function(radians) { return radians * 180 / Math.PI; }; function init() { var svg = d3.select('#playfield').append("svg") .attr("width",fieldWidth) .attr("height",fieldHeight) .attr("id","field"); field = d3.select('#field'); svg.append("rect") .attr("width",fieldWidth) .attr("height",fieldHeight) .attr("fill","black"); svg.append("circle") //sun .attr("cx",sun.cx) .attr("cy",sun.cy) .attr("r", sun.r*SCALE) .style("fill","white") .attr("id","sun"); d3.select('svg').selectAll(".ship").data(teams).enter().append("polygon") .attr("id", function(d){console.log(d.color); return d.color;}) .attr("fill", function(d){return d.color;}) .attr("class", "ship"); } function setup() { red.x = 50; red.y = Math.floor((fieldHeight-100)*Math.random())+50; red.rot = 90; red.xv = 0.0; red.yv = 0.0; red.fireTime = new Date() - 1000; red.missileReady = true; red.updateShape = true; red.shape = "full ship"; red.thrust = engineThrust; red.turnRate = 5; red.alive = true; blue.x = fieldWidth-50; blue.y = Math.floor((fieldHeight-100)*Math.random())+50; blue.rot = -90; blue.xv = 0.0; blue.yv = 0.0; blue.fireTime = new Date() - 1000; blue.missileReady = true; blue.updateShape = true; blue.shape = "full ship"; blue.thrust = engineThrust; blue.turnRate = 5; blue.alive = true; updateGraphics(); } function update() { checkKeys(); if (missiles.length){ var filteredMissiles = []; for (var i=0; i<missiles.length; i++) { var m = missiles[i]; if (new Date() - m.time > missileTimeout){ m.live = false; } if (m.live) { filteredMissiles.push(m); } } missiles = filteredMissiles; var dots = d3.select("#field").selectAll('.missile').data(missiles); dots.attr("cx", function(d){ return d.x; }) .attr("cy", function(d){ return d.y; }); dots.exit().remove(); } updatePositions(); updateGraphics(); } function updatePositions(){ var sun = d3.select('#sun'); teams.forEach(function(teamObj){ if (teamObj.alive) { var dx = teamObj.x - sun.attr('cx'); var dy = teamObj.y - sun.attr('cy'); var dis = Math.sqrt(dx*dx+dy*dy); if (dx*dx+dy*dy > 5){ var force = gravityStrength / (dx*dx+dy*dy); } else { var force = gravityStrength/5; } teamObj.xv += -force*dx/dis; teamObj.yv += -force*dy/dis; var speed = teamObj.xv*teamObj.xv + teamObj.yv*teamObj.yv; if (speed > maxSpeed*maxSpeed) { teamObj.xv = maxSpeed*teamObj.xv/Math.sqrt(speed); teamObj.yv = maxSpeed*teamObj.yv/Math.sqrt(speed); } checkShipCollision(teamObj, "sun"); teamObj.x += teamObj.xv; teamObj.x = (teamObj.x+fieldWidth)%fieldWidth; teamObj.y += teamObj.yv; teamObj.y = (teamObj.y+fieldHeight)%fieldHeight; } }); missiles.forEach(function(m){ var dx = m.x - sun.attr('cx'); var dy = m.y - sun.attr('cy'); var dis = Math.sqrt(dx*dx+dy*dy); if (dx*dx+dy*dy > 5){ var force = gravityStrength / (dx*dx+dy*dy); } else { var force = gravityStrength/5; } m.xv += -force*dx/dis; m.yv += -force*dy/dis; var speed = m.xv*m.xv + m.yv*m.yv; if (speed > maxSpeed*maxSpeed*2) { m.xv = 1.414*maxSpeed*m.xv/Math.sqrt(speed); m.yv = 1.414*maxSpeed*m.yv/Math.sqrt(speed); } m.nx = m.x + m.xv; m.ny = m.y + m.yv; checkMissileCollision(m, "sun"); checkMissileCollision(m, "red"); checkMissileCollision(m, "blue"); if (m.live) { m.x = (m.nx+fieldWidth)%fieldWidth; m.y = (m.ny+fieldHeight)%fieldHeight; } }); } function updateGraphics(team){ teams.forEach(function(teamObj){ d3.select("#"+teamObj.color).attr("transform","translate("+teamObj.x+","+teamObj.y+"),rotate("+teamObj.rot+")"); if (teamObj.updateShape) { var pointsStr = ""; shipShapes[teamObj.shape].forEach(function(point){ pointsStr += point[0]*SCALE+","+point[1]*SCALE+" "; }); d3.select("#"+teamObj.color).attr("points",pointsStr); } }); } function teamMove(team,action) { var teamObj = window[team]; if (teamObj.alive) { switch (action){ case "thrust": fireEngine(team); break; case "fire": fireMissile(team); break; case "turn right": teamObj.rot = teamObj.rot + teamObj.turnRate; break; case "turn left": teamObj.rot = teamObj.rot - teamObj.turnRate; break; case "hyperspace": break; } } } function fireEngine(team) { var teamObj = window[team]; var speed = teamObj.xv*teamObj.xv + teamObj.yv*teamObj.yv; var nxv = teamObj.xv + teamObj.thrust*Math.cos(Math.radians(teamObj.rot-90)); var nyv = teamObj.yv + teamObj.thrust*Math.sin(Math.radians(teamObj.rot-90)); var speed2 = nxv*nxv + nyv*nyv; if (speed < speedLimit*speedLimit || speed2 < speed) { //either slow enough or slowing down teamObj.xv = nxv; teamObj.yv = nyv; if (speed2 > speed && speed2 > speedLimit*speedLimit) { teamObj.xv = speedLimit*teamObj.xv/Math.sqrt(speed2); teamObj.yv = speedLimit*teamObj.yv/Math.sqrt(speed2); } } else { teamObj.xv = Math.sqrt(speed)*nxv/Math.sqrt(speed2); teamObj.yv = Math.sqrt(speed)*nyv/Math.sqrt(speed2); } } function checkShipCollision(ship, obj) { var sPoints = shipShapes[ship.shape]; var tPoints; var speed = Math.sqrt(ship.xv*ship.xv+ship.yv*ship.yv); var num = Math.ceil(speed); if (obj === "sun") { obj = sun; var dx = obj.cx - ship.x; var dy = obj.cy - ship.y; var dis = Math.sqrt(dx*dx+dy*dy); if (dis > 40) { return; } //pointless to check for a collision if they're far apart var tPoints = sun.points; for (var i=0; i<=num; i++) { var f = i/num; for (var j=0; j<sPoints.length; j++) { var j2 = (j+1)%sPoints.length; var sx1 = (sPoints[j][0]*Math.cos(Math.radians(ship.rot))-sPoints[j][1]*Math.sin(Math.radians(ship.rot))) + ship.x + f*ship.xv; var sy1 = (sPoints[j][0]*Math.sin(Math.radians(ship.rot))+sPoints[j][1]*Math.cos(Math.radians(ship.rot))) + ship.y + f*ship.yv; var sx2 = (sPoints[j2][0]*Math.cos(Math.radians(ship.rot))-sPoints[j2][1]*Math.sin(Math.radians(ship.rot))) + ship.x + f*ship.xv; var sy2 = (sPoints[j2][0]*Math.sin(Math.radians(ship.rot))+sPoints[j2][1]*Math.cos(Math.radians(ship.rot))) + ship.y + f*ship.yv; var L1 = [[sx1,sy1],[sx2,sy2]]; for (var k=0; k<tPoints.length; k++) { var k2 = (k+1)%tPoints.length; var tx1 = tPoints[k][0]; var ty1 = tPoints[k][1]; var tx2 = tPoints[k2][0]; var ty2 = tPoints[k2][1]; var L2 = [[tx1,ty1],[tx2,ty2]]; var intersection = lineIntersection(L1,L2); if (intersection.length) { ship.xv *= f; ship.yv *= f; ship.alive = false; return; } } } } } } var missiles = []; /* class Missile { constructor(x,y,xv,yv) { this.x = x; this.y = y; this.xv = xv; this.yv = yv; if (missiles.length > 0){ this.id = missiles[missiles.length-1].id + 1; } else { this.id = 1; } this.name = "missile"+this.id; } } */ function fireMissile(team) { var mx,my,mxv,myv; var p = window[team]; mxv = p.xv + 10*Math.cos(Math.radians(p.rot-90)); myv = p.yv + 10*Math.sin(Math.radians(p.rot-90)); mx = p.x + mxv; my = p.y + myv; // missiles.push(new Missile(mx,my,mxv,myv)); missiles.push({'x':mx, 'y':my, 'xv':mxv, 'yv':myv, 'time':new Date(), 'live':true}); missiles[missiles.length-1]['id'] = missiles.length; d3.select("#field").selectAll(".missile") .data(missiles) .enter().append("circle") .attr("cx", function(d){ return d.x; }) .attr("cy", function(d){ return d.y; }) .attr("r", 1.5) .style("fill","white") .attr("class", "missile"); } function checkMissileCollision(m, obj) { if (obj === "sun") { var points = sun.points; var L1 = [[m.x,m.y],[m.nx,m.ny]]; var len = points.length; for (var i=0; i<len; i++) { var L2 = [[points[i][0],points[i][1]], [points[(i+1)%len][0],points[(i+1)%len][1]]]; var intersection = lineIntersection(L1, L2); if (intersection.length) { m.live = false; } } } else if (obj === "red" || obj === "blue") { var ship = window[obj]; var sPoints = shipShapes[ship.shape]; var len = sPoints.length; var num = Math.ceil(1+Math.sqrt(ship.xv*ship.xv+ship.yv*ship.yv)); for (var i=0; i<num; i++) { var f = i/num; var mx1 = m.x + f*m.xv; var my1 = m.y + f*m.yv; var mx2 = m.x + (i+1)/num*m.xv; var my2 = m.y + (i+1)/num*m.yv; var L1 = [[mx1,my1],[mx2,my2]]; var closestIntersection = []; for (var j=0; j<len; j++) { var j2 = (j+1)%len; var sx1 = (sPoints[j][0]*Math.cos(Math.radians(ship.rot))-sPoints[j][1]*Math.sin(Math.radians(ship.rot))) + ship.x + f*ship.xv; var sy1 = (sPoints[j][0]*Math.sin(Math.radians(ship.rot))+sPoints[j][1]*Math.cos(Math.radians(ship.rot))) + ship.y + f*ship.yv; var sx2 = (sPoints[j2][0]*Math.cos(Math.radians(ship.rot))-sPoints[j2][1]*Math.sin(Math.radians(ship.rot))) + ship.x + f*ship.xv; var sy2 = (sPoints[j2][0]*Math.sin(Math.radians(ship.rot))+sPoints[j2][1]*Math.cos(Math.radians(ship.rot))) + ship.y + f*ship.yv; var L2 = [[sx1,sy1],[sx2,sy2]]; var intersection = lineIntersection(L1, L2); if (intersection.length) { if (!closestIntersection.length || (intersection[1][0] < closestIntersection[0])) { closestIntersection = intersection[1]; closestIntersection.push(j); console.log(closestIntersection[0]+","+closestIntersection[1]+","+closestIntersection[2]); } } } if (closestIntersection.length) { console.log(closestIntersection[0]+","+closestIntersection[1]+","+closestIntersection[2]); console.log(""); m.live = false; // ship.alive = false; if (ship.shape === "full ship") { switch(closestIntersection[2]) { case 0: if (closestIntersection[1] > 0.5) { //hit on the nose ship.alive = false; } else { ship.shape = "right wing"; } break; case 1: if (closestIntersection[1] < 0.5) { //hit on the nose ship.alive = false; } else { ship.shape = "left wing"; } break; case 2: if (closestIntersection[1] < 0.5) { //hit on the right side ship.shape = "left wing"; } else { ship.shape = "right wing"; } break; } } else if (ship.shape === "left wing") { switch(closestIntersection[2]) { case 0: if (closestIntersection[1] > 0.5) { //hit on the nose ship.alive = false; } else { ship.shape = "nose only"; } break; case 1: case 2: ship.alive = false; break; case 3: case 4: ship.shape = "nose only"; break; } } else if (ship.shape === "right wing") { switch(closestIntersection[2]) { case 1: if (closestIntersection[1] < 0.5) { //hit on the nose ship.alive = false; } else { ship.shape = "nose only"; } break; case 0: case 4: ship.alive = false; break; case 2: case 3: ship.shape = "nose only"; break; } } else if (ship.shape === "nose only") { ship.alive = false; } return; } } } } function lineIntersection(L1, L2) { // from http://stackoverflow.com/a/565282/1473772 var p = L1[0]; var r = [L1[1][0]-L1[0][0], L1[1][1]-L1[0][1]]; var q = L2[0]; var s = [L2[1][0]-L2[0][0], L2[1][1]-L2[0][1]]; var rcs = r[0]*s[1] - s[0]*r[1]; //r cross s var qmp = [q[0]-p[0],q[1]-p[1]]; //q minus p var qmpcr = qmp[0]*r[1] - r[0]*qmp[1]; //(q minus p) cross r var qmpcs = qmp[0]*s[1] - s[0]*qmp[1]; //(q minus p) cross s if (rcs === 0) { //they're parallel/colinear return []; //I'm just going to assume that overlapping colinear lines don't happen } else { //not parallel var t = qmpcs/rcs; var u = qmpcr/rcs; if (0 <= t && t <= 1 && 0 <= u && u <= 1) { //intersection exists var intx = p[0] + t*r[0]; var inty = p[1] + t*r[1]; return [[intx,inty],[t,u]]; } else { //no intersection return []; } } } var keystates = {}; function handleInput(event) { if (event.which == 27){ clearInterval(renderLoop); renderLoop = false; return; } else if (event.which == 13){ event.preventDefault(); if (!renderLoop){ renderLoop = setInterval(update, 30); } return; } if (event.which == 191){ event.preventDefault(); }; if (event.type == 'keydown'){ keystates[event.which] = true; } if (event.type == 'keyup') { keystates[event.which] = false; if (event.which == 66) { window["red"].missileReady = true; } else if (event.which == 191) { window["blue"].missileReady = true; } } } var keysOfInterest = [ 90,88,67,86,66, 78,77,188,190,191 ]; function checkKeys() { keysOfInterest.forEach(function(k){ if (keystates[k]){ switch (k){ // RED case 90: teamMove("red","turn left"); break; case 88: teamMove("red","turn right"); break; case 67: teamMove("red","hyperspace"); break; case 86: teamMove("red","thrust"); break; case 66: if (new Date() - window["red"].fireTime > fireRateLimit && window["red"].missileReady) { teamMove("red","fire"); window["red"].fireTime = new Date(); window["red"].missileReady = false; } break; // BLUE case 78: teamMove("blue","turn left"); break; case 77: teamMove("blue","turn right"); break; case 188: teamMove("blue","hyperspace"); break; case 190: teamMove("blue","thrust"); break; case 191: if (new Date() - window["blue"].fireTime > fireRateLimit && window["blue"].missileReady) { teamMove("blue","fire"); window["blue"].fireTime = new Date(); window["blue"].missileReady = false; } break; } } }); }
main.js
"use strict"; var renderLoop; (function($){ $(document).ready(function (){ console.log("main.js"); init(); setup(); renderLoop = setInterval(update, 30); $(document).keydown(handleInput); $(document).keyup(handleInput); $('#gravityCheck').on('change', function(){ gravityStrength = this.checked*6000; }); }); })(jQuery); var SCALE = 1.0; window["red"] = {"color":"red"}; window["blue"] = {"color":"blue"}; var teams = [window["red"], window["blue"]]; var shipShapes = { 'full ship': [[-8,16],[0,-8],[8,16]], 'left wing': [[-8,16],[0,-8],[4,4],[0,8],[0,16]], 'right wing':[[-4,4],[0,-8],[8,16],[0,16],[0,8]], 'nose only': [[-4,4],[0,-8],[4,4],[0,8]]} var field; var fieldWidth = 800; var fieldHeight = 600; window["sun"] = {"cx":fieldWidth/2, "cy":fieldHeight/2, "r":5, "points":[]} for (var i=0; i<8; i++) { var px = sun.cx+sun.r*Math.cos(i*Math.PI/4); var py = sun.cy+sun.r*Math.sin(i*Math.PI/4); sun.points.push([px,py]); } var missileTimeout = 2250; var fireRateLimit = 100; var gravityStrength = 1*6000; var speedLimit = 15; //engine propulsion var maxSpeed = 40; //gravity-boosted var engineThrust = 0.35; Math.radians = function(degrees) { return degrees * Math.PI / 180; }; Math.degrees = function(radians) { return radians * 180 / Math.PI; }; function init() { var svg = d3.select('#playfield').append("svg") .attr("width",fieldWidth) .attr("height",fieldHeight) .attr("id","field"); field = d3.select('#field'); svg.append("rect") .attr("width",fieldWidth) .attr("height",fieldHeight) .attr("fill","black"); svg.append("circle") //sun .attr("cx",sun.cx) .attr("cy",sun.cy) .attr("r", sun.r*SCALE) .style("fill","white") .attr("id","sun"); d3.select('svg').selectAll(".ship").data(teams).enter().append("polygon") .attr("id", function(d){console.log(d.color); return d.color;}) .attr("fill", function(d){return d.color;}) .attr("class", "ship"); } function setup() { red.x = 50; red.y = Math.floor((fieldHeight-100)*Math.random())+50; red.rot = 90; red.xv = 0.0; red.yv = 0.0; red.fireTime = new Date() - 1000; red.missileReady = true; red.updateShape = true; red.shape = "full ship"; red.thrust = engineThrust; red.turnRate = 5; red.alive = true; blue.x = fieldWidth-50; blue.y = Math.floor((fieldHeight-100)*Math.random())+50; blue.rot = -90; blue.xv = 0.0; blue.yv = 0.0; blue.fireTime = new Date() - 1000; blue.missileReady = true; blue.updateShape = true; blue.shape = "full ship"; blue.thrust = engineThrust; blue.turnRate = 5; blue.alive = true; updateGraphics(); } function update() { checkKeys(); if (missiles.length){ var filteredMissiles = []; for (var i=0; i<missiles.length; i++) { var m = missiles[i]; if (new Date() - m.time > missileTimeout){ m.live = false; } if (m.live) { filteredMissiles.push(m); } } missiles = filteredMissiles; var dots = d3.select("#field").selectAll('.missile').data(missiles); dots.attr("cx", function(d){ return d.x; }) .attr("cy", function(d){ return d.y; }); dots.exit().remove(); } updatePositions(); updateGraphics(); } function updatePositions(){ var sun = d3.select('#sun'); teams.forEach(function(teamObj){ if (teamObj.alive) { var dx = teamObj.x - sun.attr('cx'); var dy = teamObj.y - sun.attr('cy'); var dis = Math.sqrt(dx*dx+dy*dy); if (dx*dx+dy*dy > 5){ var force = gravityStrength / (dx*dx+dy*dy); } else { var force = gravityStrength/5; } teamObj.xv += -force*dx/dis; teamObj.yv += -force*dy/dis; var speed = teamObj.xv*teamObj.xv + teamObj.yv*teamObj.yv; if (speed > maxSpeed*maxSpeed) { teamObj.xv = maxSpeed*teamObj.xv/Math.sqrt(speed); teamObj.yv = maxSpeed*teamObj.yv/Math.sqrt(speed); } checkShipCollision(teamObj, "sun"); teamObj.x += teamObj.xv; teamObj.x = (teamObj.x+fieldWidth)%fieldWidth; teamObj.y += teamObj.yv; teamObj.y = (teamObj.y+fieldHeight)%fieldHeight; } }); missiles.forEach(function(m){ var dx = m.x - sun.attr('cx'); var dy = m.y - sun.attr('cy'); var dis = Math.sqrt(dx*dx+dy*dy); if (dx*dx+dy*dy > 5){ var force = gravityStrength / (dx*dx+dy*dy); } else { var force = gravityStrength/5; } m.xv += -force*dx/dis; m.yv += -force*dy/dis; var speed = m.xv*m.xv + m.yv*m.yv; if (speed > maxSpeed*maxSpeed*2) { m.xv = 1.414*maxSpeed*m.xv/Math.sqrt(speed); m.yv = 1.414*maxSpeed*m.yv/Math.sqrt(speed); } m.nx = m.x + m.xv; m.ny = m.y + m.yv; checkMissileCollision(m, "sun"); checkMissileCollision(m, "red"); checkMissileCollision(m, "blue"); if (m.live) { m.x = (m.nx+fieldWidth)%fieldWidth; m.y = (m.ny+fieldHeight)%fieldHeight; } }); } function updateGraphics(team){ teams.forEach(function(teamObj){ d3.select("#"+teamObj.color).attr("transform","translate("+teamObj.x+","+teamObj.y+"),rotate("+teamObj.rot+")"); if (teamObj.updateShape) { var pointsStr = ""; shipShapes[teamObj.shape].forEach(function(point){ pointsStr += point[0]*SCALE+","+point[1]*SCALE+" "; }); d3.select("#"+teamObj.color).attr("points",pointsStr); } }); } function teamMove(team,action) { var teamObj = window[team]; if (teamObj.alive) { switch (action){ case "thrust": fireEngine(team); break; case "fire": fireMissile(team); break; case "turn right": teamObj.rot = teamObj.rot + teamObj.turnRate; break; case "turn left": teamObj.rot = teamObj.rot - teamObj.turnRate; break; case "hyperspace": break; } } } function fireEngine(team) { var teamObj = window[team]; var speed = teamObj.xv*teamObj.xv + teamObj.yv*teamObj.yv; var nxv = teamObj.xv + teamObj.thrust*Math.cos(Math.radians(teamObj.rot-90)); var nyv = teamObj.yv + teamObj.thrust*Math.sin(Math.radians(teamObj.rot-90)); var speed2 = nxv*nxv + nyv*nyv; if (speed < speedLimit*speedLimit || speed2 < speed) { //either slow enough or slowing down teamObj.xv = nxv; teamObj.yv = nyv; if (speed2 > speed && speed2 > speedLimit*speedLimit) { teamObj.xv = speedLimit*teamObj.xv/Math.sqrt(speed2); teamObj.yv = speedLimit*teamObj.yv/Math.sqrt(speed2); } } else { teamObj.xv = Math.sqrt(speed)*nxv/Math.sqrt(speed2); teamObj.yv = Math.sqrt(speed)*nyv/Math.sqrt(speed2); } } function checkShipCollision(ship, obj) { var sPoints = shipShapes[ship.shape]; var tPoints; var speed = Math.sqrt(ship.xv*ship.xv+ship.yv*ship.yv); var num = Math.ceil(speed); if (obj === "sun") { obj = sun; var dx = obj.cx - ship.x; var dy = obj.cy - ship.y; var dis = Math.sqrt(dx*dx+dy*dy); if (dis > 40) { return; } //pointless to check for a collision if they're far apart var tPoints = sun.points; for (var i=0; i<=num; i++) { var f = i/num; for (var j=0; j<sPoints.length; j++) { var j2 = (j+1)%sPoints.length; var sx1 = (sPoints[j][0]*Math.cos(Math.radians(ship.rot))-sPoints[j][1]*Math.sin(Math.radians(ship.rot))) + ship.x + f*ship.xv; var sy1 = (sPoints[j][0]*Math.sin(Math.radians(ship.rot))+sPoints[j][1]*Math.cos(Math.radians(ship.rot))) + ship.y + f*ship.yv; var sx2 = (sPoints[j2][0]*Math.cos(Math.radians(ship.rot))-sPoints[j2][1]*Math.sin(Math.radians(ship.rot))) + ship.x + f*ship.xv; var sy2 = (sPoints[j2][0]*Math.sin(Math.radians(ship.rot))+sPoints[j2][1]*Math.cos(Math.radians(ship.rot))) + ship.y + f*ship.yv; var L1 = [[sx1,sy1],[sx2,sy2]]; for (var k=0; k<tPoints.length; k++) { var k2 = (k+1)%tPoints.length; var tx1 = tPoints[k][0]; var ty1 = tPoints[k][1]; var tx2 = tPoints[k2][0]; var ty2 = tPoints[k2][1]; var L2 = [[tx1,ty1],[tx2,ty2]]; var intersection = lineIntersection(L1,L2); if (intersection.length) { ship.xv *= f; ship.yv *= f; ship.alive = false; return; } } } } } } var missiles = []; /* class Missile { constructor(x,y,xv,yv) { this.x = x; this.y = y; this.xv = xv; this.yv = yv; if (missiles.length > 0){ this.id = missiles[missiles.length-1].id + 1; } else { this.id = 1; } this.name = "missile"+this.id; } } */ function fireMissile(team) { var mx,my,mxv,myv; var p = window[team]; mxv = p.xv + 10*Math.cos(Math.radians(p.rot-90)); myv = p.yv + 10*Math.sin(Math.radians(p.rot-90)); mx = p.x + mxv; my = p.y + myv; // missiles.push(new Missile(mx,my,mxv,myv)); missiles.push({'x':mx, 'y':my, 'xv':mxv, 'yv':myv, 'time':new Date(), 'live':true}); missiles[missiles.length-1]['id'] = missiles.length; d3.select("#field").selectAll(".missile") .data(missiles) .enter().append("circle") .attr("cx", function(d){ return d.x; }) .attr("cy", function(d){ return d.y; }) .attr("r", 1.5) .style("fill","white") .attr("class", "missile"); } function checkMissileCollision(m, obj) { if (obj === "sun") { var points = sun.points; var L1 = [[m.x,m.y],[m.nx,m.ny]]; var len = points.length; for (var i=0; i<len; i++) { var L2 = [[points[i][0],points[i][1]], [points[(i+1)%len][0],points[(i+1)%len][1]]]; var intersection = lineIntersection(L1, L2); if (intersection.length) { m.live = false; } } } else if (obj === "red" || obj === "blue") { var ship = window[obj]; var sPoints = shipShapes[ship.shape]; var len = sPoints.length; var num = Math.ceil(1+Math.sqrt(ship.xv*ship.xv+ship.yv*ship.yv)); for (var i=0; i<num; i++) { var f = i/num; var mx1 = m.x + f*m.xv; var my1 = m.y + f*m.yv; var mx2 = m.x + (i+1)/num*m.xv; var my2 = m.y + (i+1)/num*m.yv; var L1 = [[mx1,my1],[mx2,my2]]; for (var j=0; j<len; j++) { var j2 = (j+1)%len; var sx1 = (sPoints[j][0]*Math.cos(Math.radians(ship.rot))-sPoints[j][1]*Math.sin(Math.radians(ship.rot))) + ship.x + f*ship.xv; var sy1 = (sPoints[j][0]*Math.sin(Math.radians(ship.rot))+sPoints[j][1]*Math.cos(Math.radians(ship.rot))) + ship.y + f*ship.yv; var sx2 = (sPoints[j2][0]*Math.cos(Math.radians(ship.rot))-sPoints[j2][1]*Math.sin(Math.radians(ship.rot))) + ship.x + f*ship.xv; var sy2 = (sPoints[j2][0]*Math.sin(Math.radians(ship.rot))+sPoints[j2][1]*Math.cos(Math.radians(ship.rot))) + ship.y + f*ship.yv; var L2 = [[sx1,sy1],[sx2,sy2]]; var intersection = lineIntersection(L1, L2); if (intersection.length) { m.live = false; ship.alive = false; if (obj.shape === "full ship") { } else if (obj.shape === "left wing") { } else if (obj.shape === "right wing") { } else if (obj.shape === "nose only") { } } } } } } function lineIntersection(L1, L2) { // from http://stackoverflow.com/a/565282/1473772 var p = L1[0]; var r = [L1[1][0]-L1[0][0], L1[1][1]-L1[0][1]]; var q = L2[0]; var s = [L2[1][0]-L2[0][0], L2[1][1]-L2[0][1]]; var rcs = r[0]*s[1] - s[0]*r[1]; //r cross s var qmp = [q[0]-p[0],q[1]-p[1]]; //q minus p var qmpcr = qmp[0]*r[1] - r[0]*qmp[1]; //(q minus p) cross r var qmpcs = qmp[0]*s[1] - s[0]*qmp[1]; //(q minus p) cross s if (rcs === 0) { //they're parallel/colinear return []; //I'm just going to assume that overlapping colinear lines don't happen } else { //not parallel var t = qmpcs/rcs; var u = qmpcr/rcs; if (0 <= t && t <= 1 && 0 <= u && u <= 1) { //intersection exists var intx = p[0] + t*r[0]; var inty = p[1] + t*r[1]; return [[intx,inty],[t,u]]; } else { //no intersection return []; } } } var keystates = {}; function handleInput(event) { if (event.which == 27){ clearInterval(renderLoop); renderLoop = false; return; } else if (event.which == 13){ event.preventDefault(); if (!renderLoop){ renderLoop = setInterval(update, 30); } return; } if (event.which == 191){ event.preventDefault(); }; if (event.type == 'keydown'){ keystates[event.which] = true; } if (event.type == 'keyup') { keystates[event.which] = false; if (event.which == 66) { window["red"].missileReady = true; } else if (event.which == 191) { window["blue"].missileReady = true; } } } var keysOfInterest = [ 90,88,67,86,66, 78,77,188,190,191 ]; function checkKeys() { keysOfInterest.forEach(function(k){ if (keystates[k]){ switch (k){ // RED case 90: teamMove("red","turn left"); break; case 88: teamMove("red","turn right"); break; case 67: teamMove("red","hyperspace"); break; case 86: teamMove("red","thrust"); break; case 66: if (new Date() - window["red"].fireTime > fireRateLimit && window["red"].missileReady) { teamMove("red","fire"); window["red"].fireTime = new Date(); window["red"].missileReady = false; } break; // BLUE case 78: teamMove("blue","turn left"); break; case 77: teamMove("blue","turn right"); break; case 188: teamMove("blue","hyperspace"); break; case 190: teamMove("blue","thrust"); break; case 191: if (new Date() - window["blue"].fireTime > fireRateLimit && window["blue"].missileReady) { teamMove("blue","fire"); window["blue"].fireTime = new Date(); window["blue"].missileReady = false; } break; } } }); }
Full ship-missile collision.
main.js
Full ship-missile collision.
<ide><path>ain.js <ide> var my2 = m.y + (i+1)/num*m.yv; <ide> var L1 = [[mx1,my1],[mx2,my2]]; <ide> <add> var closestIntersection = []; <add> <ide> for (var j=0; j<len; j++) { <ide> var j2 = (j+1)%len; <ide> var sx1 = (sPoints[j][0]*Math.cos(Math.radians(ship.rot))-sPoints[j][1]*Math.sin(Math.radians(ship.rot))) + ship.x + f*ship.xv; <ide> var intersection = lineIntersection(L1, L2); <ide> <ide> if (intersection.length) { <del> m.live = false; <add> if (!closestIntersection.length || (intersection[1][0] < closestIntersection[0])) { <add> closestIntersection = intersection[1]; <add> closestIntersection.push(j); <add> console.log(closestIntersection[0]+","+closestIntersection[1]+","+closestIntersection[2]); <add> } <add> } <add> } <add> <add> if (closestIntersection.length) { <add> console.log(closestIntersection[0]+","+closestIntersection[1]+","+closestIntersection[2]); <add> console.log(""); <add> m.live = false; <add> // ship.alive = false; <add> if (ship.shape === "full ship") { <add> switch(closestIntersection[2]) { <add> case 0: <add> if (closestIntersection[1] > 0.5) { //hit on the nose <add> ship.alive = false; <add> } else { <add> ship.shape = "right wing"; <add> } <add> break; <add> case 1: <add> if (closestIntersection[1] < 0.5) { //hit on the nose <add> ship.alive = false; <add> } else { <add> ship.shape = "left wing"; <add> } <add> break; <add> case 2: <add> if (closestIntersection[1] < 0.5) { //hit on the right side <add> ship.shape = "left wing"; <add> } else { <add> ship.shape = "right wing"; <add> } <add> break; <add> } <add> } else if (ship.shape === "left wing") { <add> switch(closestIntersection[2]) { <add> case 0: <add> if (closestIntersection[1] > 0.5) { //hit on the nose <add> ship.alive = false; <add> } else { <add> ship.shape = "nose only"; <add> } <add> break; <add> case 1: <add> case 2: <add> ship.alive = false; <add> break; <add> case 3: <add> case 4: <add> ship.shape = "nose only"; <add> break; <add> } <add> } else if (ship.shape === "right wing") { <add> switch(closestIntersection[2]) { <add> case 1: <add> if (closestIntersection[1] < 0.5) { //hit on the nose <add> ship.alive = false; <add> } else { <add> ship.shape = "nose only"; <add> } <add> break; <add> case 0: <add> case 4: <add> ship.alive = false; <add> break; <add> case 2: <add> case 3: <add> ship.shape = "nose only"; <add> break; <add> } <add> } else if (ship.shape === "nose only") { <ide> ship.alive = false; <del> if (obj.shape === "full ship") { <del> } else if (obj.shape === "left wing") { <del> } else if (obj.shape === "right wing") { <del> } else if (obj.shape === "nose only") { <del> } <ide> } <add> <add> return; <ide> } <ide> } <ide> }
JavaScript
mit
4251e95dcba9de10a40484415ecb7f1880913ea6
0
root-project/jsroot,root-project/jsroot
/// @file JSRoot.io.js /// I/O methods of JavaScript ROOT JSROOT.define([], () => { "use strict"; const clTObject = 'TObject', clTNamed = 'TNamed', kChar = 1, kShort = 2, kInt = 3, kLong = 4, kFloat = 5, kCounter = 6, kCharStar = 7, kDouble = 8, kDouble32 = 9, kLegacyChar = 10, kUChar = 11, kUShort = 12, kUInt = 13, kULong = 14, kBits = 15, kLong64 = 16, kULong64 = 17, kBool = 18, kFloat16 = 19, kBase = 0, kOffsetL = 20, kOffsetP = 40, kObject = 61, kAny = 62, kObjectp = 63, kObjectP = 64, kTString = 65, kTObject = 66, kTNamed = 67, kAnyp = 68, kAnyP = 69, kStreamer = 500, kStreamLoop = 501, kMapOffset = 2, kByteCountMask = 0x40000000, kNewClassTag = 0xFFFFFFFF, kClassMask = 0x80000000, // constants of bits in version kStreamedMemberWise = JSROOT.BIT(14), // constants used for coding type of STL container kNotSTL = 0, kSTLvector = 1, kSTLlist = 2, kSTLdeque = 3, kSTLmap = 4, kSTLmultimap = 5, kSTLset = 6, kSTLmultiset = 7, kSTLbitset = 8, // kSTLforwardlist = 9, kSTLunorderedset = 10, kSTLunorderedmultiset = 11, kSTLunorderedmap = 12, // kSTLunorderedmultimap = 13, kSTLend = 14 // name of base IO types BasicTypeNames = ["BASE", "char", "short", "int", "long", "float", "int", "const char*", "double", "Double32_t", "char", "unsigned char", "unsigned short", "unsigned", "unsigned long", "unsigned", "Long64_t", "ULong64_t", "bool", "Float16_t"], // names of STL containers StlNames = ["", "vector", "list", "deque", "map", "multimap", "set", "multiset", "bitset"], // TObject bits kIsReferenced = JSROOT.BIT(4), kHasUUID = JSROOT.BIT(5); /** @summary Holder of IO functionality * @alias JSROOT.IO * @namespace * @private */ let jsrio = { // here constants which are used by tree /* kAnyPnoVT: 70, */ kSTLp: 71, /* kSkip: 100, kSkipL: 120, kSkipP: 140, kConv: 200, kConvL: 220, kConvP: 240, */ kSTL: 300, /* kSTLstring: 365, */ Mode: "array", // could be string or array, enable usage of ArrayBuffer in http requests // kSplitCollectionOfPointers: 100, // map of user-streamer function like func(buf,obj) // or alias (classname) which can be used to read that function // or list of read functions CustomStreamers: {}, // these are streamers which do not handle version regularly // used for special classes like TRef or TBasket DirectStreamers: {}, /** @summary Returns true if type is integer */ IsInteger(typ) { return ((typ >= kChar) && (typ <= kLong)) || (typ === kCounter) || ((typ >= kLegacyChar) && (typ <= kBool)); }, /** @summary Returns true if numeric type */ IsNumeric(typ) { return (typ > 0) && (typ <= kBool) && (typ !== kCharStar); }, /** @summary Returns type by its name */ GetTypeId(typname, norecursion) { switch (typname) { case "bool": case "Bool_t": return kBool; case "char": case "signed char": case "Char_t": return kChar; case "Color_t": case "Style_t": case "Width_t": case "short": case "Short_t": return kShort; case "int": case "EErrorType": case "Int_t": return kInt; case "long": case "Long_t": return kLong; case "float": case "Float_t": return kFloat; case "double": case "Double_t": return kDouble; case "unsigned char": case "UChar_t": return kUChar; case "unsigned short": case "UShort_t": return kUShort; case "unsigned": case "unsigned int": case "UInt_t": return kUInt; case "unsigned long": case "ULong_t": return kULong; case "int64_t": case "long long": case "Long64_t": return kLong64; case "uint64_t": case "unsigned long long": case "ULong64_t": return kULong64; case "Double32_t": return kDouble32; case "Float16_t": return kFloat16; case "char*": case "const char*": case "const Char_t*": return kCharStar; } if (!norecursion) { let replace = jsrio.CustomStreamers[typname]; if (typeof replace === "string") return jsrio.GetTypeId(replace, true); } return -1; }, /** @summary Get bytes size of the type */ GetTypeSize(typname) { switch (typname) { case kBool: case kChar: case kUChar: return 1; case kShort: case kUShort: return 2; case kInt: case kFloat: case kUInt: return 4; case kLong: case kDouble: case kULong: case kLong64: case kULong64: return 8; } return -1; }, /** @summary Add custom streamer * @public */ addUserStreamer(type, user_streamer) { jsrio.CustomStreamers[type] = user_streamer; } } // namespace jsrio /** @summary Analyze and returns arrays kind * @return 0 if TString (or equivalent), positive value - some basic type, -1 - any other kind * @private */ function getArrayKind(type_name) { if ((type_name === "TString") || (type_name === "string") || (jsrio.CustomStreamers[type_name] === 'TString')) return 0; if ((type_name.length < 7) || (type_name.indexOf("TArray") !== 0)) return -1; if (type_name.length == 7) switch (type_name[6]) { case 'I': return kInt; case 'D': return kDouble; case 'F': return kFloat; case 'S': return kShort; case 'C': return kChar; case 'L': return kLong; default: return -1; } return type_name == "TArrayL64" ? kLong64 : -1; } /** @summary Let directly assign methods when doing I/O * @private */ function addClassMethods(clname, streamer) { if (streamer === null) return streamer; let methods = JSROOT.getMethods(clname); if (methods !== null) for (let key in methods) if ((typeof methods[key] === 'function') || (key.indexOf("_") == 0)) streamer.push({ name: key, method: methods[key], func: function(buf, obj) { obj[this.name] = this.method; } }); return streamer; } /* Copyright (C) 1999 Masanao Izumo <[email protected]> * Version: 1.0.0.1 * LastModified: Dec 25 1999 * original: http://www.onicos.com/staff/iz/amuse/javascript/expert/inflate.txt */ /* constant parameters */ const zip_WSIZE = 32768; // Sliding Window size /* constant tables (inflate) */ const zip_MASK_BITS = [ 0x0000, 0x0001, 0x0003, 0x0007, 0x000f, 0x001f, 0x003f, 0x007f, 0x00ff, 0x01ff, 0x03ff, 0x07ff, 0x0fff, 0x1fff, 0x3fff, 0x7fff, 0xffff], // Tables for deflate from PKZIP's appnote.txt. zip_cplens = [ // Copy lengths for literal codes 257..285 3, 4, 5, 6, 7, 8, 9, 10, 11, 13, 15, 17, 19, 23, 27, 31, 35, 43, 51, 59, 67, 83, 99, 115, 131, 163, 195, 227, 258, 0, 0], /* note: see note #13 above about the 258 in this list. */ zip_cplext = [ // Extra bits for literal codes 257..285 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 2, 2, 2, 2, 3, 3, 3, 3, 4, 4, 4, 4, 5, 5, 5, 5, 0, 99, 99], // 99==invalid zip_cpdist = [ // Copy offsets for distance codes 0..29 1, 2, 3, 4, 5, 7, 9, 13, 17, 25, 33, 49, 65, 97, 129, 193, 257, 385, 513, 769, 1025, 1537, 2049, 3073, 4097, 6145, 8193, 12289, 16385, 24577], zip_cpdext = [ // Extra bits for distance codes 0, 0, 0, 0, 1, 1, 2, 2, 3, 3, 4, 4, 5, 5, 6, 6, 7, 7, 8, 8, 9, 9, 10, 10, 11, 11, 12, 12, 13, 13], zip_border = [ // Order of the bit length code lengths 16, 17, 18, 0, 8, 7, 9, 6, 10, 5, 11, 4, 12, 3, 13, 2, 14, 1, 15]; // zip_STORED_BLOCK = 0, // zip_STATIC_TREES = 1, // zip_DYN_TREES = 2, /* for inflate */ // zip_lbits = 9, // bits in base literal/length lookup table // zip_dbits = 6, // bits in base distance lookup table // zip_INBUFSIZ = 32768, // Input buffer size // zip_INBUF_EXTRA = 64, // Extra buffer function ZIP_inflate(arr, tgt) { /* variables (inflate) */ let zip_slide = new Array(2 * zip_WSIZE), zip_wp = 0, // current position in slide zip_fixed_tl = null, // inflate static zip_fixed_td, // inflate static zip_fixed_bl, zip_fixed_bd, // inflate static zip_bit_buf = 0, // bit buffer zip_bit_len = 0, // bits in bit buffer zip_method = -1, zip_eof = false, zip_copy_leng = 0, zip_copy_dist = 0, zip_tl = null, zip_td, // literal/length and distance decoder tables zip_bl, zip_bd, // number of bits decoded by tl and td zip_inflate_data = arr, zip_inflate_datalen = arr.byteLength, zip_inflate_pos = 0; function zip_NEEDBITS(n) { while (zip_bit_len < n) { if (zip_inflate_pos < zip_inflate_datalen) zip_bit_buf |= zip_inflate_data[zip_inflate_pos++] << zip_bit_len; zip_bit_len += 8; } } function zip_GETBITS(n) { return zip_bit_buf & zip_MASK_BITS[n]; } function zip_DUMPBITS(n) { zip_bit_buf >>= n; zip_bit_len -= n; } /* objects (inflate) */ function zip_HuftBuild(b, // code lengths in bits (all assumed <= BMAX) n, // number of codes (assumed <= N_MAX) s, // number of simple-valued codes (0..s-1) d, // list of base values for non-simple codes e, // list of extra bits for non-simple codes mm ) { // maximum lookup bits this.status = 0; // 0: success, 1: incomplete table, 2: bad input this.root = null; // (zip_HuftList) starting table this.m = 0; // maximum lookup bits, returns actual /* Given a list of code lengths and a maximum table size, make a set of tables to decode that set of codes. Return zero on success, one if the given code set is incomplete (the tables are still built in this case), two if the input is invalid (all zero length codes or an oversubscribed set of lengths), and three if not enough memory. The code with value 256 is special, and the tables are constructed so that no bits beyond that code are fetched when that code is decoded. */ const BMAX = 16, // maximum bit length of any code N_MAX = 288; // maximum number of codes in any set let c = Array(BMAX+1).fill(0), // bit length count table lx = Array(BMAX+1).fill(0), // stack of bits per table u = Array(BMAX).fill(null), // zip_HuftNode[BMAX][] table stack v = Array(N_MAX).fill(0), // values in order of bit length x = Array(BMAX+1).fill(0),// bit offsets, then code stack r = { e: 0, b: 0, n: 0, t: null }, // new zip_HuftNode(), // table entry for structure assignment rr = null, // temporary variable, use in assignment el = (n > 256) ? b[256] : BMAX, // set length of EOB code, if any a, // counter for codes of length k f, // i repeats in table every f entries g, // maximum code length h, // table level j, // counter k, // number of bits in current code p = b, // pointer into c[], b[], or v[] pidx = 0, // index of p q, // (zip_HuftNode) points to current table w, xp, // pointer into x or c y, // number of dummy codes added z, // number of entries in current table o, tail = this.root = null, // (zip_HuftList) i = n; // counter, current code // Generate counts for each bit length do { c[p[pidx++]]++; // assume all entries <= BMAX } while (--i > 0); if (c[0] == n) { // null input--all zero length codes this.root = null; this.m = 0; this.status = 0; return this; } // Find minimum and maximum length, bound *m by those for (j = 1; j <= BMAX; ++j) if (c[j] != 0) break; k = j; // minimum code length if (mm < j) mm = j; for (i = BMAX; i != 0; --i) if (c[i] != 0) break; g = i; // maximum code length if (mm > i) mm = i; // Adjust last length count to fill out codes, if needed for (y = 1 << j; j < i; ++j, y <<= 1) { if ((y -= c[j]) < 0) { this.status = 2; // bad input: more codes than bits this.m = mm; return this; } } if ((y -= c[i]) < 0) { this.status = 2; this.m = mm; return this; } c[i] += y; // Generate starting offsets into the value table for each length x[1] = j = 0; p = c; pidx = 1; xp = 2; while (--i > 0) // note that i == g from above x[xp++] = (j += p[pidx++]); // Make a table of values in order of bit lengths p = b; pidx = 0; i = 0; do { if ((j = p[pidx++]) != 0) v[x[j]++] = i; } while (++i < n); n = x[g]; // set n to length of v // Generate the Huffman codes and for each, make the table entries x[0] = i = 0; // first Huffman code is zero p = v; pidx = 0; // grab values in bit order h = -1; // no tables yet--level -1 w = lx[0] = 0; // no bits decoded yet q = null; // ditto z = 0; // ditto // go through the bit lengths (k already is bits in shortest code) for (; k <= g; ++k) { a = c[k]; while (a-- > 0) { // here i is the Huffman code of length k bits for value p[pidx] // make tables up to required level while (k > w + lx[1 + h]) { w += lx[1 + h++]; // add bits already decoded // compute minimum size table less than or equal to *m bits z = (z = g - w) > mm ? mm : z; // upper limit if ((f = 1 << (j = k - w)) > a + 1) { // try a k-w bit table // too few codes for k-w bit table f -= a + 1; // deduct codes from patterns left xp = k; while (++j < z) { // try smaller tables up to z bits if ((f <<= 1) <= c[++xp]) break; // enough codes to use up j bits f -= c[xp]; // else deduct codes from patterns } } if (w + j > el && w < el) j = el - w; // make EOB code end at table z = 1 << j; // table entries for j-bit table lx[1 + h] = j; // set table size in stack // allocate and link in new table q = new Array(z); for (o = 0; o < z; ++o) q[o] = { e: 0, b: 0, n: 0, t: null }; // new zip_HuftNode if (tail == null) tail = this.root = { next: null, list: null }; // new zip_HuftList(); else tail = tail.next = { next: null, list: null }; // new zip_HuftList(); tail.next = null; tail.list = q; u[h] = q; // table starts after link /* connect to last table, if there is one */ if (h > 0) { x[h] = i; // save pattern for backing up r.b = lx[h]; // bits to dump before this table r.e = 16 + j; // bits in this table r.t = q; // pointer to this table j = (i & ((1 << w) - 1)) >> (w - lx[h]); rr = u[h-1][j]; rr.e = r.e; rr.b = r.b; rr.n = r.n; rr.t = r.t; } } // set up table entry in r r.b = k - w; if (pidx >= n) r.e = 99; // out of values--invalid code else if (p[pidx] < s) { r.e = (p[pidx] < 256 ? 16 : 15); // 256 is end-of-block code r.n = p[pidx++]; // simple code is just the value } else { r.e = e[p[pidx] - s]; // non-simple--look up in lists r.n = d[p[pidx++] - s]; } // fill code-like entries with r // f = 1 << (k - w); for (j = i >> w; j < z; j += f) { rr = q[j]; rr.e = r.e; rr.b = r.b; rr.n = r.n; rr.t = r.t; } // backwards increment the k-bit code i for (j = 1 << (k - 1); (i & j) != 0; j >>= 1) i ^= j; i ^= j; // backup over finished tables while ((i & ((1 << w) - 1)) != x[h]) { w -= lx[h--]; // don't need to update q } } } /* return actual size of base table */ this.m = lx[1]; /* Return true (1) if we were given an incomplete table */ this.status = ((y != 0 && g != 1) ? 1 : 0); /* end of constructor */ return this; } /* routines (inflate) */ function zip_inflate_codes(buff, off, size) { if (size == 0) return 0; /* inflate (decompress) the codes in a deflated (compressed) block. Return an error code or zero if it all goes ok. */ let e, // table entry flag/number of extra bits t, // (zip_HuftNode) pointer to table entry n = 0; // inflate the coded data for (;;) { // do until end of block zip_NEEDBITS(zip_bl); t = zip_tl.list[zip_GETBITS(zip_bl)]; e = t.e; while (e > 16) { if (e == 99) return -1; zip_DUMPBITS(t.b); e -= 16; zip_NEEDBITS(e); t = t.t[zip_GETBITS(e)]; e = t.e; } zip_DUMPBITS(t.b); if (e == 16) { // then it's a literal zip_wp &= zip_WSIZE - 1; buff[off + n++] = zip_slide[zip_wp++] = t.n; if (n == size) return size; continue; } // exit if end of block if (e == 15) break; // it's an EOB or a length // get length of block to copy zip_NEEDBITS(e); zip_copy_leng = t.n + zip_GETBITS(e); zip_DUMPBITS(e); // decode distance of block to copy zip_NEEDBITS(zip_bd); t = zip_td.list[zip_GETBITS(zip_bd)]; e = t.e; while (e > 16) { if (e == 99) return -1; zip_DUMPBITS(t.b); e -= 16; zip_NEEDBITS(e); t = t.t[zip_GETBITS(e)]; e = t.e; } zip_DUMPBITS(t.b); zip_NEEDBITS(e); zip_copy_dist = zip_wp - t.n - zip_GETBITS(e); zip_DUMPBITS(e); // do the copy while (zip_copy_leng > 0 && n < size) { --zip_copy_leng; zip_copy_dist &= zip_WSIZE - 1; zip_wp &= zip_WSIZE - 1; buff[off + n++] = zip_slide[zip_wp++] = zip_slide[zip_copy_dist++]; } if (n == size) return size; } zip_method = -1; // done return n; } function zip_inflate_stored(buff, off, size) { /* "decompress" an inflated type 0 (stored) block. */ // go to byte boundary let n = zip_bit_len & 7; zip_DUMPBITS(n); // get the length and its complement zip_NEEDBITS(16); n = zip_GETBITS(16); zip_DUMPBITS(16); zip_NEEDBITS(16); if (n != ((~zip_bit_buf) & 0xffff)) return -1; // error in compressed data zip_DUMPBITS(16); // read and output the compressed data zip_copy_leng = n; n = 0; while (zip_copy_leng > 0 && n < size) { --zip_copy_leng; zip_wp &= zip_WSIZE - 1; zip_NEEDBITS(8); buff[off + n++] = zip_slide[zip_wp++] = zip_GETBITS(8); zip_DUMPBITS(8); } if (zip_copy_leng == 0) zip_method = -1; // done return n; } function zip_inflate_fixed(buff, off, size) { /* decompress an inflated type 1 (fixed Huffman codes) block. We should either replace this with a custom decoder, or at least precompute the Huffman tables. */ // if first time, set up tables for fixed blocks if (zip_fixed_tl == null) { let i = 0, // temporary variable l = new Array(288); // length list for huft_build // literal table while (i < 144) l[i++] = 8; while (i < 256) l[i++] = 9; while (i < 280) l[i++] = 7; while (i < 288) l[i++] = 8; // make a complete, but wrong code set zip_fixed_bl = 7; let h = new zip_HuftBuild(l, 288, 257, zip_cplens, zip_cplext, zip_fixed_bl); if (h.status != 0) throw new Error("HufBuild error: " + h.status); zip_fixed_tl = h.root; zip_fixed_bl = h.m; // distance table for (i = 0; i<30; ++i) l[i] = 5;// make an incomplete code set zip_fixed_bd = 5; h = new zip_HuftBuild(l, 30, 0, zip_cpdist, zip_cpdext, zip_fixed_bd); if (h.status > 1) { zip_fixed_tl = null; throw new Error("HufBuild error: "+h.status); } zip_fixed_td = h.root; zip_fixed_bd = h.m; } zip_tl = zip_fixed_tl; zip_td = zip_fixed_td; zip_bl = zip_fixed_bl; zip_bd = zip_fixed_bd; return zip_inflate_codes(buff, off, size); } function zip_inflate_dynamic(buff, off, size) { // decompress an inflated type 2 (dynamic Huffman codes) block. let i,j, // temporary variables l, // last length n, // number of lengths to get t, // (zip_HuftNode) literal/length code table h, // (zip_HuftBuild) ll = new Array(286+30); // literal/length and distance code lengths for (i = 0; i < ll.length; ++i) ll[i] = 0; // read in table lengths zip_NEEDBITS(5); const nl = 257 + zip_GETBITS(5); // number of literal/length codes zip_DUMPBITS(5); zip_NEEDBITS(5); const nd = 1 + zip_GETBITS(5); // number of distance codes zip_DUMPBITS(5); zip_NEEDBITS(4); const nb = 4 + zip_GETBITS(4); // number of bit length codes zip_DUMPBITS(4); if (nl > 286 || nd > 30) return -1; // bad lengths // read in bit-length-code lengths for (j = 0; j < nb; ++j) { zip_NEEDBITS(3); ll[zip_border[j]] = zip_GETBITS(3); zip_DUMPBITS(3); } for (; j < 19; ++j) ll[zip_border[j]] = 0; // build decoding table for trees--single level, 7 bit lookup zip_bl = 7; h = new zip_HuftBuild(ll, 19, 19, null, null, zip_bl); if (h.status != 0) return -1; // incomplete code set zip_tl = h.root; zip_bl = h.m; // read in literal and distance code lengths n = nl + nd; i = l = 0; while (i < n) { zip_NEEDBITS(zip_bl); t = zip_tl.list[zip_GETBITS(zip_bl)]; j = t.b; zip_DUMPBITS(j); j = t.n; if (j < 16) // length of code in bits (0..15) ll[i++] = l = j; // save last length in l else if (j == 16) { // repeat last length 3 to 6 times zip_NEEDBITS(2); j = 3 + zip_GETBITS(2); zip_DUMPBITS(2); if (i + j > n) return -1; while (j-- > 0) ll[i++] = l; } else if (j == 17) { // 3 to 10 zero length codes zip_NEEDBITS(3); j = 3 + zip_GETBITS(3); zip_DUMPBITS(3); if (i + j > n) return -1; while (j-- > 0) ll[i++] = 0; l = 0; } else { // j == 18: 11 to 138 zero length codes zip_NEEDBITS(7); j = 11 + zip_GETBITS(7); zip_DUMPBITS(7); if (i + j > n) return -1; while (j-- > 0) ll[i++] = 0; l = 0; } } // build the decoding tables for literal/length and distance codes zip_bl = 9; // zip_lbits; h = new zip_HuftBuild(ll, nl, 257, zip_cplens, zip_cplext, zip_bl); if (zip_bl == 0) // no literals or lengths h.status = 1; if (h.status != 0) { // if (h.status == 1); // **incomplete literal tree** return -1; // incomplete code set } zip_tl = h.root; zip_bl = h.m; for (i = 0; i < nd; ++i) ll[i] = ll[i + nl]; zip_bd = 6; // zip_dbits; h = new zip_HuftBuild(ll, nd, 0, zip_cpdist, zip_cpdext, zip_bd); zip_td = h.root; zip_bd = h.m; if (zip_bd == 0 && nl > 257) { // lengths but no distances // **incomplete distance tree** return -1; } //if (h.status == 1); // **incomplete distance tree** if (h.status != 0) return -1; // decompress until an end-of-block code return zip_inflate_codes(buff, off, size); } function zip_inflate_internal(buff, off, size) { // decompress an inflated entry let n = 0, i; while (n < size) { if (zip_eof && zip_method == -1) return n; if (zip_copy_leng > 0) { if (zip_method != 0 /*zip_STORED_BLOCK*/) { // STATIC_TREES or DYN_TREES while (zip_copy_leng > 0 && n < size) { --zip_copy_leng; zip_copy_dist &= zip_WSIZE - 1; zip_wp &= zip_WSIZE - 1; buff[off + n++] = zip_slide[zip_wp++] = zip_slide[zip_copy_dist++]; } } else { while (zip_copy_leng > 0 && n < size) { --zip_copy_leng; zip_wp &= zip_WSIZE - 1; zip_NEEDBITS(8); buff[off + n++] = zip_slide[zip_wp++] = zip_GETBITS(8); zip_DUMPBITS(8); } if (zip_copy_leng == 0) zip_method = -1; // done } if (n == size) return n; } if (zip_method == -1) { if (zip_eof) break; // read in last block bit zip_NEEDBITS(1); if (zip_GETBITS(1) != 0) zip_eof = true; zip_DUMPBITS(1); // read in block type zip_NEEDBITS(2); zip_method = zip_GETBITS(2); zip_DUMPBITS(2); zip_tl = null; zip_copy_leng = 0; } switch (zip_method) { case 0: // zip_STORED_BLOCK i = zip_inflate_stored(buff, off + n, size - n); break; case 1: // zip_STATIC_TREES if (zip_tl != null) i = zip_inflate_codes(buff, off + n, size - n); else i = zip_inflate_fixed(buff, off + n, size - n); break; case 2: // zip_DYN_TREES if (zip_tl != null) i = zip_inflate_codes(buff, off + n, size - n); else i = zip_inflate_dynamic(buff, off + n, size - n); break; default: // error i = -1; break; } if (i == -1) return zip_eof ? 0 : -1; n += i; } return n; } let i, cnt = 0; while ((i = zip_inflate_internal(tgt, cnt, Math.min(1024, tgt.byteLength-cnt))) > 0) { cnt += i; } return cnt; } // function ZIP_inflate /** * https://github.com/pierrec/node-lz4/blob/master/lib/binding.js * * LZ4 based compression and decompression * Copyright (c) 2014 Pierre Curto * MIT Licensed */ /** * Decode a block. Assumptions: input contains all sequences of a * chunk, output is large enough to receive the decoded data. * If the output buffer is too small, an error will be thrown. * If the returned value is negative, an error occured at the returned offset. * * @param input {Buffer} input data * @param output {Buffer} output data * @return {Number} number of decoded bytes * @private */ function LZ4_uncompress(input, output, sIdx, eIdx) { sIdx = sIdx || 0; eIdx = eIdx || (input.length - sIdx); // Process each sequence in the incoming data for (let i = sIdx, n = eIdx, j = 0; i < n;) { let token = input[i++]; // Literals let literals_length = (token >> 4); if (literals_length > 0) { // length of literals let l = literals_length + 240; while (l === 255) { l = input[i++]; literals_length += l; } // Copy the literals let end = i + literals_length; while (i < end) output[j++] = input[i++]; // End of buffer? if (i === n) return j; } // Match copy // 2 bytes offset (little endian) const offset = input[i++] | (input[i++] << 8); // 0 is an invalid offset value if (offset === 0 || offset > j) return -(i-2); // length of match copy let match_length = (token & 0xf), l = match_length + 240; while (l === 255) { l = input[i++]; match_length += l; } // Copy the match let pos = j - offset; // position of the match copy in the current output const end = j + match_length + 4 // minmatch = 4; while (j < end) output[j++] = output[pos++] } return j; } /** @summary Reads header envelope, determines zipped size and unzip content * @returns {Promise} with unzipped content * @private */ jsrio.R__unzip = function(arr, tgtsize, noalert, src_shift) { const HDRSIZE = 9, totallen = arr.byteLength, getChar = o => String.fromCharCode(arr.getUint8(o)), getCode = o => arr.getUint8(o); let curr = src_shift || 0, fullres = 0, tgtbuf = null; const nextPortion = () => { while (fullres < tgtsize) { let fmt = "unknown", off = 0, CHKSUM = 0; if (curr + HDRSIZE >= totallen) { if (!noalert) console.error("Error R__unzip: header size exceeds buffer size"); return Promise.resolve(null); } if (getChar(curr) == 'Z' && getChar(curr + 1) == 'L' && getCode(curr + 2) == 8) { fmt = "new"; off = 2; } else if (getChar(curr) == 'C' && getChar(curr + 1) == 'S' && getCode(curr + 2) == 8) { fmt = "old"; off = 0; } else if (getChar(curr) == 'X' && getChar(curr + 1) == 'Z' && getCode(curr + 2) == 0) fmt = "LZMA"; else if (getChar(curr) == 'Z' && getChar(curr + 1) == 'S' && getCode(curr + 2) == 1) fmt = "ZSTD"; else if (getChar(curr) == 'L' && getChar(curr + 1) == '4') { fmt = "LZ4"; off = 0; CHKSUM = 8; } /* C H E C K H E A D E R */ if ((fmt !== "new") && (fmt !== "old") && (fmt !== "LZ4") && (fmt !== "ZSTD")) { if (!noalert) console.error(`R__unzip: ${fmt} format is not supported!`); return Promise.resolve(null); } const srcsize = HDRSIZE + ((getCode(curr + 3) & 0xff) | ((getCode(curr + 4) & 0xff) << 8) | ((getCode(curr + 5) & 0xff) << 16)); const uint8arr = new Uint8Array(arr.buffer, arr.byteOffset + curr + HDRSIZE + off + CHKSUM, Math.min(arr.byteLength - curr - HDRSIZE - off - CHKSUM, srcsize - HDRSIZE - CHKSUM)); if (fmt === "ZSTD") { const handleZsdt = ZstdCodec => { return new Promise((resolveFunc, rejectFunc) => { ZstdCodec.run(zstd => { // const simple = new zstd.Simple(); const streaming = new zstd.Streaming(); // const data2 = simple.decompress(uint8arr); const data2 = streaming.decompress(uint8arr); // console.log(`tgtsize ${tgtsize} zstd size ${data2.length} offset ${data2.byteOffset} rawlen ${data2.buffer.byteLength}`); const reslen = data2.length; if (data2.byteOffset !== 0) return rejectFunc(Error("ZSTD result with byteOffset != 0")); // shortcut when exactly required data unpacked //if ((tgtsize == reslen) && data2.buffer) // resolveFunc(new DataView(data2.buffer)); // need to copy data while zstd does not provide simple way of doing it if (!tgtbuf) tgtbuf = new ArrayBuffer(tgtsize); let tgt8arr = new Uint8Array(tgtbuf, fullres); for(let i = 0; i < reslen; ++i) tgt8arr[i] = data2[i]; fullres += reslen; curr += srcsize; resolveFunc(true); }); }); }; let promise = JSROOT.nodejs ? handleZsdt(require('zstd-codec').ZstdCodec) : JSROOT.require('zstd-codec').then(codec => handleZsdt(codec)); return promise.then(() => nextPortion()); } // place for unpacking if (!tgtbuf) tgtbuf = new ArrayBuffer(tgtsize); let tgt8arr = new Uint8Array(tgtbuf, fullres); const reslen = (fmt === "LZ4") ? LZ4_uncompress(uint8arr, tgt8arr) : ZIP_inflate(uint8arr, tgt8arr); if (reslen <= 0) break; fullres += reslen; curr += srcsize; } if (fullres !== tgtsize) { if (!noalert) console.error(`R__unzip: fail to unzip data expects ${tgtsize}, got ${fullres}`); return Promise.resolve(null); } return Promise.resolve(new DataView(tgtbuf)); }; return nextPortion(); } // ================================================================================= /** * @summary Buffer object to read data from TFile * * @memberof JSROOT * @private */ class TBuffer { constructor(arr, pos, file, length) { this._typename = "TBuffer"; this.arr = arr; this.o = pos || 0; this.fFile = file; this.length = length || (arr ? arr.byteLength : 0); // use size of array view, blob buffer can be much bigger this.clearObjectMap(); this.fTagOffset = 0; this.last_read_version = 0; } /** @summary locate position in the buffer */ locate(pos) { this.o = pos; } /** @summary shift position in the buffer */ shift(cnt) { this.o += cnt; } /** @summary Returns remaining place in the buffer */ remain() { return this.length - this.o; } /** @summary Get mapped object with provided tag */ getMappedObject(tag) { return this.fObjectMap[tag]; } /** @summary Map object */ mapObject(tag, obj) { if (obj !== null) this.fObjectMap[tag] = obj; } /** @summary Map class */ mapClass(tag, classname) { this.fClassMap[tag] = classname; } /** @summary Get mapped class with provided tag */ getMappedClass(tag) { return (tag in this.fClassMap) ? this.fClassMap[tag] : -1; } /** @summary Clear objects map */ clearObjectMap() { this.fObjectMap = {}; this.fClassMap = {}; this.fObjectMap[0] = null; this.fDisplacement = 0; } /** @summary read class version from I/O buffer */ readVersion() { let ver = {}, bytecnt = this.ntou4(); // byte count if (bytecnt & kByteCountMask) ver.bytecnt = bytecnt - kByteCountMask - 2; // one can check between Read version and end of streamer else this.o -= 4; // rollback read bytes, this is old buffer without byte count this.last_read_version = ver.val = this.ntoi2(); this.last_read_checksum = 0; ver.off = this.o; if ((ver.val <= 0) && ver.bytecnt && (ver.bytecnt >= 4)) { ver.checksum = this.ntou4(); if (!this.fFile.findStreamerInfo(undefined, undefined, ver.checksum)) { // console.error(`Fail to find streamer info with check sum ${ver.checksum} version ${ver.val}`); this.o -= 4; // not found checksum in the list delete ver.checksum; // remove checksum } else { this.last_read_checksum = ver.checksum; } } return ver; } /** @summary Check bytecount after object streaming */ checkByteCount(ver, where) { if ((ver.bytecnt !== undefined) && (ver.off + ver.bytecnt !== this.o)) { if (where) console.log(`Missmatch in ${where} bytecount expected = ${ver.bytecnt} got = ${this.o - ver.off}`); this.o = ver.off + ver.bytecnt; return false; } return true; } /** @summary Read TString object (or equivalent) * @desc std::string uses similar binary format */ readTString() { let len = this.ntou1(); // large strings if (len == 255) len = this.ntou4(); if (len == 0) return ""; const pos = this.o; this.o += len; return (this.codeAt(pos) == 0) ? '' : this.substring(pos, pos + len); } /** @summary read Char_t array as string * @desc string either contains all symbols or until 0 symbol */ readFastString(n) { let res = "", code, closed = false; for (let i = 0; (n < 0) || (i < n); ++i) { code = this.ntou1(); if (code == 0) { closed = true; if (n < 0) break; } if (!closed) res += String.fromCharCode(code); } return res; } /** @summary read uint8_t */ ntou1() { return this.arr.getUint8(this.o++); } /** @summary read uint16_t */ ntou2() { const o = this.o; this.o += 2; return this.arr.getUint16(o); } /** @summary read uint32_t */ ntou4() { const o = this.o; this.o += 4; return this.arr.getUint32(o); } /** @summary read uint64_t */ ntou8() { const high = this.arr.getUint32(this.o); this.o += 4; const low = this.arr.getUint32(this.o); this.o += 4; return (high < 0x200000) ? (high * 0x100000000 + low) : (BigInt(high) * BigInt(0x100000000) + BigInt(low)); } /** @summary read int8_t */ ntoi1() { return this.arr.getInt8(this.o++); } /** @summary read int16_t */ ntoi2() { const o = this.o; this.o += 2; return this.arr.getInt16(o); } /** @summary read int32_t */ ntoi4() { const o = this.o; this.o += 4; return this.arr.getInt32(o); } /** @summary read int64_t */ ntoi8() { const high = this.arr.getUint32(this.o); this.o += 4; const low = this.arr.getUint32(this.o); this.o += 4; if (high < 0x80000000) return (high < 0x200000) ? (high * 0x100000000 + low) : (BigInt(high) * BigInt(0x100000000) + BigInt(low)); return (~high < 0x200000) ? (-1 - ((~high) * 0x100000000 + ~low)) : (BigInt(-1) - (BigInt(~high) * BigInt(0x100000000) + BigInt(~low))); } /** @summary read float */ ntof() { const o = this.o; this.o += 4; return this.arr.getFloat32(o); } /** @summary read double */ ntod() { const o = this.o; this.o += 8; return this.arr.getFloat64(o); } /** @summary Reads array of n values from the I/O buffer */ readFastArray(n, array_type) { let array, i = 0, o = this.o; const view = this.arr; switch (array_type) { case kDouble: array = new Float64Array(n); for (; i < n; ++i, o += 8) array[i] = view.getFloat64(o); break; case kFloat: array = new Float32Array(n); for (; i < n; ++i, o += 4) array[i] = view.getFloat32(o); break; case kLong: case kLong64: array = new Array(n); for (; i < n; ++i) array[i] = this.ntoi8(); return array; // exit here to avoid conflicts case kULong: case kULong64: array = new Array(n); for (; i < n; ++i) array[i] = this.ntou8(); return array; // exit here to avoid conflicts case kInt: case kCounter: array = new Int32Array(n); for (; i < n; ++i, o += 4) array[i] = view.getInt32(o); break; case kShort: array = new Int16Array(n); for (; i < n; ++i, o += 2) array[i] = view.getInt16(o); break; case kUShort: array = new Uint16Array(n); for (; i < n; ++i, o += 2) array[i] = view.getUint16(o); break; case kChar: array = new Int8Array(n); for (; i < n; ++i) array[i] = view.getInt8(o++); break; case kBool: case kUChar: array = new Uint8Array(n); for (; i < n; ++i) array[i] = view.getUint8(o++); break; case kTString: array = new Array(n); for (; i < n; ++i) array[i] = this.readTString(); return array; // exit here to avoid conflicts case kDouble32: throw new Error('kDouble32 should not be used in readFastArray'); case kFloat16: throw new Error('kFloat16 should not be used in readFastArray'); // case kBits: // case kUInt: default: array = new Uint32Array(n); for (; i < n; ++i, o += 4) array[i] = view.getUint32(o); break; } this.o = o; return array; } /** @summary Check if provided regions can be extracted from the buffer */ canExtract(place) { for (let n = 0; n < place.length; n += 2) if (place[n] + place[n + 1] > this.length) return false; return true; } /** @summary Extract area */ extract(place) { if (!this.arr || !this.arr.buffer || !this.canExtract(place)) return null; if (place.length === 2) return new DataView(this.arr.buffer, this.arr.byteOffset + place[0], place[1]); let res = new Array(place.length / 2); for (let n = 0; n < place.length; n += 2) res[n / 2] = new DataView(this.arr.buffer, this.arr.byteOffset + place[n], place[n + 1]); return res; // return array of buffers } /** @summary Get code at buffer position */ codeAt(pos) { return this.arr.getUint8(pos); } /** @summary Get part of buffer as string */ substring(beg, end) { let res = ""; for (let n = beg; n < end; ++n) res += String.fromCharCode(this.arr.getUint8(n)); return res; } /** @summary Read buffer as N-dim array */ readNdimArray(handle, func) { let ndim = handle.fArrayDim, maxindx = handle.fMaxIndex, res; if ((ndim < 1) && (handle.fArrayLength > 0)) { ndim = 1; maxindx = [handle.fArrayLength]; } if (handle.minus1) --ndim; if (ndim < 1) return func(this, handle); if (ndim === 1) { res = new Array(maxindx[0]); for (let n = 0; n < maxindx[0]; ++n) res[n] = func(this, handle); } else if (ndim === 2) { res = new Array(maxindx[0]); for (let n = 0; n < maxindx[0]; ++n) { let res2 = new Array(maxindx[1]); for (let k = 0; k < maxindx[1]; ++k) res2[k] = func(this, handle); res[n] = res2; } } else { let indx = [], arr = [], k; for (k = 0; k < ndim; ++k) { indx[k] = 0; arr[k] = []; } res = arr[0]; while (indx[0] < maxindx[0]) { k = ndim - 1; arr[k].push(func(this, handle)); ++indx[k]; while ((indx[k] === maxindx[k]) && (k > 0)) { indx[k] = 0; arr[k - 1].push(arr[k]); arr[k] = []; ++indx[--k]; } } } return res; } /** @summary read TKey data */ readTKey(key) { if (!key) key = {}; this.classStreamer(key, 'TKey'); let name = key.fName.replace(/['"]/g, ''); if (name !== key.fName) { key.fRealName = key.fName; key.fName = name; } return key; } /** @summary reading basket data * @desc this is remaining part of TBasket streamer to decode fEntryOffset * after unzipping of the TBasket data */ readBasketEntryOffset(basket, offset) { this.locate(basket.fLast - offset); if (this.remain() <= 0) { if (!basket.fEntryOffset && (basket.fNevBuf <= 1)) basket.fEntryOffset = [basket.fKeylen]; if (!basket.fEntryOffset) console.warn("No fEntryOffset when expected for basket with", basket.fNevBuf, "entries"); return; } const nentries = this.ntoi4(); // there is error in file=reco_103.root&item=Events;2/PCaloHits_g4SimHits_EcalHitsEE_Sim.&opt=dump;num:10;first:101 // it is workaround, but normally I/O should fail here if ((nentries < 0) || (nentries > this.remain() * 4)) { console.error("Error when reading entries offset from basket fNevBuf", basket.fNevBuf, "remains", this.remain(), "want to read", nentries); if (basket.fNevBuf <= 1) basket.fEntryOffset = [basket.fKeylen]; return; } basket.fEntryOffset = this.readFastArray(nentries, kInt); if (!basket.fEntryOffset) basket.fEntryOffset = [basket.fKeylen]; if (this.remain() > 0) basket.fDisplacement = this.readFastArray(this.ntoi4(), kInt); else basket.fDisplacement = undefined; } /** @summary read class definition from I/O buffer */ readClass() { const classInfo = { name: -1 }, bcnt = this.ntou4(), startpos = this.o; let tag; if (!(bcnt & kByteCountMask) || (bcnt == kNewClassTag)) { tag = bcnt; // bcnt = 0; } else { tag = this.ntou4(); } if (!(tag & kClassMask)) { classInfo.objtag = tag + this.fDisplacement; // indicate that we have deal with objects tag return classInfo; } if (tag == kNewClassTag) { // got a new class description followed by a new object classInfo.name = this.readFastString(-1); if (this.getMappedClass(this.fTagOffset + startpos + kMapOffset) === -1) this.mapClass(this.fTagOffset + startpos + kMapOffset, classInfo.name); } else { // got a tag to an already seen class const clTag = (tag & ~kClassMask) + this.fDisplacement; classInfo.name = this.getMappedClass(clTag); if (classInfo.name === -1) console.error(`Did not found class with tag ${clTag}`); } return classInfo; } /** @summary Read any object from buffer data */ readObjectAny() { const objtag = this.fTagOffset + this.o + kMapOffset, clRef = this.readClass(); // class identified as object and should be handled so if ('objtag' in clRef) return this.getMappedObject(clRef.objtag); if (clRef.name === -1) return null; const arrkind = getArrayKind(clRef.name); let obj; if (arrkind === 0) { obj = this.readTString(); } else if (arrkind > 0) { // reading array, can map array only afterwards obj = this.readFastArray(this.ntou4(), arrkind); this.mapObject(objtag, obj); } else { // reading normal object, should map before to obj = {}; this.mapObject(objtag, obj); this.classStreamer(obj, clRef.name); } return obj; } /** @summary Invoke streamer for specified class */ classStreamer(obj, classname) { if (obj._typename === undefined) obj._typename = classname; const direct = jsrio.DirectStreamers[classname]; if (direct) { direct(this, obj); return obj; } const ver = this.readVersion(); const streamer = this.fFile.getStreamer(classname, ver); if (streamer !== null) { const len = streamer.length; for (let n = 0; n < len; ++n) streamer[n].func(this, obj); } else { // just skip bytes belonging to not-recognized object // console.warn('skip object ', classname); JSROOT.addMethods(obj); } this.checkByteCount(ver, classname); return obj; } } // class TBuffer // ============================================================================== /** * @summary A class that reads a TDirectory from a buffer. * * @memberof JSROOT * @private */ class TDirectory { /** @summary constructor */ constructor(file, dirname, cycle) { this.fFile = file; this._typename = "TDirectory"; this.dir_name = dirname; this.dir_cycle = cycle; this.fKeys = []; } /** @summary retrieve a key by its name and cycle in the list of keys */ getKey(keyname, cycle, only_direct) { if (typeof cycle != 'number') cycle = -1; let bestkey = null; for (let i = 0; i < this.fKeys.length; ++i) { const key = this.fKeys[i]; if (!key || (key.fName!==keyname)) continue; if (key.fCycle == cycle) { bestkey = key; break; } if ((cycle < 0) && (!bestkey || (key.fCycle > bestkey.fCycle))) bestkey = key; } if (bestkey) return only_direct ? bestkey : Promise.resolve(bestkey); let pos = keyname.lastIndexOf("/"); // try to handle situation when object name contains slashed (bad practice anyway) while (pos > 0) { let dirname = keyname.substr(0, pos), subname = keyname.substr(pos+1), dirkey = this.getKey(dirname, undefined, true); if (dirkey && !only_direct && (dirkey.fClassName.indexOf("TDirectory")==0)) return this.fFile.readObject(this.dir_name + "/" + dirname, 1) .then(newdir => newdir.getKey(subname, cycle)); pos = keyname.lastIndexOf("/", pos-1); } return only_direct ? null : Promise.reject(Error("Key not found " + keyname)); } /** @summary Read object from the directory * @param {string} name - object name * @param {number} [cycle] - cycle number * @return {Promise} with read object */ readObject(obj_name, cycle) { return this.fFile.readObject(this.dir_name + "/" + obj_name, cycle); } /** @summary Read list of keys in directory */ readKeys(objbuf) { objbuf.classStreamer(this, 'TDirectory'); if ((this.fSeekKeys <= 0) || (this.fNbytesKeys <= 0)) return Promise.resolve(this); let file = this.fFile; return file.readBuffer([this.fSeekKeys, this.fNbytesKeys]).then(blob => { // Read keys of the top directory const buf = new TBuffer(blob, 0, file); buf.readTKey(); const nkeys = buf.ntoi4(); for (let i = 0; i < nkeys; ++i) this.fKeys.push(buf.readTKey()); file.fDirectories.push(this); return this; }); } } // TDirectory /** * @summary Interface to read objects from ROOT files * * @memberof JSROOT * @hideconstructor * @desc Use {@link JSROOT.openFile} to create instance of the class */ class TFile { constructor(url) { this._typename = "TFile"; this.fEND = 0; this.fFullURL = url; this.fURL = url; this.fAcceptRanges = true; // when disabled ('+' at the end of file name), complete file content read with single operation this.fUseStampPar = "stamp=" + (new Date).getTime(); // use additional time stamp parameter for file name to avoid browser caching problem this.fFileContent = null; // this can be full or partial content of the file (if ranges are not supported or if 1K header read from file) // stored as TBuffer instance this.fMaxRanges = 200; // maximal number of file ranges requested at once this.fDirectories = []; this.fKeys = []; this.fSeekInfo = 0; this.fNbytesInfo = 0; this.fTagOffset = 0; this.fStreamers = 0; this.fStreamerInfos = null; this.fFileName = ""; this.fStreamers = []; this.fBasicTypes = {}; // custom basic types, in most case enumerations if (typeof this.fURL != 'string') return this; if (this.fURL[this.fURL.length - 1] === "+") { this.fURL = this.fURL.substr(0, this.fURL.length - 1); this.fAcceptRanges = false; } if (this.fURL[this.fURL.length - 1] === "^") { this.fURL = this.fURL.substr(0, this.fURL.length - 1); this.fSkipHeadRequest = true; } if (this.fURL[this.fURL.length - 1] === "-") { this.fURL = this.fURL.substr(0, this.fURL.length - 1); this.fUseStampPar = false; } if (this.fURL.indexOf("file://") == 0) { this.fUseStampPar = false; this.fAcceptRanges = false; } const pos = Math.max(this.fURL.lastIndexOf("/"), this.fURL.lastIndexOf("\\")); this.fFileName = pos >= 0 ? this.fURL.substr(pos + 1) : this.fURL; } /** @summary Assign BufferArray with file contentOpen file * @private */ assignFileContent(bufArray) { this.fFileContent = new TBuffer(new DataView(bufArray)); this.fAcceptRanges = false; this.fUseStampPar = false; this.fEND = this.fFileContent.length; } /** @summary Open file * @returns {Promise} after file keys are read * @private */ _open() { if (!this.fAcceptRanges || this.fSkipHeadRequest) return this.readKeys(); return JSROOT.httpRequest(this.fURL, "head").then(res => { const accept_ranges = res.getResponseHeader("Accept-Ranges"); if (!accept_ranges) this.fAcceptRanges = false; const len = res.getResponseHeader("Content-Length"); if (len) this.fEND = parseInt(len); else this.fAcceptRanges = false; return this.readKeys(); }); } /** @summary read buffer(s) from the file * @returns {Promise} with read buffers * @private */ readBuffer(place, filename, progress_callback) { if ((this.fFileContent !== null) && !filename && (!this.fAcceptRanges || this.fFileContent.canExtract(place))) return Promise.resolve(this.fFileContent.extract(place)); let file = this, fileurl = file.fURL, resolveFunc, rejectFunc, promise = new Promise((resolve,reject) => { resolveFunc = resolve; rejectFunc = reject; }), first = 0, last = 0, blobs = [], read_callback; // array of requested segments if (filename && (typeof filename === 'string') && (filename.length > 0)) { const pos = fileurl.lastIndexOf("/"); fileurl = (pos < 0) ? filename : fileurl.substr(0, pos + 1) + filename; } function send_new_request(increment) { if (increment) { first = last; last = Math.min(first + file.fMaxRanges * 2, place.length); if (first >= place.length) return resolveFunc(blobs); } let fullurl = fileurl, ranges = "bytes", totalsz = 0; // try to avoid browser caching by adding stamp parameter to URL if (file.fUseStampPar) fullurl += ((fullurl.indexOf('?') < 0) ? "?" : "&") + file.fUseStampPar; for (let n = first; n < last; n += 2) { ranges += (n > first ? "," : "=") + (place[n] + "-" + (place[n] + place[n + 1] - 1)); totalsz += place[n + 1]; // accumulated total size } if (last - first > 2) totalsz += (last - first) * 60; // for multi-range ~100 bytes/per request let xhr = JSROOT.NewHttpRequest(fullurl, "buf", read_callback); if (file.fAcceptRanges) { xhr.setRequestHeader("Range", ranges); xhr.expected_size = Math.max(Math.round(1.1 * totalsz), totalsz + 200); // 200 if offset for the potential gzip } if (progress_callback && (typeof xhr.addEventListener === 'function')) { let sum1 = 0, sum2 = 0, sum_total = 0; for (let n = 1; n < place.length; n += 2) { sum_total += place[n]; if (n < first) sum1 += place[n]; if (n < last) sum2 += place[n]; } if (!sum_total) sum_total = 1; let progress_offest = sum1 / sum_total, progress_this = (sum2 - sum1) / sum_total; xhr.addEventListener("progress", function(oEvent) { if (oEvent.lengthComputable) progress_callback(progress_offest + progress_this * oEvent.loaded / oEvent.total); }); } xhr.send(null); } read_callback = function(res) { if (!res && file.fUseStampPar && (place[0] === 0) && (place.length === 2)) { // if fail to read file with stamp parameter, try once again without it file.fUseStampPar = false; return send_new_request(); } if (res && (place[0] === 0) && (place.length === 2) && !file.fFileContent) { // special case - keep content of first request (could be complete file) in memory file.fFileContent = new TBuffer((typeof res == 'string') ? res : new DataView(res)); if (!file.fAcceptRanges) file.fEND = file.fFileContent.length; return resolveFunc(file.fFileContent.extract(place)); } if (!res) { if ((first === 0) && (last > 2) && (file.fMaxRanges > 1)) { // server return no response with multi request - try to decrease ranges count or fail if (last / 2 > 200) file.fMaxRanges = 200; else if (last / 2 > 50) file.fMaxRanges = 50; else if (last / 2 > 20) file.fMaxRanges = 20; else if (last / 2 > 5) file.fMaxRanges = 5; else file.fMaxRanges = 1; last = Math.min(last, file.fMaxRanges * 2); // console.log('Change maxranges to ', file.fMaxRanges, 'last', last); return send_new_request(); } return rejectFunc(Error("Fail to read with several ranges")); } // if only single segment requested, return result as is if (last - first === 2) { let b = new DataView(res); if (place.length === 2) return resolveFunc(b); blobs.push(b); return send_new_request(true); } // object to access response data let hdr = this.getResponseHeader('Content-Type'), ismulti = (typeof hdr === 'string') && (hdr.indexOf('multipart') >= 0), view = new DataView(res); if (!ismulti) { // server may returns simple buffer, which combines all segments together let hdr_range = this.getResponseHeader('Content-Range'), segm_start = 0, segm_last = -1; if (hdr_range && hdr_range.indexOf("bytes") >= 0) { let parts = hdr_range.substr(hdr_range.indexOf("bytes") + 6).split(/[\s-\/]+/); if (parts.length === 3) { segm_start = parseInt(parts[0]); segm_last = parseInt(parts[1]); if (!Number.isInteger(segm_start) || !Number.isInteger(segm_last) || (segm_start > segm_last)) { segm_start = 0; segm_last = -1; } } } let canbe_single_segment = (segm_start <= segm_last); for (let n = first; n < last; n += 2) if ((place[n] < segm_start) || (place[n] + place[n + 1] - 1 > segm_last)) canbe_single_segment = false; if (canbe_single_segment) { for (let n = first; n < last; n += 2) blobs.push(new DataView(res, place[n] - segm_start, place[n + 1])); return send_new_request(true); } if ((file.fMaxRanges === 1) || (first !== 0)) return rejectFunc(Error('Server returns normal response when multipart was requested, disable multirange support')); file.fMaxRanges = 1; last = Math.min(last, file.fMaxRanges * 2); return send_new_request(); } // multipart messages requires special handling let indx = hdr.indexOf("boundary="), boundary = "", n = first, o = 0; if (indx > 0) { boundary = hdr.substr(indx + 9); if ((boundary[0] == '"') && (boundary[boundary.length - 1] == '"')) boundary = boundary.substr(1, boundary.length - 2); boundary = "--" + boundary; } else console.error('Did not found boundary id in the response header'); while (n < last) { let code1, code2 = view.getUint8(o), nline = 0, line = "", finish_header = false, segm_start = 0, segm_last = -1; while ((o < view.byteLength - 1) && !finish_header && (nline < 5)) { code1 = code2; code2 = view.getUint8(o + 1); if ((code1 == 13) && (code2 == 10)) { if ((line.length > 2) && (line.substr(0, 2) == '--') && (line !== boundary)) return rejectFunc(Error('Decode multipart message, expect boundary' + boundary + ' got ' + line)); line = line.toLowerCase(); if ((line.indexOf("content-range") >= 0) && (line.indexOf("bytes") > 0)) { let parts = line.substr(line.indexOf("bytes") + 6).split(/[\s-\/]+/); if (parts.length === 3) { segm_start = parseInt(parts[0]); segm_last = parseInt(parts[1]); if (!Number.isInteger(segm_start) || !Number.isInteger(segm_last) || (segm_start > segm_last)) { segm_start = 0; segm_last = -1; } } else { console.error('Fail to decode content-range', line, parts); } } if ((nline > 1) && (line.length === 0)) finish_header = true; o++; nline++; line = ""; code2 = view.getUint8(o + 1); } else { line += String.fromCharCode(code1); } o++; } if (!finish_header) return rejectFunc(Error('Cannot decode header in multipart message')); if (segm_start > segm_last) { // fall-back solution, believe that segments same as requested blobs.push(new DataView(res, o, place[n + 1])); o += place[n + 1]; n += 2; } else { while ((n < last) && (place[n] >= segm_start) && (place[n] + place[n + 1] - 1 <= segm_last)) { blobs.push(new DataView(res, o + place[n] - segm_start, place[n + 1])); n += 2; } o += (segm_last - segm_start + 1); } } send_new_request(true); } send_new_request(true); return promise; } /** @summary Returns file name */ getFileName() { return this.fFileName; } /** @summary Get directory with given name and cycle * @desc Function only can be used for already read directories, which are preserved in the memory * @private */ getDir(dirname, cycle) { if ((cycle === undefined) && (typeof dirname == 'string')) { const pos = dirname.lastIndexOf(';'); if (pos > 0) { cycle = parseInt(dirname.substr(pos + 1)); dirname = dirname.substr(0, pos); } } for (let j = 0; j < this.fDirectories.length; ++j) { const dir = this.fDirectories[j]; if (dir.dir_name != dirname) continue; if ((cycle !== undefined) && (dir.dir_cycle !== cycle)) continue; return dir; } return null; } /** @summary Retrieve a key by its name and cycle in the list of keys * @desc If only_direct not specified, returns Promise while key keys must be read first from the directory * @private */ getKey(keyname, cycle, only_direct) { if (typeof cycle != 'number') cycle = -1; let bestkey = null; for (let i = 0; i < this.fKeys.length; ++i) { const key = this.fKeys[i]; if (!key || (key.fName !== keyname)) continue; if (key.fCycle == cycle) { bestkey = key; break; } if ((cycle < 0) && (!bestkey || (key.fCycle > bestkey.fCycle))) bestkey = key; } if (bestkey) return only_direct ? bestkey : Promise.resolve(bestkey); let pos = keyname.lastIndexOf("/"); // try to handle situation when object name contains slashes (bad practice anyway) while (pos > 0) { let dirname = keyname.substr(0, pos), subname = keyname.substr(pos + 1), dir = this.getDir(dirname); if (dir) return dir.getKey(subname, cycle, only_direct); let dirkey = this.getKey(dirname, undefined, true); if (dirkey && !only_direct && (dirkey.fClassName.indexOf("TDirectory") == 0)) return this.readObject(dirname).then(newdir => newdir.getKey(subname, cycle)); pos = keyname.lastIndexOf("/", pos - 1); } return only_direct ? null : Promise.reject(Error("Key not found " + keyname)); } /** @summary Read and inflate object buffer described by its key * @private */ readObjBuffer(key) { return this.readBuffer([key.fSeekKey + key.fKeylen, key.fNbytes - key.fKeylen]).then(blob1 => { if (key.fObjlen <= key.fNbytes - key.fKeylen) { let buf = new TBuffer(blob1, 0, this); buf.fTagOffset = key.fKeylen; return buf; } return jsrio.R__unzip(blob1, key.fObjlen).then(objbuf => { if (!objbuf) return Promise.reject(Error("Fail to UNZIP buffer")); let buf = new TBuffer(objbuf, 0, this); buf.fTagOffset = key.fKeylen; return buf; }); }); } /** @summary Method called when TTree object is streamed * @private */ _addReadTree(obj) { if (jsrio.TTreeMethods) return JSROOT.extend(obj, jsrio.TTreeMethods); if (this.readTrees === undefined) this.readTrees = []; if (this.readTrees.indexOf(obj) < 0) this.readTrees.push(obj); } /** @summary Read any object from a root file * @desc One could specify cycle number in the object name or as separate argument * @param {string} obj_name - name of object, may include cycle number like "hpxpy;1" * @param {number} [cycle] - cycle number, also can be included in obj_name * @returns {Promise} promise with object read * @example * JSROOT.openFile("https://root.cern/js/files/hsimple.root") * .then(f => f.readObject("hpxpy;1")) * .then(obj => console.log(`Read object of type ${obj._typename}`)); */ readObject(obj_name, cycle, only_dir) { let pos = obj_name.lastIndexOf(";"); if (pos > 0) { cycle = parseInt(obj_name.slice(pos + 1)); obj_name = obj_name.slice(0, pos); } if (typeof cycle != 'number') cycle = -1; // remove leading slashes while (obj_name.length && (obj_name[0] == "/")) obj_name = obj_name.substr(1); let file = this, isdir, read_key; // one uses Promises while in some cases we need to // read sub-directory to get list of keys // in such situation calls are asynchrone return this.getKey(obj_name, cycle).then(key => { if ((obj_name == "StreamerInfo") && (key.fClassName == "TList")) return file.fStreamerInfos; if ((key.fClassName == 'TDirectory' || key.fClassName == 'TDirectoryFile')) { isdir = true; let dir = file.getDir(obj_name, cycle); if (dir) return dir; } if (!isdir && only_dir) return Promise.reject(Error(`Key ${obj_name} is not directory}`)); read_key = key; return file.readObjBuffer(key); }).then(buf => { if (isdir) { let dir = new TDirectory(file, obj_name, cycle); dir.fTitle = read_key.fTitle; return dir.readKeys(buf); } let obj = {}; buf.mapObject(1, obj); // tag object itself with id==1 buf.classStreamer(obj, read_key.fClassName); if ((read_key.fClassName === 'TF1') || (read_key.fClassName === 'TF2')) return file._readFormulas(obj); if (!file.readTrees) return obj; return JSROOT.require('tree').then(() => { if (file.readTrees) { file.readTrees.forEach(t => JSROOT.extend(t, jsrio.TTreeMethods)) delete file.readTrees; } return obj; }); }); } /** @summary read formulas from the file and add them to TF1/TF2 objects * @private */ _readFormulas(tf1) { let arr = []; for (let indx = 0; indx < this.fKeys.length; ++indx) if (this.fKeys[indx].fClassName == 'TFormula') arr.push(this.readObject(this.fKeys[indx].fName, this.fKeys[indx].fCycle)); return Promise.all(arr).then(formulas => { formulas.forEach(obj => tf1.addFormula(obj)); return tf1; }); } /** @summary extract streamer infos from the buffer * @private */ extractStreamerInfos(buf) { if (!buf) return; let lst = {}; buf.mapObject(1, lst); buf.classStreamer(lst, 'TList'); lst._typename = "TStreamerInfoList"; this.fStreamerInfos = lst; if (JSROOT.Painter && typeof JSROOT.Painter.addStreamerInfos === 'function') JSROOT.Painter.addStreamerInfos(lst); for (let k = 0; k < lst.arr.length; ++k) { let si = lst.arr[k]; if (!si.fElements) continue; for (let l = 0; l < si.fElements.arr.length; ++l) { let elem = si.fElements.arr[l]; if (!elem.fTypeName || !elem.fType) continue; let typ = elem.fType, typname = elem.fTypeName; if (typ >= 60) { if ((typ === kStreamer) && (elem._typename == "TStreamerSTL") && elem.fSTLtype && elem.fCtype && (elem.fCtype < 20)) { let prefix = (StlNames[elem.fSTLtype] || "undef") + "<"; if ((typname.indexOf(prefix) === 0) && (typname[typname.length - 1] == ">")) { typ = elem.fCtype; typname = typname.substr(prefix.length, typname.length - prefix.length - 1).trim(); if ((elem.fSTLtype === kSTLmap) || (elem.fSTLtype === kSTLmultimap)) if (typname.indexOf(",") > 0) typname = typname.substr(0, typname.indexOf(",")).trim(); else continue; } } if (typ >= 60) continue; } else { if ((typ > 20) && (typname[typname.length - 1] == "*")) typname = typname.substr(0, typname.length - 1); typ = typ % 20; } const kind = jsrio.GetTypeId(typname); if (kind === typ) continue; if ((typ === kBits) && (kind === kUInt)) continue; if ((typ === kCounter) && (kind === kInt)) continue; if (typname && typ && (this.fBasicTypes[typname] !== typ)) this.fBasicTypes[typname] = typ; } } } /** @summary Read file keys * @private */ readKeys() { let file = this; // with the first readbuffer we read bigger amount to create header cache return this.readBuffer([0, 1024]).then(blob => { let buf = new TBuffer(blob, 0, file); if (buf.substring(0, 4) !== 'root') return Promise.reject(Error(`Not a ROOT file ${file.fURL}`)); buf.shift(4); file.fVersion = buf.ntou4(); file.fBEGIN = buf.ntou4(); if (file.fVersion < 1000000) { //small file file.fEND = buf.ntou4(); file.fSeekFree = buf.ntou4(); file.fNbytesFree = buf.ntou4(); buf.shift(4); // const nfree = buf.ntoi4(); file.fNbytesName = buf.ntou4(); file.fUnits = buf.ntou1(); file.fCompress = buf.ntou4(); file.fSeekInfo = buf.ntou4(); file.fNbytesInfo = buf.ntou4(); } else { // new format to support large files file.fEND = buf.ntou8(); file.fSeekFree = buf.ntou8(); file.fNbytesFree = buf.ntou4(); buf.shift(4); // const nfree = buf.ntou4(); file.fNbytesName = buf.ntou4(); file.fUnits = buf.ntou1(); file.fCompress = buf.ntou4(); file.fSeekInfo = buf.ntou8(); file.fNbytesInfo = buf.ntou4(); } // empty file if (!file.fSeekInfo || !file.fNbytesInfo) return Promise.reject(Error(`File ${file.fURL} does not provide streamer infos`)); // extra check to prevent reading of corrupted data if (!file.fNbytesName || file.fNbytesName > 100000) return Promise.reject(Error(`Cannot read directory info of the file ${file.fURL}`)); //*-*-------------Read directory info let nbytes = file.fNbytesName + 22; nbytes += 4; // fDatimeC.Sizeof(); nbytes += 4; // fDatimeM.Sizeof(); nbytes += 18; // fUUID.Sizeof(); // assume that the file may be above 2 Gbytes if file version is > 4 if (file.fVersion >= 40000) nbytes += 12; // this part typically read from the header, no need to optimize return file.readBuffer([file.fBEGIN, Math.max(300, nbytes)]); }).then(blob3 => { let buf3 = new TBuffer(blob3, 0, file); // keep only title from TKey data file.fTitle = buf3.readTKey().fTitle; buf3.locate(file.fNbytesName); // we read TDirectory part of TFile buf3.classStreamer(file, 'TDirectory'); if (!file.fSeekKeys) return Promise.reject(Error(`Empty keys list in ${file.fURL}`)); // read with same request keys and streamer infos return file.readBuffer([file.fSeekKeys, file.fNbytesKeys, file.fSeekInfo, file.fNbytesInfo]); }).then(blobs => { const buf4 = new TBuffer(blobs[0], 0, file); buf4.readTKey(); // const nkeys = buf4.ntoi4(); for (let i = 0; i < nkeys; ++i) file.fKeys.push(buf4.readTKey()); const buf5 = new TBuffer(blobs[1], 0, file), si_key = buf5.readTKey(); if (!si_key) return Promise.reject(Error(`Fail to read StreamerInfo data in ${file.fURL}`)); file.fKeys.push(si_key); return file.readObjBuffer(si_key); }).then(blob6 => { file.extractStreamerInfos(blob6); return file; }); } /** @summary Read the directory content from a root file * @desc If directory was already read - return previously read object * Same functionality as {@link JSROOT.TFile.readObject} * @param {string} dir_name - directory name * @param {number} [cycle] - directory cycle * @returns {Promise} - promise with read directory */ readDirectory(dir_name, cycle) { return this.readObject(dir_name, cycle, true); } /** @summary Search streamer info * @param {string} clanme - class name * @param {number} [clversion] - class version * @param {number} [checksum] - streamer info checksum, have to match when specified * @private */ findStreamerInfo(clname, clversion, checksum) { if (!this.fStreamerInfos) return null; const arr = this.fStreamerInfos.arr, len = arr.length; if (checksum !== undefined) { let cache = this.fStreamerInfos.cache; if (!cache) cache = this.fStreamerInfos.cache = {}; let si = cache[checksum]; if (si !== undefined) return si; for (let i = 0; i < len; ++i) { si = arr[i]; if (si.fCheckSum === checksum) return cache[checksum] = si; } cache[checksum] = null; // checksum didnot found, do not try again } else { for (let i = 0; i < len; ++i) { let si = arr[i]; if ((si.fName === clname) && ((si.fClassVersion === clversion) || (clversion === undefined))) return si; } } return null; } /** @summary Returns streamer for the class 'clname', * @desc From the list of streamers or generate it from the streamer infos and add it to the list * @private */ getStreamer(clname, ver, s_i) { // these are special cases, which are handled separately if (clname == 'TQObject' || clname == "TBasket") return null; let streamer, fullname = clname; if (ver) { fullname += (ver.checksum ? ("$chksum" + ver.checksum) : ("$ver" + ver.val)); streamer = this.fStreamers[fullname]; if (streamer !== undefined) return streamer; } let custom = jsrio.CustomStreamers[clname]; // one can define in the user streamers just aliases if (typeof custom === 'string') return this.getStreamer(custom, ver, s_i); // streamer is just separate function if (typeof custom === 'function') { streamer = [{ typename: clname, func: custom }]; return addClassMethods(clname, streamer); } streamer = []; if (typeof custom === 'object') { if (!custom.name && !custom.func) return custom; streamer.push(custom); // special read entry, add in the beginning of streamer } // check element in streamer infos, one can have special cases if (!s_i) s_i = this.findStreamerInfo(clname, ver.val, ver.checksum); if (!s_i) { delete this.fStreamers[fullname]; if (!ver.nowarning) console.warn(`Not found streamer for ${clname} ver ${ver.val} checksum ${ver.checksum} full ${fullname}`); return null; } // special handling for TStyle which has duplicated member name fLineStyle if ((s_i.fName == "TStyle") && s_i.fElements) s_i.fElements.arr.forEach(elem => { if (elem.fName == "fLineStyle") elem.fName = "fLineStyles"; // like in ROOT JSON now }); // for each entry in streamer info produce member function if (s_i.fElements) for (let j = 0; j < s_i.fElements.arr.length; ++j) streamer.push(jsrio.createMember(s_i.fElements.arr[j], this)); this.fStreamers[fullname] = streamer; return addClassMethods(clname, streamer); } /** @summary Here we produce list of members, resolving all base classes * @private */ getSplittedStreamer(streamer, tgt) { if (!streamer) return tgt; if (!tgt) tgt = []; for (let n = 0; n < streamer.length; ++n) { let elem = streamer[n]; if (elem.base === undefined) { tgt.push(elem); continue; } if (elem.basename == clTObject) { tgt.push({ func: function(buf, obj) { buf.ntoi2(); // read version, why it here?? obj.fUniqueID = buf.ntou4(); obj.fBits = buf.ntou4(); if (obj.fBits & kIsReferenced) buf.ntou2(); // skip pid } }); continue; } let ver = { val: elem.base }; if (ver.val === 4294967295) { // this is -1 and indicates foreign class, need more workarounds ver.val = 1; // need to search version 1 - that happens when several versions of foreign class exists ??? } let parent = this.getStreamer(elem.basename, ver); if (parent) this.getSplittedStreamer(parent, tgt); } return tgt; } /** @summary Fully clenaup TFile data * @private */ delete() { this.fDirectories = null; this.fKeys = null; this.fStreamers = null; this.fSeekInfo = 0; this.fNbytesInfo = 0; this.fTagOffset = 0; } } // TFile // ======================================================================= /** @summary Reconstruct ROOT object from binary buffer * @desc Method can be used to reconstruct ROOT objects from binary buffer * which can be requested from running THttpServer, using **root.bin** request * To decode data, one has to request streamer infos data __after__ object data * as it shown in example. * * Method provided for convenience only to see how binary IO works. * It is strongly recommended to use **root.json** request to get data directly in * JSON format * * @param {string} class_name - Class name of the object * @param {binary} obj_rawdata - data of object root.bin request * @param {binary} sinfo_rawdata - data of streamer info root.bin request * @returns {object} - created JavaScript object * @example * async function read_binary_and_draw() { * await JSROOT.require("io"); * let obj_data = await JSROOT.httpRequest("http://localhost:8080/Files/job1.root/hpx/root.bin", "buf"); * let si_data = await JSROOT.httpRequest("http://localhost:8080/StreamerInfo/root.bin", "buf"); * let histo = await JSROOT.reconstructObject("TH1F", obj_data, si_data); * console.log(`Get histogram with title = ${histo.fTitle}`); * } * read_binary_and_draw(); * * // request same data via root.json request * JSROOT.httpRequest("http://localhost:8080/Files/job1.root/hpx/root.json", "object") * .then(histo => console.log(`Get histogram with title = ${histo.fTitle}`)); */ JSROOT.reconstructObject = function(class_name, obj_rawdata, sinfo_rawdata) { let file = new TFile; let buf = new TBuffer(sinfo_rawdata, 0, file); file.extractStreamerInfos(buf); let obj = {}; buf = new TBuffer(obj_rawdata, 0, file); buf.mapObject(obj, 1); buf.classStreamer(obj, class_name); return obj; } /** @summary Function to read vector element in the streamer * @private */ function readVectorElement(buf) { if (this.member_wise) { const n = buf.ntou4(); let streamer = null, ver = this.stl_version; if (n === 0) return []; // for empty vector no need to search split streamers if (n > 1000000) { throw new Error('member-wise streaming of ' + this.conttype + " num " + n + ' member ' + this.name); // return []; } if ((ver.val === this.member_ver) && (ver.checksum === this.member_checksum)) { streamer = this.member_streamer; } else { streamer = buf.fFile.getStreamer(this.conttype, ver); this.member_streamer = streamer = buf.fFile.getSplittedStreamer(streamer); this.member_ver = ver.val; this.member_checksum = ver.checksum; } let res = new Array(n), i, k, member; for (i = 0; i < n; ++i) res[i] = { _typename: this.conttype }; // create objects if (!streamer) { console.error('Fail to create split streamer for', this.conttype, 'need to read ', n, 'objects version', ver); } else { for (k = 0; k < streamer.length; ++k) { member = streamer[k]; if (member.split_func) { member.split_func(buf, res, n); } else { for (i = 0; i < n; ++i) member.func(buf, res[i]); } } } return res; } const n = buf.ntou4(); let res = new Array(n), i = 0; if (n > 200000) { console.error('vector streaming for of', this.conttype, n); return res; } if (this.arrkind > 0) { while (i < n) res[i++] = buf.readFastArray(buf.ntou4(), this.arrkind); } else if (this.arrkind === 0) { while (i < n) res[i++] = buf.readTString(); } else if (this.isptr) { while (i < n) res[i++] = buf.readObjectAny(); } else if (this.submember) { while (i < n) res[i++] = this.submember.readelem(buf); } else { while (i < n) res[i++] = buf.classStreamer({}, this.conttype); } return res; } /** @summary Function creates streamer for std::pair object * @private */ function getPairStreamer(si, typname, file) { if (!si) { if (typname.indexOf("pair") !== 0) return null; si = file.findStreamerInfo(typname); if (!si) { let p1 = typname.indexOf("<"), p2 = typname.lastIndexOf(">"); function GetNextName() { let res = "", p = p1 + 1, cnt = 0; while ((p < p2) && (cnt >= 0)) { switch (typname[p]) { case "<": cnt++; break; case ",": if (cnt === 0) cnt--; break; case ">": cnt--; break; } if (cnt >= 0) res += typname[p]; p++; } p1 = p - 1; return res.trim(); } si = { _typename: 'TStreamerInfo', fVersion: 1, fName: typname, fElements: JSROOT.create("TList") }; si.fElements.Add(jsrio.createStreamerElement("first", GetNextName(), file)); si.fElements.Add(jsrio.createStreamerElement("second", GetNextName(), file)); } } let streamer = file.getStreamer(typname, null, si); if (!streamer) return null; if (streamer.length !== 2) { console.error(`Streamer for pair class contains ${streamer.length} elements`); return null; } for (let nn = 0; nn < 2; ++nn) if (streamer[nn].readelem && !streamer[nn].pair_name) { streamer[nn].pair_name = (nn == 0) ? "first" : "second"; streamer[nn].func = function(buf, obj) { obj[this.pair_name] = this.readelem(buf); }; } return streamer; } /** @summary Function used in streamer to read std::map object * @private */ function readMapElement(buf) { let streamer = this.streamer; if (this.member_wise) { // when member-wise streaming is used, version is written const ver = this.stl_version; if (this.si) { let si = buf.fFile.findStreamerInfo(this.pairtype, ver.val, ver.checksum); if (this.si !== si) { streamer = getPairStreamer(si, this.pairtype, buf.fFile); if (!streamer || streamer.length !== 2) { console.log('Fail to produce streamer for ', this.pairtype); return null; } } } } const n = buf.ntoi4(); let i, res = new Array(n); if (this.member_wise && (buf.remain() >= 6)) { if (buf.ntoi2() == kStreamedMemberWise) buf.shift(4); else buf.shift(-2); // rewind } for (i = 0; i < n; ++i) { res[i] = { _typename: this.pairtype }; streamer[0].func(buf, res[i]); if (!this.member_wise) streamer[1].func(buf, res[i]); } // due-to member-wise streaming second element read after first is completed if (this.member_wise) for (i = 0; i < n; ++i) streamer[1].func(buf, res[i]); return res; } /** @summary create member entry for streamer element * @desc used for reading of data * @private */ jsrio.createMember = function(element, file) { let member = { name: element.fName, type: element.fType, fArrayLength: element.fArrayLength, fArrayDim: element.fArrayDim, fMaxIndex: element.fMaxIndex }; if (element.fTypeName === 'BASE') { if (getArrayKind(member.name) > 0) { // this is workaround for arrays as base class // we create 'fArray' member, which read as any other data member member.name = 'fArray'; member.type = kAny; } else { // create streamer for base class member.type = kBase; // this.getStreamer(element.fName); } } switch (member.type) { case kBase: member.base = element.fBaseVersion; // indicate base class member.basename = element.fName; // keep class name member.func = function(buf, obj) { buf.classStreamer(obj, this.basename); }; break; case kShort: member.func = function(buf, obj) { obj[this.name] = buf.ntoi2(); }; break; case kInt: case kCounter: member.func = function(buf, obj) { obj[this.name] = buf.ntoi4(); }; break; case kLong: case kLong64: member.func = function(buf, obj) { obj[this.name] = buf.ntoi8(); }; break; case kDouble: member.func = function(buf, obj) { obj[this.name] = buf.ntod(); }; break; case kFloat: member.func = function(buf, obj) { obj[this.name] = buf.ntof(); }; break; case kLegacyChar: case kUChar: member.func = function(buf, obj) { obj[this.name] = buf.ntou1(); }; break; case kUShort: member.func = function(buf, obj) { obj[this.name] = buf.ntou2(); }; break; case kBits: case kUInt: member.func = function(buf, obj) { obj[this.name] = buf.ntou4(); }; break; case kULong64: case kULong: member.func = function(buf, obj) { obj[this.name] = buf.ntou8(); }; break; case kBool: member.func = function(buf, obj) { obj[this.name] = buf.ntou1() != 0; }; break; case kOffsetL + kBool: case kOffsetL + kInt: case kOffsetL + kCounter: case kOffsetL + kDouble: case kOffsetL + kUChar: case kOffsetL + kShort: case kOffsetL + kUShort: case kOffsetL + kBits: case kOffsetL + kUInt: case kOffsetL + kULong: case kOffsetL + kULong64: case kOffsetL + kLong: case kOffsetL + kLong64: case kOffsetL + kFloat: if (element.fArrayDim < 2) { member.arrlength = element.fArrayLength; member.func = function(buf, obj) { obj[this.name] = buf.readFastArray(this.arrlength, this.type - kOffsetL); }; } else { member.arrlength = element.fMaxIndex[element.fArrayDim - 1]; member.minus1 = true; member.func = function(buf, obj) { obj[this.name] = buf.readNdimArray(this, (buf, handle) => buf.readFastArray(handle.arrlength, handle.type - kOffsetL)); }; } break; case kOffsetL + kChar: if (element.fArrayDim < 2) { member.arrlength = element.fArrayLength; member.func = function(buf, obj) { obj[this.name] = buf.readFastString(this.arrlength); }; } else { member.minus1 = true; // one dimension used for char* member.arrlength = element.fMaxIndex[element.fArrayDim - 1]; member.func = function(buf, obj) { obj[this.name] = buf.readNdimArray(this, (buf, handle) => buf.readFastString(handle.arrlength)); }; } break; case kOffsetP + kBool: case kOffsetP + kInt: case kOffsetP + kDouble: case kOffsetP + kUChar: case kOffsetP + kShort: case kOffsetP + kUShort: case kOffsetP + kBits: case kOffsetP + kUInt: case kOffsetP + kULong: case kOffsetP + kULong64: case kOffsetP + kLong: case kOffsetP + kLong64: case kOffsetP + kFloat: member.cntname = element.fCountName; member.func = function(buf, obj) { if (buf.ntou1() === 1) obj[this.name] = buf.readFastArray(obj[this.cntname], this.type - kOffsetP); else obj[this.name] = []; }; break; case kOffsetP + kChar: member.cntname = element.fCountName; member.func = function(buf, obj) { if (buf.ntou1() === 1) obj[this.name] = buf.readFastString(obj[this.cntname]); else obj[this.name] = null; }; break; case kDouble32: case kOffsetL + kDouble32: case kOffsetP + kDouble32: member.double32 = true; case kFloat16: case kOffsetL + kFloat16: case kOffsetP + kFloat16: if (element.fFactor !== 0) { member.factor = 1. / element.fFactor; member.min = element.fXmin; member.read = function(buf) { return buf.ntou4() * this.factor + this.min; }; } else if ((element.fXmin === 0) && member.double32) { member.read = function(buf) { return buf.ntof(); }; } else { member.nbits = Math.round(element.fXmin); if (member.nbits === 0) member.nbits = 12; member.dv = new DataView(new ArrayBuffer(8), 0); // used to cast from uint32 to float32 member.read = function(buf) { let theExp = buf.ntou1(), theMan = buf.ntou2(); this.dv.setUint32(0, (theExp << 23) | ((theMan & ((1 << (this.nbits + 1)) - 1)) << (23 - this.nbits))); return ((1 << (this.nbits + 1) & theMan) ? -1 : 1) * this.dv.getFloat32(0); }; } member.readarr = function(buf, len) { let arr = this.double32 ? new Float64Array(len) : new Float32Array(len); for (let n = 0; n < len; ++n) arr[n] = this.read(buf); return arr; } if (member.type < kOffsetL) { member.func = function(buf, obj) { obj[this.name] = this.read(buf); } } else if (member.type > kOffsetP) { member.cntname = element.fCountName; member.func = function(buf, obj) { if (buf.ntou1() === 1) { obj[this.name] = this.readarr(buf, obj[this.cntname]); } else { obj[this.name] = null; } }; } else if (element.fArrayDim < 2) { member.arrlength = element.fArrayLength; member.func = function(buf, obj) { obj[this.name] = this.readarr(buf, this.arrlength); }; } else { member.arrlength = element.fMaxIndex[element.fArrayDim - 1]; member.minus1 = true; member.func = function(buf, obj) { obj[this.name] = buf.readNdimArray(this, (buf, handle) => handle.readarr(buf, handle.arrlength)); }; } break; case kAnyP: case kObjectP: member.func = function(buf, obj) { obj[this.name] = buf.readNdimArray(this, buf => buf.readObjectAny()); }; break; case kAny: case kAnyp: case kObjectp: case kObject: { let classname = (element.fTypeName === 'BASE') ? element.fName : element.fTypeName; if (classname[classname.length - 1] == "*") classname = classname.substr(0, classname.length - 1); const arrkind = getArrayKind(classname); if (arrkind > 0) { member.arrkind = arrkind; member.func = function(buf, obj) { obj[this.name] = buf.readFastArray(buf.ntou4(), this.arrkind); }; } else if (arrkind === 0) { member.func = function(buf, obj) { obj[this.name] = buf.readTString(); }; } else { member.classname = classname; if (element.fArrayLength > 1) { member.func = function(buf, obj) { obj[this.name] = buf.readNdimArray(this, (buf, handle) => buf.classStreamer({}, handle.classname)); }; } else { member.func = function(buf, obj) { obj[this.name] = buf.classStreamer({}, this.classname); }; } } break; } case kOffsetL + kObject: case kOffsetL + kAny: case kOffsetL + kAnyp: case kOffsetL + kObjectp: { let classname = element.fTypeName; if (classname[classname.length - 1] == "*") classname = classname.substr(0, classname.length - 1); member.arrkind = getArrayKind(classname); if (member.arrkind < 0) member.classname = classname; member.func = function(buf, obj) { obj[this.name] = buf.readNdimArray(this, (buf, handle) => { if (handle.arrkind > 0) return buf.readFastArray(buf.ntou4(), handle.arrkind); if (handle.arrkind === 0) return buf.readTString(); return buf.classStreamer({}, handle.classname); }); } break; } case kChar: member.func = function(buf, obj) { obj[this.name] = buf.ntoi1(); }; break; case kCharStar: member.func = function(buf, obj) { const len = buf.ntoi4(); obj[this.name] = buf.substring(buf.o, buf.o + len); buf.o += len; }; break; case kTString: member.func = function(buf, obj) { obj[this.name] = buf.readTString(); }; break; case kTObject: case kTNamed: member.typename = element.fTypeName; member.func = function(buf, obj) { obj[this.name] = buf.classStreamer({}, this.typename); }; break; case kOffsetL + kTString: case kOffsetL + kTObject: case kOffsetL + kTNamed: member.typename = element.fTypeName; member.func = function(buf, obj) { const ver = buf.readVersion(); obj[this.name] = buf.readNdimArray(this, (buf, handle) => { if (handle.typename === 'TString') return buf.readTString(); return buf.classStreamer({}, handle.typename); }); buf.checkByteCount(ver, this.typename + "[]"); }; break; case kStreamLoop: case kOffsetL + kStreamLoop: member.typename = element.fTypeName; member.cntname = element.fCountName; if (member.typename.lastIndexOf("**") > 0) { member.typename = member.typename.substr(0, member.typename.lastIndexOf("**")); member.isptrptr = true; } else { member.typename = member.typename.substr(0, member.typename.lastIndexOf("*")); member.isptrptr = false; } if (member.isptrptr) { member.readitem = function(buf) { return buf.readObjectAny(); } } else { member.arrkind = getArrayKind(member.typename); if (member.arrkind > 0) member.readitem = function(buf) { return buf.readFastArray(buf.ntou4(), this.arrkind); } else if (member.arrkind === 0) member.readitem = function(buf) { return buf.readTString(); } else member.readitem = function(buf) { return buf.classStreamer({}, this.typename); } } if (member.readitem !== undefined) { member.read_loop = function(buf, cnt) { return buf.readNdimArray(this, (buf2, member2) => { let itemarr = new Array(cnt); for (let i = 0; i < cnt; ++i) itemarr[i] = member2.readitem(buf2); return itemarr; }); } member.func = function(buf, obj) { const ver = buf.readVersion(); let res = this.read_loop(buf, obj[this.cntname]); if (!buf.checkByteCount(ver, this.typename)) res = null; obj[this.name] = res; } member.branch_func = function(buf, obj) { // this is special functions, used by branch in the STL container const ver = buf.readVersion(), sz0 = obj[this.stl_size]; let res = new Array(sz0); for (let loop0 = 0; loop0 < sz0; ++loop0) { let cnt = obj[this.cntname][loop0]; res[loop0] = this.read_loop(buf, cnt); } if (!buf.checkByteCount(ver, this.typename)) res = null; obj[this.name] = res; } member.objs_branch_func = function(buf, obj) { // special function when branch read as part of complete object // objects already preallocated and only appropriate member must be set // see code in JSRoot.tree.js for reference const ver = buf.readVersion(); let arr = obj[this.name0]; // objects array where reading is done for (let loop0 = 0; loop0 < arr.length; ++loop0) { let obj1 = this.get(arr, loop0), cnt = obj1[this.cntname]; obj1[this.name] = this.read_loop(buf, cnt); } buf.checkByteCount(ver, this.typename); } } else { console.error(`fail to provide function for ${element.fName} (${element.fTypeName}) typ = ${element.fType}`); member.func = function(buf, obj) { const ver = buf.readVersion(); buf.checkByteCount(ver); obj[this.name] = ull; }; } break; case kStreamer: { member.typename = element.fTypeName; let stl = (element.fSTLtype || 0) % 40; if ((element._typename === 'TStreamerSTLstring') || (member.typename == "string") || (member.typename == "string*")) { member.readelem = buf => buf.readTString(); } else if ((stl === kSTLvector) || (stl === kSTLlist) || (stl === kSTLdeque) || (stl === kSTLset) || (stl === kSTLmultiset)) { let p1 = member.typename.indexOf("<"), p2 = member.typename.lastIndexOf(">"); member.conttype = member.typename.substr(p1 + 1, p2 - p1 - 1).trim(); member.typeid = jsrio.GetTypeId(member.conttype); if ((member.typeid < 0) && file.fBasicTypes[member.conttype]) { member.typeid = file.fBasicTypes[member.conttype]; console.log('!!! Reuse basic type', member.conttype, 'from file streamer infos'); } // check if (element.fCtype && (element.fCtype < 20) && (element.fCtype !== member.typeid)) { console.warn('Contained type', member.conttype, 'not recognized as basic type', element.fCtype, 'FORCE'); member.typeid = element.fCtype; } if (member.typeid > 0) { member.readelem = function(buf) { return buf.readFastArray(buf.ntoi4(), this.typeid); }; } else { member.isptr = false; if (member.conttype.lastIndexOf("*") === member.conttype.length - 1) { member.isptr = true; member.conttype = member.conttype.substr(0, member.conttype.length - 1); } if (element.fCtype === kObjectp) member.isptr = true; member.arrkind = getArrayKind(member.conttype); member.readelem = readVectorElement; if (!member.isptr && (member.arrkind < 0)) { let subelem = jsrio.createStreamerElement("temp", member.conttype); if (subelem.fType === kStreamer) { subelem.$fictional = true; member.submember = jsrio.createMember(subelem, file); } } } } else if ((stl === kSTLmap) || (stl === kSTLmultimap)) { const p1 = member.typename.indexOf("<"), p2 = member.typename.lastIndexOf(">"); member.pairtype = "pair<" + member.typename.substr(p1 + 1, p2 - p1 - 1) + ">"; // remember found streamer info from the file - // most probably it is the only one which should be used member.si = file.findStreamerInfo(member.pairtype); member.streamer = getPairStreamer(member.si, member.pairtype, file); if (!member.streamer || (member.streamer.length !== 2)) { console.error(`Fail to build streamer for pair ${member.pairtype}`); delete member.streamer; } if (member.streamer) member.readelem = readMapElement; } else if (stl === kSTLbitset) { member.readelem = (buf/*, obj*/) => buf.readFastArray(buf.ntou4(), kBool); } if (!member.readelem) { console.error(`'failed to create streamer for element ${member.typename} ${member.name} element ${element._typename} STL type ${element.fSTLtype}`); member.func = function(buf, obj) { const ver = buf.readVersion(); buf.checkByteCount(ver); obj[this.name] = null; } } else if (!element.$fictional) { member.read_version = function(buf, cnt) { if (cnt === 0) return null; const ver = buf.readVersion(); this.member_wise = ((ver.val & kStreamedMemberWise) !== 0); this.stl_version = undefined; if (this.member_wise) { ver.val = ver.val & ~kStreamedMemberWise; this.stl_version = { val: buf.ntoi2() }; if (this.stl_version.val <= 0) this.stl_version.checksum = buf.ntou4(); } return ver; } member.func = function(buf, obj) { const ver = this.read_version(buf); let res = buf.readNdimArray(this, (buf2, member2) => member2.readelem(buf2)); if (!buf.checkByteCount(ver, this.typename)) res = null; obj[this.name] = res; } member.branch_func = function(buf, obj) { // special function to read data from STL branch const cnt = obj[this.stl_size], ver = this.read_version(buf, cnt); let arr = new Array(cnt); for (let n = 0; n < cnt; ++n) arr[n] = buf.readNdimArray(this, (buf2, member2) => member2.readelem(buf2)); if (ver) buf.checkByteCount(ver, "branch " + this.typename); obj[this.name] = arr; } member.split_func = function(buf, arr, n) { // function to read array from member-wise streaming const ver = this.read_version(buf); for (let i = 0; i < n; ++i) arr[i][this.name] = buf.readNdimArray(this, (buf2, member2) => member2.readelem(buf2)); buf.checkByteCount(ver, this.typename); } member.objs_branch_func = function(buf, obj) { // special function when branch read as part of complete object // objects already preallocated and only appropriate member must be set // see code in JSRoot.tree.js for reference let arr = obj[this.name0]; // objects array where reading is done const ver = this.read_version(buf, arr.length); for (let n = 0; n < arr.length; ++n) { let obj1 = this.get(arr, n); obj1[this.name] = buf.readNdimArray(this, (buf2, member2) => member2.readelem(buf2)); } if (ver) buf.checkByteCount(ver, "branch " + this.typename); } } break; } default: console.error(`fail to provide function for ${element.fName} (${element.fTypeName}) typ = ${element.fType}`); member.func = function(/*buf, obj*/) { }; // do nothing, fix in the future } return member; } // ============================================================= /** * @summary Interface to read local file in the browser * * @memberof JSROOT * @hideconstructor * @desc Use {@link JSROOT.openFile} to create instance of the class * @private */ class TLocalFile extends TFile { constructor(file) { super(null); this.fUseStampPar = false; this.fLocalFile = file; this.fEND = file.size; this.fFullURL = file.name; this.fURL = file.name; this.fFileName = file.name; } /** @summary Open local file * @returns {Promise} after file keys are read */ _open() { return this.readKeys(); } /** @summary read buffer from local file */ readBuffer(place, filename /*, progress_callback */) { let file = this.fLocalFile; return new Promise((resolve, reject) => { if (filename) return reject(Error(`Cannot access other local file ${filename}`)); let reader = new FileReader(), cnt = 0, blobs = []; reader.onload = function(evnt) { let res = new DataView(evnt.target.result); if (place.length === 2) return resolve(res); blobs.push(res); cnt += 2; if (cnt >= place.length) return resolve(blobs); reader.readAsArrayBuffer(file.slice(place[cnt], place[cnt] + place[cnt + 1])); } reader.readAsArrayBuffer(file.slice(place[0], place[0] + place[1])); }); } } // TLocalFile // ============================================================= /** * @summary Interface to read file in node.js * * @memberof JSROOT * @hideconstructor * @desc Use {@link JSROOT.openFile} to create instance of the class * @private */ class TNodejsFile extends TFile { constructor(filename) { super(null); this.fUseStampPar = false; this.fEND = 0; this.fFullURL = filename; this.fURL = filename; this.fFileName = filename; } /** @summary Open file in node.js * @returns {Promise} after file keys are read */ _open() { this.fs = require('fs'); return new Promise((resolve,reject) => this.fs.open(this.fFileName, 'r', (status, fd) => { if (status) { console.log(status.message); return reject(Error(`Not possible to open ${this.fFileName} inside node.js`)); } let stats = this.fs.fstatSync(fd); this.fEND = stats.size; this.fd = fd; this.readKeys().then(resolve).catch(reject); }) ); } /** @summary Read buffer from node.js file * @returns {Promise} with requested blocks */ readBuffer(place, filename /*, progress_callback */) { return new Promise((resolve, reject) => { if (filename) return reject(Error(`Cannot access other local file ${filename}`)); if (!this.fs || !this.fd) return reject(Error(`File is not opened ${this.fFileName}`)); let cnt = 0, blobs = []; let readfunc = (err, bytesRead, buf) => { let res = new DataView(buf.buffer, buf.byteOffset, place[cnt + 1]); if (place.length === 2) return resolve(res); blobs.push(res); cnt += 2; if (cnt >= place.length) return resolve(blobs); this.fs.read(this.fd, Buffer.alloc(place[cnt + 1]), 0, place[cnt + 1], place[cnt], readfunc); } this.fs.read(this.fd, Buffer.alloc(place[1]), 0, place[1], place[0], readfunc); }); } } // TNodejsFile /** @summary Add custom streamers for basic ROOT classes * @private */ function produceCustomStreamers() { let cs = jsrio.CustomStreamers; cs[clTObject] = cs['TMethodCall'] = function(buf, obj) { obj.fUniqueID = buf.ntou4(); obj.fBits = buf.ntou4(); if (obj.fBits & kIsReferenced) buf.ntou2(); // skip pid }; cs[clTNamed] = [ { basename: clTObject, base: 1, func: function(buf, obj) { if (!obj._typename) obj._typename = clTNamed; buf.classStreamer(obj, clTObject); } }, { name: 'fName', func: function(buf, obj) { obj.fName = buf.readTString(); } }, { name: 'fTitle', func: function(buf, obj) { obj.fTitle = buf.readTString(); } } ]; addClassMethods(clTNamed, cs[clTNamed]); cs.TObjString = [ { basename: clTObject, base: 1, func: (buf, obj) => { if (!obj._typename) obj._typename = 'TObjString'; buf.classStreamer(obj, clTObject); } }, { name: 'fString', func: (buf, obj) => { obj.fString = buf.readTString(); } } ]; addClassMethods('TObjString', cs['TObjString']); cs.TList = cs.THashList = function(buf, obj) { // stream all objects in the list from the I/O buffer if (!obj._typename) obj._typename = this.typename; obj.$kind = "TList"; // all derived classes will be marked as well if (buf.last_read_version > 3) { buf.classStreamer(obj, clTObject); obj.name = buf.readTString(); const nobjects = buf.ntou4(); obj.arr = new Array(nobjects); obj.opt = new Array(nobjects); for (let i = 0; i < nobjects; ++i) { obj.arr[i] = buf.readObjectAny(); obj.opt[i] = buf.readTString(); } } else { obj.name = ""; obj.arr = []; obj.opt = []; } } cs.TClonesArray = (buf, list) => { if (!list._typename) list._typename = "TClonesArray"; list.$kind = "TClonesArray"; list.name = ""; const ver = buf.last_read_version; if (ver > 2) buf.classStreamer(list, clTObject); if (ver > 1) list.name = buf.readTString(); let classv = buf.readTString(), clv = 0, pos = classv.lastIndexOf(";"); if (pos > 0) { clv = parseInt(classv.substr(pos + 1)); classv = classv.substr(0, pos); } let nobjects = buf.ntou4(); if (nobjects < 0) nobjects = -nobjects; // for backward compatibility list.arr = new Array(nobjects); list.fLast = nobjects - 1; list.fLowerBound = buf.ntou4(); let streamer = buf.fFile.getStreamer(classv, { val: clv }); streamer = buf.fFile.getSplittedStreamer(streamer); if (!streamer) { console.log('Cannot get member-wise streamer for', classv, clv); } else { // create objects for (let n = 0; n < nobjects; ++n) list.arr[n] = { _typename: classv }; // call streamer for all objects member-wise for (let k = 0; k < streamer.length; ++k) for (let n = 0; n < nobjects; ++n) streamer[k].func(buf, list.arr[n]); } } cs.TMap = (buf, map) => { if (!map._typename) map._typename = "TMap"; map.name = ""; map.arr = []; const ver = buf.last_read_version; if (ver > 2) buf.classStreamer(map, clTObject); if (ver > 1) map.name = buf.readTString(); const nobjects = buf.ntou4(); // create objects for (let n = 0; n < nobjects; ++n) { let obj = { _typename: "TPair" }; obj.first = buf.readObjectAny(); obj.second = buf.readObjectAny(); if (obj.first) map.arr.push(obj); } } cs.TTreeIndex = (buf, obj) => { const ver = buf.last_read_version; obj._typename = "TTreeIndex"; buf.classStreamer(obj, "TVirtualIndex"); obj.fMajorName = buf.readTString(); obj.fMinorName = buf.readTString(); obj.fN = buf.ntoi8(); obj.fIndexValues = buf.readFastArray(obj.fN, kLong64); if (ver > 1) obj.fIndexValuesMinor = buf.readFastArray(obj.fN, kLong64); obj.fIndex = buf.readFastArray(obj.fN, kLong64); } cs.TRefArray = (buf, obj) => { obj._typename = "TRefArray"; buf.classStreamer(obj, clTObject); obj.name = buf.readTString(); const nobj = buf.ntoi4(); obj.fLast = nobj - 1; obj.fLowerBound = buf.ntoi4(); /*const pidf = */ buf.ntou2(); obj.fUIDs = buf.readFastArray(nobj, kUInt); } cs.TCanvas = (buf, obj) => { obj._typename = "TCanvas"; buf.classStreamer(obj, "TPad"); obj.fDISPLAY = buf.readTString(); obj.fDoubleBuffer = buf.ntoi4(); obj.fRetained = (buf.ntou1() !== 0); obj.fXsizeUser = buf.ntoi4(); obj.fYsizeUser = buf.ntoi4(); obj.fXsizeReal = buf.ntoi4(); obj.fYsizeReal = buf.ntoi4(); obj.fWindowTopX = buf.ntoi4(); obj.fWindowTopY = buf.ntoi4(); obj.fWindowWidth = buf.ntoi4(); obj.fWindowHeight = buf.ntoi4(); obj.fCw = buf.ntou4(); obj.fCh = buf.ntou4(); obj.fCatt = buf.classStreamer({}, "TAttCanvas"); buf.ntou1(); // ignore b << TestBit(kMoveOpaque); buf.ntou1(); // ignore b << TestBit(kResizeOpaque); obj.fHighLightColor = buf.ntoi2(); obj.fBatch = (buf.ntou1() !== 0); buf.ntou1(); // ignore b << TestBit(kShowEventStatus); buf.ntou1(); // ignore b << TestBit(kAutoExec); buf.ntou1(); // ignore b << TestBit(kMenuBar); } cs.TObjArray = (buf, list) => { if (!list._typename) list._typename = "TObjArray"; list.$kind = "TObjArray"; list.name = ""; const ver = buf.last_read_version; if (ver > 2) buf.classStreamer(list, clTObject); if (ver > 1) list.name = buf.readTString(); const nobjects = buf.ntou4(); let i = 0; list.arr = new Array(nobjects); list.fLast = nobjects - 1; list.fLowerBound = buf.ntou4(); while (i < nobjects) list.arr[i++] = buf.readObjectAny(); } cs.TPolyMarker3D = (buf, marker) => { const ver = buf.last_read_version; buf.classStreamer(marker, clTObject); buf.classStreamer(marker, "TAttMarker"); marker.fN = buf.ntoi4(); marker.fP = buf.readFastArray(marker.fN * 3, kFloat); marker.fOption = buf.readTString(); marker.fName = (ver > 1) ? buf.readTString() : "TPolyMarker3D"; } cs.TPolyLine3D = (buf, obj) => { buf.classStreamer(obj, clTObject); buf.classStreamer(obj, "TAttLine"); obj.fN = buf.ntoi4(); obj.fP = buf.readFastArray(obj.fN * 3, kFloat); obj.fOption = buf.readTString(); } cs.TStreamerInfo = (buf, obj) => { buf.classStreamer(obj, clTNamed); obj.fCheckSum = buf.ntou4(); obj.fClassVersion = buf.ntou4(); obj.fElements = buf.readObjectAny(); } cs.TStreamerElement = (buf, element) => { const ver = buf.last_read_version; buf.classStreamer(element, clTNamed); element.fType = buf.ntou4(); element.fSize = buf.ntou4(); element.fArrayLength = buf.ntou4(); element.fArrayDim = buf.ntou4(); element.fMaxIndex = buf.readFastArray((ver == 1) ? buf.ntou4() : 5, kUInt); element.fTypeName = buf.readTString(); if ((element.fType === kUChar) && ((element.fTypeName == "Bool_t") || (element.fTypeName == "bool"))) element.fType = kBool; element.fXmin = element.fXmax = element.fFactor = 0; if (ver === 3) { element.fXmin = buf.ntod(); element.fXmax = buf.ntod(); element.fFactor = buf.ntod(); } else if ((ver > 3) && (element.fBits & JSROOT.BIT(6))) { // kHasRange let p1 = element.fTitle.indexOf("["); if ((p1 >= 0) && (element.fType > kOffsetP)) p1 = element.fTitle.indexOf("[", p1 + 1); let p2 = element.fTitle.indexOf("]", p1 + 1); if ((p1 >= 0) && (p2 >= p1 + 2)) { let arr = element.fTitle.substr(p1+1, p2 - p1 - 1).split(","), nbits = 32; if (!arr || arr.length < 2) throw new Error(`Problem to decode range setting from streamer element title ${element.fTitle}`); if (arr.length === 3) nbits = parseInt(arr[2]); if (!Number.isInteger(nbits) || (nbits < 2) || (nbits > 32)) nbits = 32; let parse_range = val => { if (!val) return 0; if (val.indexOf("pi") < 0) return parseFloat(val); val = val.trim(); let sign = 1.; if (val[0] == "-") { sign = -1; val = val.substr(1); } switch (val) { case "2pi": case "2*pi": case "twopi": return sign * 2 * Math.PI; case "pi/2": return sign * Math.PI / 2; case "pi/4": return sign * Math.PI / 4; } return sign * Math.PI; }; element.fXmin = parse_range(arr[0]); element.fXmax = parse_range(arr[1]); // avoid usage of 1 << nbits, while only works up to 32 bits let bigint = ((nbits >= 0) && (nbits < 32)) ? Math.pow(2, nbits) : 0xffffffff; if (element.fXmin < element.fXmax) element.fFactor = bigint / (element.fXmax - element.fXmin); else if (nbits < 15) element.fXmin = nbits; } } } cs.TStreamerBase = (buf, elem) => { const ver = buf.last_read_version; buf.classStreamer(elem, "TStreamerElement"); if (ver > 2) elem.fBaseVersion = buf.ntou4(); } cs.TStreamerBasicPointer = cs.TStreamerLoop = (buf, elem) => { if (buf.last_read_version > 1) { buf.classStreamer(elem, "TStreamerElement"); elem.fCountVersion = buf.ntou4(); elem.fCountName = buf.readTString(); elem.fCountClass = buf.readTString(); } } cs.TStreamerSTL = (buf, elem) => { buf.classStreamer(elem, "TStreamerElement"); elem.fSTLtype = buf.ntou4(); elem.fCtype = buf.ntou4(); if ((elem.fSTLtype === kSTLmultimap) && ((elem.fTypeName.indexOf("std::set") === 0) || (elem.fTypeName.indexOf("set") === 0))) elem.fSTLtype = kSTLset; if ((elem.fSTLtype === kSTLset) && ((elem.fTypeName.indexOf("std::multimap") === 0) || (elem.fTypeName.indexOf("multimap") === 0))) elem.fSTLtype = kSTLmultimap; } cs.TStreamerSTLstring = (buf, elem) => { if (buf.last_read_version > 0) buf.classStreamer(elem, "TStreamerSTL"); } cs.TStreamerObject = cs.TStreamerBasicType = cs.TStreamerObjectAny = cs.TStreamerString = cs.TStreamerObjectPointer = (buf, elem) => { if (buf.last_read_version > 1) buf.classStreamer(elem, "TStreamerElement"); } cs.TStreamerObjectAnyPointer = (buf, elem) => { if (buf.last_read_version > 0) buf.classStreamer(elem, "TStreamerElement"); } cs.TTree = { name: '$file', func: (buf, obj) => { obj.$kind = "TTree"; obj.$file = buf.fFile; buf.fFile._addReadTree(obj); } } cs.TVirtualPerfStats = clTObject; // use directly TObject streamer cs.RooRealVar = (buf, obj) => { const v = buf.last_read_version; buf.classStreamer(obj, "RooAbsRealLValue"); if (v == 1) { buf.ntod(); buf.ntod(); buf.ntoi4(); } // skip fitMin, fitMax, fitBins obj._error = buf.ntod(); obj._asymErrLo = buf.ntod(); obj._asymErrHi = buf.ntod(); if (v >= 2) obj._binning = buf.readObjectAny(); if (v == 3) obj._sharedProp = buf.readObjectAny(); if (v >= 4) obj._sharedProp = buf.classStreamer({}, "RooRealVarSharedProperties"); } cs.RooAbsBinning = (buf, obj) => { buf.classStreamer(obj, (buf.last_read_version == 1) ? clTObject : clTNamed); buf.classStreamer(obj, "RooPrintable"); } cs.RooCategory = (buf, obj) => { const v = buf.last_read_version; buf.classStreamer(obj, "RooAbsCategoryLValue"); obj._sharedProp = (v === 1) ? buf.readObjectAny() : buf.classStreamer({}, "RooCategorySharedProperties"); } cs['RooWorkspace::CodeRepo'] = (buf /*, obj*/) => { const sz = (buf.last_read_version == 2) ? 3 : 2; for (let i = 0; i < sz; ++i) { let cnt = buf.ntoi4() * ((i == 0) ? 4 : 3); while (cnt--) buf.readTString(); } } cs.RooLinkedList = (buf, obj) => { const v = buf.last_read_version; buf.classStreamer(obj, clTObject); let size = buf.ntoi4(); obj.arr = JSROOT.create("TList"); while (size--) obj.arr.Add(buf.readObjectAny()); if (v > 1) obj._name = buf.readTString(); } cs.TImagePalette = [ { basename: clTObject, base: 1, func: (buf, obj) => { if (!obj._typename) obj._typename = 'TImagePalette'; buf.classStreamer(obj, clTObject); } }, { name: 'fNumPoints', func: (buf, obj) => { obj.fNumPoints = buf.ntou4(); } }, { name: 'fPoints', func: (buf, obj) => { obj.fPoints = buf.readFastArray(obj.fNumPoints, kDouble); } }, { name: 'fColorRed', func: (buf, obj) => { obj.fColorRed = buf.readFastArray(obj.fNumPoints, kUShort); } }, { name: 'fColorGreen', func: (buf, obj) => { obj.fColorGreen = buf.readFastArray(obj.fNumPoints, kUShort); } }, { name: 'fColorBlue', func: (buf, obj) => { obj.fColorBlue = buf.readFastArray(obj.fNumPoints, kUShort); } }, { name: 'fColorAlpha', func: (buf, obj) => { obj.fColorAlpha = buf.readFastArray(obj.fNumPoints, kUShort); } } ]; cs.TAttImage = [ { name: 'fImageQuality', func: (buf, obj) => { obj.fImageQuality = buf.ntoi4(); } }, { name: 'fImageCompression', func: (buf, obj) => { obj.fImageCompression = buf.ntou4(); } }, { name: 'fConstRatio', func: (buf, obj) => { obj.fConstRatio = (buf.ntou1() != 0); } }, { name: 'fPalette', func: (buf, obj) => { obj.fPalette = buf.classStreamer({}, "TImagePalette"); } } ] cs.TASImage = (buf, obj) => { if ((buf.last_read_version == 1) && (buf.fFile.fVersion > 0) && (buf.fFile.fVersion < 50000)) return console.warn("old TASImage version - not yet supported"); buf.classStreamer(obj, clTNamed); if (buf.ntou1() != 0) { const size = buf.ntoi4(); obj.fPngBuf = buf.readFastArray(size, kUChar); } else { buf.classStreamer(obj, "TAttImage"); obj.fWidth = buf.ntoi4(); obj.fHeight = buf.ntoi4(); obj.fImgBuf = buf.readFastArray(obj.fWidth * obj.fHeight, kDouble); } } cs.TMaterial = (buf, obj) => { const v = buf.last_read_version; buf.classStreamer(obj, clTNamed); obj.fNumber = buf.ntoi4(); obj.fA = buf.ntof(); obj.fZ = buf.ntof(); obj.fDensity = buf.ntof(); if (v > 2) { buf.classStreamer(obj, "TAttFill"); obj.fRadLength = buf.ntof(); obj.fInterLength = buf.ntof(); } else { obj.fRadLength = obj.fInterLength = 0; } } cs.TMixture = (buf, obj) => { buf.classStreamer(obj, "TMaterial"); obj.fNmixt = buf.ntoi4(); obj.fAmixt = buf.readFastArray(buf.ntoi4(), kFloat); obj.fZmixt = buf.readFastArray(buf.ntoi4(), kFloat); obj.fWmixt = buf.readFastArray(buf.ntoi4(), kFloat); } // these are direct streamers - not follow version/checksum logic let ds = jsrio.DirectStreamers; // do nothing ds.TQObject = ds.TGraphStruct = ds.TGraphNode = ds.TGraphEdge = () => {}; ds.TDatime = (buf, obj) => { obj.fDatime = buf.ntou4(); // obj.GetDate = function() { // let res = new Date(); // res.setFullYear((this.fDatime >>> 26) + 1995); // res.setMonth((this.fDatime << 6) >>> 28); // res.setDate((this.fDatime << 10) >>> 27); // res.setHours((this.fDatime << 15) >>> 27); // res.setMinutes((this.fDatime << 20) >>> 26); // res.setSeconds((this.fDatime << 26) >>> 26); // res.setMilliseconds(0); // return res; // } }; ds.TKey = (buf, key) => { key.fNbytes = buf.ntoi4(); key.fVersion = buf.ntoi2(); key.fObjlen = buf.ntou4(); key.fDatime = buf.classStreamer({}, 'TDatime'); key.fKeylen = buf.ntou2(); key.fCycle = buf.ntou2(); if (key.fVersion > 1000) { key.fSeekKey = buf.ntou8(); buf.shift(8); // skip seekPdir } else { key.fSeekKey = buf.ntou4(); buf.shift(4); // skip seekPdir } key.fClassName = buf.readTString(); key.fName = buf.readTString(); key.fTitle = buf.readTString(); }; ds.TDirectory = (buf, dir) => { const version = buf.ntou2(); dir.fDatimeC = buf.classStreamer({}, 'TDatime'); dir.fDatimeM = buf.classStreamer({}, 'TDatime'); dir.fNbytesKeys = buf.ntou4(); dir.fNbytesName = buf.ntou4(); dir.fSeekDir = (version > 1000) ? buf.ntou8() : buf.ntou4(); dir.fSeekParent = (version > 1000) ? buf.ntou8() : buf.ntou4(); dir.fSeekKeys = (version > 1000) ? buf.ntou8() : buf.ntou4(); // if ((version % 1000) > 2) buf.shift(18); // skip fUUID } ds.TBasket = (buf, obj) => { buf.classStreamer(obj, 'TKey'); const ver = buf.readVersion(); obj.fBufferSize = buf.ntoi4(); obj.fNevBufSize = buf.ntoi4(); obj.fNevBuf = buf.ntoi4(); obj.fLast = buf.ntoi4(); if (obj.fLast > obj.fBufferSize) obj.fBufferSize = obj.fLast; const flag = buf.ntoi1(); if (flag === 0) return; if ((flag % 10) != 2) { if (obj.fNevBuf) { obj.fEntryOffset = buf.readFastArray(buf.ntoi4(), kInt); if ((20 < flag) && (flag < 40)) for (let i = 0, kDisplacementMask = 0xFF000000; i < obj.fNevBuf; ++i) obj.fEntryOffset[i] &= ~kDisplacementMask; } if (flag > 40) obj.fDisplacement = buf.readFastArray(buf.ntoi4(), kInt); } if ((flag === 1) || (flag > 10)) { // here is reading of raw data const sz = (ver.val <= 1) ? buf.ntoi4() : obj.fLast; if (sz > obj.fKeylen) { // buffer includes again complete TKey data - exclude it let blob = buf.extract([buf.o + obj.fKeylen, sz - obj.fKeylen]); obj.fBufferRef = new TBuffer(blob, 0, buf.fFile, sz - obj.fKeylen); obj.fBufferRef.fTagOffset = obj.fKeylen; } buf.shift(sz); } } ds.TRef = (buf, obj) => { buf.classStreamer(obj, clTObject); if (obj.fBits & kHasUUID) obj.fUUID = buf.readTString(); else obj.fPID = buf.ntou2(); } ds['TMatrixTSym<float>'] = (buf, obj) => { buf.classStreamer(obj, "TMatrixTBase<float>"); obj.fElements = new Float32Array(obj.fNelems); let arr = buf.readFastArray((obj.fNrows * (obj.fNcols + 1)) / 2, kFloat), cnt = 0; for (let i = 0; i < obj.fNrows; ++i) for (let j = i; j < obj.fNcols; ++j) obj.fElements[j * obj.fNcols + i] = obj.fElements[i * obj.fNcols + j] = arr[cnt++]; } ds['TMatrixTSym<double>'] = (buf, obj) => { buf.classStreamer(obj, "TMatrixTBase<double>"); obj.fElements = new Float64Array(obj.fNelems); let arr = buf.readFastArray((obj.fNrows * (obj.fNcols + 1)) / 2, kDouble), cnt = 0; for (let i = 0; i < obj.fNrows; ++i) for (let j = i; j < obj.fNcols; ++j) obj.fElements[j * obj.fNcols + i] = obj.fElements[i * obj.fNcols + j] = arr[cnt++]; } } /** @summary create element of the streamer * @private */ jsrio.createStreamerElement = function(name, typename, file) { const elem = { _typename: 'TStreamerElement', fName: name, fTypeName: typename, fType: 0, fSize: 0, fArrayLength: 0, fArrayDim: 0, fMaxIndex: [0, 0, 0, 0, 0], fXmin: 0, fXmax: 0, fFactor: 0 }; if (typeof typename === "string") { elem.fType = jsrio.GetTypeId(typename); if ((elem.fType < 0) && file && file.fBasicTypes[typename]) elem.fType = file.fBasicTypes[typename]; } else { elem.fType = typename; typename = elem.fTypeName = BasicTypeNames[elem.fType] || "int"; } if (elem.fType > 0) return elem; // basic type // check if there are STL containers let stltype = kNotSTL, pos = typename.indexOf("<"); if ((pos > 0) && (typename.indexOf(">") > pos + 2)) for (let stl = 1; stl < StlNames.length; ++stl) if (typename.substr(0, pos) === StlNames[stl]) { stltype = stl; break; } if (stltype !== kNotSTL) { elem._typename = 'TStreamerSTL'; elem.fType = kStreamer; elem.fSTLtype = stltype; elem.fCtype = 0; return elem; } const isptr = (typename.lastIndexOf("*") === typename.length - 1); if (isptr) elem.fTypeName = typename = typename.substr(0, typename.length - 1); if (getArrayKind(typename) == 0) { elem.fType = kTString; return elem; } elem.fType = isptr ? kAnyP : kAny; return elem; } /** @summary Open ROOT file for reading * @desc Generic method to open ROOT file for reading * Following kind of arguments can be provided: * - string with file URL (see example). In node.js environment local file like "file://hsimple.root" can be specified * - [File]{@link https://developer.mozilla.org/en-US/docs/Web/API/File} instance which let read local files from browser * - [ArrayBuffer]{@link https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/ArrayBuffer} instance with complete file content * @param {string|object} arg - argument for file open like url, see details * @returns {object} - Promise with {@link JSROOT.TFile} instance when file is opened * @example * JSROOT.openFile("https://root.cern/js/files/hsimple.root") * .then(f => console.log(`Open file ${f.getFileName()}`)); */ JSROOT.openFile = function(arg) { let file; if (JSROOT.nodejs && (typeof arg == "string")) { if (arg.indexOf("file://") == 0) file = new TNodejsFile(arg.substr(7)); else if (arg.indexOf("http") !== 0) file = new TNodejsFile(arg); } if (!file && (typeof arg === 'object') && (arg instanceof ArrayBuffer)) { file = new TFile("localfile.root"); file.assignFileContent(arg); } if (!file && (typeof arg === 'object') && arg.size && arg.name) file = new TLocalFile(arg); if (!file) file = new TFile(arg); return file._open(); } produceCustomStreamers(); jsrio.kChar = kChar; jsrio.kShort = kShort; jsrio.kInt = kInt; jsrio.kLong = kLong; jsrio.kFloat = kFloat; jsrio.kCounter = kCounter; jsrio.kCharStar = kCharStar; jsrio.kDouble = kDouble; jsrio.kDouble32 = kDouble32; jsrio.kLegacyChar = kLegacyChar; jsrio.kUChar = kUChar; jsrio.kUShort = kUShort; jsrio.kUInt = kUInt; jsrio.kULong = kULong; jsrio.kBits = kBits; jsrio.kLong64 = kLong64; jsrio.kULong64 = kULong64; jsrio.kBool = kBool; jsrio.kFloat16 = kFloat16; jsrio.kBase = kBase; jsrio.kOffsetL = kOffsetL; jsrio.kOffsetP = kOffsetP; jsrio.kObject = kObject; jsrio.kAny = kAny; jsrio.kObjectp = kObjectp; jsrio.kObjectP = kObjectP; jsrio.kTString = kTString; //jsrio.kTObject = kTObject; //jsrio.kTNamed = kTNamed; //jsrio.kAnyp = kAnyp; jsrio.kAnyP = kAnyP; jsrio.kStreamer = kStreamer; jsrio.kStreamLoop = kStreamLoop; JSROOT.TBuffer = TBuffer; JSROOT.TDirectory = TDirectory; JSROOT.TFile = TFile; JSROOT.TLocalFile = TLocalFile; JSROOT.TNodejsFile = TNodejsFile; JSROOT.IO = jsrio; if (JSROOT.nodejs) module.exports = jsrio; return jsrio; })
scripts/JSRoot.io.js
/// @file JSRoot.io.js /// I/O methods of JavaScript ROOT JSROOT.define([], () => { "use strict"; const clTObject = 'TObject', clTNamed = 'TNamed', kChar = 1, kShort = 2, kInt = 3, kLong = 4, kFloat = 5, kCounter = 6, kCharStar = 7, kDouble = 8, kDouble32 = 9, kLegacyChar = 10, kUChar = 11, kUShort = 12, kUInt = 13, kULong = 14, kBits = 15, kLong64 = 16, kULong64 = 17, kBool = 18, kFloat16 = 19, kBase = 0, kOffsetL = 20, kOffsetP = 40, kObject = 61, kAny = 62, kObjectp = 63, kObjectP = 64, kTString = 65, kTObject = 66, kTNamed = 67, kAnyp = 68, kAnyP = 69, kStreamer = 500, kStreamLoop = 501, kMapOffset = 2, kByteCountMask = 0x40000000, kNewClassTag = 0xFFFFFFFF, kClassMask = 0x80000000, // constants of bits in version kStreamedMemberWise = JSROOT.BIT(14), // constants used for coding type of STL container kNotSTL = 0, kSTLvector = 1, kSTLlist = 2, kSTLdeque = 3, kSTLmap = 4, kSTLmultimap = 5, kSTLset = 6, kSTLmultiset = 7, kSTLbitset = 8, // kSTLforwardlist = 9, kSTLunorderedset = 10, kSTLunorderedmultiset = 11, kSTLunorderedmap = 12, // kSTLunorderedmultimap = 13, kSTLend = 14 // name of base IO types BasicTypeNames = ["BASE", "char", "short", "int", "long", "float", "int", "const char*", "double", "Double32_t", "char", "unsigned char", "unsigned short", "unsigned", "unsigned long", "unsigned", "Long64_t", "ULong64_t", "bool", "Float16_t"], // names of STL containers StlNames = ["", "vector", "list", "deque", "map", "multimap", "set", "multiset", "bitset"], // TObject bits kIsReferenced = JSROOT.BIT(4), kHasUUID = JSROOT.BIT(5); /** @summary Holder of IO functionality * @alias JSROOT.IO * @namespace * @private */ let jsrio = { // here constants which are used by tree /* kAnyPnoVT: 70, */ kSTLp: 71, /* kSkip: 100, kSkipL: 120, kSkipP: 140, kConv: 200, kConvL: 220, kConvP: 240, */ kSTL: 300, /* kSTLstring: 365, */ Mode: "array", // could be string or array, enable usage of ArrayBuffer in http requests // kSplitCollectionOfPointers: 100, // map of user-streamer function like func(buf,obj) // or alias (classname) which can be used to read that function // or list of read functions CustomStreamers: {}, // these are streamers which do not handle version regularly // used for special classes like TRef or TBasket DirectStreamers: {}, /** @summary Returns true if type is integer */ IsInteger(typ) { return ((typ >= kChar) && (typ <= kLong)) || (typ === kCounter) || ((typ >= kLegacyChar) && (typ <= kBool)); }, /** @summary Returns true if numeric type */ IsNumeric(typ) { return (typ > 0) && (typ <= kBool) && (typ !== kCharStar); }, /** @summary Returns type by its name */ GetTypeId(typname, norecursion) { switch (typname) { case "bool": case "Bool_t": return kBool; case "char": case "signed char": case "Char_t": return kChar; case "Color_t": case "Style_t": case "Width_t": case "short": case "Short_t": return kShort; case "int": case "EErrorType": case "Int_t": return kInt; case "long": case "Long_t": return kLong; case "float": case "Float_t": return kFloat; case "double": case "Double_t": return kDouble; case "unsigned char": case "UChar_t": return kUChar; case "unsigned short": case "UShort_t": return kUShort; case "unsigned": case "unsigned int": case "UInt_t": return kUInt; case "unsigned long": case "ULong_t": return kULong; case "int64_t": case "long long": case "Long64_t": return kLong64; case "uint64_t": case "unsigned long long": case "ULong64_t": return kULong64; case "Double32_t": return kDouble32; case "Float16_t": return kFloat16; case "char*": case "const char*": case "const Char_t*": return kCharStar; } if (!norecursion) { let replace = jsrio.CustomStreamers[typname]; if (typeof replace === "string") return jsrio.GetTypeId(replace, true); } return -1; }, /** @summary Get bytes size of the type */ GetTypeSize(typname) { switch (typname) { case kBool: case kChar: case kUChar: return 1; case kShort: case kUShort: return 2; case kInt: case kFloat: case kUInt: return 4; case kLong: case kDouble: case kULong: case kLong64: case kULong64: return 8; } return -1; }, /** @summary Add custom streamer * @public */ addUserStreamer(type, user_streamer) { jsrio.CustomStreamers[type] = user_streamer; } } // namespace jsrio /** @summary Analyze and returns arrays kind * @return 0 if TString (or equivalent), positive value - some basic type, -1 - any other kind * @private */ function getArrayKind(type_name) { if ((type_name === "TString") || (type_name === "string") || (jsrio.CustomStreamers[type_name] === 'TString')) return 0; if ((type_name.length < 7) || (type_name.indexOf("TArray") !== 0)) return -1; if (type_name.length == 7) switch (type_name[6]) { case 'I': return kInt; case 'D': return kDouble; case 'F': return kFloat; case 'S': return kShort; case 'C': return kChar; case 'L': return kLong; default: return -1; } return type_name == "TArrayL64" ? kLong64 : -1; } /** @summary Let directly assign methods when doing I/O * @private */ function addClassMethods(clname, streamer) { if (streamer === null) return streamer; let methods = JSROOT.getMethods(clname); if (methods !== null) for (let key in methods) if ((typeof methods[key] === 'function') || (key.indexOf("_") == 0)) streamer.push({ name: key, method: methods[key], func: function(buf, obj) { obj[this.name] = this.method; } }); return streamer; } /* Copyright (C) 1999 Masanao Izumo <[email protected]> * Version: 1.0.0.1 * LastModified: Dec 25 1999 * original: http://www.onicos.com/staff/iz/amuse/javascript/expert/inflate.txt */ /* constant parameters */ const zip_WSIZE = 32768; // Sliding Window size /* constant tables (inflate) */ const zip_MASK_BITS = [ 0x0000, 0x0001, 0x0003, 0x0007, 0x000f, 0x001f, 0x003f, 0x007f, 0x00ff, 0x01ff, 0x03ff, 0x07ff, 0x0fff, 0x1fff, 0x3fff, 0x7fff, 0xffff], // Tables for deflate from PKZIP's appnote.txt. zip_cplens = [ // Copy lengths for literal codes 257..285 3, 4, 5, 6, 7, 8, 9, 10, 11, 13, 15, 17, 19, 23, 27, 31, 35, 43, 51, 59, 67, 83, 99, 115, 131, 163, 195, 227, 258, 0, 0], /* note: see note #13 above about the 258 in this list. */ zip_cplext = [ // Extra bits for literal codes 257..285 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 2, 2, 2, 2, 3, 3, 3, 3, 4, 4, 4, 4, 5, 5, 5, 5, 0, 99, 99], // 99==invalid zip_cpdist = [ // Copy offsets for distance codes 0..29 1, 2, 3, 4, 5, 7, 9, 13, 17, 25, 33, 49, 65, 97, 129, 193, 257, 385, 513, 769, 1025, 1537, 2049, 3073, 4097, 6145, 8193, 12289, 16385, 24577], zip_cpdext = [ // Extra bits for distance codes 0, 0, 0, 0, 1, 1, 2, 2, 3, 3, 4, 4, 5, 5, 6, 6, 7, 7, 8, 8, 9, 9, 10, 10, 11, 11, 12, 12, 13, 13], zip_border = [ // Order of the bit length code lengths 16, 17, 18, 0, 8, 7, 9, 6, 10, 5, 11, 4, 12, 3, 13, 2, 14, 1, 15]; // zip_STORED_BLOCK = 0, // zip_STATIC_TREES = 1, // zip_DYN_TREES = 2, /* for inflate */ // zip_lbits = 9, // bits in base literal/length lookup table // zip_dbits = 6, // bits in base distance lookup table // zip_INBUFSIZ = 32768, // Input buffer size // zip_INBUF_EXTRA = 64, // Extra buffer function ZIP_inflate(arr, tgt) { /* variables (inflate) */ let zip_slide = new Array(2 * zip_WSIZE), zip_wp = 0, // current position in slide zip_fixed_tl = null, // inflate static zip_fixed_td, // inflate static zip_fixed_bl, zip_fixed_bd, // inflate static zip_bit_buf = 0, // bit buffer zip_bit_len = 0, // bits in bit buffer zip_method = -1, zip_eof = false, zip_copy_leng = 0, zip_copy_dist = 0, zip_tl = null, zip_td, // literal/length and distance decoder tables zip_bl, zip_bd, // number of bits decoded by tl and td zip_inflate_data = arr, zip_inflate_datalen = arr.byteLength, zip_inflate_pos = 0; /* objects (inflate) */ function zip_HuftBuild(b, // code lengths in bits (all assumed <= BMAX) n, // number of codes (assumed <= N_MAX) s, // number of simple-valued codes (0..s-1) d, // list of base values for non-simple codes e, // list of extra bits for non-simple codes mm ) { // maximum lookup bits this.status = 0; // 0: success, 1: incomplete table, 2: bad input this.root = null; // (zip_HuftList) starting table this.m = 0; // maximum lookup bits, returns actual /* Given a list of code lengths and a maximum table size, make a set of tables to decode that set of codes. Return zero on success, one if the given code set is incomplete (the tables are still built in this case), two if the input is invalid (all zero length codes or an oversubscribed set of lengths), and three if not enough memory. The code with value 256 is special, and the tables are constructed so that no bits beyond that code are fetched when that code is decoded. */ const BMAX = 16, // maximum bit length of any code N_MAX = 288; // maximum number of codes in any set let c = new Array(BMAX+1), // bit length count table lx = new Array(BMAX+1), // stack of bits per table u = new Array(BMAX), // zip_HuftNode[BMAX][] table stack v = new Array(N_MAX), // values in order of bit length x = new Array(BMAX+1),// bit offsets, then code stack r = { e: 0, b: 0, n: 0, t: null }, // new zip_HuftNode(), // table entry for structure assignment rr = null, // temporary variable, use in assignment a, // counter for codes of length k el, // length of EOB code (value 256) f, // i repeats in table every f entries g, // maximum code length h, // table level i, // counter, current code j, // counter k, // number of bits in current code p, // pointer into c[], b[], or v[] pidx, // index of p q, // (zip_HuftNode) points to current table w, xp, // pointer into x or c y, // number of dummy codes added z, // number of entries in current table o, tail = this.root = null; // (zip_HuftList) for (i=0; i<=BMAX; ++i) c[i] = lx[i] = x[i] = 0; for (i=0; i<BMAX; ++i) u[i] = null; for (i=0; i<N_MAX; ++i) v[i] = 0; // Generate counts for each bit length el = (n > 256) ? b[256] : BMAX; // set length of EOB code, if any p = b; pidx = 0; i = n; do { c[p[pidx++]]++; // assume all entries <= BMAX } while (--i > 0); if (c[0] == n) { // null input--all zero length codes this.root = null; this.m = 0; this.status = 0; return this; } // Find minimum and maximum length, bound *m by those for (j = 1; j <= BMAX; ++j) if (c[j] != 0) break; k = j; // minimum code length if (mm < j) mm = j; for (i = BMAX; i != 0; --i) if (c[i] != 0) break; g = i; // maximum code length if (mm > i) mm = i; // Adjust last length count to fill out codes, if needed for (y = 1 << j; j < i; ++j, y <<= 1) { if ((y -= c[j]) < 0) { this.status = 2; // bad input: more codes than bits this.m = mm; return this; } } if ((y -= c[i]) < 0) { this.status = 2; this.m = mm; return this; } c[i] += y; // Generate starting offsets into the value table for each length x[1] = j = 0; p = c; pidx = 1; xp = 2; while (--i > 0) // note that i == g from above x[xp++] = (j += p[pidx++]); // Make a table of values in order of bit lengths p = b; pidx = 0; i = 0; do { if ((j = p[pidx++]) != 0) v[x[j]++] = i; } while (++i < n); n = x[g]; // set n to length of v // Generate the Huffman codes and for each, make the table entries x[0] = i = 0; // first Huffman code is zero p = v; pidx = 0; // grab values in bit order h = -1; // no tables yet--level -1 w = lx[0] = 0; // no bits decoded yet q = null; // ditto z = 0; // ditto // go through the bit lengths (k already is bits in shortest code) for (; k <= g; ++k) { a = c[k]; while (a-- > 0) { // here i is the Huffman code of length k bits for value p[pidx] // make tables up to required level while (k > w + lx[1 + h]) { w += lx[1 + h++]; // add bits already decoded // compute minimum size table less than or equal to *m bits z = (z = g - w) > mm ? mm : z; // upper limit if ((f = 1 << (j = k - w)) > a + 1) { // try a k-w bit table // too few codes for k-w bit table f -= a + 1; // deduct codes from patterns left xp = k; while (++j < z) { // try smaller tables up to z bits if ((f <<= 1) <= c[++xp]) break; // enough codes to use up j bits f -= c[xp]; // else deduct codes from patterns } } if (w + j > el && w < el) j = el - w; // make EOB code end at table z = 1 << j; // table entries for j-bit table lx[1 + h] = j; // set table size in stack // allocate and link in new table q = new Array(z); for (o = 0; o < z; ++o) q[o] = { e: 0, b: 0, n: 0, t: null }; // new zip_HuftNode if (tail == null) tail = this.root = { next: null, list: null }; // new zip_HuftList(); else tail = tail.next = { next: null, list: null }; // new zip_HuftList(); tail.next = null; tail.list = q; u[h] = q; // table starts after link /* connect to last table, if there is one */ if (h > 0) { x[h] = i; // save pattern for backing up r.b = lx[h]; // bits to dump before this table r.e = 16 + j; // bits in this table r.t = q; // pointer to this table j = (i & ((1 << w) - 1)) >> (w - lx[h]); rr = u[h-1][j]; rr.e = r.e; rr.b = r.b; rr.n = r.n; rr.t = r.t; } } // set up table entry in r r.b = k - w; if (pidx >= n) r.e = 99; // out of values--invalid code else if (p[pidx] < s) { r.e = (p[pidx] < 256 ? 16 : 15); // 256 is end-of-block code r.n = p[pidx++]; // simple code is just the value } else { r.e = e[p[pidx] - s]; // non-simple--look up in lists r.n = d[p[pidx++] - s]; } // fill code-like entries with r // f = 1 << (k - w); for (j = i >> w; j < z; j += f) { rr = q[j]; rr.e = r.e; rr.b = r.b; rr.n = r.n; rr.t = r.t; } // backwards increment the k-bit code i for (j = 1 << (k - 1); (i & j) != 0; j >>= 1) i ^= j; i ^= j; // backup over finished tables while ((i & ((1 << w) - 1)) != x[h]) { w -= lx[h--]; // don't need to update q } } } /* return actual size of base table */ this.m = lx[1]; /* Return true (1) if we were given an incomplete table */ this.status = ((y != 0 && g != 1) ? 1 : 0); /* end of constructor */ return this; } /* routines (inflate) */ function zip_NEEDBITS(n) { while (zip_bit_len < n) { if (zip_inflate_pos < zip_inflate_datalen) zip_bit_buf |= zip_inflate_data[zip_inflate_pos++] << zip_bit_len; zip_bit_len += 8; } } function zip_GETBITS(n) { return zip_bit_buf & zip_MASK_BITS[n]; } function zip_DUMPBITS(n) { zip_bit_buf >>= n; zip_bit_len -= n; } function zip_inflate_codes(buff, off, size) { if (size == 0) return 0; /* inflate (decompress) the codes in a deflated (compressed) block. Return an error code or zero if it all goes ok. */ let e, // table entry flag/number of extra bits t, // (zip_HuftNode) pointer to table entry n = 0; // inflate the coded data for (;;) { // do until end of block zip_NEEDBITS(zip_bl); t = zip_tl.list[zip_GETBITS(zip_bl)]; e = t.e; while (e > 16) { if (e == 99) return -1; zip_DUMPBITS(t.b); e -= 16; zip_NEEDBITS(e); t = t.t[zip_GETBITS(e)]; e = t.e; } zip_DUMPBITS(t.b); if (e == 16) { // then it's a literal zip_wp &= zip_WSIZE - 1; buff[off + n++] = zip_slide[zip_wp++] = t.n; if (n == size) return size; continue; } // exit if end of block if (e == 15) break; // it's an EOB or a length // get length of block to copy zip_NEEDBITS(e); zip_copy_leng = t.n + zip_GETBITS(e); zip_DUMPBITS(e); // decode distance of block to copy zip_NEEDBITS(zip_bd); t = zip_td.list[zip_GETBITS(zip_bd)]; e = t.e; while (e > 16) { if (e == 99) return -1; zip_DUMPBITS(t.b); e -= 16; zip_NEEDBITS(e); t = t.t[zip_GETBITS(e)]; e = t.e; } zip_DUMPBITS(t.b); zip_NEEDBITS(e); zip_copy_dist = zip_wp - t.n - zip_GETBITS(e); zip_DUMPBITS(e); // do the copy while (zip_copy_leng > 0 && n < size) { --zip_copy_leng; zip_copy_dist &= zip_WSIZE - 1; zip_wp &= zip_WSIZE - 1; buff[off + n++] = zip_slide[zip_wp++] = zip_slide[zip_copy_dist++]; } if (n == size) return size; } zip_method = -1; // done return n; } function zip_inflate_stored(buff, off, size) { /* "decompress" an inflated type 0 (stored) block. */ // go to byte boundary let n = zip_bit_len & 7; zip_DUMPBITS(n); // get the length and its complement zip_NEEDBITS(16); n = zip_GETBITS(16); zip_DUMPBITS(16); zip_NEEDBITS(16); if (n != ((~zip_bit_buf) & 0xffff)) return -1; // error in compressed data zip_DUMPBITS(16); // read and output the compressed data zip_copy_leng = n; n = 0; while (zip_copy_leng > 0 && n < size) { --zip_copy_leng; zip_wp &= zip_WSIZE - 1; zip_NEEDBITS(8); buff[off + n++] = zip_slide[zip_wp++] = zip_GETBITS(8); zip_DUMPBITS(8); } if (zip_copy_leng == 0) zip_method = -1; // done return n; } function zip_inflate_fixed(buff, off, size) { /* decompress an inflated type 1 (fixed Huffman codes) block. We should either replace this with a custom decoder, or at least precompute the Huffman tables. */ // if first time, set up tables for fixed blocks if (zip_fixed_tl == null) { let i = 0, // temporary variable l = new Array(288); // length list for huft_build // literal table while (i < 144) l[i++] = 8; while (i < 256) l[i++] = 9; while (i < 280) l[i++] = 7; while (i < 288) l[i++] = 8; // make a complete, but wrong code set zip_fixed_bl = 7; let h = new zip_HuftBuild(l, 288, 257, zip_cplens, zip_cplext, zip_fixed_bl); if (h.status != 0) throw new Error("HufBuild error: " + h.status); zip_fixed_tl = h.root; zip_fixed_bl = h.m; // distance table for (i = 0; i<30; ++i) l[i] = 5;// make an incomplete code set zip_fixed_bd = 5; h = new zip_HuftBuild(l, 30, 0, zip_cpdist, zip_cpdext, zip_fixed_bd); if (h.status > 1) { zip_fixed_tl = null; throw new Error("HufBuild error: "+h.status); } zip_fixed_td = h.root; zip_fixed_bd = h.m; } zip_tl = zip_fixed_tl; zip_td = zip_fixed_td; zip_bl = zip_fixed_bl; zip_bd = zip_fixed_bd; return zip_inflate_codes(buff, off, size); } function zip_inflate_dynamic(buff, off, size) { // decompress an inflated type 2 (dynamic Huffman codes) block. let i,j, // temporary variables l, // last length n, // number of lengths to get t, // (zip_HuftNode) literal/length code table h, // (zip_HuftBuild) ll = new Array(286+30); // literal/length and distance code lengths for (i = 0; i < ll.length; ++i) ll[i] = 0; // read in table lengths zip_NEEDBITS(5); const nl = 257 + zip_GETBITS(5); // number of literal/length codes zip_DUMPBITS(5); zip_NEEDBITS(5); const nd = 1 + zip_GETBITS(5); // number of distance codes zip_DUMPBITS(5); zip_NEEDBITS(4); const nb = 4 + zip_GETBITS(4); // number of bit length codes zip_DUMPBITS(4); if (nl > 286 || nd > 30) return -1; // bad lengths // read in bit-length-code lengths for (j = 0; j < nb; ++j) { zip_NEEDBITS(3); ll[zip_border[j]] = zip_GETBITS(3); zip_DUMPBITS(3); } for (; j < 19; ++j) ll[zip_border[j]] = 0; // build decoding table for trees--single level, 7 bit lookup zip_bl = 7; h = new zip_HuftBuild(ll, 19, 19, null, null, zip_bl); if (h.status != 0) return -1; // incomplete code set zip_tl = h.root; zip_bl = h.m; // read in literal and distance code lengths n = nl + nd; i = l = 0; while (i < n) { zip_NEEDBITS(zip_bl); t = zip_tl.list[zip_GETBITS(zip_bl)]; j = t.b; zip_DUMPBITS(j); j = t.n; if (j < 16) // length of code in bits (0..15) ll[i++] = l = j; // save last length in l else if (j == 16) { // repeat last length 3 to 6 times zip_NEEDBITS(2); j = 3 + zip_GETBITS(2); zip_DUMPBITS(2); if (i + j > n) return -1; while (j-- > 0) ll[i++] = l; } else if (j == 17) { // 3 to 10 zero length codes zip_NEEDBITS(3); j = 3 + zip_GETBITS(3); zip_DUMPBITS(3); if (i + j > n) return -1; while (j-- > 0) ll[i++] = 0; l = 0; } else { // j == 18: 11 to 138 zero length codes zip_NEEDBITS(7); j = 11 + zip_GETBITS(7); zip_DUMPBITS(7); if (i + j > n) return -1; while (j-- > 0) ll[i++] = 0; l = 0; } } // build the decoding tables for literal/length and distance codes zip_bl = 9; // zip_lbits; h = new zip_HuftBuild(ll, nl, 257, zip_cplens, zip_cplext, zip_bl); if (zip_bl == 0) // no literals or lengths h.status = 1; if (h.status != 0) { // if (h.status == 1); // **incomplete literal tree** return -1; // incomplete code set } zip_tl = h.root; zip_bl = h.m; for (i = 0; i < nd; ++i) ll[i] = ll[i + nl]; zip_bd = 6; // zip_dbits; h = new zip_HuftBuild(ll, nd, 0, zip_cpdist, zip_cpdext, zip_bd); zip_td = h.root; zip_bd = h.m; if (zip_bd == 0 && nl > 257) { // lengths but no distances // **incomplete distance tree** return -1; } //if (h.status == 1); // **incomplete distance tree** if (h.status != 0) return -1; // decompress until an end-of-block code return zip_inflate_codes(buff, off, size); } function zip_inflate_internal(buff, off, size) { // decompress an inflated entry let n = 0, i; while (n < size) { if (zip_eof && zip_method == -1) return n; if (zip_copy_leng > 0) { if (zip_method != 0 /*zip_STORED_BLOCK*/) { // STATIC_TREES or DYN_TREES while (zip_copy_leng > 0 && n < size) { --zip_copy_leng; zip_copy_dist &= zip_WSIZE - 1; zip_wp &= zip_WSIZE - 1; buff[off + n++] = zip_slide[zip_wp++] = zip_slide[zip_copy_dist++]; } } else { while (zip_copy_leng > 0 && n < size) { --zip_copy_leng; zip_wp &= zip_WSIZE - 1; zip_NEEDBITS(8); buff[off + n++] = zip_slide[zip_wp++] = zip_GETBITS(8); zip_DUMPBITS(8); } if (zip_copy_leng == 0) zip_method = -1; // done } if (n == size) return n; } if (zip_method == -1) { if (zip_eof) break; // read in last block bit zip_NEEDBITS(1); if (zip_GETBITS(1) != 0) zip_eof = true; zip_DUMPBITS(1); // read in block type zip_NEEDBITS(2); zip_method = zip_GETBITS(2); zip_DUMPBITS(2); zip_tl = null; zip_copy_leng = 0; } switch (zip_method) { case 0: // zip_STORED_BLOCK i = zip_inflate_stored(buff, off + n, size - n); break; case 1: // zip_STATIC_TREES if (zip_tl != null) i = zip_inflate_codes(buff, off + n, size - n); else i = zip_inflate_fixed(buff, off + n, size - n); break; case 2: // zip_DYN_TREES if (zip_tl != null) i = zip_inflate_codes(buff, off + n, size - n); else i = zip_inflate_dynamic(buff, off + n, size - n); break; default: // error i = -1; break; } if (i == -1) return zip_eof ? 0 : -1; n += i; } return n; } let i, cnt = 0; while ((i = zip_inflate_internal(tgt, cnt, Math.min(1024, tgt.byteLength-cnt))) > 0) { cnt += i; } return cnt; } // function ZIP_inflate /** * https://github.com/pierrec/node-lz4/blob/master/lib/binding.js * * LZ4 based compression and decompression * Copyright (c) 2014 Pierre Curto * MIT Licensed */ /** * Decode a block. Assumptions: input contains all sequences of a * chunk, output is large enough to receive the decoded data. * If the output buffer is too small, an error will be thrown. * If the returned value is negative, an error occured at the returned offset. * * @param input {Buffer} input data * @param output {Buffer} output data * @return {Number} number of decoded bytes * @private */ function LZ4_uncompress(input, output, sIdx, eIdx) { sIdx = sIdx || 0; eIdx = eIdx || (input.length - sIdx); // Process each sequence in the incoming data for (let i = sIdx, n = eIdx, j = 0; i < n;) { let token = input[i++]; // Literals let literals_length = (token >> 4); if (literals_length > 0) { // length of literals let l = literals_length + 240; while (l === 255) { l = input[i++]; literals_length += l; } // Copy the literals let end = i + literals_length; while (i < end) output[j++] = input[i++]; // End of buffer? if (i === n) return j; } // Match copy // 2 bytes offset (little endian) const offset = input[i++] | (input[i++] << 8); // 0 is an invalid offset value if (offset === 0 || offset > j) return -(i-2); // length of match copy let match_length = (token & 0xf), l = match_length + 240; while (l === 255) { l = input[i++]; match_length += l; } // Copy the match let pos = j - offset; // position of the match copy in the current output const end = j + match_length + 4 // minmatch = 4; while (j < end) output[j++] = output[pos++] } return j; } /** @summary Reads header envelope, determines zipped size and unzip content * @returns {Promise} with unzipped content * @private */ jsrio.R__unzip = function(arr, tgtsize, noalert, src_shift) { const HDRSIZE = 9, totallen = arr.byteLength, getChar = o => String.fromCharCode(arr.getUint8(o)), getCode = o => arr.getUint8(o); let curr = src_shift || 0, fullres = 0, tgtbuf = null; const nextPortion = () => { while (fullres < tgtsize) { let fmt = "unknown", off = 0, CHKSUM = 0; if (curr + HDRSIZE >= totallen) { if (!noalert) console.error("Error R__unzip: header size exceeds buffer size"); return Promise.resolve(null); } if (getChar(curr) == 'Z' && getChar(curr + 1) == 'L' && getCode(curr + 2) == 8) { fmt = "new"; off = 2; } else if (getChar(curr) == 'C' && getChar(curr + 1) == 'S' && getCode(curr + 2) == 8) { fmt = "old"; off = 0; } else if (getChar(curr) == 'X' && getChar(curr + 1) == 'Z' && getCode(curr + 2) == 0) fmt = "LZMA"; else if (getChar(curr) == 'Z' && getChar(curr + 1) == 'S' && getCode(curr + 2) == 1) fmt = "ZSTD"; else if (getChar(curr) == 'L' && getChar(curr + 1) == '4') { fmt = "LZ4"; off = 0; CHKSUM = 8; } /* C H E C K H E A D E R */ if ((fmt !== "new") && (fmt !== "old") && (fmt !== "LZ4") && (fmt !== "ZSTD")) { if (!noalert) console.error(`R__unzip: ${fmt} format is not supported!`); return Promise.resolve(null); } const srcsize = HDRSIZE + ((getCode(curr + 3) & 0xff) | ((getCode(curr + 4) & 0xff) << 8) | ((getCode(curr + 5) & 0xff) << 16)); const uint8arr = new Uint8Array(arr.buffer, arr.byteOffset + curr + HDRSIZE + off + CHKSUM, Math.min(arr.byteLength - curr - HDRSIZE - off - CHKSUM, srcsize - HDRSIZE - CHKSUM)); if (fmt === "ZSTD") { const handleZsdt = ZstdCodec => { return new Promise((resolveFunc, rejectFunc) => { ZstdCodec.run(zstd => { // const simple = new zstd.Simple(); const streaming = new zstd.Streaming(); // const data2 = simple.decompress(uint8arr); const data2 = streaming.decompress(uint8arr); // console.log(`tgtsize ${tgtsize} zstd size ${data2.length} offset ${data2.byteOffset} rawlen ${data2.buffer.byteLength}`); const reslen = data2.length; if (data2.byteOffset !== 0) return rejectFunc(Error("ZSTD result with byteOffset != 0")); // shortcut when exactly required data unpacked //if ((tgtsize == reslen) && data2.buffer) // resolveFunc(new DataView(data2.buffer)); // need to copy data while zstd does not provide simple way of doing it if (!tgtbuf) tgtbuf = new ArrayBuffer(tgtsize); let tgt8arr = new Uint8Array(tgtbuf, fullres); for(let i = 0; i < reslen; ++i) tgt8arr[i] = data2[i]; fullres += reslen; curr += srcsize; resolveFunc(true); }); }); }; let promise = JSROOT.nodejs ? handleZsdt(require('zstd-codec').ZstdCodec) : JSROOT.require('zstd-codec').then(codec => handleZsdt(codec)); return promise.then(() => nextPortion()); } // place for unpacking if (!tgtbuf) tgtbuf = new ArrayBuffer(tgtsize); let tgt8arr = new Uint8Array(tgtbuf, fullres); const reslen = (fmt === "LZ4") ? LZ4_uncompress(uint8arr, tgt8arr) : ZIP_inflate(uint8arr, tgt8arr); if (reslen <= 0) break; fullres += reslen; curr += srcsize; } if (fullres !== tgtsize) { if (!noalert) console.error(`R__unzip: fail to unzip data expects ${tgtsize}, got ${fullres}`); return Promise.resolve(null); } return Promise.resolve(new DataView(tgtbuf)); }; return nextPortion(); } // ================================================================================= /** * @summary Buffer object to read data from TFile * * @memberof JSROOT * @private */ class TBuffer { constructor(arr, pos, file, length) { this._typename = "TBuffer"; this.arr = arr; this.o = pos || 0; this.fFile = file; this.length = length || (arr ? arr.byteLength : 0); // use size of array view, blob buffer can be much bigger this.clearObjectMap(); this.fTagOffset = 0; this.last_read_version = 0; } /** @summary locate position in the buffer */ locate(pos) { this.o = pos; } /** @summary shift position in the buffer */ shift(cnt) { this.o += cnt; } /** @summary Returns remaining place in the buffer */ remain() { return this.length - this.o; } /** @summary Get mapped object with provided tag */ getMappedObject(tag) { return this.fObjectMap[tag]; } /** @summary Map object */ mapObject(tag, obj) { if (obj !== null) this.fObjectMap[tag] = obj; } /** @summary Map class */ mapClass(tag, classname) { this.fClassMap[tag] = classname; } /** @summary Get mapped class with provided tag */ getMappedClass(tag) { return (tag in this.fClassMap) ? this.fClassMap[tag] : -1; } /** @summary Clear objects map */ clearObjectMap() { this.fObjectMap = {}; this.fClassMap = {}; this.fObjectMap[0] = null; this.fDisplacement = 0; } /** @summary read class version from I/O buffer */ readVersion() { let ver = {}, bytecnt = this.ntou4(); // byte count if (bytecnt & kByteCountMask) ver.bytecnt = bytecnt - kByteCountMask - 2; // one can check between Read version and end of streamer else this.o -= 4; // rollback read bytes, this is old buffer without byte count this.last_read_version = ver.val = this.ntoi2(); this.last_read_checksum = 0; ver.off = this.o; if ((ver.val <= 0) && ver.bytecnt && (ver.bytecnt >= 4)) { ver.checksum = this.ntou4(); if (!this.fFile.findStreamerInfo(undefined, undefined, ver.checksum)) { // console.error(`Fail to find streamer info with check sum ${ver.checksum} version ${ver.val}`); this.o -= 4; // not found checksum in the list delete ver.checksum; // remove checksum } else { this.last_read_checksum = ver.checksum; } } return ver; } /** @summary Check bytecount after object streaming */ checkByteCount(ver, where) { if ((ver.bytecnt !== undefined) && (ver.off + ver.bytecnt !== this.o)) { if (where) console.log(`Missmatch in ${where} bytecount expected = ${ver.bytecnt} got = ${this.o - ver.off}`); this.o = ver.off + ver.bytecnt; return false; } return true; } /** @summary Read TString object (or equivalent) * @desc std::string uses similar binary format */ readTString() { let len = this.ntou1(); // large strings if (len == 255) len = this.ntou4(); if (len == 0) return ""; const pos = this.o; this.o += len; return (this.codeAt(pos) == 0) ? '' : this.substring(pos, pos + len); } /** @summary read Char_t array as string * @desc string either contains all symbols or until 0 symbol */ readFastString(n) { let res = "", code, closed = false; for (let i = 0; (n < 0) || (i < n); ++i) { code = this.ntou1(); if (code == 0) { closed = true; if (n < 0) break; } if (!closed) res += String.fromCharCode(code); } return res; } /** @summary read uint8_t */ ntou1() { return this.arr.getUint8(this.o++); } /** @summary read uint16_t */ ntou2() { const o = this.o; this.o += 2; return this.arr.getUint16(o); } /** @summary read uint32_t */ ntou4() { const o = this.o; this.o += 4; return this.arr.getUint32(o); } /** @summary read uint64_t */ ntou8() { const high = this.arr.getUint32(this.o); this.o += 4; const low = this.arr.getUint32(this.o); this.o += 4; return (high < 0x200000) ? (high * 0x100000000 + low) : (BigInt(high) * BigInt(0x100000000) + BigInt(low)); } /** @summary read int8_t */ ntoi1() { return this.arr.getInt8(this.o++); } /** @summary read int16_t */ ntoi2() { const o = this.o; this.o += 2; return this.arr.getInt16(o); } /** @summary read int32_t */ ntoi4() { const o = this.o; this.o += 4; return this.arr.getInt32(o); } /** @summary read int64_t */ ntoi8() { const high = this.arr.getUint32(this.o); this.o += 4; const low = this.arr.getUint32(this.o); this.o += 4; if (high < 0x80000000) return (high < 0x200000) ? (high * 0x100000000 + low) : (BigInt(high) * BigInt(0x100000000) + BigInt(low)); return (~high < 0x200000) ? (-1 - ((~high) * 0x100000000 + ~low)) : (BigInt(-1) - (BigInt(~high) * BigInt(0x100000000) + BigInt(~low))); } /** @summary read float */ ntof() { const o = this.o; this.o += 4; return this.arr.getFloat32(o); } /** @summary read double */ ntod() { const o = this.o; this.o += 8; return this.arr.getFloat64(o); } /** @summary Reads array of n values from the I/O buffer */ readFastArray(n, array_type) { let array, i = 0, o = this.o; const view = this.arr; switch (array_type) { case kDouble: array = new Float64Array(n); for (; i < n; ++i, o += 8) array[i] = view.getFloat64(o); break; case kFloat: array = new Float32Array(n); for (; i < n; ++i, o += 4) array[i] = view.getFloat32(o); break; case kLong: case kLong64: array = new Array(n); for (; i < n; ++i) array[i] = this.ntoi8(); return array; // exit here to avoid conflicts case kULong: case kULong64: array = new Array(n); for (; i < n; ++i) array[i] = this.ntou8(); return array; // exit here to avoid conflicts case kInt: case kCounter: array = new Int32Array(n); for (; i < n; ++i, o += 4) array[i] = view.getInt32(o); break; case kShort: array = new Int16Array(n); for (; i < n; ++i, o += 2) array[i] = view.getInt16(o); break; case kUShort: array = new Uint16Array(n); for (; i < n; ++i, o += 2) array[i] = view.getUint16(o); break; case kChar: array = new Int8Array(n); for (; i < n; ++i) array[i] = view.getInt8(o++); break; case kBool: case kUChar: array = new Uint8Array(n); for (; i < n; ++i) array[i] = view.getUint8(o++); break; case kTString: array = new Array(n); for (; i < n; ++i) array[i] = this.readTString(); return array; // exit here to avoid conflicts case kDouble32: throw new Error('kDouble32 should not be used in readFastArray'); case kFloat16: throw new Error('kFloat16 should not be used in readFastArray'); // case kBits: // case kUInt: default: array = new Uint32Array(n); for (; i < n; ++i, o += 4) array[i] = view.getUint32(o); break; } this.o = o; return array; } /** @summary Check if provided regions can be extracted from the buffer */ canExtract(place) { for (let n = 0; n < place.length; n += 2) if (place[n] + place[n + 1] > this.length) return false; return true; } /** @summary Extract area */ extract(place) { if (!this.arr || !this.arr.buffer || !this.canExtract(place)) return null; if (place.length === 2) return new DataView(this.arr.buffer, this.arr.byteOffset + place[0], place[1]); let res = new Array(place.length / 2); for (let n = 0; n < place.length; n += 2) res[n / 2] = new DataView(this.arr.buffer, this.arr.byteOffset + place[n], place[n + 1]); return res; // return array of buffers } /** @summary Get code at buffer position */ codeAt(pos) { return this.arr.getUint8(pos); } /** @summary Get part of buffer as string */ substring(beg, end) { let res = ""; for (let n = beg; n < end; ++n) res += String.fromCharCode(this.arr.getUint8(n)); return res; } /** @summary Read buffer as N-dim array */ readNdimArray(handle, func) { let ndim = handle.fArrayDim, maxindx = handle.fMaxIndex, res; if ((ndim < 1) && (handle.fArrayLength > 0)) { ndim = 1; maxindx = [handle.fArrayLength]; } if (handle.minus1) --ndim; if (ndim < 1) return func(this, handle); if (ndim === 1) { res = new Array(maxindx[0]); for (let n = 0; n < maxindx[0]; ++n) res[n] = func(this, handle); } else if (ndim === 2) { res = new Array(maxindx[0]); for (let n = 0; n < maxindx[0]; ++n) { let res2 = new Array(maxindx[1]); for (let k = 0; k < maxindx[1]; ++k) res2[k] = func(this, handle); res[n] = res2; } } else { let indx = [], arr = [], k; for (k = 0; k < ndim; ++k) { indx[k] = 0; arr[k] = []; } res = arr[0]; while (indx[0] < maxindx[0]) { k = ndim - 1; arr[k].push(func(this, handle)); ++indx[k]; while ((indx[k] === maxindx[k]) && (k > 0)) { indx[k] = 0; arr[k - 1].push(arr[k]); arr[k] = []; ++indx[--k]; } } } return res; } /** @summary read TKey data */ readTKey(key) { if (!key) key = {}; this.classStreamer(key, 'TKey'); let name = key.fName.replace(/['"]/g, ''); if (name !== key.fName) { key.fRealName = key.fName; key.fName = name; } return key; } /** @summary reading basket data * @desc this is remaining part of TBasket streamer to decode fEntryOffset * after unzipping of the TBasket data */ readBasketEntryOffset(basket, offset) { this.locate(basket.fLast - offset); if (this.remain() <= 0) { if (!basket.fEntryOffset && (basket.fNevBuf <= 1)) basket.fEntryOffset = [basket.fKeylen]; if (!basket.fEntryOffset) console.warn("No fEntryOffset when expected for basket with", basket.fNevBuf, "entries"); return; } const nentries = this.ntoi4(); // there is error in file=reco_103.root&item=Events;2/PCaloHits_g4SimHits_EcalHitsEE_Sim.&opt=dump;num:10;first:101 // it is workaround, but normally I/O should fail here if ((nentries < 0) || (nentries > this.remain() * 4)) { console.error("Error when reading entries offset from basket fNevBuf", basket.fNevBuf, "remains", this.remain(), "want to read", nentries); if (basket.fNevBuf <= 1) basket.fEntryOffset = [basket.fKeylen]; return; } basket.fEntryOffset = this.readFastArray(nentries, kInt); if (!basket.fEntryOffset) basket.fEntryOffset = [basket.fKeylen]; if (this.remain() > 0) basket.fDisplacement = this.readFastArray(this.ntoi4(), kInt); else basket.fDisplacement = undefined; } /** @summary read class definition from I/O buffer */ readClass() { const classInfo = { name: -1 }, bcnt = this.ntou4(), startpos = this.o; let tag; if (!(bcnt & kByteCountMask) || (bcnt == kNewClassTag)) { tag = bcnt; // bcnt = 0; } else { tag = this.ntou4(); } if (!(tag & kClassMask)) { classInfo.objtag = tag + this.fDisplacement; // indicate that we have deal with objects tag return classInfo; } if (tag == kNewClassTag) { // got a new class description followed by a new object classInfo.name = this.readFastString(-1); if (this.getMappedClass(this.fTagOffset + startpos + kMapOffset) === -1) this.mapClass(this.fTagOffset + startpos + kMapOffset, classInfo.name); } else { // got a tag to an already seen class const clTag = (tag & ~kClassMask) + this.fDisplacement; classInfo.name = this.getMappedClass(clTag); if (classInfo.name === -1) console.error(`Did not found class with tag ${clTag}`); } return classInfo; } /** @summary Read any object from buffer data */ readObjectAny() { const objtag = this.fTagOffset + this.o + kMapOffset, clRef = this.readClass(); // class identified as object and should be handled so if ('objtag' in clRef) return this.getMappedObject(clRef.objtag); if (clRef.name === -1) return null; const arrkind = getArrayKind(clRef.name); let obj; if (arrkind === 0) { obj = this.readTString(); } else if (arrkind > 0) { // reading array, can map array only afterwards obj = this.readFastArray(this.ntou4(), arrkind); this.mapObject(objtag, obj); } else { // reading normal object, should map before to obj = {}; this.mapObject(objtag, obj); this.classStreamer(obj, clRef.name); } return obj; } /** @summary Invoke streamer for specified class */ classStreamer(obj, classname) { if (obj._typename === undefined) obj._typename = classname; const direct = jsrio.DirectStreamers[classname]; if (direct) { direct(this, obj); return obj; } const ver = this.readVersion(); const streamer = this.fFile.getStreamer(classname, ver); if (streamer !== null) { const len = streamer.length; for (let n = 0; n < len; ++n) streamer[n].func(this, obj); } else { // just skip bytes belonging to not-recognized object // console.warn('skip object ', classname); JSROOT.addMethods(obj); } this.checkByteCount(ver, classname); return obj; } } // class TBuffer // ============================================================================== /** * @summary A class that reads a TDirectory from a buffer. * * @memberof JSROOT * @private */ class TDirectory { /** @summary constructor */ constructor(file, dirname, cycle) { this.fFile = file; this._typename = "TDirectory"; this.dir_name = dirname; this.dir_cycle = cycle; this.fKeys = []; } /** @summary retrieve a key by its name and cycle in the list of keys */ getKey(keyname, cycle, only_direct) { if (typeof cycle != 'number') cycle = -1; let bestkey = null; for (let i = 0; i < this.fKeys.length; ++i) { const key = this.fKeys[i]; if (!key || (key.fName!==keyname)) continue; if (key.fCycle == cycle) { bestkey = key; break; } if ((cycle < 0) && (!bestkey || (key.fCycle > bestkey.fCycle))) bestkey = key; } if (bestkey) return only_direct ? bestkey : Promise.resolve(bestkey); let pos = keyname.lastIndexOf("/"); // try to handle situation when object name contains slashed (bad practice anyway) while (pos > 0) { let dirname = keyname.substr(0, pos), subname = keyname.substr(pos+1), dirkey = this.getKey(dirname, undefined, true); if (dirkey && !only_direct && (dirkey.fClassName.indexOf("TDirectory")==0)) return this.fFile.readObject(this.dir_name + "/" + dirname, 1) .then(newdir => newdir.getKey(subname, cycle)); pos = keyname.lastIndexOf("/", pos-1); } return only_direct ? null : Promise.reject(Error("Key not found " + keyname)); } /** @summary Read object from the directory * @param {string} name - object name * @param {number} [cycle] - cycle number * @return {Promise} with read object */ readObject(obj_name, cycle) { return this.fFile.readObject(this.dir_name + "/" + obj_name, cycle); } /** @summary Read list of keys in directory */ readKeys(objbuf) { objbuf.classStreamer(this, 'TDirectory'); if ((this.fSeekKeys <= 0) || (this.fNbytesKeys <= 0)) return Promise.resolve(this); let file = this.fFile; return file.readBuffer([this.fSeekKeys, this.fNbytesKeys]).then(blob => { // Read keys of the top directory const buf = new TBuffer(blob, 0, file); buf.readTKey(); const nkeys = buf.ntoi4(); for (let i = 0; i < nkeys; ++i) this.fKeys.push(buf.readTKey()); file.fDirectories.push(this); return this; }); } } // TDirectory /** * @summary Interface to read objects from ROOT files * * @memberof JSROOT * @hideconstructor * @desc Use {@link JSROOT.openFile} to create instance of the class */ class TFile { constructor(url) { this._typename = "TFile"; this.fEND = 0; this.fFullURL = url; this.fURL = url; this.fAcceptRanges = true; // when disabled ('+' at the end of file name), complete file content read with single operation this.fUseStampPar = "stamp=" + (new Date).getTime(); // use additional time stamp parameter for file name to avoid browser caching problem this.fFileContent = null; // this can be full or partial content of the file (if ranges are not supported or if 1K header read from file) // stored as TBuffer instance this.fMaxRanges = 200; // maximal number of file ranges requested at once this.fDirectories = []; this.fKeys = []; this.fSeekInfo = 0; this.fNbytesInfo = 0; this.fTagOffset = 0; this.fStreamers = 0; this.fStreamerInfos = null; this.fFileName = ""; this.fStreamers = []; this.fBasicTypes = {}; // custom basic types, in most case enumerations if (typeof this.fURL != 'string') return this; if (this.fURL[this.fURL.length - 1] === "+") { this.fURL = this.fURL.substr(0, this.fURL.length - 1); this.fAcceptRanges = false; } if (this.fURL[this.fURL.length - 1] === "^") { this.fURL = this.fURL.substr(0, this.fURL.length - 1); this.fSkipHeadRequest = true; } if (this.fURL[this.fURL.length - 1] === "-") { this.fURL = this.fURL.substr(0, this.fURL.length - 1); this.fUseStampPar = false; } if (this.fURL.indexOf("file://") == 0) { this.fUseStampPar = false; this.fAcceptRanges = false; } const pos = Math.max(this.fURL.lastIndexOf("/"), this.fURL.lastIndexOf("\\")); this.fFileName = pos >= 0 ? this.fURL.substr(pos + 1) : this.fURL; } /** @summary Assign BufferArray with file contentOpen file * @private */ assignFileContent(bufArray) { this.fFileContent = new TBuffer(new DataView(bufArray)); this.fAcceptRanges = false; this.fUseStampPar = false; this.fEND = this.fFileContent.length; } /** @summary Open file * @returns {Promise} after file keys are read * @private */ _open() { if (!this.fAcceptRanges || this.fSkipHeadRequest) return this.readKeys(); return JSROOT.httpRequest(this.fURL, "head").then(res => { const accept_ranges = res.getResponseHeader("Accept-Ranges"); if (!accept_ranges) this.fAcceptRanges = false; const len = res.getResponseHeader("Content-Length"); if (len) this.fEND = parseInt(len); else this.fAcceptRanges = false; return this.readKeys(); }); } /** @summary read buffer(s) from the file * @returns {Promise} with read buffers * @private */ readBuffer(place, filename, progress_callback) { if ((this.fFileContent !== null) && !filename && (!this.fAcceptRanges || this.fFileContent.canExtract(place))) return Promise.resolve(this.fFileContent.extract(place)); let file = this, fileurl = file.fURL, resolveFunc, rejectFunc, promise = new Promise((resolve,reject) => { resolveFunc = resolve; rejectFunc = reject; }), first = 0, last = 0, blobs = [], read_callback; // array of requested segments if (filename && (typeof filename === 'string') && (filename.length > 0)) { const pos = fileurl.lastIndexOf("/"); fileurl = (pos < 0) ? filename : fileurl.substr(0, pos + 1) + filename; } function send_new_request(increment) { if (increment) { first = last; last = Math.min(first + file.fMaxRanges * 2, place.length); if (first >= place.length) return resolveFunc(blobs); } let fullurl = fileurl, ranges = "bytes", totalsz = 0; // try to avoid browser caching by adding stamp parameter to URL if (file.fUseStampPar) fullurl += ((fullurl.indexOf('?') < 0) ? "?" : "&") + file.fUseStampPar; for (let n = first; n < last; n += 2) { ranges += (n > first ? "," : "=") + (place[n] + "-" + (place[n] + place[n + 1] - 1)); totalsz += place[n + 1]; // accumulated total size } if (last - first > 2) totalsz += (last - first) * 60; // for multi-range ~100 bytes/per request let xhr = JSROOT.NewHttpRequest(fullurl, "buf", read_callback); if (file.fAcceptRanges) { xhr.setRequestHeader("Range", ranges); xhr.expected_size = Math.max(Math.round(1.1 * totalsz), totalsz + 200); // 200 if offset for the potential gzip } if (progress_callback && (typeof xhr.addEventListener === 'function')) { let sum1 = 0, sum2 = 0, sum_total = 0; for (let n = 1; n < place.length; n += 2) { sum_total += place[n]; if (n < first) sum1 += place[n]; if (n < last) sum2 += place[n]; } if (!sum_total) sum_total = 1; let progress_offest = sum1 / sum_total, progress_this = (sum2 - sum1) / sum_total; xhr.addEventListener("progress", function(oEvent) { if (oEvent.lengthComputable) progress_callback(progress_offest + progress_this * oEvent.loaded / oEvent.total); }); } xhr.send(null); } read_callback = function(res) { if (!res && file.fUseStampPar && (place[0] === 0) && (place.length === 2)) { // if fail to read file with stamp parameter, try once again without it file.fUseStampPar = false; return send_new_request(); } if (res && (place[0] === 0) && (place.length === 2) && !file.fFileContent) { // special case - keep content of first request (could be complete file) in memory file.fFileContent = new TBuffer((typeof res == 'string') ? res : new DataView(res)); if (!file.fAcceptRanges) file.fEND = file.fFileContent.length; return resolveFunc(file.fFileContent.extract(place)); } if (!res) { if ((first === 0) && (last > 2) && (file.fMaxRanges > 1)) { // server return no response with multi request - try to decrease ranges count or fail if (last / 2 > 200) file.fMaxRanges = 200; else if (last / 2 > 50) file.fMaxRanges = 50; else if (last / 2 > 20) file.fMaxRanges = 20; else if (last / 2 > 5) file.fMaxRanges = 5; else file.fMaxRanges = 1; last = Math.min(last, file.fMaxRanges * 2); // console.log('Change maxranges to ', file.fMaxRanges, 'last', last); return send_new_request(); } return rejectFunc(Error("Fail to read with several ranges")); } // if only single segment requested, return result as is if (last - first === 2) { let b = new DataView(res); if (place.length === 2) return resolveFunc(b); blobs.push(b); return send_new_request(true); } // object to access response data let hdr = this.getResponseHeader('Content-Type'), ismulti = (typeof hdr === 'string') && (hdr.indexOf('multipart') >= 0), view = new DataView(res); if (!ismulti) { // server may returns simple buffer, which combines all segments together let hdr_range = this.getResponseHeader('Content-Range'), segm_start = 0, segm_last = -1; if (hdr_range && hdr_range.indexOf("bytes") >= 0) { let parts = hdr_range.substr(hdr_range.indexOf("bytes") + 6).split(/[\s-\/]+/); if (parts.length === 3) { segm_start = parseInt(parts[0]); segm_last = parseInt(parts[1]); if (!Number.isInteger(segm_start) || !Number.isInteger(segm_last) || (segm_start > segm_last)) { segm_start = 0; segm_last = -1; } } } let canbe_single_segment = (segm_start <= segm_last); for (let n = first; n < last; n += 2) if ((place[n] < segm_start) || (place[n] + place[n + 1] - 1 > segm_last)) canbe_single_segment = false; if (canbe_single_segment) { for (let n = first; n < last; n += 2) blobs.push(new DataView(res, place[n] - segm_start, place[n + 1])); return send_new_request(true); } if ((file.fMaxRanges === 1) || (first !== 0)) return rejectFunc(Error('Server returns normal response when multipart was requested, disable multirange support')); file.fMaxRanges = 1; last = Math.min(last, file.fMaxRanges * 2); return send_new_request(); } // multipart messages requires special handling let indx = hdr.indexOf("boundary="), boundary = "", n = first, o = 0; if (indx > 0) { boundary = hdr.substr(indx + 9); if ((boundary[0] == '"') && (boundary[boundary.length - 1] == '"')) boundary = boundary.substr(1, boundary.length - 2); boundary = "--" + boundary; } else console.error('Did not found boundary id in the response header'); while (n < last) { let code1, code2 = view.getUint8(o), nline = 0, line = "", finish_header = false, segm_start = 0, segm_last = -1; while ((o < view.byteLength - 1) && !finish_header && (nline < 5)) { code1 = code2; code2 = view.getUint8(o + 1); if ((code1 == 13) && (code2 == 10)) { if ((line.length > 2) && (line.substr(0, 2) == '--') && (line !== boundary)) return rejectFunc(Error('Decode multipart message, expect boundary' + boundary + ' got ' + line)); line = line.toLowerCase(); if ((line.indexOf("content-range") >= 0) && (line.indexOf("bytes") > 0)) { let parts = line.substr(line.indexOf("bytes") + 6).split(/[\s-\/]+/); if (parts.length === 3) { segm_start = parseInt(parts[0]); segm_last = parseInt(parts[1]); if (!Number.isInteger(segm_start) || !Number.isInteger(segm_last) || (segm_start > segm_last)) { segm_start = 0; segm_last = -1; } } else { console.error('Fail to decode content-range', line, parts); } } if ((nline > 1) && (line.length === 0)) finish_header = true; o++; nline++; line = ""; code2 = view.getUint8(o + 1); } else { line += String.fromCharCode(code1); } o++; } if (!finish_header) return rejectFunc(Error('Cannot decode header in multipart message')); if (segm_start > segm_last) { // fall-back solution, believe that segments same as requested blobs.push(new DataView(res, o, place[n + 1])); o += place[n + 1]; n += 2; } else { while ((n < last) && (place[n] >= segm_start) && (place[n] + place[n + 1] - 1 <= segm_last)) { blobs.push(new DataView(res, o + place[n] - segm_start, place[n + 1])); n += 2; } o += (segm_last - segm_start + 1); } } send_new_request(true); } send_new_request(true); return promise; } /** @summary Returns file name */ getFileName() { return this.fFileName; } /** @summary Get directory with given name and cycle * @desc Function only can be used for already read directories, which are preserved in the memory * @private */ getDir(dirname, cycle) { if ((cycle === undefined) && (typeof dirname == 'string')) { const pos = dirname.lastIndexOf(';'); if (pos > 0) { cycle = parseInt(dirname.substr(pos + 1)); dirname = dirname.substr(0, pos); } } for (let j = 0; j < this.fDirectories.length; ++j) { const dir = this.fDirectories[j]; if (dir.dir_name != dirname) continue; if ((cycle !== undefined) && (dir.dir_cycle !== cycle)) continue; return dir; } return null; } /** @summary Retrieve a key by its name and cycle in the list of keys * @desc If only_direct not specified, returns Promise while key keys must be read first from the directory * @private */ getKey(keyname, cycle, only_direct) { if (typeof cycle != 'number') cycle = -1; let bestkey = null; for (let i = 0; i < this.fKeys.length; ++i) { const key = this.fKeys[i]; if (!key || (key.fName !== keyname)) continue; if (key.fCycle == cycle) { bestkey = key; break; } if ((cycle < 0) && (!bestkey || (key.fCycle > bestkey.fCycle))) bestkey = key; } if (bestkey) return only_direct ? bestkey : Promise.resolve(bestkey); let pos = keyname.lastIndexOf("/"); // try to handle situation when object name contains slashes (bad practice anyway) while (pos > 0) { let dirname = keyname.substr(0, pos), subname = keyname.substr(pos + 1), dir = this.getDir(dirname); if (dir) return dir.getKey(subname, cycle, only_direct); let dirkey = this.getKey(dirname, undefined, true); if (dirkey && !only_direct && (dirkey.fClassName.indexOf("TDirectory") == 0)) return this.readObject(dirname).then(newdir => newdir.getKey(subname, cycle)); pos = keyname.lastIndexOf("/", pos - 1); } return only_direct ? null : Promise.reject(Error("Key not found " + keyname)); } /** @summary Read and inflate object buffer described by its key * @private */ readObjBuffer(key) { return this.readBuffer([key.fSeekKey + key.fKeylen, key.fNbytes - key.fKeylen]).then(blob1 => { if (key.fObjlen <= key.fNbytes - key.fKeylen) { let buf = new TBuffer(blob1, 0, this); buf.fTagOffset = key.fKeylen; return buf; } return jsrio.R__unzip(blob1, key.fObjlen).then(objbuf => { if (!objbuf) return Promise.reject(Error("Fail to UNZIP buffer")); let buf = new TBuffer(objbuf, 0, this); buf.fTagOffset = key.fKeylen; return buf; }); }); } /** @summary Method called when TTree object is streamed * @private */ _addReadTree(obj) { if (jsrio.TTreeMethods) return JSROOT.extend(obj, jsrio.TTreeMethods); if (this.readTrees === undefined) this.readTrees = []; if (this.readTrees.indexOf(obj) < 0) this.readTrees.push(obj); } /** @summary Read any object from a root file * @desc One could specify cycle number in the object name or as separate argument * @param {string} obj_name - name of object, may include cycle number like "hpxpy;1" * @param {number} [cycle] - cycle number, also can be included in obj_name * @returns {Promise} promise with object read * @example * JSROOT.openFile("https://root.cern/js/files/hsimple.root") * .then(f => f.readObject("hpxpy;1")) * .then(obj => console.log(`Read object of type ${obj._typename}`)); */ readObject(obj_name, cycle, only_dir) { let pos = obj_name.lastIndexOf(";"); if (pos > 0) { cycle = parseInt(obj_name.slice(pos + 1)); obj_name = obj_name.slice(0, pos); } if (typeof cycle != 'number') cycle = -1; // remove leading slashes while (obj_name.length && (obj_name[0] == "/")) obj_name = obj_name.substr(1); let file = this, isdir, read_key; // one uses Promises while in some cases we need to // read sub-directory to get list of keys // in such situation calls are asynchrone return this.getKey(obj_name, cycle).then(key => { if ((obj_name == "StreamerInfo") && (key.fClassName == "TList")) return file.fStreamerInfos; if ((key.fClassName == 'TDirectory' || key.fClassName == 'TDirectoryFile')) { isdir = true; let dir = file.getDir(obj_name, cycle); if (dir) return dir; } if (!isdir && only_dir) return Promise.reject(Error(`Key ${obj_name} is not directory}`)); read_key = key; return file.readObjBuffer(key); }).then(buf => { if (isdir) { let dir = new TDirectory(file, obj_name, cycle); dir.fTitle = read_key.fTitle; return dir.readKeys(buf); } let obj = {}; buf.mapObject(1, obj); // tag object itself with id==1 buf.classStreamer(obj, read_key.fClassName); if ((read_key.fClassName === 'TF1') || (read_key.fClassName === 'TF2')) return file._readFormulas(obj); if (!file.readTrees) return obj; return JSROOT.require('tree').then(() => { if (file.readTrees) { file.readTrees.forEach(t => JSROOT.extend(t, jsrio.TTreeMethods)) delete file.readTrees; } return obj; }); }); } /** @summary read formulas from the file and add them to TF1/TF2 objects * @private */ _readFormulas(tf1) { let arr = []; for (let indx = 0; indx < this.fKeys.length; ++indx) if (this.fKeys[indx].fClassName == 'TFormula') arr.push(this.readObject(this.fKeys[indx].fName, this.fKeys[indx].fCycle)); return Promise.all(arr).then(formulas => { formulas.forEach(obj => tf1.addFormula(obj)); return tf1; }); } /** @summary extract streamer infos from the buffer * @private */ extractStreamerInfos(buf) { if (!buf) return; let lst = {}; buf.mapObject(1, lst); buf.classStreamer(lst, 'TList'); lst._typename = "TStreamerInfoList"; this.fStreamerInfos = lst; if (JSROOT.Painter && typeof JSROOT.Painter.addStreamerInfos === 'function') JSROOT.Painter.addStreamerInfos(lst); for (let k = 0; k < lst.arr.length; ++k) { let si = lst.arr[k]; if (!si.fElements) continue; for (let l = 0; l < si.fElements.arr.length; ++l) { let elem = si.fElements.arr[l]; if (!elem.fTypeName || !elem.fType) continue; let typ = elem.fType, typname = elem.fTypeName; if (typ >= 60) { if ((typ === kStreamer) && (elem._typename == "TStreamerSTL") && elem.fSTLtype && elem.fCtype && (elem.fCtype < 20)) { let prefix = (StlNames[elem.fSTLtype] || "undef") + "<"; if ((typname.indexOf(prefix) === 0) && (typname[typname.length - 1] == ">")) { typ = elem.fCtype; typname = typname.substr(prefix.length, typname.length - prefix.length - 1).trim(); if ((elem.fSTLtype === kSTLmap) || (elem.fSTLtype === kSTLmultimap)) if (typname.indexOf(",") > 0) typname = typname.substr(0, typname.indexOf(",")).trim(); else continue; } } if (typ >= 60) continue; } else { if ((typ > 20) && (typname[typname.length - 1] == "*")) typname = typname.substr(0, typname.length - 1); typ = typ % 20; } const kind = jsrio.GetTypeId(typname); if (kind === typ) continue; if ((typ === kBits) && (kind === kUInt)) continue; if ((typ === kCounter) && (kind === kInt)) continue; if (typname && typ && (this.fBasicTypes[typname] !== typ)) this.fBasicTypes[typname] = typ; } } } /** @summary Read file keys * @private */ readKeys() { let file = this; // with the first readbuffer we read bigger amount to create header cache return this.readBuffer([0, 1024]).then(blob => { let buf = new TBuffer(blob, 0, file); if (buf.substring(0, 4) !== 'root') return Promise.reject(Error(`Not a ROOT file ${file.fURL}`)); buf.shift(4); file.fVersion = buf.ntou4(); file.fBEGIN = buf.ntou4(); if (file.fVersion < 1000000) { //small file file.fEND = buf.ntou4(); file.fSeekFree = buf.ntou4(); file.fNbytesFree = buf.ntou4(); buf.shift(4); // const nfree = buf.ntoi4(); file.fNbytesName = buf.ntou4(); file.fUnits = buf.ntou1(); file.fCompress = buf.ntou4(); file.fSeekInfo = buf.ntou4(); file.fNbytesInfo = buf.ntou4(); } else { // new format to support large files file.fEND = buf.ntou8(); file.fSeekFree = buf.ntou8(); file.fNbytesFree = buf.ntou4(); buf.shift(4); // const nfree = buf.ntou4(); file.fNbytesName = buf.ntou4(); file.fUnits = buf.ntou1(); file.fCompress = buf.ntou4(); file.fSeekInfo = buf.ntou8(); file.fNbytesInfo = buf.ntou4(); } // empty file if (!file.fSeekInfo || !file.fNbytesInfo) return Promise.reject(Error(`File ${file.fURL} does not provide streamer infos`)); // extra check to prevent reading of corrupted data if (!file.fNbytesName || file.fNbytesName > 100000) return Promise.reject(Error(`Cannot read directory info of the file ${file.fURL}`)); //*-*-------------Read directory info let nbytes = file.fNbytesName + 22; nbytes += 4; // fDatimeC.Sizeof(); nbytes += 4; // fDatimeM.Sizeof(); nbytes += 18; // fUUID.Sizeof(); // assume that the file may be above 2 Gbytes if file version is > 4 if (file.fVersion >= 40000) nbytes += 12; // this part typically read from the header, no need to optimize return file.readBuffer([file.fBEGIN, Math.max(300, nbytes)]); }).then(blob3 => { let buf3 = new TBuffer(blob3, 0, file); // keep only title from TKey data file.fTitle = buf3.readTKey().fTitle; buf3.locate(file.fNbytesName); // we read TDirectory part of TFile buf3.classStreamer(file, 'TDirectory'); if (!file.fSeekKeys) return Promise.reject(Error(`Empty keys list in ${file.fURL}`)); // read with same request keys and streamer infos return file.readBuffer([file.fSeekKeys, file.fNbytesKeys, file.fSeekInfo, file.fNbytesInfo]); }).then(blobs => { const buf4 = new TBuffer(blobs[0], 0, file); buf4.readTKey(); // const nkeys = buf4.ntoi4(); for (let i = 0; i < nkeys; ++i) file.fKeys.push(buf4.readTKey()); const buf5 = new TBuffer(blobs[1], 0, file), si_key = buf5.readTKey(); if (!si_key) return Promise.reject(Error(`Fail to read StreamerInfo data in ${file.fURL}`)); file.fKeys.push(si_key); return file.readObjBuffer(si_key); }).then(blob6 => { file.extractStreamerInfos(blob6); return file; }); } /** @summary Read the directory content from a root file * @desc If directory was already read - return previously read object * Same functionality as {@link JSROOT.TFile.readObject} * @param {string} dir_name - directory name * @param {number} [cycle] - directory cycle * @returns {Promise} - promise with read directory */ readDirectory(dir_name, cycle) { return this.readObject(dir_name, cycle, true); } /** @summary Search streamer info * @param {string} clanme - class name * @param {number} [clversion] - class version * @param {number} [checksum] - streamer info checksum, have to match when specified * @private */ findStreamerInfo(clname, clversion, checksum) { if (!this.fStreamerInfos) return null; const arr = this.fStreamerInfos.arr, len = arr.length; if (checksum !== undefined) { let cache = this.fStreamerInfos.cache; if (!cache) cache = this.fStreamerInfos.cache = {}; let si = cache[checksum]; if (si !== undefined) return si; for (let i = 0; i < len; ++i) { si = arr[i]; if (si.fCheckSum === checksum) return cache[checksum] = si; } cache[checksum] = null; // checksum didnot found, do not try again } else { for (let i = 0; i < len; ++i) { let si = arr[i]; if ((si.fName === clname) && ((si.fClassVersion === clversion) || (clversion === undefined))) return si; } } return null; } /** @summary Returns streamer for the class 'clname', * @desc From the list of streamers or generate it from the streamer infos and add it to the list * @private */ getStreamer(clname, ver, s_i) { // these are special cases, which are handled separately if (clname == 'TQObject' || clname == "TBasket") return null; let streamer, fullname = clname; if (ver) { fullname += (ver.checksum ? ("$chksum" + ver.checksum) : ("$ver" + ver.val)); streamer = this.fStreamers[fullname]; if (streamer !== undefined) return streamer; } let custom = jsrio.CustomStreamers[clname]; // one can define in the user streamers just aliases if (typeof custom === 'string') return this.getStreamer(custom, ver, s_i); // streamer is just separate function if (typeof custom === 'function') { streamer = [{ typename: clname, func: custom }]; return addClassMethods(clname, streamer); } streamer = []; if (typeof custom === 'object') { if (!custom.name && !custom.func) return custom; streamer.push(custom); // special read entry, add in the beginning of streamer } // check element in streamer infos, one can have special cases if (!s_i) s_i = this.findStreamerInfo(clname, ver.val, ver.checksum); if (!s_i) { delete this.fStreamers[fullname]; if (!ver.nowarning) console.warn(`Not found streamer for ${clname} ver ${ver.val} checksum ${ver.checksum} full ${fullname}`); return null; } // special handling for TStyle which has duplicated member name fLineStyle if ((s_i.fName == "TStyle") && s_i.fElements) s_i.fElements.arr.forEach(elem => { if (elem.fName == "fLineStyle") elem.fName = "fLineStyles"; // like in ROOT JSON now }); // for each entry in streamer info produce member function if (s_i.fElements) for (let j = 0; j < s_i.fElements.arr.length; ++j) streamer.push(jsrio.createMember(s_i.fElements.arr[j], this)); this.fStreamers[fullname] = streamer; return addClassMethods(clname, streamer); } /** @summary Here we produce list of members, resolving all base classes * @private */ getSplittedStreamer(streamer, tgt) { if (!streamer) return tgt; if (!tgt) tgt = []; for (let n = 0; n < streamer.length; ++n) { let elem = streamer[n]; if (elem.base === undefined) { tgt.push(elem); continue; } if (elem.basename == clTObject) { tgt.push({ func: function(buf, obj) { buf.ntoi2(); // read version, why it here?? obj.fUniqueID = buf.ntou4(); obj.fBits = buf.ntou4(); if (obj.fBits & kIsReferenced) buf.ntou2(); // skip pid } }); continue; } let ver = { val: elem.base }; if (ver.val === 4294967295) { // this is -1 and indicates foreign class, need more workarounds ver.val = 1; // need to search version 1 - that happens when several versions of foreign class exists ??? } let parent = this.getStreamer(elem.basename, ver); if (parent) this.getSplittedStreamer(parent, tgt); } return tgt; } /** @summary Fully clenaup TFile data * @private */ delete() { this.fDirectories = null; this.fKeys = null; this.fStreamers = null; this.fSeekInfo = 0; this.fNbytesInfo = 0; this.fTagOffset = 0; } } // TFile // ======================================================================= /** @summary Reconstruct ROOT object from binary buffer * @desc Method can be used to reconstruct ROOT objects from binary buffer * which can be requested from running THttpServer, using **root.bin** request * To decode data, one has to request streamer infos data __after__ object data * as it shown in example. * * Method provided for convenience only to see how binary IO works. * It is strongly recommended to use **root.json** request to get data directly in * JSON format * * @param {string} class_name - Class name of the object * @param {binary} obj_rawdata - data of object root.bin request * @param {binary} sinfo_rawdata - data of streamer info root.bin request * @returns {object} - created JavaScript object * @example * async function read_binary_and_draw() { * await JSROOT.require("io"); * let obj_data = await JSROOT.httpRequest("http://localhost:8080/Files/job1.root/hpx/root.bin", "buf"); * let si_data = await JSROOT.httpRequest("http://localhost:8080/StreamerInfo/root.bin", "buf"); * let histo = await JSROOT.reconstructObject("TH1F", obj_data, si_data); * console.log(`Get histogram with title = ${histo.fTitle}`); * } * read_binary_and_draw(); * * // request same data via root.json request * JSROOT.httpRequest("http://localhost:8080/Files/job1.root/hpx/root.json", "object") * .then(histo => console.log(`Get histogram with title = ${histo.fTitle}`)); */ JSROOT.reconstructObject = function(class_name, obj_rawdata, sinfo_rawdata) { let file = new TFile; let buf = new TBuffer(sinfo_rawdata, 0, file); file.extractStreamerInfos(buf); let obj = {}; buf = new TBuffer(obj_rawdata, 0, file); buf.mapObject(obj, 1); buf.classStreamer(obj, class_name); return obj; } /** @summary Function to read vector element in the streamer * @private */ function readVectorElement(buf) { if (this.member_wise) { const n = buf.ntou4(); let streamer = null, ver = this.stl_version; if (n === 0) return []; // for empty vector no need to search split streamers if (n > 1000000) { throw new Error('member-wise streaming of ' + this.conttype + " num " + n + ' member ' + this.name); // return []; } if ((ver.val === this.member_ver) && (ver.checksum === this.member_checksum)) { streamer = this.member_streamer; } else { streamer = buf.fFile.getStreamer(this.conttype, ver); this.member_streamer = streamer = buf.fFile.getSplittedStreamer(streamer); this.member_ver = ver.val; this.member_checksum = ver.checksum; } let res = new Array(n), i, k, member; for (i = 0; i < n; ++i) res[i] = { _typename: this.conttype }; // create objects if (!streamer) { console.error('Fail to create split streamer for', this.conttype, 'need to read ', n, 'objects version', ver); } else { for (k = 0; k < streamer.length; ++k) { member = streamer[k]; if (member.split_func) { member.split_func(buf, res, n); } else { for (i = 0; i < n; ++i) member.func(buf, res[i]); } } } return res; } const n = buf.ntou4(); let res = new Array(n), i = 0; if (n > 200000) { console.error('vector streaming for of', this.conttype, n); return res; } if (this.arrkind > 0) { while (i < n) res[i++] = buf.readFastArray(buf.ntou4(), this.arrkind); } else if (this.arrkind === 0) { while (i < n) res[i++] = buf.readTString(); } else if (this.isptr) { while (i < n) res[i++] = buf.readObjectAny(); } else if (this.submember) { while (i < n) res[i++] = this.submember.readelem(buf); } else { while (i < n) res[i++] = buf.classStreamer({}, this.conttype); } return res; } /** @summary Function creates streamer for std::pair object * @private */ function getPairStreamer(si, typname, file) { if (!si) { if (typname.indexOf("pair") !== 0) return null; si = file.findStreamerInfo(typname); if (!si) { let p1 = typname.indexOf("<"), p2 = typname.lastIndexOf(">"); function GetNextName() { let res = "", p = p1 + 1, cnt = 0; while ((p < p2) && (cnt >= 0)) { switch (typname[p]) { case "<": cnt++; break; case ",": if (cnt === 0) cnt--; break; case ">": cnt--; break; } if (cnt >= 0) res += typname[p]; p++; } p1 = p - 1; return res.trim(); } si = { _typename: 'TStreamerInfo', fVersion: 1, fName: typname, fElements: JSROOT.create("TList") }; si.fElements.Add(jsrio.createStreamerElement("first", GetNextName(), file)); si.fElements.Add(jsrio.createStreamerElement("second", GetNextName(), file)); } } let streamer = file.getStreamer(typname, null, si); if (!streamer) return null; if (streamer.length !== 2) { console.error(`Streamer for pair class contains ${streamer.length} elements`); return null; } for (let nn = 0; nn < 2; ++nn) if (streamer[nn].readelem && !streamer[nn].pair_name) { streamer[nn].pair_name = (nn == 0) ? "first" : "second"; streamer[nn].func = function(buf, obj) { obj[this.pair_name] = this.readelem(buf); }; } return streamer; } /** @summary Function used in streamer to read std::map object * @private */ function readMapElement(buf) { let streamer = this.streamer; if (this.member_wise) { // when member-wise streaming is used, version is written const ver = this.stl_version; if (this.si) { let si = buf.fFile.findStreamerInfo(this.pairtype, ver.val, ver.checksum); if (this.si !== si) { streamer = getPairStreamer(si, this.pairtype, buf.fFile); if (!streamer || streamer.length !== 2) { console.log('Fail to produce streamer for ', this.pairtype); return null; } } } } const n = buf.ntoi4(); let i, res = new Array(n); if (this.member_wise && (buf.remain() >= 6)) { if (buf.ntoi2() == kStreamedMemberWise) buf.shift(4); else buf.shift(-2); // rewind } for (i = 0; i < n; ++i) { res[i] = { _typename: this.pairtype }; streamer[0].func(buf, res[i]); if (!this.member_wise) streamer[1].func(buf, res[i]); } // due-to member-wise streaming second element read after first is completed if (this.member_wise) for (i = 0; i < n; ++i) streamer[1].func(buf, res[i]); return res; } /** @summary create member entry for streamer element * @desc used for reading of data * @private */ jsrio.createMember = function(element, file) { let member = { name: element.fName, type: element.fType, fArrayLength: element.fArrayLength, fArrayDim: element.fArrayDim, fMaxIndex: element.fMaxIndex }; if (element.fTypeName === 'BASE') { if (getArrayKind(member.name) > 0) { // this is workaround for arrays as base class // we create 'fArray' member, which read as any other data member member.name = 'fArray'; member.type = kAny; } else { // create streamer for base class member.type = kBase; // this.getStreamer(element.fName); } } switch (member.type) { case kBase: member.base = element.fBaseVersion; // indicate base class member.basename = element.fName; // keep class name member.func = function(buf, obj) { buf.classStreamer(obj, this.basename); }; break; case kShort: member.func = function(buf, obj) { obj[this.name] = buf.ntoi2(); }; break; case kInt: case kCounter: member.func = function(buf, obj) { obj[this.name] = buf.ntoi4(); }; break; case kLong: case kLong64: member.func = function(buf, obj) { obj[this.name] = buf.ntoi8(); }; break; case kDouble: member.func = function(buf, obj) { obj[this.name] = buf.ntod(); }; break; case kFloat: member.func = function(buf, obj) { obj[this.name] = buf.ntof(); }; break; case kLegacyChar: case kUChar: member.func = function(buf, obj) { obj[this.name] = buf.ntou1(); }; break; case kUShort: member.func = function(buf, obj) { obj[this.name] = buf.ntou2(); }; break; case kBits: case kUInt: member.func = function(buf, obj) { obj[this.name] = buf.ntou4(); }; break; case kULong64: case kULong: member.func = function(buf, obj) { obj[this.name] = buf.ntou8(); }; break; case kBool: member.func = function(buf, obj) { obj[this.name] = buf.ntou1() != 0; }; break; case kOffsetL + kBool: case kOffsetL + kInt: case kOffsetL + kCounter: case kOffsetL + kDouble: case kOffsetL + kUChar: case kOffsetL + kShort: case kOffsetL + kUShort: case kOffsetL + kBits: case kOffsetL + kUInt: case kOffsetL + kULong: case kOffsetL + kULong64: case kOffsetL + kLong: case kOffsetL + kLong64: case kOffsetL + kFloat: if (element.fArrayDim < 2) { member.arrlength = element.fArrayLength; member.func = function(buf, obj) { obj[this.name] = buf.readFastArray(this.arrlength, this.type - kOffsetL); }; } else { member.arrlength = element.fMaxIndex[element.fArrayDim - 1]; member.minus1 = true; member.func = function(buf, obj) { obj[this.name] = buf.readNdimArray(this, (buf, handle) => buf.readFastArray(handle.arrlength, handle.type - kOffsetL)); }; } break; case kOffsetL + kChar: if (element.fArrayDim < 2) { member.arrlength = element.fArrayLength; member.func = function(buf, obj) { obj[this.name] = buf.readFastString(this.arrlength); }; } else { member.minus1 = true; // one dimension used for char* member.arrlength = element.fMaxIndex[element.fArrayDim - 1]; member.func = function(buf, obj) { obj[this.name] = buf.readNdimArray(this, (buf, handle) => buf.readFastString(handle.arrlength)); }; } break; case kOffsetP + kBool: case kOffsetP + kInt: case kOffsetP + kDouble: case kOffsetP + kUChar: case kOffsetP + kShort: case kOffsetP + kUShort: case kOffsetP + kBits: case kOffsetP + kUInt: case kOffsetP + kULong: case kOffsetP + kULong64: case kOffsetP + kLong: case kOffsetP + kLong64: case kOffsetP + kFloat: member.cntname = element.fCountName; member.func = function(buf, obj) { if (buf.ntou1() === 1) obj[this.name] = buf.readFastArray(obj[this.cntname], this.type - kOffsetP); else obj[this.name] = []; }; break; case kOffsetP + kChar: member.cntname = element.fCountName; member.func = function(buf, obj) { if (buf.ntou1() === 1) obj[this.name] = buf.readFastString(obj[this.cntname]); else obj[this.name] = null; }; break; case kDouble32: case kOffsetL + kDouble32: case kOffsetP + kDouble32: member.double32 = true; case kFloat16: case kOffsetL + kFloat16: case kOffsetP + kFloat16: if (element.fFactor !== 0) { member.factor = 1. / element.fFactor; member.min = element.fXmin; member.read = function(buf) { return buf.ntou4() * this.factor + this.min; }; } else if ((element.fXmin === 0) && member.double32) { member.read = function(buf) { return buf.ntof(); }; } else { member.nbits = Math.round(element.fXmin); if (member.nbits === 0) member.nbits = 12; member.dv = new DataView(new ArrayBuffer(8), 0); // used to cast from uint32 to float32 member.read = function(buf) { let theExp = buf.ntou1(), theMan = buf.ntou2(); this.dv.setUint32(0, (theExp << 23) | ((theMan & ((1 << (this.nbits + 1)) - 1)) << (23 - this.nbits))); return ((1 << (this.nbits + 1) & theMan) ? -1 : 1) * this.dv.getFloat32(0); }; } member.readarr = function(buf, len) { let arr = this.double32 ? new Float64Array(len) : new Float32Array(len); for (let n = 0; n < len; ++n) arr[n] = this.read(buf); return arr; } if (member.type < kOffsetL) { member.func = function(buf, obj) { obj[this.name] = this.read(buf); } } else if (member.type > kOffsetP) { member.cntname = element.fCountName; member.func = function(buf, obj) { if (buf.ntou1() === 1) { obj[this.name] = this.readarr(buf, obj[this.cntname]); } else { obj[this.name] = null; } }; } else if (element.fArrayDim < 2) { member.arrlength = element.fArrayLength; member.func = function(buf, obj) { obj[this.name] = this.readarr(buf, this.arrlength); }; } else { member.arrlength = element.fMaxIndex[element.fArrayDim - 1]; member.minus1 = true; member.func = function(buf, obj) { obj[this.name] = buf.readNdimArray(this, (buf, handle) => handle.readarr(buf, handle.arrlength)); }; } break; case kAnyP: case kObjectP: member.func = function(buf, obj) { obj[this.name] = buf.readNdimArray(this, buf => buf.readObjectAny()); }; break; case kAny: case kAnyp: case kObjectp: case kObject: { let classname = (element.fTypeName === 'BASE') ? element.fName : element.fTypeName; if (classname[classname.length - 1] == "*") classname = classname.substr(0, classname.length - 1); const arrkind = getArrayKind(classname); if (arrkind > 0) { member.arrkind = arrkind; member.func = function(buf, obj) { obj[this.name] = buf.readFastArray(buf.ntou4(), this.arrkind); }; } else if (arrkind === 0) { member.func = function(buf, obj) { obj[this.name] = buf.readTString(); }; } else { member.classname = classname; if (element.fArrayLength > 1) { member.func = function(buf, obj) { obj[this.name] = buf.readNdimArray(this, (buf, handle) => buf.classStreamer({}, handle.classname)); }; } else { member.func = function(buf, obj) { obj[this.name] = buf.classStreamer({}, this.classname); }; } } break; } case kOffsetL + kObject: case kOffsetL + kAny: case kOffsetL + kAnyp: case kOffsetL + kObjectp: { let classname = element.fTypeName; if (classname[classname.length - 1] == "*") classname = classname.substr(0, classname.length - 1); member.arrkind = getArrayKind(classname); if (member.arrkind < 0) member.classname = classname; member.func = function(buf, obj) { obj[this.name] = buf.readNdimArray(this, (buf, handle) => { if (handle.arrkind > 0) return buf.readFastArray(buf.ntou4(), handle.arrkind); if (handle.arrkind === 0) return buf.readTString(); return buf.classStreamer({}, handle.classname); }); } break; } case kChar: member.func = function(buf, obj) { obj[this.name] = buf.ntoi1(); }; break; case kCharStar: member.func = function(buf, obj) { const len = buf.ntoi4(); obj[this.name] = buf.substring(buf.o, buf.o + len); buf.o += len; }; break; case kTString: member.func = function(buf, obj) { obj[this.name] = buf.readTString(); }; break; case kTObject: case kTNamed: member.typename = element.fTypeName; member.func = function(buf, obj) { obj[this.name] = buf.classStreamer({}, this.typename); }; break; case kOffsetL + kTString: case kOffsetL + kTObject: case kOffsetL + kTNamed: member.typename = element.fTypeName; member.func = function(buf, obj) { const ver = buf.readVersion(); obj[this.name] = buf.readNdimArray(this, (buf, handle) => { if (handle.typename === 'TString') return buf.readTString(); return buf.classStreamer({}, handle.typename); }); buf.checkByteCount(ver, this.typename + "[]"); }; break; case kStreamLoop: case kOffsetL + kStreamLoop: member.typename = element.fTypeName; member.cntname = element.fCountName; if (member.typename.lastIndexOf("**") > 0) { member.typename = member.typename.substr(0, member.typename.lastIndexOf("**")); member.isptrptr = true; } else { member.typename = member.typename.substr(0, member.typename.lastIndexOf("*")); member.isptrptr = false; } if (member.isptrptr) { member.readitem = function(buf) { return buf.readObjectAny(); } } else { member.arrkind = getArrayKind(member.typename); if (member.arrkind > 0) member.readitem = function(buf) { return buf.readFastArray(buf.ntou4(), this.arrkind); } else if (member.arrkind === 0) member.readitem = function(buf) { return buf.readTString(); } else member.readitem = function(buf) { return buf.classStreamer({}, this.typename); } } if (member.readitem !== undefined) { member.read_loop = function(buf, cnt) { return buf.readNdimArray(this, (buf2, member2) => { let itemarr = new Array(cnt); for (let i = 0; i < cnt; ++i) itemarr[i] = member2.readitem(buf2); return itemarr; }); } member.func = function(buf, obj) { const ver = buf.readVersion(); let res = this.read_loop(buf, obj[this.cntname]); if (!buf.checkByteCount(ver, this.typename)) res = null; obj[this.name] = res; } member.branch_func = function(buf, obj) { // this is special functions, used by branch in the STL container const ver = buf.readVersion(), sz0 = obj[this.stl_size]; let res = new Array(sz0); for (let loop0 = 0; loop0 < sz0; ++loop0) { let cnt = obj[this.cntname][loop0]; res[loop0] = this.read_loop(buf, cnt); } if (!buf.checkByteCount(ver, this.typename)) res = null; obj[this.name] = res; } member.objs_branch_func = function(buf, obj) { // special function when branch read as part of complete object // objects already preallocated and only appropriate member must be set // see code in JSRoot.tree.js for reference const ver = buf.readVersion(); let arr = obj[this.name0]; // objects array where reading is done for (let loop0 = 0; loop0 < arr.length; ++loop0) { let obj1 = this.get(arr, loop0), cnt = obj1[this.cntname]; obj1[this.name] = this.read_loop(buf, cnt); } buf.checkByteCount(ver, this.typename); } } else { console.error(`fail to provide function for ${element.fName} (${element.fTypeName}) typ = ${element.fType}`); member.func = function(buf, obj) { const ver = buf.readVersion(); buf.checkByteCount(ver); obj[this.name] = ull; }; } break; case kStreamer: { member.typename = element.fTypeName; let stl = (element.fSTLtype || 0) % 40; if ((element._typename === 'TStreamerSTLstring') || (member.typename == "string") || (member.typename == "string*")) { member.readelem = buf => buf.readTString(); } else if ((stl === kSTLvector) || (stl === kSTLlist) || (stl === kSTLdeque) || (stl === kSTLset) || (stl === kSTLmultiset)) { let p1 = member.typename.indexOf("<"), p2 = member.typename.lastIndexOf(">"); member.conttype = member.typename.substr(p1 + 1, p2 - p1 - 1).trim(); member.typeid = jsrio.GetTypeId(member.conttype); if ((member.typeid < 0) && file.fBasicTypes[member.conttype]) { member.typeid = file.fBasicTypes[member.conttype]; console.log('!!! Reuse basic type', member.conttype, 'from file streamer infos'); } // check if (element.fCtype && (element.fCtype < 20) && (element.fCtype !== member.typeid)) { console.warn('Contained type', member.conttype, 'not recognized as basic type', element.fCtype, 'FORCE'); member.typeid = element.fCtype; } if (member.typeid > 0) { member.readelem = function(buf) { return buf.readFastArray(buf.ntoi4(), this.typeid); }; } else { member.isptr = false; if (member.conttype.lastIndexOf("*") === member.conttype.length - 1) { member.isptr = true; member.conttype = member.conttype.substr(0, member.conttype.length - 1); } if (element.fCtype === kObjectp) member.isptr = true; member.arrkind = getArrayKind(member.conttype); member.readelem = readVectorElement; if (!member.isptr && (member.arrkind < 0)) { let subelem = jsrio.createStreamerElement("temp", member.conttype); if (subelem.fType === kStreamer) { subelem.$fictional = true; member.submember = jsrio.createMember(subelem, file); } } } } else if ((stl === kSTLmap) || (stl === kSTLmultimap)) { const p1 = member.typename.indexOf("<"), p2 = member.typename.lastIndexOf(">"); member.pairtype = "pair<" + member.typename.substr(p1 + 1, p2 - p1 - 1) + ">"; // remember found streamer info from the file - // most probably it is the only one which should be used member.si = file.findStreamerInfo(member.pairtype); member.streamer = getPairStreamer(member.si, member.pairtype, file); if (!member.streamer || (member.streamer.length !== 2)) { console.error(`Fail to build streamer for pair ${member.pairtype}`); delete member.streamer; } if (member.streamer) member.readelem = readMapElement; } else if (stl === kSTLbitset) { member.readelem = (buf/*, obj*/) => buf.readFastArray(buf.ntou4(), kBool); } if (!member.readelem) { console.error(`'failed to create streamer for element ${member.typename} ${member.name} element ${element._typename} STL type ${element.fSTLtype}`); member.func = function(buf, obj) { const ver = buf.readVersion(); buf.checkByteCount(ver); obj[this.name] = null; } } else if (!element.$fictional) { member.read_version = function(buf, cnt) { if (cnt === 0) return null; const ver = buf.readVersion(); this.member_wise = ((ver.val & kStreamedMemberWise) !== 0); this.stl_version = undefined; if (this.member_wise) { ver.val = ver.val & ~kStreamedMemberWise; this.stl_version = { val: buf.ntoi2() }; if (this.stl_version.val <= 0) this.stl_version.checksum = buf.ntou4(); } return ver; } member.func = function(buf, obj) { const ver = this.read_version(buf); let res = buf.readNdimArray(this, (buf2, member2) => member2.readelem(buf2)); if (!buf.checkByteCount(ver, this.typename)) res = null; obj[this.name] = res; } member.branch_func = function(buf, obj) { // special function to read data from STL branch const cnt = obj[this.stl_size], ver = this.read_version(buf, cnt); let arr = new Array(cnt); for (let n = 0; n < cnt; ++n) arr[n] = buf.readNdimArray(this, (buf2, member2) => member2.readelem(buf2)); if (ver) buf.checkByteCount(ver, "branch " + this.typename); obj[this.name] = arr; } member.split_func = function(buf, arr, n) { // function to read array from member-wise streaming const ver = this.read_version(buf); for (let i = 0; i < n; ++i) arr[i][this.name] = buf.readNdimArray(this, (buf2, member2) => member2.readelem(buf2)); buf.checkByteCount(ver, this.typename); } member.objs_branch_func = function(buf, obj) { // special function when branch read as part of complete object // objects already preallocated and only appropriate member must be set // see code in JSRoot.tree.js for reference let arr = obj[this.name0]; // objects array where reading is done const ver = this.read_version(buf, arr.length); for (let n = 0; n < arr.length; ++n) { let obj1 = this.get(arr, n); obj1[this.name] = buf.readNdimArray(this, (buf2, member2) => member2.readelem(buf2)); } if (ver) buf.checkByteCount(ver, "branch " + this.typename); } } break; } default: console.error(`fail to provide function for ${element.fName} (${element.fTypeName}) typ = ${element.fType}`); member.func = function(/*buf, obj*/) { }; // do nothing, fix in the future } return member; } // ============================================================= /** * @summary Interface to read local file in the browser * * @memberof JSROOT * @hideconstructor * @desc Use {@link JSROOT.openFile} to create instance of the class * @private */ class TLocalFile extends TFile { constructor(file) { super(null); this.fUseStampPar = false; this.fLocalFile = file; this.fEND = file.size; this.fFullURL = file.name; this.fURL = file.name; this.fFileName = file.name; } /** @summary Open local file * @returns {Promise} after file keys are read */ _open() { return this.readKeys(); } /** @summary read buffer from local file */ readBuffer(place, filename /*, progress_callback */) { let file = this.fLocalFile; return new Promise((resolve, reject) => { if (filename) return reject(Error(`Cannot access other local file ${filename}`)); let reader = new FileReader(), cnt = 0, blobs = []; reader.onload = function(evnt) { let res = new DataView(evnt.target.result); if (place.length === 2) return resolve(res); blobs.push(res); cnt += 2; if (cnt >= place.length) return resolve(blobs); reader.readAsArrayBuffer(file.slice(place[cnt], place[cnt] + place[cnt + 1])); } reader.readAsArrayBuffer(file.slice(place[0], place[0] + place[1])); }); } } // TLocalFile // ============================================================= /** * @summary Interface to read file in node.js * * @memberof JSROOT * @hideconstructor * @desc Use {@link JSROOT.openFile} to create instance of the class * @private */ class TNodejsFile extends TFile { constructor(filename) { super(null); this.fUseStampPar = false; this.fEND = 0; this.fFullURL = filename; this.fURL = filename; this.fFileName = filename; } /** @summary Open file in node.js * @returns {Promise} after file keys are read */ _open() { this.fs = require('fs'); return new Promise((resolve,reject) => this.fs.open(this.fFileName, 'r', (status, fd) => { if (status) { console.log(status.message); return reject(Error(`Not possible to open ${this.fFileName} inside node.js`)); } let stats = this.fs.fstatSync(fd); this.fEND = stats.size; this.fd = fd; this.readKeys().then(resolve).catch(reject); }) ); } /** @summary Read buffer from node.js file * @returns {Promise} with requested blocks */ readBuffer(place, filename /*, progress_callback */) { return new Promise((resolve, reject) => { if (filename) return reject(Error(`Cannot access other local file ${filename}`)); if (!this.fs || !this.fd) return reject(Error(`File is not opened ${this.fFileName}`)); let cnt = 0, blobs = []; let readfunc = (err, bytesRead, buf) => { let res = new DataView(buf.buffer, buf.byteOffset, place[cnt + 1]); if (place.length === 2) return resolve(res); blobs.push(res); cnt += 2; if (cnt >= place.length) return resolve(blobs); this.fs.read(this.fd, Buffer.alloc(place[cnt + 1]), 0, place[cnt + 1], place[cnt], readfunc); } this.fs.read(this.fd, Buffer.alloc(place[1]), 0, place[1], place[0], readfunc); }); } } // TNodejsFile /** @summary Add custom streamers for basic ROOT classes * @private */ function produceCustomStreamers() { let cs = jsrio.CustomStreamers; cs[clTObject] = cs['TMethodCall'] = function(buf, obj) { obj.fUniqueID = buf.ntou4(); obj.fBits = buf.ntou4(); if (obj.fBits & kIsReferenced) buf.ntou2(); // skip pid }; cs[clTNamed] = [ { basename: clTObject, base: 1, func: function(buf, obj) { if (!obj._typename) obj._typename = clTNamed; buf.classStreamer(obj, clTObject); } }, { name: 'fName', func: function(buf, obj) { obj.fName = buf.readTString(); } }, { name: 'fTitle', func: function(buf, obj) { obj.fTitle = buf.readTString(); } } ]; addClassMethods(clTNamed, cs[clTNamed]); cs.TObjString = [ { basename: clTObject, base: 1, func: (buf, obj) => { if (!obj._typename) obj._typename = 'TObjString'; buf.classStreamer(obj, clTObject); } }, { name: 'fString', func: (buf, obj) => { obj.fString = buf.readTString(); } } ]; addClassMethods('TObjString', cs['TObjString']); cs.TList = cs.THashList = function(buf, obj) { // stream all objects in the list from the I/O buffer if (!obj._typename) obj._typename = this.typename; obj.$kind = "TList"; // all derived classes will be marked as well if (buf.last_read_version > 3) { buf.classStreamer(obj, clTObject); obj.name = buf.readTString(); const nobjects = buf.ntou4(); obj.arr = new Array(nobjects); obj.opt = new Array(nobjects); for (let i = 0; i < nobjects; ++i) { obj.arr[i] = buf.readObjectAny(); obj.opt[i] = buf.readTString(); } } else { obj.name = ""; obj.arr = []; obj.opt = []; } } cs.TClonesArray = (buf, list) => { if (!list._typename) list._typename = "TClonesArray"; list.$kind = "TClonesArray"; list.name = ""; const ver = buf.last_read_version; if (ver > 2) buf.classStreamer(list, clTObject); if (ver > 1) list.name = buf.readTString(); let classv = buf.readTString(), clv = 0, pos = classv.lastIndexOf(";"); if (pos > 0) { clv = parseInt(classv.substr(pos + 1)); classv = classv.substr(0, pos); } let nobjects = buf.ntou4(); if (nobjects < 0) nobjects = -nobjects; // for backward compatibility list.arr = new Array(nobjects); list.fLast = nobjects - 1; list.fLowerBound = buf.ntou4(); let streamer = buf.fFile.getStreamer(classv, { val: clv }); streamer = buf.fFile.getSplittedStreamer(streamer); if (!streamer) { console.log('Cannot get member-wise streamer for', classv, clv); } else { // create objects for (let n = 0; n < nobjects; ++n) list.arr[n] = { _typename: classv }; // call streamer for all objects member-wise for (let k = 0; k < streamer.length; ++k) for (let n = 0; n < nobjects; ++n) streamer[k].func(buf, list.arr[n]); } } cs.TMap = (buf, map) => { if (!map._typename) map._typename = "TMap"; map.name = ""; map.arr = []; const ver = buf.last_read_version; if (ver > 2) buf.classStreamer(map, clTObject); if (ver > 1) map.name = buf.readTString(); const nobjects = buf.ntou4(); // create objects for (let n = 0; n < nobjects; ++n) { let obj = { _typename: "TPair" }; obj.first = buf.readObjectAny(); obj.second = buf.readObjectAny(); if (obj.first) map.arr.push(obj); } } cs.TTreeIndex = (buf, obj) => { const ver = buf.last_read_version; obj._typename = "TTreeIndex"; buf.classStreamer(obj, "TVirtualIndex"); obj.fMajorName = buf.readTString(); obj.fMinorName = buf.readTString(); obj.fN = buf.ntoi8(); obj.fIndexValues = buf.readFastArray(obj.fN, kLong64); if (ver > 1) obj.fIndexValuesMinor = buf.readFastArray(obj.fN, kLong64); obj.fIndex = buf.readFastArray(obj.fN, kLong64); } cs.TRefArray = (buf, obj) => { obj._typename = "TRefArray"; buf.classStreamer(obj, clTObject); obj.name = buf.readTString(); const nobj = buf.ntoi4(); obj.fLast = nobj - 1; obj.fLowerBound = buf.ntoi4(); /*const pidf = */ buf.ntou2(); obj.fUIDs = buf.readFastArray(nobj, kUInt); } cs.TCanvas = (buf, obj) => { obj._typename = "TCanvas"; buf.classStreamer(obj, "TPad"); obj.fDISPLAY = buf.readTString(); obj.fDoubleBuffer = buf.ntoi4(); obj.fRetained = (buf.ntou1() !== 0); obj.fXsizeUser = buf.ntoi4(); obj.fYsizeUser = buf.ntoi4(); obj.fXsizeReal = buf.ntoi4(); obj.fYsizeReal = buf.ntoi4(); obj.fWindowTopX = buf.ntoi4(); obj.fWindowTopY = buf.ntoi4(); obj.fWindowWidth = buf.ntoi4(); obj.fWindowHeight = buf.ntoi4(); obj.fCw = buf.ntou4(); obj.fCh = buf.ntou4(); obj.fCatt = buf.classStreamer({}, "TAttCanvas"); buf.ntou1(); // ignore b << TestBit(kMoveOpaque); buf.ntou1(); // ignore b << TestBit(kResizeOpaque); obj.fHighLightColor = buf.ntoi2(); obj.fBatch = (buf.ntou1() !== 0); buf.ntou1(); // ignore b << TestBit(kShowEventStatus); buf.ntou1(); // ignore b << TestBit(kAutoExec); buf.ntou1(); // ignore b << TestBit(kMenuBar); } cs.TObjArray = (buf, list) => { if (!list._typename) list._typename = "TObjArray"; list.$kind = "TObjArray"; list.name = ""; const ver = buf.last_read_version; if (ver > 2) buf.classStreamer(list, clTObject); if (ver > 1) list.name = buf.readTString(); const nobjects = buf.ntou4(); let i = 0; list.arr = new Array(nobjects); list.fLast = nobjects - 1; list.fLowerBound = buf.ntou4(); while (i < nobjects) list.arr[i++] = buf.readObjectAny(); } cs.TPolyMarker3D = (buf, marker) => { const ver = buf.last_read_version; buf.classStreamer(marker, clTObject); buf.classStreamer(marker, "TAttMarker"); marker.fN = buf.ntoi4(); marker.fP = buf.readFastArray(marker.fN * 3, kFloat); marker.fOption = buf.readTString(); marker.fName = (ver > 1) ? buf.readTString() : "TPolyMarker3D"; } cs.TPolyLine3D = (buf, obj) => { buf.classStreamer(obj, clTObject); buf.classStreamer(obj, "TAttLine"); obj.fN = buf.ntoi4(); obj.fP = buf.readFastArray(obj.fN * 3, kFloat); obj.fOption = buf.readTString(); } cs.TStreamerInfo = (buf, obj) => { buf.classStreamer(obj, clTNamed); obj.fCheckSum = buf.ntou4(); obj.fClassVersion = buf.ntou4(); obj.fElements = buf.readObjectAny(); } cs.TStreamerElement = (buf, element) => { const ver = buf.last_read_version; buf.classStreamer(element, clTNamed); element.fType = buf.ntou4(); element.fSize = buf.ntou4(); element.fArrayLength = buf.ntou4(); element.fArrayDim = buf.ntou4(); element.fMaxIndex = buf.readFastArray((ver == 1) ? buf.ntou4() : 5, kUInt); element.fTypeName = buf.readTString(); if ((element.fType === kUChar) && ((element.fTypeName == "Bool_t") || (element.fTypeName == "bool"))) element.fType = kBool; element.fXmin = element.fXmax = element.fFactor = 0; if (ver === 3) { element.fXmin = buf.ntod(); element.fXmax = buf.ntod(); element.fFactor = buf.ntod(); } else if ((ver > 3) && (element.fBits & JSROOT.BIT(6))) { // kHasRange let p1 = element.fTitle.indexOf("["); if ((p1 >= 0) && (element.fType > kOffsetP)) p1 = element.fTitle.indexOf("[", p1 + 1); let p2 = element.fTitle.indexOf("]", p1 + 1); if ((p1 >= 0) && (p2 >= p1 + 2)) { let arr = element.fTitle.substr(p1+1, p2 - p1 - 1).split(","), nbits = 32; if (!arr || arr.length < 2) throw new Error(`Problem to decode range setting from streamer element title ${element.fTitle}`); if (arr.length === 3) nbits = parseInt(arr[2]); if (!Number.isInteger(nbits) || (nbits < 2) || (nbits > 32)) nbits = 32; let parse_range = val => { if (!val) return 0; if (val.indexOf("pi") < 0) return parseFloat(val); val = val.trim(); let sign = 1.; if (val[0] == "-") { sign = -1; val = val.substr(1); } switch (val) { case "2pi": case "2*pi": case "twopi": return sign * 2 * Math.PI; case "pi/2": return sign * Math.PI / 2; case "pi/4": return sign * Math.PI / 4; } return sign * Math.PI; }; element.fXmin = parse_range(arr[0]); element.fXmax = parse_range(arr[1]); // avoid usage of 1 << nbits, while only works up to 32 bits let bigint = ((nbits >= 0) && (nbits < 32)) ? Math.pow(2, nbits) : 0xffffffff; if (element.fXmin < element.fXmax) element.fFactor = bigint / (element.fXmax - element.fXmin); else if (nbits < 15) element.fXmin = nbits; } } } cs.TStreamerBase = (buf, elem) => { const ver = buf.last_read_version; buf.classStreamer(elem, "TStreamerElement"); if (ver > 2) elem.fBaseVersion = buf.ntou4(); } cs.TStreamerBasicPointer = cs.TStreamerLoop = (buf, elem) => { if (buf.last_read_version > 1) { buf.classStreamer(elem, "TStreamerElement"); elem.fCountVersion = buf.ntou4(); elem.fCountName = buf.readTString(); elem.fCountClass = buf.readTString(); } } cs.TStreamerSTL = (buf, elem) => { buf.classStreamer(elem, "TStreamerElement"); elem.fSTLtype = buf.ntou4(); elem.fCtype = buf.ntou4(); if ((elem.fSTLtype === kSTLmultimap) && ((elem.fTypeName.indexOf("std::set") === 0) || (elem.fTypeName.indexOf("set") === 0))) elem.fSTLtype = kSTLset; if ((elem.fSTLtype === kSTLset) && ((elem.fTypeName.indexOf("std::multimap") === 0) || (elem.fTypeName.indexOf("multimap") === 0))) elem.fSTLtype = kSTLmultimap; } cs.TStreamerSTLstring = (buf, elem) => { if (buf.last_read_version > 0) buf.classStreamer(elem, "TStreamerSTL"); } cs.TStreamerObject = cs.TStreamerBasicType = cs.TStreamerObjectAny = cs.TStreamerString = cs.TStreamerObjectPointer = (buf, elem) => { if (buf.last_read_version > 1) buf.classStreamer(elem, "TStreamerElement"); } cs.TStreamerObjectAnyPointer = (buf, elem) => { if (buf.last_read_version > 0) buf.classStreamer(elem, "TStreamerElement"); } cs.TTree = { name: '$file', func: (buf, obj) => { obj.$kind = "TTree"; obj.$file = buf.fFile; buf.fFile._addReadTree(obj); } } cs.TVirtualPerfStats = clTObject; // use directly TObject streamer cs.RooRealVar = (buf, obj) => { const v = buf.last_read_version; buf.classStreamer(obj, "RooAbsRealLValue"); if (v == 1) { buf.ntod(); buf.ntod(); buf.ntoi4(); } // skip fitMin, fitMax, fitBins obj._error = buf.ntod(); obj._asymErrLo = buf.ntod(); obj._asymErrHi = buf.ntod(); if (v >= 2) obj._binning = buf.readObjectAny(); if (v == 3) obj._sharedProp = buf.readObjectAny(); if (v >= 4) obj._sharedProp = buf.classStreamer({}, "RooRealVarSharedProperties"); } cs.RooAbsBinning = (buf, obj) => { buf.classStreamer(obj, (buf.last_read_version == 1) ? clTObject : clTNamed); buf.classStreamer(obj, "RooPrintable"); } cs.RooCategory = (buf, obj) => { const v = buf.last_read_version; buf.classStreamer(obj, "RooAbsCategoryLValue"); obj._sharedProp = (v === 1) ? buf.readObjectAny() : buf.classStreamer({}, "RooCategorySharedProperties"); } cs['RooWorkspace::CodeRepo'] = (buf /*, obj*/) => { const sz = (buf.last_read_version == 2) ? 3 : 2; for (let i = 0; i < sz; ++i) { let cnt = buf.ntoi4() * ((i == 0) ? 4 : 3); while (cnt--) buf.readTString(); } } cs.RooLinkedList = (buf, obj) => { const v = buf.last_read_version; buf.classStreamer(obj, clTObject); let size = buf.ntoi4(); obj.arr = JSROOT.create("TList"); while (size--) obj.arr.Add(buf.readObjectAny()); if (v > 1) obj._name = buf.readTString(); } cs.TImagePalette = [ { basename: clTObject, base: 1, func: (buf, obj) => { if (!obj._typename) obj._typename = 'TImagePalette'; buf.classStreamer(obj, clTObject); } }, { name: 'fNumPoints', func: (buf, obj) => { obj.fNumPoints = buf.ntou4(); } }, { name: 'fPoints', func: (buf, obj) => { obj.fPoints = buf.readFastArray(obj.fNumPoints, kDouble); } }, { name: 'fColorRed', func: (buf, obj) => { obj.fColorRed = buf.readFastArray(obj.fNumPoints, kUShort); } }, { name: 'fColorGreen', func: (buf, obj) => { obj.fColorGreen = buf.readFastArray(obj.fNumPoints, kUShort); } }, { name: 'fColorBlue', func: (buf, obj) => { obj.fColorBlue = buf.readFastArray(obj.fNumPoints, kUShort); } }, { name: 'fColorAlpha', func: (buf, obj) => { obj.fColorAlpha = buf.readFastArray(obj.fNumPoints, kUShort); } } ]; cs.TAttImage = [ { name: 'fImageQuality', func: (buf, obj) => { obj.fImageQuality = buf.ntoi4(); } }, { name: 'fImageCompression', func: (buf, obj) => { obj.fImageCompression = buf.ntou4(); } }, { name: 'fConstRatio', func: (buf, obj) => { obj.fConstRatio = (buf.ntou1() != 0); } }, { name: 'fPalette', func: (buf, obj) => { obj.fPalette = buf.classStreamer({}, "TImagePalette"); } } ] cs.TASImage = (buf, obj) => { if ((buf.last_read_version == 1) && (buf.fFile.fVersion > 0) && (buf.fFile.fVersion < 50000)) return console.warn("old TASImage version - not yet supported"); buf.classStreamer(obj, clTNamed); if (buf.ntou1() != 0) { const size = buf.ntoi4(); obj.fPngBuf = buf.readFastArray(size, kUChar); } else { buf.classStreamer(obj, "TAttImage"); obj.fWidth = buf.ntoi4(); obj.fHeight = buf.ntoi4(); obj.fImgBuf = buf.readFastArray(obj.fWidth * obj.fHeight, kDouble); } } cs.TMaterial = (buf, obj) => { const v = buf.last_read_version; buf.classStreamer(obj, clTNamed); obj.fNumber = buf.ntoi4(); obj.fA = buf.ntof(); obj.fZ = buf.ntof(); obj.fDensity = buf.ntof(); if (v > 2) { buf.classStreamer(obj, "TAttFill"); obj.fRadLength = buf.ntof(); obj.fInterLength = buf.ntof(); } else { obj.fRadLength = obj.fInterLength = 0; } } cs.TMixture = (buf, obj) => { buf.classStreamer(obj, "TMaterial"); obj.fNmixt = buf.ntoi4(); obj.fAmixt = buf.readFastArray(buf.ntoi4(), kFloat); obj.fZmixt = buf.readFastArray(buf.ntoi4(), kFloat); obj.fWmixt = buf.readFastArray(buf.ntoi4(), kFloat); } // these are direct streamers - not follow version/checksum logic let ds = jsrio.DirectStreamers; // do nothing ds.TQObject = ds.TGraphStruct = ds.TGraphNode = ds.TGraphEdge = () => {}; ds.TDatime = (buf, obj) => { obj.fDatime = buf.ntou4(); // obj.GetDate = function() { // let res = new Date(); // res.setFullYear((this.fDatime >>> 26) + 1995); // res.setMonth((this.fDatime << 6) >>> 28); // res.setDate((this.fDatime << 10) >>> 27); // res.setHours((this.fDatime << 15) >>> 27); // res.setMinutes((this.fDatime << 20) >>> 26); // res.setSeconds((this.fDatime << 26) >>> 26); // res.setMilliseconds(0); // return res; // } }; ds.TKey = (buf, key) => { key.fNbytes = buf.ntoi4(); key.fVersion = buf.ntoi2(); key.fObjlen = buf.ntou4(); key.fDatime = buf.classStreamer({}, 'TDatime'); key.fKeylen = buf.ntou2(); key.fCycle = buf.ntou2(); if (key.fVersion > 1000) { key.fSeekKey = buf.ntou8(); buf.shift(8); // skip seekPdir } else { key.fSeekKey = buf.ntou4(); buf.shift(4); // skip seekPdir } key.fClassName = buf.readTString(); key.fName = buf.readTString(); key.fTitle = buf.readTString(); }; ds.TDirectory = (buf, dir) => { const version = buf.ntou2(); dir.fDatimeC = buf.classStreamer({}, 'TDatime'); dir.fDatimeM = buf.classStreamer({}, 'TDatime'); dir.fNbytesKeys = buf.ntou4(); dir.fNbytesName = buf.ntou4(); dir.fSeekDir = (version > 1000) ? buf.ntou8() : buf.ntou4(); dir.fSeekParent = (version > 1000) ? buf.ntou8() : buf.ntou4(); dir.fSeekKeys = (version > 1000) ? buf.ntou8() : buf.ntou4(); // if ((version % 1000) > 2) buf.shift(18); // skip fUUID } ds.TBasket = (buf, obj) => { buf.classStreamer(obj, 'TKey'); const ver = buf.readVersion(); obj.fBufferSize = buf.ntoi4(); obj.fNevBufSize = buf.ntoi4(); obj.fNevBuf = buf.ntoi4(); obj.fLast = buf.ntoi4(); if (obj.fLast > obj.fBufferSize) obj.fBufferSize = obj.fLast; const flag = buf.ntoi1(); if (flag === 0) return; if ((flag % 10) != 2) { if (obj.fNevBuf) { obj.fEntryOffset = buf.readFastArray(buf.ntoi4(), kInt); if ((20 < flag) && (flag < 40)) for (let i = 0, kDisplacementMask = 0xFF000000; i < obj.fNevBuf; ++i) obj.fEntryOffset[i] &= ~kDisplacementMask; } if (flag > 40) obj.fDisplacement = buf.readFastArray(buf.ntoi4(), kInt); } if ((flag === 1) || (flag > 10)) { // here is reading of raw data const sz = (ver.val <= 1) ? buf.ntoi4() : obj.fLast; if (sz > obj.fKeylen) { // buffer includes again complete TKey data - exclude it let blob = buf.extract([buf.o + obj.fKeylen, sz - obj.fKeylen]); obj.fBufferRef = new TBuffer(blob, 0, buf.fFile, sz - obj.fKeylen); obj.fBufferRef.fTagOffset = obj.fKeylen; } buf.shift(sz); } } ds.TRef = (buf, obj) => { buf.classStreamer(obj, clTObject); if (obj.fBits & kHasUUID) obj.fUUID = buf.readTString(); else obj.fPID = buf.ntou2(); } ds['TMatrixTSym<float>'] = (buf, obj) => { buf.classStreamer(obj, "TMatrixTBase<float>"); obj.fElements = new Float32Array(obj.fNelems); let arr = buf.readFastArray((obj.fNrows * (obj.fNcols + 1)) / 2, kFloat), cnt = 0; for (let i = 0; i < obj.fNrows; ++i) for (let j = i; j < obj.fNcols; ++j) obj.fElements[j * obj.fNcols + i] = obj.fElements[i * obj.fNcols + j] = arr[cnt++]; } ds['TMatrixTSym<double>'] = (buf, obj) => { buf.classStreamer(obj, "TMatrixTBase<double>"); obj.fElements = new Float64Array(obj.fNelems); let arr = buf.readFastArray((obj.fNrows * (obj.fNcols + 1)) / 2, kDouble), cnt = 0; for (let i = 0; i < obj.fNrows; ++i) for (let j = i; j < obj.fNcols; ++j) obj.fElements[j * obj.fNcols + i] = obj.fElements[i * obj.fNcols + j] = arr[cnt++]; } } /** @summary create element of the streamer * @private */ jsrio.createStreamerElement = function(name, typename, file) { const elem = { _typename: 'TStreamerElement', fName: name, fTypeName: typename, fType: 0, fSize: 0, fArrayLength: 0, fArrayDim: 0, fMaxIndex: [0, 0, 0, 0, 0], fXmin: 0, fXmax: 0, fFactor: 0 }; if (typeof typename === "string") { elem.fType = jsrio.GetTypeId(typename); if ((elem.fType < 0) && file && file.fBasicTypes[typename]) elem.fType = file.fBasicTypes[typename]; } else { elem.fType = typename; typename = elem.fTypeName = BasicTypeNames[elem.fType] || "int"; } if (elem.fType > 0) return elem; // basic type // check if there are STL containers let stltype = kNotSTL, pos = typename.indexOf("<"); if ((pos > 0) && (typename.indexOf(">") > pos + 2)) for (let stl = 1; stl < StlNames.length; ++stl) if (typename.substr(0, pos) === StlNames[stl]) { stltype = stl; break; } if (stltype !== kNotSTL) { elem._typename = 'TStreamerSTL'; elem.fType = kStreamer; elem.fSTLtype = stltype; elem.fCtype = 0; return elem; } const isptr = (typename.lastIndexOf("*") === typename.length - 1); if (isptr) elem.fTypeName = typename = typename.substr(0, typename.length - 1); if (getArrayKind(typename) == 0) { elem.fType = kTString; return elem; } elem.fType = isptr ? kAnyP : kAny; return elem; } /** @summary Open ROOT file for reading * @desc Generic method to open ROOT file for reading * Following kind of arguments can be provided: * - string with file URL (see example). In node.js environment local file like "file://hsimple.root" can be specified * - [File]{@link https://developer.mozilla.org/en-US/docs/Web/API/File} instance which let read local files from browser * - [ArrayBuffer]{@link https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/ArrayBuffer} instance with complete file content * @param {string|object} arg - argument for file open like url, see details * @returns {object} - Promise with {@link JSROOT.TFile} instance when file is opened * @example * JSROOT.openFile("https://root.cern/js/files/hsimple.root") * .then(f => console.log(`Open file ${f.getFileName()}`)); */ JSROOT.openFile = function(arg) { let file; if (JSROOT.nodejs && (typeof arg == "string")) { if (arg.indexOf("file://") == 0) file = new TNodejsFile(arg.substr(7)); else if (arg.indexOf("http") !== 0) file = new TNodejsFile(arg); } if (!file && (typeof arg === 'object') && (arg instanceof ArrayBuffer)) { file = new TFile("localfile.root"); file.assignFileContent(arg); } if (!file && (typeof arg === 'object') && arg.size && arg.name) file = new TLocalFile(arg); if (!file) file = new TFile(arg); return file._open(); } produceCustomStreamers(); jsrio.kChar = kChar; jsrio.kShort = kShort; jsrio.kInt = kInt; jsrio.kLong = kLong; jsrio.kFloat = kFloat; jsrio.kCounter = kCounter; jsrio.kCharStar = kCharStar; jsrio.kDouble = kDouble; jsrio.kDouble32 = kDouble32; jsrio.kLegacyChar = kLegacyChar; jsrio.kUChar = kUChar; jsrio.kUShort = kUShort; jsrio.kUInt = kUInt; jsrio.kULong = kULong; jsrio.kBits = kBits; jsrio.kLong64 = kLong64; jsrio.kULong64 = kULong64; jsrio.kBool = kBool; jsrio.kFloat16 = kFloat16; jsrio.kBase = kBase; jsrio.kOffsetL = kOffsetL; jsrio.kOffsetP = kOffsetP; jsrio.kObject = kObject; jsrio.kAny = kAny; jsrio.kObjectp = kObjectp; jsrio.kObjectP = kObjectP; jsrio.kTString = kTString; //jsrio.kTObject = kTObject; //jsrio.kTNamed = kTNamed; //jsrio.kAnyp = kAnyp; jsrio.kAnyP = kAnyP; jsrio.kStreamer = kStreamer; jsrio.kStreamLoop = kStreamLoop; JSROOT.TBuffer = TBuffer; JSROOT.TDirectory = TDirectory; JSROOT.TFile = TFile; JSROOT.TLocalFile = TLocalFile; JSROOT.TNodejsFile = TNodejsFile; JSROOT.IO = jsrio; if (JSROOT.nodejs) module.exports = jsrio; return jsrio; })
Initialize arrays with fill Also init directly some variables
scripts/JSRoot.io.js
Initialize arrays with fill
<ide><path>cripts/JSRoot.io.js <ide> zip_inflate_datalen = arr.byteLength, <ide> zip_inflate_pos = 0; <ide> <add> function zip_NEEDBITS(n) { <add> while (zip_bit_len < n) { <add> if (zip_inflate_pos < zip_inflate_datalen) <add> zip_bit_buf |= zip_inflate_data[zip_inflate_pos++] << zip_bit_len; <add> zip_bit_len += 8; <add> } <add> } <add> <add> function zip_GETBITS(n) { <add> return zip_bit_buf & zip_MASK_BITS[n]; <add> } <add> <add> function zip_DUMPBITS(n) { <add> zip_bit_buf >>= n; <add> zip_bit_len -= n; <add> } <add> <ide> /* objects (inflate) */ <del> <ide> function zip_HuftBuild(b, // code lengths in bits (all assumed <= BMAX) <ide> n, // number of codes (assumed <= N_MAX) <ide> s, // number of simple-valued codes (0..s-1) <ide> <ide> const BMAX = 16, // maximum bit length of any code <ide> N_MAX = 288; // maximum number of codes in any set <del> let c = new Array(BMAX+1), // bit length count table <del> lx = new Array(BMAX+1), // stack of bits per table <del> u = new Array(BMAX), // zip_HuftNode[BMAX][] table stack <del> v = new Array(N_MAX), // values in order of bit length <del> x = new Array(BMAX+1),// bit offsets, then code stack <add> let c = Array(BMAX+1).fill(0), // bit length count table <add> lx = Array(BMAX+1).fill(0), // stack of bits per table <add> u = Array(BMAX).fill(null), // zip_HuftNode[BMAX][] table stack <add> v = Array(N_MAX).fill(0), // values in order of bit length <add> x = Array(BMAX+1).fill(0),// bit offsets, then code stack <ide> r = { e: 0, b: 0, n: 0, t: null }, // new zip_HuftNode(), // table entry for structure assignment <ide> rr = null, // temporary variable, use in assignment <add> el = (n > 256) ? b[256] : BMAX, // set length of EOB code, if any <ide> a, // counter for codes of length k <del> el, // length of EOB code (value 256) <ide> f, // i repeats in table every f entries <ide> g, // maximum code length <ide> h, // table level <del> i, // counter, current code <ide> j, // counter <ide> k, // number of bits in current code <del> p, // pointer into c[], b[], or v[] <del> pidx, // index of p <add> p = b, // pointer into c[], b[], or v[] <add> pidx = 0, // index of p <ide> q, // (zip_HuftNode) points to current table <ide> w, <ide> xp, // pointer into x or c <ide> y, // number of dummy codes added <ide> z, // number of entries in current table <ide> o, <del> tail = this.root = null; // (zip_HuftList) <del> <del> for (i=0; i<=BMAX; ++i) c[i] = lx[i] = x[i] = 0; <del> for (i=0; i<BMAX; ++i) u[i] = null; <del> for (i=0; i<N_MAX; ++i) v[i] = 0; <add> tail = this.root = null, // (zip_HuftList) <add> i = n; // counter, current code <ide> <ide> // Generate counts for each bit length <del> el = (n > 256) ? b[256] : BMAX; // set length of EOB code, if any <del> p = b; pidx = 0; i = n; <ide> do { <ide> c[p[pidx++]]++; // assume all entries <= BMAX <ide> } while (--i > 0); <ide> } <ide> <ide> /* routines (inflate) */ <del> <del> function zip_NEEDBITS(n) { <del> while (zip_bit_len < n) { <del> if (zip_inflate_pos < zip_inflate_datalen) <del> zip_bit_buf |= zip_inflate_data[zip_inflate_pos++] << zip_bit_len; <del> zip_bit_len += 8; <del> } <del> } <del> <del> function zip_GETBITS(n) { <del> return zip_bit_buf & zip_MASK_BITS[n]; <del> } <del> <del> function zip_DUMPBITS(n) { <del> zip_bit_buf >>= n; <del> zip_bit_len -= n; <del> } <ide> <ide> function zip_inflate_codes(buff, off, size) { <ide> if (size == 0) return 0;
Java
apache-2.0
9cdd9545a0dc9377aadb5eaa21434eb530b3d695
0
suninformation/ymate-platform-v2,suninformation/ymate-platform-v2
/* * Copyright 2007-2016 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 net.ymate.platform.webmvc.support; import com.alibaba.fastjson.JSON; import net.ymate.platform.core.beans.annotation.Order; import net.ymate.platform.core.beans.annotation.Proxy; import net.ymate.platform.core.beans.proxy.IProxy; import net.ymate.platform.core.beans.proxy.IProxyChain; import net.ymate.platform.core.util.ClassUtils; import net.ymate.platform.validation.ValidateResult; import net.ymate.platform.validation.Validations; import net.ymate.platform.webmvc.IWebMvc; import net.ymate.platform.webmvc.RequestMeta; import net.ymate.platform.webmvc.annotation.Controller; import net.ymate.platform.webmvc.annotation.RequestMapping; import net.ymate.platform.webmvc.base.Type; import net.ymate.platform.webmvc.context.WebContext; import net.ymate.platform.webmvc.view.IView; import java.util.HashMap; import java.util.Map; /** * 请求参数代理, 用于处理控制器请求参数验证等 * * @author 刘镇 ([email protected]) on 16/3/21 下午8:42 * @version 1.0 */ @Proxy(annotation = Controller.class, order = @Order(-90)) public class RequestParametersProxy implements IProxy { public Object doProxy(IProxyChain proxyChain) throws Throwable { // 该代理仅处理控制器中声明@RequestMapping的方法 if (proxyChain.getTargetMethod().getAnnotation(RequestMapping.class) != null) { IWebMvc __owner = WebContext.getContext().getOwner(); RequestMeta __requestMeta = WebContext.getContext().getAttribute(RequestMeta.class.getName()); Map<String, Object> _paramValues = WebContext.getContext().getAttribute(RequestParametersProxy.class.getName()); // Map<String, ValidateResult> _resultMap = new HashMap<String, ValidateResult>(); if (!__requestMeta.isSingleton()) { _resultMap = Validations.get(__owner.getOwner()).validate(__requestMeta.getTargetClass(), _paramValues); } if (!__requestMeta.getMethodParamNames().isEmpty()) { _resultMap.putAll(Validations.get(__owner.getOwner()).validate(__requestMeta.getTargetClass(), __requestMeta.getMethod(), _paramValues)); } if (!_resultMap.isEmpty()) { IView _validationView = null; if (__owner.getModuleCfg().getErrorProcessor() != null) { _validationView = __owner.getModuleCfg().getErrorProcessor().onValidation(__owner, _resultMap); } if (_validationView == null) { throw new IllegalArgumentException(JSON.toJSONString(_resultMap.values())); } else { return _validationView; } } if (__owner.getModuleCfg().isParameterEscapeMode() && Type.EscapeOrder.AFTER.equals(__owner.getModuleCfg().getParameterEscapeOrder())) { // 若执行转义顺序为after时, 取出暂存在WebContext中已被转义处理的参数 _paramValues = WebContext.getContext().getAttribute(Type.EscapeOrder.class.getName()); // 因为进行了参数转义, 所以需要重新组装方法所需参数 for (int _idx = 0; _idx < __requestMeta.getMethodParamNames().size(); _idx++) { proxyChain.getMethodParams()[_idx] = _paramValues.get(__requestMeta.getMethodParamNames().get(_idx)); } } // if (!__requestMeta.isSingleton()) { ClassUtils.wrapper(proxyChain.getTargetObject()).fromMap(_paramValues); } } // return proxyChain.doProxyChain(); } }
ymate-platform-webmvc/src/main/java/net/ymate/platform/webmvc/support/RequestParametersProxy.java
/* * Copyright 2007-2016 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 net.ymate.platform.webmvc.support; import com.alibaba.fastjson.JSON; import net.ymate.platform.core.beans.annotation.Order; import net.ymate.platform.core.beans.annotation.Proxy; import net.ymate.platform.core.beans.proxy.IProxy; import net.ymate.platform.core.beans.proxy.IProxyChain; import net.ymate.platform.core.util.ClassUtils; import net.ymate.platform.validation.ValidateResult; import net.ymate.platform.validation.Validations; import net.ymate.platform.webmvc.IWebMvc; import net.ymate.platform.webmvc.RequestMeta; import net.ymate.platform.webmvc.annotation.Controller; import net.ymate.platform.webmvc.base.Type; import net.ymate.platform.webmvc.context.WebContext; import net.ymate.platform.webmvc.view.IView; import java.util.HashMap; import java.util.Map; /** * 请求参数代理, 用于处理控制器请求参数验证等 * * @author 刘镇 ([email protected]) on 16/3/21 下午8:42 * @version 1.0 */ @Proxy(annotation = Controller.class, order = @Order(-90)) public class RequestParametersProxy implements IProxy { public Object doProxy(IProxyChain proxyChain) throws Throwable { IWebMvc __owner = WebContext.getContext().getOwner(); RequestMeta __requestMeta = WebContext.getContext().getAttribute(RequestMeta.class.getName()); Map<String, Object> _paramValues = WebContext.getContext().getAttribute(RequestParametersProxy.class.getName()); // Map<String, ValidateResult> _resultMap = new HashMap<String, ValidateResult>(); if (!__requestMeta.isSingleton()) { _resultMap = Validations.get(__owner.getOwner()).validate(__requestMeta.getTargetClass(), _paramValues); } if (!__requestMeta.getMethodParamNames().isEmpty()) { _resultMap.putAll(Validations.get(__owner.getOwner()).validate(__requestMeta.getTargetClass(), __requestMeta.getMethod(), _paramValues)); } if (!_resultMap.isEmpty()) { IView _validationView = null; if (__owner.getModuleCfg().getErrorProcessor() != null) { _validationView = __owner.getModuleCfg().getErrorProcessor().onValidation(__owner, _resultMap); } if (_validationView == null) { throw new IllegalArgumentException(JSON.toJSONString(_resultMap.values())); } else { return _validationView; } } if (__owner.getModuleCfg().isParameterEscapeMode() && Type.EscapeOrder.AFTER.equals(__owner.getModuleCfg().getParameterEscapeOrder())) { // 若执行转义顺序为after时, 取出暂存在WebContext中已被转义处理的参数 _paramValues = WebContext.getContext().getAttribute(Type.EscapeOrder.class.getName()); // 因为进行了参数转义, 所以需要重新组装方法所需参数 for (int _idx = 0; _idx < __requestMeta.getMethodParamNames().size(); _idx++) { proxyChain.getMethodParams()[_idx] = _paramValues.get(__requestMeta.getMethodParamNames().get(_idx)); } } // if (!__requestMeta.isSingleton()) { ClassUtils.wrapper(proxyChain.getTargetObject()).fromMap(_paramValues); } // return proxyChain.doProxyChain(); } }
修正请求参数代理仅处理控制器中声明@RequestMapping的方法
ymate-platform-webmvc/src/main/java/net/ymate/platform/webmvc/support/RequestParametersProxy.java
修正请求参数代理仅处理控制器中声明@RequestMapping的方法
<ide><path>mate-platform-webmvc/src/main/java/net/ymate/platform/webmvc/support/RequestParametersProxy.java <ide> import net.ymate.platform.webmvc.IWebMvc; <ide> import net.ymate.platform.webmvc.RequestMeta; <ide> import net.ymate.platform.webmvc.annotation.Controller; <add>import net.ymate.platform.webmvc.annotation.RequestMapping; <ide> import net.ymate.platform.webmvc.base.Type; <ide> import net.ymate.platform.webmvc.context.WebContext; <ide> import net.ymate.platform.webmvc.view.IView; <ide> public class RequestParametersProxy implements IProxy { <ide> <ide> public Object doProxy(IProxyChain proxyChain) throws Throwable { <del> IWebMvc __owner = WebContext.getContext().getOwner(); <del> RequestMeta __requestMeta = WebContext.getContext().getAttribute(RequestMeta.class.getName()); <del> Map<String, Object> _paramValues = WebContext.getContext().getAttribute(RequestParametersProxy.class.getName()); <del> // <del> Map<String, ValidateResult> _resultMap = new HashMap<String, ValidateResult>(); <del> if (!__requestMeta.isSingleton()) { <del> _resultMap = Validations.get(__owner.getOwner()).validate(__requestMeta.getTargetClass(), _paramValues); <del> } <del> if (!__requestMeta.getMethodParamNames().isEmpty()) { <del> _resultMap.putAll(Validations.get(__owner.getOwner()).validate(__requestMeta.getTargetClass(), __requestMeta.getMethod(), _paramValues)); <del> } <del> if (!_resultMap.isEmpty()) { <del> IView _validationView = null; <del> if (__owner.getModuleCfg().getErrorProcessor() != null) { <del> _validationView = __owner.getModuleCfg().getErrorProcessor().onValidation(__owner, _resultMap); <add> // 该代理仅处理控制器中声明@RequestMapping的方法 <add> if (proxyChain.getTargetMethod().getAnnotation(RequestMapping.class) != null) { <add> IWebMvc __owner = WebContext.getContext().getOwner(); <add> RequestMeta __requestMeta = WebContext.getContext().getAttribute(RequestMeta.class.getName()); <add> Map<String, Object> _paramValues = WebContext.getContext().getAttribute(RequestParametersProxy.class.getName()); <add> // <add> Map<String, ValidateResult> _resultMap = new HashMap<String, ValidateResult>(); <add> if (!__requestMeta.isSingleton()) { <add> _resultMap = Validations.get(__owner.getOwner()).validate(__requestMeta.getTargetClass(), _paramValues); <ide> } <del> if (_validationView == null) { <del> throw new IllegalArgumentException(JSON.toJSONString(_resultMap.values())); <del> } else { <del> return _validationView; <add> if (!__requestMeta.getMethodParamNames().isEmpty()) { <add> _resultMap.putAll(Validations.get(__owner.getOwner()).validate(__requestMeta.getTargetClass(), __requestMeta.getMethod(), _paramValues)); <ide> } <del> } <del> if (__owner.getModuleCfg().isParameterEscapeMode() && Type.EscapeOrder.AFTER.equals(__owner.getModuleCfg().getParameterEscapeOrder())) { <del> // 若执行转义顺序为after时, 取出暂存在WebContext中已被转义处理的参数 <del> _paramValues = WebContext.getContext().getAttribute(Type.EscapeOrder.class.getName()); <del> // 因为进行了参数转义, 所以需要重新组装方法所需参数 <del> for (int _idx = 0; _idx < __requestMeta.getMethodParamNames().size(); _idx++) { <del> proxyChain.getMethodParams()[_idx] = _paramValues.get(__requestMeta.getMethodParamNames().get(_idx)); <add> if (!_resultMap.isEmpty()) { <add> IView _validationView = null; <add> if (__owner.getModuleCfg().getErrorProcessor() != null) { <add> _validationView = __owner.getModuleCfg().getErrorProcessor().onValidation(__owner, _resultMap); <add> } <add> if (_validationView == null) { <add> throw new IllegalArgumentException(JSON.toJSONString(_resultMap.values())); <add> } else { <add> return _validationView; <add> } <ide> } <del> } <del> // <del> if (!__requestMeta.isSingleton()) { <del> ClassUtils.wrapper(proxyChain.getTargetObject()).fromMap(_paramValues); <add> if (__owner.getModuleCfg().isParameterEscapeMode() && Type.EscapeOrder.AFTER.equals(__owner.getModuleCfg().getParameterEscapeOrder())) { <add> // 若执行转义顺序为after时, 取出暂存在WebContext中已被转义处理的参数 <add> _paramValues = WebContext.getContext().getAttribute(Type.EscapeOrder.class.getName()); <add> // 因为进行了参数转义, 所以需要重新组装方法所需参数 <add> for (int _idx = 0; _idx < __requestMeta.getMethodParamNames().size(); _idx++) { <add> proxyChain.getMethodParams()[_idx] = _paramValues.get(__requestMeta.getMethodParamNames().get(_idx)); <add> } <add> } <add> // <add> if (!__requestMeta.isSingleton()) { <add> ClassUtils.wrapper(proxyChain.getTargetObject()).fromMap(_paramValues); <add> } <ide> } <ide> // <ide> return proxyChain.doProxyChain();
JavaScript
mit
aade1d3d8761a25457a1ce0a42a3e5b2e42c072d
0
RizzleCi/Library-manager,RizzleCi/Library-manager
import React from 'react' import { connect } from 'react-redux' import { bindActionCreators } from 'redux' import { browserHistory } from 'react-router' import * as BookActions from '../../actions/book.action' import * as UserActions from '../../actions/user.action' import { Layout, Button, Modal, Table, message, Cascader } from 'antd' const { Header, Content, Sider } = Layout import Head from '../../components/head' import Sidebar from '../../components/sidebar' import BookForm from '../../components/bookForm' import AddPopover from '../../components/addPopover' import { getSideList,getFormList } from '../../api/tools' import './style.scss' class Admin extends React.Component { constructor(props) { super(props) this.state = { type: 'book', bookFormVisible: false, bookFormType: 'addbook', bookData: null } } componentWillMount() { const { fetchUserData } = this.props.userActions const token = localStorage.token if (!token) { this.showDialog({ title: '请登录', type: 'user', cb: browserHistory.push.bind(null, '/login') }) } } componentDidMount() { const { fetchUserData } = this.props.userActions const { fetchBookData, fetchTypeData } = this.props.bookActions const token = localStorage.token fetchUserData('checkManage', {token: token}).then(() => { const { resCode, manage, message } = this.props.state.user let routeTo = message.match(/过期/) ? browserHistory.push.bind(null, '/login') : browserHistory.push.bind(null, '/') if (resCode === 'error' || manage == 0) { this.showDialog({ title: manage == 0 ? '权限不足' : message, type: 'user', cb: routeTo }) } }) fetchTypeData('all') fetchBookData('book') fetchUserData('user') } changeType(type) { this.setState({type: type}) } handleFilter(value){ const { filterBook } = this.props.bookActions filterBook(value) } showDialog(options) { const { resetUserReq } = this.props.userActions const { resetBookReq } = this.props.bookActions let reset = options.type === 'user' ? resetUserReq : resetBookReq if (options.success === "success") { return Modal.success({ title: options.title, onOk: () => { options.cb() reset() return false } }) }else { return Modal.error({ title: options.title, onOk: () => { options.cb() reset() return false } }) } } setManage(name, num) { const { fetchUserData, resetReq } = this.props.userActions fetchUserData('setManage', { token: localStorage.token, name: name, manage: num }).then(() => { const { resCode, message } = this.props.state.user this.showDialog({ success: resCode, title: message, type: 'user', cb: fetchUserData.bind(null, 'user') }) }) } remove(type, id) { const { fetchUserData } = this.props.userActions const { fetchBookData } = this.props.bookActions let fetchData, data, resCode, message switch (type) { case 'user': fetchData = fetchUserData data = {token: localStorage.token, name: id} break case 'book': fetchData = fetchBookData data = {token: localStorage.token, isbn: id} break } fetchData('remove', data).then(() => { this.showDialog({ success: type === 'user' ? this.props.state.user.resCode : this.props.state.user.message, title: type === 'user' ? this.props.state.user.message : this.props.state.book.message, type: type, cb: fetchData.bind(null, type) }) }) } editBook(item) { this.setState({ bookFormVisible: true, bookFormType: 'edit', bookData: item }) } handleTypeSubmit( type, options ) { const { fetchTypeData } = this.props.bookActions fetchTypeData(type, Object.assign({token: localStorage.token}, options) ) .then(() => { const { resCode, resMessage } = this.props.state.type if(resCode === 'success') { message.success(resMessage) fetchTypeData('all') } else { message.error(resMessage) } }) } layout() { const listData = this.props.state.type.data || [] const list = getSideList( listData ) const types = getFormList( listData ) switch (this.state.type) { case 'book': const { data, filtedata } = this.props.state.book const deviceWidth = document.documentElement.clientWidth let columns = [ { title: 'ISBN', dataIndex: 'isbn', key: 'isbn' }, { title: '书名', dataIndex: 'title', key: 'title' }, { title: '作者', dataIndex: 'author', key: 'author' }, { title: '分类', dataIndex: 'type', key: 'type', render: (text) => text.join('/'), filterDropdown: ( <Cascader options={types} onChange={this.handleFilter.bind(this)}/> )}, { title: '数量', dataIndex: 'sumNum', key: 'sumNum' }, { title: '操作', dataIndex: '', key: 'admin', render: (text,record) => { if (deviceWidth < 600) { return(<div className="btns"> <Button onClick={this.editBook.bind(this, record)} type="primary">编辑</Button> <Button onClick={this.remove.bind(this, 'book', record.isbn)}>删除</Button> </div>) } else { return ( <Button.Group> <Button onClick={this.editBook.bind(this, record)} type="primary">编辑</Button> <Button onClick={this.remove.bind(this, 'book', record.isbn)}>删除</Button> </Button.Group> ) } }} ] const popovers = [<AddPopover key="add" name="添加类目" proList={listData} onSubmit={this.handleTypeSubmit.bind(this, 'addtype')} />, <AddPopover key="delet" name="删除类目" proList={listData} onSubmit={this.handleTypeSubmit.bind(this, 'removetype')} />] const bar = deviceWidth < 600 ? ( <div> <Sidebar list={list} action={this.handleFilter.bind(this)}/> <div className="btns"> { popovers } <Button type="primary" className="addbookbtn" onClick={this.showAddBookDialog.bind(this)}>添加书目</Button> </div> </div> ) : ( <Sider width={200} style={{ background: '#fff' }}> { popovers } <Sidebar list={list} action={this.handleFilter.bind(this)}/> </Sider>) return ( <Layout className="main-layout"> { bar } <Content className="main-content"> { deviceWidth < 600 ? null : ( <Content> <Button className="addbookbtn" onClick={this.showAddBookDialog.bind(this)}>添加书目</Button> </Content> )} <Table columns={columns} dataSource={filtedata || data} expandedRowRender={record => <p>{record.description}</p>} /> </Content> </Layout> ) case 'user': const { users } = this.props.state.user columns = [ { title: '用户名', dataIndex: 'name', key: 'name' }, { title: '权限', dataIndex: 'manage', key: 'manage' }, { title: '操作', dataIndex: '', key: 'admin', render: (text,record) => ( <Button.Group> {record.manage ? <Button type="primary" onClick={this.setManage.bind(this, record.name, 0)}>取消管理员</Button> : <Button type="primary" onClick={this.setManage.bind(this, record.name, 1)}>设为管理员</Button>} <Button onClick={this.remove.bind(this, 'user', record.name)}>删除</Button> </Button.Group> )} ] return ( <Layout className="main-layout"> <Content className="main-content"> <Table columns={columns} dataSource={users} /> </Content> </Layout> ) } } showAddBookDialog(){ this.setState({ bookFormType: 'addbook', bookData: null, bookFormVisible: true }) } handleSubmit( type, info ){ // addBook({isbn:test}) const { addBook, fetchBookData } = this.props.bookActions fetchBookData(type, Object.assign({token: localStorage.token}, info)).then(() => { const { resCode, message } = this.props.state.book this.showDialog({ success: resCode, title: message, type: 'book', cb: fetchBookData.bind(null, 'book') }) this.setState({ bookFormVisible: false }) }) } handleCancel(){ this.setState({ bookFormVisible: false, bookData: null }) } render(){ const { data, addBookInfo, receiveAddbookRes } = this.props.state.book const { message, name, books } = this.props.state.user const { bookInfo } = this.props.state.book const { addBook, fetchBookData } = this.props.bookActions return ( <Layout> <Head user={localStorage.userName}/> <Content className="warp"> <Content className="adminbar"> <Button onClick={this.changeType.bind(this, 'book')} >管理图书</Button> <Button onClick={this.changeType.bind(this, 'user')} >管理用户</Button> </Content> {this.layout()} </Content> <BookForm title="请输入要添加书目的ISBN" visible={this.state.bookFormVisible} data={this.state.bookData} type={this.state.bookFormType} onSubmit={this.handleSubmit.bind(this)} onCancel={this.handleCancel.bind(this)} /> </Layout> ) } } function mapState(state) { return { state: state } } function mapDispatch(dispatch) { return { bookActions: bindActionCreators(BookActions, dispatch), userActions: bindActionCreators(UserActions, dispatch) } } export default connect(mapState, mapDispatch)(Admin)
app/container/admin/index.js
import React from 'react' import { connect } from 'react-redux' import { bindActionCreators } from 'redux' import { browserHistory } from 'react-router' import * as BookActions from '../../actions/book.action' import * as UserActions from '../../actions/user.action' import { Layout, Button, Modal, Table, message, Cascader } from 'antd' const { Header, Content, Sider } = Layout import Head from '../../components/head' import Sidebar from '../../components/sidebar' import BookForm from '../../components/bookForm' import AddPopover from '../../components/addPopover' import { getSideList,getFormList } from '../../api/tools' import './style.scss' class Admin extends React.Component { constructor(props) { super(props) this.state = { type: 'book', bookFormVisible: false, bookFormType: 'addbook', bookData: null } } componentWillMount() { const { fetchUserData } = this.props.userActions const token = localStorage.token if (!token) { this.showDialog({ title: '请登录', type: 'user', cb: browserHistory.push.bind(null, '/login') }) } } componentDidMount() { const { fetchUserData } = this.props.userActions const { fetchBookData, fetchTypeData } = this.props.bookActions const token = localStorage.token fetchUserData('checkManage', {token: token}).then(() => { const { resCode, manage, message } = this.props.state.user let routeTo = message.match(/过期/) ? browserHistory.push.bind(null, '/login') : browserHistory.push.bind(null, '/') if (resCode === 'error') { this.showDialog({ title: message, type: 'user', cb: routeTo }) } }) fetchTypeData('all') fetchBookData('book') fetchUserData('user') } changeType(type) { this.setState({type: type}) } handleFilter(value){ const { filterBook } = this.props.bookActions filterBook(value) } showDialog(options) { const { resetUserReq } = this.props.userActions const { resetBookReq } = this.props.bookActions let reset = options.type === 'user' ? resetUserReq : resetBookReq if (options.success === "success") { return Modal.success({ title: options.title, onOk: () => { options.cb() reset() return false } }) }else { return Modal.error({ title: options.title, onOk: () => { options.cb() reset() return false } }) } } setManage(name, num) { const { fetchUserData, resetReq } = this.props.userActions fetchUserData('setManage', { token: localStorage.token, name: name, manage: num }).then(() => { const { resCode, message } = this.props.state.user this.showDialog({ success: resCode, title: message, type: 'user', cb: fetchUserData.bind(null, 'user') }) }) } remove(type, id) { const { fetchUserData } = this.props.userActions const { fetchBookData } = this.props.bookActions let fetchData, data, resCode, message switch (type) { case 'user': fetchData = fetchUserData data = {token: localStorage.token, name: id} break case 'book': fetchData = fetchBookData data = {token: localStorage.token, isbn: id} break } fetchData('remove', data).then(() => { this.showDialog({ success: type === 'user' ? this.props.state.user.resCode : this.props.state.user.message, title: type === 'user' ? this.props.state.book.resCode : this.props.state.book.message, type: type, cb: fetchData.bind(null, type) }) }) } editBook(item) { this.setState({ bookFormVisible: true, bookFormType: 'edit', bookData: item }) } handleTypeSubmit( type, options ) { const { fetchTypeData } = this.props.bookActions fetchTypeData(type, Object.assign({token: localStorage.token}, options) ) .then(() => { const { resCode, resMessage } = this.props.state.type if(resCode === 'success') { message.success(resMessage) fetchTypeData('all') } else { message.error(resMessage) } }) } layout() { const listData = this.props.state.type.data || [] const list = getSideList( listData ) const types = getFormList( listData ) switch (this.state.type) { case 'book': const { data, filtedata } = this.props.state.book const deviceWidth = document.documentElement.clientWidth let columns = [ { title: 'ISBN', dataIndex: 'isbn', key: 'isbn' }, { title: '书名', dataIndex: 'title', key: 'title' }, { title: '作者', dataIndex: 'author', key: 'author' }, { title: '分类', dataIndex: 'type', key: 'type', render: (text) => text.join('/'), filterDropdown: ( <Cascader options={types} onChange={this.handleFilter.bind(this)}/> )}, { title: '数量', dataIndex: 'sumNum', key: 'sumNum' }, { title: '操作', dataIndex: '', key: 'admin', render: (text,record) => { if (deviceWidth < 600) { return(<div className="btns"> <Button onClick={this.editBook.bind(this, record)} type="primary">编辑</Button> <Button onClick={this.remove.bind(this, 'book', record.isbn)}>删除</Button> </div>) } else { return ( <Button.Group> <Button onClick={this.editBook.bind(this, record)} type="primary">编辑</Button> <Button onClick={this.remove.bind(this, 'book', record.isbn)}>删除</Button> </Button.Group> ) } }} ] const popovers = [<AddPopover key="add" name="添加类目" proList={listData} onSubmit={this.handleTypeSubmit.bind(this, 'addtype')} />, <AddPopover key="delet" name="删除类目" proList={listData} onSubmit={this.handleTypeSubmit.bind(this, 'removetype')} />] const bar = deviceWidth < 600 ? ( <div> <Sidebar list={list} action={this.handleFilter.bind(this)}/> <div className="btns"> { popovers } <Button type="primary" className="addbookbtn" onClick={this.showAddBookDialog.bind(this)}>添加书目</Button> </div> </div> ) : ( <Sider width={200} style={{ background: '#fff' }}> { popovers } <Sidebar list={list} action={this.handleFilter.bind(this)}/> </Sider>) return ( <Layout className="main-layout"> { bar } <Content className="main-content"> { deviceWidth < 600 ? null : ( <Content> <Button className="addbookbtn" onClick={this.showAddBookDialog.bind(this)}>添加书目</Button> </Content> )} <Table columns={columns} dataSource={filtedata || data} expandedRowRender={record => <p>{record.description}</p>} /> </Content> </Layout> ) case 'user': const { users } = this.props.state.user columns = [ { title: '用户名', dataIndex: 'name', key: 'name' }, { title: '权限', dataIndex: 'manage', key: 'manage' }, { title: '操作', dataIndex: '', key: 'admin', render: (text,record) => ( <Button.Group> {record.manage ? <Button type="primary" onClick={this.setManage.bind(this, record.name, 0)}>取消管理员</Button> : <Button type="primary" onClick={this.setManage.bind(this, record.name, 1)}>设为管理员</Button>} <Button onClick={this.remove.bind(this, 'user', record.name)}>删除</Button> </Button.Group> )} ] return ( <Layout className="main-layout"> <Content className="main-content"> <Table columns={columns} dataSource={users} /> </Content> </Layout> ) } } showAddBookDialog(){ this.setState({ bookFormType: 'addbook', bookData: null, bookFormVisible: true }) } handleSubmit( type, info ){ // addBook({isbn:test}) const { addBook, fetchBookData } = this.props.bookActions fetchBookData(type, Object.assign({token: localStorage.token}, info)).then(() => { const { resCode, message } = this.props.state.book this.showDialog({ success: resCode, title: message, type: 'book', cb: fetchBookData.bind(null, 'book') }) this.setState({ bookFormVisible: false }) }) } handleCancel(){ this.setState({ bookFormVisible: false, bookData: null }) } render(){ const { data, addBookInfo, receiveAddbookRes } = this.props.state.book const { message, name, books } = this.props.state.user const { bookInfo } = this.props.state.book const { addBook, fetchBookData } = this.props.bookActions return ( <Layout> <Head user={localStorage.userName}/> <Content className="warp"> <Content className="adminbar"> <Button onClick={this.changeType.bind(this, 'book')} >管理图书</Button> <Button onClick={this.changeType.bind(this, 'user')} >管理用户</Button> </Content> {this.layout()} </Content> <BookForm title="请输入要添加书目的ISBN" visible={this.state.bookFormVisible} data={this.state.bookData} type={this.state.bookFormType} onSubmit={this.handleSubmit.bind(this)} onCancel={this.handleCancel.bind(this)} /> </Layout> ) } } function mapState(state) { return { state: state } } function mapDispatch(dispatch) { return { bookActions: bindActionCreators(BookActions, dispatch), userActions: bindActionCreators(UserActions, dispatch) } } export default connect(mapState, mapDispatch)(Admin)
debug
app/container/admin/index.js
debug
<ide><path>pp/container/admin/index.js <ide> fetchUserData('checkManage', {token: token}).then(() => { <ide> const { resCode, manage, message } = this.props.state.user <ide> let routeTo = message.match(/过期/) ? browserHistory.push.bind(null, '/login') : browserHistory.push.bind(null, '/') <del> if (resCode === 'error') { <add> if (resCode === 'error' || manage == 0) { <ide> this.showDialog({ <del> title: message, <add> title: manage == 0 ? '权限不足' : message, <ide> type: 'user', <ide> cb: routeTo <ide> }) <ide> fetchData('remove', data).then(() => { <ide> this.showDialog({ <ide> success: type === 'user' ? this.props.state.user.resCode : this.props.state.user.message, <del> title: type === 'user' ? this.props.state.book.resCode : this.props.state.book.message, <add> title: type === 'user' ? this.props.state.user.message : this.props.state.book.message, <ide> type: type, <ide> cb: fetchData.bind(null, type) <ide> })
Java
apache-2.0
e4c53c4400b840b081bd2a3e3a67ffde9ad9b81b
0
code4craft/webmagic,sanlingdd/personalLinkedProfilesIn,sanlingdd/personalLinkedProfilesIn,sanlingdd/personalLinkedProfilesIn,code4craft/webmagic,sanlingdd/personalLinkedProfilesIn,code4craft/webmagic,sanlingdd/personalLinkedProfilesIn,code4craft/webmagic,code4craft/webmagic,zhuyuesut/webmagic,code4craft/webmagic,zhuyuesut/webmagic,zhuyuesut/webmagic,code4craft/webmagic,zhuyuesut/webmagic,zhuyuesut/webmagic,sanlingdd/personalLinkedProfilesIn,zhuyuesut/webmagic
package us.codecraft.webmagic.samples; import us.codecraft.webmagic.Page; import us.codecraft.webmagic.Site; import us.codecraft.webmagic.Spider; import us.codecraft.webmagic.downloader.selenium.SeleniumDownloader; import us.codecraft.webmagic.pipeline.FilePipeline; import us.codecraft.webmagic.processor.PageProcessor; import us.codecraft.webmagic.scheduler.RedisScheduler; /** * 花瓣网抽取器。<br> * 使用Selenium做页面动态渲染。<br> * @author [email protected] <br> * @date: 13-7-26 <br> * Time: 下午4:08 <br> */ public class HuabanProcessor implements PageProcessor { private Site site; @Override public void process(Page page) { page.addTargetRequests(page.getHtml().links().regex("http://huaban\\.com/.*").all()); if (page.getUrl().toString().contains("pins")) { page.putField("img", page.getHtml().xpath("//div[@id='pin_img']/img/@src").toString()); } else { page.getResultItems().setSkip(true); } } @Override public Site getSite() { if (site == null) { site = Site.me().setDomain("huaban.com").addStartUrl("http://huaban.com/").setSleepTime(0); } return site; } public static void main(String[] args) { Spider.create(new HuabanProcessor()).thread(5) .scheduler(new RedisScheduler("localhost")) .pipeline(new FilePipeline("/data/webmagic/test/")) .downloader(new SeleniumDownloader("/Users/yihua/Downloads/chromedriver")) .runAsync(); } }
webmagic-samples/src/main/java/us/codecraft/webmagic/samples/HuabanProcessor.java
package us.codecraft.webmagic.samples; import us.codecraft.webmagic.Page; import us.codecraft.webmagic.Site; import us.codecraft.webmagic.Spider; import us.codecraft.webmagic.pipeline.FilePipeline; import us.codecraft.webmagic.processor.PageProcessor; import us.codecraft.webmagic.scheduler.RedisScheduler; import us.codecraft.webmagic.downloader.downloader.SeleniumDownloader; /** * 花瓣网抽取器。<br> * 使用Selenium做页面动态渲染。<br> * @author [email protected] <br> * @date: 13-7-26 <br> * Time: 下午4:08 <br> */ public class HuabanProcessor implements PageProcessor { private Site site; @Override public void process(Page page) { page.addTargetRequests(page.getHtml().links().regex("http://huaban\\.com/.*").all()); if (page.getUrl().toString().contains("pins")) { page.putField("img", page.getHtml().xpath("//div[@id='pin_img']/img/@src").toString()); } else { page.getResultItems().setSkip(true); } } @Override public Site getSite() { if (site == null) { site = Site.me().setDomain("huaban.com").addStartUrl("http://huaban.com/").setSleepTime(0); } return site; } public static void main(String[] args) { Spider.create(new HuabanProcessor()).thread(5) .scheduler(new RedisScheduler("localhost")) .pipeline(new FilePipeline("/data/webmagic/test/")) .downloader(new SeleniumDownloader("/Users/yihua/Downloads/chromedriver")) .runAsync(); } }
fix compile error
webmagic-samples/src/main/java/us/codecraft/webmagic/samples/HuabanProcessor.java
fix compile error
<ide><path>ebmagic-samples/src/main/java/us/codecraft/webmagic/samples/HuabanProcessor.java <ide> import us.codecraft.webmagic.Page; <ide> import us.codecraft.webmagic.Site; <ide> import us.codecraft.webmagic.Spider; <add>import us.codecraft.webmagic.downloader.selenium.SeleniumDownloader; <ide> import us.codecraft.webmagic.pipeline.FilePipeline; <ide> import us.codecraft.webmagic.processor.PageProcessor; <ide> import us.codecraft.webmagic.scheduler.RedisScheduler; <del>import us.codecraft.webmagic.downloader.downloader.SeleniumDownloader; <ide> <ide> /** <ide> * 花瓣网抽取器。<br>
Java
agpl-3.0
d716220f823f558911518d011785e52e3d31501c
0
JanMarvin/rstudio,JanMarvin/rstudio,JanMarvin/rstudio,JanMarvin/rstudio,JanMarvin/rstudio,JanMarvin/rstudio,JanMarvin/rstudio,JanMarvin/rstudio,JanMarvin/rstudio
/* * Source.java * * Copyright (C) 2009-17 by RStudio, Inc. * * Unless you have received this program directly from RStudio pursuant * to the terms of a commercial license agreement with RStudio, then * this program is licensed to you under the terms of version 3 of the * GNU Affero General Public License. This program is distributed WITHOUT * ANY EXPRESS OR IMPLIED WARRANTY, INCLUDING THOSE OF NON-INFRINGEMENT, * MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE. Please refer to the * AGPL (http://www.gnu.org/licenses/agpl-3.0.txt) for more details. * */ package org.rstudio.studio.client.workbench.views.source; import com.google.gwt.core.client.JavaScriptObject; import com.google.gwt.core.client.JsArray; import com.google.gwt.core.client.JsArrayString; import com.google.gwt.core.client.Scheduler; import com.google.gwt.core.client.Scheduler.ScheduledCommand; import com.google.gwt.event.dom.client.ChangeEvent; import com.google.gwt.event.dom.client.ChangeHandler; import com.google.gwt.event.dom.client.KeyCodes; import com.google.gwt.event.logical.shared.CloseEvent; import com.google.gwt.event.logical.shared.CloseHandler; import com.google.gwt.event.logical.shared.HasBeforeSelectionHandlers; import com.google.gwt.event.logical.shared.HasSelectionHandlers; import com.google.gwt.event.logical.shared.SelectionEvent; import com.google.gwt.event.logical.shared.SelectionHandler; import com.google.gwt.event.logical.shared.ValueChangeEvent; import com.google.gwt.event.logical.shared.ValueChangeHandler; import com.google.gwt.event.shared.HandlerRegistration; import com.google.gwt.json.client.JSONString; import com.google.gwt.json.client.JSONValue; import com.google.gwt.resources.client.ImageResource; import com.google.gwt.user.client.Command; import com.google.gwt.user.client.Event; import com.google.gwt.user.client.Event.NativePreviewEvent; import com.google.gwt.user.client.Event.NativePreviewHandler; import com.google.gwt.user.client.Timer; import com.google.gwt.user.client.Window; import com.google.gwt.user.client.ui.IsWidget; import com.google.gwt.user.client.ui.Widget; import com.google.inject.Inject; import com.google.inject.Provider; import org.rstudio.core.client.*; import org.rstudio.core.client.command.AppCommand; import org.rstudio.core.client.command.Handler; import org.rstudio.core.client.command.KeyboardShortcut; import org.rstudio.core.client.command.ShortcutManager; import org.rstudio.core.client.events.*; import org.rstudio.core.client.files.FileSystemItem; import org.rstudio.core.client.js.JsObject; import org.rstudio.core.client.widget.Operation; import org.rstudio.core.client.widget.OperationWithInput; import org.rstudio.core.client.widget.ProgressIndicator; import org.rstudio.core.client.widget.ProgressOperationWithInput; import org.rstudio.studio.client.RStudioGinjector; import org.rstudio.studio.client.application.ApplicationAction; import org.rstudio.studio.client.application.ApplicationUtils; import org.rstudio.studio.client.application.Desktop; import org.rstudio.studio.client.application.events.CrossWindowEvent; import org.rstudio.studio.client.application.events.EventBus; import org.rstudio.studio.client.common.FileDialogs; import org.rstudio.studio.client.common.FilePathUtils; import org.rstudio.studio.client.common.GlobalDisplay; import org.rstudio.studio.client.common.GlobalProgressDelayer; import org.rstudio.studio.client.common.SimpleRequestCallback; import org.rstudio.studio.client.common.dependencies.DependencyManager; import org.rstudio.studio.client.common.filetypes.EditableFileType; import org.rstudio.studio.client.common.filetypes.FileTypeRegistry; import org.rstudio.studio.client.common.filetypes.TextFileType; import org.rstudio.studio.client.common.filetypes.events.OpenPresentationSourceFileEvent; import org.rstudio.studio.client.common.filetypes.events.OpenSourceFileEvent; import org.rstudio.studio.client.common.filetypes.events.OpenSourceFileHandler; import org.rstudio.studio.client.common.filetypes.model.NavigationMethods; import org.rstudio.studio.client.common.rnw.RnwWeave; import org.rstudio.studio.client.common.rnw.RnwWeaveRegistry; import org.rstudio.studio.client.common.satellite.Satellite; import org.rstudio.studio.client.common.synctex.Synctex; import org.rstudio.studio.client.common.synctex.events.SynctexStatusChangedEvent; import org.rstudio.studio.client.events.GetEditorContextEvent; import org.rstudio.studio.client.events.GetEditorContextEvent.DocumentSelection; import org.rstudio.studio.client.events.ReplaceRangesEvent; import org.rstudio.studio.client.events.ReplaceRangesEvent.ReplacementData; import org.rstudio.studio.client.events.SetSelectionRangesEvent; import org.rstudio.studio.client.rmarkdown.model.RmdChosenTemplate; import org.rstudio.studio.client.rmarkdown.model.RmdFrontMatter; import org.rstudio.studio.client.rmarkdown.model.RmdOutputFormat; import org.rstudio.studio.client.rmarkdown.model.RmdTemplateData; import org.rstudio.studio.client.server.ServerError; import org.rstudio.studio.client.server.ServerRequestCallback; import org.rstudio.studio.client.server.VoidServerRequestCallback; import org.rstudio.studio.client.workbench.ConsoleEditorProvider; import org.rstudio.studio.client.workbench.MainWindowObject; import org.rstudio.studio.client.workbench.FileMRUList; import org.rstudio.studio.client.workbench.WorkbenchContext; import org.rstudio.studio.client.workbench.codesearch.model.SearchPathFunctionDefinition; import org.rstudio.studio.client.workbench.commands.Commands; import org.rstudio.studio.client.workbench.events.ZoomPaneEvent; import org.rstudio.studio.client.workbench.model.ClientState; import org.rstudio.studio.client.workbench.model.RemoteFileSystemContext; import org.rstudio.studio.client.workbench.model.Session; import org.rstudio.studio.client.workbench.model.SessionInfo; import org.rstudio.studio.client.workbench.model.SessionUtils; import org.rstudio.studio.client.workbench.model.UnsavedChangesItem; import org.rstudio.studio.client.workbench.model.UnsavedChangesTarget; import org.rstudio.studio.client.workbench.model.helper.IntStateValue; import org.rstudio.studio.client.workbench.prefs.model.UIPrefs; import org.rstudio.studio.client.workbench.snippets.SnippetHelper; import org.rstudio.studio.client.workbench.snippets.model.SnippetsChangedEvent; import org.rstudio.studio.client.workbench.ui.unsaved.UnsavedChangesDialog; import org.rstudio.studio.client.workbench.views.console.shell.editor.InputEditorDisplay; import org.rstudio.studio.client.workbench.views.data.events.ViewDataEvent; import org.rstudio.studio.client.workbench.views.data.events.ViewDataHandler; import org.rstudio.studio.client.workbench.views.environment.events.DebugModeChangedEvent; import org.rstudio.studio.client.workbench.views.output.find.events.FindInFilesEvent; import org.rstudio.studio.client.workbench.views.source.NewShinyWebApplication.Result; import org.rstudio.studio.client.workbench.views.source.SourceWindowManager.NavigationResult; import org.rstudio.studio.client.workbench.views.source.editors.EditingTarget; import org.rstudio.studio.client.workbench.views.source.editors.EditingTargetSource; import org.rstudio.studio.client.workbench.views.source.editors.codebrowser.CodeBrowserEditingTarget; import org.rstudio.studio.client.workbench.views.source.editors.data.DataEditingTarget; import org.rstudio.studio.client.workbench.views.source.editors.explorer.ObjectExplorerEditingTarget; import org.rstudio.studio.client.workbench.views.source.editors.explorer.events.OpenObjectExplorerEvent; import org.rstudio.studio.client.workbench.views.source.editors.explorer.model.ObjectExplorerHandle; import org.rstudio.studio.client.workbench.views.source.editors.profiler.OpenProfileEvent; import org.rstudio.studio.client.workbench.views.source.editors.profiler.model.ProfilerContents; import org.rstudio.studio.client.workbench.views.source.editors.text.AceEditor; import org.rstudio.studio.client.workbench.views.source.editors.text.DocDisplay; import org.rstudio.studio.client.workbench.views.source.editors.text.TextEditingTarget; import org.rstudio.studio.client.workbench.views.source.editors.text.TextEditingTargetPresentationHelper; import org.rstudio.studio.client.workbench.views.source.editors.text.TextEditingTargetRMarkdownHelper; import org.rstudio.studio.client.workbench.views.source.editors.text.ace.AceEditorNative; import org.rstudio.studio.client.workbench.views.source.editors.text.ace.Position; import org.rstudio.studio.client.workbench.views.source.editors.text.ace.Range; import org.rstudio.studio.client.workbench.views.source.editors.text.ace.Selection; import org.rstudio.studio.client.workbench.views.source.editors.text.events.FileTypeChangedEvent; import org.rstudio.studio.client.workbench.views.source.editors.text.events.FileTypeChangedHandler; import org.rstudio.studio.client.workbench.views.source.editors.text.events.NewWorkingCopyEvent; import org.rstudio.studio.client.workbench.views.source.editors.text.events.SourceOnSaveChangedEvent; import org.rstudio.studio.client.workbench.views.source.editors.text.events.SourceOnSaveChangedHandler; import org.rstudio.studio.client.workbench.views.source.editors.text.ui.NewRMarkdownDialog; import org.rstudio.studio.client.workbench.views.source.editors.text.ui.NewRdDialog; import org.rstudio.studio.client.workbench.views.source.events.*; import org.rstudio.studio.client.workbench.views.source.model.ContentItem; import org.rstudio.studio.client.workbench.views.source.model.DataItem; import org.rstudio.studio.client.workbench.views.source.model.DocTabDragParams; import org.rstudio.studio.client.workbench.views.source.model.RdShellResult; import org.rstudio.studio.client.workbench.views.source.model.SourceDocument; import org.rstudio.studio.client.workbench.views.source.model.SourceDocumentResult; import org.rstudio.studio.client.workbench.views.source.model.SourceNavigation; import org.rstudio.studio.client.workbench.views.source.model.SourceNavigationHistory; import org.rstudio.studio.client.workbench.views.source.model.SourcePosition; import org.rstudio.studio.client.workbench.views.source.model.SourceServerOperations; import java.util.ArrayList; import java.util.HashSet; import java.util.LinkedList; import java.util.Queue; public class Source implements InsertSourceHandler, IsWidget, OpenSourceFileHandler, TabClosingHandler, TabCloseHandler, TabReorderHandler, SelectionHandler<Integer>, TabClosedHandler, FileEditHandler, ShowContentHandler, ShowDataHandler, CodeBrowserNavigationHandler, CodeBrowserFinishedHandler, CodeBrowserHighlightEvent.Handler, SourceExtendedTypeDetectedEvent.Handler, BeforeShowHandler, SnippetsChangedEvent.Handler, PopoutDocEvent.Handler, DocWindowChangedEvent.Handler, DocTabDragInitiatedEvent.Handler, PopoutDocInitiatedEvent.Handler, DebugModeChangedEvent.Handler, OpenProfileEvent.Handler, OpenObjectExplorerEvent.Handler, ReplaceRangesEvent.Handler, SetSelectionRangesEvent.Handler, GetEditorContextEvent.Handler { public interface Display extends IsWidget, HasTabClosingHandlers, HasTabCloseHandlers, HasTabClosedHandlers, HasTabReorderHandlers, HasBeforeSelectionHandlers<Integer>, HasSelectionHandlers<Integer> { void addTab(Widget widget, ImageResource icon, String docId, String name, String tooltip, Integer position, boolean switchToTab); void selectTab(int tabIndex); void selectTab(Widget widget); int getTabCount(); int getActiveTabIndex(); void closeTab(Widget widget, boolean interactive); void closeTab(Widget widget, boolean interactive, Command onClosed); void closeTab(int index, boolean interactive); void closeTab(int index, boolean interactive, Command onClosed); void moveTab(int index, int delta); void setDirty(Widget widget, boolean dirty); void manageChevronVisibility(); void showOverflowPopup(); void cancelTabDrag(); void showUnsavedChangesDialog( String title, ArrayList<UnsavedChangesTarget> dirtyTargets, OperationWithInput<UnsavedChangesDialog.Result> saveOperation, Command onCancelled); void ensureVisible(); void renameTab(Widget child, ImageResource icon, String value, String tooltip); HandlerRegistration addBeforeShowHandler(BeforeShowHandler handler); } public interface CPSEditingTargetCommand { void execute(EditingTarget editingTarget, Command continuation); } @Inject public Source(Commands commands, Display view, SourceServerOperations server, EditingTargetSource editingTargetSource, FileTypeRegistry fileTypeRegistry, GlobalDisplay globalDisplay, FileDialogs fileDialogs, RemoteFileSystemContext fileContext, EventBus events, final Session session, Synctex synctex, WorkbenchContext workbenchContext, Provider<FileMRUList> pMruList, UIPrefs uiPrefs, Satellite satellite, ConsoleEditorProvider consoleEditorProvider, RnwWeaveRegistry rnwWeaveRegistry, DependencyManager dependencyManager, SourceWindowManager windowManager) { commands_ = commands; view_ = view; server_ = server; editingTargetSource_ = editingTargetSource; fileTypeRegistry_ = fileTypeRegistry; globalDisplay_ = globalDisplay; fileDialogs_ = fileDialogs; fileContext_ = fileContext; rmarkdown_ = new TextEditingTargetRMarkdownHelper(); events_ = events; session_ = session; synctex_ = synctex; workbenchContext_ = workbenchContext; pMruList_ = pMruList; uiPrefs_ = uiPrefs; consoleEditorProvider_ = consoleEditorProvider; rnwWeaveRegistry_ = rnwWeaveRegistry; dependencyManager_ = dependencyManager; windowManager_ = windowManager; vimCommands_ = new SourceVimCommands(); view_.addTabClosingHandler(this); view_.addTabCloseHandler(this); view_.addTabClosedHandler(this); view_.addTabReorderHandler(this); view_.addSelectionHandler(this); view_.addBeforeShowHandler(this); dynamicCommands_ = new HashSet<AppCommand>(); dynamicCommands_.add(commands.saveSourceDoc()); dynamicCommands_.add(commands.reopenSourceDocWithEncoding()); dynamicCommands_.add(commands.saveSourceDocAs()); dynamicCommands_.add(commands.saveSourceDocWithEncoding()); dynamicCommands_.add(commands.printSourceDoc()); dynamicCommands_.add(commands.vcsFileLog()); dynamicCommands_.add(commands.vcsFileDiff()); dynamicCommands_.add(commands.vcsFileRevert()); dynamicCommands_.add(commands.executeCode()); dynamicCommands_.add(commands.executeCodeWithoutFocus()); dynamicCommands_.add(commands.executeAllCode()); dynamicCommands_.add(commands.executeToCurrentLine()); dynamicCommands_.add(commands.executeFromCurrentLine()); dynamicCommands_.add(commands.executeCurrentFunction()); dynamicCommands_.add(commands.executeCurrentSection()); dynamicCommands_.add(commands.executeLastCode()); dynamicCommands_.add(commands.insertChunk()); dynamicCommands_.add(commands.insertSection()); dynamicCommands_.add(commands.executeSetupChunk()); dynamicCommands_.add(commands.executePreviousChunks()); dynamicCommands_.add(commands.executeSubsequentChunks()); dynamicCommands_.add(commands.executeCurrentChunk()); dynamicCommands_.add(commands.executeNextChunk()); dynamicCommands_.add(commands.sourceActiveDocument()); dynamicCommands_.add(commands.sourceActiveDocumentWithEcho()); dynamicCommands_.add(commands.knitDocument()); dynamicCommands_.add(commands.previewHTML()); dynamicCommands_.add(commands.compilePDF()); dynamicCommands_.add(commands.compileNotebook()); dynamicCommands_.add(commands.synctexSearch()); dynamicCommands_.add(commands.popoutDoc()); dynamicCommands_.add(commands.returnDocToMain()); dynamicCommands_.add(commands.findReplace()); dynamicCommands_.add(commands.findNext()); dynamicCommands_.add(commands.findPrevious()); dynamicCommands_.add(commands.findFromSelection()); dynamicCommands_.add(commands.replaceAndFind()); dynamicCommands_.add(commands.extractFunction()); dynamicCommands_.add(commands.extractLocalVariable()); dynamicCommands_.add(commands.commentUncomment()); dynamicCommands_.add(commands.reindent()); dynamicCommands_.add(commands.reflowComment()); dynamicCommands_.add(commands.jumpTo()); dynamicCommands_.add(commands.jumpToMatching()); dynamicCommands_.add(commands.goToHelp()); dynamicCommands_.add(commands.goToFunctionDefinition()); dynamicCommands_.add(commands.setWorkingDirToActiveDoc()); dynamicCommands_.add(commands.debugDumpContents()); dynamicCommands_.add(commands.debugImportDump()); dynamicCommands_.add(commands.goToLine()); dynamicCommands_.add(commands.checkSpelling()); dynamicCommands_.add(commands.codeCompletion()); dynamicCommands_.add(commands.findUsages()); dynamicCommands_.add(commands.debugBreakpoint()); dynamicCommands_.add(commands.vcsViewOnGitHub()); dynamicCommands_.add(commands.vcsBlameOnGitHub()); dynamicCommands_.add(commands.editRmdFormatOptions()); dynamicCommands_.add(commands.reformatCode()); dynamicCommands_.add(commands.showDiagnosticsActiveDocument()); dynamicCommands_.add(commands.renameInScope()); dynamicCommands_.add(commands.insertRoxygenSkeleton()); dynamicCommands_.add(commands.expandSelection()); dynamicCommands_.add(commands.shrinkSelection()); dynamicCommands_.add(commands.toggleDocumentOutline()); dynamicCommands_.add(commands.knitWithParameters()); dynamicCommands_.add(commands.clearKnitrCache()); dynamicCommands_.add(commands.goToNextSection()); dynamicCommands_.add(commands.goToPrevSection()); dynamicCommands_.add(commands.goToNextChunk()); dynamicCommands_.add(commands.goToPrevChunk()); dynamicCommands_.add(commands.profileCode()); dynamicCommands_.add(commands.profileCodeWithoutFocus()); dynamicCommands_.add(commands.saveProfileAs()); dynamicCommands_.add(commands.restartRClearOutput()); dynamicCommands_.add(commands.restartRRunAllChunks()); dynamicCommands_.add(commands.notebookCollapseAllOutput()); dynamicCommands_.add(commands.notebookExpandAllOutput()); dynamicCommands_.add(commands.notebookClearOutput()); dynamicCommands_.add(commands.notebookClearAllOutput()); dynamicCommands_.add(commands.notebookToggleExpansion()); for (AppCommand command : dynamicCommands_) { command.setVisible(false); command.setEnabled(false); } // fake shortcuts for commands which we handle at a lower level commands.goToHelp().setShortcut(new KeyboardShortcut(112)); commands.goToFunctionDefinition().setShortcut(new KeyboardShortcut(113)); commands.codeCompletion().setShortcut( new KeyboardShortcut(KeyCodes.KEY_TAB)); // See bug 3673 and https://bugs.webkit.org/show_bug.cgi?id=41016 if (BrowseCap.isMacintosh()) { ShortcutManager.INSTANCE.register( KeyboardShortcut.META | KeyboardShortcut.ALT, 192, commands.executeNextChunk(), "Execute", commands.executeNextChunk().getMenuLabel(false), ""); } events.addHandler(ShowContentEvent.TYPE, this); events.addHandler(ShowDataEvent.TYPE, this); events.addHandler(OpenObjectExplorerEvent.TYPE, this); events.addHandler(ViewDataEvent.TYPE, new ViewDataHandler() { public void onViewData(ViewDataEvent event) { server_.newDocument( FileTypeRegistry.DATAFRAME.getTypeId(), null, JsObject.createJsObject(), new SimpleRequestCallback<SourceDocument>("Edit Data Frame") { public void onResponseReceived(SourceDocument response) { addTab(response, OPEN_INTERACTIVE); } }); } }); events.addHandler(CodeBrowserNavigationEvent.TYPE, this); events.addHandler(CodeBrowserFinishedEvent.TYPE, this); events.addHandler(CodeBrowserHighlightEvent.TYPE, this); events.addHandler(FileTypeChangedEvent.TYPE, new FileTypeChangedHandler() { public void onFileTypeChanged(FileTypeChangedEvent event) { manageCommands(); } }); events.addHandler(SourceOnSaveChangedEvent.TYPE, new SourceOnSaveChangedHandler() { @Override public void onSourceOnSaveChanged(SourceOnSaveChangedEvent event) { manageSaveCommands(); } }); events.addHandler(SwitchToDocEvent.TYPE, new SwitchToDocHandler() { public void onSwitchToDoc(SwitchToDocEvent event) { ensureVisible(false); setPhysicalTabIndex(event.getSelectedIndex()); // Fire an activation event just to ensure the activated // tab gets focus commands_.activateSource().execute(); } }); events.addHandler(SourceFileSavedEvent.TYPE, new SourceFileSavedHandler() { public void onSourceFileSaved(SourceFileSavedEvent event) { pMruList_.get().add(event.getPath()); } }); events.addHandler(SourcePathChangedEvent.TYPE, new SourcePathChangedEvent.Handler() { @Override public void onSourcePathChanged(final SourcePathChangedEvent event) { inEditorForPath(event.getFrom(), new OperationWithInput<EditingTarget>() { @Override public void execute(EditingTarget input) { FileSystemItem toPath = FileSystemItem.createFile(event.getTo()); if (input instanceof TextEditingTarget) { // for text files, notify the editing surface so it can // react to the new file type ((TextEditingTarget)input).setPath(toPath); } else { // for other files, just rename the tab input.getName().setValue(toPath.getName(), true); } events_.fireEvent(new SourceFileSavedEvent( input.getId(), event.getTo())); } }); } }); events.addHandler(SourceNavigationEvent.TYPE, new SourceNavigationHandler() { @Override public void onSourceNavigation(SourceNavigationEvent event) { if (!suspendSourceNavigationAdding_) { sourceNavigationHistory_.add(event.getNavigation()); } } }); events.addHandler(SourceExtendedTypeDetectedEvent.TYPE, this); sourceNavigationHistory_.addChangeHandler(new ChangeHandler() { @Override public void onChange(ChangeEvent event) { manageSourceNavigationCommands(); } }); events.addHandler(SynctexStatusChangedEvent.TYPE, new SynctexStatusChangedEvent.Handler() { @Override public void onSynctexStatusChanged(SynctexStatusChangedEvent event) { manageSynctexCommands(); } }); events.addHandler(CollabEditStartedEvent.TYPE, new CollabEditStartedEvent.Handler() { @Override public void onCollabEditStarted(final CollabEditStartedEvent collab) { inEditorForPath(collab.getStartParams().getPath(), new OperationWithInput<EditingTarget>() { @Override public void execute(EditingTarget editor) { editor.beginCollabSession(collab.getStartParams()); } }); } }); events.addHandler(CollabEditEndedEvent.TYPE, new CollabEditEndedEvent.Handler() { @Override public void onCollabEditEnded(final CollabEditEndedEvent collab) { inEditorForPath(collab.getPath(), new OperationWithInput<EditingTarget>() { @Override public void execute(EditingTarget editor) { editor.endCollabSession(); } }); } }); events.addHandler(NewWorkingCopyEvent.TYPE, new NewWorkingCopyEvent.Handler() { @Override public void onNewWorkingCopy(NewWorkingCopyEvent event) { newDoc(event.getType(), event.getContents(), null); } }); events.addHandler(PopoutDocEvent.TYPE, this); events.addHandler(DocWindowChangedEvent.TYPE, this); events.addHandler(DocTabDragInitiatedEvent.TYPE, this); events.addHandler(PopoutDocInitiatedEvent.TYPE, this); events.addHandler(DebugModeChangedEvent.TYPE, this); events.addHandler(ReplaceRangesEvent.TYPE, this); events.addHandler(GetEditorContextEvent.TYPE, this); events.addHandler(SetSelectionRangesEvent.TYPE, this); events.addHandler(OpenProfileEvent.TYPE, this); // Suppress 'CTRL + ALT + SHIFT + click' to work around #2483 in Ace Event.addNativePreviewHandler(new NativePreviewHandler() { @Override public void onPreviewNativeEvent(NativePreviewEvent event) { int type = event.getTypeInt(); if (type == Event.ONMOUSEDOWN || type == Event.ONMOUSEUP) { int modifier = KeyboardShortcut.getModifierValue(event.getNativeEvent()); if (modifier == (KeyboardShortcut.ALT | KeyboardShortcut.CTRL | KeyboardShortcut.SHIFT)) { event.cancel(); return; } } } }); restoreDocuments(session); // get the key to use for active tab persistence; use ordinal-based key // for source windows rather than their ID to avoid unbounded accumulation String activeTabKey = KEY_ACTIVETAB; if (!SourceWindowManager.isMainSourceWindow()) activeTabKey += "SourceWindow" + windowManager_.getSourceWindowOrdinal(); new IntStateValue(MODULE_SOURCE, activeTabKey, ClientState.PROJECT_PERSISTENT, session.getSessionInfo().getClientState()) { @Override protected void onInit(Integer value) { if (value == null) return; if (value >= 0 && view_.getTabCount() > value) view_.selectTab(value); if (view_.getTabCount() > 0 && view_.getActiveTabIndex() >= 0) { editors_.get(view_.getActiveTabIndex()).onInitiallyLoaded(); } // clear the history manager sourceNavigationHistory_.clear(); } @Override protected Integer getValue() { return getPhysicalTabIndex(); } }; AceEditorNative.syncUiPrefs(uiPrefs_); // sync UI prefs with shortcut manager if (uiPrefs_.useVimMode().getGlobalValue()) ShortcutManager.INSTANCE.setEditorMode(KeyboardShortcut.MODE_VIM); else if (uiPrefs_.enableEmacsKeybindings().getGlobalValue()) ShortcutManager.INSTANCE.setEditorMode(KeyboardShortcut.MODE_EMACS); else ShortcutManager.INSTANCE.setEditorMode(KeyboardShortcut.MODE_DEFAULT); initialized_ = true; // As tabs were added before, manageCommands() was suppressed due to // initialized_ being false, so we need to run it explicitly manageCommands(); // Same with this event fireDocTabsChanged(); // open project or edit_published docs (only for main source window) if (SourceWindowManager.isMainSourceWindow()) { openProjectDocs(session); openEditPublishedDocs(); } // add vim commands initVimCommands(); } private boolean consoleEditorHadFocusLast() { String id = MainWindowObject.lastFocusedEditor().get(); return "rstudio_console_input".equals(id); } private void withTarget(String id, CommandWithArg<TextEditingTarget> command, Command onFailure) { EditingTarget target = StringUtil.isNullOrEmpty(id) ? activeEditor_ : getEditingTargetForId(id); if (target == null) { if (onFailure != null) onFailure.execute(); return; } if (!(target instanceof TextEditingTarget)) { if (onFailure != null) onFailure.execute(); return; } command.execute((TextEditingTarget) target); } private void getEditorContext(String id, String path, DocDisplay docDisplay) { AceEditor editor = (AceEditor) docDisplay; Selection selection = editor.getNativeSelection(); Range[] ranges = selection.getAllRanges(); JsArray<DocumentSelection> docSelections = JavaScriptObject.createArray().cast(); for (int i = 0; i < ranges.length; i++) { docSelections.push(DocumentSelection.create( ranges[i], editor.getTextForRange(ranges[i]))); } id = StringUtil.notNull(id); path = StringUtil.notNull(path); GetEditorContextEvent.SelectionData data = GetEditorContextEvent.SelectionData.create(id, path, editor.getCode(), docSelections); server_.getEditorContextCompleted(data, new VoidServerRequestCallback()); } private void withTarget(String id, CommandWithArg<TextEditingTarget> command) { withTarget(id, command, null); } private void initVimCommands() { vimCommands_.save(this); vimCommands_.selectTabIndex(this); vimCommands_.selectNextTab(this); vimCommands_.selectPreviousTab(this); vimCommands_.closeActiveTab(this); vimCommands_.closeAllTabs(this); vimCommands_.createNewDocument(this); vimCommands_.saveAndCloseActiveTab(this); vimCommands_.readFile(this, uiPrefs_.defaultEncoding().getValue()); vimCommands_.runRScript(this); vimCommands_.reflowText(this); vimCommands_.showVimHelp( RStudioGinjector.INSTANCE.getShortcutViewer()); vimCommands_.showHelpAtCursor(this); vimCommands_.reindent(this); vimCommands_.expandShrinkSelection(this); vimCommands_.addStarRegister(); } private void vimSetTabIndex(int index) { int tabCount = view_.getTabCount(); if (index >= tabCount) return; setPhysicalTabIndex(index); } private void closeAllTabs(boolean interactive) { if (interactive) { // call into the interactive tab closer onCloseAllSourceDocs(); } else { // revert unsaved targets and close tabs revertUnsavedTargets(new Command() { @Override public void execute() { // documents have been reverted; we can close cpsExecuteForEachEditor(editors_, new CPSEditingTargetCommand() { @Override public void execute(EditingTarget editingTarget, Command continuation) { view_.closeTab( editingTarget.asWidget(), false, continuation); } }); } }); } } private void saveActiveSourceDoc() { if (activeEditor_ != null && activeEditor_ instanceof TextEditingTarget) { TextEditingTarget target = (TextEditingTarget) activeEditor_; target.save(); } } private void saveAndCloseActiveSourceDoc() { if (activeEditor_ != null && activeEditor_ instanceof TextEditingTarget) { TextEditingTarget target = (TextEditingTarget) activeEditor_; target.save(new Command() { @Override public void execute() { onCloseSourceDoc(); } }); } } /** * @param isNewTabPending True if a new tab is about to be created. (If * false and there are no tabs already, then a new source doc might * be created to make sure we don't end up with a source pane showing * with no tabs in it.) */ private void ensureVisible(boolean isNewTabPending) { newTabPending_++; try { view_.ensureVisible(); } finally { newTabPending_--; } } public Widget asWidget() { return view_.asWidget(); } private void restoreDocuments(final Session session) { final JsArray<SourceDocument> docs = session.getSessionInfo().getSourceDocuments(); for (int i = 0; i < docs.length(); i++) { // restore the docs assigned to this source window SourceDocument doc = docs.get(i); String docWindowId = doc.getProperties().getString( SourceWindowManager.SOURCE_WINDOW_ID); if (docWindowId == null) docWindowId = ""; String currentSourceWindowId = SourceWindowManager.getSourceWindowId(); // it belongs in this window if (a) it's assigned to it, or (b) this // is the main window, and the window it's assigned to isn't open. if (currentSourceWindowId == docWindowId || (SourceWindowManager.isMainSourceWindow() && !windowManager_.isSourceWindowOpen(docWindowId))) { // attempt to add a tab for the current doc; try/catch this since // we don't want to allow one failure to prevent all docs from // opening EditingTarget sourceEditor = null; try { sourceEditor = addTab(doc, true, OPEN_REPLAY); } catch (Exception e) { Debug.logException(e); } // if we couldn't add the tab for this doc, just continue to the // next one if (sourceEditor == null) continue; } } } private void openEditPublishedDocs() { // don't do this if we are switching projects (it // will be done after the switch) if (ApplicationAction.isSwitchProject()) return; // check for edit_published url parameter final String kEditPublished = "edit_published"; String editPublished = StringUtil.notNull( Window.Location.getParameter(kEditPublished)); // this is an appPath which we can call the server // to determine source files to edit if (editPublished.length() > 0) { // remove it from the url ApplicationUtils.removeQueryParam(kEditPublished); server_.getEditPublishedDocs( editPublished, new SimpleRequestCallback<JsArrayString>() { @Override public void onResponseReceived(JsArrayString docs) { new SourceFilesOpener(docs).run(); } } ); } } private void openProjectDocs(final Session session) { JsArrayString openDocs = session.getSessionInfo().getProjectOpenDocs(); if (openDocs.length() > 0) { // set new tab pending for the duration of the continuation newTabPending_++; // create a continuation for opening the source docs SerializedCommandQueue openCommands = new SerializedCommandQueue(); for (int i=0; i<openDocs.length(); i++) { String doc = openDocs.get(i); final FileSystemItem fsi = FileSystemItem.createFile(doc); openCommands.addCommand(new SerializedCommand() { @Override public void onExecute(final Command continuation) { openFile(fsi, fileTypeRegistry_.getTextTypeForFile(fsi), new CommandWithArg<EditingTarget>() { @Override public void execute(EditingTarget arg) { continuation.execute(); } }); } }); } // decrement newTabPending and select first tab when done openCommands.addCommand(new SerializedCommand() { @Override public void onExecute(Command continuation) { newTabPending_--; onFirstTab(); continuation.execute(); } }); // execute the continuation openCommands.run(); } } public void onShowContent(ShowContentEvent event) { // ignore if we're a satellite if (!SourceWindowManager.isMainSourceWindow()) return; ensureVisible(true); ContentItem content = event.getContent(); server_.newDocument( FileTypeRegistry.URLCONTENT.getTypeId(), null, (JsObject) content.cast(), new SimpleRequestCallback<SourceDocument>("Show") { @Override public void onResponseReceived(SourceDocument response) { addTab(response, OPEN_INTERACTIVE); } }); } @Override public void onOpenObjectExplorerEvent(OpenObjectExplorerEvent event) { // ignore if we're a satellite if (!SourceWindowManager.isMainSourceWindow()) return; ObjectExplorerHandle handle = event.getHandle(); // attempt to open pre-existing tab for (int i = 0; i < editors_.size(); i++) { String path = editors_.get(i).getPath(); if (path != null && path.equals(handle.getPath())) { ((ObjectExplorerEditingTarget)editors_.get(i)).update(handle); ensureVisible(false); view_.selectTab(i); return; } } ensureVisible(true); server_.newDocument( FileTypeRegistry.OBJECT_EXPLORER.getTypeId(), null, (JsObject) handle.cast(), new SimpleRequestCallback<SourceDocument>("Show Object Explorer") { @Override public void onResponseReceived(SourceDocument response) { addTab(response, OPEN_INTERACTIVE); } }); } @Override public void onShowData(ShowDataEvent event) { // ignore if we're a satellite if (!SourceWindowManager.isMainSourceWindow()) return; DataItem data = event.getData(); for (int i = 0; i < editors_.size(); i++) { String path = editors_.get(i).getPath(); if (path != null && path.equals(data.getURI())) { ((DataEditingTarget)editors_.get(i)).updateData(data); ensureVisible(false); view_.selectTab(i); return; } } ensureVisible(true); server_.newDocument( FileTypeRegistry.DATAFRAME.getTypeId(), null, (JsObject) data.cast(), new SimpleRequestCallback<SourceDocument>("Show Data Frame") { @Override public void onResponseReceived(SourceDocument response) { addTab(response, OPEN_INTERACTIVE); } }); } public void onShowProfiler(OpenProfileEvent event) { String profilePath = event.getFilePath(); String htmlPath = event.getHtmlPath(); String htmlLocalPath = event.getHtmlLocalPath(); // first try to activate existing for (int idx = 0; idx < editors_.size(); idx++) { String path = editors_.get(idx).getPath(); if (path != null && profilePath.equals(path)) { ensureVisible(false); view_.selectTab(idx); return; } } // create new profiler ensureVisible(true); if (event.getDocId() != null) { server_.getSourceDocument(event.getDocId(), new ServerRequestCallback<SourceDocument>() { @Override public void onResponseReceived(SourceDocument response) { addTab(response, OPEN_INTERACTIVE); } @Override public void onError(ServerError error) { Debug.logError(error); globalDisplay_.showErrorMessage("Source Document Error", error.getUserMessage()); } }); } else { server_.newDocument( FileTypeRegistry.PROFILER.getTypeId(), null, (JsObject) ProfilerContents.create( profilePath, htmlPath, htmlLocalPath, event.getCreateProfile()).cast(), new SimpleRequestCallback<SourceDocument>("Show Profiler") { @Override public void onResponseReceived(SourceDocument response) { addTab(response, OPEN_INTERACTIVE); } @Override public void onError(ServerError error) { Debug.logError(error); globalDisplay_.showErrorMessage("Source Document Error", error.getUserMessage()); } }); } } @Handler public void onNewSourceDoc() { newDoc(FileTypeRegistry.R, null); } @Handler public void onNewTextDoc() { newDoc(FileTypeRegistry.TEXT, null); } @Handler public void onNewRNotebook() { dependencyManager_.withRMarkdown("R Notebook", "Create R Notebook", new CommandWithArg<Boolean>() { @Override public void execute(Boolean succeeded) { if (!succeeded) { globalDisplay_.showErrorMessage("Notebook Creation Failed", "One or more packages required for R Notebook " + "creation were not installed."); return; } String basename = "r_markdown_notebook"; if (BrowseCap.isMacintosh()) basename += "_osx"; newSourceDocWithTemplate( FileTypeRegistry.RMARKDOWN, "", basename + ".Rmd", Position.create(3, 0)); } }); } @Handler public void onNewCppDoc() { if (uiPrefs_.useRcppTemplate().getValue()) { newSourceDocWithTemplate( FileTypeRegistry.CPP, "", "rcpp.cpp", Position.create(0, 0), new CommandWithArg<EditingTarget> () { @Override public void execute(EditingTarget target) { target.verifyCppPrerequisites(); } } ); } else { newDoc(FileTypeRegistry.CPP, new ResultCallback<EditingTarget, ServerError> () { @Override public void onSuccess(EditingTarget target) { target.verifyCppPrerequisites(); } }); } } @Handler public void onNewSweaveDoc() { // set concordance value if we need to String concordance = new String(); if (uiPrefs_.alwaysEnableRnwConcordance().getValue()) { RnwWeave activeWeave = rnwWeaveRegistry_.findTypeIgnoreCase( uiPrefs_.defaultSweaveEngine().getValue()); if (activeWeave.getInjectConcordance()) concordance = "\\SweaveOpts{concordance=TRUE}\n"; } final String concordanceValue = concordance; // show progress final ProgressIndicator indicator = new GlobalProgressDelayer( globalDisplay_, 500, "Creating new document...").getIndicator(); // get the template server_.getSourceTemplate("", "sweave.Rnw", new ServerRequestCallback<String>() { @Override public void onResponseReceived(String templateContents) { indicator.onCompleted(); // add in concordance if necessary final boolean hasConcordance = concordanceValue.length() > 0; if (hasConcordance) { String beginDoc = "\\begin{document}\n"; templateContents = templateContents.replace( beginDoc, beginDoc + concordanceValue); } newDoc(FileTypeRegistry.SWEAVE, templateContents, new ResultCallback<EditingTarget, ServerError> () { @Override public void onSuccess(EditingTarget target) { int startRow = 4 + (hasConcordance ? 1 : 0); target.setCursorPosition(Position.create(startRow, 0)); } }); } @Override public void onError(ServerError error) { indicator.onError(error.getUserMessage()); } }); } @Handler public void onNewRMarkdownDoc() { SessionInfo sessionInfo = session_.getSessionInfo(); boolean useRMarkdownV2 = sessionInfo.getRMarkdownPackageAvailable(); if (useRMarkdownV2) newRMarkdownV2Doc(); else newRMarkdownV1Doc(); } private void doNewRShinyApp(NewShinyWebApplication.Result result) { server_.createShinyApp( result.getAppName(), result.getAppType(), result.getAppDir(), new SimpleRequestCallback<JsArrayString>("Error Creating Shiny Application", true) { @Override public void onResponseReceived(JsArrayString createdFiles) { // Open and focus files that we created new SourceFilesOpener(createdFiles).run(); } }); } // open a list of source files then focus the first one within the list private class SourceFilesOpener extends SerializedCommandQueue { public SourceFilesOpener(JsArrayString sourceFiles) { for (int i=0; i<sourceFiles.length(); i++) { final String filePath = sourceFiles.get(i); addCommand(new SerializedCommand() { @Override public void onExecute(final Command continuation) { FileSystemItem path = FileSystemItem.createFile(filePath); openFile(path, FileTypeRegistry.R, new CommandWithArg<EditingTarget>() { @Override public void execute(EditingTarget target) { // record first target if necessary if (firstTarget_ == null) firstTarget_ = target; continuation.execute(); } }); } }); } addCommand(new SerializedCommand() { @Override public void onExecute(Command continuation) { if (firstTarget_ != null) { view_.selectTab(firstTarget_.asWidget()); firstTarget_.setCursorPosition(Position.create(0, 0)); } continuation.execute(); } }); } private EditingTarget firstTarget_ = null; } @Handler public void onNewRShinyApp() { dependencyManager_.withShiny("Creating Shiny applications", new Command() { @Override public void execute() { NewShinyWebApplication widget = new NewShinyWebApplication( "New Shiny Web Application", new OperationWithInput<NewShinyWebApplication.Result>() { @Override public void execute(Result input) { doNewRShinyApp(input); } }); widget.showModal(); } }); } @Handler public void onNewRHTMLDoc() { newSourceDocWithTemplate(FileTypeRegistry.RHTML, "", "r_html.Rhtml"); } @Handler public void onNewRDocumentationDoc() { new NewRdDialog( new OperationWithInput<NewRdDialog.Result>() { @Override public void execute(final NewRdDialog.Result result) { final Command createEmptyDoc = new Command() { @Override public void execute() { newSourceDocWithTemplate(FileTypeRegistry.RD, result.name, "r_documentation_empty.Rd", Position.create(3, 7)); } }; if (!result.type.equals(NewRdDialog.Result.TYPE_NONE)) { server_.createRdShell( result.name, result.type, new SimpleRequestCallback<RdShellResult>() { @Override public void onResponseReceived(RdShellResult result) { if (result.getPath() != null) { fileTypeRegistry_.openFile( FileSystemItem.createFile(result.getPath())); } else if (result.getContents() != null) { newDoc(FileTypeRegistry.RD, result.getContents(), null); } else { createEmptyDoc.execute(); } } }); } else { createEmptyDoc.execute(); } } }).showModal(); } @Handler public void onNewRPresentationDoc() { dependencyManager_.withRMarkdown( "Authoring R Presentations", new Command() { @Override public void execute() { fileDialogs_.saveFile( "New R Presentation", fileContext_, workbenchContext_.getDefaultFileDialogDir(), ".Rpres", true, new ProgressOperationWithInput<FileSystemItem>() { @Override public void execute(final FileSystemItem input, final ProgressIndicator indicator) { if (input == null) { indicator.onCompleted(); return; } indicator.onProgress("Creating Presentation..."); server_.createNewPresentation( input.getPath(), new VoidServerRequestCallback(indicator) { @Override public void onSuccess() { openFile(input, FileTypeRegistry.RPRESENTATION, new CommandWithArg<EditingTarget>() { @Override public void execute(EditingTarget arg) { server_.showPresentationPane( input.getPath(), new VoidServerRequestCallback()); } }); } }); } }); } }); } private void newRMarkdownV1Doc() { newSourceDocWithTemplate(FileTypeRegistry.RMARKDOWN, "", "r_markdown.Rmd", Position.create(3, 0)); } private void newRMarkdownV2Doc() { rmarkdown_.showNewRMarkdownDialog( new OperationWithInput<NewRMarkdownDialog.Result>() { @Override public void execute(final NewRMarkdownDialog.Result result) { if (result.isNewDocument()) { NewRMarkdownDialog.RmdNewDocument doc = result.getNewDocument(); String author = doc.getAuthor(); if (author.length() > 0) { uiPrefs_.documentAuthor().setGlobalValue(author); uiPrefs_.writeUIPrefs(); } newRMarkdownV2Doc(doc); } else { newDocFromRmdTemplate(result); } } }); } private void newDocFromRmdTemplate(final NewRMarkdownDialog.Result result) { final RmdChosenTemplate template = result.getFromTemplate(); if (template.createDir()) { rmarkdown_.createDraftFromTemplate(template); return; } rmarkdown_.getTemplateContent(template, new OperationWithInput<String>() { @Override public void execute(final String content) { if (content.length() == 0) globalDisplay_.showErrorMessage("Template Content Missing", "The template at " + template.getTemplatePath() + " is missing."); newDoc(FileTypeRegistry.RMARKDOWN, content, null); } }); } private void newRMarkdownV2Doc( final NewRMarkdownDialog.RmdNewDocument doc) { rmarkdown_.frontMatterToYAML((RmdFrontMatter)doc.getJSOResult().cast(), null, new CommandWithArg<String>() { @Override public void execute(final String yaml) { String template = ""; // select a template appropriate to the document type we're creating if (doc.getTemplate().equals(RmdTemplateData.PRESENTATION_TEMPLATE)) template = "r_markdown_v2_presentation.Rmd"; else if (doc.isShiny()) { if (doc.getFormat().endsWith( RmdOutputFormat.OUTPUT_PRESENTATION_SUFFIX)) template = "r_markdown_presentation_shiny.Rmd"; else template = "r_markdown_shiny.Rmd"; } else template = "r_markdown_v2.Rmd"; newSourceDocWithTemplate(FileTypeRegistry.RMARKDOWN, "", template, Position.create(1, 0), null, new TransformerCommand<String>() { @Override public String transform(String input) { return RmdFrontMatter.FRONTMATTER_SEPARATOR + yaml + RmdFrontMatter.FRONTMATTER_SEPARATOR + "\n" + input; } }); } }); } private void newSourceDocWithTemplate(final TextFileType fileType, String name, String template) { newSourceDocWithTemplate(fileType, name, template, null); } private void newSourceDocWithTemplate(final TextFileType fileType, String name, String template, final Position cursorPosition) { newSourceDocWithTemplate(fileType, name, template, cursorPosition, null); } private void newSourceDocWithTemplate( final TextFileType fileType, String name, String template, final Position cursorPosition, final CommandWithArg<EditingTarget> onSuccess) { newSourceDocWithTemplate(fileType, name, template, cursorPosition, onSuccess, null); } private void newSourceDocWithTemplate( final TextFileType fileType, String name, String template, final Position cursorPosition, final CommandWithArg<EditingTarget> onSuccess, final TransformerCommand<String> contentTransformer) { final ProgressIndicator indicator = new GlobalProgressDelayer( globalDisplay_, 500, "Creating new document...").getIndicator(); server_.getSourceTemplate(name, template, new ServerRequestCallback<String>() { @Override public void onResponseReceived(String templateContents) { indicator.onCompleted(); if (contentTransformer != null) templateContents = contentTransformer.transform(templateContents); newDoc(fileType, templateContents, new ResultCallback<EditingTarget, ServerError> () { @Override public void onSuccess(EditingTarget target) { if (cursorPosition != null) target.setCursorPosition(cursorPosition); if (onSuccess != null) onSuccess.execute(target); } }); } @Override public void onError(ServerError error) { indicator.onError(error.getUserMessage()); } }); } private void newDoc(EditableFileType fileType, ResultCallback<EditingTarget, ServerError> callback) { newDoc(fileType, null, callback); } private void newDoc(EditableFileType fileType, final String contents, final ResultCallback<EditingTarget, ServerError> resultCallback) { ensureVisible(true); server_.newDocument( fileType.getTypeId(), contents, JsObject.createJsObject(), new SimpleRequestCallback<SourceDocument>( "Error Creating New Document") { @Override public void onResponseReceived(SourceDocument newDoc) { EditingTarget target = addTab(newDoc, OPEN_INTERACTIVE); if (contents != null) { target.forceSaveCommandActive(); manageSaveCommands(); } if (resultCallback != null) resultCallback.onSuccess(target); } @Override public void onError(ServerError error) { if (resultCallback != null) resultCallback.onFailure(error); } }); } @Handler public void onFindInFiles() { String searchPattern = ""; if (activeEditor_ != null && activeEditor_ instanceof TextEditingTarget) { TextEditingTarget textEditor = (TextEditingTarget) activeEditor_; String selection = textEditor.getSelectedText(); boolean multiLineSelection = selection.indexOf('\n') != -1; if ((selection.length() != 0) && !multiLineSelection) searchPattern = selection; } events_.fireEvent(new FindInFilesEvent(searchPattern)); } @Handler public void onActivateSource() { onActivateSource(null); } public void onActivateSource(final Command afterActivation) { // give the window manager a chance to activate the last source pane if (windowManager_.activateLastFocusedSource()) return; if (activeEditor_ == null) { newDoc(FileTypeRegistry.R, new ResultCallback<EditingTarget, ServerError>() { @Override public void onSuccess(EditingTarget target) { activeEditor_ = target; doActivateSource(afterActivation); } }); } else { doActivateSource(afterActivation); } } @Handler public void onLayoutZoomSource() { onActivateSource(new Command() { @Override public void execute() { events_.fireEvent(new ZoomPaneEvent("Source")); } }); } private void doActivateSource(final Command afterActivation) { ensureVisible(false); if (activeEditor_ != null) { activeEditor_.focus(); activeEditor_.ensureCursorVisible(); } if (afterActivation != null) afterActivation.execute(); } @Handler public void onSwitchToTab() { if (view_.getTabCount() == 0) return; ensureVisible(false); view_.showOverflowPopup(); } @Handler public void onFirstTab() { if (view_.getTabCount() == 0) return; ensureVisible(false); if (view_.getTabCount() > 0) setPhysicalTabIndex(0); } @Handler public void onPreviousTab() { switchToTab(-1, uiPrefs_.wrapTabNavigation().getValue()); } @Handler public void onNextTab() { switchToTab(1, uiPrefs_.wrapTabNavigation().getValue()); } @Handler public void onLastTab() { if (view_.getTabCount() == 0) return; ensureVisible(false); if (view_.getTabCount() > 0) setPhysicalTabIndex(view_.getTabCount() - 1); } public void nextTabWithWrap() { switchToTab(1, true); } public void prevTabWithWrap() { switchToTab(-1, true); } private void switchToTab(int delta, boolean wrap) { if (view_.getTabCount() == 0) return; ensureVisible(false); int targetIndex = getPhysicalTabIndex() + delta; if (targetIndex > (view_.getTabCount() - 1)) { if (wrap) targetIndex = 0; else return; } else if (targetIndex < 0) { if (wrap) targetIndex = view_.getTabCount() - 1; else return; } setPhysicalTabIndex(targetIndex); } @Handler public void onMoveTabRight() { view_.moveTab(getPhysicalTabIndex(), 1); } @Handler public void onMoveTabLeft() { view_.moveTab(getPhysicalTabIndex(), -1); } @Handler public void onMoveTabToFirst() { view_.moveTab(getPhysicalTabIndex(), getPhysicalTabIndex() * -1); } @Handler public void onMoveTabToLast() { view_.moveTab(getPhysicalTabIndex(), (view_.getTabCount() - getPhysicalTabIndex()) - 1); } @Override public void onPopoutDoc(final PopoutDocEvent e) { // disowning the doc may cause the entire window to close, so defer it // to allow any other popout processing to occur Scheduler.get().scheduleDeferred(new ScheduledCommand() { @Override public void execute() { disownDoc(e.getDocId()); } }); } @Override public void onDebugModeChanged(DebugModeChangedEvent evt) { // when debugging ends, always disengage any active debug highlights if (!evt.debugging() && activeEditor_ != null) { activeEditor_.endDebugHighlighting(); } } @Override public void onDocWindowChanged(final DocWindowChangedEvent e) { if (e.getNewWindowId() == SourceWindowManager.getSourceWindowId()) { ensureVisible(true); // look for a collaborative editing session currently running inside // the document being transferred between windows--if we didn't know // about one with the event, try to look it up in the local cache of // source documents final CollabEditStartParams collabParams = e.getCollabParams() == null ? windowManager_.getDocCollabParams(e.getDocId()) : e.getCollabParams(); // if we're the adopting window, add the doc server_.getSourceDocument(e.getDocId(), new ServerRequestCallback<SourceDocument>() { @Override public void onResponseReceived(final SourceDocument doc) { final EditingTarget target = addTab(doc, e.getPos()); Scheduler.get().scheduleDeferred(new Scheduler.ScheduledCommand() { @Override public void execute() { // if there was a collab session, resume it if (collabParams != null) target.beginCollabSession(e.getCollabParams()); } }); } @Override public void onError(ServerError error) { globalDisplay_.showErrorMessage("Document Tab Move Failed", "Couldn't move the tab to this window: \n" + error.getMessage()); } }); } else if (e.getOldWindowId() == SourceWindowManager.getSourceWindowId()) { // cancel tab drag if it was occurring view_.cancelTabDrag(); // disown this doc if it was our own disownDoc(e.getDocId()); } } private void disownDoc(String docId) { suspendDocumentClose_ = true; for (int i = 0; i < editors_.size(); i++) { if (editors_.get(i).getId() == docId) { view_.closeTab(i, false); break; } } suspendDocumentClose_ = false; } @Override public void onDocTabDragInitiated(final DocTabDragInitiatedEvent event) { inEditorForId(event.getDragParams().getDocId(), new OperationWithInput<EditingTarget>() { @Override public void execute(EditingTarget editor) { DocTabDragParams params = event.getDragParams(); params.setSourcePosition(editor.currentPosition()); events_.fireEvent(new DocTabDragStartedEvent(params)); } }); } @Override public void onPopoutDocInitiated(final PopoutDocInitiatedEvent event) { inEditorForId(event.getDocId(), new OperationWithInput<EditingTarget>() { @Override public void execute(EditingTarget editor) { // if this is a text editor, ensure that its content is // synchronized with the server before we pop it out if (editor instanceof TextEditingTarget) { final TextEditingTarget textEditor = (TextEditingTarget)editor; textEditor.withSavedDoc(new Command() { @Override public void execute() { textEditor.syncLocalSourceDb(); events_.fireEvent(new PopoutDocEvent(event, textEditor.currentPosition())); } }); } else { events_.fireEvent(new PopoutDocEvent(event, editor.currentPosition())); } } }); } @Handler public void onCloseSourceDoc() { closeSourceDoc(true); } void closeSourceDoc(boolean interactive) { if (view_.getTabCount() == 0) return; view_.closeTab(view_.getActiveTabIndex(), interactive); } /** * Execute the given command for each editor, using continuation-passing * style. When executed, the CPSEditingTargetCommand needs to execute its * own Command parameter to continue the iteration. * @param command The command to run on each EditingTarget */ private void cpsExecuteForEachEditor(ArrayList<EditingTarget> editors, final CPSEditingTargetCommand command, final Command completedCommand) { SerializedCommandQueue queue = new SerializedCommandQueue(); // Clone editors_, since the original may be mutated during iteration for (final EditingTarget editor : new ArrayList<EditingTarget>(editors)) { queue.addCommand(new SerializedCommand() { @Override public void onExecute(Command continuation) { command.execute(editor, continuation); } }); } if (completedCommand != null) { queue.addCommand(new SerializedCommand() { public void onExecute(Command continuation) { completedCommand.execute(); continuation.execute(); } }); } } private void cpsExecuteForEachEditor(ArrayList<EditingTarget> editors, final CPSEditingTargetCommand command) { cpsExecuteForEachEditor(editors, command, null); } @Handler public void onSaveAllSourceDocs() { cpsExecuteForEachEditor(editors_, new CPSEditingTargetCommand() { @Override public void execute(EditingTarget target, Command continuation) { if (target.dirtyState().getValue()) { target.save(continuation); } else { continuation.execute(); } } }); } private void saveEditingTargetsWithPrompt( String title, ArrayList<EditingTarget> editingTargets, final Command onCompleted, final Command onCancelled) { // execute on completed right away if the list is empty if (editingTargets.size() == 0) { onCompleted.execute(); } // if there is just one thing dirty then go straight to the save dialog else if (editingTargets.size() == 1) { editingTargets.get(0).saveWithPrompt(onCompleted, onCancelled); } // otherwise use the multi save changes dialog else { // convert to UnsavedChangesTarget collection ArrayList<UnsavedChangesTarget> unsavedTargets = new ArrayList<UnsavedChangesTarget>(); unsavedTargets.addAll(editingTargets); // show dialog view_.showUnsavedChangesDialog( title, unsavedTargets, new OperationWithInput<UnsavedChangesDialog.Result>() { @Override public void execute(UnsavedChangesDialog.Result result) { saveChanges(result.getSaveTargets(), onCompleted); } }, onCancelled); } } private void saveChanges(ArrayList<UnsavedChangesTarget> targets, Command onCompleted) { // convert back to editing targets ArrayList<EditingTarget> saveTargets = new ArrayList<EditingTarget>(); for (UnsavedChangesTarget target: targets) { EditingTarget saveTarget = getEditingTargetForId(target.getId()); if (saveTarget != null) saveTargets.add(saveTarget); } // execute the save cpsExecuteForEachEditor( // targets the user chose to save saveTargets, // save each editor new CPSEditingTargetCommand() { @Override public void execute(EditingTarget saveTarget, Command continuation) { saveTarget.save(continuation); } }, // onCompleted at the end onCompleted ); } private EditingTarget getEditingTargetForId(String id) { for (EditingTarget target : editors_) if (id.equals(target.getId())) return target; return null; } @Handler public void onCloseAllSourceDocs() { closeAllSourceDocs("Close All", null, false); } @Handler public void onCloseOtherSourceDocs() { closeAllSourceDocs("Close Other", null, true); } public void closeAllSourceDocs(final String caption, final Command onCompleted, final boolean excludeActive) { if (SourceWindowManager.isMainSourceWindow() && !excludeActive) { // if this is the main window, close docs in the satellites first windowManager_.closeAllSatelliteDocs(caption, new Command() { @Override public void execute() { closeAllLocalSourceDocs(caption, onCompleted, excludeActive); } }); } else { // this is a satellite (or we don't need to query satellites)--just // close our own tabs closeAllLocalSourceDocs(caption, onCompleted, excludeActive); } } private void closeAllLocalSourceDocs(String caption, Command onCompleted, final boolean excludeActive) { // save active editor for exclusion (it changes as we close tabs) final EditingTarget activeEditor = activeEditor_; // collect up a list of dirty documents ArrayList<EditingTarget> dirtyTargets = new ArrayList<EditingTarget>(); for (EditingTarget target : editors_) { if (excludeActive && target == activeEditor) continue; if (target.dirtyState().getValue()) dirtyTargets.add(target); } // create a command used to close all tabs final Command closeAllTabsCommand = new Command() { @Override public void execute() { cpsExecuteForEachEditor(editors_, new CPSEditingTargetCommand() { @Override public void execute(EditingTarget target, Command continuation) { if (excludeActive && target == activeEditor) { continuation.execute(); return; } else { view_.closeTab(target.asWidget(), false, continuation); } } }); } }; // save targets saveEditingTargetsWithPrompt(caption, dirtyTargets, CommandUtil.join(closeAllTabsCommand, onCompleted), null); } private boolean isUnsavedTarget(EditingTarget target, int type) { boolean fileBacked = target.getPath() != null; return target.dirtyState().getValue() && ((type == TYPE_FILE_BACKED && fileBacked) || (type == TYPE_UNTITLED && !fileBacked)); } public ArrayList<UnsavedChangesTarget> getUnsavedChanges(int type) { ArrayList<UnsavedChangesTarget> targets = new ArrayList<UnsavedChangesTarget>(); // if this is the main window, collect all unsaved changes from // the satellite windows as well if (SourceWindowManager.isMainSourceWindow()) { targets.addAll(windowManager_.getAllSatelliteUnsavedChanges(type)); } for (EditingTarget target : editors_) if (isUnsavedTarget(target, type)) targets.add(target); return targets; } public void saveAllUnsaved(final Command onCompleted) { Command saveAllLocal = new Command() { @Override public void execute() { saveChanges(getUnsavedChanges(TYPE_FILE_BACKED), onCompleted); } }; // if this is the main source window, save all files in satellites first if (SourceWindowManager.isMainSourceWindow()) windowManager_.saveAllUnsaved(saveAllLocal); else saveAllLocal.execute(); } public void saveWithPrompt(UnsavedChangesTarget target, Command onCompleted, Command onCancelled) { if (SourceWindowManager.isMainSourceWindow() && !windowManager_.getWindowIdOfDocId(target.getId()).isEmpty()) { // we are the main window, and we're being asked to save a document // that's in a different window; perform the save over there windowManager_.saveWithPrompt(UnsavedChangesItem.create(target), onCompleted); return; } EditingTarget editingTarget = getEditingTargetForId(target.getId()); if (editingTarget != null) editingTarget.saveWithPrompt(onCompleted, onCancelled); } public void handleUnsavedChangesBeforeExit( final ArrayList<UnsavedChangesTarget> saveTargets, final Command onCompleted) { // first handle saves, then revert unsaved, then callback on completed final Command completed = new Command() { @Override public void execute() { // revert unsaved revertUnsavedTargets(onCompleted); } }; // if this is the main source window, let satellite windows save any // changes first if (SourceWindowManager.isMainSourceWindow()) { windowManager_.handleUnsavedChangesBeforeExit( saveTargets, new Command() { @Override public void execute() { saveChanges(saveTargets, completed); } }); } else { saveChanges(saveTargets, completed); } } public Display getView() { return view_; } private void revertActiveDocument() { if (activeEditor_ == null) return; if (activeEditor_.getPath() != null) activeEditor_.revertChanges(null); // Ensure that the document is in view activeEditor_.ensureCursorVisible(); } private void revertUnsavedTargets(Command onCompleted) { // collect up unsaved targets ArrayList<EditingTarget> unsavedTargets = new ArrayList<EditingTarget>(); for (EditingTarget target : editors_) if (isUnsavedTarget(target, TYPE_FILE_BACKED)) unsavedTargets.add(target); // revert all of them cpsExecuteForEachEditor( // targets the user chose not to save unsavedTargets, // save each editor new CPSEditingTargetCommand() { @Override public void execute(EditingTarget saveTarget, Command continuation) { if (saveTarget.getPath() != null) { // file backed document -- revert it saveTarget.revertChanges(continuation); } else { // untitled document -- just close the tab non-interactively view_.closeTab(saveTarget.asWidget(), false, continuation); } } }, // onCompleted at the end onCompleted ); } @Handler public void onOpenSourceDoc() { fileDialogs_.openFile( "Open File", fileContext_, workbenchContext_.getDefaultFileDialogDir(), new ProgressOperationWithInput<FileSystemItem>() { public void execute(final FileSystemItem input, ProgressIndicator indicator) { if (input == null) return; workbenchContext_.setDefaultFileDialogDir( input.getParentPath()); indicator.onCompleted(); Scheduler.get().scheduleDeferred(new ScheduledCommand() { public void execute() { fileTypeRegistry_.openFile(input); } }); } }); } public void onNewDocumentWithCode(final NewDocumentWithCodeEvent event) { // determine the type final EditableFileType docType; if (event.getType().equals(NewDocumentWithCodeEvent.R_SCRIPT)) docType = FileTypeRegistry.R; else docType = FileTypeRegistry.RMARKDOWN; // command to create and run the new doc Command newDocCommand = new Command() { @Override public void execute() { newDoc(docType, new ResultCallback<EditingTarget, ServerError>() { public void onSuccess(EditingTarget arg) { TextEditingTarget editingTarget = (TextEditingTarget)arg; editingTarget.insertCode(event.getCode(), false); if (event.getCursorPosition() != null) { editingTarget.navigateToPosition(event.getCursorPosition(), false); } if (event.getExecute()) { if (docType.equals(FileTypeRegistry.R)) { commands_.executeToCurrentLine().execute(); commands_.activateSource().execute(); } else { commands_.executePreviousChunks().execute(); } } } }); } }; // do it if (docType.equals(FileTypeRegistry.R)) { newDocCommand.execute(); } else { dependencyManager_.withRMarkdown("R Notebook", "Create R Notebook", newDocCommand); } } public void onOpenSourceFile(final OpenSourceFileEvent event) { doOpenSourceFile(event.getFile(), event.getFileType(), event.getPosition(), null, event.getNavigationMethod(), false); } public void onOpenPresentationSourceFile(OpenPresentationSourceFileEvent event) { // don't do the navigation if the active document is a source // file from this presentation module doOpenSourceFile(event.getFile(), event.getFileType(), event.getPosition(), event.getPattern(), NavigationMethods.HIGHLIGHT_LINE, true); } public void onEditPresentationSource(final EditPresentationSourceEvent event) { openFile( event.getSourceFile(), FileTypeRegistry.RPRESENTATION, new CommandWithArg<EditingTarget>() { @Override public void execute(final EditingTarget editor) { TextEditingTargetPresentationHelper.navigateToSlide( editor, event.getSlideIndex()); } }); } private void doOpenSourceFile(final FileSystemItem file, final TextFileType fileType, final FilePosition position, final String pattern, final int navMethod, final boolean forceHighlightMode) { // if the navigation should happen in another window, do that instead NavigationResult navResult = windowManager_.navigateToFile(file, position, navMethod); // we navigated externally, just skip this if (navResult.getType() == NavigationResult.RESULT_NAVIGATED) return; // we're about to open in this window--if it's the main window, focus it if (SourceWindowManager.isMainSourceWindow() && Desktop.isDesktop()) Desktop.getFrame().bringMainFrameToFront(); final boolean isDebugNavigation = navMethod == NavigationMethods.DEBUG_STEP || navMethod == NavigationMethods.DEBUG_END; final CommandWithArg<EditingTarget> editingTargetAction = new CommandWithArg<EditingTarget>() { @Override public void execute(EditingTarget target) { // the rstudioapi package can use the proxy (-1, -1) position to // indicate that source navigation should not occur; ie, we should // preserve whatever position was used in the document earlier boolean navigateToPosition = position != null && (position.getLine() != -1 && position.getColumn() != -1); if (navigateToPosition) { SourcePosition endPosition = null; if (isDebugNavigation) { DebugFilePosition filePos = (DebugFilePosition) position.cast(); endPosition = SourcePosition.create( filePos.getEndLine() - 1, filePos.getEndColumn() + 1); if (Desktop.isDesktop() && navMethod != NavigationMethods.DEBUG_END) Desktop.getFrame().bringMainFrameToFront(); } navigate(target, SourcePosition.create(position.getLine() - 1, position.getColumn() - 1), endPosition); } else if (pattern != null) { Position pos = target.search(pattern); if (pos != null) { navigate(target, SourcePosition.create(pos.getRow(), 0), null); } } } private void navigate(final EditingTarget target, final SourcePosition srcPosition, final SourcePosition srcEndPosition) { Scheduler.get().scheduleDeferred(new ScheduledCommand() { @Override public void execute() { if (navMethod == NavigationMethods.DEBUG_STEP) { target.highlightDebugLocation( srcPosition, srcEndPosition, true); } else if (navMethod == NavigationMethods.DEBUG_END) { target.endDebugHighlighting(); } else { // force highlight mode if requested if (forceHighlightMode) target.forceLineHighlighting(); // now navigate to the new position boolean highlight = navMethod == NavigationMethods.HIGHLIGHT_LINE && !uiPrefs_.highlightSelectedLine().getValue(); target.navigateToPosition(srcPosition, false, highlight); } } }); } }; if (navResult.getType() == NavigationResult.RESULT_RELOCATE) { server_.getSourceDocument(navResult.getDocId(), new ServerRequestCallback<SourceDocument>() { @Override public void onResponseReceived(final SourceDocument doc) { editingTargetAction.execute(addTab(doc, OPEN_REPLAY)); } @Override public void onError(ServerError error) { globalDisplay_.showErrorMessage("Document Tab Move Failed", "Couldn't move the tab to this window: \n" + error.getMessage()); } }); return; } final CommandWithArg<FileSystemItem> action = new CommandWithArg<FileSystemItem>() { @Override public void execute(FileSystemItem file) { openFile(file, fileType, editingTargetAction); } }; // If this is a debug navigation, we only want to treat this as a full // file open if the file isn't already open; otherwise, we can just // highlight in place. if (isDebugNavigation) { setPendingDebugSelection(); for (int i = 0; i < editors_.size(); i++) { EditingTarget target = editors_.get(i); String path = target.getPath(); if (path != null && path.equalsIgnoreCase(file.getPath())) { // the file's open; just update its highlighting if (navMethod == NavigationMethods.DEBUG_END) { target.endDebugHighlighting(); } else { view_.selectTab(i); editingTargetAction.execute(target); } return; } } // If we're here, the target file wasn't open in an editor. Don't // open a file just to turn off debug highlighting in the file! if (navMethod == NavigationMethods.DEBUG_END) return; } // Warning: event.getFile() can be null (e.g. new Sweave document) if (file != null && file.getLength() < 0) { statQueue_.add(new StatFileEntry(file, action)); if (statQueue_.size() == 1) processStatQueue(); } else { action.execute(file); } } private void processStatQueue() { if (statQueue_.isEmpty()) return; final StatFileEntry entry = statQueue_.peek(); final Command processNextEntry = new Command() { @Override public void execute() { statQueue_.remove(); if (!statQueue_.isEmpty()) processStatQueue(); } }; server_.stat(entry.file.getPath(), new ServerRequestCallback<FileSystemItem>() { @Override public void onResponseReceived(FileSystemItem response) { processNextEntry.execute(); entry.action.execute(response); } @Override public void onError(ServerError error) { processNextEntry.execute(); // Couldn't stat the file? Proceed anyway. If the file doesn't // exist, we'll let the downstream code be the one to show the // error. entry.action.execute(entry.file); } }); } private void openFile(FileSystemItem file) { openFile(file, fileTypeRegistry_.getTextTypeForFile(file)); } private void openFile(FileSystemItem file, TextFileType fileType) { openFile(file, fileType, new CommandWithArg<EditingTarget>() { @Override public void execute(EditingTarget arg) { } }); } private void openFile(final FileSystemItem file, final TextFileType fileType, final CommandWithArg<EditingTarget> executeOnSuccess) { // add this work to the queue openFileQueue_.add(new OpenFileEntry(file, fileType, executeOnSuccess)); // begin queue processing if it's the only work in the queue if (openFileQueue_.size() == 1) processOpenFileQueue(); } private void processOpenFileQueue() { // no work to do if (openFileQueue_.isEmpty()) return; // find the first work unit final OpenFileEntry entry = openFileQueue_.peek(); // define command to advance queue final Command processNextEntry = new Command() { @Override public void execute() { openFileQueue_.remove(); if (!openFileQueue_.isEmpty()) processOpenFileQueue(); } }; openFile(entry.file, entry.fileType, new ResultCallback<EditingTarget, ServerError>() { @Override public void onSuccess(EditingTarget target) { processNextEntry.execute(); if (entry.executeOnSuccess != null) entry.executeOnSuccess.execute(target); } @Override public void onFailure(ServerError error) { String message = error.getUserMessage(); // see if a special message was provided JSONValue errValue = error.getClientInfo(); if (errValue != null) { JSONString errMsg = errValue.isString(); if (errMsg != null) message = errMsg.stringValue(); } globalDisplay_.showMessage(GlobalDisplay.MSG_ERROR, "Error while opening file", message); processNextEntry.execute(); } }); } private void openNotebook( final FileSystemItem rmdFile, final SourceDocumentResult doc, final ResultCallback<EditingTarget, ServerError> resultCallback) { if (!StringUtil.isNullOrEmpty(doc.getDocPath())) { // this happens if we created the R Markdown file, or if the R Markdown // file on disk matched the one inside the notebook openFileFromServer(rmdFile, FileTypeRegistry.RMARKDOWN, resultCallback); } else if (!StringUtil.isNullOrEmpty(doc.getDocId())) { // this happens when we have to open an untitled buffer for the the // notebook (usually because the of a conflict between the Rmd on disk // and the one in the .nb.html file) server_.getSourceDocument(doc.getDocId(), new ServerRequestCallback<SourceDocument>() { @Override public void onResponseReceived(SourceDocument doc) { // create the editor EditingTarget target = addTab(doc, OPEN_INTERACTIVE); // show a warning bar if (target instanceof TextEditingTarget) { ((TextEditingTarget) target).showWarningMessage( "This notebook has the same name as an R Markdown " + "file, but doesn't match it."); } resultCallback.onSuccess(target); } @Override public void onError(ServerError error) { globalDisplay_.showErrorMessage( "Notebook Open Failed", "This notebook could not be opened. " + "If the error persists, try removing the " + "accompanying R Markdown file. \n\n" + error.getMessage()); resultCallback.onFailure(error); } }); } } private void openNotebook(final FileSystemItem rnbFile, final TextFileType fileType, final ResultCallback<EditingTarget, ServerError> resultCallback) { // construct path to .Rmd final String rnbPath = rnbFile.getPath(); final String rmdPath = FilePathUtils.filePathSansExtension(rnbPath) + ".Rmd"; final FileSystemItem rmdFile = FileSystemItem.createFile(rmdPath); // if we already have associated .Rmd file open, then just edit it // TODO: should we perform conflict resolution here as well? if (openFileAlreadyOpen(rmdFile, resultCallback)) return; // ask the server to extract the .Rmd, then open that Command extractRmdCommand = new Command() { @Override public void execute() { server_.extractRmdFromNotebook( rnbPath, new ServerRequestCallback<SourceDocumentResult>() { @Override public void onResponseReceived(SourceDocumentResult doc) { openNotebook(rmdFile, doc, resultCallback); } @Override public void onError(ServerError error) { globalDisplay_.showErrorMessage("Notebook Open Failed", "This notebook could not be opened. \n\n" + error.getMessage()); resultCallback.onFailure(error); } }); } }; dependencyManager_.withRMarkdown("R Notebook", "Using R Notebooks", extractRmdCommand); } private boolean openFileAlreadyOpen(final FileSystemItem file, final ResultCallback<EditingTarget, ServerError> resultCallback) { // check to see if any local editors have the file open for (int i = 0; i < editors_.size(); i++) { EditingTarget target = editors_.get(i); String thisPath = target.getPath(); if (thisPath != null && thisPath.equalsIgnoreCase(file.getPath())) { view_.selectTab(i); pMruList_.get().add(thisPath); if (resultCallback != null) resultCallback.onSuccess(target); return true; } } return false; } // top-level wrapper for opening files. takes care of: // - making sure the view is visible // - checking whether it is already open and re-selecting its tab // - prohibit opening very large files (>500KB) // - confirmation of opening large files (>100KB) // - finally, actually opening the file from the server // via the call to the lower level openFile method private void openFile(final FileSystemItem file, final TextFileType fileType, final ResultCallback<EditingTarget, ServerError> resultCallback) { ensureVisible(true); if (fileType.isRNotebook()) { openNotebook(file, fileType, resultCallback); return; } if (file == null) { newDoc(fileType, resultCallback); return; } if (openFileAlreadyOpen(file, resultCallback)) return; EditingTarget target = editingTargetSource_.getEditingTarget(fileType); if (file.getLength() > target.getFileSizeLimit()) { if (resultCallback != null) resultCallback.onCancelled(); showFileTooLargeWarning(file, target.getFileSizeLimit()); } else if (file.getLength() > target.getLargeFileSize()) { confirmOpenLargeFile(file, new Operation() { public void execute() { openFileFromServer(file, fileType, resultCallback); } }, new Operation() { public void execute() { // user (wisely) cancelled if (resultCallback != null) resultCallback.onCancelled(); } }); } else { openFileFromServer(file, fileType, resultCallback); } } private void showFileTooLargeWarning(FileSystemItem file, long sizeLimit) { StringBuilder msg = new StringBuilder(); msg.append("The file '" + file.getName() + "' is too "); msg.append("large to open in the source editor (the file is "); msg.append(StringUtil.formatFileSize(file.getLength()) + " and the "); msg.append("maximum file size is "); msg.append(StringUtil.formatFileSize(sizeLimit) + ")"); globalDisplay_.showMessage(GlobalDisplay.MSG_WARNING, "Selected File Too Large", msg.toString()); } private void confirmOpenLargeFile(FileSystemItem file, Operation openOperation, Operation cancelOperation) { StringBuilder msg = new StringBuilder(); msg.append("The source file '" + file.getName() + "' is large ("); msg.append(StringUtil.formatFileSize(file.getLength()) + ") "); msg.append("and may take some time to open. "); msg.append("Are you sure you want to continue opening it?"); globalDisplay_.showYesNoMessage(GlobalDisplay.MSG_WARNING, "Confirm Open", msg.toString(), openOperation, false); // 'No' is default } private void openFileFromServer( final FileSystemItem file, final TextFileType fileType, final ResultCallback<EditingTarget, ServerError> resultCallback) { final Command dismissProgress = globalDisplay_.showProgress( "Opening file..."); server_.openDocument( file.getPath(), fileType.getTypeId(), uiPrefs_.defaultEncoding().getValue(), new ServerRequestCallback<SourceDocument>() { @Override public void onError(ServerError error) { dismissProgress.execute(); pMruList_.get().remove(file.getPath()); Debug.logError(error); if (resultCallback != null) resultCallback.onFailure(error); } @Override public void onResponseReceived(SourceDocument document) { dismissProgress.execute(); pMruList_.get().add(document.getPath()); EditingTarget target = addTab(document, OPEN_INTERACTIVE); if (resultCallback != null) resultCallback.onSuccess(target); } }); } Widget createWidget(EditingTarget target) { return target.asWidget(); } private EditingTarget addTab(SourceDocument doc, int mode) { return addTab(doc, false, mode); } private EditingTarget addTab(SourceDocument doc, boolean atEnd, int mode) { // by default, add at the tab immediately after the current tab return addTab(doc, atEnd ? null : getPhysicalTabIndex() + 1, mode); } private EditingTarget addTab(SourceDocument doc, Integer position, int mode) { final String defaultNamePrefix = editingTargetSource_.getDefaultNamePrefix(doc); final EditingTarget target = editingTargetSource_.getEditingTarget( doc, fileContext_, new Provider<String>() { public String get() { return getNextDefaultName(defaultNamePrefix); } }); final Widget widget = createWidget(target); if (position == null) { editors_.add(target); } else { // we're inserting into an existing permuted tabset -- push aside // any tabs physically to the right of this tab editors_.add(position, target); for (int i = 0; i < tabOrder_.size(); i++) { int pos = tabOrder_.get(i); if (pos >= position) tabOrder_.set(i, pos + 1); } // add this tab in its "natural" position tabOrder_.add(position, position); } view_.addTab(widget, target.getIcon(), target.getId(), target.getName().getValue(), target.getTabTooltip(), // used as tooltip, if non-null position, true); fireDocTabsChanged(); target.getName().addValueChangeHandler(new ValueChangeHandler<String>() { public void onValueChange(ValueChangeEvent<String> event) { view_.renameTab(widget, target.getIcon(), event.getValue(), target.getPath()); fireDocTabsChanged(); } }); view_.setDirty(widget, target.dirtyState().getValue()); target.dirtyState().addValueChangeHandler(new ValueChangeHandler<Boolean>() { public void onValueChange(ValueChangeEvent<Boolean> event) { view_.setDirty(widget, event.getValue()); manageCommands(); } }); target.addEnsureVisibleHandler(new EnsureVisibleHandler() { public void onEnsureVisible(EnsureVisibleEvent event) { view_.selectTab(widget); } }); target.addCloseHandler(new CloseHandler<Void>() { public void onClose(CloseEvent<Void> voidCloseEvent) { view_.closeTab(widget, false); } }); events_.fireEvent(new SourceDocAddedEvent(doc, mode)); // adding a tab may enable commands that are only available when // multiple documents are open; if this is the second document, go check if (editors_.size() == 2) manageMultiTabCommands(); // if the target had an editing session active, attempt to resume it if (doc.getCollabParams() != null) target.beginCollabSession(doc.getCollabParams()); return target; } private String getNextDefaultName(String defaultNamePrefix) { if (StringUtil.isNullOrEmpty(defaultNamePrefix)) { defaultNamePrefix = "Untitled"; } int max = 0; for (EditingTarget target : editors_) { String name = target.getName().getValue(); max = Math.max(max, getUntitledNum(name, defaultNamePrefix)); } return defaultNamePrefix + (max + 1); } private native final int getUntitledNum(String name, String prefix) /*-{ var match = (new RegExp("^" + prefix + "([0-9]{1,5})$")).exec(name); if (!match) return 0; return parseInt(match[1]); }-*/; public void onInsertSource(final InsertSourceEvent event) { if (activeEditor_ != null && activeEditor_ instanceof TextEditingTarget && commands_.executeCode().isEnabled()) { TextEditingTarget textEditor = (TextEditingTarget) activeEditor_; textEditor.insertCode(event.getCode(), event.isBlock()); } else { newDoc(FileTypeRegistry.R, new ResultCallback<EditingTarget, ServerError>() { public void onSuccess(EditingTarget arg) { ((TextEditingTarget)arg).insertCode(event.getCode(), event.isBlock()); } }); } } public void onTabClosing(final TabClosingEvent event) { EditingTarget target = editors_.get(event.getTabIndex()); if (!target.onBeforeDismiss()) event.cancel(); } @Override public void onTabClose(TabCloseEvent event) { // can't proceed if there is no active editor if (activeEditor_ == null) return; if (event.getTabIndex() >= editors_.size()) return; // Seems like this should never happen...? final String activeEditorId = activeEditor_.getId(); if (editors_.get(event.getTabIndex()).getId().equals(activeEditorId)) { // scan the source navigation history for an entry that can // be used as the next active tab (anything that doesn't have // the same document id as the currently active tab) SourceNavigation srcNav = sourceNavigationHistory_.scanBack( new SourceNavigationHistory.Filter() { public boolean includeEntry(SourceNavigation navigation) { return !navigation.getDocumentId().equals(activeEditorId); } }); // see if the source navigation we found corresponds to an active // tab -- if it does then set this on the event if (srcNav != null) { for (int i=0; i<editors_.size(); i++) { if (srcNav.getDocumentId().equals(editors_.get(i).getId())) { view_.selectTab(i); break; } } } } } private void closeTabIndex(int idx, boolean closeDocument) { EditingTarget target = editors_.remove(idx); tabOrder_.remove(new Integer(idx)); for (int i = 0; i < tabOrder_.size(); i++) { if (tabOrder_.get(i) > idx) { tabOrder_.set(i, tabOrder_.get(i) - 1); } } target.onDismiss(closeDocument ? EditingTarget.DISMISS_TYPE_CLOSE : EditingTarget.DISMISS_TYPE_MOVE); if (activeEditor_ == target) { activeEditor_.onDeactivate(); activeEditor_ = null; } if (closeDocument) { events_.fireEvent(new DocTabClosedEvent(target.getId())); server_.closeDocument(target.getId(), new VoidServerRequestCallback()); } manageCommands(); fireDocTabsChanged(); if (view_.getTabCount() == 0) { sourceNavigationHistory_.clear(); events_.fireEvent(new LastSourceDocClosedEvent()); } } public void onTabClosed(TabClosedEvent event) { closeTabIndex(event.getTabIndex(), !suspendDocumentClose_); } @Override public void onTabReorder(TabReorderEvent event) { syncTabOrder(); // sanity check: make sure we're moving from a valid location and to a // valid location if (event.getOldPos() < 0 || event.getOldPos() >= tabOrder_.size() || event.getNewPos() < 0 || event.getNewPos() >= tabOrder_.size()) { return; } // remove the tab from its old position int idx = tabOrder_.get(event.getOldPos()); tabOrder_.remove(new Integer(idx)); // force type box // add it to its new position tabOrder_.add(event.getNewPos(), idx); // sort the document IDs and send to the server ArrayList<String> ids = new ArrayList<String>(); for (int i = 0; i < tabOrder_.size(); i++) { ids.add(editors_.get(tabOrder_.get(i)).getId()); } server_.setDocOrder(ids, new VoidServerRequestCallback()); // activate the tab setPhysicalTabIndex(event.getNewPos()); fireDocTabsChanged(); } private void syncTabOrder() { // ensure the tab order is synced to the list of editors for (int i = tabOrder_.size(); i < editors_.size(); i++) { tabOrder_.add(i); } for (int i = editors_.size(); i < tabOrder_.size(); i++) { tabOrder_.remove(i); } } private void fireDocTabsChanged() { if (!initialized_) return; // ensure we have a tab order (we want the popup list to match the order // of the tabs) syncTabOrder(); String[] ids = new String[editors_.size()]; ImageResource[] icons = new ImageResource[editors_.size()]; String[] names = new String[editors_.size()]; String[] paths = new String[editors_.size()]; for (int i = 0; i < ids.length; i++) { EditingTarget target = editors_.get(tabOrder_.get(i)); ids[i] = target.getId(); icons[i] = target.getIcon(); names[i] = target.getName().getValue(); paths[i] = target.getPath(); } events_.fireEvent(new DocTabsChangedEvent(ids, icons, names, paths)); view_.manageChevronVisibility(); } public void onSelection(SelectionEvent<Integer> event) { if (activeEditor_ != null) activeEditor_.onDeactivate(); activeEditor_ = null; if (event.getSelectedItem() >= 0) { activeEditor_ = editors_.get(event.getSelectedItem()); activeEditor_.onActivate(); // let any listeners know this tab was activated events_.fireEvent(new DocTabActivatedEvent( activeEditor_.getPath(), activeEditor_.getId())); // don't send focus to the tab if we're expecting a debug selection // event if (initialized_ && !isDebugSelectionPending()) { Scheduler.get().scheduleDeferred(new ScheduledCommand() { public void execute() { if (activeEditor_ != null) activeEditor_.focus(); } }); } else if (isDebugSelectionPending()) { // we're debugging, so send focus to the console instead of the // editor commands_.activateConsole().execute(); clearPendingDebugSelection(); } } if (initialized_) manageCommands(); } private void manageCommands() { boolean hasDocs = editors_.size() > 0; commands_.closeSourceDoc().setEnabled(hasDocs); commands_.closeAllSourceDocs().setEnabled(hasDocs); commands_.nextTab().setEnabled(hasDocs); commands_.previousTab().setEnabled(hasDocs); commands_.firstTab().setEnabled(hasDocs); commands_.lastTab().setEnabled(hasDocs); commands_.switchToTab().setEnabled(hasDocs); commands_.setWorkingDirToActiveDoc().setEnabled(hasDocs); HashSet<AppCommand> newCommands = activeEditor_ != null ? activeEditor_.getSupportedCommands() : new HashSet<AppCommand>(); HashSet<AppCommand> commandsToEnable = new HashSet<AppCommand>(newCommands); commandsToEnable.removeAll(activeCommands_); HashSet<AppCommand> commandsToDisable = new HashSet<AppCommand>(activeCommands_); commandsToDisable.removeAll(newCommands); for (AppCommand command : commandsToEnable) { command.setEnabled(true); command.setVisible(true); } for (AppCommand command : commandsToDisable) { command.setEnabled(false); command.setVisible(false); } // commands which should always be visible even when disabled commands_.saveSourceDoc().setVisible(true); commands_.saveSourceDocAs().setVisible(true); commands_.printSourceDoc().setVisible(true); commands_.setWorkingDirToActiveDoc().setVisible(true); commands_.debugBreakpoint().setVisible(true); // manage synctex commands manageSynctexCommands(); // manage vcs commands manageVcsCommands(); // manage save and save all manageSaveCommands(); // manage source navigation manageSourceNavigationCommands(); // manage RSConnect commands manageRSConnectCommands(); // manage R Markdown commands manageRMarkdownCommands(); // manage multi-tab commands manageMultiTabCommands(); activeCommands_ = newCommands; // give the active editor a chance to manage commands if (activeEditor_ != null) activeEditor_.manageCommands(); assert verifyNoUnsupportedCommands(newCommands) : "Unsupported commands detected (please add to Source.dynamicCommands_)"; } private void manageMultiTabCommands() { boolean hasMultipleDocs = editors_.size() > 1; // special case--these editing targets always support popout, but it's // nonsensical to show it if it's the only tab in a satellite; hide it in // this case if (commands_.popoutDoc().isEnabled() && activeEditor_ != null && (activeEditor_ instanceof TextEditingTarget || activeEditor_ instanceof CodeBrowserEditingTarget) && !SourceWindowManager.isMainSourceWindow()) { commands_.popoutDoc().setVisible(hasMultipleDocs); } commands_.closeOtherSourceDocs().setEnabled(hasMultipleDocs); } private void manageSynctexCommands() { // synctex commands are enabled if we have synctex for the active editor boolean synctexAvailable = synctex_.isSynctexAvailable(); if (synctexAvailable) { if ((activeEditor_ != null) && (activeEditor_.getPath() != null) && activeEditor_.canCompilePdf()) { synctexAvailable = synctex_.isSynctexAvailable(); } else { synctexAvailable = false; } } synctex_.enableCommands(synctexAvailable); } private void manageVcsCommands() { // manage availablity of vcs commands boolean vcsCommandsEnabled = session_.getSessionInfo().isVcsEnabled() && (activeEditor_ != null) && (activeEditor_.getPath() != null) && activeEditor_.getPath().startsWith( session_.getSessionInfo().getActiveProjectDir().getPath()); commands_.vcsFileLog().setVisible(vcsCommandsEnabled); commands_.vcsFileLog().setEnabled(vcsCommandsEnabled); commands_.vcsFileDiff().setVisible(vcsCommandsEnabled); commands_.vcsFileDiff().setEnabled(vcsCommandsEnabled); commands_.vcsFileRevert().setVisible(vcsCommandsEnabled); commands_.vcsFileRevert().setEnabled(vcsCommandsEnabled); if (vcsCommandsEnabled) { String name = FileSystemItem.getNameFromPath(activeEditor_.getPath()); commands_.vcsFileDiff().setMenuLabel("_Diff \"" + name + "\""); commands_.vcsFileLog().setMenuLabel("_Log of \"" + name +"\""); commands_.vcsFileRevert().setMenuLabel("_Revert \"" + name + "\"..."); } boolean isGithubRepo = session_.getSessionInfo().isGithubRepository(); if (vcsCommandsEnabled && isGithubRepo) { String name = FileSystemItem.getNameFromPath(activeEditor_.getPath()); commands_.vcsViewOnGitHub().setVisible(true); commands_.vcsViewOnGitHub().setEnabled(true); commands_.vcsViewOnGitHub().setMenuLabel( "_View \"" + name + "\" on GitHub"); commands_.vcsBlameOnGitHub().setVisible(true); commands_.vcsBlameOnGitHub().setEnabled(true); commands_.vcsBlameOnGitHub().setMenuLabel( "_Blame \"" + name + "\" on GitHub"); } else { commands_.vcsViewOnGitHub().setVisible(false); commands_.vcsViewOnGitHub().setEnabled(false); commands_.vcsBlameOnGitHub().setVisible(false); commands_.vcsBlameOnGitHub().setEnabled(false); } } private void manageRSConnectCommands() { boolean rsCommandsAvailable = SessionUtils.showPublishUi(session_, uiPrefs_) && (activeEditor_ != null) && (activeEditor_.getPath() != null) && ((activeEditor_.getExtendedFileType() != null && activeEditor_.getExtendedFileType() .startsWith(SourceDocument.XT_SHINY_PREFIX)) || (activeEditor_.getExtendedFileType() == SourceDocument.XT_RMARKDOWN)); commands_.rsconnectDeploy().setVisible(rsCommandsAvailable); if (activeEditor_ != null) commands_.rsconnectDeploy().setLabel( activeEditor_.getExtendedFileType() != null && activeEditor_.getExtendedFileType() .startsWith(SourceDocument.XT_SHINY_PREFIX) ? "Publish Application..." : "Publish Document..."); commands_.rsconnectConfigure().setVisible(rsCommandsAvailable); } private void manageRMarkdownCommands() { boolean rmdCommandsAvailable = session_.getSessionInfo().getRMarkdownPackageAvailable() && (activeEditor_ != null) && activeEditor_.getExtendedFileType() == SourceDocument.XT_RMARKDOWN; commands_.editRmdFormatOptions().setVisible(rmdCommandsAvailable); commands_.editRmdFormatOptions().setEnabled(rmdCommandsAvailable); } private void manageSaveCommands() { boolean saveEnabled = (activeEditor_ != null) && activeEditor_.isSaveCommandActive(); commands_.saveSourceDoc().setEnabled(saveEnabled); manageSaveAllCommand(); } private void manageSaveAllCommand() { // if one document is dirty then we are enabled for (EditingTarget target : editors_) { if (target.isSaveCommandActive()) { commands_.saveAllSourceDocs().setEnabled(true); return; } } // not one was dirty, disabled commands_.saveAllSourceDocs().setEnabled(false); } private boolean verifyNoUnsupportedCommands(HashSet<AppCommand> commands) { HashSet<AppCommand> temp = new HashSet<AppCommand>(commands); temp.removeAll(dynamicCommands_); return temp.size() == 0; } private void pasteFileContentsAtCursor(final String path, final String encoding) { if (activeEditor_ != null && activeEditor_ instanceof TextEditingTarget) { final TextEditingTarget target = (TextEditingTarget) activeEditor_; server_.getFileContents(path, encoding, new ServerRequestCallback<String>() { @Override public void onResponseReceived(String content) { target.insertCode(content, false); } @Override public void onError(ServerError error) { Debug.logError(error); } }); } } private void pasteRCodeExecutionResult(final String code) { server_.executeRCode(code, new ServerRequestCallback<String>() { @Override public void onResponseReceived(String output) { if (activeEditor_ != null && activeEditor_ instanceof TextEditingTarget) { TextEditingTarget editor = (TextEditingTarget) activeEditor_; editor.insertCode(output, false); } } @Override public void onError(ServerError error) { Debug.logError(error); } }); } private void reflowText() { if (activeEditor_ != null && activeEditor_ instanceof TextEditingTarget) { TextEditingTarget editor = (TextEditingTarget) activeEditor_; editor.reflowText(); } } private void reindent() { if (activeEditor_ != null && activeEditor_ instanceof TextEditingTarget) { TextEditingTarget editor = (TextEditingTarget) activeEditor_; editor.getDocDisplay().reindent(); } } private void editFile(final String path) { server_.ensureFileExists( path, new ServerRequestCallback<Boolean>() { @Override public void onResponseReceived(Boolean success) { if (success) { FileSystemItem file = FileSystemItem.createFile(path); openFile(file); } } @Override public void onError(ServerError error) { Debug.logError(error); } }); } private void showHelpAtCursor() { if (activeEditor_ != null && activeEditor_ instanceof TextEditingTarget) { TextEditingTarget editor = (TextEditingTarget) activeEditor_; editor.showHelpAtCursor(); } } public void onFileEdit(FileEditEvent event) { if (SourceWindowManager.isMainSourceWindow()) { fileTypeRegistry_.editFile(event.getFile()); } } public void onBeforeShow(BeforeShowEvent event) { if (view_.getTabCount() == 0 && newTabPending_ == 0) { // Avoid scenarios where the Source tab comes up but no tabs are // in it. (But also avoid creating an extra source tab when there // were already new tabs about to be created!) onNewSourceDoc(); } } @Handler public void onSourceNavigateBack() { if (!sourceNavigationHistory_.isForwardEnabled()) { if (activeEditor_ != null) activeEditor_.recordCurrentNavigationPosition(); } SourceNavigation navigation = sourceNavigationHistory_.goBack(); if (navigation != null) attemptSourceNavigation(navigation, commands_.sourceNavigateBack()); } @Handler public void onSourceNavigateForward() { SourceNavigation navigation = sourceNavigationHistory_.goForward(); if (navigation != null) attemptSourceNavigation(navigation, commands_.sourceNavigateForward()); } private void attemptSourceNavigation(final SourceNavigation navigation, final AppCommand retryCommand) { // see if we can navigate by id String docId = navigation.getDocumentId(); final EditingTarget target = getEditingTargetForId(docId); if (target != null) { // check for navigation to the current position -- in this // case execute the retry command if ( (target == activeEditor_) && target.isAtSourceRow(navigation.getPosition())) { if (retryCommand.isEnabled()) retryCommand.execute(); } else { suspendSourceNavigationAdding_ = true; try { view_.selectTab(target.asWidget()); target.restorePosition(navigation.getPosition()); } finally { suspendSourceNavigationAdding_ = false; } } } // check for code browser navigation else if ((navigation.getPath() != null) && navigation.getPath().startsWith(CodeBrowserEditingTarget.PATH)) { activateCodeBrowser( navigation.getPath(), false, new SourceNavigationResultCallback<CodeBrowserEditingTarget>( navigation.getPosition(), retryCommand)); } // check for file path navigation else if ((navigation.getPath() != null) && !navigation.getPath().startsWith(DataItem.URI_PREFIX) && !navigation.getPath().startsWith(ObjectExplorerHandle.URI_PREFIX)) { FileSystemItem file = FileSystemItem.createFile(navigation.getPath()); TextFileType fileType = fileTypeRegistry_.getTextTypeForFile(file); // open the file and restore the position openFile(file, fileType, new SourceNavigationResultCallback<EditingTarget>( navigation.getPosition(), retryCommand)); } else { // couldn't navigate to this item, retry if (retryCommand.isEnabled()) retryCommand.execute(); } } private void manageSourceNavigationCommands() { commands_.sourceNavigateBack().setEnabled( sourceNavigationHistory_.isBackEnabled()); commands_.sourceNavigateForward().setEnabled( sourceNavigationHistory_.isForwardEnabled()); } @Override public void onCodeBrowserNavigation(final CodeBrowserNavigationEvent event) { // if this isn't the main source window, don't handle server-dispatched // code browser events if (event.serverDispatched() && !SourceWindowManager.isMainSourceWindow()) { return; } tryExternalCodeBrowser(event.getFunction(), event, new Command() { @Override public void execute() { if (event.getDebugPosition() != null) { setPendingDebugSelection(); } activateCodeBrowser( CodeBrowserEditingTarget.getCodeBrowserPath(event.getFunction()), !event.serverDispatched(), new ResultCallback<CodeBrowserEditingTarget,ServerError>() { @Override public void onSuccess(CodeBrowserEditingTarget target) { target.showFunction(event.getFunction()); if (event.getDebugPosition() != null) { highlightDebugBrowserPosition(target, event.getDebugPosition(), event.getExecuting()); } } }); } }); } @Override public void onCodeBrowserFinished(final CodeBrowserFinishedEvent event) { tryExternalCodeBrowser(event.getFunction(), event, new Command() { @Override public void execute() { final String path = CodeBrowserEditingTarget.getCodeBrowserPath( event.getFunction()); for (int i = 0; i < editors_.size(); i++) { if (editors_.get(i).getPath() == path) { view_.closeTab(i, false); return; } } } }); } @Override public void onCodeBrowserHighlight(final CodeBrowserHighlightEvent event) { tryExternalCodeBrowser(event.getFunction(), event, new Command() { @Override public void execute() { setPendingDebugSelection(); activateCodeBrowser( CodeBrowserEditingTarget.getCodeBrowserPath(event.getFunction()), false, new ResultCallback<CodeBrowserEditingTarget,ServerError>() { @Override public void onSuccess(CodeBrowserEditingTarget target) { // if we just stole this code browser from another window, // we may need to repopulate it if (StringUtil.isNullOrEmpty(target.getContext())) target.showFunction(event.getFunction()); highlightDebugBrowserPosition(target, event.getDebugPosition(), true); } }); } }); } private void tryExternalCodeBrowser(SearchPathFunctionDefinition func, CrossWindowEvent<?> event, Command withLocalCodeBrowser) { final String path = CodeBrowserEditingTarget.getCodeBrowserPath(func); NavigationResult result = windowManager_.navigateToCodeBrowser( path, event); if (result.getType() != NavigationResult.RESULT_NAVIGATED) { withLocalCodeBrowser.execute(); } } private void highlightDebugBrowserPosition(CodeBrowserEditingTarget target, DebugFilePosition pos, boolean executing) { target.highlightDebugLocation(SourcePosition.create( pos.getLine(), pos.getColumn() - 1), SourcePosition.create( pos.getEndLine(), pos.getEndColumn() + 1), executing); } private void activateCodeBrowser( final String codeBrowserPath, boolean replaceIfActive, final ResultCallback<CodeBrowserEditingTarget,ServerError> callback) { // first check to see if this request can be fulfilled with an existing // code browser tab for (int i = 0; i < editors_.size(); i++) { if (editors_.get(i).getPath() == codeBrowserPath) { // select the tab ensureVisible(false); view_.selectTab(i); // callback callback.onSuccess((CodeBrowserEditingTarget) editors_.get(i)); // satisfied request return; } } // then check to see if the active editor is a code browser -- if it is, // we'll use it as is, replacing its contents if (replaceIfActive && activeEditor_ != null && activeEditor_ instanceof CodeBrowserEditingTarget) { events_.fireEvent(new CodeBrowserCreatedEvent(activeEditor_.getId(), codeBrowserPath)); callback.onSuccess((CodeBrowserEditingTarget) activeEditor_); return; } // create a new one newDoc(FileTypeRegistry.CODEBROWSER, new ResultCallback<EditingTarget, ServerError>() { @Override public void onSuccess(EditingTarget arg) { events_.fireEvent(new CodeBrowserCreatedEvent( arg.getId(), codeBrowserPath)); callback.onSuccess( (CodeBrowserEditingTarget)arg); } @Override public void onFailure(ServerError error) { callback.onFailure(error); } @Override public void onCancelled() { callback.onCancelled(); } }); } private boolean isDebugSelectionPending() { return debugSelectionTimer_ != null; } private void clearPendingDebugSelection() { if (debugSelectionTimer_ != null) { debugSelectionTimer_.cancel(); debugSelectionTimer_ = null; } } private void setPendingDebugSelection() { if (!isDebugSelectionPending()) { debugSelectionTimer_ = new Timer() { public void run() { debugSelectionTimer_ = null; } }; debugSelectionTimer_.schedule(250); } } private class SourceNavigationResultCallback<T extends EditingTarget> extends ResultCallback<T,ServerError> { public SourceNavigationResultCallback(SourcePosition restorePosition, AppCommand retryCommand) { suspendSourceNavigationAdding_ = true; restorePosition_ = restorePosition; retryCommand_ = retryCommand; } @Override public void onSuccess(final T target) { Scheduler.get().scheduleDeferred(new ScheduledCommand() { @Override public void execute() { try { target.restorePosition(restorePosition_); } finally { suspendSourceNavigationAdding_ = false; } } }); } @Override public void onFailure(ServerError info) { suspendSourceNavigationAdding_ = false; if (retryCommand_.isEnabled()) retryCommand_.execute(); } @Override public void onCancelled() { suspendSourceNavigationAdding_ = false; } private final SourcePosition restorePosition_; private final AppCommand retryCommand_; } @Override public void onSourceExtendedTypeDetected(SourceExtendedTypeDetectedEvent e) { // set the extended type of the specified source file for (EditingTarget editor : editors_) { if (editor.getId().equals(e.getDocId())) { editor.adaptToExtendedFileType(e.getExtendedType()); break; } } } @Override public void onSnippetsChanged(SnippetsChangedEvent event) { SnippetHelper.onSnippetsChanged(event); } // when tabs have been reordered in the session, the physical layout of the // tabs doesn't match the logical order of editors_. it's occasionally // necessary to get or set the tabs by their physical order. public int getPhysicalTabIndex() { int idx = view_.getActiveTabIndex(); if (idx < tabOrder_.size()) { idx = tabOrder_.indexOf(idx); } return idx; } public void setPhysicalTabIndex(int idx) { if (idx < tabOrder_.size()) { idx = tabOrder_.get(idx); } view_.selectTab(idx); } public EditingTarget getActiveEditor() { return activeEditor_; } public void onOpenProfileEvent(OpenProfileEvent event) { onShowProfiler(event); } private void inEditorForPath(String path, OperationWithInput<EditingTarget> onEditorLocated) { for (int i = 0; i < editors_.size(); i++) { String editorPath = editors_.get(i).getPath(); if (editorPath != null && editorPath.equals(path)) { onEditorLocated.execute(editors_.get(i)); break; } } } private void inEditorForId(String id, OperationWithInput<EditingTarget> onEditorLocated) { for (int i = 0; i < editors_.size(); i++) { String editorId = editors_.get(i).getId(); if (editorId != null && editorId.equals(id)) { onEditorLocated.execute(editors_.get(i)); break; } } } private void dispatchEditorEvent(final String id, final CommandWithArg<DocDisplay> command) { InputEditorDisplay console = consoleEditorProvider_.getConsoleEditor(); boolean isConsoleEvent = false; if (console != null) { isConsoleEvent = (StringUtil.isNullOrEmpty(id) && console.isFocused()) || "#console".equals(id); } if (isConsoleEvent) { command.execute((DocDisplay) console); } else { withTarget(id, new CommandWithArg<TextEditingTarget>() { @Override public void execute(TextEditingTarget target) { command.execute(target.getDocDisplay()); } }); } } @Override public void onSetSelectionRanges(final SetSelectionRangesEvent event) { dispatchEditorEvent(event.getData().getId(), new CommandWithArg<DocDisplay>() { @Override public void execute(DocDisplay docDisplay) { JsArray<Range> ranges = event.getData().getRanges(); if (ranges.length() == 0) return; AceEditor editor = (AceEditor) docDisplay; editor.setSelectionRanges(ranges); } }); } @Override public void onGetEditorContext(GetEditorContextEvent event) { GetEditorContextEvent.Data data = event.getData(); int type = data.getType(); if (type == GetEditorContextEvent.TYPE_ACTIVE_EDITOR) { if (consoleEditorHadFocusLast() || activeEditor_ == null) type = GetEditorContextEvent.TYPE_CONSOLE_EDITOR; else type = GetEditorContextEvent.TYPE_SOURCE_EDITOR; } if (type == GetEditorContextEvent.TYPE_CONSOLE_EDITOR) { InputEditorDisplay editor = consoleEditorProvider_.getConsoleEditor(); if (editor != null && editor instanceof DocDisplay) { getEditorContext("#console", "", (DocDisplay) editor); return; } } else if (type == GetEditorContextEvent.TYPE_SOURCE_EDITOR) { EditingTarget target = activeEditor_; if (target != null && target instanceof TextEditingTarget) { getEditorContext( target.getId(), target.getPath(), ((TextEditingTarget) target).getDocDisplay()); return; } } // We need to ensure a 'getEditorContext' event is always // returned as we have a 'wait-for' event on the server side server_.getEditorContextCompleted( GetEditorContextEvent.SelectionData.create(), new VoidServerRequestCallback()); } @Override public void onReplaceRanges(final ReplaceRangesEvent event) { dispatchEditorEvent(event.getData().getId(), new CommandWithArg<DocDisplay>() { @Override public void execute(DocDisplay docDisplay) { doReplaceRanges(event, docDisplay); } }); } private void doReplaceRanges(ReplaceRangesEvent event, DocDisplay docDisplay) { JsArray<ReplacementData> data = event.getData().getReplacementData(); int n = data.length(); for (int i = 0; i < n; i++) { ReplacementData el = data.get(n - i - 1); Range range = el.getRange(); String text = el.getText(); // A null range at this point is a proxy to use the current selection if (range == null) range = docDisplay.getSelectionRange(); docDisplay.replaceRange(range, text); } docDisplay.focus(); } private class OpenFileEntry { public OpenFileEntry(FileSystemItem fileIn, TextFileType fileTypeIn, CommandWithArg<EditingTarget> executeIn) { file = fileIn; fileType = fileTypeIn; executeOnSuccess = executeIn; } public final FileSystemItem file; public final TextFileType fileType; public final CommandWithArg<EditingTarget> executeOnSuccess; } private class StatFileEntry { public StatFileEntry(FileSystemItem fileIn, CommandWithArg<FileSystemItem> actionIn) { file = fileIn; action = actionIn; } public final FileSystemItem file; public final CommandWithArg<FileSystemItem> action; } final Queue<StatFileEntry> statQueue_ = new LinkedList<StatFileEntry>(); final Queue<OpenFileEntry> openFileQueue_ = new LinkedList<OpenFileEntry>(); ArrayList<EditingTarget> editors_ = new ArrayList<EditingTarget>(); ArrayList<Integer> tabOrder_ = new ArrayList<Integer>(); private EditingTarget activeEditor_; private final Commands commands_; private final Display view_; private final SourceServerOperations server_; private final EditingTargetSource editingTargetSource_; private final FileTypeRegistry fileTypeRegistry_; private final GlobalDisplay globalDisplay_; private final WorkbenchContext workbenchContext_; private final FileDialogs fileDialogs_; private final RemoteFileSystemContext fileContext_; private final TextEditingTargetRMarkdownHelper rmarkdown_; private final EventBus events_; private final Session session_; private final Synctex synctex_; private final Provider<FileMRUList> pMruList_; private final UIPrefs uiPrefs_; private final ConsoleEditorProvider consoleEditorProvider_; private final RnwWeaveRegistry rnwWeaveRegistry_; private HashSet<AppCommand> activeCommands_ = new HashSet<AppCommand>(); private final HashSet<AppCommand> dynamicCommands_; private final SourceNavigationHistory sourceNavigationHistory_ = new SourceNavigationHistory(30); private final SourceVimCommands vimCommands_; private boolean suspendSourceNavigationAdding_; private boolean suspendDocumentClose_ = false; private static final String MODULE_SOURCE = "source-pane"; private static final String KEY_ACTIVETAB = "activeTab"; private boolean initialized_; private Timer debugSelectionTimer_ = null; private final SourceWindowManager windowManager_; // If positive, a new tab is about to be created private int newTabPending_; private DependencyManager dependencyManager_; public final static int TYPE_FILE_BACKED = 0; public final static int TYPE_UNTITLED = 1; public final static int OPEN_INTERACTIVE = 0; public final static int OPEN_REPLAY = 1; }
src/gwt/src/org/rstudio/studio/client/workbench/views/source/Source.java
/* * Source.java * * Copyright (C) 2009-17 by RStudio, Inc. * * Unless you have received this program directly from RStudio pursuant * to the terms of a commercial license agreement with RStudio, then * this program is licensed to you under the terms of version 3 of the * GNU Affero General Public License. This program is distributed WITHOUT * ANY EXPRESS OR IMPLIED WARRANTY, INCLUDING THOSE OF NON-INFRINGEMENT, * MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE. Please refer to the * AGPL (http://www.gnu.org/licenses/agpl-3.0.txt) for more details. * */ package org.rstudio.studio.client.workbench.views.source; import com.google.gwt.core.client.JavaScriptObject; import com.google.gwt.core.client.JsArray; import com.google.gwt.core.client.JsArrayString; import com.google.gwt.core.client.Scheduler; import com.google.gwt.core.client.Scheduler.ScheduledCommand; import com.google.gwt.event.dom.client.ChangeEvent; import com.google.gwt.event.dom.client.ChangeHandler; import com.google.gwt.event.dom.client.KeyCodes; import com.google.gwt.event.logical.shared.CloseEvent; import com.google.gwt.event.logical.shared.CloseHandler; import com.google.gwt.event.logical.shared.HasBeforeSelectionHandlers; import com.google.gwt.event.logical.shared.HasSelectionHandlers; import com.google.gwt.event.logical.shared.SelectionEvent; import com.google.gwt.event.logical.shared.SelectionHandler; import com.google.gwt.event.logical.shared.ValueChangeEvent; import com.google.gwt.event.logical.shared.ValueChangeHandler; import com.google.gwt.event.shared.HandlerRegistration; import com.google.gwt.json.client.JSONString; import com.google.gwt.json.client.JSONValue; import com.google.gwt.resources.client.ImageResource; import com.google.gwt.user.client.Command; import com.google.gwt.user.client.Event; import com.google.gwt.user.client.Event.NativePreviewEvent; import com.google.gwt.user.client.Event.NativePreviewHandler; import com.google.gwt.user.client.Timer; import com.google.gwt.user.client.Window; import com.google.gwt.user.client.ui.IsWidget; import com.google.gwt.user.client.ui.Widget; import com.google.inject.Inject; import com.google.inject.Provider; import org.rstudio.core.client.*; import org.rstudio.core.client.command.AppCommand; import org.rstudio.core.client.command.Handler; import org.rstudio.core.client.command.KeyboardShortcut; import org.rstudio.core.client.command.ShortcutManager; import org.rstudio.core.client.events.*; import org.rstudio.core.client.files.FileSystemItem; import org.rstudio.core.client.js.JsObject; import org.rstudio.core.client.widget.Operation; import org.rstudio.core.client.widget.OperationWithInput; import org.rstudio.core.client.widget.ProgressIndicator; import org.rstudio.core.client.widget.ProgressOperationWithInput; import org.rstudio.studio.client.RStudioGinjector; import org.rstudio.studio.client.application.ApplicationAction; import org.rstudio.studio.client.application.ApplicationUtils; import org.rstudio.studio.client.application.Desktop; import org.rstudio.studio.client.application.events.CrossWindowEvent; import org.rstudio.studio.client.application.events.EventBus; import org.rstudio.studio.client.common.FileDialogs; import org.rstudio.studio.client.common.FilePathUtils; import org.rstudio.studio.client.common.GlobalDisplay; import org.rstudio.studio.client.common.GlobalProgressDelayer; import org.rstudio.studio.client.common.SimpleRequestCallback; import org.rstudio.studio.client.common.dependencies.DependencyManager; import org.rstudio.studio.client.common.filetypes.EditableFileType; import org.rstudio.studio.client.common.filetypes.FileTypeRegistry; import org.rstudio.studio.client.common.filetypes.TextFileType; import org.rstudio.studio.client.common.filetypes.events.OpenPresentationSourceFileEvent; import org.rstudio.studio.client.common.filetypes.events.OpenSourceFileEvent; import org.rstudio.studio.client.common.filetypes.events.OpenSourceFileHandler; import org.rstudio.studio.client.common.filetypes.model.NavigationMethods; import org.rstudio.studio.client.common.rnw.RnwWeave; import org.rstudio.studio.client.common.rnw.RnwWeaveRegistry; import org.rstudio.studio.client.common.satellite.Satellite; import org.rstudio.studio.client.common.synctex.Synctex; import org.rstudio.studio.client.common.synctex.events.SynctexStatusChangedEvent; import org.rstudio.studio.client.events.GetEditorContextEvent; import org.rstudio.studio.client.events.GetEditorContextEvent.DocumentSelection; import org.rstudio.studio.client.events.ReplaceRangesEvent; import org.rstudio.studio.client.events.ReplaceRangesEvent.ReplacementData; import org.rstudio.studio.client.events.SetSelectionRangesEvent; import org.rstudio.studio.client.rmarkdown.model.RmdChosenTemplate; import org.rstudio.studio.client.rmarkdown.model.RmdFrontMatter; import org.rstudio.studio.client.rmarkdown.model.RmdOutputFormat; import org.rstudio.studio.client.rmarkdown.model.RmdTemplateData; import org.rstudio.studio.client.server.ServerError; import org.rstudio.studio.client.server.ServerRequestCallback; import org.rstudio.studio.client.server.VoidServerRequestCallback; import org.rstudio.studio.client.workbench.ConsoleEditorProvider; import org.rstudio.studio.client.workbench.MainWindowObject; import org.rstudio.studio.client.workbench.FileMRUList; import org.rstudio.studio.client.workbench.WorkbenchContext; import org.rstudio.studio.client.workbench.codesearch.model.SearchPathFunctionDefinition; import org.rstudio.studio.client.workbench.commands.Commands; import org.rstudio.studio.client.workbench.events.ZoomPaneEvent; import org.rstudio.studio.client.workbench.model.ClientState; import org.rstudio.studio.client.workbench.model.RemoteFileSystemContext; import org.rstudio.studio.client.workbench.model.Session; import org.rstudio.studio.client.workbench.model.SessionInfo; import org.rstudio.studio.client.workbench.model.SessionUtils; import org.rstudio.studio.client.workbench.model.UnsavedChangesItem; import org.rstudio.studio.client.workbench.model.UnsavedChangesTarget; import org.rstudio.studio.client.workbench.model.helper.IntStateValue; import org.rstudio.studio.client.workbench.prefs.model.UIPrefs; import org.rstudio.studio.client.workbench.snippets.SnippetHelper; import org.rstudio.studio.client.workbench.snippets.model.SnippetsChangedEvent; import org.rstudio.studio.client.workbench.ui.unsaved.UnsavedChangesDialog; import org.rstudio.studio.client.workbench.views.console.shell.editor.InputEditorDisplay; import org.rstudio.studio.client.workbench.views.data.events.ViewDataEvent; import org.rstudio.studio.client.workbench.views.data.events.ViewDataHandler; import org.rstudio.studio.client.workbench.views.environment.events.DebugModeChangedEvent; import org.rstudio.studio.client.workbench.views.output.find.events.FindInFilesEvent; import org.rstudio.studio.client.workbench.views.source.NewShinyWebApplication.Result; import org.rstudio.studio.client.workbench.views.source.SourceWindowManager.NavigationResult; import org.rstudio.studio.client.workbench.views.source.editors.EditingTarget; import org.rstudio.studio.client.workbench.views.source.editors.EditingTargetSource; import org.rstudio.studio.client.workbench.views.source.editors.codebrowser.CodeBrowserEditingTarget; import org.rstudio.studio.client.workbench.views.source.editors.data.DataEditingTarget; import org.rstudio.studio.client.workbench.views.source.editors.explorer.ObjectExplorerEditingTarget; import org.rstudio.studio.client.workbench.views.source.editors.explorer.events.OpenObjectExplorerEvent; import org.rstudio.studio.client.workbench.views.source.editors.explorer.model.ObjectExplorerHandle; import org.rstudio.studio.client.workbench.views.source.editors.profiler.OpenProfileEvent; import org.rstudio.studio.client.workbench.views.source.editors.profiler.model.ProfilerContents; import org.rstudio.studio.client.workbench.views.source.editors.text.AceEditor; import org.rstudio.studio.client.workbench.views.source.editors.text.DocDisplay; import org.rstudio.studio.client.workbench.views.source.editors.text.TextEditingTarget; import org.rstudio.studio.client.workbench.views.source.editors.text.TextEditingTargetPresentationHelper; import org.rstudio.studio.client.workbench.views.source.editors.text.TextEditingTargetRMarkdownHelper; import org.rstudio.studio.client.workbench.views.source.editors.text.ace.AceEditorNative; import org.rstudio.studio.client.workbench.views.source.editors.text.ace.Position; import org.rstudio.studio.client.workbench.views.source.editors.text.ace.Range; import org.rstudio.studio.client.workbench.views.source.editors.text.ace.Selection; import org.rstudio.studio.client.workbench.views.source.editors.text.events.FileTypeChangedEvent; import org.rstudio.studio.client.workbench.views.source.editors.text.events.FileTypeChangedHandler; import org.rstudio.studio.client.workbench.views.source.editors.text.events.NewWorkingCopyEvent; import org.rstudio.studio.client.workbench.views.source.editors.text.events.SourceOnSaveChangedEvent; import org.rstudio.studio.client.workbench.views.source.editors.text.events.SourceOnSaveChangedHandler; import org.rstudio.studio.client.workbench.views.source.editors.text.ui.NewRMarkdownDialog; import org.rstudio.studio.client.workbench.views.source.editors.text.ui.NewRdDialog; import org.rstudio.studio.client.workbench.views.source.events.*; import org.rstudio.studio.client.workbench.views.source.model.ContentItem; import org.rstudio.studio.client.workbench.views.source.model.DataItem; import org.rstudio.studio.client.workbench.views.source.model.DocTabDragParams; import org.rstudio.studio.client.workbench.views.source.model.RdShellResult; import org.rstudio.studio.client.workbench.views.source.model.SourceDocument; import org.rstudio.studio.client.workbench.views.source.model.SourceDocumentResult; import org.rstudio.studio.client.workbench.views.source.model.SourceNavigation; import org.rstudio.studio.client.workbench.views.source.model.SourceNavigationHistory; import org.rstudio.studio.client.workbench.views.source.model.SourcePosition; import org.rstudio.studio.client.workbench.views.source.model.SourceServerOperations; import java.util.ArrayList; import java.util.HashSet; import java.util.LinkedList; import java.util.Queue; public class Source implements InsertSourceHandler, IsWidget, OpenSourceFileHandler, TabClosingHandler, TabCloseHandler, TabReorderHandler, SelectionHandler<Integer>, TabClosedHandler, FileEditHandler, ShowContentHandler, ShowDataHandler, CodeBrowserNavigationHandler, CodeBrowserFinishedHandler, CodeBrowserHighlightEvent.Handler, SourceExtendedTypeDetectedEvent.Handler, BeforeShowHandler, SnippetsChangedEvent.Handler, PopoutDocEvent.Handler, DocWindowChangedEvent.Handler, DocTabDragInitiatedEvent.Handler, PopoutDocInitiatedEvent.Handler, DebugModeChangedEvent.Handler, OpenProfileEvent.Handler, OpenObjectExplorerEvent.Handler, ReplaceRangesEvent.Handler, SetSelectionRangesEvent.Handler, GetEditorContextEvent.Handler { public interface Display extends IsWidget, HasTabClosingHandlers, HasTabCloseHandlers, HasTabClosedHandlers, HasTabReorderHandlers, HasBeforeSelectionHandlers<Integer>, HasSelectionHandlers<Integer> { void addTab(Widget widget, ImageResource icon, String docId, String name, String tooltip, Integer position, boolean switchToTab); void selectTab(int tabIndex); void selectTab(Widget widget); int getTabCount(); int getActiveTabIndex(); void closeTab(Widget widget, boolean interactive); void closeTab(Widget widget, boolean interactive, Command onClosed); void closeTab(int index, boolean interactive); void closeTab(int index, boolean interactive, Command onClosed); void moveTab(int index, int delta); void setDirty(Widget widget, boolean dirty); void manageChevronVisibility(); void showOverflowPopup(); void cancelTabDrag(); void showUnsavedChangesDialog( String title, ArrayList<UnsavedChangesTarget> dirtyTargets, OperationWithInput<UnsavedChangesDialog.Result> saveOperation, Command onCancelled); void ensureVisible(); void renameTab(Widget child, ImageResource icon, String value, String tooltip); HandlerRegistration addBeforeShowHandler(BeforeShowHandler handler); } public interface CPSEditingTargetCommand { void execute(EditingTarget editingTarget, Command continuation); } @Inject public Source(Commands commands, Display view, SourceServerOperations server, EditingTargetSource editingTargetSource, FileTypeRegistry fileTypeRegistry, GlobalDisplay globalDisplay, FileDialogs fileDialogs, RemoteFileSystemContext fileContext, EventBus events, final Session session, Synctex synctex, WorkbenchContext workbenchContext, Provider<FileMRUList> pMruList, UIPrefs uiPrefs, Satellite satellite, ConsoleEditorProvider consoleEditorProvider, RnwWeaveRegistry rnwWeaveRegistry, DependencyManager dependencyManager, SourceWindowManager windowManager) { commands_ = commands; view_ = view; server_ = server; editingTargetSource_ = editingTargetSource; fileTypeRegistry_ = fileTypeRegistry; globalDisplay_ = globalDisplay; fileDialogs_ = fileDialogs; fileContext_ = fileContext; rmarkdown_ = new TextEditingTargetRMarkdownHelper(); events_ = events; session_ = session; synctex_ = synctex; workbenchContext_ = workbenchContext; pMruList_ = pMruList; uiPrefs_ = uiPrefs; consoleEditorProvider_ = consoleEditorProvider; rnwWeaveRegistry_ = rnwWeaveRegistry; dependencyManager_ = dependencyManager; windowManager_ = windowManager; vimCommands_ = new SourceVimCommands(); view_.addTabClosingHandler(this); view_.addTabCloseHandler(this); view_.addTabClosedHandler(this); view_.addTabReorderHandler(this); view_.addSelectionHandler(this); view_.addBeforeShowHandler(this); dynamicCommands_ = new HashSet<AppCommand>(); dynamicCommands_.add(commands.saveSourceDoc()); dynamicCommands_.add(commands.reopenSourceDocWithEncoding()); dynamicCommands_.add(commands.saveSourceDocAs()); dynamicCommands_.add(commands.saveSourceDocWithEncoding()); dynamicCommands_.add(commands.printSourceDoc()); dynamicCommands_.add(commands.vcsFileLog()); dynamicCommands_.add(commands.vcsFileDiff()); dynamicCommands_.add(commands.vcsFileRevert()); dynamicCommands_.add(commands.executeCode()); dynamicCommands_.add(commands.executeCodeWithoutFocus()); dynamicCommands_.add(commands.executeAllCode()); dynamicCommands_.add(commands.executeToCurrentLine()); dynamicCommands_.add(commands.executeFromCurrentLine()); dynamicCommands_.add(commands.executeCurrentFunction()); dynamicCommands_.add(commands.executeCurrentSection()); dynamicCommands_.add(commands.executeLastCode()); dynamicCommands_.add(commands.insertChunk()); dynamicCommands_.add(commands.insertSection()); dynamicCommands_.add(commands.executeSetupChunk()); dynamicCommands_.add(commands.executePreviousChunks()); dynamicCommands_.add(commands.executeSubsequentChunks()); dynamicCommands_.add(commands.executeCurrentChunk()); dynamicCommands_.add(commands.executeNextChunk()); dynamicCommands_.add(commands.sourceActiveDocument()); dynamicCommands_.add(commands.sourceActiveDocumentWithEcho()); dynamicCommands_.add(commands.knitDocument()); dynamicCommands_.add(commands.previewHTML()); dynamicCommands_.add(commands.compilePDF()); dynamicCommands_.add(commands.compileNotebook()); dynamicCommands_.add(commands.synctexSearch()); dynamicCommands_.add(commands.popoutDoc()); dynamicCommands_.add(commands.returnDocToMain()); dynamicCommands_.add(commands.findReplace()); dynamicCommands_.add(commands.findNext()); dynamicCommands_.add(commands.findPrevious()); dynamicCommands_.add(commands.findFromSelection()); dynamicCommands_.add(commands.replaceAndFind()); dynamicCommands_.add(commands.extractFunction()); dynamicCommands_.add(commands.extractLocalVariable()); dynamicCommands_.add(commands.commentUncomment()); dynamicCommands_.add(commands.reindent()); dynamicCommands_.add(commands.reflowComment()); dynamicCommands_.add(commands.jumpTo()); dynamicCommands_.add(commands.jumpToMatching()); dynamicCommands_.add(commands.goToHelp()); dynamicCommands_.add(commands.goToFunctionDefinition()); dynamicCommands_.add(commands.setWorkingDirToActiveDoc()); dynamicCommands_.add(commands.debugDumpContents()); dynamicCommands_.add(commands.debugImportDump()); dynamicCommands_.add(commands.goToLine()); dynamicCommands_.add(commands.checkSpelling()); dynamicCommands_.add(commands.codeCompletion()); dynamicCommands_.add(commands.findUsages()); dynamicCommands_.add(commands.debugBreakpoint()); dynamicCommands_.add(commands.vcsViewOnGitHub()); dynamicCommands_.add(commands.vcsBlameOnGitHub()); dynamicCommands_.add(commands.editRmdFormatOptions()); dynamicCommands_.add(commands.reformatCode()); dynamicCommands_.add(commands.showDiagnosticsActiveDocument()); dynamicCommands_.add(commands.renameInScope()); dynamicCommands_.add(commands.insertRoxygenSkeleton()); dynamicCommands_.add(commands.expandSelection()); dynamicCommands_.add(commands.shrinkSelection()); dynamicCommands_.add(commands.toggleDocumentOutline()); dynamicCommands_.add(commands.knitWithParameters()); dynamicCommands_.add(commands.clearKnitrCache()); dynamicCommands_.add(commands.goToNextSection()); dynamicCommands_.add(commands.goToPrevSection()); dynamicCommands_.add(commands.goToNextChunk()); dynamicCommands_.add(commands.goToPrevChunk()); dynamicCommands_.add(commands.profileCode()); dynamicCommands_.add(commands.profileCodeWithoutFocus()); dynamicCommands_.add(commands.saveProfileAs()); dynamicCommands_.add(commands.restartRClearOutput()); dynamicCommands_.add(commands.restartRRunAllChunks()); dynamicCommands_.add(commands.notebookCollapseAllOutput()); dynamicCommands_.add(commands.notebookExpandAllOutput()); dynamicCommands_.add(commands.notebookClearOutput()); dynamicCommands_.add(commands.notebookClearAllOutput()); dynamicCommands_.add(commands.notebookToggleExpansion()); for (AppCommand command : dynamicCommands_) { command.setVisible(false); command.setEnabled(false); } // fake shortcuts for commands which we handle at a lower level commands.goToHelp().setShortcut(new KeyboardShortcut(112)); commands.goToFunctionDefinition().setShortcut(new KeyboardShortcut(113)); commands.codeCompletion().setShortcut( new KeyboardShortcut(KeyCodes.KEY_TAB)); // See bug 3673 and https://bugs.webkit.org/show_bug.cgi?id=41016 if (BrowseCap.isMacintosh()) { ShortcutManager.INSTANCE.register( KeyboardShortcut.META | KeyboardShortcut.ALT, 192, commands.executeNextChunk(), "Execute", commands.executeNextChunk().getMenuLabel(false), ""); } events.addHandler(ShowContentEvent.TYPE, this); events.addHandler(ShowDataEvent.TYPE, this); events.addHandler(OpenObjectExplorerEvent.TYPE, this); events.addHandler(ViewDataEvent.TYPE, new ViewDataHandler() { public void onViewData(ViewDataEvent event) { server_.newDocument( FileTypeRegistry.DATAFRAME.getTypeId(), null, JsObject.createJsObject(), new SimpleRequestCallback<SourceDocument>("Edit Data Frame") { public void onResponseReceived(SourceDocument response) { addTab(response, OPEN_INTERACTIVE); } }); } }); events.addHandler(CodeBrowserNavigationEvent.TYPE, this); events.addHandler(CodeBrowserFinishedEvent.TYPE, this); events.addHandler(CodeBrowserHighlightEvent.TYPE, this); events.addHandler(FileTypeChangedEvent.TYPE, new FileTypeChangedHandler() { public void onFileTypeChanged(FileTypeChangedEvent event) { manageCommands(); } }); events.addHandler(SourceOnSaveChangedEvent.TYPE, new SourceOnSaveChangedHandler() { @Override public void onSourceOnSaveChanged(SourceOnSaveChangedEvent event) { manageSaveCommands(); } }); events.addHandler(SwitchToDocEvent.TYPE, new SwitchToDocHandler() { public void onSwitchToDoc(SwitchToDocEvent event) { ensureVisible(false); setPhysicalTabIndex(event.getSelectedIndex()); // Fire an activation event just to ensure the activated // tab gets focus commands_.activateSource().execute(); } }); events.addHandler(SourceFileSavedEvent.TYPE, new SourceFileSavedHandler() { public void onSourceFileSaved(SourceFileSavedEvent event) { pMruList_.get().add(event.getPath()); } }); events.addHandler(SourcePathChangedEvent.TYPE, new SourcePathChangedEvent.Handler() { @Override public void onSourcePathChanged(final SourcePathChangedEvent event) { inEditorForPath(event.getFrom(), new OperationWithInput<EditingTarget>() { @Override public void execute(EditingTarget input) { FileSystemItem toPath = FileSystemItem.createFile(event.getTo()); if (input instanceof TextEditingTarget) { // for text files, notify the editing surface so it can // react to the new file type ((TextEditingTarget)input).setPath(toPath); } else { // for other files, just rename the tab input.getName().setValue(toPath.getName(), true); } events_.fireEvent(new SourceFileSavedEvent( input.getId(), event.getTo())); } }); } }); events.addHandler(SourceNavigationEvent.TYPE, new SourceNavigationHandler() { @Override public void onSourceNavigation(SourceNavigationEvent event) { if (!suspendSourceNavigationAdding_) { sourceNavigationHistory_.add(event.getNavigation()); } } }); events.addHandler(SourceExtendedTypeDetectedEvent.TYPE, this); sourceNavigationHistory_.addChangeHandler(new ChangeHandler() { @Override public void onChange(ChangeEvent event) { manageSourceNavigationCommands(); } }); events.addHandler(SynctexStatusChangedEvent.TYPE, new SynctexStatusChangedEvent.Handler() { @Override public void onSynctexStatusChanged(SynctexStatusChangedEvent event) { manageSynctexCommands(); } }); events.addHandler(CollabEditStartedEvent.TYPE, new CollabEditStartedEvent.Handler() { @Override public void onCollabEditStarted(final CollabEditStartedEvent collab) { inEditorForPath(collab.getStartParams().getPath(), new OperationWithInput<EditingTarget>() { @Override public void execute(EditingTarget editor) { editor.beginCollabSession(collab.getStartParams()); } }); } }); events.addHandler(CollabEditEndedEvent.TYPE, new CollabEditEndedEvent.Handler() { @Override public void onCollabEditEnded(final CollabEditEndedEvent collab) { inEditorForPath(collab.getPath(), new OperationWithInput<EditingTarget>() { @Override public void execute(EditingTarget editor) { editor.endCollabSession(); } }); } }); events.addHandler(NewWorkingCopyEvent.TYPE, new NewWorkingCopyEvent.Handler() { @Override public void onNewWorkingCopy(NewWorkingCopyEvent event) { newDoc(event.getType(), event.getContents(), null); } }); events.addHandler(PopoutDocEvent.TYPE, this); events.addHandler(DocWindowChangedEvent.TYPE, this); events.addHandler(DocTabDragInitiatedEvent.TYPE, this); events.addHandler(PopoutDocInitiatedEvent.TYPE, this); events.addHandler(DebugModeChangedEvent.TYPE, this); events.addHandler(ReplaceRangesEvent.TYPE, this); events.addHandler(GetEditorContextEvent.TYPE, this); events.addHandler(SetSelectionRangesEvent.TYPE, this); events.addHandler(OpenProfileEvent.TYPE, this); // Suppress 'CTRL + ALT + SHIFT + click' to work around #2483 in Ace Event.addNativePreviewHandler(new NativePreviewHandler() { @Override public void onPreviewNativeEvent(NativePreviewEvent event) { int type = event.getTypeInt(); if (type == Event.ONMOUSEDOWN || type == Event.ONMOUSEUP) { int modifier = KeyboardShortcut.getModifierValue(event.getNativeEvent()); if (modifier == (KeyboardShortcut.ALT | KeyboardShortcut.CTRL | KeyboardShortcut.SHIFT)) { event.cancel(); return; } } } }); restoreDocuments(session); // get the key to use for active tab persistence; use ordinal-based key // for source windows rather than their ID to avoid unbounded accumulation String activeTabKey = KEY_ACTIVETAB; if (!SourceWindowManager.isMainSourceWindow()) activeTabKey += "SourceWindow" + windowManager_.getSourceWindowOrdinal(); new IntStateValue(MODULE_SOURCE, activeTabKey, ClientState.PROJECT_PERSISTENT, session.getSessionInfo().getClientState()) { @Override protected void onInit(Integer value) { if (value == null) return; if (value >= 0 && view_.getTabCount() > value) view_.selectTab(value); if (view_.getTabCount() > 0 && view_.getActiveTabIndex() >= 0) { editors_.get(view_.getActiveTabIndex()).onInitiallyLoaded(); } // clear the history manager sourceNavigationHistory_.clear(); } @Override protected Integer getValue() { return getPhysicalTabIndex(); } }; AceEditorNative.syncUiPrefs(uiPrefs_); // sync UI prefs with shortcut manager if (uiPrefs_.useVimMode().getGlobalValue()) ShortcutManager.INSTANCE.setEditorMode(KeyboardShortcut.MODE_VIM); else if (uiPrefs_.enableEmacsKeybindings().getGlobalValue()) ShortcutManager.INSTANCE.setEditorMode(KeyboardShortcut.MODE_EMACS); else ShortcutManager.INSTANCE.setEditorMode(KeyboardShortcut.MODE_DEFAULT); initialized_ = true; // As tabs were added before, manageCommands() was suppressed due to // initialized_ being false, so we need to run it explicitly manageCommands(); // Same with this event fireDocTabsChanged(); // open project or edit_published docs (only for main source window) if (SourceWindowManager.isMainSourceWindow()) { openProjectDocs(session); openEditPublishedDocs(); } // add vim commands initVimCommands(); } private boolean consoleEditorHadFocusLast() { String id = MainWindowObject.lastFocusedEditor().get(); return "rstudio_console_input".equals(id); } private void withTarget(String id, CommandWithArg<TextEditingTarget> command, Command onFailure) { EditingTarget target = StringUtil.isNullOrEmpty(id) ? activeEditor_ : getEditingTargetForId(id); if (target == null) { if (onFailure != null) onFailure.execute(); return; } if (!(target instanceof TextEditingTarget)) { if (onFailure != null) onFailure.execute(); return; } command.execute((TextEditingTarget) target); } private void getEditorContext(String id, String path, DocDisplay docDisplay) { AceEditor editor = (AceEditor) docDisplay; Selection selection = editor.getNativeSelection(); Range[] ranges = selection.getAllRanges(); JsArray<DocumentSelection> docSelections = JavaScriptObject.createArray().cast(); for (int i = 0; i < ranges.length; i++) { docSelections.push(DocumentSelection.create( ranges[i], editor.getTextForRange(ranges[i]))); } id = StringUtil.notNull(id); path = StringUtil.notNull(path); GetEditorContextEvent.SelectionData data = GetEditorContextEvent.SelectionData.create(id, path, editor.getCode(), docSelections); server_.getEditorContextCompleted(data, new VoidServerRequestCallback()); } private void withTarget(String id, CommandWithArg<TextEditingTarget> command) { withTarget(id, command, null); } private void initVimCommands() { vimCommands_.save(this); vimCommands_.selectTabIndex(this); vimCommands_.selectNextTab(this); vimCommands_.selectPreviousTab(this); vimCommands_.closeActiveTab(this); vimCommands_.closeAllTabs(this); vimCommands_.createNewDocument(this); vimCommands_.saveAndCloseActiveTab(this); vimCommands_.readFile(this, uiPrefs_.defaultEncoding().getValue()); vimCommands_.runRScript(this); vimCommands_.reflowText(this); vimCommands_.showVimHelp( RStudioGinjector.INSTANCE.getShortcutViewer()); vimCommands_.showHelpAtCursor(this); vimCommands_.reindent(this); vimCommands_.expandShrinkSelection(this); vimCommands_.addStarRegister(); } private void vimSetTabIndex(int index) { int tabCount = view_.getTabCount(); if (index >= tabCount) return; setPhysicalTabIndex(index); } private void closeAllTabs(boolean interactive) { if (interactive) { // call into the interactive tab closer onCloseAllSourceDocs(); } else { // revert unsaved targets and close tabs revertUnsavedTargets(new Command() { @Override public void execute() { // documents have been reverted; we can close cpsExecuteForEachEditor(editors_, new CPSEditingTargetCommand() { @Override public void execute(EditingTarget editingTarget, Command continuation) { view_.closeTab( editingTarget.asWidget(), false, continuation); } }); } }); } } private void saveActiveSourceDoc() { if (activeEditor_ != null && activeEditor_ instanceof TextEditingTarget) { TextEditingTarget target = (TextEditingTarget) activeEditor_; target.save(); } } private void saveAndCloseActiveSourceDoc() { if (activeEditor_ != null && activeEditor_ instanceof TextEditingTarget) { TextEditingTarget target = (TextEditingTarget) activeEditor_; target.save(new Command() { @Override public void execute() { onCloseSourceDoc(); } }); } } /** * @param isNewTabPending True if a new tab is about to be created. (If * false and there are no tabs already, then a new source doc might * be created to make sure we don't end up with a source pane showing * with no tabs in it.) */ private void ensureVisible(boolean isNewTabPending) { newTabPending_++; try { view_.ensureVisible(); } finally { newTabPending_--; } } public Widget asWidget() { return view_.asWidget(); } private void restoreDocuments(final Session session) { final JsArray<SourceDocument> docs = session.getSessionInfo().getSourceDocuments(); for (int i = 0; i < docs.length(); i++) { // restore the docs assigned to this source window SourceDocument doc = docs.get(i); String docWindowId = doc.getProperties().getString( SourceWindowManager.SOURCE_WINDOW_ID); if (docWindowId == null) docWindowId = ""; String currentSourceWindowId = SourceWindowManager.getSourceWindowId(); // it belongs in this window if (a) it's assigned to it, or (b) this // is the main window, and the window it's assigned to isn't open. if (currentSourceWindowId == docWindowId || (SourceWindowManager.isMainSourceWindow() && !windowManager_.isSourceWindowOpen(docWindowId))) { // attempt to add a tab for the current doc; try/catch this since // we don't want to allow one failure to prevent all docs from // opening EditingTarget sourceEditor = null; try { sourceEditor = addTab(doc, true, OPEN_REPLAY); } catch (Exception e) { Debug.logException(e); } // if we couldn't add the tab for this doc, just continue to the // next one if (sourceEditor == null) continue; } } } private void openEditPublishedDocs() { // don't do this if we are switching projects (it // will be done after the switch) if (ApplicationAction.isSwitchProject()) return; // check for edit_published url parameter final String kEditPublished = "edit_published"; String editPublished = StringUtil.notNull( Window.Location.getParameter(kEditPublished)); // this is an appPath which we can call the server // to determine source files to edit if (editPublished.length() > 0) { // remove it from the url ApplicationUtils.removeQueryParam(kEditPublished); server_.getEditPublishedDocs( editPublished, new SimpleRequestCallback<JsArrayString>() { @Override public void onResponseReceived(JsArrayString docs) { new SourceFilesOpener(docs).run(); } } ); } } private void openProjectDocs(final Session session) { JsArrayString openDocs = session.getSessionInfo().getProjectOpenDocs(); if (openDocs.length() > 0) { // set new tab pending for the duration of the continuation newTabPending_++; // create a continuation for opening the source docs SerializedCommandQueue openCommands = new SerializedCommandQueue(); for (int i=0; i<openDocs.length(); i++) { String doc = openDocs.get(i); final FileSystemItem fsi = FileSystemItem.createFile(doc); openCommands.addCommand(new SerializedCommand() { @Override public void onExecute(final Command continuation) { openFile(fsi, fileTypeRegistry_.getTextTypeForFile(fsi), new CommandWithArg<EditingTarget>() { @Override public void execute(EditingTarget arg) { continuation.execute(); } }); } }); } // decrement newTabPending and select first tab when done openCommands.addCommand(new SerializedCommand() { @Override public void onExecute(Command continuation) { newTabPending_--; onFirstTab(); continuation.execute(); } }); // execute the continuation openCommands.run(); } } public void onShowContent(ShowContentEvent event) { // ignore if we're a satellite if (!SourceWindowManager.isMainSourceWindow()) return; ensureVisible(true); ContentItem content = event.getContent(); server_.newDocument( FileTypeRegistry.URLCONTENT.getTypeId(), null, (JsObject) content.cast(), new SimpleRequestCallback<SourceDocument>("Show") { @Override public void onResponseReceived(SourceDocument response) { addTab(response, OPEN_INTERACTIVE); } }); } @Override public void onOpenObjectExplorerEvent(OpenObjectExplorerEvent event) { // ignore if we're a satellite if (!SourceWindowManager.isMainSourceWindow()) return; ObjectExplorerHandle handle = event.getHandle(); // attempt to open pre-existing tab for (int i = 0; i < editors_.size(); i++) { String path = editors_.get(i).getPath(); if (path != null && path.equals(handle.getPath())) { ((ObjectExplorerEditingTarget)editors_.get(i)).update(handle); ensureVisible(false); view_.selectTab(i); return; } } ensureVisible(true); server_.newDocument( FileTypeRegistry.OBJECT_EXPLORER.getTypeId(), null, (JsObject) handle.cast(), new SimpleRequestCallback<SourceDocument>("Show Object Explorer") { @Override public void onResponseReceived(SourceDocument response) { addTab(response, OPEN_INTERACTIVE); } }); } @Override public void onShowData(ShowDataEvent event) { // ignore if we're a satellite if (!SourceWindowManager.isMainSourceWindow()) return; DataItem data = event.getData(); for (int i = 0; i < editors_.size(); i++) { String path = editors_.get(i).getPath(); if (path != null && path.equals(data.getURI())) { ((DataEditingTarget)editors_.get(i)).updateData(data); ensureVisible(false); view_.selectTab(i); return; } } ensureVisible(true); server_.newDocument( FileTypeRegistry.DATAFRAME.getTypeId(), null, (JsObject) data.cast(), new SimpleRequestCallback<SourceDocument>("Show Data Frame") { @Override public void onResponseReceived(SourceDocument response) { addTab(response, OPEN_INTERACTIVE); } }); } public void onShowProfiler(OpenProfileEvent event) { String profilePath = event.getFilePath(); String htmlPath = event.getHtmlPath(); String htmlLocalPath = event.getHtmlLocalPath(); // first try to activate existing for (int idx = 0; idx < editors_.size(); idx++) { String path = editors_.get(idx).getPath(); if (path != null && profilePath.equals(path)) { ensureVisible(false); view_.selectTab(idx); return; } } // create new profiler ensureVisible(true); if (event.getDocId() != null) { server_.getSourceDocument(event.getDocId(), new ServerRequestCallback<SourceDocument>() { @Override public void onResponseReceived(SourceDocument response) { addTab(response, OPEN_INTERACTIVE); } @Override public void onError(ServerError error) { Debug.logError(error); globalDisplay_.showErrorMessage("Source Document Error", error.getUserMessage()); } }); } else { server_.newDocument( FileTypeRegistry.PROFILER.getTypeId(), null, (JsObject) ProfilerContents.create( profilePath, htmlPath, htmlLocalPath, event.getCreateProfile()).cast(), new SimpleRequestCallback<SourceDocument>("Show Profiler") { @Override public void onResponseReceived(SourceDocument response) { addTab(response, OPEN_INTERACTIVE); } @Override public void onError(ServerError error) { Debug.logError(error); globalDisplay_.showErrorMessage("Source Document Error", error.getUserMessage()); } }); } } @Handler public void onNewSourceDoc() { newDoc(FileTypeRegistry.R, null); } @Handler public void onNewTextDoc() { newDoc(FileTypeRegistry.TEXT, null); } @Handler public void onNewRNotebook() { dependencyManager_.withRMarkdown("R Notebook", "Create R Notebook", new CommandWithArg<Boolean>() { @Override public void execute(Boolean succeeded) { if (!succeeded) { globalDisplay_.showErrorMessage("Notebook Creation Failed", "One or more packages required for R Notebook " + "creation were not installed."); return; } String basename = "r_markdown_notebook"; if (BrowseCap.isMacintosh()) basename += "_osx"; newSourceDocWithTemplate( FileTypeRegistry.RMARKDOWN, "", basename + ".Rmd", Position.create(3, 0)); } }); } @Handler public void onNewCppDoc() { if (uiPrefs_.useRcppTemplate().getValue()) { newSourceDocWithTemplate( FileTypeRegistry.CPP, "", "rcpp.cpp", Position.create(0, 0), new CommandWithArg<EditingTarget> () { @Override public void execute(EditingTarget target) { target.verifyCppPrerequisites(); } } ); } else { newDoc(FileTypeRegistry.CPP, new ResultCallback<EditingTarget, ServerError> () { @Override public void onSuccess(EditingTarget target) { target.verifyCppPrerequisites(); } }); } } @Handler public void onNewSweaveDoc() { // set concordance value if we need to String concordance = new String(); if (uiPrefs_.alwaysEnableRnwConcordance().getValue()) { RnwWeave activeWeave = rnwWeaveRegistry_.findTypeIgnoreCase( uiPrefs_.defaultSweaveEngine().getValue()); if (activeWeave.getInjectConcordance()) concordance = "\\SweaveOpts{concordance=TRUE}\n"; } final String concordanceValue = concordance; // show progress final ProgressIndicator indicator = new GlobalProgressDelayer( globalDisplay_, 500, "Creating new document...").getIndicator(); // get the template server_.getSourceTemplate("", "sweave.Rnw", new ServerRequestCallback<String>() { @Override public void onResponseReceived(String templateContents) { indicator.onCompleted(); // add in concordance if necessary final boolean hasConcordance = concordanceValue.length() > 0; if (hasConcordance) { String beginDoc = "\\begin{document}\n"; templateContents = templateContents.replace( beginDoc, beginDoc + concordanceValue); } newDoc(FileTypeRegistry.SWEAVE, templateContents, new ResultCallback<EditingTarget, ServerError> () { @Override public void onSuccess(EditingTarget target) { int startRow = 4 + (hasConcordance ? 1 : 0); target.setCursorPosition(Position.create(startRow, 0)); } }); } @Override public void onError(ServerError error) { indicator.onError(error.getUserMessage()); } }); } @Handler public void onNewRMarkdownDoc() { SessionInfo sessionInfo = session_.getSessionInfo(); boolean useRMarkdownV2 = sessionInfo.getRMarkdownPackageAvailable(); if (useRMarkdownV2) newRMarkdownV2Doc(); else newRMarkdownV1Doc(); } private void doNewRShinyApp(NewShinyWebApplication.Result result) { server_.createShinyApp( result.getAppName(), result.getAppType(), result.getAppDir(), new SimpleRequestCallback<JsArrayString>("Error Creating Shiny Application", true) { @Override public void onResponseReceived(JsArrayString createdFiles) { // Open and focus files that we created new SourceFilesOpener(createdFiles).run(); } }); } // open a list of source files then focus the first one within the list private class SourceFilesOpener extends SerializedCommandQueue { public SourceFilesOpener(JsArrayString sourceFiles) { for (int i=0; i<sourceFiles.length(); i++) { final String filePath = sourceFiles.get(i); addCommand(new SerializedCommand() { @Override public void onExecute(final Command continuation) { FileSystemItem path = FileSystemItem.createFile(filePath); openFile(path, FileTypeRegistry.R, new CommandWithArg<EditingTarget>() { @Override public void execute(EditingTarget target) { // record first target if necessary if (firstTarget_ == null) firstTarget_ = target; continuation.execute(); } }); } }); } addCommand(new SerializedCommand() { @Override public void onExecute(Command continuation) { if (firstTarget_ != null) { view_.selectTab(firstTarget_.asWidget()); firstTarget_.setCursorPosition(Position.create(0, 0)); } continuation.execute(); } }); } private EditingTarget firstTarget_ = null; } @Handler public void onNewRShinyApp() { dependencyManager_.withShiny("Creating Shiny applications", new Command() { @Override public void execute() { NewShinyWebApplication widget = new NewShinyWebApplication( "New Shiny Web Application", new OperationWithInput<NewShinyWebApplication.Result>() { @Override public void execute(Result input) { doNewRShinyApp(input); } }); widget.showModal(); } }); } @Handler public void onNewRHTMLDoc() { newSourceDocWithTemplate(FileTypeRegistry.RHTML, "", "r_html.Rhtml"); } @Handler public void onNewRDocumentationDoc() { new NewRdDialog( new OperationWithInput<NewRdDialog.Result>() { @Override public void execute(final NewRdDialog.Result result) { final Command createEmptyDoc = new Command() { @Override public void execute() { newSourceDocWithTemplate(FileTypeRegistry.RD, result.name, "r_documentation_empty.Rd", Position.create(3, 7)); } }; if (!result.type.equals(NewRdDialog.Result.TYPE_NONE)) { server_.createRdShell( result.name, result.type, new SimpleRequestCallback<RdShellResult>() { @Override public void onResponseReceived(RdShellResult result) { if (result.getPath() != null) { fileTypeRegistry_.openFile( FileSystemItem.createFile(result.getPath())); } else if (result.getContents() != null) { newDoc(FileTypeRegistry.RD, result.getContents(), null); } else { createEmptyDoc.execute(); } } }); } else { createEmptyDoc.execute(); } } }).showModal(); } @Handler public void onNewRPresentationDoc() { dependencyManager_.withRMarkdown( "Authoring R Presentations", new Command() { @Override public void execute() { fileDialogs_.saveFile( "New R Presentation", fileContext_, workbenchContext_.getDefaultFileDialogDir(), ".Rpres", true, new ProgressOperationWithInput<FileSystemItem>() { @Override public void execute(final FileSystemItem input, final ProgressIndicator indicator) { if (input == null) { indicator.onCompleted(); return; } indicator.onProgress("Creating Presentation..."); server_.createNewPresentation( input.getPath(), new VoidServerRequestCallback(indicator) { @Override public void onSuccess() { openFile(input, FileTypeRegistry.RPRESENTATION, new CommandWithArg<EditingTarget>() { @Override public void execute(EditingTarget arg) { server_.showPresentationPane( input.getPath(), new VoidServerRequestCallback()); } }); } }); } }); } }); } private void newRMarkdownV1Doc() { newSourceDocWithTemplate(FileTypeRegistry.RMARKDOWN, "", "r_markdown.Rmd", Position.create(3, 0)); } private void newRMarkdownV2Doc() { rmarkdown_.showNewRMarkdownDialog( new OperationWithInput<NewRMarkdownDialog.Result>() { @Override public void execute(final NewRMarkdownDialog.Result result) { if (result.isNewDocument()) { NewRMarkdownDialog.RmdNewDocument doc = result.getNewDocument(); String author = doc.getAuthor(); if (author.length() > 0) { uiPrefs_.documentAuthor().setGlobalValue(author); uiPrefs_.writeUIPrefs(); } newRMarkdownV2Doc(doc); } else { newDocFromRmdTemplate(result); } } }); } private void newDocFromRmdTemplate(final NewRMarkdownDialog.Result result) { final RmdChosenTemplate template = result.getFromTemplate(); if (template.createDir()) { rmarkdown_.createDraftFromTemplate(template); return; } rmarkdown_.getTemplateContent(template, new OperationWithInput<String>() { @Override public void execute(final String content) { if (content.length() == 0) globalDisplay_.showErrorMessage("Template Content Missing", "The template at " + template.getTemplatePath() + " is missing."); newDoc(FileTypeRegistry.RMARKDOWN, content, null); } }); } private void newRMarkdownV2Doc( final NewRMarkdownDialog.RmdNewDocument doc) { rmarkdown_.frontMatterToYAML((RmdFrontMatter)doc.getJSOResult().cast(), null, new CommandWithArg<String>() { @Override public void execute(final String yaml) { String template = ""; // select a template appropriate to the document type we're creating if (doc.getTemplate().equals(RmdTemplateData.PRESENTATION_TEMPLATE)) template = "r_markdown_v2_presentation.Rmd"; else if (doc.isShiny()) { if (doc.getFormat().endsWith( RmdOutputFormat.OUTPUT_PRESENTATION_SUFFIX)) template = "r_markdown_presentation_shiny.Rmd"; else template = "r_markdown_shiny.Rmd"; } else template = "r_markdown_v2.Rmd"; newSourceDocWithTemplate(FileTypeRegistry.RMARKDOWN, "", template, Position.create(1, 0), null, new TransformerCommand<String>() { @Override public String transform(String input) { return RmdFrontMatter.FRONTMATTER_SEPARATOR + yaml + RmdFrontMatter.FRONTMATTER_SEPARATOR + "\n" + input; } }); } }); } private void newSourceDocWithTemplate(final TextFileType fileType, String name, String template) { newSourceDocWithTemplate(fileType, name, template, null); } private void newSourceDocWithTemplate(final TextFileType fileType, String name, String template, final Position cursorPosition) { newSourceDocWithTemplate(fileType, name, template, cursorPosition, null); } private void newSourceDocWithTemplate( final TextFileType fileType, String name, String template, final Position cursorPosition, final CommandWithArg<EditingTarget> onSuccess) { newSourceDocWithTemplate(fileType, name, template, cursorPosition, onSuccess, null); } private void newSourceDocWithTemplate( final TextFileType fileType, String name, String template, final Position cursorPosition, final CommandWithArg<EditingTarget> onSuccess, final TransformerCommand<String> contentTransformer) { final ProgressIndicator indicator = new GlobalProgressDelayer( globalDisplay_, 500, "Creating new document...").getIndicator(); server_.getSourceTemplate(name, template, new ServerRequestCallback<String>() { @Override public void onResponseReceived(String templateContents) { indicator.onCompleted(); if (contentTransformer != null) templateContents = contentTransformer.transform(templateContents); newDoc(fileType, templateContents, new ResultCallback<EditingTarget, ServerError> () { @Override public void onSuccess(EditingTarget target) { if (cursorPosition != null) target.setCursorPosition(cursorPosition); if (onSuccess != null) onSuccess.execute(target); } }); } @Override public void onError(ServerError error) { indicator.onError(error.getUserMessage()); } }); } private void newDoc(EditableFileType fileType, ResultCallback<EditingTarget, ServerError> callback) { newDoc(fileType, null, callback); } private void newDoc(EditableFileType fileType, final String contents, final ResultCallback<EditingTarget, ServerError> resultCallback) { ensureVisible(true); server_.newDocument( fileType.getTypeId(), contents, JsObject.createJsObject(), new SimpleRequestCallback<SourceDocument>( "Error Creating New Document") { @Override public void onResponseReceived(SourceDocument newDoc) { EditingTarget target = addTab(newDoc, OPEN_INTERACTIVE); if (contents != null) { target.forceSaveCommandActive(); manageSaveCommands(); } if (resultCallback != null) resultCallback.onSuccess(target); } @Override public void onError(ServerError error) { if (resultCallback != null) resultCallback.onFailure(error); } }); } @Handler public void onFindInFiles() { String searchPattern = ""; if (activeEditor_ != null && activeEditor_ instanceof TextEditingTarget) { TextEditingTarget textEditor = (TextEditingTarget) activeEditor_; String selection = textEditor.getSelectedText(); boolean multiLineSelection = selection.indexOf('\n') != -1; if ((selection.length() != 0) && !multiLineSelection) searchPattern = selection; } events_.fireEvent(new FindInFilesEvent(searchPattern)); } @Handler public void onActivateSource() { onActivateSource(null); } public void onActivateSource(final Command afterActivation) { // give the window manager a chance to activate the last source pane if (windowManager_.activateLastFocusedSource()) return; if (activeEditor_ == null) { newDoc(FileTypeRegistry.R, new ResultCallback<EditingTarget, ServerError>() { @Override public void onSuccess(EditingTarget target) { activeEditor_ = target; doActivateSource(afterActivation); } }); } else { doActivateSource(afterActivation); } } @Handler public void onLayoutZoomSource() { onActivateSource(new Command() { @Override public void execute() { events_.fireEvent(new ZoomPaneEvent("Source")); } }); } private void doActivateSource(final Command afterActivation) { ensureVisible(false); if (activeEditor_ != null) { activeEditor_.focus(); activeEditor_.ensureCursorVisible(); } if (afterActivation != null) afterActivation.execute(); } @Handler public void onSwitchToTab() { if (view_.getTabCount() == 0) return; ensureVisible(false); view_.showOverflowPopup(); } @Handler public void onFirstTab() { if (view_.getTabCount() == 0) return; ensureVisible(false); if (view_.getTabCount() > 0) setPhysicalTabIndex(0); } @Handler public void onPreviousTab() { switchToTab(-1, uiPrefs_.wrapTabNavigation().getValue()); } @Handler public void onNextTab() { switchToTab(1, uiPrefs_.wrapTabNavigation().getValue()); } @Handler public void onLastTab() { if (view_.getTabCount() == 0) return; ensureVisible(false); if (view_.getTabCount() > 0) setPhysicalTabIndex(view_.getTabCount() - 1); } public void nextTabWithWrap() { switchToTab(1, true); } public void prevTabWithWrap() { switchToTab(-1, true); } private void switchToTab(int delta, boolean wrap) { if (view_.getTabCount() == 0) return; ensureVisible(false); int targetIndex = getPhysicalTabIndex() + delta; if (targetIndex > (view_.getTabCount() - 1)) { if (wrap) targetIndex = 0; else return; } else if (targetIndex < 0) { if (wrap) targetIndex = view_.getTabCount() - 1; else return; } setPhysicalTabIndex(targetIndex); } @Handler public void onMoveTabRight() { view_.moveTab(getPhysicalTabIndex(), 1); } @Handler public void onMoveTabLeft() { view_.moveTab(getPhysicalTabIndex(), -1); } @Handler public void onMoveTabToFirst() { view_.moveTab(getPhysicalTabIndex(), getPhysicalTabIndex() * -1); } @Handler public void onMoveTabToLast() { view_.moveTab(getPhysicalTabIndex(), (view_.getTabCount() - getPhysicalTabIndex()) - 1); } @Override public void onPopoutDoc(final PopoutDocEvent e) { // disowning the doc may cause the entire window to close, so defer it // to allow any other popout processing to occur Scheduler.get().scheduleDeferred(new ScheduledCommand() { @Override public void execute() { disownDoc(e.getDocId()); } }); } @Override public void onDebugModeChanged(DebugModeChangedEvent evt) { // when debugging ends, always disengage any active debug highlights if (!evt.debugging() && activeEditor_ != null) { activeEditor_.endDebugHighlighting(); } } @Override public void onDocWindowChanged(final DocWindowChangedEvent e) { if (e.getNewWindowId() == SourceWindowManager.getSourceWindowId()) { ensureVisible(true); // look for a collaborative editing session currently running inside // the document being transferred between windows--if we didn't know // about one with the event, try to look it up in the local cache of // source documents final CollabEditStartParams collabParams = e.getCollabParams() == null ? windowManager_.getDocCollabParams(e.getDocId()) : e.getCollabParams(); // if we're the adopting window, add the doc server_.getSourceDocument(e.getDocId(), new ServerRequestCallback<SourceDocument>() { @Override public void onResponseReceived(final SourceDocument doc) { final EditingTarget target = addTab(doc, e.getPos()); Scheduler.get().scheduleDeferred(new Scheduler.ScheduledCommand() { @Override public void execute() { // if there was a collab session, resume it if (collabParams != null) target.beginCollabSession(e.getCollabParams()); } }); } @Override public void onError(ServerError error) { globalDisplay_.showErrorMessage("Document Tab Move Failed", "Couldn't move the tab to this window: \n" + error.getMessage()); } }); } else if (e.getOldWindowId() == SourceWindowManager.getSourceWindowId()) { // cancel tab drag if it was occurring view_.cancelTabDrag(); // disown this doc if it was our own disownDoc(e.getDocId()); } } private void disownDoc(String docId) { suspendDocumentClose_ = true; for (int i = 0; i < editors_.size(); i++) { if (editors_.get(i).getId() == docId) { view_.closeTab(i, false); break; } } suspendDocumentClose_ = false; } @Override public void onDocTabDragInitiated(final DocTabDragInitiatedEvent event) { inEditorForId(event.getDragParams().getDocId(), new OperationWithInput<EditingTarget>() { @Override public void execute(EditingTarget editor) { DocTabDragParams params = event.getDragParams(); params.setSourcePosition(editor.currentPosition()); events_.fireEvent(new DocTabDragStartedEvent(params)); } }); } @Override public void onPopoutDocInitiated(final PopoutDocInitiatedEvent event) { inEditorForId(event.getDocId(), new OperationWithInput<EditingTarget>() { @Override public void execute(EditingTarget editor) { // if this is a text editor, ensure that its content is // synchronized with the server before we pop it out if (editor instanceof TextEditingTarget) { final TextEditingTarget textEditor = (TextEditingTarget)editor; textEditor.withSavedDoc(new Command() { @Override public void execute() { textEditor.syncLocalSourceDb(); events_.fireEvent(new PopoutDocEvent(event, textEditor.currentPosition())); } }); } else { events_.fireEvent(new PopoutDocEvent(event, editor.currentPosition())); } } }); } @Handler public void onCloseSourceDoc() { closeSourceDoc(true); } void closeSourceDoc(boolean interactive) { if (view_.getTabCount() == 0) return; view_.closeTab(view_.getActiveTabIndex(), interactive); } /** * Execute the given command for each editor, using continuation-passing * style. When executed, the CPSEditingTargetCommand needs to execute its * own Command parameter to continue the iteration. * @param command The command to run on each EditingTarget */ private void cpsExecuteForEachEditor(ArrayList<EditingTarget> editors, final CPSEditingTargetCommand command, final Command completedCommand) { SerializedCommandQueue queue = new SerializedCommandQueue(); // Clone editors_, since the original may be mutated during iteration for (final EditingTarget editor : new ArrayList<EditingTarget>(editors)) { queue.addCommand(new SerializedCommand() { @Override public void onExecute(Command continuation) { command.execute(editor, continuation); } }); } if (completedCommand != null) { queue.addCommand(new SerializedCommand() { public void onExecute(Command continuation) { completedCommand.execute(); continuation.execute(); } }); } } private void cpsExecuteForEachEditor(ArrayList<EditingTarget> editors, final CPSEditingTargetCommand command) { cpsExecuteForEachEditor(editors, command, null); } @Handler public void onSaveAllSourceDocs() { cpsExecuteForEachEditor(editors_, new CPSEditingTargetCommand() { @Override public void execute(EditingTarget target, Command continuation) { if (target.dirtyState().getValue()) { target.save(continuation); } else { continuation.execute(); } } }); } private void saveEditingTargetsWithPrompt( String title, ArrayList<EditingTarget> editingTargets, final Command onCompleted, final Command onCancelled) { // execute on completed right away if the list is empty if (editingTargets.size() == 0) { onCompleted.execute(); } // if there is just one thing dirty then go straight to the save dialog else if (editingTargets.size() == 1) { editingTargets.get(0).saveWithPrompt(onCompleted, onCancelled); } // otherwise use the multi save changes dialog else { // convert to UnsavedChangesTarget collection ArrayList<UnsavedChangesTarget> unsavedTargets = new ArrayList<UnsavedChangesTarget>(); unsavedTargets.addAll(editingTargets); // show dialog view_.showUnsavedChangesDialog( title, unsavedTargets, new OperationWithInput<UnsavedChangesDialog.Result>() { @Override public void execute(UnsavedChangesDialog.Result result) { saveChanges(result.getSaveTargets(), onCompleted); } }, onCancelled); } } private void saveChanges(ArrayList<UnsavedChangesTarget> targets, Command onCompleted) { // convert back to editing targets ArrayList<EditingTarget> saveTargets = new ArrayList<EditingTarget>(); for (UnsavedChangesTarget target: targets) { EditingTarget saveTarget = getEditingTargetForId(target.getId()); if (saveTarget != null) saveTargets.add(saveTarget); } // execute the save cpsExecuteForEachEditor( // targets the user chose to save saveTargets, // save each editor new CPSEditingTargetCommand() { @Override public void execute(EditingTarget saveTarget, Command continuation) { saveTarget.save(continuation); } }, // onCompleted at the end onCompleted ); } private EditingTarget getEditingTargetForId(String id) { for (EditingTarget target : editors_) if (id.equals(target.getId())) return target; return null; } @Handler public void onCloseAllSourceDocs() { closeAllSourceDocs("Close All", null, false); } @Handler public void onCloseOtherSourceDocs() { closeAllSourceDocs("Close Other", null, true); } public void closeAllSourceDocs(final String caption, final Command onCompleted, final boolean excludeActive) { if (SourceWindowManager.isMainSourceWindow() && !excludeActive) { // if this is the main window, close docs in the satellites first windowManager_.closeAllSatelliteDocs(caption, new Command() { @Override public void execute() { closeAllLocalSourceDocs(caption, onCompleted, excludeActive); } }); } else { // this is a satellite (or we don't need to query satellites)--just // close our own tabs closeAllLocalSourceDocs(caption, onCompleted, excludeActive); } } private void closeAllLocalSourceDocs(String caption, Command onCompleted, final boolean excludeActive) { // save active editor for exclusion (it changes as we close tabs) final EditingTarget activeEditor = activeEditor_; // collect up a list of dirty documents ArrayList<EditingTarget> dirtyTargets = new ArrayList<EditingTarget>(); for (EditingTarget target : editors_) { if (excludeActive && target == activeEditor) continue; if (target.dirtyState().getValue()) dirtyTargets.add(target); } // create a command used to close all tabs final Command closeAllTabsCommand = new Command() { @Override public void execute() { cpsExecuteForEachEditor(editors_, new CPSEditingTargetCommand() { @Override public void execute(EditingTarget target, Command continuation) { if (excludeActive && target == activeEditor) { continuation.execute(); return; } else { view_.closeTab(target.asWidget(), false, continuation); } } }); } }; // save targets saveEditingTargetsWithPrompt(caption, dirtyTargets, CommandUtil.join(closeAllTabsCommand, onCompleted), null); } private boolean isUnsavedTarget(EditingTarget target, int type) { boolean fileBacked = target.getPath() != null; return target.dirtyState().getValue() && ((type == TYPE_FILE_BACKED && fileBacked) || (type == TYPE_UNTITLED && !fileBacked)); } public ArrayList<UnsavedChangesTarget> getUnsavedChanges(int type) { ArrayList<UnsavedChangesTarget> targets = new ArrayList<UnsavedChangesTarget>(); // if this is the main window, collect all unsaved changes from // the satellite windows as well if (SourceWindowManager.isMainSourceWindow()) { targets.addAll(windowManager_.getAllSatelliteUnsavedChanges(type)); } for (EditingTarget target : editors_) if (isUnsavedTarget(target, type)) targets.add(target); return targets; } public void saveAllUnsaved(final Command onCompleted) { Command saveAllLocal = new Command() { @Override public void execute() { saveChanges(getUnsavedChanges(TYPE_FILE_BACKED), onCompleted); } }; // if this is the main source window, save all files in satellites first if (SourceWindowManager.isMainSourceWindow()) windowManager_.saveAllUnsaved(saveAllLocal); else saveAllLocal.execute(); } public void saveWithPrompt(UnsavedChangesTarget target, Command onCompleted, Command onCancelled) { if (SourceWindowManager.isMainSourceWindow() && !windowManager_.getWindowIdOfDocId(target.getId()).isEmpty()) { // we are the main window, and we're being asked to save a document // that's in a different window; perform the save over there windowManager_.saveWithPrompt(UnsavedChangesItem.create(target), onCompleted); return; } EditingTarget editingTarget = getEditingTargetForId(target.getId()); if (editingTarget != null) editingTarget.saveWithPrompt(onCompleted, onCancelled); } public void handleUnsavedChangesBeforeExit( final ArrayList<UnsavedChangesTarget> saveTargets, final Command onCompleted) { // first handle saves, then revert unsaved, then callback on completed final Command completed = new Command() { @Override public void execute() { // revert unsaved revertUnsavedTargets(onCompleted); } }; // if this is the main source window, let satellite windows save any // changes first if (SourceWindowManager.isMainSourceWindow()) { windowManager_.handleUnsavedChangesBeforeExit( saveTargets, new Command() { @Override public void execute() { saveChanges(saveTargets, completed); } }); } else { saveChanges(saveTargets, completed); } } public Display getView() { return view_; } private void revertActiveDocument() { if (activeEditor_ == null) return; if (activeEditor_.getPath() != null) activeEditor_.revertChanges(null); // Ensure that the document is in view activeEditor_.ensureCursorVisible(); } private void revertUnsavedTargets(Command onCompleted) { // collect up unsaved targets ArrayList<EditingTarget> unsavedTargets = new ArrayList<EditingTarget>(); for (EditingTarget target : editors_) if (isUnsavedTarget(target, TYPE_FILE_BACKED)) unsavedTargets.add(target); // revert all of them cpsExecuteForEachEditor( // targets the user chose not to save unsavedTargets, // save each editor new CPSEditingTargetCommand() { @Override public void execute(EditingTarget saveTarget, Command continuation) { if (saveTarget.getPath() != null) { // file backed document -- revert it saveTarget.revertChanges(continuation); } else { // untitled document -- just close the tab non-interactively view_.closeTab(saveTarget.asWidget(), false, continuation); } } }, // onCompleted at the end onCompleted ); } @Handler public void onOpenSourceDoc() { fileDialogs_.openFile( "Open File", fileContext_, workbenchContext_.getDefaultFileDialogDir(), new ProgressOperationWithInput<FileSystemItem>() { public void execute(final FileSystemItem input, ProgressIndicator indicator) { if (input == null) return; workbenchContext_.setDefaultFileDialogDir( input.getParentPath()); indicator.onCompleted(); Scheduler.get().scheduleDeferred(new ScheduledCommand() { public void execute() { fileTypeRegistry_.openFile(input); } }); } }); } public void onNewDocumentWithCode(final NewDocumentWithCodeEvent event) { // determine the type final EditableFileType docType; if (event.getType().equals(NewDocumentWithCodeEvent.R_SCRIPT)) docType = FileTypeRegistry.R; else docType = FileTypeRegistry.RMARKDOWN; // command to create and run the new doc Command newDocCommand = new Command() { @Override public void execute() { newDoc(docType, new ResultCallback<EditingTarget, ServerError>() { public void onSuccess(EditingTarget arg) { TextEditingTarget editingTarget = (TextEditingTarget)arg; editingTarget.insertCode(event.getCode(), false); if (event.getCursorPosition() != null) { editingTarget.navigateToPosition(event.getCursorPosition(), false); } if (event.getExecute()) { if (docType.equals(FileTypeRegistry.R)) { commands_.executeToCurrentLine().execute(); commands_.activateSource().execute(); } else { commands_.executePreviousChunks().execute(); } } } }); } }; // do it if (docType.equals(FileTypeRegistry.R)) { newDocCommand.execute(); } else { dependencyManager_.withRMarkdown("R Notebook", "Create R Notebook", newDocCommand); } } public void onOpenSourceFile(final OpenSourceFileEvent event) { doOpenSourceFile(event.getFile(), event.getFileType(), event.getPosition(), null, event.getNavigationMethod(), false); } public void onOpenPresentationSourceFile(OpenPresentationSourceFileEvent event) { // don't do the navigation if the active document is a source // file from this presentation module doOpenSourceFile(event.getFile(), event.getFileType(), event.getPosition(), event.getPattern(), NavigationMethods.HIGHLIGHT_LINE, true); } public void onEditPresentationSource(final EditPresentationSourceEvent event) { openFile( event.getSourceFile(), FileTypeRegistry.RPRESENTATION, new CommandWithArg<EditingTarget>() { @Override public void execute(final EditingTarget editor) { TextEditingTargetPresentationHelper.navigateToSlide( editor, event.getSlideIndex()); } }); } private void doOpenSourceFile(final FileSystemItem file, final TextFileType fileType, final FilePosition position, final String pattern, final int navMethod, final boolean forceHighlightMode) { // if the navigation should happen in another window, do that instead NavigationResult navResult = windowManager_.navigateToFile(file, position, navMethod); // we navigated externally, just skip this if (navResult.getType() == NavigationResult.RESULT_NAVIGATED) return; // we're about to open in this window--if it's the main window, focus it if (SourceWindowManager.isMainSourceWindow() && Desktop.isDesktop()) Desktop.getFrame().bringMainFrameToFront(); final boolean isDebugNavigation = navMethod == NavigationMethods.DEBUG_STEP || navMethod == NavigationMethods.DEBUG_END; final CommandWithArg<EditingTarget> editingTargetAction = new CommandWithArg<EditingTarget>() { @Override public void execute(EditingTarget target) { if (position != null) { SourcePosition endPosition = null; if (isDebugNavigation) { DebugFilePosition filePos = (DebugFilePosition) position.cast(); endPosition = SourcePosition.create( filePos.getEndLine() - 1, filePos.getEndColumn() + 1); if (Desktop.isDesktop() && navMethod != NavigationMethods.DEBUG_END) Desktop.getFrame().bringMainFrameToFront(); } navigate(target, SourcePosition.create(position.getLine() - 1, position.getColumn() - 1), endPosition); } else if (pattern != null) { Position pos = target.search(pattern); if (pos != null) { navigate(target, SourcePosition.create(pos.getRow(), 0), null); } } } private void navigate(final EditingTarget target, final SourcePosition srcPosition, final SourcePosition srcEndPosition) { Scheduler.get().scheduleDeferred(new ScheduledCommand() { @Override public void execute() { if (navMethod == NavigationMethods.DEBUG_STEP) { target.highlightDebugLocation( srcPosition, srcEndPosition, true); } else if (navMethod == NavigationMethods.DEBUG_END) { target.endDebugHighlighting(); } else { // force highlight mode if requested if (forceHighlightMode) target.forceLineHighlighting(); // now navigate to the new position boolean highlight = navMethod == NavigationMethods.HIGHLIGHT_LINE && !uiPrefs_.highlightSelectedLine().getValue(); target.navigateToPosition(srcPosition, false, highlight); } } }); } }; if (navResult.getType() == NavigationResult.RESULT_RELOCATE) { server_.getSourceDocument(navResult.getDocId(), new ServerRequestCallback<SourceDocument>() { @Override public void onResponseReceived(final SourceDocument doc) { editingTargetAction.execute(addTab(doc, OPEN_REPLAY)); } @Override public void onError(ServerError error) { globalDisplay_.showErrorMessage("Document Tab Move Failed", "Couldn't move the tab to this window: \n" + error.getMessage()); } }); return; } final CommandWithArg<FileSystemItem> action = new CommandWithArg<FileSystemItem>() { @Override public void execute(FileSystemItem file) { openFile(file, fileType, editingTargetAction); } }; // If this is a debug navigation, we only want to treat this as a full // file open if the file isn't already open; otherwise, we can just // highlight in place. if (isDebugNavigation) { setPendingDebugSelection(); for (int i = 0; i < editors_.size(); i++) { EditingTarget target = editors_.get(i); String path = target.getPath(); if (path != null && path.equalsIgnoreCase(file.getPath())) { // the file's open; just update its highlighting if (navMethod == NavigationMethods.DEBUG_END) { target.endDebugHighlighting(); } else { view_.selectTab(i); editingTargetAction.execute(target); } return; } } // If we're here, the target file wasn't open in an editor. Don't // open a file just to turn off debug highlighting in the file! if (navMethod == NavigationMethods.DEBUG_END) return; } // Warning: event.getFile() can be null (e.g. new Sweave document) if (file != null && file.getLength() < 0) { statQueue_.add(new StatFileEntry(file, action)); if (statQueue_.size() == 1) processStatQueue(); } else { action.execute(file); } } private void processStatQueue() { if (statQueue_.isEmpty()) return; final StatFileEntry entry = statQueue_.peek(); final Command processNextEntry = new Command() { @Override public void execute() { statQueue_.remove(); if (!statQueue_.isEmpty()) processStatQueue(); } }; server_.stat(entry.file.getPath(), new ServerRequestCallback<FileSystemItem>() { @Override public void onResponseReceived(FileSystemItem response) { processNextEntry.execute(); entry.action.execute(response); } @Override public void onError(ServerError error) { processNextEntry.execute(); // Couldn't stat the file? Proceed anyway. If the file doesn't // exist, we'll let the downstream code be the one to show the // error. entry.action.execute(entry.file); } }); } private void openFile(FileSystemItem file) { openFile(file, fileTypeRegistry_.getTextTypeForFile(file)); } private void openFile(FileSystemItem file, TextFileType fileType) { openFile(file, fileType, new CommandWithArg<EditingTarget>() { @Override public void execute(EditingTarget arg) { } }); } private void openFile(final FileSystemItem file, final TextFileType fileType, final CommandWithArg<EditingTarget> executeOnSuccess) { // add this work to the queue openFileQueue_.add(new OpenFileEntry(file, fileType, executeOnSuccess)); // begin queue processing if it's the only work in the queue if (openFileQueue_.size() == 1) processOpenFileQueue(); } private void processOpenFileQueue() { // no work to do if (openFileQueue_.isEmpty()) return; // find the first work unit final OpenFileEntry entry = openFileQueue_.peek(); // define command to advance queue final Command processNextEntry = new Command() { @Override public void execute() { openFileQueue_.remove(); if (!openFileQueue_.isEmpty()) processOpenFileQueue(); } }; openFile(entry.file, entry.fileType, new ResultCallback<EditingTarget, ServerError>() { @Override public void onSuccess(EditingTarget target) { processNextEntry.execute(); if (entry.executeOnSuccess != null) entry.executeOnSuccess.execute(target); } @Override public void onFailure(ServerError error) { String message = error.getUserMessage(); // see if a special message was provided JSONValue errValue = error.getClientInfo(); if (errValue != null) { JSONString errMsg = errValue.isString(); if (errMsg != null) message = errMsg.stringValue(); } globalDisplay_.showMessage(GlobalDisplay.MSG_ERROR, "Error while opening file", message); processNextEntry.execute(); } }); } private void openNotebook( final FileSystemItem rmdFile, final SourceDocumentResult doc, final ResultCallback<EditingTarget, ServerError> resultCallback) { if (!StringUtil.isNullOrEmpty(doc.getDocPath())) { // this happens if we created the R Markdown file, or if the R Markdown // file on disk matched the one inside the notebook openFileFromServer(rmdFile, FileTypeRegistry.RMARKDOWN, resultCallback); } else if (!StringUtil.isNullOrEmpty(doc.getDocId())) { // this happens when we have to open an untitled buffer for the the // notebook (usually because the of a conflict between the Rmd on disk // and the one in the .nb.html file) server_.getSourceDocument(doc.getDocId(), new ServerRequestCallback<SourceDocument>() { @Override public void onResponseReceived(SourceDocument doc) { // create the editor EditingTarget target = addTab(doc, OPEN_INTERACTIVE); // show a warning bar if (target instanceof TextEditingTarget) { ((TextEditingTarget) target).showWarningMessage( "This notebook has the same name as an R Markdown " + "file, but doesn't match it."); } resultCallback.onSuccess(target); } @Override public void onError(ServerError error) { globalDisplay_.showErrorMessage( "Notebook Open Failed", "This notebook could not be opened. " + "If the error persists, try removing the " + "accompanying R Markdown file. \n\n" + error.getMessage()); resultCallback.onFailure(error); } }); } } private void openNotebook(final FileSystemItem rnbFile, final TextFileType fileType, final ResultCallback<EditingTarget, ServerError> resultCallback) { // construct path to .Rmd final String rnbPath = rnbFile.getPath(); final String rmdPath = FilePathUtils.filePathSansExtension(rnbPath) + ".Rmd"; final FileSystemItem rmdFile = FileSystemItem.createFile(rmdPath); // if we already have associated .Rmd file open, then just edit it // TODO: should we perform conflict resolution here as well? if (openFileAlreadyOpen(rmdFile, resultCallback)) return; // ask the server to extract the .Rmd, then open that Command extractRmdCommand = new Command() { @Override public void execute() { server_.extractRmdFromNotebook( rnbPath, new ServerRequestCallback<SourceDocumentResult>() { @Override public void onResponseReceived(SourceDocumentResult doc) { openNotebook(rmdFile, doc, resultCallback); } @Override public void onError(ServerError error) { globalDisplay_.showErrorMessage("Notebook Open Failed", "This notebook could not be opened. \n\n" + error.getMessage()); resultCallback.onFailure(error); } }); } }; dependencyManager_.withRMarkdown("R Notebook", "Using R Notebooks", extractRmdCommand); } private boolean openFileAlreadyOpen(final FileSystemItem file, final ResultCallback<EditingTarget, ServerError> resultCallback) { // check to see if any local editors have the file open for (int i = 0; i < editors_.size(); i++) { EditingTarget target = editors_.get(i); String thisPath = target.getPath(); if (thisPath != null && thisPath.equalsIgnoreCase(file.getPath())) { view_.selectTab(i); pMruList_.get().add(thisPath); if (resultCallback != null) resultCallback.onSuccess(target); return true; } } return false; } // top-level wrapper for opening files. takes care of: // - making sure the view is visible // - checking whether it is already open and re-selecting its tab // - prohibit opening very large files (>500KB) // - confirmation of opening large files (>100KB) // - finally, actually opening the file from the server // via the call to the lower level openFile method private void openFile(final FileSystemItem file, final TextFileType fileType, final ResultCallback<EditingTarget, ServerError> resultCallback) { ensureVisible(true); if (fileType.isRNotebook()) { openNotebook(file, fileType, resultCallback); return; } if (file == null) { newDoc(fileType, resultCallback); return; } if (openFileAlreadyOpen(file, resultCallback)) return; EditingTarget target = editingTargetSource_.getEditingTarget(fileType); if (file.getLength() > target.getFileSizeLimit()) { if (resultCallback != null) resultCallback.onCancelled(); showFileTooLargeWarning(file, target.getFileSizeLimit()); } else if (file.getLength() > target.getLargeFileSize()) { confirmOpenLargeFile(file, new Operation() { public void execute() { openFileFromServer(file, fileType, resultCallback); } }, new Operation() { public void execute() { // user (wisely) cancelled if (resultCallback != null) resultCallback.onCancelled(); } }); } else { openFileFromServer(file, fileType, resultCallback); } } private void showFileTooLargeWarning(FileSystemItem file, long sizeLimit) { StringBuilder msg = new StringBuilder(); msg.append("The file '" + file.getName() + "' is too "); msg.append("large to open in the source editor (the file is "); msg.append(StringUtil.formatFileSize(file.getLength()) + " and the "); msg.append("maximum file size is "); msg.append(StringUtil.formatFileSize(sizeLimit) + ")"); globalDisplay_.showMessage(GlobalDisplay.MSG_WARNING, "Selected File Too Large", msg.toString()); } private void confirmOpenLargeFile(FileSystemItem file, Operation openOperation, Operation cancelOperation) { StringBuilder msg = new StringBuilder(); msg.append("The source file '" + file.getName() + "' is large ("); msg.append(StringUtil.formatFileSize(file.getLength()) + ") "); msg.append("and may take some time to open. "); msg.append("Are you sure you want to continue opening it?"); globalDisplay_.showYesNoMessage(GlobalDisplay.MSG_WARNING, "Confirm Open", msg.toString(), openOperation, false); // 'No' is default } private void openFileFromServer( final FileSystemItem file, final TextFileType fileType, final ResultCallback<EditingTarget, ServerError> resultCallback) { final Command dismissProgress = globalDisplay_.showProgress( "Opening file..."); server_.openDocument( file.getPath(), fileType.getTypeId(), uiPrefs_.defaultEncoding().getValue(), new ServerRequestCallback<SourceDocument>() { @Override public void onError(ServerError error) { dismissProgress.execute(); pMruList_.get().remove(file.getPath()); Debug.logError(error); if (resultCallback != null) resultCallback.onFailure(error); } @Override public void onResponseReceived(SourceDocument document) { dismissProgress.execute(); pMruList_.get().add(document.getPath()); EditingTarget target = addTab(document, OPEN_INTERACTIVE); if (resultCallback != null) resultCallback.onSuccess(target); } }); } Widget createWidget(EditingTarget target) { return target.asWidget(); } private EditingTarget addTab(SourceDocument doc, int mode) { return addTab(doc, false, mode); } private EditingTarget addTab(SourceDocument doc, boolean atEnd, int mode) { // by default, add at the tab immediately after the current tab return addTab(doc, atEnd ? null : getPhysicalTabIndex() + 1, mode); } private EditingTarget addTab(SourceDocument doc, Integer position, int mode) { final String defaultNamePrefix = editingTargetSource_.getDefaultNamePrefix(doc); final EditingTarget target = editingTargetSource_.getEditingTarget( doc, fileContext_, new Provider<String>() { public String get() { return getNextDefaultName(defaultNamePrefix); } }); final Widget widget = createWidget(target); if (position == null) { editors_.add(target); } else { // we're inserting into an existing permuted tabset -- push aside // any tabs physically to the right of this tab editors_.add(position, target); for (int i = 0; i < tabOrder_.size(); i++) { int pos = tabOrder_.get(i); if (pos >= position) tabOrder_.set(i, pos + 1); } // add this tab in its "natural" position tabOrder_.add(position, position); } view_.addTab(widget, target.getIcon(), target.getId(), target.getName().getValue(), target.getTabTooltip(), // used as tooltip, if non-null position, true); fireDocTabsChanged(); target.getName().addValueChangeHandler(new ValueChangeHandler<String>() { public void onValueChange(ValueChangeEvent<String> event) { view_.renameTab(widget, target.getIcon(), event.getValue(), target.getPath()); fireDocTabsChanged(); } }); view_.setDirty(widget, target.dirtyState().getValue()); target.dirtyState().addValueChangeHandler(new ValueChangeHandler<Boolean>() { public void onValueChange(ValueChangeEvent<Boolean> event) { view_.setDirty(widget, event.getValue()); manageCommands(); } }); target.addEnsureVisibleHandler(new EnsureVisibleHandler() { public void onEnsureVisible(EnsureVisibleEvent event) { view_.selectTab(widget); } }); target.addCloseHandler(new CloseHandler<Void>() { public void onClose(CloseEvent<Void> voidCloseEvent) { view_.closeTab(widget, false); } }); events_.fireEvent(new SourceDocAddedEvent(doc, mode)); // adding a tab may enable commands that are only available when // multiple documents are open; if this is the second document, go check if (editors_.size() == 2) manageMultiTabCommands(); // if the target had an editing session active, attempt to resume it if (doc.getCollabParams() != null) target.beginCollabSession(doc.getCollabParams()); return target; } private String getNextDefaultName(String defaultNamePrefix) { if (StringUtil.isNullOrEmpty(defaultNamePrefix)) { defaultNamePrefix = "Untitled"; } int max = 0; for (EditingTarget target : editors_) { String name = target.getName().getValue(); max = Math.max(max, getUntitledNum(name, defaultNamePrefix)); } return defaultNamePrefix + (max + 1); } private native final int getUntitledNum(String name, String prefix) /*-{ var match = (new RegExp("^" + prefix + "([0-9]{1,5})$")).exec(name); if (!match) return 0; return parseInt(match[1]); }-*/; public void onInsertSource(final InsertSourceEvent event) { if (activeEditor_ != null && activeEditor_ instanceof TextEditingTarget && commands_.executeCode().isEnabled()) { TextEditingTarget textEditor = (TextEditingTarget) activeEditor_; textEditor.insertCode(event.getCode(), event.isBlock()); } else { newDoc(FileTypeRegistry.R, new ResultCallback<EditingTarget, ServerError>() { public void onSuccess(EditingTarget arg) { ((TextEditingTarget)arg).insertCode(event.getCode(), event.isBlock()); } }); } } public void onTabClosing(final TabClosingEvent event) { EditingTarget target = editors_.get(event.getTabIndex()); if (!target.onBeforeDismiss()) event.cancel(); } @Override public void onTabClose(TabCloseEvent event) { // can't proceed if there is no active editor if (activeEditor_ == null) return; if (event.getTabIndex() >= editors_.size()) return; // Seems like this should never happen...? final String activeEditorId = activeEditor_.getId(); if (editors_.get(event.getTabIndex()).getId().equals(activeEditorId)) { // scan the source navigation history for an entry that can // be used as the next active tab (anything that doesn't have // the same document id as the currently active tab) SourceNavigation srcNav = sourceNavigationHistory_.scanBack( new SourceNavigationHistory.Filter() { public boolean includeEntry(SourceNavigation navigation) { return !navigation.getDocumentId().equals(activeEditorId); } }); // see if the source navigation we found corresponds to an active // tab -- if it does then set this on the event if (srcNav != null) { for (int i=0; i<editors_.size(); i++) { if (srcNav.getDocumentId().equals(editors_.get(i).getId())) { view_.selectTab(i); break; } } } } } private void closeTabIndex(int idx, boolean closeDocument) { EditingTarget target = editors_.remove(idx); tabOrder_.remove(new Integer(idx)); for (int i = 0; i < tabOrder_.size(); i++) { if (tabOrder_.get(i) > idx) { tabOrder_.set(i, tabOrder_.get(i) - 1); } } target.onDismiss(closeDocument ? EditingTarget.DISMISS_TYPE_CLOSE : EditingTarget.DISMISS_TYPE_MOVE); if (activeEditor_ == target) { activeEditor_.onDeactivate(); activeEditor_ = null; } if (closeDocument) { events_.fireEvent(new DocTabClosedEvent(target.getId())); server_.closeDocument(target.getId(), new VoidServerRequestCallback()); } manageCommands(); fireDocTabsChanged(); if (view_.getTabCount() == 0) { sourceNavigationHistory_.clear(); events_.fireEvent(new LastSourceDocClosedEvent()); } } public void onTabClosed(TabClosedEvent event) { closeTabIndex(event.getTabIndex(), !suspendDocumentClose_); } @Override public void onTabReorder(TabReorderEvent event) { syncTabOrder(); // sanity check: make sure we're moving from a valid location and to a // valid location if (event.getOldPos() < 0 || event.getOldPos() >= tabOrder_.size() || event.getNewPos() < 0 || event.getNewPos() >= tabOrder_.size()) { return; } // remove the tab from its old position int idx = tabOrder_.get(event.getOldPos()); tabOrder_.remove(new Integer(idx)); // force type box // add it to its new position tabOrder_.add(event.getNewPos(), idx); // sort the document IDs and send to the server ArrayList<String> ids = new ArrayList<String>(); for (int i = 0; i < tabOrder_.size(); i++) { ids.add(editors_.get(tabOrder_.get(i)).getId()); } server_.setDocOrder(ids, new VoidServerRequestCallback()); // activate the tab setPhysicalTabIndex(event.getNewPos()); fireDocTabsChanged(); } private void syncTabOrder() { // ensure the tab order is synced to the list of editors for (int i = tabOrder_.size(); i < editors_.size(); i++) { tabOrder_.add(i); } for (int i = editors_.size(); i < tabOrder_.size(); i++) { tabOrder_.remove(i); } } private void fireDocTabsChanged() { if (!initialized_) return; // ensure we have a tab order (we want the popup list to match the order // of the tabs) syncTabOrder(); String[] ids = new String[editors_.size()]; ImageResource[] icons = new ImageResource[editors_.size()]; String[] names = new String[editors_.size()]; String[] paths = new String[editors_.size()]; for (int i = 0; i < ids.length; i++) { EditingTarget target = editors_.get(tabOrder_.get(i)); ids[i] = target.getId(); icons[i] = target.getIcon(); names[i] = target.getName().getValue(); paths[i] = target.getPath(); } events_.fireEvent(new DocTabsChangedEvent(ids, icons, names, paths)); view_.manageChevronVisibility(); } public void onSelection(SelectionEvent<Integer> event) { if (activeEditor_ != null) activeEditor_.onDeactivate(); activeEditor_ = null; if (event.getSelectedItem() >= 0) { activeEditor_ = editors_.get(event.getSelectedItem()); activeEditor_.onActivate(); // let any listeners know this tab was activated events_.fireEvent(new DocTabActivatedEvent( activeEditor_.getPath(), activeEditor_.getId())); // don't send focus to the tab if we're expecting a debug selection // event if (initialized_ && !isDebugSelectionPending()) { Scheduler.get().scheduleDeferred(new ScheduledCommand() { public void execute() { if (activeEditor_ != null) activeEditor_.focus(); } }); } else if (isDebugSelectionPending()) { // we're debugging, so send focus to the console instead of the // editor commands_.activateConsole().execute(); clearPendingDebugSelection(); } } if (initialized_) manageCommands(); } private void manageCommands() { boolean hasDocs = editors_.size() > 0; commands_.closeSourceDoc().setEnabled(hasDocs); commands_.closeAllSourceDocs().setEnabled(hasDocs); commands_.nextTab().setEnabled(hasDocs); commands_.previousTab().setEnabled(hasDocs); commands_.firstTab().setEnabled(hasDocs); commands_.lastTab().setEnabled(hasDocs); commands_.switchToTab().setEnabled(hasDocs); commands_.setWorkingDirToActiveDoc().setEnabled(hasDocs); HashSet<AppCommand> newCommands = activeEditor_ != null ? activeEditor_.getSupportedCommands() : new HashSet<AppCommand>(); HashSet<AppCommand> commandsToEnable = new HashSet<AppCommand>(newCommands); commandsToEnable.removeAll(activeCommands_); HashSet<AppCommand> commandsToDisable = new HashSet<AppCommand>(activeCommands_); commandsToDisable.removeAll(newCommands); for (AppCommand command : commandsToEnable) { command.setEnabled(true); command.setVisible(true); } for (AppCommand command : commandsToDisable) { command.setEnabled(false); command.setVisible(false); } // commands which should always be visible even when disabled commands_.saveSourceDoc().setVisible(true); commands_.saveSourceDocAs().setVisible(true); commands_.printSourceDoc().setVisible(true); commands_.setWorkingDirToActiveDoc().setVisible(true); commands_.debugBreakpoint().setVisible(true); // manage synctex commands manageSynctexCommands(); // manage vcs commands manageVcsCommands(); // manage save and save all manageSaveCommands(); // manage source navigation manageSourceNavigationCommands(); // manage RSConnect commands manageRSConnectCommands(); // manage R Markdown commands manageRMarkdownCommands(); // manage multi-tab commands manageMultiTabCommands(); activeCommands_ = newCommands; // give the active editor a chance to manage commands if (activeEditor_ != null) activeEditor_.manageCommands(); assert verifyNoUnsupportedCommands(newCommands) : "Unsupported commands detected (please add to Source.dynamicCommands_)"; } private void manageMultiTabCommands() { boolean hasMultipleDocs = editors_.size() > 1; // special case--these editing targets always support popout, but it's // nonsensical to show it if it's the only tab in a satellite; hide it in // this case if (commands_.popoutDoc().isEnabled() && activeEditor_ != null && (activeEditor_ instanceof TextEditingTarget || activeEditor_ instanceof CodeBrowserEditingTarget) && !SourceWindowManager.isMainSourceWindow()) { commands_.popoutDoc().setVisible(hasMultipleDocs); } commands_.closeOtherSourceDocs().setEnabled(hasMultipleDocs); } private void manageSynctexCommands() { // synctex commands are enabled if we have synctex for the active editor boolean synctexAvailable = synctex_.isSynctexAvailable(); if (synctexAvailable) { if ((activeEditor_ != null) && (activeEditor_.getPath() != null) && activeEditor_.canCompilePdf()) { synctexAvailable = synctex_.isSynctexAvailable(); } else { synctexAvailable = false; } } synctex_.enableCommands(synctexAvailable); } private void manageVcsCommands() { // manage availablity of vcs commands boolean vcsCommandsEnabled = session_.getSessionInfo().isVcsEnabled() && (activeEditor_ != null) && (activeEditor_.getPath() != null) && activeEditor_.getPath().startsWith( session_.getSessionInfo().getActiveProjectDir().getPath()); commands_.vcsFileLog().setVisible(vcsCommandsEnabled); commands_.vcsFileLog().setEnabled(vcsCommandsEnabled); commands_.vcsFileDiff().setVisible(vcsCommandsEnabled); commands_.vcsFileDiff().setEnabled(vcsCommandsEnabled); commands_.vcsFileRevert().setVisible(vcsCommandsEnabled); commands_.vcsFileRevert().setEnabled(vcsCommandsEnabled); if (vcsCommandsEnabled) { String name = FileSystemItem.getNameFromPath(activeEditor_.getPath()); commands_.vcsFileDiff().setMenuLabel("_Diff \"" + name + "\""); commands_.vcsFileLog().setMenuLabel("_Log of \"" + name +"\""); commands_.vcsFileRevert().setMenuLabel("_Revert \"" + name + "\"..."); } boolean isGithubRepo = session_.getSessionInfo().isGithubRepository(); if (vcsCommandsEnabled && isGithubRepo) { String name = FileSystemItem.getNameFromPath(activeEditor_.getPath()); commands_.vcsViewOnGitHub().setVisible(true); commands_.vcsViewOnGitHub().setEnabled(true); commands_.vcsViewOnGitHub().setMenuLabel( "_View \"" + name + "\" on GitHub"); commands_.vcsBlameOnGitHub().setVisible(true); commands_.vcsBlameOnGitHub().setEnabled(true); commands_.vcsBlameOnGitHub().setMenuLabel( "_Blame \"" + name + "\" on GitHub"); } else { commands_.vcsViewOnGitHub().setVisible(false); commands_.vcsViewOnGitHub().setEnabled(false); commands_.vcsBlameOnGitHub().setVisible(false); commands_.vcsBlameOnGitHub().setEnabled(false); } } private void manageRSConnectCommands() { boolean rsCommandsAvailable = SessionUtils.showPublishUi(session_, uiPrefs_) && (activeEditor_ != null) && (activeEditor_.getPath() != null) && ((activeEditor_.getExtendedFileType() != null && activeEditor_.getExtendedFileType() .startsWith(SourceDocument.XT_SHINY_PREFIX)) || (activeEditor_.getExtendedFileType() == SourceDocument.XT_RMARKDOWN)); commands_.rsconnectDeploy().setVisible(rsCommandsAvailable); if (activeEditor_ != null) commands_.rsconnectDeploy().setLabel( activeEditor_.getExtendedFileType() != null && activeEditor_.getExtendedFileType() .startsWith(SourceDocument.XT_SHINY_PREFIX) ? "Publish Application..." : "Publish Document..."); commands_.rsconnectConfigure().setVisible(rsCommandsAvailable); } private void manageRMarkdownCommands() { boolean rmdCommandsAvailable = session_.getSessionInfo().getRMarkdownPackageAvailable() && (activeEditor_ != null) && activeEditor_.getExtendedFileType() == SourceDocument.XT_RMARKDOWN; commands_.editRmdFormatOptions().setVisible(rmdCommandsAvailable); commands_.editRmdFormatOptions().setEnabled(rmdCommandsAvailable); } private void manageSaveCommands() { boolean saveEnabled = (activeEditor_ != null) && activeEditor_.isSaveCommandActive(); commands_.saveSourceDoc().setEnabled(saveEnabled); manageSaveAllCommand(); } private void manageSaveAllCommand() { // if one document is dirty then we are enabled for (EditingTarget target : editors_) { if (target.isSaveCommandActive()) { commands_.saveAllSourceDocs().setEnabled(true); return; } } // not one was dirty, disabled commands_.saveAllSourceDocs().setEnabled(false); } private boolean verifyNoUnsupportedCommands(HashSet<AppCommand> commands) { HashSet<AppCommand> temp = new HashSet<AppCommand>(commands); temp.removeAll(dynamicCommands_); return temp.size() == 0; } private void pasteFileContentsAtCursor(final String path, final String encoding) { if (activeEditor_ != null && activeEditor_ instanceof TextEditingTarget) { final TextEditingTarget target = (TextEditingTarget) activeEditor_; server_.getFileContents(path, encoding, new ServerRequestCallback<String>() { @Override public void onResponseReceived(String content) { target.insertCode(content, false); } @Override public void onError(ServerError error) { Debug.logError(error); } }); } } private void pasteRCodeExecutionResult(final String code) { server_.executeRCode(code, new ServerRequestCallback<String>() { @Override public void onResponseReceived(String output) { if (activeEditor_ != null && activeEditor_ instanceof TextEditingTarget) { TextEditingTarget editor = (TextEditingTarget) activeEditor_; editor.insertCode(output, false); } } @Override public void onError(ServerError error) { Debug.logError(error); } }); } private void reflowText() { if (activeEditor_ != null && activeEditor_ instanceof TextEditingTarget) { TextEditingTarget editor = (TextEditingTarget) activeEditor_; editor.reflowText(); } } private void reindent() { if (activeEditor_ != null && activeEditor_ instanceof TextEditingTarget) { TextEditingTarget editor = (TextEditingTarget) activeEditor_; editor.getDocDisplay().reindent(); } } private void editFile(final String path) { server_.ensureFileExists( path, new ServerRequestCallback<Boolean>() { @Override public void onResponseReceived(Boolean success) { if (success) { FileSystemItem file = FileSystemItem.createFile(path); openFile(file); } } @Override public void onError(ServerError error) { Debug.logError(error); } }); } private void showHelpAtCursor() { if (activeEditor_ != null && activeEditor_ instanceof TextEditingTarget) { TextEditingTarget editor = (TextEditingTarget) activeEditor_; editor.showHelpAtCursor(); } } public void onFileEdit(FileEditEvent event) { if (SourceWindowManager.isMainSourceWindow()) { fileTypeRegistry_.editFile(event.getFile()); } } public void onBeforeShow(BeforeShowEvent event) { if (view_.getTabCount() == 0 && newTabPending_ == 0) { // Avoid scenarios where the Source tab comes up but no tabs are // in it. (But also avoid creating an extra source tab when there // were already new tabs about to be created!) onNewSourceDoc(); } } @Handler public void onSourceNavigateBack() { if (!sourceNavigationHistory_.isForwardEnabled()) { if (activeEditor_ != null) activeEditor_.recordCurrentNavigationPosition(); } SourceNavigation navigation = sourceNavigationHistory_.goBack(); if (navigation != null) attemptSourceNavigation(navigation, commands_.sourceNavigateBack()); } @Handler public void onSourceNavigateForward() { SourceNavigation navigation = sourceNavigationHistory_.goForward(); if (navigation != null) attemptSourceNavigation(navigation, commands_.sourceNavigateForward()); } private void attemptSourceNavigation(final SourceNavigation navigation, final AppCommand retryCommand) { // see if we can navigate by id String docId = navigation.getDocumentId(); final EditingTarget target = getEditingTargetForId(docId); if (target != null) { // check for navigation to the current position -- in this // case execute the retry command if ( (target == activeEditor_) && target.isAtSourceRow(navigation.getPosition())) { if (retryCommand.isEnabled()) retryCommand.execute(); } else { suspendSourceNavigationAdding_ = true; try { view_.selectTab(target.asWidget()); target.restorePosition(navigation.getPosition()); } finally { suspendSourceNavigationAdding_ = false; } } } // check for code browser navigation else if ((navigation.getPath() != null) && navigation.getPath().startsWith(CodeBrowserEditingTarget.PATH)) { activateCodeBrowser( navigation.getPath(), false, new SourceNavigationResultCallback<CodeBrowserEditingTarget>( navigation.getPosition(), retryCommand)); } // check for file path navigation else if ((navigation.getPath() != null) && !navigation.getPath().startsWith(DataItem.URI_PREFIX) && !navigation.getPath().startsWith(ObjectExplorerHandle.URI_PREFIX)) { FileSystemItem file = FileSystemItem.createFile(navigation.getPath()); TextFileType fileType = fileTypeRegistry_.getTextTypeForFile(file); // open the file and restore the position openFile(file, fileType, new SourceNavigationResultCallback<EditingTarget>( navigation.getPosition(), retryCommand)); } else { // couldn't navigate to this item, retry if (retryCommand.isEnabled()) retryCommand.execute(); } } private void manageSourceNavigationCommands() { commands_.sourceNavigateBack().setEnabled( sourceNavigationHistory_.isBackEnabled()); commands_.sourceNavigateForward().setEnabled( sourceNavigationHistory_.isForwardEnabled()); } @Override public void onCodeBrowserNavigation(final CodeBrowserNavigationEvent event) { // if this isn't the main source window, don't handle server-dispatched // code browser events if (event.serverDispatched() && !SourceWindowManager.isMainSourceWindow()) { return; } tryExternalCodeBrowser(event.getFunction(), event, new Command() { @Override public void execute() { if (event.getDebugPosition() != null) { setPendingDebugSelection(); } activateCodeBrowser( CodeBrowserEditingTarget.getCodeBrowserPath(event.getFunction()), !event.serverDispatched(), new ResultCallback<CodeBrowserEditingTarget,ServerError>() { @Override public void onSuccess(CodeBrowserEditingTarget target) { target.showFunction(event.getFunction()); if (event.getDebugPosition() != null) { highlightDebugBrowserPosition(target, event.getDebugPosition(), event.getExecuting()); } } }); } }); } @Override public void onCodeBrowserFinished(final CodeBrowserFinishedEvent event) { tryExternalCodeBrowser(event.getFunction(), event, new Command() { @Override public void execute() { final String path = CodeBrowserEditingTarget.getCodeBrowserPath( event.getFunction()); for (int i = 0; i < editors_.size(); i++) { if (editors_.get(i).getPath() == path) { view_.closeTab(i, false); return; } } } }); } @Override public void onCodeBrowserHighlight(final CodeBrowserHighlightEvent event) { tryExternalCodeBrowser(event.getFunction(), event, new Command() { @Override public void execute() { setPendingDebugSelection(); activateCodeBrowser( CodeBrowserEditingTarget.getCodeBrowserPath(event.getFunction()), false, new ResultCallback<CodeBrowserEditingTarget,ServerError>() { @Override public void onSuccess(CodeBrowserEditingTarget target) { // if we just stole this code browser from another window, // we may need to repopulate it if (StringUtil.isNullOrEmpty(target.getContext())) target.showFunction(event.getFunction()); highlightDebugBrowserPosition(target, event.getDebugPosition(), true); } }); } }); } private void tryExternalCodeBrowser(SearchPathFunctionDefinition func, CrossWindowEvent<?> event, Command withLocalCodeBrowser) { final String path = CodeBrowserEditingTarget.getCodeBrowserPath(func); NavigationResult result = windowManager_.navigateToCodeBrowser( path, event); if (result.getType() != NavigationResult.RESULT_NAVIGATED) { withLocalCodeBrowser.execute(); } } private void highlightDebugBrowserPosition(CodeBrowserEditingTarget target, DebugFilePosition pos, boolean executing) { target.highlightDebugLocation(SourcePosition.create( pos.getLine(), pos.getColumn() - 1), SourcePosition.create( pos.getEndLine(), pos.getEndColumn() + 1), executing); } private void activateCodeBrowser( final String codeBrowserPath, boolean replaceIfActive, final ResultCallback<CodeBrowserEditingTarget,ServerError> callback) { // first check to see if this request can be fulfilled with an existing // code browser tab for (int i = 0; i < editors_.size(); i++) { if (editors_.get(i).getPath() == codeBrowserPath) { // select the tab ensureVisible(false); view_.selectTab(i); // callback callback.onSuccess((CodeBrowserEditingTarget) editors_.get(i)); // satisfied request return; } } // then check to see if the active editor is a code browser -- if it is, // we'll use it as is, replacing its contents if (replaceIfActive && activeEditor_ != null && activeEditor_ instanceof CodeBrowserEditingTarget) { events_.fireEvent(new CodeBrowserCreatedEvent(activeEditor_.getId(), codeBrowserPath)); callback.onSuccess((CodeBrowserEditingTarget) activeEditor_); return; } // create a new one newDoc(FileTypeRegistry.CODEBROWSER, new ResultCallback<EditingTarget, ServerError>() { @Override public void onSuccess(EditingTarget arg) { events_.fireEvent(new CodeBrowserCreatedEvent( arg.getId(), codeBrowserPath)); callback.onSuccess( (CodeBrowserEditingTarget)arg); } @Override public void onFailure(ServerError error) { callback.onFailure(error); } @Override public void onCancelled() { callback.onCancelled(); } }); } private boolean isDebugSelectionPending() { return debugSelectionTimer_ != null; } private void clearPendingDebugSelection() { if (debugSelectionTimer_ != null) { debugSelectionTimer_.cancel(); debugSelectionTimer_ = null; } } private void setPendingDebugSelection() { if (!isDebugSelectionPending()) { debugSelectionTimer_ = new Timer() { public void run() { debugSelectionTimer_ = null; } }; debugSelectionTimer_.schedule(250); } } private class SourceNavigationResultCallback<T extends EditingTarget> extends ResultCallback<T,ServerError> { public SourceNavigationResultCallback(SourcePosition restorePosition, AppCommand retryCommand) { suspendSourceNavigationAdding_ = true; restorePosition_ = restorePosition; retryCommand_ = retryCommand; } @Override public void onSuccess(final T target) { Scheduler.get().scheduleDeferred(new ScheduledCommand() { @Override public void execute() { try { target.restorePosition(restorePosition_); } finally { suspendSourceNavigationAdding_ = false; } } }); } @Override public void onFailure(ServerError info) { suspendSourceNavigationAdding_ = false; if (retryCommand_.isEnabled()) retryCommand_.execute(); } @Override public void onCancelled() { suspendSourceNavigationAdding_ = false; } private final SourcePosition restorePosition_; private final AppCommand retryCommand_; } @Override public void onSourceExtendedTypeDetected(SourceExtendedTypeDetectedEvent e) { // set the extended type of the specified source file for (EditingTarget editor : editors_) { if (editor.getId().equals(e.getDocId())) { editor.adaptToExtendedFileType(e.getExtendedType()); break; } } } @Override public void onSnippetsChanged(SnippetsChangedEvent event) { SnippetHelper.onSnippetsChanged(event); } // when tabs have been reordered in the session, the physical layout of the // tabs doesn't match the logical order of editors_. it's occasionally // necessary to get or set the tabs by their physical order. public int getPhysicalTabIndex() { int idx = view_.getActiveTabIndex(); if (idx < tabOrder_.size()) { idx = tabOrder_.indexOf(idx); } return idx; } public void setPhysicalTabIndex(int idx) { if (idx < tabOrder_.size()) { idx = tabOrder_.get(idx); } view_.selectTab(idx); } public EditingTarget getActiveEditor() { return activeEditor_; } public void onOpenProfileEvent(OpenProfileEvent event) { onShowProfiler(event); } private void inEditorForPath(String path, OperationWithInput<EditingTarget> onEditorLocated) { for (int i = 0; i < editors_.size(); i++) { String editorPath = editors_.get(i).getPath(); if (editorPath != null && editorPath.equals(path)) { onEditorLocated.execute(editors_.get(i)); break; } } } private void inEditorForId(String id, OperationWithInput<EditingTarget> onEditorLocated) { for (int i = 0; i < editors_.size(); i++) { String editorId = editors_.get(i).getId(); if (editorId != null && editorId.equals(id)) { onEditorLocated.execute(editors_.get(i)); break; } } } private void dispatchEditorEvent(final String id, final CommandWithArg<DocDisplay> command) { InputEditorDisplay console = consoleEditorProvider_.getConsoleEditor(); boolean isConsoleEvent = false; if (console != null) { isConsoleEvent = (StringUtil.isNullOrEmpty(id) && console.isFocused()) || "#console".equals(id); } if (isConsoleEvent) { command.execute((DocDisplay) console); } else { withTarget(id, new CommandWithArg<TextEditingTarget>() { @Override public void execute(TextEditingTarget target) { command.execute(target.getDocDisplay()); } }); } } @Override public void onSetSelectionRanges(final SetSelectionRangesEvent event) { dispatchEditorEvent(event.getData().getId(), new CommandWithArg<DocDisplay>() { @Override public void execute(DocDisplay docDisplay) { JsArray<Range> ranges = event.getData().getRanges(); if (ranges.length() == 0) return; AceEditor editor = (AceEditor) docDisplay; editor.setSelectionRanges(ranges); } }); } @Override public void onGetEditorContext(GetEditorContextEvent event) { GetEditorContextEvent.Data data = event.getData(); int type = data.getType(); if (type == GetEditorContextEvent.TYPE_ACTIVE_EDITOR) { if (consoleEditorHadFocusLast() || activeEditor_ == null) type = GetEditorContextEvent.TYPE_CONSOLE_EDITOR; else type = GetEditorContextEvent.TYPE_SOURCE_EDITOR; } if (type == GetEditorContextEvent.TYPE_CONSOLE_EDITOR) { InputEditorDisplay editor = consoleEditorProvider_.getConsoleEditor(); if (editor != null && editor instanceof DocDisplay) { getEditorContext("#console", "", (DocDisplay) editor); return; } } else if (type == GetEditorContextEvent.TYPE_SOURCE_EDITOR) { EditingTarget target = activeEditor_; if (target != null && target instanceof TextEditingTarget) { getEditorContext( target.getId(), target.getPath(), ((TextEditingTarget) target).getDocDisplay()); return; } } // We need to ensure a 'getEditorContext' event is always // returned as we have a 'wait-for' event on the server side server_.getEditorContextCompleted( GetEditorContextEvent.SelectionData.create(), new VoidServerRequestCallback()); } @Override public void onReplaceRanges(final ReplaceRangesEvent event) { dispatchEditorEvent(event.getData().getId(), new CommandWithArg<DocDisplay>() { @Override public void execute(DocDisplay docDisplay) { doReplaceRanges(event, docDisplay); } }); } private void doReplaceRanges(ReplaceRangesEvent event, DocDisplay docDisplay) { JsArray<ReplacementData> data = event.getData().getReplacementData(); int n = data.length(); for (int i = 0; i < n; i++) { ReplacementData el = data.get(n - i - 1); Range range = el.getRange(); String text = el.getText(); // A null range at this point is a proxy to use the current selection if (range == null) range = docDisplay.getSelectionRange(); docDisplay.replaceRange(range, text); } docDisplay.focus(); } private class OpenFileEntry { public OpenFileEntry(FileSystemItem fileIn, TextFileType fileTypeIn, CommandWithArg<EditingTarget> executeIn) { file = fileIn; fileType = fileTypeIn; executeOnSuccess = executeIn; } public final FileSystemItem file; public final TextFileType fileType; public final CommandWithArg<EditingTarget> executeOnSuccess; } private class StatFileEntry { public StatFileEntry(FileSystemItem fileIn, CommandWithArg<FileSystemItem> actionIn) { file = fileIn; action = actionIn; } public final FileSystemItem file; public final CommandWithArg<FileSystemItem> action; } final Queue<StatFileEntry> statQueue_ = new LinkedList<StatFileEntry>(); final Queue<OpenFileEntry> openFileQueue_ = new LinkedList<OpenFileEntry>(); ArrayList<EditingTarget> editors_ = new ArrayList<EditingTarget>(); ArrayList<Integer> tabOrder_ = new ArrayList<Integer>(); private EditingTarget activeEditor_; private final Commands commands_; private final Display view_; private final SourceServerOperations server_; private final EditingTargetSource editingTargetSource_; private final FileTypeRegistry fileTypeRegistry_; private final GlobalDisplay globalDisplay_; private final WorkbenchContext workbenchContext_; private final FileDialogs fileDialogs_; private final RemoteFileSystemContext fileContext_; private final TextEditingTargetRMarkdownHelper rmarkdown_; private final EventBus events_; private final Session session_; private final Synctex synctex_; private final Provider<FileMRUList> pMruList_; private final UIPrefs uiPrefs_; private final ConsoleEditorProvider consoleEditorProvider_; private final RnwWeaveRegistry rnwWeaveRegistry_; private HashSet<AppCommand> activeCommands_ = new HashSet<AppCommand>(); private final HashSet<AppCommand> dynamicCommands_; private final SourceNavigationHistory sourceNavigationHistory_ = new SourceNavigationHistory(30); private final SourceVimCommands vimCommands_; private boolean suspendSourceNavigationAdding_; private boolean suspendDocumentClose_ = false; private static final String MODULE_SOURCE = "source-pane"; private static final String KEY_ACTIVETAB = "activeTab"; private boolean initialized_; private Timer debugSelectionTimer_ = null; private final SourceWindowManager windowManager_; // If positive, a new tab is about to be created private int newTabPending_; private DependencyManager dependencyManager_; public final static int TYPE_FILE_BACKED = 0; public final static int TYPE_UNTITLED = 1; public final static int OPEN_INTERACTIVE = 0; public final static int OPEN_REPLAY = 1; }
allow 'navigateToFile' to preserve position
src/gwt/src/org/rstudio/studio/client/workbench/views/source/Source.java
allow 'navigateToFile' to preserve position
<ide><path>rc/gwt/src/org/rstudio/studio/client/workbench/views/source/Source.java <ide> @Override <ide> public void execute(EditingTarget target) <ide> { <del> if (position != null) <add> // the rstudioapi package can use the proxy (-1, -1) position to <add> // indicate that source navigation should not occur; ie, we should <add> // preserve whatever position was used in the document earlier <add> boolean navigateToPosition = <add> position != null && <add> (position.getLine() != -1 && position.getColumn() != -1); <add> <add> if (navigateToPosition) <ide> { <ide> SourcePosition endPosition = null; <ide> if (isDebugNavigation)
Java
apache-2.0
f2d5951c250dfaf52f0e3de3a8187c3a0581ee56
0
vishalzanzrukia/streamex,amaembo/streamex,manikitos/streamex
/* * Copyright 2015 Tagir Valeev * * 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 javax.util.streamex; import java.util.BitSet; import java.util.Collection; import java.util.Comparator; import java.util.IntSummaryStatistics; import java.util.List; import java.util.OptionalDouble; import java.util.OptionalInt; import java.util.Random; import java.util.PrimitiveIterator.OfInt; import java.util.function.BiConsumer; import java.util.function.DoublePredicate; import java.util.function.IntBinaryOperator; import java.util.function.IntConsumer; import java.util.function.IntFunction; import java.util.function.IntPredicate; import java.util.function.IntSupplier; import java.util.function.IntToDoubleFunction; import java.util.function.IntToLongFunction; import java.util.function.IntUnaryOperator; import java.util.function.LongPredicate; import java.util.function.ObjIntConsumer; import java.util.function.Predicate; import java.util.function.Supplier; import java.util.stream.IntStream; /** * An {@link IntStream} implementation with additional functionality * * @author Tagir Valeev */ public class IntStreamEx implements IntStream { private static final IntStreamEx EMPTY = new IntStreamEx(IntStream.empty()); private final IntStream stream; IntStreamEx(IntStream stream) { this.stream = stream; } @Override public boolean isParallel() { return stream.isParallel(); } @Override public IntStreamEx unordered() { return new IntStreamEx(stream.unordered()); } @Override public IntStreamEx onClose(Runnable closeHandler) { return new IntStreamEx(stream.onClose(closeHandler)); } @Override public void close() { stream.close(); } @Override public IntStreamEx filter(IntPredicate predicate) { return new IntStreamEx(stream.filter(predicate)); } @Override public IntStreamEx map(IntUnaryOperator mapper) { return new IntStreamEx(stream.map(mapper)); } @Override public <U> StreamEx<U> mapToObj(IntFunction<? extends U> mapper) { return new StreamEx<>(stream.mapToObj(mapper)); } @Override public LongStreamEx mapToLong(IntToLongFunction mapper) { return new LongStreamEx(stream.mapToLong(mapper)); } @Override public DoubleStreamEx mapToDouble(IntToDoubleFunction mapper) { return new DoubleStreamEx(stream.mapToDouble(mapper)); } @Override public IntStreamEx flatMap(IntFunction<? extends IntStream> mapper) { return new IntStreamEx(stream.flatMap(mapper)); } @Override public IntStreamEx distinct() { return new IntStreamEx(stream.distinct()); } /** * Returns a stream consisting of the elements of this stream in sorted * order. * * <p>This is a stateful intermediate operation. * * @return the new stream */ @Override public IntStreamEx sorted() { return new IntStreamEx(stream.sorted()); } @Override public IntStreamEx peek(IntConsumer action) { return new IntStreamEx(stream.peek(action)); } @Override public IntStreamEx limit(long maxSize) { return new IntStreamEx(stream.limit(maxSize)); } @Override public IntStreamEx skip(long n) { return new IntStreamEx(stream.skip(n)); } @Override public void forEach(IntConsumer action) { stream.forEach(action); } @Override public void forEachOrdered(IntConsumer action) { stream.forEachOrdered(action); } @Override public int[] toArray() { return stream.toArray(); } @Override public int reduce(int identity, IntBinaryOperator op) { return stream.reduce(identity, op); } @Override public OptionalInt reduce(IntBinaryOperator op) { return stream.reduce(op); } @Override public <R> R collect(Supplier<R> supplier, ObjIntConsumer<R> accumulator, BiConsumer<R, R> combiner) { return stream.collect(supplier, accumulator, combiner); } @Override public int sum() { return stream.sum(); } @Override public OptionalInt min() { return stream.min(); } @Override public OptionalInt max() { return stream.max(); } @Override public long count() { return stream.count(); } @Override public OptionalDouble average() { return stream.average(); } @Override public IntSummaryStatistics summaryStatistics() { return stream.summaryStatistics(); } @Override public boolean anyMatch(IntPredicate predicate) { return stream.anyMatch(predicate); } @Override public boolean allMatch(IntPredicate predicate) { return stream.allMatch(predicate); } @Override public boolean noneMatch(IntPredicate predicate) { return stream.noneMatch(predicate); } @Override public OptionalInt findFirst() { return stream.findFirst(); } @Override public OptionalInt findAny() { return stream.findAny(); } @Override public LongStreamEx asLongStream() { return new LongStreamEx(stream.asLongStream()); } @Override public DoubleStreamEx asDoubleStream() { return new DoubleStreamEx(stream.asDoubleStream()); } @Override public StreamEx<Integer> boxed() { return new StreamEx<>(stream.boxed()); } @Override public IntStreamEx sequential() { return new IntStreamEx(stream.sequential()); } @Override public IntStreamEx parallel() { return new IntStreamEx(stream.parallel()); } @Override public OfInt iterator() { return stream.iterator(); } @Override public java.util.Spliterator.OfInt spliterator() { return stream.spliterator(); } /** * Returns a new {@code IntStreamEx} which is a concatenation of this stream * and the stream containing supplied values * * @param values the values to append to the stream * @return the new stream */ public IntStreamEx append(int... values) { return new IntStreamEx(IntStream.concat(stream, IntStream.of(values))); } public IntStreamEx append(IntStream other) { return new IntStreamEx(IntStream.concat(stream, other)); } /** * Returns a new {@code IntStreamEx} which is a concatenation of * the stream containing supplied values and this stream * * @param values the values to prepend to the stream * @return the new stream */ public IntStreamEx prepend(int... values) { return new IntStreamEx(IntStream.concat(IntStream.of(values), stream)); } public IntStreamEx prepend(IntStream other) { return new IntStreamEx(IntStream.concat(other, stream)); } public IntStreamEx remove(IntPredicate predicate) { return new IntStreamEx(stream.filter(predicate.negate())); } public OptionalInt findAny(IntPredicate predicate) { return stream.filter(predicate).findAny(); } public OptionalInt findFirst(IntPredicate predicate) { return stream.filter(predicate).findFirst(); } /** * Returns true if this stream contains the specified value * * <p>This is a short-circuiting terminal operation. * * @param value the value too look for in the stream * @return true if this stream contains the specified value * @see IntStream#anyMatch(IntPredicate) */ public boolean has(int value) { return stream.anyMatch(x -> x == value); } public IntStreamEx sorted(Comparator<Integer> comparator) { return new IntStreamEx(stream.boxed().sorted(comparator).mapToInt(Integer::intValue)); } /** * Returns a stream consisting of the elements of this stream in reverse * sorted order. * * <p>This is a stateful intermediate operation. * * @return the new stream * @since 0.0.8 */ public IntStreamEx reverseSorted() { return sorted((a, b) -> b.compareTo(a)); } public <V extends Comparable<? super V>> IntStreamEx sortedBy(IntFunction<V> keyExtractor) { return new IntStreamEx(stream.boxed().sorted(Comparator.comparing(i -> keyExtractor.apply(i))) .mapToInt(Integer::intValue)); } public IntStreamEx sortedByInt(IntUnaryOperator keyExtractor) { return new IntStreamEx(stream.boxed().sorted(Comparator.comparingInt(i -> keyExtractor.applyAsInt(i))) .mapToInt(Integer::intValue)); } public IntStreamEx sortedByLong(IntToLongFunction keyExtractor) { return new IntStreamEx(stream.boxed().sorted(Comparator.comparingLong(i -> keyExtractor.applyAsLong(i))) .mapToInt(Integer::intValue)); } public IntStreamEx sortedByDouble(IntToDoubleFunction keyExtractor) { return new IntStreamEx(stream.boxed().sorted(Comparator.comparingDouble(i -> keyExtractor.applyAsDouble(i))) .mapToInt(Integer::intValue)); } public static IntStreamEx empty() { return EMPTY; } /** * Returns a sequential {@code IntStreamEx} containing a single element. * * @param element the single element * @return a singleton sequential stream */ public static IntStreamEx of(int element) { return new IntStreamEx(IntStream.of(element)); } /** * Returns a sequential ordered {@code IntStreamEx} whose elements are the specified values. * * @param elements the elements of the new stream * @return the new stream */ public static IntStreamEx of(int... elements) { return new IntStreamEx(IntStream.of(elements)); } /** * Returns a sequential ordered {@code IntStreamEx} containing all the * indices of the supplied list. * * @param <T> list element type * @param list list to get the stream of its indices * @return a sequential {@code IntStreamEx} for the range of {@code int} * elements starting from 0 to (not inclusive) list.size() * @since 0.1.1 */ public static <T> IntStreamEx ofIndices(List<T> list) { return range(0, list.size()); } /** * Returns a sequential ordered {@code IntStreamEx} containing all the * indices of the supplied list elements which match given predicate. * * The list elements are accessed using {@link List#get(int)}, so the * list should provide fast random access. The list is assumed to be * unmodifiable during the stream operations. * * @param <T> list element type * @param list list to get the stream of its indices * @param predicate a predicate to test list elements * @return a sequential {@code IntStreamEx} of the matched list indices * @since 0.1.1 */ public static <T> IntStreamEx ofIndices(List<T> list, Predicate<T> predicate) { return new IntStreamEx(IntStream.range(0, list.size()).filter(i -> predicate.test(list.get(i)))); } /** * Returns a sequential ordered {@code IntStreamEx} containing all the * indices of the supplied array. * * @param <T> array element type * @param array array to get the stream of its indices * @return a sequential {@code IntStreamEx} for the range of {@code int} * elements starting from 0 to (not inclusive) array.length * @since 0.1.1 */ public static <T> IntStreamEx ofIndices(T[] array) { return range(0, array.length); } /** * Returns a sequential ordered {@code IntStreamEx} containing all the * indices of the supplied array elements which match given predicate. * * @param <T> array element type * @param array array to get the stream of its indices * @param predicate a predicate to test array elements * @return a sequential {@code IntStreamEx} of the matched array indices * @since 0.1.1 */ public static <T> IntStreamEx ofIndices(T[] array, Predicate<T> predicate) { return new IntStreamEx(IntStream.range(0, array.length).filter(i -> predicate.test(array[i]))); } /** * Returns a sequential ordered {@code IntStreamEx} containing all the * indices of supplied array. * * @param array array to get the stream of its indices * @return a sequential {@code IntStreamEx} for the range of {@code int} * elements starting from 0 to (not inclusive) array.length * @since 0.1.1 */ public static IntStreamEx ofIndices(int[] array) { return range(0, array.length); } /** * Returns a sequential ordered {@code IntStreamEx} containing all the * indices of the supplied array elements which match given predicate. * * @param array array to get the stream of its indices * @param predicate a predicate to test array elements * @return a sequential {@code IntStreamEx} of the matched array indices * @since 0.1.1 */ public static IntStreamEx ofIndices(int[] array, IntPredicate predicate) { return new IntStreamEx(IntStream.range(0, array.length).filter(i -> predicate.test(array[i]))); } /** * Returns a sequential ordered {@code IntStreamEx} containing all the * indices of supplied array. * * @param array array to get the stream of its indices * @return a sequential {@code IntStreamEx} for the range of {@code int} * elements starting from 0 to (not inclusive) array.length * @since 0.1.1 */ public static IntStreamEx ofIndices(long[] array) { return range(0, array.length); } /** * Returns a sequential ordered {@code IntStreamEx} containing all the * indices of the supplied array elements which match given predicate. * * @param array array to get the stream of its indices * @param predicate a predicate to test array elements * @return a sequential {@code IntStreamEx} of the matched array indices * @since 0.1.1 */ public static IntStreamEx ofIndices(long[] array, LongPredicate predicate) { return new IntStreamEx(IntStream.range(0, array.length).filter(i -> predicate.test(array[i]))); } /** * Returns a sequential ordered {@code IntStreamEx} containing all the * indices of supplied array. * * @param array array to get the stream of its indices * @return a sequential {@code IntStreamEx} for the range of {@code int} * elements starting from 0 to (not inclusive) array.length * @since 0.1.1 */ public static IntStreamEx ofIndices(double[] array) { return range(0, array.length); } /** * Returns a sequential ordered {@code IntStreamEx} containing all the * indices of the supplied array elements which match given predicate. * * @param array array to get the stream of its indices * @param predicate a predicate to test array elements * @return a sequential {@code IntStreamEx} of the matched array indices * @since 0.1.1 */ public static IntStreamEx ofIndices(double[] array, DoublePredicate predicate) { return new IntStreamEx(IntStream.range(0, array.length).filter(i -> predicate.test(array[i]))); } /** * Returns an {@code IntStreamEx} object which wraps given {@link IntStream} * @param stream original stream * @return the wrapped stream * @since 0.0.8 */ public static IntStreamEx of(IntStream stream) { return stream instanceof IntStreamEx ? (IntStreamEx) stream : new IntStreamEx(stream); } /** * Returns an {@code IntStreamEx} of indices for which the specified {@link BitSet} * contains a bit in the set state. The indices are returned * in order, from lowest to highest. The size of the stream * is the number of bits in the set state, equal to the value * returned by the {@link BitSet#cardinality()} method. * * <p>The bit set must remain constant during the execution of the * terminal stream operation. Otherwise, the result of the terminal * stream operation is undefined. * * @param bitSet a {@link BitSet} to produce the stream from * @return a stream of integers representing set indices * @see BitSet#stream() */ public static IntStreamEx of(BitSet bitSet) { return new IntStreamEx(bitSet.stream()); } /** * Returns an {@code IntStreamEx} containing primitive * integers from given collection * * @param c a collection to produce the stream from * @return the new stream * @see Collection#stream() */ public static IntStreamEx of(Collection<Integer> c) { return new IntStreamEx(c.stream().mapToInt(Integer::intValue)); } /** * Returns an effectively unlimited stream of pseudorandom {@code int} * values produced by given {@link Random} object. * * <p>A pseudorandom {@code int} value is generated as if it's the result of * calling the method {@link Random#nextInt()}. * * @param random a {@link Random} object to produce the stream from * @return a stream of pseudorandom {@code int} values * @see Random#ints() */ public static IntStreamEx of(Random random) { return new IntStreamEx(random.ints()); } /** * Returns a stream producing the given {@code streamSize} number of * pseudorandom {@code int} values. * * <p>A pseudorandom {@code int} value is generated as if it's the result of * calling the method {@link Random#nextInt()}. * * @param random a {@link Random} object to produce the stream from * @param streamSize the number of values to generate * @return a stream of pseudorandom {@code int} values * @see Random#ints(long) */ public static IntStreamEx of(Random random, long streamSize) { return new IntStreamEx(random.ints(streamSize)); } public static IntStreamEx of(Random random, int randomNumberOrigin, int randomNumberBound) { return new IntStreamEx(random.ints(randomNumberOrigin, randomNumberBound)); } public static IntStreamEx of(Random random, long streamSize, int randomNumberOrigin, int randomNumberBound) { return new IntStreamEx(random.ints(streamSize, randomNumberOrigin, randomNumberBound)); } /** * Returns an {@code IntStreamEx} of {@code int} zero-extending the {@code char} values * from the supplied {@link CharSequence}. Any char which maps to a * surrogate code point is passed through uninterpreted. * * <p>If the sequence is mutated while the stream is being read, the * result is undefined. * * @param seq sequence to read characters from * @return an IntStreamEx of char values from the sequence * @see CharSequence#chars() */ public static IntStreamEx ofChars(CharSequence seq) { return new IntStreamEx(seq.chars()); } /** * Returns an {@code IntStreamEx} of code point values from the supplied {@link CharSequence}. * Any surrogate pairs encountered in the sequence are combined as if by * {@linkplain Character#toCodePoint Character.toCodePoint} and the result is passed * to the stream. Any other code units, including ordinary BMP characters, * unpaired surrogates, and undefined code units, are zero-extended to * {@code int} values which are then passed to the stream. * * <p>If the sequence is mutated while the stream is being read, the result * is undefined. * * @param seq sequence to read code points from * @return an IntStreamEx of Unicode code points from this sequence * @see CharSequence#codePoints() */ public static IntStreamEx ofCodePoints(CharSequence seq) { return new IntStreamEx(seq.codePoints()); } /** * Returns an infinite sequential ordered {@code IntStreamEx} produced by iterative * application of a function {@code f} to an initial element {@code seed}, * producing a stream consisting of {@code seed}, {@code f(seed)}, * {@code f(f(seed))}, etc. * * <p>The first element (position {@code 0}) in the {@code IntStreamEx} will be * the provided {@code seed}. For {@code n > 0}, the element at position * {@code n}, will be the result of applying the function {@code f} to the * element at position {@code n - 1}. * * @param seed the initial element * @param f a function to be applied to to the previous element to produce * a new element * @return A new sequential {@code IntStream} * @see IntStream#iterate(int, IntUnaryOperator) */ public static IntStreamEx iterate(final int seed, final IntUnaryOperator f) { return new IntStreamEx(IntStream.iterate(seed, f)); } /** * Returns an infinite sequential unordered stream where each element is * generated by the provided {@code IntSupplier}. This is suitable for * generating constant streams, streams of random elements, etc. * * @param s the {@code IntSupplier} for generated elements * @return a new infinite sequential unordered {@code IntStreamEx} * @see IntStream#generate(IntSupplier) */ public static IntStreamEx generate(IntSupplier s) { return new IntStreamEx(IntStream.generate(s)); } /** * Returns a sequential ordered {@code IntStreamEx} from {@code startInclusive} * (inclusive) to {@code endExclusive} (exclusive) by an incremental step of * {@code 1}. * * @param startInclusive the (inclusive) initial value * @param endExclusive the exclusive upper bound * @return a sequential {@code IntStreamEx} for the range of {@code int} * elements */ public static IntStreamEx range(int startInclusive, int endExclusive) { return new IntStreamEx(IntStream.range(startInclusive, endExclusive)); } public static IntStreamEx rangeClosed(int startInclusive, int endInclusive) { return new IntStreamEx(IntStream.rangeClosed(startInclusive, endInclusive)); } }
src/main/java/javax/util/streamex/IntStreamEx.java
/* * Copyright 2015 Tagir Valeev * * 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 javax.util.streamex; import java.util.BitSet; import java.util.Collection; import java.util.Comparator; import java.util.IntSummaryStatistics; import java.util.List; import java.util.OptionalDouble; import java.util.OptionalInt; import java.util.Random; import java.util.PrimitiveIterator.OfInt; import java.util.function.BiConsumer; import java.util.function.DoublePredicate; import java.util.function.IntBinaryOperator; import java.util.function.IntConsumer; import java.util.function.IntFunction; import java.util.function.IntPredicate; import java.util.function.IntSupplier; import java.util.function.IntToDoubleFunction; import java.util.function.IntToLongFunction; import java.util.function.IntUnaryOperator; import java.util.function.LongPredicate; import java.util.function.ObjIntConsumer; import java.util.function.Predicate; import java.util.function.Supplier; import java.util.stream.IntStream; /** * An {@link IntStream} implementation with additional functionality * * @author Tagir Valeev */ public class IntStreamEx implements IntStream { private static final IntStreamEx EMPTY = new IntStreamEx(IntStream.empty()); private final IntStream stream; IntStreamEx(IntStream stream) { this.stream = stream; } @Override public boolean isParallel() { return stream.isParallel(); } @Override public IntStreamEx unordered() { return new IntStreamEx(stream.unordered()); } @Override public IntStreamEx onClose(Runnable closeHandler) { return new IntStreamEx(stream.onClose(closeHandler)); } @Override public void close() { stream.close(); } @Override public IntStreamEx filter(IntPredicate predicate) { return new IntStreamEx(stream.filter(predicate)); } @Override public IntStreamEx map(IntUnaryOperator mapper) { return new IntStreamEx(stream.map(mapper)); } @Override public <U> StreamEx<U> mapToObj(IntFunction<? extends U> mapper) { return new StreamEx<>(stream.mapToObj(mapper)); } @Override public LongStreamEx mapToLong(IntToLongFunction mapper) { return new LongStreamEx(stream.mapToLong(mapper)); } @Override public DoubleStreamEx mapToDouble(IntToDoubleFunction mapper) { return new DoubleStreamEx(stream.mapToDouble(mapper)); } @Override public IntStreamEx flatMap(IntFunction<? extends IntStream> mapper) { return new IntStreamEx(stream.flatMap(mapper)); } @Override public IntStreamEx distinct() { return new IntStreamEx(stream.distinct()); } /** * Returns a stream consisting of the elements of this stream in sorted * order. * * <p>This is a stateful intermediate operation. * * @return the new stream */ @Override public IntStreamEx sorted() { return new IntStreamEx(stream.sorted()); } @Override public IntStreamEx peek(IntConsumer action) { return new IntStreamEx(stream.peek(action)); } @Override public IntStreamEx limit(long maxSize) { return new IntStreamEx(stream.limit(maxSize)); } @Override public IntStreamEx skip(long n) { return new IntStreamEx(stream.skip(n)); } @Override public void forEach(IntConsumer action) { stream.forEach(action); } @Override public void forEachOrdered(IntConsumer action) { stream.forEachOrdered(action); } @Override public int[] toArray() { return stream.toArray(); } @Override public int reduce(int identity, IntBinaryOperator op) { return stream.reduce(identity, op); } @Override public OptionalInt reduce(IntBinaryOperator op) { return stream.reduce(op); } @Override public <R> R collect(Supplier<R> supplier, ObjIntConsumer<R> accumulator, BiConsumer<R, R> combiner) { return stream.collect(supplier, accumulator, combiner); } @Override public int sum() { return stream.sum(); } @Override public OptionalInt min() { return stream.min(); } @Override public OptionalInt max() { return stream.max(); } @Override public long count() { return stream.count(); } @Override public OptionalDouble average() { return stream.average(); } @Override public IntSummaryStatistics summaryStatistics() { return stream.summaryStatistics(); } @Override public boolean anyMatch(IntPredicate predicate) { return stream.anyMatch(predicate); } @Override public boolean allMatch(IntPredicate predicate) { return stream.allMatch(predicate); } @Override public boolean noneMatch(IntPredicate predicate) { return stream.noneMatch(predicate); } @Override public OptionalInt findFirst() { return stream.findFirst(); } @Override public OptionalInt findAny() { return stream.findAny(); } @Override public LongStreamEx asLongStream() { return new LongStreamEx(stream.asLongStream()); } @Override public DoubleStreamEx asDoubleStream() { return new DoubleStreamEx(stream.asDoubleStream()); } @Override public StreamEx<Integer> boxed() { return new StreamEx<>(stream.boxed()); } @Override public IntStreamEx sequential() { return new IntStreamEx(stream.sequential()); } @Override public IntStreamEx parallel() { return new IntStreamEx(stream.parallel()); } @Override public OfInt iterator() { return stream.iterator(); } @Override public java.util.Spliterator.OfInt spliterator() { return stream.spliterator(); } /** * Returns a new {@code IntStreamEx} which is a concatenation of this stream * and the stream containing supplied values * * @param values the values to append to the stream * @return the new stream */ public IntStreamEx append(int... values) { return new IntStreamEx(IntStream.concat(stream, IntStream.of(values))); } public IntStreamEx append(IntStream other) { return new IntStreamEx(IntStream.concat(stream, other)); } /** * Returns a new {@code IntStreamEx} which is a concatenation of * the stream containing supplied values and this stream * * @param values the values to prepend to the stream * @return the new stream */ public IntStreamEx prepend(int... values) { return new IntStreamEx(IntStream.concat(IntStream.of(values), stream)); } public IntStreamEx prepend(IntStream other) { return new IntStreamEx(IntStream.concat(other, stream)); } public IntStreamEx remove(IntPredicate predicate) { return new IntStreamEx(stream.filter(predicate.negate())); } public OptionalInt findAny(IntPredicate predicate) { return stream.filter(predicate).findAny(); } public OptionalInt findFirst(IntPredicate predicate) { return stream.filter(predicate).findFirst(); } /** * Returns true if this stream contains the specified value * * <p>This is a short-circuiting terminal operation. * * @param value the value too look for in the stream * @return true if this stream contains the specified value * @see IntStream#anyMatch(IntPredicate) */ public boolean has(int value) { return stream.anyMatch(x -> x == value); } public IntStreamEx sorted(Comparator<Integer> comparator) { return new IntStreamEx(stream.boxed().sorted(comparator).mapToInt(Integer::intValue)); } /** * Returns a stream consisting of the elements of this stream in reverse * sorted order. * * <p>This is a stateful intermediate operation. * * @return the new stream * @since 0.0.8 */ public IntStreamEx reverseSorted() { return sorted((a, b) -> b.compareTo(a)); } public <V extends Comparable<? super V>> IntStreamEx sortedBy(IntFunction<V> keyExtractor) { return new IntStreamEx(stream.boxed().sorted(Comparator.comparing(i -> keyExtractor.apply(i))) .mapToInt(Integer::intValue)); } public IntStreamEx sortedByInt(IntUnaryOperator keyExtractor) { return new IntStreamEx(stream.boxed().sorted(Comparator.comparingInt(i -> keyExtractor.applyAsInt(i))) .mapToInt(Integer::intValue)); } public IntStreamEx sortedByLong(IntToLongFunction keyExtractor) { return new IntStreamEx(stream.boxed().sorted(Comparator.comparingLong(i -> keyExtractor.applyAsLong(i))) .mapToInt(Integer::intValue)); } public IntStreamEx sortedByDouble(IntToDoubleFunction keyExtractor) { return new IntStreamEx(stream.boxed().sorted(Comparator.comparingDouble(i -> keyExtractor.applyAsDouble(i))) .mapToInt(Integer::intValue)); } public static IntStreamEx empty() { return EMPTY; } /** * Returns a sequential {@code IntStreamEx} containing a single element. * * @param element the single element * @return a singleton sequential stream */ public static IntStreamEx of(int element) { return new IntStreamEx(IntStream.of(element)); } /** * Returns a sequential ordered {@code IntStreamEx} whose elements are the specified values. * * @param elements the elements of the new stream * @return the new stream */ public static IntStreamEx of(int... elements) { return new IntStreamEx(IntStream.of(elements)); } /** * Returns a sequential ordered {@code IntStreamEx} containing all the * indices of the supplied list. * * @param <T> list element type * @param list list to get the stream of its indices * @return a sequential {@code IntStreamEx} for the range of {@code int} * elements starting from 0 to (not inclusive) list.size() */ public static <T> IntStreamEx ofIndices(List<T> list) { return range(0, list.size()); } /** * Returns a sequential ordered {@code IntStreamEx} containing all the * indices of the supplied list elements which match given predicate. * * The list elements are accessed using {@link List#get(int)}, so the * list should provide fast random access. The list is assumed to be * unmodifiable during the stream operations. * * @param <T> list element type * @param list list to get the stream of its indices * @param predicate a predicate to test list elements * @return a sequential {@code IntStreamEx} of the matched list indices */ public static <T> IntStreamEx ofIndices(List<T> list, Predicate<T> predicate) { return range(0, list.size()).filter(i -> predicate.test(list.get(i))); } /** * Returns a sequential ordered {@code IntStreamEx} containing all the * indices of the supplied array. * * @param <T> array element type * @param array array to get the stream of its indices * @return a sequential {@code IntStreamEx} for the range of {@code int} * elements starting from 0 to (not inclusive) array.length */ public static <T> IntStreamEx ofIndices(T[] array) { return range(0, array.length); } /** * Returns a sequential ordered {@code IntStreamEx} containing all the * indices of the supplied array elements which match given predicate. * * @param <T> array element type * @param array array to get the stream of its indices * @param predicate a predicate to test array elements * @return a sequential {@code IntStreamEx} of the matched array indices */ public static <T> IntStreamEx ofIndices(T[] array, Predicate<T> predicate) { return range(0, array.length).filter(i -> predicate.test(array[i])); } /** * Returns a sequential ordered {@code IntStreamEx} containing all the * indices of supplied array. * * @param array array to get the stream of its indices * @return a sequential {@code IntStreamEx} for the range of {@code int} * elements starting from 0 to (not inclusive) array.length */ public static IntStreamEx ofIndices(int[] array) { return range(0, array.length); } /** * Returns a sequential ordered {@code IntStreamEx} containing all the * indices of the supplied array elements which match given predicate. * * @param array array to get the stream of its indices * @param predicate a predicate to test array elements * @return a sequential {@code IntStreamEx} of the matched array indices */ public static IntStreamEx ofIndices(int[] array, IntPredicate predicate) { return range(0, array.length).filter(i -> predicate.test(array[i])); } /** * Returns a sequential ordered {@code IntStreamEx} containing all the * indices of supplied array. * * @param array array to get the stream of its indices * @return a sequential {@code IntStreamEx} for the range of {@code int} * elements starting from 0 to (not inclusive) array.length */ public static IntStreamEx ofIndices(long[] array) { return range(0, array.length); } /** * Returns a sequential ordered {@code IntStreamEx} containing all the * indices of the supplied array elements which match given predicate. * * @param array array to get the stream of its indices * @param predicate a predicate to test array elements * @return a sequential {@code IntStreamEx} of the matched array indices */ public static IntStreamEx ofIndices(long[] array, LongPredicate predicate) { return range(0, array.length).filter(i -> predicate.test(array[i])); } /** * Returns a sequential ordered {@code IntStreamEx} containing all the * indices of supplied array. * * @param array array to get the stream of its indices * @return a sequential {@code IntStreamEx} for the range of {@code int} * elements starting from 0 to (not inclusive) array.length */ public static IntStreamEx ofIndices(double[] array) { return range(0, array.length); } /** * Returns a sequential ordered {@code IntStreamEx} containing all the * indices of the supplied array elements which match given predicate. * * @param array array to get the stream of its indices * @param predicate a predicate to test array elements * @return a sequential {@code IntStreamEx} of the matched array indices */ public static IntStreamEx ofIndices(double[] array, DoublePredicate predicate) { return range(0, array.length).filter(i -> predicate.test(array[i])); } /** * Returns an {@code IntStreamEx} object which wraps given {@link IntStream} * @param stream original stream * @return the wrapped stream * @since 0.0.8 */ public static IntStreamEx of(IntStream stream) { return stream instanceof IntStreamEx ? (IntStreamEx) stream : new IntStreamEx(stream); } /** * Returns an {@code IntStreamEx} of indices for which the specified {@link BitSet} * contains a bit in the set state. The indices are returned * in order, from lowest to highest. The size of the stream * is the number of bits in the set state, equal to the value * returned by the {@link BitSet#cardinality()} method. * * <p>The bit set must remain constant during the execution of the * terminal stream operation. Otherwise, the result of the terminal * stream operation is undefined. * * @param bitSet a {@link BitSet} to produce the stream from * @return a stream of integers representing set indices * @see BitSet#stream() */ public static IntStreamEx of(BitSet bitSet) { return new IntStreamEx(bitSet.stream()); } /** * Returns an {@code IntStreamEx} containing primitive * integers from given collection * * @param c a collection to produce the stream from * @return the new stream * @see Collection#stream() */ public static IntStreamEx of(Collection<Integer> c) { return new IntStreamEx(c.stream().mapToInt(Integer::intValue)); } /** * Returns an effectively unlimited stream of pseudorandom {@code int} * values produced by given {@link Random} object. * * <p>A pseudorandom {@code int} value is generated as if it's the result of * calling the method {@link Random#nextInt()}. * * @param random a {@link Random} object to produce the stream from * @return a stream of pseudorandom {@code int} values * @see Random#ints() */ public static IntStreamEx of(Random random) { return new IntStreamEx(random.ints()); } /** * Returns a stream producing the given {@code streamSize} number of * pseudorandom {@code int} values. * * <p>A pseudorandom {@code int} value is generated as if it's the result of * calling the method {@link Random#nextInt()}. * * @param random a {@link Random} object to produce the stream from * @param streamSize the number of values to generate * @return a stream of pseudorandom {@code int} values * @see Random#ints(long) */ public static IntStreamEx of(Random random, long streamSize) { return new IntStreamEx(random.ints(streamSize)); } public static IntStreamEx of(Random random, int randomNumberOrigin, int randomNumberBound) { return new IntStreamEx(random.ints(randomNumberOrigin, randomNumberBound)); } public static IntStreamEx of(Random random, long streamSize, int randomNumberOrigin, int randomNumberBound) { return new IntStreamEx(random.ints(streamSize, randomNumberOrigin, randomNumberBound)); } /** * Returns an {@code IntStreamEx} of {@code int} zero-extending the {@code char} values * from the supplied {@link CharSequence}. Any char which maps to a * surrogate code point is passed through uninterpreted. * * <p>If the sequence is mutated while the stream is being read, the * result is undefined. * * @param seq sequence to read characters from * @return an IntStreamEx of char values from the sequence * @see CharSequence#chars() */ public static IntStreamEx ofChars(CharSequence seq) { return new IntStreamEx(seq.chars()); } /** * Returns an {@code IntStreamEx} of code point values from the supplied {@link CharSequence}. * Any surrogate pairs encountered in the sequence are combined as if by * {@linkplain Character#toCodePoint Character.toCodePoint} and the result is passed * to the stream. Any other code units, including ordinary BMP characters, * unpaired surrogates, and undefined code units, are zero-extended to * {@code int} values which are then passed to the stream. * * <p>If the sequence is mutated while the stream is being read, the result * is undefined. * * @param seq sequence to read code points from * @return an IntStreamEx of Unicode code points from this sequence * @see CharSequence#codePoints() */ public static IntStreamEx ofCodePoints(CharSequence seq) { return new IntStreamEx(seq.codePoints()); } /** * Returns an infinite sequential ordered {@code IntStreamEx} produced by iterative * application of a function {@code f} to an initial element {@code seed}, * producing a stream consisting of {@code seed}, {@code f(seed)}, * {@code f(f(seed))}, etc. * * <p>The first element (position {@code 0}) in the {@code IntStreamEx} will be * the provided {@code seed}. For {@code n > 0}, the element at position * {@code n}, will be the result of applying the function {@code f} to the * element at position {@code n - 1}. * * @param seed the initial element * @param f a function to be applied to to the previous element to produce * a new element * @return A new sequential {@code IntStream} * @see IntStream#iterate(int, IntUnaryOperator) */ public static IntStreamEx iterate(final int seed, final IntUnaryOperator f) { return new IntStreamEx(IntStream.iterate(seed, f)); } /** * Returns an infinite sequential unordered stream where each element is * generated by the provided {@code IntSupplier}. This is suitable for * generating constant streams, streams of random elements, etc. * * @param s the {@code IntSupplier} for generated elements * @return a new infinite sequential unordered {@code IntStreamEx} * @see IntStream#generate(IntSupplier) */ public static IntStreamEx generate(IntSupplier s) { return new IntStreamEx(IntStream.generate(s)); } /** * Returns a sequential ordered {@code IntStreamEx} from {@code startInclusive} * (inclusive) to {@code endExclusive} (exclusive) by an incremental step of * {@code 1}. * * @param startInclusive the (inclusive) initial value * @param endExclusive the exclusive upper bound * @return a sequential {@code IntStreamEx} for the range of {@code int} * elements */ public static IntStreamEx range(int startInclusive, int endExclusive) { return new IntStreamEx(IntStream.range(startInclusive, endExclusive)); } public static IntStreamEx rangeClosed(int startInclusive, int endInclusive) { return new IntStreamEx(IntStream.rangeClosed(startInclusive, endInclusive)); } }
IntStreamEx#ofIndices: minor optimization, @since tag added
src/main/java/javax/util/streamex/IntStreamEx.java
IntStreamEx#ofIndices: minor optimization, @since tag added
<ide><path>rc/main/java/javax/util/streamex/IntStreamEx.java <ide> * @param list list to get the stream of its indices <ide> * @return a sequential {@code IntStreamEx} for the range of {@code int} <ide> * elements starting from 0 to (not inclusive) list.size() <add> * @since 0.1.1 <ide> */ <ide> public static <T> IntStreamEx ofIndices(List<T> list) { <ide> return range(0, list.size()); <ide> * @param list list to get the stream of its indices <ide> * @param predicate a predicate to test list elements <ide> * @return a sequential {@code IntStreamEx} of the matched list indices <add> * @since 0.1.1 <ide> */ <ide> public static <T> IntStreamEx ofIndices(List<T> list, Predicate<T> predicate) { <del> return range(0, list.size()).filter(i -> predicate.test(list.get(i))); <add> return new IntStreamEx(IntStream.range(0, list.size()).filter(i -> predicate.test(list.get(i)))); <ide> } <ide> <ide> /** <ide> * @param array array to get the stream of its indices <ide> * @return a sequential {@code IntStreamEx} for the range of {@code int} <ide> * elements starting from 0 to (not inclusive) array.length <add> * @since 0.1.1 <ide> */ <ide> public static <T> IntStreamEx ofIndices(T[] array) { <ide> return range(0, array.length); <ide> * @param array array to get the stream of its indices <ide> * @param predicate a predicate to test array elements <ide> * @return a sequential {@code IntStreamEx} of the matched array indices <add> * @since 0.1.1 <ide> */ <ide> public static <T> IntStreamEx ofIndices(T[] array, Predicate<T> predicate) { <del> return range(0, array.length).filter(i -> predicate.test(array[i])); <add> return new IntStreamEx(IntStream.range(0, array.length).filter(i -> predicate.test(array[i]))); <ide> } <ide> <ide> /** <ide> * @param array array to get the stream of its indices <ide> * @return a sequential {@code IntStreamEx} for the range of {@code int} <ide> * elements starting from 0 to (not inclusive) array.length <add> * @since 0.1.1 <ide> */ <ide> public static IntStreamEx ofIndices(int[] array) { <ide> return range(0, array.length); <ide> * @param array array to get the stream of its indices <ide> * @param predicate a predicate to test array elements <ide> * @return a sequential {@code IntStreamEx} of the matched array indices <add> * @since 0.1.1 <ide> */ <ide> public static IntStreamEx ofIndices(int[] array, IntPredicate predicate) { <del> return range(0, array.length).filter(i -> predicate.test(array[i])); <add> return new IntStreamEx(IntStream.range(0, array.length).filter(i -> predicate.test(array[i]))); <ide> } <ide> <ide> /** <ide> * @param array array to get the stream of its indices <ide> * @return a sequential {@code IntStreamEx} for the range of {@code int} <ide> * elements starting from 0 to (not inclusive) array.length <add> * @since 0.1.1 <ide> */ <ide> public static IntStreamEx ofIndices(long[] array) { <ide> return range(0, array.length); <ide> * @param array array to get the stream of its indices <ide> * @param predicate a predicate to test array elements <ide> * @return a sequential {@code IntStreamEx} of the matched array indices <add> * @since 0.1.1 <ide> */ <ide> public static IntStreamEx ofIndices(long[] array, LongPredicate predicate) { <del> return range(0, array.length).filter(i -> predicate.test(array[i])); <add> return new IntStreamEx(IntStream.range(0, array.length).filter(i -> predicate.test(array[i]))); <ide> } <ide> <ide> /** <ide> * @param array array to get the stream of its indices <ide> * @return a sequential {@code IntStreamEx} for the range of {@code int} <ide> * elements starting from 0 to (not inclusive) array.length <add> * @since 0.1.1 <ide> */ <ide> public static IntStreamEx ofIndices(double[] array) { <ide> return range(0, array.length); <ide> * @param array array to get the stream of its indices <ide> * @param predicate a predicate to test array elements <ide> * @return a sequential {@code IntStreamEx} of the matched array indices <add> * @since 0.1.1 <ide> */ <ide> public static IntStreamEx ofIndices(double[] array, DoublePredicate predicate) { <del> return range(0, array.length).filter(i -> predicate.test(array[i])); <add> return new IntStreamEx(IntStream.range(0, array.length).filter(i -> predicate.test(array[i]))); <ide> } <ide> <ide> /**
Java
apache-2.0
1b726825fac4ed20dcefe7a44d894d3094aca784
0
Xcorpio/spring-security,izeye/spring-security,eddumelendez/spring-security,zhaoqin102/spring-security,jgrandja/spring-security,pwheel/spring-security,dsyer/spring-security,Krasnyanskiy/spring-security,Krasnyanskiy/spring-security,yinhe402/spring-security,likaiwalkman/spring-security,mrkingybc/spring-security,liuguohua/spring-security,zgscwjm/spring-security,zshift/spring-security,pkdevbox/spring-security,Xcorpio/spring-security,pwheel/spring-security,mrkingybc/spring-security,jmnarloch/spring-security,jgrandja/spring-security,dsyer/spring-security,kazuki43zoo/spring-security,MatthiasWinzeler/spring-security,Krasnyanskiy/spring-security,Peter32/spring-security,spring-projects/spring-security,xingguang2013/spring-security,mounb/spring-security,zhaoqin102/spring-security,follow99/spring-security,thomasdarimont/spring-security,adairtaosy/spring-security,izeye/spring-security,kazuki43zoo/spring-security,forestqqqq/spring-security,spring-projects/spring-security,dsyer/spring-security,cyratech/spring-security,yinhe402/spring-security,wilkinsona/spring-security,mdeinum/spring-security,rwinch/spring-security,thomasdarimont/spring-security,driftman/spring-security,wkorando/spring-security,chinazhaoht/spring-security,olezhuravlev/spring-security,kazuki43zoo/spring-security,fhanik/spring-security,liuguohua/spring-security,mdeinum/spring-security,raindev/spring-security,tekul/spring-security,liuguohua/spring-security,pwheel/spring-security,SanjayUser/SpringSecurityPro,vitorgv/spring-security,mounb/spring-security,chinazhaoht/spring-security,mparaz/spring-security,tekul/spring-security,fhanik/spring-security,fhanik/spring-security,olezhuravlev/spring-security,eddumelendez/spring-security,forestqqqq/spring-security,caiwenshu/spring-security,mdeinum/spring-security,SanjayUser/SpringSecurityPro,follow99/spring-security,SanjayUser/SpringSecurityPro,Peter32/spring-security,fhanik/spring-security,hippostar/spring-security,diegofernandes/spring-security,kazuki43zoo/spring-security,spring-projects/spring-security,izeye/spring-security,MatthiasWinzeler/spring-security,caiwenshu/spring-security,spring-projects/spring-security,jmnarloch/spring-security,djechelon/spring-security,justinedelson/spring-security,tekul/spring-security,diegofernandes/spring-security,ajdinhedzic/spring-security,zshift/spring-security,thomasdarimont/spring-security,panchenko/spring-security,rwinch/spring-security,MatthiasWinzeler/spring-security,ollie314/spring-security,fhanik/spring-security,fhanik/spring-security,likaiwalkman/spring-security,follow99/spring-security,ajdinhedzic/spring-security,panchenko/spring-security,rwinch/spring-security,jmnarloch/spring-security,xingguang2013/spring-security,ractive/spring-security,ractive/spring-security,caiwenshu/spring-security,mparaz/spring-security,chinazhaoht/spring-security,olezhuravlev/spring-security,zshift/spring-security,mparaz/spring-security,driftman/spring-security,eddumelendez/spring-security,kazuki43zoo/spring-security,ollie314/spring-security,rwinch/spring-security,xingguang2013/spring-security,raindev/spring-security,cyratech/spring-security,mparaz/spring-security,driftman/spring-security,SanjayUser/SpringSecurityPro,adairtaosy/spring-security,forestqqqq/spring-security,zgscwjm/spring-security,olezhuravlev/spring-security,zgscwjm/spring-security,ollie314/spring-security,zhaoqin102/spring-security,rwinch/spring-security,cyratech/spring-security,panchenko/spring-security,zhaoqin102/spring-security,Peter32/spring-security,justinedelson/spring-security,justinedelson/spring-security,wkorando/spring-security,caiwenshu/spring-security,djechelon/spring-security,thomasdarimont/spring-security,ajdinhedzic/spring-security,Xcorpio/spring-security,spring-projects/spring-security,rwinch/spring-security,eddumelendez/spring-security,wilkinsona/spring-security,diegofernandes/spring-security,zgscwjm/spring-security,wilkinsona/spring-security,Xcorpio/spring-security,vitorgv/spring-security,olezhuravlev/spring-security,pwheel/spring-security,MatthiasWinzeler/spring-security,mounb/spring-security,mounb/spring-security,mrkingybc/spring-security,chinazhaoht/spring-security,hippostar/spring-security,wilkinsona/spring-security,hippostar/spring-security,izeye/spring-security,raindev/spring-security,xingguang2013/spring-security,driftman/spring-security,liuguohua/spring-security,ollie314/spring-security,jgrandja/spring-security,likaiwalkman/spring-security,vitorgv/spring-security,pkdevbox/spring-security,mrkingybc/spring-security,dsyer/spring-security,raindev/spring-security,jmnarloch/spring-security,adairtaosy/spring-security,eddumelendez/spring-security,hippostar/spring-security,Krasnyanskiy/spring-security,ajdinhedzic/spring-security,tekul/spring-security,ractive/spring-security,spring-projects/spring-security,pkdevbox/spring-security,wkorando/spring-security,yinhe402/spring-security,jgrandja/spring-security,Peter32/spring-security,djechelon/spring-security,dsyer/spring-security,jgrandja/spring-security,vitorgv/spring-security,justinedelson/spring-security,forestqqqq/spring-security,ractive/spring-security,pkdevbox/spring-security,diegofernandes/spring-security,likaiwalkman/spring-security,cyratech/spring-security,follow99/spring-security,jgrandja/spring-security,djechelon/spring-security,yinhe402/spring-security,thomasdarimont/spring-security,spring-projects/spring-security,adairtaosy/spring-security,pwheel/spring-security,panchenko/spring-security,mdeinum/spring-security,wkorando/spring-security,SanjayUser/SpringSecurityPro,zshift/spring-security,djechelon/spring-security
/* Copyright 2004 Acegi Technology Pty Limited * * 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 net.sf.acegisecurity.providers.dao.memory; import net.sf.acegisecurity.GrantedAuthority; import net.sf.acegisecurity.GrantedAuthorityImpl; import java.util.List; import java.util.Vector; /** * Used by {@link InMemoryDaoImpl} to temporarily store the attributes * associated with a user. * * @author Ben Alex * @version $Id$ */ public class UserAttributeDefinition { //~ Instance fields ======================================================== private List authorities = new Vector(); private String password; private boolean enabled = true; //~ Constructors =========================================================== public UserAttributeDefinition() { super(); } //~ Methods ================================================================ public GrantedAuthority[] getAuthorities() { GrantedAuthority[] toReturn = {new GrantedAuthorityImpl("demo")}; return (GrantedAuthority[]) this.authorities.toArray(toReturn); } public void setEnabled(boolean enabled) { this.enabled = enabled; } public boolean isEnabled() { return enabled; } public void setPassword(String password) { this.password = password; } public String getPassword() { return password; } public boolean isValid() { if ((this.password != null) && (authorities.size() > 0)) { return true; } else { return false; } } public void addAuthority(GrantedAuthority newAuthority) { this.authorities.add(newAuthority); } }
core/src/main/java/org/acegisecurity/userdetails/memory/UserAttributeDefinition.java
/* Copyright 2004 Acegi Technology Pty Limited * * 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 net.sf.acegisecurity.providers.dao.memory; import net.sf.acegisecurity.GrantedAuthority; import net.sf.acegisecurity.GrantedAuthorityImpl; import java.util.HashSet; import java.util.Set; /** * Used by {@link InMemoryDaoImpl} to temporarily store the attributes * associated with a user. * * @author Ben Alex * @version $Id$ */ public class UserAttributeDefinition { //~ Instance fields ======================================================== private Set authorities = new HashSet(); private String password; private boolean enabled = true; //~ Constructors =========================================================== public UserAttributeDefinition() { super(); } //~ Methods ================================================================ public GrantedAuthority[] getAuthorities() { GrantedAuthority[] toReturn = {new GrantedAuthorityImpl("demo")}; return (GrantedAuthority[]) this.authorities.toArray(toReturn); } public void setEnabled(boolean enabled) { this.enabled = enabled; } public boolean isEnabled() { return enabled; } public void setPassword(String password) { this.password = password; } public String getPassword() { return password; } public boolean isValid() { if ((this.password != null) && (authorities.size() > 0)) { return true; } else { return false; } } public void addAuthority(GrantedAuthority newAuthority) { this.authorities.add(newAuthority); } }
Changed internals to use list instead of set, to preserve element ordering.
core/src/main/java/org/acegisecurity/userdetails/memory/UserAttributeDefinition.java
Changed internals to use list instead of set, to preserve element ordering.
<ide><path>ore/src/main/java/org/acegisecurity/userdetails/memory/UserAttributeDefinition.java <ide> import net.sf.acegisecurity.GrantedAuthority; <ide> import net.sf.acegisecurity.GrantedAuthorityImpl; <ide> <del>import java.util.HashSet; <del>import java.util.Set; <add>import java.util.List; <add>import java.util.Vector; <ide> <ide> <ide> /** <ide> public class UserAttributeDefinition { <ide> //~ Instance fields ======================================================== <ide> <del> private Set authorities = new HashSet(); <add> private List authorities = new Vector(); <ide> private String password; <ide> private boolean enabled = true; <ide>
Java
bsd-3-clause
48b815bace39ea1b1d2ca4fefc1d3d183275ca2a
0
chocoteam/choco3,chocoteam/choco3,chocoteam/choco3,chocoteam/choco3
/** * Copyright (c) 2015, Ecole des Mines de Nantes * 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. All advertising materials mentioning features or use of this software * must display the following acknowledgement: * This product includes software developed by the <organization>. * 4. Neither the name of the <organization> 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 <COPYRIGHT HOLDER> ''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> 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 org.chocosolver.solver.search.strategy; import org.chocosolver.solver.ResolutionPolicy; import org.chocosolver.solver.search.strategy.assignments.DecisionOperator; import org.chocosolver.solver.search.strategy.selectors.IntValueSelector; import org.chocosolver.solver.search.strategy.selectors.RealValueSelector; import org.chocosolver.solver.search.strategy.selectors.SetValueSelector; import org.chocosolver.solver.search.strategy.selectors.VariableSelector; import org.chocosolver.solver.search.strategy.selectors.variables.ActivityBased; import org.chocosolver.solver.search.strategy.selectors.variables.DomOverWDeg; import org.chocosolver.solver.search.strategy.strategy.*; import org.chocosolver.solver.variables.IntVar; import org.chocosolver.solver.variables.RealVar; import org.chocosolver.solver.variables.SetVar; import static org.chocosolver.solver.search.strategy.selectors.ValSelectorFactory.*; import static org.chocosolver.solver.search.strategy.selectors.VarSelectorFactory.*; public class SearchStrategyFactory { // ************************************************************************************ // GENERIC PATTERNS // ************************************************************************************ /** * Use the last conflict heuristic as a pluggin to improve a former search heuristic * Should be set after specifying a search strategy. * @return last conflict strategy */ public static AbstractStrategy lastConflict(AbstractStrategy formerSearch) { return new LastConflict(formerSearch.getVariables()[0].getModel(), formerSearch,1); } /** * Make the input search strategy greedy, that is, decisions can be applied but not refuted. * @param search a search heuristic building branching decisions * @return a greedy form of search */ public static AbstractStrategy greedySearch(AbstractStrategy search){ return new GreedyBranching(search); } public static AbstractStrategy sequencer(AbstractStrategy... searches){ return new StrategiesSequencer(searches); } // ************************************************************************************ // SETVAR STRATEGIES // ************************************************************************************ /** * Generic strategy to branch on set variables * * @param varS variable selection strategy * @param valS integer selection strategy * @param enforceFirst branching order true = enforce first; false = remove first * @param sets SetVar array to branch on * @return a strategy to instantiate sets */ public static SetStrategy setVarSearch(VariableSelector<SetVar> varS, SetValueSelector valS, boolean enforceFirst, SetVar... sets) { return new SetStrategy(sets, varS, valS, enforceFirst); } /** * strategy to branch on sets by choosing the first unfixed variable and forcing its first unfixed value * * @param sets variables to branch on * @return a strategy to instantiate sets */ public static SetStrategy setVarSearch(SetVar... sets) { return setVarSearch(minDomVar(), firstSetVal(), true, sets); } // ************************************************************************************ // REALVAR STRATEGIES // ************************************************************************************ /** * Generic strategy to branch on real variables, based on domain splitting * @param varS variable selection strategy * @param valS strategy to select where to split domains * @param rvars RealVar array to branch on * @return a strategy to instantiate reals */ public static RealStrategy realVarSearch(VariableSelector<RealVar> varS, RealValueSelector valS, RealVar... rvars) { return new RealStrategy(rvars, varS, valS); } /** * strategy to branch on real variables by choosing sequentially the next variable domain * to split in two, wrt the middle value * @param reals variables to branch on * @return a strategy to instantiate real variables */ public static RealStrategy realVarSearch(RealVar... reals) { return realVarSearch(roundRobinVar(), midRealVal(), reals); } // ************************************************************************************ // INTVAR STRATEGIES // ************************************************************************************ /** * Builds your own search strategy based on <b>binary</b> decisions. * * @param varSelector defines how to select a variable to branch on. * @param valSelector defines how to select a value in the domain of the selected variable * @param decisionOperator defines how to modify the domain of the selected variable with the selected value * @param vars variables to branch on * @return a custom search strategy */ public static IntStrategy intVarSearch(VariableSelector<IntVar> varSelector, IntValueSelector valSelector, DecisionOperator<IntVar> decisionOperator, IntVar... vars) { return new IntStrategy(vars, varSelector, valSelector, decisionOperator); } /** * Builds your own assignment strategy based on <b>binary</b> decisions. * Selects a variable X and a value V to make the decision X = V. * Note that value assignments are the public static decision operators. * Therefore, they are not mentioned in the search heuristic name. * @param varSelector defines how to select a variable to branch on. * @param valSelector defines how to select a value in the domain of the selected variable * @param vars variables to branch on * @return a custom search strategy */ public static IntStrategy intVarSearch(VariableSelector<IntVar> varSelector, IntValueSelector valSelector, IntVar... vars) { return intVarSearch(varSelector, valSelector, DecisionOperator.int_eq, vars); } /** * Builds a default search heuristics of integer variables * Relies on {@link #domOverWDegSearch(IntVar...)} * @param vars variables to branch on * @return a default search strategy */ public static AbstractStrategy<IntVar> intVarSearch(IntVar... vars) { boolean satOrMin = vars[0].getModel().getResolutionPolicy()!= ResolutionPolicy.MAXIMIZE; return new DomOverWDeg(vars, 0, satOrMin?minIntVal():maxIntVal()); } /** * Assignment strategy which selects a variable according to <code>DomOverWDeg</code> and assign it to its lower bound * @param vars list of variables * @return assignment strategy */ public static AbstractStrategy<IntVar> domOverWDegSearch(IntVar... vars) { return new DomOverWDeg(vars, 0, minIntVal()); } /** * Create an Activity based search strategy. * <p> * <b>"Activity-Based Search for Black-Box Constraint Propagramming Solver"<b/>, * Laurent Michel and Pascal Van Hentenryck, CPAIOR12. * <br/> * Uses public static parameters (GAMMA=0.999d, DELTA=0.2d, ALPHA=8, RESTART=1.1d, FORCE_SAMPLING=1) * * @param vars collection of variables * @return an Activity based search strategy. */ public static AbstractStrategy<IntVar> activityBasedSearch(IntVar... vars) { return new ActivityBased(vars); } /** * Randomly selects a variable and assigns it to a value randomly taken in * - the domain in case the variable has an enumerated domain * - {LB,UB} (one of the two bounds) in case the domain is bounded * * @param vars list of variables * @param seed a seed for random * @return assignment strategy */ public static IntStrategy randomSearch(IntVar[] vars, long seed) { IntValueSelector value = randomIntVal(seed); IntValueSelector bound = randomIntBound(seed); IntValueSelector selector = (IntValueSelector) var -> { if (var.hasEnumeratedDomain()) { return value.selectValue(var); } else { return bound.selectValue(var); } }; return intVarSearch(randomVar(seed), selector, vars); } // ************************************************************************************ // SOME EXAMPLES OF STRATEGIES YOU CAN BUILD // ************************************************************************************ /** * Assigns the first non-instantiated variable to its lower bound. * @param vars list of variables * @return int strategy based on value assignments */ public static IntStrategy inputOrderLBSearch(IntVar... vars) { return intVarSearch(inputOrderVar(), minIntVal(), vars); } /** * Assigns the first non-instantiated variable to its upper bound. * @param vars list of variables * @return assignment strategy */ public static IntStrategy inputOrderUBSearch(IntVar... vars) { return intVarSearch(inputOrderVar(), maxIntVal(), vars); } /** * Assigns the non-instantiated variable of smallest domain size to its lower bound. * @param vars list of variables * @return assignment strategy */ public static IntStrategy minDomLBSearch(IntVar... vars) { return intVarSearch(minDomIntVar(), minIntVal(), vars); } /** * Assigns the non-instantiated variable of smallest domain size to its upper bound. * @param vars list of variables * @return assignment strategy */ public static IntStrategy minDomUBSearch(IntVar... vars) { return intVarSearch(minDomIntVar(), maxIntVal(), vars); } }
src/main/java/org/chocosolver/solver/search/strategy/SearchStrategyFactory.java
/** * Copyright (c) 2015, Ecole des Mines de Nantes * 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. All advertising materials mentioning features or use of this software * must display the following acknowledgement: * This product includes software developed by the <organization>. * 4. Neither the name of the <organization> 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 <COPYRIGHT HOLDER> ''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> 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 org.chocosolver.solver.search.strategy; import org.chocosolver.solver.search.strategy.assignments.DecisionOperator; import org.chocosolver.solver.search.strategy.selectors.IntValueSelector; import org.chocosolver.solver.search.strategy.selectors.RealValueSelector; import org.chocosolver.solver.search.strategy.selectors.SetValueSelector; import org.chocosolver.solver.search.strategy.selectors.VariableSelector; import org.chocosolver.solver.search.strategy.selectors.variables.ActivityBased; import org.chocosolver.solver.search.strategy.selectors.variables.DomOverWDeg; import org.chocosolver.solver.search.strategy.strategy.*; import org.chocosolver.solver.variables.IntVar; import org.chocosolver.solver.variables.RealVar; import org.chocosolver.solver.variables.SetVar; import static org.chocosolver.solver.search.strategy.selectors.ValSelectorFactory.*; import static org.chocosolver.solver.search.strategy.selectors.VarSelectorFactory.*; public class SearchStrategyFactory { // ************************************************************************************ // GENERIC PATTERNS // ************************************************************************************ /** * Use the last conflict heuristic as a pluggin to improve a former search heuristic * Should be set after specifying a search strategy. * @return last conflict strategy */ public static AbstractStrategy lastConflict(AbstractStrategy formerSearch) { return new LastConflict(formerSearch.getVariables()[0].getModel(), formerSearch,1); } /** * Make the input search strategy greedy, that is, decisions can be applied but not refuted. * @param search a search heuristic building branching decisions * @return a greedy form of search */ public static AbstractStrategy greedySearch(AbstractStrategy search){ return new GreedyBranching(search); } public static AbstractStrategy sequencer(AbstractStrategy... searches){ return new StrategiesSequencer(searches); } // ************************************************************************************ // SETVAR STRATEGIES // ************************************************************************************ /** * Generic strategy to branch on set variables * * @param varS variable selection strategy * @param valS integer selection strategy * @param enforceFirst branching order true = enforce first; false = remove first * @param sets SetVar array to branch on * @return a strategy to instantiate sets */ public static SetStrategy setVarSearch(VariableSelector<SetVar> varS, SetValueSelector valS, boolean enforceFirst, SetVar... sets) { return new SetStrategy(sets, varS, valS, enforceFirst); } /** * strategy to branch on sets by choosing the first unfixed variable and forcing its first unfixed value * * @param sets variables to branch on * @return a strategy to instantiate sets */ public static SetStrategy setVarSearch(SetVar... sets) { return setVarSearch(minDomVar(), firstSetVal(), true, sets); } // ************************************************************************************ // REALVAR STRATEGIES // ************************************************************************************ /** * Generic strategy to branch on real variables, based on domain splitting * @param varS variable selection strategy * @param valS strategy to select where to split domains * @param rvars RealVar array to branch on * @return a strategy to instantiate reals */ public static RealStrategy realVarSearch(VariableSelector<RealVar> varS, RealValueSelector valS, RealVar... rvars) { return new RealStrategy(rvars, varS, valS); } /** * strategy to branch on real variables by choosing sequentially the next variable domain * to split in two, wrt the middle value * @param reals variables to branch on * @return a strategy to instantiate real variables */ public static RealStrategy realVarSearch(RealVar... reals) { return realVarSearch(roundRobinVar(), midRealVal(), reals); } // ************************************************************************************ // INTVAR STRATEGIES // ************************************************************************************ /** * Builds your own search strategy based on <b>binary</b> decisions. * * @param varSelector defines how to select a variable to branch on. * @param valSelector defines how to select a value in the domain of the selected variable * @param decisionOperator defines how to modify the domain of the selected variable with the selected value * @param vars variables to branch on * @return a custom search strategy */ public static IntStrategy intVarSearch(VariableSelector<IntVar> varSelector, IntValueSelector valSelector, DecisionOperator<IntVar> decisionOperator, IntVar... vars) { return new IntStrategy(vars, varSelector, valSelector, decisionOperator); } /** * Builds your own assignment strategy based on <b>binary</b> decisions. * Selects a variable X and a value V to make the decision X = V. * Note that value assignments are the public static decision operators. * Therefore, they are not mentioned in the search heuristic name. * @param varSelector defines how to select a variable to branch on. * @param valSelector defines how to select a value in the domain of the selected variable * @param vars variables to branch on * @return a custom search strategy */ public static IntStrategy intVarSearch(VariableSelector<IntVar> varSelector, IntValueSelector valSelector, IntVar... vars) { return intVarSearch(varSelector, valSelector, DecisionOperator.int_eq, vars); } /** * Builds a default search heuristics of integer variables * Relies on {@link #domOverWDegSearch(IntVar...)} * @param vars variables to branch on * @return a default search strategy */ public static AbstractStrategy<IntVar> intVarSearch(IntVar... vars) { return domOverWDegSearch(vars); } /** * Assignment strategy which selects a variable according to <code>DomOverWDeg</code> and assign it to its lower bound * @param vars list of variables * @return assignment strategy */ public static AbstractStrategy<IntVar> domOverWDegSearch(IntVar... vars) { return new DomOverWDeg(vars, 0, minIntVal()); } /** * Create an Activity based search strategy. * <p> * <b>"Activity-Based Search for Black-Box Constraint Propagramming Solver"<b/>, * Laurent Michel and Pascal Van Hentenryck, CPAIOR12. * <br/> * Uses public static parameters (GAMMA=0.999d, DELTA=0.2d, ALPHA=8, RESTART=1.1d, FORCE_SAMPLING=1) * * @param vars collection of variables * @return an Activity based search strategy. */ public static AbstractStrategy<IntVar> activityBasedSearch(IntVar... vars) { return new ActivityBased(vars); } /** * Randomly selects a variable and assigns it to a value randomly taken in * - the domain in case the variable has an enumerated domain * - {LB,UB} (one of the two bounds) in case the domain is bounded * * @param vars list of variables * @param seed a seed for random * @return assignment strategy */ public static IntStrategy randomSearch(IntVar[] vars, long seed) { IntValueSelector value = randomIntVal(seed); IntValueSelector bound = randomIntBound(seed); IntValueSelector selector = (IntValueSelector) var -> { if (var.hasEnumeratedDomain()) { return value.selectValue(var); } else { return bound.selectValue(var); } }; return intVarSearch(randomVar(seed), selector, vars); } // ************************************************************************************ // SOME EXAMPLES OF STRATEGIES YOU CAN BUILD // ************************************************************************************ /** * Assigns the first non-instantiated variable to its lower bound. * @param vars list of variables * @return int strategy based on value assignments */ public static IntStrategy inputOrderLBSearch(IntVar... vars) { return intVarSearch(inputOrderVar(), minIntVal(), vars); } /** * Assigns the first non-instantiated variable to its upper bound. * @param vars list of variables * @return assignment strategy */ public static IntStrategy inputOrderUBSearch(IntVar... vars) { return intVarSearch(inputOrderVar(), maxIntVal(), vars); } /** * Assigns the non-instantiated variable of smallest domain size to its lower bound. * @param vars list of variables * @return assignment strategy */ public static IntStrategy minDomLBSearch(IntVar... vars) { return intVarSearch(minDomIntVar(), minIntVal(), vars); } /** * Assigns the non-instantiated variable of smallest domain size to its upper bound. * @param vars list of variables * @return assignment strategy */ public static IntStrategy minDomUBSearch(IntVar... vars) { return intVarSearch(minDomIntVar(), maxIntVal(), vars); } }
better default search
src/main/java/org/chocosolver/solver/search/strategy/SearchStrategyFactory.java
better default search
<ide><path>rc/main/java/org/chocosolver/solver/search/strategy/SearchStrategyFactory.java <ide> */ <ide> package org.chocosolver.solver.search.strategy; <ide> <add>import org.chocosolver.solver.ResolutionPolicy; <ide> import org.chocosolver.solver.search.strategy.assignments.DecisionOperator; <ide> import org.chocosolver.solver.search.strategy.selectors.IntValueSelector; <ide> import org.chocosolver.solver.search.strategy.selectors.RealValueSelector; <ide> * @return a default search strategy <ide> */ <ide> public static AbstractStrategy<IntVar> intVarSearch(IntVar... vars) { <del> return domOverWDegSearch(vars); <add> boolean satOrMin = vars[0].getModel().getResolutionPolicy()!= ResolutionPolicy.MAXIMIZE; <add> return new DomOverWDeg(vars, 0, satOrMin?minIntVal():maxIntVal()); <ide> } <ide> <ide> /**
Java
apache-2.0
3dafa45a1adf079e288150ba890e029a673aa6a2
0
vespa-engine/vespa,vespa-engine/vespa,vespa-engine/vespa,vespa-engine/vespa,vespa-engine/vespa,vespa-engine/vespa,vespa-engine/vespa,vespa-engine/vespa,vespa-engine/vespa,vespa-engine/vespa
config-model/src/main/java/com/yahoo/vespa/model/container/component/HttpFilter.java
// Copyright Yahoo. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root. package com.yahoo.vespa.model.container.component; import com.yahoo.component.ComponentId; import com.yahoo.component.ComponentSpecification; import com.yahoo.container.FilterConfigProvider; import com.yahoo.container.bundle.BundleInstantiationSpecification; import com.yahoo.osgi.provider.model.ComponentModel; /** * This is only for the legacy certificate filter setup, outside http. * * TODO: Remove when 'filter' directly under 'container' can be removed from services.xml * * @author Tony Vaagenes */ public class HttpFilter extends SimpleComponent { private static final ComponentSpecification filterConfigProviderClass = ComponentSpecification.fromString(FilterConfigProvider.class.getName()); public final SimpleComponent filterConfigProvider; public HttpFilter(BundleInstantiationSpecification spec) { super(new ComponentModel(spec)); filterConfigProvider = new SimpleComponent(new ComponentModel( new BundleInstantiationSpecification(configProviderId(spec.id), filterConfigProviderClass, null))); addChild(filterConfigProvider); } // public for testing public static ComponentId configProviderId(ComponentId filterId) { return ComponentId.fromString("filterConfig").nestInNamespace(filterId); } }
Remove unused class
config-model/src/main/java/com/yahoo/vespa/model/container/component/HttpFilter.java
Remove unused class
<ide><path>onfig-model/src/main/java/com/yahoo/vespa/model/container/component/HttpFilter.java <del>// Copyright Yahoo. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root. <del>package com.yahoo.vespa.model.container.component; <del> <del>import com.yahoo.component.ComponentId; <del>import com.yahoo.component.ComponentSpecification; <del>import com.yahoo.container.FilterConfigProvider; <del>import com.yahoo.container.bundle.BundleInstantiationSpecification; <del>import com.yahoo.osgi.provider.model.ComponentModel; <del> <del>/** <del> * This is only for the legacy certificate filter setup, outside http. <del> * <del> * TODO: Remove when 'filter' directly under 'container' can be removed from services.xml <del> * <del> * @author Tony Vaagenes <del> */ <del>public class HttpFilter extends SimpleComponent { <del> private static final ComponentSpecification filterConfigProviderClass = <del> ComponentSpecification.fromString(FilterConfigProvider.class.getName()); <del> <del> public final SimpleComponent filterConfigProvider; <del> <del> public HttpFilter(BundleInstantiationSpecification spec) { <del> super(new ComponentModel(spec)); <del> <del> filterConfigProvider = new SimpleComponent(new ComponentModel( <del> new BundleInstantiationSpecification(configProviderId(spec.id), filterConfigProviderClass, null))); <del> <del> addChild(filterConfigProvider); <del> } <del> <del> // public for testing <del> public static ComponentId configProviderId(ComponentId filterId) { <del> return ComponentId.fromString("filterConfig").nestInNamespace(filterId); <del> } <del>}
Java
lgpl-2.1
6834cfa701752c9797d512ac576100ef53be6383
0
Arabidopsis-Information-Portal/intermine,JoeCarlson/intermine,elsiklab/intermine,kimrutherford/intermine,joshkh/intermine,JoeCarlson/intermine,drhee/toxoMine,JoeCarlson/intermine,tomck/intermine,Arabidopsis-Information-Portal/intermine,JoeCarlson/intermine,joshkh/intermine,tomck/intermine,justincc/intermine,drhee/toxoMine,joshkh/intermine,zebrafishmine/intermine,Arabidopsis-Information-Portal/intermine,JoeCarlson/intermine,kimrutherford/intermine,justincc/intermine,Arabidopsis-Information-Portal/intermine,zebrafishmine/intermine,elsiklab/intermine,drhee/toxoMine,justincc/intermine,tomck/intermine,drhee/toxoMine,tomck/intermine,justincc/intermine,zebrafishmine/intermine,justincc/intermine,drhee/toxoMine,zebrafishmine/intermine,tomck/intermine,JoeCarlson/intermine,Arabidopsis-Information-Portal/intermine,zebrafishmine/intermine,JoeCarlson/intermine,JoeCarlson/intermine,kimrutherford/intermine,joshkh/intermine,zebrafishmine/intermine,tomck/intermine,elsiklab/intermine,elsiklab/intermine,joshkh/intermine,drhee/toxoMine,Arabidopsis-Information-Portal/intermine,elsiklab/intermine,Arabidopsis-Information-Portal/intermine,kimrutherford/intermine,elsiklab/intermine,drhee/toxoMine,kimrutherford/intermine,drhee/toxoMine,zebrafishmine/intermine,JoeCarlson/intermine,joshkh/intermine,elsiklab/intermine,elsiklab/intermine,tomck/intermine,justincc/intermine,zebrafishmine/intermine,joshkh/intermine,justincc/intermine,tomck/intermine,Arabidopsis-Information-Portal/intermine,Arabidopsis-Information-Portal/intermine,kimrutherford/intermine,joshkh/intermine,elsiklab/intermine,kimrutherford/intermine,kimrutherford/intermine,kimrutherford/intermine,justincc/intermine,zebrafishmine/intermine,joshkh/intermine,tomck/intermine,drhee/toxoMine,justincc/intermine
package org.intermine.bio.dataconversion; /* * Copyright (C) 2002-2010 FlyMine * * This code may be freely distributed and modified under the * terms of the GNU Lesser General Public Licence. This should * be distributed with the code. See the LICENSE file for more * information or http://www.gnu.org/copyleft/lesser.html. * */ import java.sql.Connection; import java.sql.ResultSet; import java.sql.SQLException; import java.sql.Statement; import java.util.ArrayList; import java.util.Arrays; import java.util.HashMap; import java.util.HashSet; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.Set; import org.apache.commons.collections.keyvalue.MultiKey; import org.apache.commons.collections.map.MultiKeyMap; import org.apache.log4j.Logger; import org.intermine.bio.chado.config.ConfigAction; import org.intermine.bio.chado.config.SetFieldConfigAction; import org.intermine.bio.util.OrganismData; import org.intermine.objectstore.ObjectStoreException; import org.intermine.util.StringUtil; import org.intermine.util.TypeUtil; import org.intermine.xml.full.Attribute; import org.intermine.xml.full.Item; /** * A processor that loads feature referred to by the modENCODE metadata. This class is designed * to be used by ModEncodeMetaDataProcessor and will be called once for each submission that has * metadata. * @author Kim Rutherford */ public class ModEncodeFeatureProcessor extends SequenceProcessor { private static final Logger LOG = Logger.getLogger(ModEncodeFeatureProcessor.class); private final String dataSetIdentifier; private final String dataSourceIdentifier; private final List<Integer> dataList; private final String title; private Set<String> commonFeatureInterMineTypes = new HashSet<String>(); private static final String SUBFEATUREID_TEMP_TABLE_NAME = "modmine_subfeatureid_temp"; // feature type to query from the feature table private static final List<String> FEATURES = Arrays.asList( "gene", "mRNA", "transcript", "CDS", "intron", "exon", "EST", "five_prime_untranslated_region", "five_prime_UTR", "three_prime_untranslated_region", "three_prime_UTR", "origin_of_replication", "binding_site", "protein_binding_site", "TF_binding_site", "transcript_region", "histone_binding_site", "copy_number_variation", "natural_transposable_element", "start_codon", "stop_codon" , "cDNA" , "three_prime_RACE_clone", "three_prime_RST", "three_prime_UST" , "polyA_site", "overlapping_EST_set", "exon_region" , "experimental_feature", "SL1_acceptor_site", "SL2_acceptor_site" , "transcription_end_site", "TSS" ); // the FB name for the mitochondrial genome private static final String MITOCHONDRION = "dmel_mitochondrion_genome"; // ... private static final String CHROMOSOME = "Chromosome"; // the configuration for this processor, set when getConfig() is called the first time private final Map<Integer, MultiKeyMap> config = new HashMap<Integer, MultiKeyMap>(); private Map<Integer, FeatureData> commonFeaturesMap = new HashMap<Integer, FeatureData>(); /** * Create a new ModEncodeFeatureProcessor. * @param chadoDBConverter the parent converter * @param dataSetIdentifier the item identifier of the DataSet, * i.e. the submissionItemIdentifier * @param dataSourceIdentifier the item identifier of the DataSource, * i.e. the labItemIdentifier * @param dataList the list of data ids to be used in the subquery * @param title the title */ public ModEncodeFeatureProcessor(ChadoDBConverter chadoDBConverter, String dataSetIdentifier, String dataSourceIdentifier, List <Integer> dataList, String title) { super(chadoDBConverter); this.dataSetIdentifier = dataSetIdentifier; this.dataSourceIdentifier = dataSourceIdentifier; this.dataList = dataList; this.title = title; for (String chromosomeType : getChromosomeFeatureTypes()) { commonFeatureInterMineTypes.add( TypeUtil.javaiseClassName(fixFeatureType(chromosomeType))); } commonFeatureInterMineTypes.add("Gene"); commonFeatureInterMineTypes.add("MRNA"); commonFeatureInterMineTypes.add("CDNA"); commonFeatureInterMineTypes.add("EST"); commonFeatureInterMineTypes.add("CDS"); } /** * Get a list of the chado/so types of the LocatedSequenceFeatures we wish to load. The list * will not include chromosome-like features. * @return the list of features */ @Override protected List<String> getFeatures() { return FEATURES; } /** * Get a map of features that are expected to be common between submissions. This map can be * used to initialise this processor for a subsequent run. The feature types added to this map * are governed by the addToFeatureMap method in this class. * @return a map of chado feature id to FeatureData objects */ protected Map<Integer, FeatureData> getCommonFeaturesMap() { return commonFeaturesMap; } /** * Initialise SequenceProcessor with features that have already been processed and put the same * features data into a commonFeaturesMap that tracks features (e.g. Chromosomes) that appear * in multiple submissions but should only be processed once. * @param initialMap map of chado feature id to FeatureData objects */ protected void initialiseCommonFeatures(Map<Integer, FeatureData> initialMap) { super.initialiseFeatureMap(initialMap); commonFeaturesMap.putAll(initialMap); } /** * {@inheritDoc} */ @Override protected String getExtraFeatureConstraint() { /* * tried also other queries (using union, without join), this seems better */ return "(cvterm.name = 'chromosome' OR cvterm.name = 'chromosome_arm') AND " + " feature_id IN ( SELECT featureloc.srcfeature_id " + " FROM featureloc, " + SUBFEATUREID_TEMP_TABLE_NAME + " WHERE featureloc.feature_id = " + SUBFEATUREID_TEMP_TABLE_NAME + ".feature_id) " + " OR feature_id IN ( SELECT feature_id " + " FROM " + SUBFEATUREID_TEMP_TABLE_NAME + " ) "; /* return "(cvterm.name = 'chromosome' OR cvterm.name = 'chromosome_arm') AND " + " feature_id IN ( SELECT featureloc.srcfeature_id " + " FROM featureloc " + " WHERE featureloc.feature_id IN ( SELECT feature_id " + " FROM " + SUBFEATUREID_TEMP_TABLE_NAME + " )) " + " OR feature_id IN ( SELECT feature_id " + " FROM " + SUBFEATUREID_TEMP_TABLE_NAME + " ) "; */ } /** * {@inheritDoc} */ @Override protected void extraProcessing(Connection connection, Map<Integer, FeatureData> featureDataMap) throws ObjectStoreException, SQLException { // TODO: check if there is already a method to get all the match types // (and merge the methods) // also: add match to query and do everything here // process indirect locations via match features and featureloc feature<->match<->feature ResultSet matchLocRes = getMatchLocResultSet(connection); processLocationTable(connection, matchLocRes); List<String> types = getMatchTypes(connection); Iterator<String> t = types.iterator(); while (t.hasNext()) { String featType = t.next(); if (featType.equalsIgnoreCase("cDNA_match")) { continue; } ResultSet matchTypeLocRes = getMatchLocResultSet(connection, featType); processLocationTable(connection, matchTypeLocRes); } // adding scores processFeatureScores(connection); } /** * Method to set the source for gene * for modencode datasources it will add the title * @param imObjectId the im object id * @param dataSourceName the data source * @throws ObjectStoreException the exception * */ @Override protected void setGeneSource(Integer imObjectId, String dataSourceName) throws ObjectStoreException { String source = dataSourceName + "-" + title; setAttribute(imObjectId, "source", source); } /** * Override method that adds completed features to featureMap. Also put features that will * appear in multiple submissions in a map made available at the end of processing. * @param featureId the chado feature id * @param fdat feature information */ protected void addToFeatureMap(Integer featureId, FeatureData fdat) { super.addToFeatureMap(featureId, fdat); // We know chromosomes will be common between submissions so add them here if (commonFeatureInterMineTypes.contains(fdat.getInterMineType()) && !commonFeaturesMap.containsKey(featureId)) { commonFeaturesMap.put(featureId, fdat); } } private List<String> getMatchTypes(Connection connection) throws SQLException, ObjectStoreException { List<String> types = new ArrayList<String>(); ResultSet res = getMatchTypesResultSet(connection); while (res.next()) { String type = res.getString("name"); types.add(type.substring(0, type.indexOf('_'))); } res.close(); return types; } /** * Return the match types, used to determine which additional query to run * This is a protected method so that it can be overriden for testing * @param connection the db connection * @return the SQL result set * @throws SQLException if a database problem occurs */ protected ResultSet getMatchTypesResultSet(Connection connection) throws SQLException { String query = "SELECT name from cvterm where name like '%_match' "; LOG.info("executing: " + query); long bT = System.currentTimeMillis(); Statement stmt = connection.createStatement(); ResultSet res = stmt.executeQuery(query); LOG.debug("QUERY TIME feature match types: " + (System.currentTimeMillis() - bT)); return res; } /** * Return the interesting feature (EST, UST, RST, other?) matches * from the featureloc and feature tables. * * feature<->featureloc<->match_feature<->featureloc<->feature * This is a protected method so that it can be overriden for testing * @param connection the db connection * @param featType the type of feature (EST,UST, etc) * @return the SQL result set * @throws SQLException if a database problem occurs */ protected ResultSet getMatchLocResultSet(Connection connection, String featType) throws SQLException { String query = "SELECT -1 AS featureloc_id, feat.feature_id, chrloc.fmin, " + " chrloc.srcfeature_id AS srcfeature_id, chrloc.fmax, FALSE AS is_fmin_partial, " + " featloc.strand " + " FROM feature feat, featureloc featloc, cvterm featcv, feature mf, " + " cvterm mfcv, featureloc chrloc, feature chr, cvterm chrcv " + " WHERE feat.type_id = featcv.cvterm_id " + " AND featcv.name = '" + featType + "' " + " AND feat.feature_id = featloc.srcfeature_id " + " AND featloc.feature_id = mf.feature_id " + " AND mf.feature_id = chrloc.feature_id " + " AND chrloc.srcfeature_id = chr.feature_id " + " AND chr.type_id = chrcv.cvterm_id " + " AND chrcv.name = 'chromosome' " + " AND mf.type_id = mfcv.cvterm_id " + " AND mfcv.name = '" + featType + "_match' " + " AND feat.feature_id IN " + " (select feature_id from " + SUBFEATUREID_TEMP_TABLE_NAME + " ) "; LOG.info("executing: " + query); long bT = System.currentTimeMillis(); Statement stmt = connection.createStatement(); ResultSet res = stmt.executeQuery(query); LOG.info("QUERY TIME feature " + featType + "_match: " + (System.currentTimeMillis() - bT)); return res; } /** * {@inheritDoc} */ @Override protected Integer store(Item feature, int taxonId) throws ObjectStoreException { processItem(feature, taxonId); Integer itemId = super.store(feature, taxonId); return itemId; } /** * {@inheritDoc} */ @Override protected Item makeLocation(int start, int end, int strand, FeatureData srcFeatureData, FeatureData featureData, int taxonId) throws ObjectStoreException { Item location = super.makeLocation(start, end, strand, srcFeatureData, featureData, taxonId); processItem(location, taxonId); return location; } /** * {@inheritDoc} */ @Override protected Item createSynonym(FeatureData fdat, String type, String identifier, boolean isPrimary, List<Item> otherEvidence) throws ObjectStoreException { // Don't create synonyms for main identifiers of modENCODE features. There are too many and // not useful to quick search. if (isPrimary) { return null; } Item synonym = super.createSynonym(fdat, type, identifier, isPrimary, otherEvidence); OrganismData od = fdat.getOrganismData(); processItem(synonym, od.getTaxonId()); return synonym; } /** * Method to add dataSets and DataSources to items before storing */ private void processItem(Item item, Integer taxonId) { if (item.getClassName().equals("DataSource") || item.getClassName().equals("DataSet") || item.getClassName().equals("Organism") || item.getClassName().equals("Sequence")) { return; } if (taxonId == null) { ClassLoader currentClassLoader = Thread.currentThread().getContextClassLoader(); ClassLoader classLoader = getClass().getClassLoader(); Thread.currentThread().setContextClassLoader(classLoader); try { throw new RuntimeException("getCurrentTaxonId() returned null while processing " + item); } finally { Thread.currentThread().setContextClassLoader(currentClassLoader); } } else { DataSetStoreHook.setDataSets(getModel(), item, dataSetIdentifier, dataSourceIdentifier); } } /** * {@inheritDoc} * * see FlyBaseProcessor for many more examples of configuration */ @Override protected Map<MultiKey, List<ConfigAction>> getConfig(int taxonId) { MultiKeyMap map = config.get(new Integer(taxonId)); if (map == null) { map = new MultiKeyMap(); config.put(new Integer(taxonId), map); // TODO: check possible conflicts with our sql matching // map.put(new MultiKey("relationship", "ESTMatch", "evidence_for_feature", "Intron"), // Arrays.asList(new SetFieldConfigAction("intron"))); // for sub 515 map.put(new MultiKey("relationship", "ThreePrimeUTR", "adjacent_to", "CDS"), Arrays.asList(new SetFieldConfigAction("CDS"))); map.put(new MultiKey("relationship", "PolyASite", "derives_from", "ThreePrimeRACEClone"), Arrays.asList(new SetFieldConfigAction("threePrimeRACEClone"))); map.put(new MultiKey("relationship", "ThreePrimeRST", "derives_from", "ThreePrimeRACEClone"), Arrays.asList(new SetFieldConfigAction("threePrimeRACEClone"))); map.put(new MultiKey("relationship", "ThreePrimeUST", "complete_evidence_for_feature", "ThreePrimeUTR"), Arrays.asList(new SetFieldConfigAction("threePrimeUTR"))); // for sub 35 map.put(new MultiKey("relationship", "OverlappingESTSet", "full_evidence_for_feature", "Gene"), Arrays.asList(new SetFieldConfigAction("gene"))); map.put(new MultiKey("relationship", "OverlappingESTSet", "full_evidence_for_feature", "MRNA"), Arrays.asList(new SetFieldConfigAction("mRNA"))); map.put(new MultiKey("relationship", "OverlappingESTSet", "partial_evidence_for_feature", "MRNA"), Arrays.asList(new SetFieldConfigAction("mRNA"))); // 433 map.put(new MultiKey("relationship", "OverlappingESTSet", "full_evidence_for_feature", "Gene"), Arrays.asList(new SetFieldConfigAction("gene"))); map.put(new MultiKey("relationship", "OverlappingESTSet", "complete_evidence_for_feature", "Intron"), Arrays.asList(new SetFieldConfigAction("intron"))); map.put(new MultiKey("relationship", "OverlappingESTSet", "complete_evidence_for_feature", "PolyASite"), Arrays.asList(new SetFieldConfigAction("polyASite"))); map.put(new MultiKey("relationship", "OverlappingESTSet", "complete_evidence_for_feature", "SL1AcceptorSite"), Arrays.asList(new SetFieldConfigAction("SL1AcceptorSite"))); map.put(new MultiKey("relationship", "OverlappingESTSet", "complete_evidence_for_feature", "SL2AcceptorSite"), Arrays.asList(new SetFieldConfigAction("SL2AcceptorSite"))); map.put(new MultiKey("relationship", "OverlappingESTSet", "complete_evidence_for_feature", "TranscriptionEndSite"), Arrays.asList(new SetFieldConfigAction("transcriptionEndSite"))); map.put(new MultiKey("relationship", "OverlappingESTSet", "evidence_for_feature", "TranscriptRegion"), Arrays.asList(new SetFieldConfigAction("transcriptRegion"))); map.put(new MultiKey("relationship", "OverlappingESTSet", "complete_evidence_for_feature", "TSS"), Arrays.asList(new SetFieldConfigAction("TSS"))); map.put(new MultiKey("relationship", "ExperimentalFeature", "evidence_for_feature", "Transcript"), Arrays.asList(new SetFieldConfigAction("transcript"))); map.put(new MultiKey("relationship", "ExperimentalFeature", "evidence_for_feature", "Exon"), Arrays.asList(new SetFieldConfigAction("exon"))); } return map; } /** * copied from FlyBaseProcessor * {@inheritDoc} */ @Override protected Item makeFeature(Integer featureId, String chadoFeatureType, String interMineType, String name, String uniqueName, int seqlen, int taxonId) { String realInterMineType = interMineType; if (chadoFeatureType.equals("chromosome_arm") || chadoFeatureType.equals("ultra_scaffold")) { realInterMineType = "Chromosome"; if (uniqueName.startsWith("chr")) { // this is to fix some data problem with sub 146 in modmine // where there are duplicated chromosome_arm features, with // and without a 'chr' prefix (e.g. 3R and chr3R) // The chr ones are not the location for any other feature. // So we skip them. return null; } } Item feature = getChadoDBConverter().createItem(realInterMineType); return feature; } /** * method to transform dataList (list of integers) * in the string for a IN clause in SQL (comma separated) * @return String */ protected String forINclause() { StringBuffer ql = new StringBuffer(); Iterator<Integer> i = dataList.iterator(); Integer index = 0; while (i.hasNext()) { index++; if (index > 1) { ql = ql.append(", "); } ql = ql.append(i.next()); } return ql.toString(); } /** * Create a temporary table of all feature_ids for a given submission. * @param connection the connection * @throws SQLException if there is a database problem */ protected void createSubFeatureIdTempTable(Connection connection) throws SQLException { String queryList = forINclause(); String query = " CREATE TEMPORARY TABLE " + SUBFEATUREID_TEMP_TABLE_NAME + " AS SELECT data_feature.feature_id " + " FROM data_feature " + " WHERE data_id IN (" + queryList + ")"; Statement stmt = connection.createStatement(); LOG.info("executing: " + query); long bT = System.currentTimeMillis(); stmt.execute(query); LOG.info("TIME feature creating TEMP table: " + (System.currentTimeMillis() - bT)); String idIndexQuery = "CREATE INDEX " + SUBFEATUREID_TEMP_TABLE_NAME + "_feature_index ON " + SUBFEATUREID_TEMP_TABLE_NAME + "(feature_id)"; LOG.info("executing: " + idIndexQuery); long bT1 = System.currentTimeMillis(); stmt.execute(idIndexQuery); LOG.info("TIME feature creating INDEX: " + (System.currentTimeMillis() - bT1)); String analyze = "ANALYZE " + SUBFEATUREID_TEMP_TABLE_NAME; LOG.info("executing: " + analyze); long bT2 = System.currentTimeMillis(); stmt.execute(analyze); LOG.debug("TIME feature analyzing: " + (System.currentTimeMillis() - bT2)); } /** * {@inheritDoc} */ @Override protected void earlyExtraProcessing(Connection connection) throws SQLException { // to limit the process to the current submission createSubFeatureIdTempTable(connection); } /** * {@inheritDoc} */ @Override protected void finishedProcessing(Connection connection, Map<Integer, FeatureData> featureDataMap) throws SQLException { // override in subclasses as necessary String query = " DROP TABLE " + SUBFEATUREID_TEMP_TABLE_NAME; Statement stmt = connection.createStatement(); LOG.info("executing: " + query); stmt.execute(query); } /** * Process the identifier and return a "cleaned" version. Implemented in sub-classes to fix * data problem. * @param type the InterMine type of the feature that this identifier came from * @param identifier the identifier * @return a cleaned identifier */ /** * {@inheritDoc} */ @Override protected String fixIdentifier(FeatureData fdat, String identifier) { String uniqueName = fdat.getChadoFeatureUniqueName(); String name = fdat.getChadoFeatureName(); String type = fdat.getInterMineType(); if (identifier.equalsIgnoreCase(uniqueName)) { if (type.equalsIgnoreCase(CHROMOSOME)) { if (uniqueName.equalsIgnoreCase("M")) { // this is to fix some data problem in modmine // where submissions (e.g. 100) refer to M chromosome instead // of dmel_mitochondrion_genome as in FlyBase uniqueName = MITOCHONDRION; return uniqueName; } } // Piano submissions have Gene: and Transcript: // in front of gene and transcript identifiers if (type.equalsIgnoreCase("Gene")) { if (uniqueName.startsWith("Gene:")) { return uniqueName.substring(5); } } } if (StringUtil.isEmpty(identifier)) { if (StringUtil.isEmpty(name)) { String fixedName = uniqueName.substring(uniqueName.lastIndexOf('.') + 1); return fixedName; } else { return name; } } return identifier; } private void processFeatureScores(Connection connection) throws SQLException, ObjectStoreException { ResultSet res = getFeatureScores(connection); while (res.next()) { Integer featureId = res.getInt("feature_id"); Double score = res.getDouble("score"); String program = res.getString("program"); if (featureMap.containsKey(featureId)) { FeatureData fData = featureMap.get(featureId); Integer storedFeatureId = fData.getIntermineObjectId(); Attribute scoreAttribute = new Attribute("score", score.toString()); getChadoDBConverter().store(scoreAttribute, storedFeatureId); Attribute scoreTypeAttribute = new Attribute("scoreType", program); getChadoDBConverter().store(scoreTypeAttribute, storedFeatureId); } } res.close(); } private ResultSet getFeatureScores(Connection connection) throws SQLException { String query = "SELECT f.feature_id as feature_id, af.rawscore as score, a.program as program" + " FROM feature f, analysisfeature af, analysis a " + " WHERE f.feature_id = af.feature_id " + " AND af.analysis_id = a.analysis_id " + " AND f.feature_id IN " + " (select feature_id from " + SUBFEATUREID_TEMP_TABLE_NAME + " ) "; LOG.info("executing: " + query); long bT = System.currentTimeMillis(); Statement stmt = connection.createStatement(); ResultSet res = stmt.executeQuery(query); LOG.info("QUERY TIME feature scores: " + (System.currentTimeMillis() - bT)); return res; } }
bio/sources/chado-db/main/src/org/intermine/bio/dataconversion/ModEncodeFeatureProcessor.java
package org.intermine.bio.dataconversion; /* * Copyright (C) 2002-2010 FlyMine * * This code may be freely distributed and modified under the * terms of the GNU Lesser General Public Licence. This should * be distributed with the code. See the LICENSE file for more * information or http://www.gnu.org/copyleft/lesser.html. * */ import java.sql.Connection; import java.sql.ResultSet; import java.sql.SQLException; import java.sql.Statement; import java.util.ArrayList; import java.util.Arrays; import java.util.HashMap; import java.util.HashSet; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.Set; import org.apache.commons.collections.keyvalue.MultiKey; import org.apache.commons.collections.map.MultiKeyMap; import org.apache.log4j.Logger; import org.intermine.bio.chado.config.ConfigAction; import org.intermine.bio.chado.config.SetFieldConfigAction; import org.intermine.bio.util.OrganismData; import org.intermine.objectstore.ObjectStoreException; import org.intermine.util.StringUtil; import org.intermine.util.TypeUtil; import org.intermine.xml.full.Attribute; import org.intermine.xml.full.Item; /** * A processor that loads feature referred to by the modENCODE metadata. This class is designed * to be used by ModEncodeMetaDataProcessor and will be called once for each submission that has * metadata. * @author Kim Rutherford */ public class ModEncodeFeatureProcessor extends SequenceProcessor { private static final Logger LOG = Logger.getLogger(ModEncodeFeatureProcessor.class); private final String dataSetIdentifier; private final String dataSourceIdentifier; private final List<Integer> dataList; private final String title; private Set<String> commonFeatureInterMineTypes = new HashSet<String>(); private static final String SUBFEATUREID_TEMP_TABLE_NAME = "modmine_subfeatureid_temp"; // feature type to query from the feature table private static final List<String> FEATURES = Arrays.asList( "gene", "mRNA", "transcript", "CDS", "intron", "exon", "EST", "five_prime_untranslated_region", "five_prime_UTR", "three_prime_untranslated_region", "three_prime_UTR", "origin_of_replication", "binding_site", "protein_binding_site", "TF_binding_site", "transcript_region", "histone_binding_site", "copy_number_variation", "natural_transposable_element", "start_codon", "stop_codon" , "cDNA" , "three_prime_RACE_clone", "three_prime_RST", "three_prime_UST" , "polyA_site", "overlapping_EST_set", "exon_region" , "experimental_feature", "SL1_acceptor_site", "SL2_acceptor_site" , "transcription_end_site", "TSS" ); // the FB name for the mitochondrial genome private static final String MITOCHONDRION = "dmel_mitochondrion_genome"; // ... private static final String CHROMOSOME = "Chromosome"; // the configuration for this processor, set when getConfig() is called the first time private final Map<Integer, MultiKeyMap> config = new HashMap<Integer, MultiKeyMap>(); private Map<Integer, FeatureData> commonFeaturesMap = new HashMap<Integer, FeatureData>(); /** * Create a new ModEncodeFeatureProcessor. * @param chadoDBConverter the parent converter * @param dataSetIdentifier the item identifier of the DataSet, * i.e. the submissionItemIdentifier * @param dataSourceIdentifier the item identifier of the DataSource, * i.e. the labItemIdentifier * @param dataList the list of data ids to be used in the subquery * @param title the title */ public ModEncodeFeatureProcessor(ChadoDBConverter chadoDBConverter, String dataSetIdentifier, String dataSourceIdentifier, List <Integer> dataList, String title) { super(chadoDBConverter); this.dataSetIdentifier = dataSetIdentifier; this.dataSourceIdentifier = dataSourceIdentifier; this.dataList = dataList; this.title = title; for (String chromosomeType : getChromosomeFeatureTypes()) { commonFeatureInterMineTypes.add( TypeUtil.javaiseClassName(fixFeatureType(chromosomeType))); } commonFeatureInterMineTypes.add("Gene"); commonFeatureInterMineTypes.add("MRNA"); commonFeatureInterMineTypes.add("CDNA"); commonFeatureInterMineTypes.add("EST"); commonFeatureInterMineTypes.add("CDS"); commonFeatureInterMineTypes.add("Transcript"); } /** * Get a list of the chado/so types of the LocatedSequenceFeatures we wish to load. The list * will not include chromosome-like features. * @return the list of features */ @Override protected List<String> getFeatures() { return FEATURES; } /** * Get a map of features that are expected to be common between submissions. This map can be * used to initialise this processor for a subsequent run. The feature types added to this map * are governed by the addToFeatureMap method in this class. * @return a map of chado feature id to FeatureData objects */ protected Map<Integer, FeatureData> getCommonFeaturesMap() { return commonFeaturesMap; } /** * Initialise SequenceProcessor with features that have already been processed and put the same * features data into a commonFeaturesMap that tracks features (e.g. Chromosomes) that appear * in multiple submissions but should only be processed once. * @param initialMap map of chado feature id to FeatureData objects */ protected void initialiseCommonFeatures(Map<Integer, FeatureData> initialMap) { super.initialiseFeatureMap(initialMap); commonFeaturesMap.putAll(initialMap); } /** * {@inheritDoc} */ @Override protected String getExtraFeatureConstraint() { /* * tried also other queries (using union, without join), this seems better */ return "(cvterm.name = 'chromosome' OR cvterm.name = 'chromosome_arm') AND " + " feature_id IN ( SELECT featureloc.srcfeature_id " + " FROM featureloc, " + SUBFEATUREID_TEMP_TABLE_NAME + " WHERE featureloc.feature_id = " + SUBFEATUREID_TEMP_TABLE_NAME + ".feature_id) " + " OR feature_id IN ( SELECT feature_id " + " FROM " + SUBFEATUREID_TEMP_TABLE_NAME + " ) "; /* return "(cvterm.name = 'chromosome' OR cvterm.name = 'chromosome_arm') AND " + " feature_id IN ( SELECT featureloc.srcfeature_id " + " FROM featureloc " + " WHERE featureloc.feature_id IN ( SELECT feature_id " + " FROM " + SUBFEATUREID_TEMP_TABLE_NAME + " )) " + " OR feature_id IN ( SELECT feature_id " + " FROM " + SUBFEATUREID_TEMP_TABLE_NAME + " ) "; */ } /** * {@inheritDoc} */ @Override protected void extraProcessing(Connection connection, Map<Integer, FeatureData> featureDataMap) throws ObjectStoreException, SQLException { // TODO: check if there is already a method to get all the match types // (and merge the methods) // also: add match to query and do everything here // process indirect locations via match features and featureloc feature<->match<->feature ResultSet matchLocRes = getMatchLocResultSet(connection); processLocationTable(connection, matchLocRes); List<String> types = getMatchTypes(connection); Iterator<String> t = types.iterator(); while (t.hasNext()) { String featType = t.next(); if (featType.equalsIgnoreCase("cDNA_match")) { continue; } ResultSet matchTypeLocRes = getMatchLocResultSet(connection, featType); processLocationTable(connection, matchTypeLocRes); } // adding scores processFeatureScores(connection); } /** * Method to set the source for gene * for modencode datasources it will add the title * @param imObjectId the im object id * @param dataSourceName the data source * @throws ObjectStoreException the exception * */ @Override protected void setGeneSource(Integer imObjectId, String dataSourceName) throws ObjectStoreException { String source = dataSourceName + "-" + title; setAttribute(imObjectId, "source", source); } /** * Override method that adds completed features to featureMap. Also put features that will * appear in multiple submissions in a map made available at the end of processing. * @param featureId the chado feature id * @param fdat feature information */ protected void addToFeatureMap(Integer featureId, FeatureData fdat) { super.addToFeatureMap(featureId, fdat); // We know chromosomes will be common between submissions so add them here if (commonFeatureInterMineTypes.contains(fdat.getInterMineType()) && !commonFeaturesMap.containsKey(featureId)) { commonFeaturesMap.put(featureId, fdat); } } private List<String> getMatchTypes(Connection connection) throws SQLException, ObjectStoreException { List<String> types = new ArrayList<String>(); ResultSet res = getMatchTypesResultSet(connection); while (res.next()) { String type = res.getString("name"); types.add(type.substring(0, type.indexOf('_'))); } res.close(); return types; } /** * Return the match types, used to determine which additional query to run * This is a protected method so that it can be overriden for testing * @param connection the db connection * @return the SQL result set * @throws SQLException if a database problem occurs */ protected ResultSet getMatchTypesResultSet(Connection connection) throws SQLException { String query = "SELECT name from cvterm where name like '%_match' "; LOG.info("executing: " + query); long bT = System.currentTimeMillis(); Statement stmt = connection.createStatement(); ResultSet res = stmt.executeQuery(query); LOG.debug("QUERY TIME feature match types: " + (System.currentTimeMillis() - bT)); return res; } /** * Return the interesting feature (EST, UST, RST, other?) matches * from the featureloc and feature tables. * * feature<->featureloc<->match_feature<->featureloc<->feature * This is a protected method so that it can be overriden for testing * @param connection the db connection * @param featType the type of feature (EST,UST, etc) * @return the SQL result set * @throws SQLException if a database problem occurs */ protected ResultSet getMatchLocResultSet(Connection connection, String featType) throws SQLException { String query = "SELECT -1 AS featureloc_id, feat.feature_id, chrloc.fmin, " + " chrloc.srcfeature_id AS srcfeature_id, chrloc.fmax, FALSE AS is_fmin_partial, " + " featloc.strand " + " FROM feature feat, featureloc featloc, cvterm featcv, feature mf, " + " cvterm mfcv, featureloc chrloc, feature chr, cvterm chrcv " + " WHERE feat.type_id = featcv.cvterm_id " + " AND featcv.name = '" + featType + "' " + " AND feat.feature_id = featloc.srcfeature_id " + " AND featloc.feature_id = mf.feature_id " + " AND mf.feature_id = chrloc.feature_id " + " AND chrloc.srcfeature_id = chr.feature_id " + " AND chr.type_id = chrcv.cvterm_id " + " AND chrcv.name = 'chromosome' " + " AND mf.type_id = mfcv.cvterm_id " + " AND mfcv.name = '" + featType + "_match' " + " AND feat.feature_id IN " + " (select feature_id from " + SUBFEATUREID_TEMP_TABLE_NAME + " ) "; LOG.info("executing: " + query); long bT = System.currentTimeMillis(); Statement stmt = connection.createStatement(); ResultSet res = stmt.executeQuery(query); LOG.info("QUERY TIME feature " + featType + "_match: " + (System.currentTimeMillis() - bT)); return res; } /** * {@inheritDoc} */ @Override protected Integer store(Item feature, int taxonId) throws ObjectStoreException { processItem(feature, taxonId); Integer itemId = super.store(feature, taxonId); return itemId; } /** * {@inheritDoc} */ @Override protected Item makeLocation(int start, int end, int strand, FeatureData srcFeatureData, FeatureData featureData, int taxonId) throws ObjectStoreException { Item location = super.makeLocation(start, end, strand, srcFeatureData, featureData, taxonId); processItem(location, taxonId); return location; } /** * {@inheritDoc} */ @Override protected Item createSynonym(FeatureData fdat, String type, String identifier, boolean isPrimary, List<Item> otherEvidence) throws ObjectStoreException { // Don't create synonyms for main identifiers of modENCODE features. There are too many and // not useful to quick search. if (isPrimary) { return null; } Item synonym = super.createSynonym(fdat, type, identifier, isPrimary, otherEvidence); OrganismData od = fdat.getOrganismData(); processItem(synonym, od.getTaxonId()); return synonym; } /** * Method to add dataSets and DataSources to items before storing */ private void processItem(Item item, Integer taxonId) { if (item.getClassName().equals("DataSource") || item.getClassName().equals("DataSet") || item.getClassName().equals("Organism") || item.getClassName().equals("Sequence")) { return; } if (taxonId == null) { ClassLoader currentClassLoader = Thread.currentThread().getContextClassLoader(); ClassLoader classLoader = getClass().getClassLoader(); Thread.currentThread().setContextClassLoader(classLoader); try { throw new RuntimeException("getCurrentTaxonId() returned null while processing " + item); } finally { Thread.currentThread().setContextClassLoader(currentClassLoader); } } else { DataSetStoreHook.setDataSets(getModel(), item, dataSetIdentifier, dataSourceIdentifier); } } /** * {@inheritDoc} * * see FlyBaseProcessor for many more examples of configuration */ @Override protected Map<MultiKey, List<ConfigAction>> getConfig(int taxonId) { MultiKeyMap map = config.get(new Integer(taxonId)); if (map == null) { map = new MultiKeyMap(); config.put(new Integer(taxonId), map); // TODO: check possible conflicts with our sql matching // map.put(new MultiKey("relationship", "ESTMatch", "evidence_for_feature", "Intron"), // Arrays.asList(new SetFieldConfigAction("intron"))); // for sub 515 map.put(new MultiKey("relationship", "ThreePrimeUTR", "adjacent_to", "CDS"), Arrays.asList(new SetFieldConfigAction("CDS"))); map.put(new MultiKey("relationship", "PolyASite", "derives_from", "ThreePrimeRACEClone"), Arrays.asList(new SetFieldConfigAction("threePrimeRACEClone"))); map.put(new MultiKey("relationship", "ThreePrimeRST", "derives_from", "ThreePrimeRACEClone"), Arrays.asList(new SetFieldConfigAction("threePrimeRACEClone"))); map.put(new MultiKey("relationship", "ThreePrimeUST", "complete_evidence_for_feature", "ThreePrimeUTR"), Arrays.asList(new SetFieldConfigAction("threePrimeUTR"))); // for sub 35 map.put(new MultiKey("relationship", "OverlappingESTSet", "full_evidence_for_feature", "Gene"), Arrays.asList(new SetFieldConfigAction("gene"))); map.put(new MultiKey("relationship", "OverlappingESTSet", "full_evidence_for_feature", "MRNA"), Arrays.asList(new SetFieldConfigAction("mRNA"))); map.put(new MultiKey("relationship", "OverlappingESTSet", "partial_evidence_for_feature", "MRNA"), Arrays.asList(new SetFieldConfigAction("mRNA"))); // 433 map.put(new MultiKey("relationship", "OverlappingESTSet", "full_evidence_for_feature", "Gene"), Arrays.asList(new SetFieldConfigAction("gene"))); map.put(new MultiKey("relationship", "OverlappingESTSet", "complete_evidence_for_feature", "Intron"), Arrays.asList(new SetFieldConfigAction("intron"))); map.put(new MultiKey("relationship", "OverlappingESTSet", "complete_evidence_for_feature", "PolyASite"), Arrays.asList(new SetFieldConfigAction("polyASite"))); map.put(new MultiKey("relationship", "OverlappingESTSet", "complete_evidence_for_feature", "SL1AcceptorSite"), Arrays.asList(new SetFieldConfigAction("SL1AcceptorSite"))); map.put(new MultiKey("relationship", "OverlappingESTSet", "complete_evidence_for_feature", "SL2AcceptorSite"), Arrays.asList(new SetFieldConfigAction("SL2AcceptorSite"))); map.put(new MultiKey("relationship", "OverlappingESTSet", "complete_evidence_for_feature", "TranscriptionEndSite"), Arrays.asList(new SetFieldConfigAction("transcriptionEndSite"))); map.put(new MultiKey("relationship", "OverlappingESTSet", "evidence_for_feature", "TranscriptRegion"), Arrays.asList(new SetFieldConfigAction("transcriptRegion"))); map.put(new MultiKey("relationship", "OverlappingESTSet", "complete_evidence_for_feature", "TSS"), Arrays.asList(new SetFieldConfigAction("TSS"))); map.put(new MultiKey("relationship", "ExperimentalFeature", "evidence_for_feature", "Transcript"), Arrays.asList(new SetFieldConfigAction("transcript"))); map.put(new MultiKey("relationship", "ExperimentalFeature", "evidence_for_feature", "Exon"), Arrays.asList(new SetFieldConfigAction("exon"))); } return map; } /** * copied from FlyBaseProcessor * {@inheritDoc} */ @Override protected Item makeFeature(Integer featureId, String chadoFeatureType, String interMineType, String name, String uniqueName, int seqlen, int taxonId) { String realInterMineType = interMineType; if (chadoFeatureType.equals("chromosome_arm") || chadoFeatureType.equals("ultra_scaffold")) { realInterMineType = "Chromosome"; if (uniqueName.startsWith("chr")) { // this is to fix some data problem with sub 146 in modmine // where there are duplicated chromosome_arm features, with // and without a 'chr' prefix (e.g. 3R and chr3R) // The chr ones are not the location for any other feature. // So we skip them. return null; } } Item feature = getChadoDBConverter().createItem(realInterMineType); return feature; } /** * method to transform dataList (list of integers) * in the string for a IN clause in SQL (comma separated) * @return String */ protected String forINclause() { StringBuffer ql = new StringBuffer(); Iterator<Integer> i = dataList.iterator(); Integer index = 0; while (i.hasNext()) { index++; if (index > 1) { ql = ql.append(", "); } ql = ql.append(i.next()); } return ql.toString(); } /** * Create a temporary table of all feature_ids for a given submission. * @param connection the connection * @throws SQLException if there is a database problem */ protected void createSubFeatureIdTempTable(Connection connection) throws SQLException { String queryList = forINclause(); String query = " CREATE TEMPORARY TABLE " + SUBFEATUREID_TEMP_TABLE_NAME + " AS SELECT data_feature.feature_id " + " FROM data_feature " + " WHERE data_id IN (" + queryList + ")"; Statement stmt = connection.createStatement(); LOG.info("executing: " + query); long bT = System.currentTimeMillis(); stmt.execute(query); LOG.info("TIME feature creating TEMP table: " + (System.currentTimeMillis() - bT)); String idIndexQuery = "CREATE INDEX " + SUBFEATUREID_TEMP_TABLE_NAME + "_feature_index ON " + SUBFEATUREID_TEMP_TABLE_NAME + "(feature_id)"; LOG.info("executing: " + idIndexQuery); long bT1 = System.currentTimeMillis(); stmt.execute(idIndexQuery); LOG.info("TIME feature creating INDEX: " + (System.currentTimeMillis() - bT1)); String analyze = "ANALYZE " + SUBFEATUREID_TEMP_TABLE_NAME; LOG.info("executing: " + analyze); long bT2 = System.currentTimeMillis(); stmt.execute(analyze); LOG.debug("TIME feature analyzing: " + (System.currentTimeMillis() - bT2)); } /** * {@inheritDoc} */ @Override protected void earlyExtraProcessing(Connection connection) throws SQLException { // to limit the process to the current submission createSubFeatureIdTempTable(connection); } /** * {@inheritDoc} */ @Override protected void finishedProcessing(Connection connection, Map<Integer, FeatureData> featureDataMap) throws SQLException { // override in subclasses as necessary String query = " DROP TABLE " + SUBFEATUREID_TEMP_TABLE_NAME; Statement stmt = connection.createStatement(); LOG.info("executing: " + query); stmt.execute(query); } /** * Process the identifier and return a "cleaned" version. Implemented in sub-classes to fix * data problem. * @param type the InterMine type of the feature that this identifier came from * @param identifier the identifier * @return a cleaned identifier */ /** * {@inheritDoc} */ @Override protected String fixIdentifier(FeatureData fdat, String identifier) { String uniqueName = fdat.getChadoFeatureUniqueName(); String name = fdat.getChadoFeatureName(); String type = fdat.getInterMineType(); if (identifier.equalsIgnoreCase(uniqueName)) { if (type.equalsIgnoreCase(CHROMOSOME)) { if (uniqueName.equalsIgnoreCase("M")) { // this is to fix some data problem in modmine // where submissions (e.g. 100) refer to M chromosome instead // of dmel_mitochondrion_genome as in FlyBase uniqueName = MITOCHONDRION; return uniqueName; } } // Piano submissions have Gene: and Transcript: // in front of gene and transcript identifiers if (type.equalsIgnoreCase("Gene")) { if (uniqueName.startsWith("Gene:")) { return uniqueName.substring(5); } } if (type.equalsIgnoreCase("Transcript")) { if (uniqueName.startsWith("Transcript:")) { return uniqueName.substring(11); } } } if (StringUtil.isEmpty(identifier)) { if (StringUtil.isEmpty(name)) { String fixedName = uniqueName.substring(uniqueName.lastIndexOf('.') + 1); return fixedName; } else { return name; } } return identifier; } private void processFeatureScores(Connection connection) throws SQLException, ObjectStoreException { ResultSet res = getFeatureScores(connection); while (res.next()) { Integer featureId = res.getInt("feature_id"); Double score = res.getDouble("score"); String program = res.getString("program"); if (featureMap.containsKey(featureId)) { FeatureData fData = featureMap.get(featureId); Integer storedFeatureId = fData.getIntermineObjectId(); Attribute scoreAttribute = new Attribute("score", score.toString()); getChadoDBConverter().store(scoreAttribute, storedFeatureId); Attribute scoreTypeAttribute = new Attribute("scoreType", program); getChadoDBConverter().store(scoreTypeAttribute, storedFeatureId); } } res.close(); } private ResultSet getFeatureScores(Connection connection) throws SQLException { String query = "SELECT f.feature_id as feature_id, af.rawscore as score, a.program as program" + " FROM feature f, analysisfeature af, analysis a " + " WHERE f.feature_id = af.feature_id " + " AND af.analysis_id = a.analysis_id " + " AND f.feature_id IN " + " (select feature_id from " + SUBFEATUREID_TEMP_TABLE_NAME + " ) "; LOG.info("executing: " + query); long bT = System.currentTimeMillis(); Statement stmt = connection.createStatement(); ResultSet res = stmt.executeQuery(query); LOG.info("QUERY TIME feature scores: " + (System.currentTimeMillis() - bT)); return res; } }
Allow Waterston data to load by removing Transcript from common features and not stripping prefix.
bio/sources/chado-db/main/src/org/intermine/bio/dataconversion/ModEncodeFeatureProcessor.java
Allow Waterston data to load by removing Transcript from common features and not stripping prefix.
<ide><path>io/sources/chado-db/main/src/org/intermine/bio/dataconversion/ModEncodeFeatureProcessor.java <ide> commonFeatureInterMineTypes.add("CDNA"); <ide> commonFeatureInterMineTypes.add("EST"); <ide> commonFeatureInterMineTypes.add("CDS"); <del> commonFeatureInterMineTypes.add("Transcript"); <ide> } <ide> <ide> /** <ide> return uniqueName.substring(5); <ide> } <ide> } <del> if (type.equalsIgnoreCase("Transcript")) { <del> if (uniqueName.startsWith("Transcript:")) { <del> return uniqueName.substring(11); <del> } <del> } <ide> } <ide> <ide> if (StringUtil.isEmpty(identifier)) {
JavaScript
mit
6b2e2c000a85a7766f39247393c5d7f81243d266
0
wikitree/wikitree-dynamic-tree,wikitree/wikitree-dynamic-tree
/* * Tree.js * * This is the general JS run in index.html. This handles a couple of functions: * A) Logins to the WikiTree API. * Some views (or views of particular profiles) will require the user be logged into the API. * The view page (i.e. index.html) should have a form/button that posts to the clientLogin action of the API, * with a returnURL back to the viewed page. The code here handles checking the auth code that comes back, * and saving the API user name and Id in cookies so that the page knows the user is logged in. * * B) New Tree/Start-Profile selection * Each Tree is a separate view, built into the id="treeViewerContainer" div. There's a selection element * that let's the user select a new view. When the "Go" button there is clicked, newTree() is called. That * pulls out the tree view id from the selected option and then switches the display to that view with launchTree(). * * Similarly, a new starting profile can be selected by providing a new WikiTree ID and clicking the associated "Go" button. * The same newTree() function is called, followed by launchTree() if we have a selected tree and profile. * * To add a new view to the dynamic tree: * - Add a new <option> to the selection field in index.html * - Add the appropriate code to launch/display the view in launchTree(). * */ $(document).ready(function() { // In order to view non-public profiles, the user must be logged into the WikiTree API. // That's on a separate hostname, so while the credentials are the same for the user, the browser doesn't carry over a login from WikiTree.com. // If the user is not yet logged into the API, there's a button they can use to login through API clientLogin(). // When there's a successful login, we store this status in a cookie so future loads of this page don't have to repeat it. // See: https://github.com/wikitree/wikitree-api/blob/main/authentication.md // We want the API login process to return back where we started. $('#returnURL').val( window.location.href ); // We store userName and userId of the logged-in user locally in a cookie so we know on return that // the user is signed in (and so we can use it as a default starting point for tree views). var userName = WikiTreeAPI.cookie('WikiTreeAPI_userName'); var userId = WikiTreeAPI.cookie('WikiTreeAPI_userId'); // We also track the last treeId the user was viewing and the starting personId in case they return from elsewhere. var viewTreeId = WikiTreeAPI.cookie('viewTreeId'); var viewTreePersonId = WikiTreeAPI.cookie('viewTreePersonId'); var viewTreePersonName = WikiTreeAPI.cookie('viewTreePersonName'); // If we've arrived with an "authcode", it's the redirect back from the API clientLogin(), and we should // verify the code and then redirect back to ourselves to clear out the parameter. var u = new URLSearchParams(window.location.search) var authcode = u.get('authcode'); if ((typeof(userName) != 'undefined') && (userName != null) && (userName != '')) { // According to our saved cookie, we have a user that is logged into the API. // Update the login div with a status instead of the button. $('#getAPILogin').html("Logged into API: "+userName); // Display our tree. If we don't have one, use the wikitree-dynamic-tree as a default. // If we have a cookie-saved starting personId, use that, otherwise start with the logged-in user's id. if ((typeof(viewTreeId) == 'undefined') || !viewTreeId) { viewTreeId = 'wikitree-dynamic-tree'; } if ((typeof(viewTreePersonId) == 'undefined') || !viewTreePersonId) { viewTreePersonId = userId; viewTreePersonName = userName; } // Launch our desired tree on page load. launchTree(viewTreeId, viewTreePersonId, viewTreePersonName); } else if ((typeof authcode != 'undefined') && (authcode != null) && (authcode != '')) { // We have an auth code to confirm. Show our interim message div while we do. // This is very brief; one the clientLogin() returns we redirect back to ourselves. $('#confirmAuth').show(); WikiTreeAPI.postToAPI( { 'action':'clientLogin', 'authcode': authcode } ) .then(function(data) { if (data.clientLogin.result == 'Success') { WikiTreeAPI.cookie('WikiTreeAPI_userName', data.clientLogin.username, { 'path': '/'} ); WikiTreeAPI.cookie('WikiTreeAPI_userId', data.clientLogin.userid, { 'path': '/'} ); var urlPieces = [location.protocol, '//', location.host, location.pathname] var url = urlPieces.join(''); window.location = url; } else { // The login at the API failed. We should have a friendlier error here. alert('API login failure'); $('#confirmAuth').hide(); } }); } else if (viewTreePersonId && viewTreePersonName && viewTreeId) { // If there's no auth code to process, and no user id to check, we can just trying displaying the current view. launchTree(viewTreeId, viewTreePersonId, viewTreePersonName); } else { // No tree to launch! } }); /* * Given a viewTreeId, we have different code to instantiate that particular view, using the * id or name (WikiTree ID) of the starting profile. * */ function launchTree(viewTreeId, viewTreePersonId, viewTreePersonName) { // Grab the new view options - the id of the selected view and the starting profile. Save these in cookies // so we can return to this view automatically when the page reloads. $('#viewTreeId').val(viewTreeId); $('#viewTreePersonId').val(viewTreePersonId); $('#viewTreePersonName').val(viewTreePersonName); WikiTreeAPI.cookie('viewTreeId', viewTreeId); WikiTreeAPI.cookie('viewTreePersonId', viewTreePersonId); WikiTreeAPI.cookie('viewTreePersonName', viewTreePersonName); // In case the container was hidden (e.g. during login/auth-code verification), display it. $('#treeViewerContainer').show(); // Define the Person profile fields to retrieve, which we can use to fill the treeInfo selection // and some elements in the page. var infoFields = "Id,Name,FirstName,LastName,Derived.BirthName,Derived.BirthNamePrivate"; // The base/core/default tree view if (viewTreeId == 'wikitree-dynamic-tree') { $('#treeInfo').load( 'views/baseDynamicTree/treeInfo.html', function() { WikiTreeAPI.postToAPI( {'action': 'getPerson', 'key': viewTreePersonId, 'fields': infoFields } ) .then(function(data) { updateViewedPersonContent(data[0].person); var tree = new WikiTreeDynamicTreeViewer('#treeViewerContainer', viewTreePersonId); }); } ); } if (viewTreeId == 'restyled-base') { $('#treeInfo').load( 'views/restyledBaseExample/treeInfo.html', function() { WikiTreeAPI.postToAPI( {'action': 'getPerson', 'key': viewTreePersonId, 'fields': infoFields } ) .then(function(data) { updateViewedPersonContent(data[0].person); var tree = new alternateViewExample('#treeViewerContainer', viewTreePersonId); }); } ); } } /* * When a new tree or starting profile is desired, we lookup the profile with the API. If one is found, we start a new tree. * This function is called when one of the "Go" buttons is clicked in index.html for either a new starting profile or a * new view option. */ function newTree(k) { var key; if (k) { $('#viewTreePersonName').val(k); } var key = $('#viewTreePersonName').val(); WikiTreeAPI.postToAPI( {'action':'getPerson', 'key':key } ) .then(function(data) { if (data.error) { alert("Error retrieiving \""+key+"\" from API."); } else { if (data[0].person.Id) { $('#treeViewerContainer').empty(); viewTreePersonId = data[0].person.Id; viewTreePersonName = data[0].person.Name; viewTreeId = $('#viewTreeId').val(); launchTree(viewTreeId, viewTreePersonId, viewTreePersonName); updateViewedPersonContent(data[0].person); } else { alert("Error retrieiving \""+key+"\" from API."); } } }); }; /* * Create navigation bar with the number ID of a profile, and update spans/links to have the person data. */ function updateViewedPersonContent(person) { // Stash the info into the web page. $('.viewTreePersonId').html(person.Id); $('.viewTreePersonName').html(person.Name); $('.viewTreePersonBirthName').html(person.BirthName ? person.BirthName : person.BirthNamePrivate); $('.viewTreePersonURL').html(person.Name); $('.viewTreePersonURL').attr("href", "https://www.WikiTree.com/wiki/"+person.Name); }
Tree.js
/* * Tree.js * * This is the general JS run in index.html. This handles a couple of functions: * A) Logins to the WikiTree API. * Some views (or views of particular profiles) will require the user be logged into the API. * The view page (i.e. index.html) should have a form/button that posts to the clientLogin action of the API, * with a returnURL back to the viewed page. The code here handles checking the auth code that comes back, * and saving the API user name and Id in cookies so that the page knows the user is logged in. * * B) New Tree/Start-Profile selection * Each Tree is a separate view, built into the id="treeViewerContainer" div. There's a selection element * that let's the user select a new view. When the "Go" button there is clicked, newTree() is called. That * pulls out the tree view id from the selected option and then switches the display to that view with launchTree(). * * Similarly, a new starting profile can be selected by providing a new WikiTree ID and clicking the associated "Go" button. * The same newTree() function is called, followed by launchTree() if we have a selected tree and profile. * * To add a new view to the dynamic tree: * - Add a new <option> to the selection field in index.html * - Add the appropriate code to launch/display the view in launchTree(). * */ $(document).ready(function() { // In order to view non-public profiles, the user must be logged into the WikiTree API. // That's on a separate hostname, so while the credentials are the same for the user, the browser doesn't carry over a login from WikiTree.com. // If the user is not yet logged into the API, there's a button they can use to login through API clientLogin(). // When there's a successful login, we store this status in a cookie so future loads of this page don't have to repeat it. // See: https://github.com/wikitree/wikitree-api/blob/main/authentication.md // We want the API login process to return back where we started. $('#returnURL').val( window.location.href ); // We store userName and userId of the logged-in user locally in a cookie so we know on return that // the user is signed in (and so we can use it as a default starting point for tree views). var userName = WikiTreeAPI.cookie('WikiTreeAPI_userName'); var userId = WikiTreeAPI.cookie('WikiTreeAPI_userId'); // We also track the last treeId the user was viewing and the starting personId in case they return from elsewhere. var viewTreeId = WikiTreeAPI.cookie('viewTreeId'); var viewTreePersonId = WikiTreeAPI.cookie('viewTreePersonId'); var viewTreePersonName = WikiTreeAPI.cookie('viewTreePersonName'); // If we've arrived with an "authcode", it's the redirect back from the API clientLogin(), and we should // verify the code and then redirect back to ourselves to clear out the parameter. var u = new URLSearchParams(window.location.search) var authcode = u.get('authcode'); if ((typeof(userName) != 'undefined') && (userName != null) && (userName != '')) { // According to our saved cookie, we have a user that is logged into the API. // Update the login div with a status instead of the button. $('#getAPILogin').html("Logged into API: "+userName); // Display our tree. If we don't have one, use the wikitree-dynamic-tree as a default. // If we have a cookie-saved starting personId, use that, otherwise start with the logged-in user's id. if ((typeof(viewTreeId) == 'undefined') || !viewTreeId) { viewTreeId = 'wikitree-dynamic-tree'; } if ((typeof(viewTreePersonId) == 'undefined') || !viewTreePersonId) { viewTreePersonId = userId; viewTreePersonName = userName; } // Launch our desired tree on page load. launchTree(viewTreeId, viewTreePersonId, viewTreePersonName); } else if ((typeof authcode != 'undefined') && (authcode != null) && (authcode != '')) { // We have an auth code to confirm. Show our interim message div while we do. // This is very brief; one the clientLogin() returns we redirect back to ourselves. $('#confirmAuth').show(); WikiTreeAPI.postToAPI( { 'action':'clientLogin', 'authcode': authcode } ) .then(function(data) { if (data.clientLogin.result == 'Success') { WikiTreeAPI.cookie('WikiTreeAPI_userName', data.clientLogin.username, { 'path': '/'} ); WikiTreeAPI.cookie('WikiTreeAPI_userId', data.clientLogin.userid, { 'path': '/'} ); var urlPieces = [location.protocol, '//', location.host, location.pathname] var url = urlPieces.join(''); window.location = url; } else { // The login at the API failed. We should have a friendlier error here. alert('API login failure'); $('#confirmAuth').hide(); } }); } else if (viewTreePersonId && viewTreePersonName && viewTreeId) { // If there's no auth code to process, and no user id to check, we can just trying displaying the current view. launchTree(viewTreeId, viewTreePersonId, viewTreePersonName); } else { // No tree to launch! } }); /* * Given a viewTreeId, we have different code to instantiate that particular view, using the * id or name (WikiTree ID) of the starting profile. * */ function launchTree(viewTreeId, viewTreePersonId, viewTreePersonName) { // Grab the new view options - the id of the selected view and the starting profile. Save these in cookies // so we can return to this view automatically when the page reloads. $('#viewTreeId').val(viewTreeId); $('#viewTreePersonId').val(viewTreePersonId); $('#viewTreePersonName').val(viewTreePersonName); WikiTreeAPI.cookie('viewTreeId', viewTreeId); WikiTreeAPI.cookie('viewTreePersonId', viewTreePersonId); WikiTreeAPI.cookie('viewTreePersonName', viewTreePersonName); // In case the container was hidden (e.g. during login/auth-code verification), display it. $('#treeViewerContainer').show(); // Define the Person profile fields to retrieve, which we can use to fill the treeInfo selection // and some elements in the page. var infoFields = "Id,Name,FirstName,LastName,Derived.BirthName,Derived.BirthNamePrivate"; // The base/core/default tree view if (viewTreeId == 'wikitree-dynamic-tree') { $('#treeInfo').load('views/baseDynamicTree/treeInfo.html'); WikiTreeAPI.postToAPI( {'action': 'getPerson', 'key': viewTreePersonId, 'fields': infoFields } ) .then(function(data) { updateViewedPersonContent(data[0].person); var tree = new WikiTreeDynamicTreeViewer('#treeViewerContainer', viewTreePersonId); }); } if (viewTreeId == 'restyled-base') { $('#treeInfo').load('views/restyledBaseExample/treeInfo.html'); WikiTreeAPI.postToAPI( {'action': 'getPerson', 'key': viewTreePersonId, 'fields': infoFields } ) .then(function(data) { updateViewedPersonContent(data[0].person); var tree = new alternateViewExample('#treeViewerContainer', viewTreePersonId); }); } } /* * When a new tree or starting profile is desired, we lookup the profile with the API. If one is found, we start a new tree. * This function is called when one of the "Go" buttons is clicked in index.html for either a new starting profile or a * new view option. */ function newTree(k) { var key; if (k) { $('#viewTreePersonName').val(k); } var key = $('#viewTreePersonName').val(); WikiTreeAPI.postToAPI( {'action':'getPerson', 'key':key } ) .then(function(data) { if (data.error) { alert("Error retrieiving \""+key+"\" from API."); } else { if (data[0].person.Id) { $('#treeViewerContainer').empty(); viewTreePersonId = data[0].person.Id; viewTreePersonName = data[0].person.Name; viewTreeId = $('#viewTreeId').val(); launchTree(viewTreeId, viewTreePersonId, viewTreePersonName); updateViewedPersonContent(data[0].person); } else { alert("Error retrieiving \""+key+"\" from API."); } } }); }; /* * Create navigation bar with the number ID of a profile, and update spans/links to have the person data. */ function updateViewedPersonContent(person) { // Stash the info into the web page. $('.viewTreePersonId').html(person.Id); $('.viewTreePersonName').html(person.Name); $('.viewTreePersonBirthName').html(person.BirthName ? person.BirthName : person.BirthNamePrivate); $('.viewTreePersonURL').html(person.Name); $('.viewTreePersonURL').attr("href", "https://www.WikiTree.com/wiki/"+person.Name); }
Move actions after .load()ing the treeInfo.html into a success function so that the viewPerson data in them is present before updateViewedPersonContent runs.
Tree.js
Move actions after .load()ing the treeInfo.html into a success function so that the viewPerson data in them is present before updateViewedPersonContent runs.
<ide><path>ree.js <ide> <ide> // The base/core/default tree view <ide> if (viewTreeId == 'wikitree-dynamic-tree') { <del> $('#treeInfo').load('views/baseDynamicTree/treeInfo.html'); <del> WikiTreeAPI.postToAPI( {'action': 'getPerson', 'key': viewTreePersonId, 'fields': infoFields } ) <del> .then(function(data) { <del> updateViewedPersonContent(data[0].person); <del> var tree = new WikiTreeDynamicTreeViewer('#treeViewerContainer', viewTreePersonId); <del> }); <del> <add> $('#treeInfo').load( <add> 'views/baseDynamicTree/treeInfo.html', <add> function() { <add> WikiTreeAPI.postToAPI( {'action': 'getPerson', 'key': viewTreePersonId, 'fields': infoFields } ) <add> .then(function(data) { <add> updateViewedPersonContent(data[0].person); <add> var tree = new WikiTreeDynamicTreeViewer('#treeViewerContainer', viewTreePersonId); <add> }); <add> } <add> ); <ide> } <ide> if (viewTreeId == 'restyled-base') { <del> $('#treeInfo').load('views/restyledBaseExample/treeInfo.html'); <del> WikiTreeAPI.postToAPI( {'action': 'getPerson', 'key': viewTreePersonId, 'fields': infoFields } ) <del> .then(function(data) { <del> updateViewedPersonContent(data[0].person); <del> var tree = new alternateViewExample('#treeViewerContainer', viewTreePersonId); <del> }); <del> <add> $('#treeInfo').load( <add> 'views/restyledBaseExample/treeInfo.html', <add> function() { <add> WikiTreeAPI.postToAPI( {'action': 'getPerson', 'key': viewTreePersonId, 'fields': infoFields } ) <add> .then(function(data) { <add> updateViewedPersonContent(data[0].person); <add> var tree = new alternateViewExample('#treeViewerContainer', viewTreePersonId); <add> }); <add> } <add> ); <ide> } <ide> } <ide>
Java
lgpl-2.1
c5779b64f3ebe45a2672aa09d4fd67311d5b1ab4
0
MinecraftForge/ForgeGradle,MinecraftForge/ForgeGradle
/* * ForgeGradle * Copyright (C) 2018 Forge Development LLC * * 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.1 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; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 * USA */ package net.minecraftforge.gradle.common.util; import com.google.common.collect.ImmutableList; import com.google.common.collect.ImmutableMap; import com.google.gson.Gson; import com.google.gson.GsonBuilder; import com.google.gson.JsonArray; import com.google.gson.JsonObject; import org.apache.commons.lang3.tuple.ImmutableTriple; import org.apache.commons.lang3.tuple.Triple; import org.gradle.api.Project; import org.gradle.api.Task; import org.gradle.api.plugins.JavaPluginConvention; import org.gradle.api.tasks.SourceSet; import org.gradle.api.tasks.TaskProvider; import org.gradle.plugins.ide.eclipse.model.EclipseModel; import org.gradle.plugins.ide.eclipse.model.SourceFolder; import org.w3c.dom.Document; import org.w3c.dom.Element; import javax.annotation.Nonnull; import javax.xml.parsers.DocumentBuilder; import javax.xml.parsers.DocumentBuilderFactory; import javax.xml.parsers.ParserConfigurationException; import javax.xml.transform.OutputKeys; import javax.xml.transform.Transformer; import javax.xml.transform.TransformerConfigurationException; import javax.xml.transform.TransformerException; import javax.xml.transform.TransformerFactory; import javax.xml.transform.dom.DOMSource; import javax.xml.transform.stream.StreamResult; import java.io.File; import java.io.FileWriter; import java.io.IOException; import java.io.Writer; import java.util.Collections; import java.util.LinkedHashMap; import java.util.List; import java.util.Map; import java.util.function.Function; import java.util.stream.Collectors; import java.util.stream.Stream; public final class IDEUtils { @SuppressWarnings("UnstableApiUsage") public static void createIDEGenRunsTasks(@Nonnull final MinecraftExtension minecraft, @Nonnull final TaskProvider<Task> prepareRuns, @Nonnull final TaskProvider<Task> makeSourceDirs) { final Project project = minecraft.getProject(); final Map<String, Triple<List<Object>, File, RunConfigurationBuilder>> ideConfigurationGenerators = ImmutableMap.<String, Triple<List<Object>, File, RunConfigurationBuilder>>builder() .put("genIntellijRuns", ImmutableTriple.of(Collections.singletonList(prepareRuns.get()), new File(project.getRootProject().getRootDir(), ".idea/runConfigurations"), new XMLConfigurationBuilder(IDEUtils::createIntellijRunConfigurationXML))) .put("genEclipseRuns", ImmutableTriple.of(ImmutableList.of(prepareRuns.get(), makeSourceDirs.get()), project.getProjectDir(), new XMLConfigurationBuilder(IDEUtils::createEclipseRunConfigurationXML))) .put("genVSCodeRuns", ImmutableTriple.of(ImmutableList.of(prepareRuns.get(), makeSourceDirs.get()), new File(project.getProjectDir(), ".vscode"), new JsonConfigurationBuilder(IDEUtils::createVSCodeRunConfiguration))) .build(); ideConfigurationGenerators.forEach((taskName, configurationGenerator) -> { project.getTasks().register(taskName, Task.class, task -> { task.setGroup(RunConfig.RUNS_GROUP); task.dependsOn(configurationGenerator.getLeft()); task.doLast(t -> { final File runConfigurationsDir = configurationGenerator.getMiddle(); if (!runConfigurationsDir.exists()) { runConfigurationsDir.mkdirs(); } configurationGenerator.getRight().createConfig(minecraft, runConfigurationsDir, project); }); }); }); } private static void elementOption(@Nonnull Document document, @Nonnull final Element parent, @Nonnull final String name, @Nonnull final String value) { final Element option = document.createElement("option"); { option.setAttribute("name", name); option.setAttribute("value", value); } parent.appendChild(option); } @Nonnull private static Map<String, Document> createIntellijRunConfigurationXML(@Nonnull final Project project, @Nonnull final RunConfig runConfig, @Nonnull final String props, @Nonnull final DocumentBuilder documentBuilder) { final Map<String, Document> documents = new LinkedHashMap<>(); // Java run config final Document javaDocument = documentBuilder.newDocument(); { final Element rootElement = javaDocument.createElement("component"); { final Element configuration = javaDocument.createElement("configuration"); { configuration.setAttribute("default", "false"); configuration.setAttribute("name", runConfig.getUniqueName()); configuration.setAttribute("type", "Application"); configuration.setAttribute("factoryName", "Application"); configuration.setAttribute("singleton", runConfig.isSingleInstance() ? "true" : "false"); elementOption(javaDocument, configuration, "MAIN_CLASS_NAME", runConfig.getMain()); elementOption(javaDocument, configuration, "VM_PARAMETERS", props); elementOption(javaDocument, configuration, "PROGRAM_PARAMETERS", String.join(" ", runConfig.getArgs())); elementOption(javaDocument, configuration, "WORKING_DIRECTORY", runConfig.getWorkingDirectory()); final Element module = javaDocument.createElement("module"); { module.setAttribute("name", runConfig.getIdeaModule()); } configuration.appendChild(module); final Element envs = javaDocument.createElement("envs"); { runConfig.getEnvironment().forEach((name, value) -> { final Element envEntry = javaDocument.createElement("env"); { envEntry.setAttribute("name", name); envEntry.setAttribute("value", value); } envs.appendChild(envEntry); }); } configuration.appendChild(envs); final Element methods = javaDocument.createElement("method"); { methods.setAttribute("v", "2"); final Element makeTask = javaDocument.createElement("option"); { makeTask.setAttribute("name", "Make"); makeTask.setAttribute("enabled", "true"); } methods.appendChild(makeTask); final Element gradleTask = javaDocument.createElement("option"); { gradleTask.setAttribute("name", "Gradle.BeforeRunTask"); gradleTask.setAttribute("enabled", "true"); gradleTask.setAttribute("tasks", project.getTasks().getByName("prepare" + Utils.capitalize(runConfig.getTaskName())).getPath()); gradleTask.setAttribute("externalProjectPath", "$PROJECT_DIR$"); } methods.appendChild(gradleTask); } configuration.appendChild(methods); } rootElement.appendChild(configuration); } javaDocument.appendChild(rootElement); } documents.put(runConfig.getUniqueFileName() + ".xml", javaDocument); return documents; } private static void elementAttribute(@Nonnull Document document, @Nonnull final Element parent, @Nonnull final String attributeType, @Nonnull final String key, @Nonnull final String value) { final Element attribute = document.createElement(attributeType + "Attribute"); { attribute.setAttribute("key", key); attribute.setAttribute("value", value); } parent.appendChild(attribute); } @Nonnull private static Map<String, Document> createEclipseRunConfigurationXML(@Nonnull final Project project, @Nonnull final RunConfig runConfig, @Nonnull final String props, @Nonnull final DocumentBuilder documentBuilder) { final Map<String, Document> documents = new LinkedHashMap<>(); // Java run config final Document javaDocument = documentBuilder.newDocument(); { final Element rootElement = javaDocument.createElement("launchConfiguration"); { rootElement.setAttribute("type", "org.eclipse.jdt.launching.localJavaApplication"); elementAttribute(javaDocument, rootElement, "string", "org.eclipse.jdt.launching.PROJECT_ATTR", project.getName()); elementAttribute(javaDocument, rootElement, "string", "org.eclipse.jdt.launching.MAIN_TYPE", runConfig.getMain()); elementAttribute(javaDocument, rootElement, "string", "org.eclipse.jdt.launching.VM_ARGUMENTS", props); elementAttribute(javaDocument, rootElement, "string", "org.eclipse.jdt.launching.PROGRAM_ARGUMENTS", String.join(" ", runConfig.getArgs())); final File workingDirectory = new File(runConfig.getWorkingDirectory()); // Eclipse requires working directory to exist if (!workingDirectory.exists()) { workingDirectory.mkdirs(); } elementAttribute(javaDocument, rootElement, "string", "org.eclipse.jdt.launching.WORKING_DIRECTORY", runConfig.getWorkingDirectory()); final Element envs = javaDocument.createElement("mapAttribute"); { envs.setAttribute("key", "org.eclipse.debug.core.environmentVariables"); runConfig.getEnvironment().compute("MOD_CLASSES", (key, value) -> mapModClasses(key, value, project, runConfig)); runConfig.getEnvironment().forEach((name, value) -> { final Element envEntry = javaDocument.createElement("mapEntry"); { envEntry.setAttribute("key", name); envEntry.setAttribute("value", value); } envs.appendChild(envEntry); }); } rootElement.appendChild(envs); } javaDocument.appendChild(rootElement); } documents.put(runConfig.getTaskName() + ".launch", javaDocument); return documents; } @Nonnull private static JsonObject createVSCodeRunConfiguration(@Nonnull final Project project, @Nonnull final RunConfig runConfig, @Nonnull final String props) { JsonObject config = new JsonObject(); config.addProperty("type", "java"); config.addProperty("name", runConfig.getTaskName()); config.addProperty("request", "launch"); config.addProperty("mainClass", runConfig.getMain()); config.addProperty("projectName", project.getName()); config.addProperty("cwd", replaceRootDirBy(project, runConfig.getWorkingDirectory().toString(), "${workspaceFolder}")); config.addProperty("vmArgs", props); config.addProperty("args", String.join(" ", runConfig.getArgs())); JsonObject env = new JsonObject(); runConfig.getEnvironment().compute("MOD_CLASSES", (key, value) -> replaceRootDirBy(project, mapModClasses(key, value, project, runConfig), "${workspaceFolder}")); runConfig.getEnvironment().compute("nativesDirectory", (key, value) -> replaceRootDirBy(project, value, "${workspaceFolder}")); runConfig.getEnvironment().forEach((name, value) -> { env.addProperty(name, value); }); config.add("env", env); return config; } private static String replaceRootDirBy(@Nonnull final Project project, String value, @Nonnull final String replacement) { if (value == null || value.isEmpty()) { return value; } return value.replace(project.getRootDir().toString(), replacement); } private static String mapModClasses(String key, String value, @Nonnull final Project project, @Nonnull final RunConfig runConfig) { // Only replace environment variable if it is already set if (value == null || value.isEmpty()) { return value; } final EclipseModel eclipse = project.getExtensions().findByType(EclipseModel.class); if (eclipse != null) { final Map<String, String> outputs = eclipse.getClasspath().resolveDependencies().stream() .filter(SourceFolder.class::isInstance) .map(SourceFolder.class::cast) .map(SourceFolder::getOutput) .distinct() .collect(Collectors.toMap(output -> output.split("/")[output.split("/").length - 1], output -> project.file(output).getAbsolutePath())); if (runConfig.getMods().isEmpty()) { return runConfig.getAllSources().stream() .map(SourceSet::getName) .filter(outputs::containsKey) .map(outputs::get) .map(s -> String.join(File.pathSeparator, s, s)) // <resources>:<classes> .collect(Collectors.joining(File.pathSeparator)); } else { final SourceSet main = project.getConvention().getPlugin(JavaPluginConvention.class).getSourceSets().getByName(SourceSet.MAIN_SOURCE_SET_NAME); return runConfig.getMods().stream() .map(modConfig -> { return (modConfig.getSources().isEmpty() ? Stream.of(main) : modConfig.getSources().stream()) .map(SourceSet::getName) .filter(outputs::containsKey) .map(outputs::get) .map(output -> modConfig.getName() + "%%" + output) .map(s -> String.join(File.pathSeparator, s, s)); // <resources>:<classes> }) .flatMap(Function.identity()) .collect(Collectors.joining(File.pathSeparator)); } } return value; } @FunctionalInterface private interface XMLRunConfigurationGenerator { @Nonnull Map<String, Document> createRunConfigurationXML(@Nonnull final Project project, @Nonnull final RunConfig runConfig, @Nonnull final String props, @Nonnull final DocumentBuilder documentBuilder); } @FunctionalInterface private interface JsonRunConfigurationGenerator { @Nonnull JsonObject createRunConfigurationJson(@Nonnull final Project project, @Nonnull final RunConfig runConfig, @Nonnull final String props); } private interface RunConfigurationBuilder { void createConfig(@Nonnull final MinecraftExtension minecraft, @Nonnull final File runConfigurationsDir, @Nonnull final Project project); } private static class XMLConfigurationBuilder implements RunConfigurationBuilder { private XMLRunConfigurationGenerator configGenerator; public XMLConfigurationBuilder(XMLRunConfigurationGenerator generator) { configGenerator = generator; } @Override public void createConfig(@Nonnull final MinecraftExtension minecraft, @Nonnull final File runConfigurationsDir, @Nonnull final Project project) { try { final DocumentBuilderFactory docFactory = DocumentBuilderFactory.newInstance(); final DocumentBuilder docBuilder = docFactory.newDocumentBuilder(); final TransformerFactory transformerFactory = TransformerFactory.newInstance(); final Transformer transformer = transformerFactory.newTransformer(); transformer.setOutputProperty(OutputKeys.INDENT, "yes"); transformer.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", "2"); minecraft.getRuns().forEach(runConfig -> { final Stream<String> propStream = runConfig.getProperties().entrySet().stream().map(kv -> String.format("-D%s=%s", kv.getKey(), kv.getValue())); final String props = Stream.concat(propStream, runConfig.getJvmArgs().stream()).collect(Collectors.joining(" ")); final Map<String, Document> documents = configGenerator.createRunConfigurationXML(project, runConfig, props, docBuilder); documents.forEach((fileName, document) -> { final DOMSource source = new DOMSource(document); final StreamResult result = new StreamResult(new File(runConfigurationsDir, fileName)); try { transformer.transform(source, result); } catch (TransformerException e) { e.printStackTrace(); } }); }); } catch (ParserConfigurationException | TransformerConfigurationException e) { e.printStackTrace(); } } } private static class JsonConfigurationBuilder implements RunConfigurationBuilder { private JsonRunConfigurationGenerator configGenerator; public JsonConfigurationBuilder(JsonRunConfigurationGenerator generator) { configGenerator = generator; } @Override public void createConfig(@Nonnull final MinecraftExtension minecraft, @Nonnull final File runConfigurationsDir, @Nonnull final Project project) { final JsonObject rootObject = new JsonObject(); rootObject.addProperty("version", "0.2.0"); JsonArray runConfigs = new JsonArray(); minecraft.getRuns().forEach(runConfig -> { final Stream<String> propStream = runConfig.getProperties().entrySet().stream().map(kv -> String.format("-D%s=%s", kv.getKey(), kv.getValue())); final String props = Stream.concat(propStream, runConfig.getJvmArgs().stream()).collect(Collectors.joining(" ")); runConfigs.add(configGenerator.createRunConfigurationJson(project, runConfig, props)); }); rootObject.add("configurations", runConfigs); Writer writer; try { writer = new FileWriter(new File(runConfigurationsDir, "launch.json")); Gson gson = new GsonBuilder().setPrettyPrinting().create(); writer.write(gson.toJson(rootObject)); writer.close(); } catch (IOException e) { e.printStackTrace(); } } } }
src/common/java/net/minecraftforge/gradle/common/util/IDEUtils.java
/* * ForgeGradle * Copyright (C) 2018 Forge Development LLC * * 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.1 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; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 * USA */ package net.minecraftforge.gradle.common.util; import com.google.common.collect.ImmutableList; import com.google.common.collect.ImmutableMap; import org.apache.commons.lang3.tuple.ImmutableTriple; import org.apache.commons.lang3.tuple.Triple; import org.gradle.api.Project; import org.gradle.api.Task; import org.gradle.api.plugins.JavaPluginConvention; import org.gradle.api.tasks.SourceSet; import org.gradle.api.tasks.TaskProvider; import org.gradle.plugins.ide.eclipse.model.EclipseModel; import org.gradle.plugins.ide.eclipse.model.SourceFolder; import org.w3c.dom.Document; import org.w3c.dom.Element; import javax.annotation.Nonnull; import javax.xml.parsers.DocumentBuilder; import javax.xml.parsers.DocumentBuilderFactory; import javax.xml.parsers.ParserConfigurationException; import javax.xml.transform.OutputKeys; import javax.xml.transform.Transformer; import javax.xml.transform.TransformerConfigurationException; import javax.xml.transform.TransformerException; import javax.xml.transform.TransformerFactory; import javax.xml.transform.dom.DOMSource; import javax.xml.transform.stream.StreamResult; import java.io.File; import java.util.Collections; import java.util.LinkedHashMap; import java.util.List; import java.util.Map; import java.util.function.Function; import java.util.stream.Collectors; import java.util.stream.Stream; public final class IDEUtils { @SuppressWarnings("UnstableApiUsage") public static void createIDEGenRunsTasks(@Nonnull final MinecraftExtension minecraft, @Nonnull final TaskProvider<Task> prepareRuns, @Nonnull final TaskProvider<Task> makeSourceDirs) { final Project project = minecraft.getProject(); final Map<String, Triple<List<Object>, File, RunConfigurationGenerator>> ideConfigurationGenerators = ImmutableMap.<String, Triple<List<Object>, File, RunConfigurationGenerator>>builder() .put("genIntellijRuns", ImmutableTriple.of(Collections.singletonList(prepareRuns.get()), new File(project.getRootProject().getRootDir(), ".idea/runConfigurations"), IDEUtils::createIntellijRunConfigurationXML)) .put("genEclipseRuns", ImmutableTriple.of(ImmutableList.of(prepareRuns.get(), makeSourceDirs.get()), project.getProjectDir(), IDEUtils::createEclipseRunConfigurationXML)) .build(); ideConfigurationGenerators.forEach((taskName, configurationGenerator) -> { project.getTasks().register(taskName, Task.class, task -> { task.setGroup(RunConfig.RUNS_GROUP); task.dependsOn(configurationGenerator.getLeft()); task.doLast(t -> { try { final File runConfigurationsDir = configurationGenerator.getMiddle(); if (!runConfigurationsDir.exists()) { runConfigurationsDir.mkdirs(); } final DocumentBuilderFactory docFactory = DocumentBuilderFactory.newInstance(); final DocumentBuilder docBuilder = docFactory.newDocumentBuilder(); final TransformerFactory transformerFactory = TransformerFactory.newInstance(); final Transformer transformer = transformerFactory.newTransformer(); transformer.setOutputProperty(OutputKeys.INDENT, "yes"); transformer.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", "2"); minecraft.getRuns().forEach(runConfig -> { final Stream<String> propStream = runConfig.getProperties().entrySet().stream().map(kv -> String.format("-D%s=%s", kv.getKey(), kv.getValue())); final String props = Stream.concat(propStream, runConfig.getJvmArgs().stream()).collect(Collectors.joining(" ")); final Map<String, Document> documents = configurationGenerator.getRight().createRunConfigurationXML(project, runConfig, props, docBuilder); documents.forEach((fileName, document) -> { final DOMSource source = new DOMSource(document); final StreamResult result = new StreamResult(new File(runConfigurationsDir, fileName)); try { transformer.transform(source, result); } catch (TransformerException e) { e.printStackTrace(); } }); }); } catch (ParserConfigurationException | TransformerConfigurationException e) { e.printStackTrace(); } }); }); }); } private static void elementOption(@Nonnull Document document, @Nonnull final Element parent, @Nonnull final String name, @Nonnull final String value) { final Element option = document.createElement("option"); { option.setAttribute("name", name); option.setAttribute("value", value); } parent.appendChild(option); } @Nonnull private static Map<String, Document> createIntellijRunConfigurationXML(@Nonnull final Project project, @Nonnull final RunConfig runConfig, @Nonnull final String props, @Nonnull final DocumentBuilder documentBuilder) { final Map<String, Document> documents = new LinkedHashMap<>(); // Java run config final Document javaDocument = documentBuilder.newDocument(); { final Element rootElement = javaDocument.createElement("component"); { final Element configuration = javaDocument.createElement("configuration"); { configuration.setAttribute("default", "false"); configuration.setAttribute("name", runConfig.getUniqueName()); configuration.setAttribute("type", "Application"); configuration.setAttribute("factoryName", "Application"); configuration.setAttribute("singleton", runConfig.isSingleInstance() ? "true" : "false"); elementOption(javaDocument, configuration, "MAIN_CLASS_NAME", runConfig.getMain()); elementOption(javaDocument, configuration, "VM_PARAMETERS", props); elementOption(javaDocument, configuration, "PROGRAM_PARAMETERS", String.join(" ", runConfig.getArgs())); elementOption(javaDocument, configuration, "WORKING_DIRECTORY", runConfig.getWorkingDirectory()); final Element module = javaDocument.createElement("module"); { module.setAttribute("name", runConfig.getIdeaModule()); } configuration.appendChild(module); final Element envs = javaDocument.createElement("envs"); { runConfig.getEnvironment().forEach((name, value) -> { final Element envEntry = javaDocument.createElement("env"); { envEntry.setAttribute("name", name); envEntry.setAttribute("value", value); } envs.appendChild(envEntry); }); } configuration.appendChild(envs); final Element methods = javaDocument.createElement("method"); { methods.setAttribute("v", "2"); final Element makeTask = javaDocument.createElement("option"); { makeTask.setAttribute("name", "Make"); makeTask.setAttribute("enabled", "true"); } methods.appendChild(makeTask); final Element gradleTask = javaDocument.createElement("option"); { gradleTask.setAttribute("name", "Gradle.BeforeRunTask"); gradleTask.setAttribute("enabled", "true"); gradleTask.setAttribute("tasks", project.getTasks().getByName("prepare" + Utils.capitalize(runConfig.getTaskName())).getPath()); gradleTask.setAttribute("externalProjectPath", "$PROJECT_DIR$"); } methods.appendChild(gradleTask); } configuration.appendChild(methods); } rootElement.appendChild(configuration); } javaDocument.appendChild(rootElement); } documents.put(runConfig.getUniqueFileName() + ".xml", javaDocument); return documents; } private static void elementAttribute(@Nonnull Document document, @Nonnull final Element parent, @Nonnull final String attributeType, @Nonnull final String key, @Nonnull final String value) { final Element attribute = document.createElement(attributeType + "Attribute"); { attribute.setAttribute("key", key); attribute.setAttribute("value", value); } parent.appendChild(attribute); } @Nonnull private static Map<String, Document> createEclipseRunConfigurationXML(@Nonnull final Project project, @Nonnull final RunConfig runConfig, @Nonnull final String props, @Nonnull final DocumentBuilder documentBuilder) { final Map<String, Document> documents = new LinkedHashMap<>(); // Java run config final Document javaDocument = documentBuilder.newDocument(); { final Element rootElement = javaDocument.createElement("launchConfiguration"); { rootElement.setAttribute("type", "org.eclipse.jdt.launching.localJavaApplication"); elementAttribute(javaDocument, rootElement, "string", "org.eclipse.jdt.launching.PROJECT_ATTR", project.getName()); elementAttribute(javaDocument, rootElement, "string", "org.eclipse.jdt.launching.MAIN_TYPE", runConfig.getMain()); elementAttribute(javaDocument, rootElement, "string", "org.eclipse.jdt.launching.VM_ARGUMENTS", props); elementAttribute(javaDocument, rootElement, "string", "org.eclipse.jdt.launching.PROGRAM_ARGUMENTS", String.join(" ", runConfig.getArgs())); final File workingDirectory = new File(runConfig.getWorkingDirectory()); // Eclipse requires working directory to exist if (!workingDirectory.exists()) { workingDirectory.mkdirs(); } elementAttribute(javaDocument, rootElement, "string", "org.eclipse.jdt.launching.WORKING_DIRECTORY", runConfig.getWorkingDirectory()); final Element envs = javaDocument.createElement("mapAttribute"); { envs.setAttribute("key", "org.eclipse.debug.core.environmentVariables"); runConfig.getEnvironment().compute("MOD_CLASSES", (key, value) -> { // Only replace environment variable if it is already set if (value == null || value.isEmpty()) { return value; } final EclipseModel eclipse = project.getExtensions().findByType(EclipseModel.class); if (eclipse != null) { final Map<String, String> outputs = eclipse.getClasspath().resolveDependencies().stream() .filter(SourceFolder.class::isInstance) .map(SourceFolder.class::cast) .map(SourceFolder::getOutput) .distinct() .collect(Collectors.toMap(output -> output.split("/")[output.split("/").length - 1], output -> project.file(output).getAbsolutePath())); if (runConfig.getMods().isEmpty()) { return runConfig.getAllSources().stream() .map(SourceSet::getName) .filter(outputs::containsKey) .map(outputs::get) .map(s -> String.join(File.pathSeparator, s, s)) // <resources>:<classes> .collect(Collectors.joining(File.pathSeparator)); } else { final SourceSet main = project.getConvention().getPlugin(JavaPluginConvention.class).getSourceSets().getByName(SourceSet.MAIN_SOURCE_SET_NAME); return runConfig.getMods().stream() .map(modConfig -> { return (modConfig.getSources().isEmpty() ? Stream.of(main) : modConfig.getSources().stream()) .map(SourceSet::getName) .filter(outputs::containsKey) .map(outputs::get) .map(output -> modConfig.getName() + "%%" + output) .map(s -> String.join(File.pathSeparator, s, s)); // <resources>:<classes> }) .flatMap(Function.identity()) .collect(Collectors.joining(File.pathSeparator)); } } return value; }); runConfig.getEnvironment().forEach((name, value) -> { final Element envEntry = javaDocument.createElement("mapEntry"); { envEntry.setAttribute("key", name); envEntry.setAttribute("value", value); } envs.appendChild(envEntry); }); } rootElement.appendChild(envs); } javaDocument.appendChild(rootElement); } documents.put(runConfig.getTaskName() + ".launch", javaDocument); return documents; } @FunctionalInterface private interface RunConfigurationGenerator { @Nonnull Map<String, Document> createRunConfigurationXML(@Nonnull final Project project, @Nonnull final RunConfig runConfig, @Nonnull final String props, @Nonnull final DocumentBuilder documentBuilder); } }
Add support for VSCode run configs (#589)
src/common/java/net/minecraftforge/gradle/common/util/IDEUtils.java
Add support for VSCode run configs (#589)
<ide><path>rc/common/java/net/minecraftforge/gradle/common/util/IDEUtils.java <ide> <ide> import com.google.common.collect.ImmutableList; <ide> import com.google.common.collect.ImmutableMap; <add>import com.google.gson.Gson; <add>import com.google.gson.GsonBuilder; <add>import com.google.gson.JsonArray; <add>import com.google.gson.JsonObject; <add> <ide> import org.apache.commons.lang3.tuple.ImmutableTriple; <ide> import org.apache.commons.lang3.tuple.Triple; <ide> import org.gradle.api.Project; <ide> import javax.xml.transform.dom.DOMSource; <ide> import javax.xml.transform.stream.StreamResult; <ide> import java.io.File; <add>import java.io.FileWriter; <add>import java.io.IOException; <add>import java.io.Writer; <ide> import java.util.Collections; <ide> import java.util.LinkedHashMap; <ide> import java.util.List; <ide> public static void createIDEGenRunsTasks(@Nonnull final MinecraftExtension minecraft, @Nonnull final TaskProvider<Task> prepareRuns, @Nonnull final TaskProvider<Task> makeSourceDirs) { <ide> final Project project = minecraft.getProject(); <ide> <del> final Map<String, Triple<List<Object>, File, RunConfigurationGenerator>> ideConfigurationGenerators = ImmutableMap.<String, Triple<List<Object>, File, RunConfigurationGenerator>>builder() <add> final Map<String, Triple<List<Object>, File, RunConfigurationBuilder>> ideConfigurationGenerators = ImmutableMap.<String, Triple<List<Object>, File, RunConfigurationBuilder>>builder() <ide> .put("genIntellijRuns", ImmutableTriple.of(Collections.singletonList(prepareRuns.get()), <del> new File(project.getRootProject().getRootDir(), ".idea/runConfigurations"), IDEUtils::createIntellijRunConfigurationXML)) <add> new File(project.getRootProject().getRootDir(), ".idea/runConfigurations"), new XMLConfigurationBuilder(IDEUtils::createIntellijRunConfigurationXML))) <ide> .put("genEclipseRuns", ImmutableTriple.of(ImmutableList.of(prepareRuns.get(), makeSourceDirs.get()), <del> project.getProjectDir(), IDEUtils::createEclipseRunConfigurationXML)) <add> project.getProjectDir(), new XMLConfigurationBuilder(IDEUtils::createEclipseRunConfigurationXML))) <add> .put("genVSCodeRuns", ImmutableTriple.of(ImmutableList.of(prepareRuns.get(), makeSourceDirs.get()), <add> new File(project.getProjectDir(), ".vscode"), new JsonConfigurationBuilder(IDEUtils::createVSCodeRunConfiguration))) <ide> .build(); <ide> <ide> ideConfigurationGenerators.forEach((taskName, configurationGenerator) -> { <ide> task.dependsOn(configurationGenerator.getLeft()); <ide> <ide> task.doLast(t -> { <del> try { <del> final File runConfigurationsDir = configurationGenerator.getMiddle(); <del> <del> if (!runConfigurationsDir.exists()) { <del> runConfigurationsDir.mkdirs(); <del> } <del> <del> final DocumentBuilderFactory docFactory = DocumentBuilderFactory.newInstance(); <del> final DocumentBuilder docBuilder = docFactory.newDocumentBuilder(); <del> final TransformerFactory transformerFactory = TransformerFactory.newInstance(); <del> final Transformer transformer = transformerFactory.newTransformer(); <del> <del> transformer.setOutputProperty(OutputKeys.INDENT, "yes"); <del> transformer.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", "2"); <del> <del> minecraft.getRuns().forEach(runConfig -> { <del> final Stream<String> propStream = runConfig.getProperties().entrySet().stream().map(kv -> String.format("-D%s=%s", kv.getKey(), kv.getValue())); <del> final String props = Stream.concat(propStream, runConfig.getJvmArgs().stream()).collect(Collectors.joining(" ")); <del> final Map<String, Document> documents = configurationGenerator.getRight().createRunConfigurationXML(project, runConfig, props, docBuilder); <del> <del> documents.forEach((fileName, document) -> { <del> final DOMSource source = new DOMSource(document); <del> final StreamResult result = new StreamResult(new File(runConfigurationsDir, fileName)); <del> <del> try { <del> transformer.transform(source, result); <del> } catch (TransformerException e) { <del> e.printStackTrace(); <del> } <del> }); <del> }); <del> } catch (ParserConfigurationException | TransformerConfigurationException e) { <del> e.printStackTrace(); <add> final File runConfigurationsDir = configurationGenerator.getMiddle(); <add> <add> if (!runConfigurationsDir.exists()) { <add> runConfigurationsDir.mkdirs(); <ide> } <add> configurationGenerator.getRight().createConfig(minecraft, runConfigurationsDir, project); <ide> }); <ide> }); <ide> }); <ide> { <ide> envs.setAttribute("key", "org.eclipse.debug.core.environmentVariables"); <ide> <del> runConfig.getEnvironment().compute("MOD_CLASSES", (key, value) -> { <del> // Only replace environment variable if it is already set <del> if (value == null || value.isEmpty()) { <del> return value; <del> } <del> <del> final EclipseModel eclipse = project.getExtensions().findByType(EclipseModel.class); <del> <del> if (eclipse != null) { <del> final Map<String, String> outputs = eclipse.getClasspath().resolveDependencies().stream() <del> .filter(SourceFolder.class::isInstance) <del> .map(SourceFolder.class::cast) <del> .map(SourceFolder::getOutput) <del> .distinct() <del> .collect(Collectors.toMap(output -> output.split("/")[output.split("/").length - 1], output -> project.file(output).getAbsolutePath())); <del> <del> if (runConfig.getMods().isEmpty()) { <del> return runConfig.getAllSources().stream() <del> .map(SourceSet::getName) <del> .filter(outputs::containsKey) <del> .map(outputs::get) <del> .map(s -> String.join(File.pathSeparator, s, s)) // <resources>:<classes> <del> .collect(Collectors.joining(File.pathSeparator)); <del> } else { <del> final SourceSet main = project.getConvention().getPlugin(JavaPluginConvention.class).getSourceSets().getByName(SourceSet.MAIN_SOURCE_SET_NAME); <del> <del> return runConfig.getMods().stream() <del> .map(modConfig -> { <del> return (modConfig.getSources().isEmpty() ? Stream.of(main) : modConfig.getSources().stream()) <del> .map(SourceSet::getName) <del> .filter(outputs::containsKey) <del> .map(outputs::get) <del> .map(output -> modConfig.getName() + "%%" + output) <del> .map(s -> String.join(File.pathSeparator, s, s)); // <resources>:<classes> <del> }) <del> .flatMap(Function.identity()) <del> .collect(Collectors.joining(File.pathSeparator)); <del> } <del> } <del> <del> return value; <del> }); <del> <add> runConfig.getEnvironment().compute("MOD_CLASSES", (key, value) -> mapModClasses(key, value, project, runConfig)); <ide> runConfig.getEnvironment().forEach((name, value) -> { <ide> final Element envEntry = javaDocument.createElement("mapEntry"); <ide> { <ide> return documents; <ide> } <ide> <add> @Nonnull <add> private static JsonObject createVSCodeRunConfiguration(@Nonnull final Project project, @Nonnull final RunConfig runConfig, @Nonnull final String props) { <add> JsonObject config = new JsonObject(); <add> config.addProperty("type", "java"); <add> config.addProperty("name", runConfig.getTaskName()); <add> config.addProperty("request", "launch"); <add> config.addProperty("mainClass", runConfig.getMain()); <add> config.addProperty("projectName", project.getName()); <add> config.addProperty("cwd", replaceRootDirBy(project, runConfig.getWorkingDirectory().toString(), "${workspaceFolder}")); <add> config.addProperty("vmArgs", props); <add> config.addProperty("args", String.join(" ", runConfig.getArgs())); <add> JsonObject env = new JsonObject(); <add> runConfig.getEnvironment().compute("MOD_CLASSES", (key, value) -> replaceRootDirBy(project, mapModClasses(key, value, project, runConfig), "${workspaceFolder}")); <add> runConfig.getEnvironment().compute("nativesDirectory", (key, value) -> replaceRootDirBy(project, value, "${workspaceFolder}")); <add> runConfig.getEnvironment().forEach((name, value) -> { <add> env.addProperty(name, value); <add> }); <add> config.add("env", env); <add> return config; <add> } <add> <add> private static String replaceRootDirBy(@Nonnull final Project project, String value, @Nonnull final String replacement) { <add> if (value == null || value.isEmpty()) { <add> return value; <add> } <add> return value.replace(project.getRootDir().toString(), replacement); <add> } <add> <add> private static String mapModClasses(String key, String value, @Nonnull final Project project, @Nonnull final RunConfig runConfig) { <add> // Only replace environment variable if it is already set <add> if (value == null || value.isEmpty()) { <add> return value; <add> } <add> <add> final EclipseModel eclipse = project.getExtensions().findByType(EclipseModel.class); <add> <add> if (eclipse != null) { <add> final Map<String, String> outputs = eclipse.getClasspath().resolveDependencies().stream() <add> .filter(SourceFolder.class::isInstance) <add> .map(SourceFolder.class::cast) <add> .map(SourceFolder::getOutput) <add> .distinct() <add> .collect(Collectors.toMap(output -> output.split("/")[output.split("/").length - 1], output -> project.file(output).getAbsolutePath())); <add> <add> if (runConfig.getMods().isEmpty()) { <add> return runConfig.getAllSources().stream() <add> .map(SourceSet::getName) <add> .filter(outputs::containsKey) <add> .map(outputs::get) <add> .map(s -> String.join(File.pathSeparator, s, s)) // <resources>:<classes> <add> .collect(Collectors.joining(File.pathSeparator)); <add> } else { <add> final SourceSet main = project.getConvention().getPlugin(JavaPluginConvention.class).getSourceSets().getByName(SourceSet.MAIN_SOURCE_SET_NAME); <add> <add> return runConfig.getMods().stream() <add> .map(modConfig -> { <add> return (modConfig.getSources().isEmpty() ? Stream.of(main) : modConfig.getSources().stream()) <add> .map(SourceSet::getName) <add> .filter(outputs::containsKey) <add> .map(outputs::get) <add> .map(output -> modConfig.getName() + "%%" + output) <add> .map(s -> String.join(File.pathSeparator, s, s)); // <resources>:<classes> <add> }) <add> .flatMap(Function.identity()) <add> .collect(Collectors.joining(File.pathSeparator)); <add> } <add> } <add> <add> return value; <add> } <add> <ide> @FunctionalInterface <del> private interface RunConfigurationGenerator { <add> private interface XMLRunConfigurationGenerator { <ide> <ide> @Nonnull <ide> Map<String, Document> createRunConfigurationXML(@Nonnull final Project project, @Nonnull final RunConfig runConfig, @Nonnull final String props, @Nonnull final DocumentBuilder documentBuilder); <ide> <ide> } <ide> <add> @FunctionalInterface <add> private interface JsonRunConfigurationGenerator { <add> <add> @Nonnull <add> JsonObject createRunConfigurationJson(@Nonnull final Project project, @Nonnull final RunConfig runConfig, @Nonnull final String props); <add> <add> } <add> <add> private interface RunConfigurationBuilder { <add> <add> void createConfig(@Nonnull final MinecraftExtension minecraft, @Nonnull final File runConfigurationsDir, @Nonnull final Project project); <add> <add> } <add> <add> private static class XMLConfigurationBuilder implements RunConfigurationBuilder { <add> <add> private XMLRunConfigurationGenerator configGenerator; <add> <add> public XMLConfigurationBuilder(XMLRunConfigurationGenerator generator) { <add> configGenerator = generator; <add> } <add> <add> @Override <add> public void createConfig(@Nonnull final MinecraftExtension minecraft, @Nonnull final File runConfigurationsDir, @Nonnull final Project project) { <add> try { <add> final DocumentBuilderFactory docFactory = DocumentBuilderFactory.newInstance(); <add> final DocumentBuilder docBuilder = docFactory.newDocumentBuilder(); <add> final TransformerFactory transformerFactory = TransformerFactory.newInstance(); <add> final Transformer transformer = transformerFactory.newTransformer(); <add> <add> transformer.setOutputProperty(OutputKeys.INDENT, "yes"); <add> transformer.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", "2"); <add> <add> minecraft.getRuns().forEach(runConfig -> { <add> final Stream<String> propStream = runConfig.getProperties().entrySet().stream().map(kv -> String.format("-D%s=%s", kv.getKey(), kv.getValue())); <add> final String props = Stream.concat(propStream, runConfig.getJvmArgs().stream()).collect(Collectors.joining(" ")); <add> final Map<String, Document> documents = configGenerator.createRunConfigurationXML(project, runConfig, props, docBuilder); <add> <add> documents.forEach((fileName, document) -> { <add> final DOMSource source = new DOMSource(document); <add> final StreamResult result = new StreamResult(new File(runConfigurationsDir, fileName)); <add> <add> try { <add> transformer.transform(source, result); <add> } catch (TransformerException e) { <add> e.printStackTrace(); <add> } <add> }); <add> }); <add> } catch (ParserConfigurationException | TransformerConfigurationException e) { <add> e.printStackTrace(); <add> } <add> } <add> } <add> <add> private static class JsonConfigurationBuilder implements RunConfigurationBuilder { <add> <add> private JsonRunConfigurationGenerator configGenerator; <add> <add> public JsonConfigurationBuilder(JsonRunConfigurationGenerator generator) { <add> configGenerator = generator; <add> } <add> <add> @Override <add> public void createConfig(@Nonnull final MinecraftExtension minecraft, @Nonnull final File runConfigurationsDir, @Nonnull final Project project) { <add> final JsonObject rootObject = new JsonObject(); <add> rootObject.addProperty("version", "0.2.0"); <add> JsonArray runConfigs = new JsonArray(); <add> minecraft.getRuns().forEach(runConfig -> { <add> final Stream<String> propStream = runConfig.getProperties().entrySet().stream().map(kv -> String.format("-D%s=%s", kv.getKey(), kv.getValue())); <add> final String props = Stream.concat(propStream, runConfig.getJvmArgs().stream()).collect(Collectors.joining(" ")); <add> runConfigs.add(configGenerator.createRunConfigurationJson(project, runConfig, props)); <add> }); <add> rootObject.add("configurations", runConfigs); <add> Writer writer; <add> try { <add> writer = new FileWriter(new File(runConfigurationsDir, "launch.json")); <add> Gson gson = new GsonBuilder().setPrettyPrinting().create(); <add> writer.write(gson.toJson(rootObject)); <add> writer.close(); <add> } catch (IOException e) { <add> e.printStackTrace(); <add> } <add> } <add> } <ide> }
JavaScript
mit
03029e78d3a5ef0b92b930fdca47007f1139d140
0
shyiko/lorem
module.exports = function(grunt) { grunt.initConfig({ pkg: '<json:package.json>', test: { files: ['src/nodeunit/**/*.js'] }, qunit: { files: ['src/qunit/index.html'] }, lint: { files: ['grunt.js', 'src/library/**/*.js', 'src/nodeunit/**/*.js'] }, watch: { files: '<config:lint.files>', tasks: 'lint' }, jshint: { options: { curly: true, eqeqeq: true, immed: true, latedef: true, newcap: true, noarg: true, sub: true, undef: true, boss: true, eqnull: true, node: true }, globals: { exports: true, define: true, jQuery: true } } }); grunt.registerTask('default', 'lint test qunit'); grunt.registerTask('endless-lint', 'lint watch'); grunt.registerTask('travis', 'lint test'); };
grunt.js
module.exports = function(grunt) { grunt.initConfig({ pkg: '<json:package.json>', test: { files: ['src/nodeunit/**/*.js'] }, qunit: { files: ['src/qunit/index.html'] }, lint: { files: ['grunt.js', 'src/library/**/*.js', 'src/nodeunit/**/*.js'] }, watch: { files: '<config:lint.files>', tasks: 'lint' }, jshint: { options: { curly: true, eqeqeq: true, immed: true, latedef: true, newcap: true, noarg: true, sub: true, undef: true, boss: true, eqnull: true, node: true }, globals: { exports: true, define: true, jQuery: true } } }); grunt.registerTask('default', 'lint test qunit'); grunt.registerTask('endless-lint', 'lint watch'); grunt.registerTask('travis', 'lint test qunit'); };
Disabled QUnit tests for Travis CI builds
grunt.js
Disabled QUnit tests for Travis CI builds
<ide><path>runt.js <ide> <ide> grunt.registerTask('default', 'lint test qunit'); <ide> grunt.registerTask('endless-lint', 'lint watch'); <del> grunt.registerTask('travis', 'lint test qunit'); <add> grunt.registerTask('travis', 'lint test'); <ide> <ide> };
JavaScript
bsd-2-clause
06ed4293b01dd8f6386b0c735399dc6f479cbcc1
0
rajpurkar/driverseat,psrthegreat/driverseat,rajpurkar/driverseat,psrthegreat/driverseat,psrthegreat/driverseat,rajpurkar/driverseat,rajpurkar/driverseat,psrthegreat/driverseat
//todo: not make these globals since multiple things are starting to use geometry //please don't remove commented code var renderer; var camera; var scene; var geometry; var pickLocation; var mouse = { x: 1, y: 1 }; var projector, raycaster; var dataFile = "files/datafile.json"; var gpsFile = "files/gpsfile.json"; var lanesFile = "files/lanesfile.json"; var shiftKey = false; var gpsData; // Detect when shift key is being pressed for painting document.addEventListener('keydown', function(event) { if (event.keyCode == 16) shiftKey = true; }, false); document.addEventListener('keyup', function(event) { if (event.keyCode == 16) shiftKey = false; }, false); /** * Algorithm to calculate a single RGB channel (0-255) from HSL hue (0-1.0) */ function HUEtoRGB(hue) { if (hue < 0) { hue += 1; } else if (hue > 1) { hue -= 1; } var rgb = 0; if (hue < 1/6) { rgb = hue*6; } else if (hue < 1/2) { rgb = 1; } else if (hue < 2/3) { rgb = (2/3 - hue)*6; } return Math.round(rgb * 255); } function loadPoints(df){ var xhr = new XMLHttpRequest(); xhr.open("GET", df, false); xhr.send(null); if (xhr.status !== 200 && xhr.status !== 0) { throw new Error(df + " not found"); } var data = JSON.parse(xhr.responseText); return data; } function generatePointCloud(data, size, color) { var geometry = new THREE.BufferGeometry(); var positions = new Float32Array(3*data.length); var colors = new Float32Array(3*data.length); for (var i = 0; i < data.length; i++) { //Note: order is changed positions[3*i] = data[i][2]; //x positions[3*i+1] = data[i][0]; //y positions[3*i+2] = data[i][1]; //z // map intensity (0-120) to RGB if(data[i].length >= 4){ var hue = 1 - data[i][3]/120; //TODO: fix intensity scaling colors[3*i+1] = HUEtoRGB(hue+1/3); //r colors[3*i+2] = HUEtoRGB(hue); //g colors[3*i+0] = HUEtoRGB(hue-1/3); //b }else{ colors[3*i+1] = color; //r colors[3*i+2] = color; //g colors[3*i+0] = color; } } geometry.addAttribute('position', new THREE.BufferAttribute(positions, 3)); geometry.addAttribute('color', new THREE.BufferAttribute(colors, 3)); var material = new THREE.PointCloudMaterial({ size: size, vertexColors: true }); var pointcloud = new THREE.PointCloud(geometry, material); return pointcloud; } function addCar2(){ THREE.Loader.Handlers.add( /\.dds$/i, new THREE.DDSLoader() ); var loader = new THREE.OBJMTLLoader(); loader.load('/files/R8_14blend.obj', '/files/R8_14blend.mtl', function(object) { object.position.set( 0, 0, 0 ); object.rotation.set( 0, Math.PI / 2, Math.PI ); object.scale.set( 10, 10, 10 ); scene.add(object); }); } function addCar(){ var loader = new THREE.PLYLoader(); loader.addEventListener('load', function ( event ) { var geometry = event.content; var material = new THREE.MeshBasicMaterial( {} ); var mesh = new THREE.Mesh( geometry, material ); mesh.position.set( -2, 30, -2 ); mesh.rotation.set( 0, Math.PI / 2, Math.PI ); mesh.scale.set( 1, 1, 1 ); //mesh.castShadow = true; //mesh.receiveShadow = true; scene.add( mesh ); } ); loader.load('/files/gtr.ply' ); } function onWindowResize() { camera.aspect = window.innerWidth / window.innerHeight; camera.updateProjectionMatrix(); renderer.setSize( window.innerWidth, window.innerHeight ); } var target = new THREE.Vector3(0, 200, 0 ); function init() { scene = new THREE.Scene(); camera = new THREE.PerspectiveCamera(75, window.innerWidth/window.innerHeight, 0.1, 1000); cameraTarget = target; projector = new THREE.Projector(); raycaster = new THREE.Raycaster(); renderer = new THREE.WebGLRenderer({alpha:true}); renderer.setClearColor(0, 1) renderer.setSize(window.innerWidth, window.innerHeight); document.body.appendChild(renderer.domElement); var pointData = loadPoints(dataFile) pointcloud = generatePointCloud(pointData, 0.01); scene.add(pointcloud); gpsData = loadPoints(gpsFile) gpsCloud = generatePointCloud(gpsData, 0.05, 250); lanesData = loadPoints(lanesFile); for (var lane in lanesData){ laneCloud = generatePointCloud(lanesData[lane], 0.15, 255); scene.add(laneCloud); } var sphereGeometry = new THREE.SphereGeometry(0.1, 32, 32); var sphereMaterial = new THREE.MeshBasicMaterial({color: 0xff0000, shading: THREE.FlatShading}); pickLocation = new THREE.Mesh(sphereGeometry, sphereMaterial); scene.add(pickLocation); //addCar2(); // controls camera.position.set(0,0,0); //controls = new THREE.OrbitControls(camera); //controls.target.set( 0, 100, 0 ); //camera.lookAt(new THREE.Vector3(0,100,0)); document.addEventListener( 'mousemove', onDocumentMouseMove, false ); window.addEventListener( 'resize', onWindowResize, false ); } function onDocumentMouseMove( event ) { event.preventDefault(); mouse.x = ( event.clientX / window.innerWidth ) * 2 - 1; mouse.y = - ( event.clientY / window.innerHeight ) * 2 + 1; } function animate() { requestAnimationFrame( animate ); render(); } var count = 0; function render() { camera.updateMatrixWorld(true); vector = new THREE.Vector3( mouse.x, mouse.y, 0.5 ); projector.unprojectVector( vector, camera ); raycaster.params = {"PointCloud" : {threshold: 0.1}}; raycaster.ray.set( camera.position, vector.sub( camera.position ).normalize() ); var intersects = raycaster.intersectObject(pointcloud); if(intersects.length > 0){ pickLocation.position.copy(intersects[0].point); // Paint the points with the cursor while pressing <shift> if (shiftKey) { var pointColors = geometry.attributes.color.array; for (var i = 0; i < intersects.length; i++) { var index = 3*intersects[i].index; pointColors[index] = 255; pointColors[index+1] = 255; pointColors[index+2] = 255; } geometry.attributes.color.needsUpdate = true; } } //var timer = Date.now() * 0.0005; //camera.position.y += Math.abs(Math.cos( timer )) *.3 ; //camera.position.z += Math.cos( timer ) * 0.03; positionArr = gpsData[count]; camera.position.y = gpsData[count+1][0]; camera.position.z = gpsData[count+1][1]; camera.position.x = gpsData[count+1][2]; target.y = gpsData[count + 5][0]; target.z = gpsData[count + 1][1]; target.x = gpsData[count + 1][2]; //camera.position.set(new THREE.Vector3(positionArr[2],positionArr[0],positionArr[1])); //camera.lookAt(new THREE.Vector3(0,100,0)); camera.lookAt(target); renderer.render( scene, camera ); renderer.render(scene, camera); count++; console.log(count) } init(); animate();
public/demo.js
//todo: not make these globals since multiple things are starting to use geometry var renderer; var camera; var scene; var geometry; var pickLocation; var mouse = { x: 1, y: 1 }; var projector, raycaster; var dataFile = "files/datafile.json"; var gpsFile = "files/gpsfile.json"; var shiftKey = false; var gpsData; // Detect when shift key is being pressed for painting document.addEventListener('keydown', function(event) { if (event.keyCode == 16) shiftKey = true; }, false); document.addEventListener('keyup', function(event) { if (event.keyCode == 16) shiftKey = false; }, false); /** * Algorithm to calculate a single RGB channel (0-255) from HSL hue (0-1.0) */ function HUEtoRGB(hue) { if (hue < 0) { hue += 1; } else if (hue > 1) { hue -= 1; } var rgb = 0; if (hue < 1/6) { rgb = hue*6; } else if (hue < 1/2) { rgb = 1; } else if (hue < 2/3) { rgb = (2/3 - hue)*6; } return Math.round(rgb * 255); } function loadPoints(df){ var xhr = new XMLHttpRequest(); xhr.open("GET", df, false); xhr.send(null); if (xhr.status !== 200 && xhr.status !== 0) { throw new Error(df + " not found"); } var data = JSON.parse(xhr.responseText); return data; } function generatePointCloud(data) { var geometry = new THREE.BufferGeometry(); var positions = new Float32Array(3*data.length); var colors = new Float32Array(3*data.length); for (var i = 0; i < data.length; i++) { //Note: order is changed positions[3*i] = data[i][2]; //x positions[3*i+1] = data[i][0]; //y positions[3*i+2] = data[i][1]; //z // map intensity (0-120) to RGB if(data[i].length >= 4){ var hue = 1 - data[i][3]/120; //TODO: fix intensity scaling colors[3*i+1] = HUEtoRGB(hue+1/3); //r colors[3*i+2] = HUEtoRGB(hue); //g colors[3*i+0] = HUEtoRGB(hue-1/3); //b }else{ colors[3*i+1] = 240; //r colors[3*i+2] = 240; //g colors[3*i+0] = 240; } } geometry.addAttribute('position', new THREE.BufferAttribute(positions, 3)); geometry.addAttribute('color', new THREE.BufferAttribute(colors, 3)); var material = new THREE.PointCloudMaterial({ size: 0.01, vertexColors: true }); var pointcloud = new THREE.PointCloud(geometry, material); return pointcloud; } function addCar2(){ THREE.Loader.Handlers.add( /\.dds$/i, new THREE.DDSLoader() ); var loader = new THREE.OBJMTLLoader(); loader.load('/files/R8_14blend.obj', '/files/R8_14blend.mtl', function(object) { object.position.set( 0, 0, 0 ); object.rotation.set( 0, Math.PI / 2, Math.PI ); object.scale.set( 10, 10, 10 ); scene.add(object); }); } function addCar(){ var loader = new THREE.PLYLoader(); loader.addEventListener('load', function ( event ) { var geometry = event.content; var material = new THREE.MeshBasicMaterial( {} ); var mesh = new THREE.Mesh( geometry, material ); mesh.position.set( -2, 30, -2 ); mesh.rotation.set( 0, Math.PI / 2, Math.PI ); mesh.scale.set( 1, 1, 1 ); //mesh.castShadow = true; //mesh.receiveShadow = true; scene.add( mesh ); } ); loader.load('/files/gtr.ply' ); } function onWindowResize() { camera.aspect = window.innerWidth / window.innerHeight; camera.updateProjectionMatrix(); renderer.setSize( window.innerWidth, window.innerHeight ); } var target = new THREE.Vector3(0, 200, 0 ); function init() { scene = new THREE.Scene(); camera = new THREE.PerspectiveCamera(75, window.innerWidth/window.innerHeight, 0.1, 1000); cameraTarget = target; projector = new THREE.Projector(); raycaster = new THREE.Raycaster(); renderer = new THREE.WebGLRenderer({alpha:true}); renderer.setClearColor(0, 1) renderer.setSize(window.innerWidth, window.innerHeight); document.body.appendChild(renderer.domElement); var pointData = loadPoints(dataFile) pointcloud = generatePointCloud(pointData); scene.add(pointcloud); gpsData = loadPoints(gpsFile) gpsCloud = generatePointCloud(gpsData); scene.add(gpsCloud); var sphereGeometry = new THREE.SphereGeometry(0.1, 32, 32); var sphereMaterial = new THREE.MeshBasicMaterial({color: 0xff0000, shading: THREE.FlatShading}); pickLocation = new THREE.Mesh(sphereGeometry, sphereMaterial); scene.add(pickLocation); //addCar2(); // controls camera.position.set(0,0,0); //controls = new THREE.OrbitControls(camera); //controls.target.set( 0, 100, 0 ); //camera.lookAt(new THREE.Vector3(0,100,0)); document.addEventListener( 'mousemove', onDocumentMouseMove, false ); window.addEventListener( 'resize', onWindowResize, false ); } function onDocumentMouseMove( event ) { event.preventDefault(); mouse.x = ( event.clientX / window.innerWidth ) * 2 - 1; mouse.y = - ( event.clientY / window.innerHeight ) * 2 + 1; } function animate() { requestAnimationFrame( animate ); render(); } var count = 0; function render() { camera.updateMatrixWorld(true); vector = new THREE.Vector3( mouse.x, mouse.y, 0.5 ); projector.unprojectVector( vector, camera ); raycaster.params = {"PointCloud" : {threshold: 0.1}}; raycaster.ray.set( camera.position, vector.sub( camera.position ).normalize() ); var intersects = raycaster.intersectObject(pointcloud); if(intersects.length > 0){ pickLocation.position.copy(intersects[0].point); // Paint the points with the cursor while pressing <shift> if (shiftKey) { var pointColors = geometry.attributes.color.array; for (var i = 0; i < intersects.length; i++) { var index = 3*intersects[i].index; pointColors[index] = 255; pointColors[index+1] = 255; pointColors[index+2] = 255; } geometry.attributes.color.needsUpdate = true; } } //var timer = Date.now() * 0.0005; //camera.position.y += Math.abs(Math.cos( timer )) *.3 ; //camera.position.z += Math.cos( timer ) * 0.03; positionArr = gpsData[count]; camera.position.y = gpsData[count+1][0]; camera.position.z = gpsData[count+1][1]; camera.position.x = gpsData[count+1][2]; console.log(camera.position.y) lookAtArr = gpsData[count + 30]; target.y = gpsData[count + 5][0]; target.z = gpsData[count + 1][1]; target.x = gpsData[count + 1][2]; //camera.position.set(new THREE.Vector3(positionArr[2],positionArr[0],positionArr[1])); //camera.lookAt(new THREE.Vector3(0,100,0)); camera.lookAt(target); renderer.render( scene, camera ); renderer.render(scene, camera); count++; console.log(count) } init(); animate();
adds lane, adds variable thickness
public/demo.js
adds lane, adds variable thickness
<ide><path>ublic/demo.js <ide> //todo: not make these globals since multiple things are starting to use geometry <add>//please don't remove commented code <ide> var renderer; <ide> var camera; <ide> var scene; <ide> var projector, raycaster; <ide> var dataFile = "files/datafile.json"; <ide> var gpsFile = "files/gpsfile.json"; <add>var lanesFile = "files/lanesfile.json"; <ide> var shiftKey = false; <ide> var gpsData; <ide> <ide> return data; <ide> } <ide> <del> function generatePointCloud(data) { <add> function generatePointCloud(data, size, color) { <ide> var geometry = new THREE.BufferGeometry(); <ide> var positions = new Float32Array(3*data.length); <ide> var colors = new Float32Array(3*data.length); <ide> colors[3*i+2] = HUEtoRGB(hue); //g <ide> colors[3*i+0] = HUEtoRGB(hue-1/3); //b <ide> }else{ <del> colors[3*i+1] = 240; //r <del> colors[3*i+2] = 240; //g <del> colors[3*i+0] = 240; <add> colors[3*i+1] = color; //r <add> colors[3*i+2] = color; //g <add> colors[3*i+0] = color; <ide> } <ide> } <ide> <ide> geometry.addAttribute('position', new THREE.BufferAttribute(positions, 3)); <ide> geometry.addAttribute('color', new THREE.BufferAttribute(colors, 3)); <ide> <del> var material = new THREE.PointCloudMaterial({ size: 0.01, vertexColors: true }); <add> var material = new THREE.PointCloudMaterial({ size: size, vertexColors: true }); <ide> var pointcloud = new THREE.PointCloud(geometry, material); <ide> <ide> return pointcloud; <ide> document.body.appendChild(renderer.domElement); <ide> <ide> var pointData = loadPoints(dataFile) <del> pointcloud = generatePointCloud(pointData); <add> pointcloud = generatePointCloud(pointData, 0.01); <ide> scene.add(pointcloud); <ide> gpsData = loadPoints(gpsFile) <del> gpsCloud = generatePointCloud(gpsData); <del> scene.add(gpsCloud); <add> gpsCloud = generatePointCloud(gpsData, 0.05, 250); <add> lanesData = loadPoints(lanesFile); <add> for (var lane in lanesData){ <add> laneCloud = generatePointCloud(lanesData[lane], 0.15, 255); <add> scene.add(laneCloud); <add> } <add> <ide> <ide> var sphereGeometry = new THREE.SphereGeometry(0.1, 32, 32); <ide> var sphereMaterial = new THREE.MeshBasicMaterial({color: 0xff0000, shading: THREE.FlatShading}); <ide> } <ide> } <ide> //var timer = Date.now() * 0.0005; <del> <ide> //camera.position.y += Math.abs(Math.cos( timer )) *.3 ; <ide> //camera.position.z += Math.cos( timer ) * 0.03; <ide> positionArr = gpsData[count]; <ide> camera.position.y = gpsData[count+1][0]; <ide> camera.position.z = gpsData[count+1][1]; <ide> camera.position.x = gpsData[count+1][2]; <del> console.log(camera.position.y) <del> lookAtArr = gpsData[count + 30]; <ide> target.y = gpsData[count + 5][0]; <ide> target.z = gpsData[count + 1][1]; <ide> target.x = gpsData[count + 1][2];
Java
apache-2.0
ff3309097ece7cea196416a4ee13ab6d9bf4a2f4
0
googleinterns/cloudsearch-ai,googleinterns/cloudsearch-ai,googleinterns/cloudsearch-ai,googleinterns/cloudsearch-ai
package com.google.cloudsearch.ai; import com.google.common.collect.Multimap; import org.json.simple.JSONObject; import org.json.simple.parser.JSONParser; import java.io.FileReader; import java.util.List; import org.apache.log4j.Logger; /** * AI Skill Driver manages the creation and execution of skills. */ public class AISkillDriver { private static AISkillSet skillSet; private static Logger log = Logger.getLogger(AISkillDriver.class.getName()); /** * Initialize the Driver * @param aiConfigName File path of the Configuration * @param schemaName File path of CloudSearch Schema * @throws Exception Throws Exception if skill setup fails */ public static void initialize(String aiConfigName, String schemaName) throws Exception { JSONParser parser = new JSONParser(); JSONObject schema = (JSONObject) parser.parse(new FileReader(schemaName)); JSONObject aiConfig = (JSONObject) parser.parse(new FileReader(aiConfigName)); skillSet = new AISkillSet(aiConfig, schema); for(AISkill skill : skillSet.getSkills()) { skill.setupSkill(); } } /** * Populates the structured Data by executing the skills. * @param structuredData Multimap for storing the structured data. * @param contentOrURI CloudStorage URI or File content in String format. */ public static void populateStructuredData(String contentOrURI, Multimap<String, Object> structuredData) { List<AISkill> skillList = (List<AISkill>) skillSet.getSkills(); if(skillList == null) { log.error("No skills Specified. Initialize the driver before calling populateStructuredData."); return; } skillList.forEach(skill -> { skill.executeSkill(contentOrURI, structuredData); }); } /** * Handles skill shutdown. */ public static void closeSkillDriver() throws NullPointerException { List<AISkill> skillList = (List<AISkill>) skillSet.getSkills(); if(skillList == null) { log.error("AISkill List is not initialized. Call AISkillDriver.initialize() before calling closeSkillDriver()"); return; } skillList.forEach(skill -> { skill.shutdownSkill(); }); } }
indexer/ai/src/main/java/com/google/cloudsearch/ai/AISkillDriver.java
package com.google.cloudsearch.ai; import com.google.common.collect.Multimap; import org.json.simple.JSONObject; import org.json.simple.parser.JSONParser; import java.io.FileReader; import java.util.List; import org.apache.log4j.Logger; /** * AI Skill Driver manages the creation and execution of skills. */ public class AISkillDriver { private static AISkillSet skillSet; private static Logger log = Logger.getLogger(AISkillDriver.class.getName()); /** * Initialize the Driver * @param aiConfigName File path of the Configuration * @param schemaName File path of CloudSearch Schema * @throws Exception Throws Exception if skill setup fails */ public static void initialize(String aiConfigName, String schemaName) throws Exception { JSONParser parser = new JSONParser(); JSONObject schema = (JSONObject) parser.parse(new FileReader(schemaName)); JSONObject aiConfig = (JSONObject) parser.parse(new FileReader(aiConfigName)); skillSet = new AISkillSet(aiConfig, schema); for(AISkill skill : skillSet.getSkills()) { skill.setupSkill(); } } /** * Populates the structured Data by executing the skills. * @param structuredData Multimap for storing the structured data. * @param contentOrURI CloudStorage URI or File content in String format. */ public static void populateStructuredData(String contentOrURI, Multimap<String, Object> structuredData) { List<AISkill> skillList = (List<AISkill>) skillSet.getSkills(); if(skillList == null) { log.info("No skills Specified. Initialize the driver before calling populateStructuredData."); } for(AISkill skill : skillList) { skill.executeSkill(contentOrURI, structuredData); } } /** * Handles skill shutdown. */ public static void closeSkillDriver() throws NullPointerException { try { List<AISkill> skillList = (List<AISkill>) skillSet.getSkills(); for(AISkill skill : skillList) { skill.shutdownSkill(); } } catch (NullPointerException e) { throw new NullPointerException("AISkill List is not initialized. Call AISkillDriver.initialize() before calling closeSkillDriver()"); } } }
Use Lambda Expressions
indexer/ai/src/main/java/com/google/cloudsearch/ai/AISkillDriver.java
Use Lambda Expressions
<ide><path>ndexer/ai/src/main/java/com/google/cloudsearch/ai/AISkillDriver.java <ide> * @param contentOrURI CloudStorage URI or File content in String format. <ide> */ <ide> public static void populateStructuredData(String contentOrURI, Multimap<String, Object> structuredData) { <del> <ide> List<AISkill> skillList = (List<AISkill>) skillSet.getSkills(); <ide> if(skillList == null) { <del> log.info("No skills Specified. Initialize the driver before calling populateStructuredData."); <add> log.error("No skills Specified. Initialize the driver before calling populateStructuredData."); <add> return; <ide> } <del> for(AISkill skill : skillList) { <add> skillList.forEach(skill -> { <ide> skill.executeSkill(contentOrURI, structuredData); <del> } <add> }); <ide> } <ide> <ide> /** <ide> * Handles skill shutdown. <ide> */ <ide> public static void closeSkillDriver() throws NullPointerException { <del> try { <del> List<AISkill> skillList = (List<AISkill>) skillSet.getSkills(); <del> for(AISkill skill : skillList) { <del> skill.shutdownSkill(); <del> } <add> List<AISkill> skillList = (List<AISkill>) skillSet.getSkills(); <add> if(skillList == null) { <add> log.error("AISkill List is not initialized. Call AISkillDriver.initialize() before calling closeSkillDriver()"); <add> return; <ide> } <del> catch (NullPointerException e) { <del> throw new NullPointerException("AISkill List is not initialized. Call AISkillDriver.initialize() before calling closeSkillDriver()"); <del> } <add> skillList.forEach(skill -> { <add> skill.shutdownSkill(); <add> }); <ide> } <ide> }
Java
apache-2.0
5d5ef60e1930cf14e2930bd8b1639e61a26ed564
0
vlsi/calcite,apache/calcite,adeshr/incubator-calcite,datametica/calcite,yeongwei/incubator-calcite,sudheeshkatkam/incubator-calcite,sreev/incubator-calcite,apache/calcite,datametica/calcite,mehant/incubator-calcite,looker-open-source/calcite-avatica,jcamachor/calcite,yeongwei/incubator-calcite,looker-open-source/calcite,looker-open-source/calcite,YrAuYong/incubator-calcite,sudheeshkatkam/incubator-calcite,jcamachor/calcite,wanglan/calcite,xhoong/incubator-calcite,arina-ielchiieva/calcite,yeongwei/incubator-calcite,joshelser/incubator-calcite,YrAuYong/incubator-calcite,googleinterns/calcite,b-slim/calcite,hsuanyi/incubator-calcite,dindin5258/calcite,vlsi/calcite,looker-open-source/calcite,datametica/calcite,jcamachor/calcite,joshelser/incubator-calcite,amoghmargoor/incubator-calcite,googleinterns/calcite,apache/calcite,apache/calcite,apache/calcite-avatica,hsuanyi/incubator-calcite,apache/calcite-avatica,minji-kim/calcite,jinfengni/incubator-optiq,minji-kim/calcite,arina-ielchiieva/calcite,julianhyde/calcite,glimpseio/incubator-calcite,sreev/incubator-calcite,jinfengni/incubator-optiq,amoghmargoor/incubator-calcite,dindin5258/calcite,googleinterns/calcite,adeshr/incubator-calcite,joshelser/calcite-avatica,joshelser/calcite-avatica,dindin5258/calcite,minji-kim/calcite,looker-open-source/calcite-avatica,b-slim/calcite,julianhyde/linq4j,mehant/incubator-calcite,glimpseio/incubator-calcite,YrAuYong/incubator-calcite,adeshr/incubator-calcite,hsuanyi/incubator-calcite,datametica/calcite,apache/calcite,sreev/incubator-calcite,julianhyde/calcite,sudheeshkatkam/incubator-calcite,wanglan/calcite,apache/calcite,julianhyde/calcite,yeongwei/incubator-calcite,looker-open-source/calcite,jcamachor/calcite,googleinterns/calcite,dindin5258/calcite,vlsi/incubator-calcite,apache/calcite-avatica,amoghmargoor/incubator-calcite,arina-ielchiieva/calcite,vlsi/calcite,julianhyde/calcite,apache/calcite-avatica,b-slim/calcite,looker-open-source/calcite,arina-ielchiieva/calcite,glimpseio/incubator-calcite,jcamachor/calcite,sreev/incubator-calcite,mapr/incubator-calcite,amoghmargoor/incubator-calcite,dindin5258/calcite,jinfengni/optiq,apache/incubator-optiq-linq4j,looker-open-source/calcite-avatica,b-slim/calcite,vlsi/calcite,wanglan/calcite,joshelser/calcite-avatica,mapr/incubator-calcite,datametica/calcite,dindin5258/calcite,jinfengni/optiq,vlsi/incubator-calcite,julianhyde/calcite,sudheeshkatkam/incubator-calcite,vlsi/calcite,wanglan/calcite,xhoong/incubator-calcite,looker-open-source/calcite-avatica,glimpseio/incubator-calcite,joshelser/incubator-calcite,looker-open-source/calcite-avatica,minji-kim/calcite,vlsi/calcite,julianhyde/calcite,adeshr/incubator-calcite,joshelser/incubator-calcite,looker-open-source/calcite,devth/calcite,jcamachor/calcite,googleinterns/calcite,xhoong/incubator-calcite,arina-ielchiieva/calcite,googleinterns/calcite,b-slim/calcite,hsuanyi/incubator-calcite,minji-kim/calcite,datametica/calcite,YrAuYong/incubator-calcite,xhoong/incubator-calcite,apache/calcite-avatica,devth/calcite
/* // Licensed to Julian Hyde under one or more contributor license // agreements. See the NOTICE file distributed with this work for // additional information regarding copyright ownership. // // Julian Hyde 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 net.hydromatic.linq4j.test; import net.hydromatic.linq4j.*; import net.hydromatic.linq4j.expressions.*; import net.hydromatic.linq4j.function.*; import junit.framework.TestCase; import java.util.*; /** * Tests for LINQ4J. */ public class Linq4jTest extends TestCase { public static final Function1<Employee, String> EMP_NAME_SELECTOR = new Function1<Employee, String>() { public String apply(Employee employee) { return employee.name; } }; public static final Function1<Employee, Integer> EMP_DEPTNO_SELECTOR = new Function1<Employee, Integer>() { public Integer apply(Employee employee) { return employee.deptno; } }; public static final Function1<Employee, Integer> EMP_EMPNO_SELECTOR = new Function1<Employee, Integer>() { public Integer apply(Employee employee) { return employee.empno; } }; public static final Function1<Department, Enumerable<Employee>> DEPT_EMPLOYEES_SELECTOR = new Function1<Department, Enumerable<Employee>>() { public Enumerable<Employee> apply(Department a0) { return Linq4j.asEnumerable(a0.employees); } }; public static final Function1<Department, String> DEPT_NAME_SELECTOR = new Function1<Department, String>() { public String apply(Department department) { return department.name; } }; public static final Function1<Department, Integer> DEPT_DEPTNO_SELECTOR = new Function1<Department, Integer>() { public Integer apply(Department department) { return department.deptno; } }; public static final IntegerFunction1<Department> DEPT_DEPTNO_SELECTOR2 = new IntegerFunction1<Department>() { public int apply(Department department) { return department.deptno; } }; public static final Function1<Object, Integer> ONE_SELECTOR = new Function1<Object, Integer>() { public Integer apply(Object employee) { return 1; } }; private static final Function2<Object, Object, Integer> PAIR_SELECTOR = new Function2<Object, Object, Integer>() { public Integer apply(Object employee, Object v2) { return 1; } }; public void testSelect() { List<String> names = Linq4j.asEnumerable(emps) .select(EMP_NAME_SELECTOR) .toList(); assertEquals("[Fred, Bill, Eric, Janet]", names.toString()); } public void testWhere() { List<String> names = Linq4j.asEnumerable(emps) .where( new Predicate1<Employee>() { public boolean apply(Employee employee) { return employee.deptno < 15; } }) .select(EMP_NAME_SELECTOR) .toList(); assertEquals("[Fred, Eric, Janet]", names.toString()); } public void testWhereIndexed() { // Returns every other employee. List<String> names = Linq4j.asEnumerable(emps) .where( new Predicate2<Employee, Integer>() { public boolean apply(Employee employee, Integer n) { return n % 2 == 0; } }) .select(EMP_NAME_SELECTOR) .toList(); assertEquals("[Fred, Eric]", names.toString()); } public void testSelectMany() { final List<String> nameSeqs = Linq4j.asEnumerable(depts) .selectMany(DEPT_EMPLOYEES_SELECTOR) .select( new Function2<Employee, Integer, String>() { public String apply(Employee v1, Integer v2) { return "#" + v2 + ": " + v1.name; } }) .toList(); assertEquals( "[#0: Fred, #1: Eric, #2: Janet, #3: Bill]", nameSeqs.toString()); } public void testCount() { final int count = Linq4j.asEnumerable(depts).count(); assertEquals(3, count); } public void testCountPredicate() { final int count = Linq4j.asEnumerable(depts).count( new Predicate1<Department>() { public boolean apply(Department v1) { return v1.employees.size() > 0; } }); assertEquals(2, count); } public void testLongCount() { final long count = Linq4j.asEnumerable(depts).longCount(); assertEquals(3, count); } public void testLongCountPredicate() { final long count = Linq4j.asEnumerable(depts).longCount( new Predicate1<Department>() { public boolean apply(Department v1) { return v1.employees.size() > 0; } }); assertEquals(2, count); } public void testAverageSelector() { assertEquals( 20, Linq4j.asEnumerable(depts).average(DEPT_DEPTNO_SELECTOR2)); } public void testMin() { assertEquals( 10, (int) Linq4j.asEnumerable(depts).select(DEPT_DEPTNO_SELECTOR) .min()); } public void testMinSelector() { assertEquals( 10, (int) Linq4j.asEnumerable(depts).min(DEPT_DEPTNO_SELECTOR)); } public void testMinSelector2() { assertEquals( 10, Linq4j.asEnumerable(depts).min(DEPT_DEPTNO_SELECTOR2)); } public void testMax() { assertEquals( 30, (int) Linq4j.asEnumerable(depts).select(DEPT_DEPTNO_SELECTOR) .max()); } public void testMaxSelector() { assertEquals( 30, (int) Linq4j.asEnumerable(depts).max(DEPT_DEPTNO_SELECTOR)); } public void testMaxSelector2() { assertEquals( 30, Linq4j.asEnumerable(depts).max(DEPT_DEPTNO_SELECTOR2)); } public void testAggregate() { assertEquals( "Sales,HR,Marketing", Linq4j.asEnumerable(depts) .select(DEPT_NAME_SELECTOR) .aggregate( null, new Function2<String, String, String>() { public String apply(String v1, String v2) { return v1 == null ? v2 : v1 + "," + v2; } })); } public void testToMap() { final Map<Integer, Employee> map = Linq4j.asEnumerable(emps) .toMap(EMP_EMPNO_SELECTOR); assertEquals(4, map.size()); assertTrue(map.get(110).name.equals("Bill")); } public void testToMap2() { final Map<Integer, Integer> map = Linq4j.asEnumerable(emps) .toMap(EMP_EMPNO_SELECTOR, EMP_DEPTNO_SELECTOR); assertEquals(4, map.size()); assertTrue(map.get(110) == 30); } public void testToLookup() { final Lookup<Integer, Employee> lookup = Linq4j.asEnumerable(emps).toLookup( EMP_DEPTNO_SELECTOR); int n = 0; for (Grouping<Integer, Employee> grouping : lookup) { ++n; switch (grouping.getKey()) { case 10: assertEquals(3, grouping.count()); break; case 30: assertEquals(1, grouping.count()); break; default: fail("unknown department number " + grouping); } } assertEquals(n, 2); } public void testToLookupSelector() { final Lookup<Integer, String> lookup = Linq4j.asEnumerable(emps).toLookup( EMP_DEPTNO_SELECTOR, EMP_NAME_SELECTOR); int n = 0; for (Grouping<Integer, String> grouping : lookup) { ++n; switch (grouping.getKey()) { case 10: assertEquals(3, grouping.count()); assertTrue(grouping.contains("Fred")); assertTrue(grouping.contains("Eric")); assertTrue(grouping.contains("Janet")); assertFalse(grouping.contains("Bill")); break; case 30: assertEquals(1, grouping.count()); assertTrue(grouping.contains("Bill")); assertFalse(grouping.contains("Fred")); break; default: fail("unknown department number " + grouping); } } assertEquals(n, 2); assertEquals( "[10:3, 30:1]", lookup.applyResultSelector( new Function2<Integer, Enumerable<String>, String>() { public String apply(Integer v1, Enumerable<String> v2) { return v1 + ":" + v2.count(); } }) .orderBy(Functions.<String>identitySelector()) .toList().toString()); } public void testToLookupSelectorComparer() { final Lookup<String, Employee> lookup = Linq4j.asEnumerable(emps).toLookup( EMP_NAME_SELECTOR, new EqualityComparer<String>() { public boolean equal(String v1, String v2) { return v1.length() == v2.length(); } public int hashCode(String s) { return s.length(); } }); assertEquals(2, lookup.size()); assertEquals( "[Fred, Janet]", new TreeSet<String>(lookup.keySet()).toString()); StringBuilder buf = new StringBuilder(); for (Grouping<String, Employee> grouping : lookup.orderBy( Linq4jTest.<String, Employee>groupingKeyExtractor())) { buf.append(grouping).append("\n"); } assertEquals( "Fred: [Employee(name: Fred, deptno:10), Employee(name: Bill, deptno:30), Employee(name: Eric, deptno:10)]\n" + "Janet: [Employee(name: Janet, deptno:10)]\n", buf.toString()); } private static <K extends Comparable, V> Function1<Grouping<K, V>, K> groupingKeyExtractor() { return new Function1<Grouping<K, V>, K>() { public K apply(Grouping<K, V> a0) { return a0.getKey(); } }; } /** * Tests the version of {@link ExtendedEnumerable#groupBy} * that uses an accumulator; does not build intermediate lists. */ public void testGroupBy() { String s = Linq4j.asEnumerable(emps) .groupBy( EMP_DEPTNO_SELECTOR, new Function0<String>() { public String apply() { return null; } }, new Function2<String, Employee, String>() { public String apply(String v1, Employee e0) { return v1 == null ? e0.name : (v1 + "+" + e0.name); } }, new Function2<Integer, String, String>() { public String apply(Integer v1, String v2) { return v1 + ": " + v2; } } ) .orderBy(Functions.<String>identitySelector()) .toList() .toString(); assertEquals( "[10: Fred+Eric+Janet, 30: Bill]", s); } /** * Tests the version of * {@link ExtendedEnumerable#aggregate} * that has a result selector. Note how similar it is to * {@link #testGroupBy()}. */ public void testAggregate2() { String s = Linq4j.asEnumerable(emps) .aggregate( new Function0<String>() { public String apply() { return null; } }.apply(), new Function2<String, Employee, String>() { public String apply(String v1, Employee e0) { return v1 == null ? e0.name : (v1 + "+" + e0.name); } }, new Function1<String, String>() { public String apply(String v2) { return "<no key>: " + v2; } }) .toString(); assertEquals( "<no key>: Fred+Bill+Eric+Janet", s); } public void testCast() { final List<Number> numbers = Arrays.asList((Number) 2, null, 3.14, 5); final Enumerator<Integer> enumerator = Linq4j.asEnumerable(numbers) .cast(Integer.class) .enumerator(); checkCast(enumerator); } public void testIterableCast() { final List<Number> numbers = Arrays.asList((Number) 2, null, 3.14, 5); final Enumerator<Integer> enumerator = Linq4j.cast(numbers, Integer.class) .enumerator(); checkCast(enumerator); } private void checkCast(Enumerator<Integer> enumerator) { assertTrue(enumerator.moveNext()); assertEquals(Integer.valueOf(2), enumerator.current()); assertTrue(enumerator.moveNext()); assertNull(enumerator.current()); assertTrue(enumerator.moveNext()); try { Object x = enumerator.current(); fail("expected error, got " + x); } catch (ClassCastException e) { // good } assertTrue(enumerator.moveNext()); assertEquals(Integer.valueOf(5), enumerator.current()); assertFalse(enumerator.moveNext()); enumerator.reset(); assertTrue(enumerator.moveNext()); assertEquals(Integer.valueOf(2), enumerator.current()); } public void testOfType() { final List<Number> numbers = Arrays.asList((Number) 2, null, 3.14, 5); final Enumerator<Integer> enumerator = Linq4j.asEnumerable(numbers) .ofType(Integer.class) .enumerator(); checkIterable(enumerator); } public void testIterableOfType() { final List<Number> numbers = Arrays.asList((Number) 2, null, 3.14, 5); final Enumerator<Integer> enumerator = Linq4j.ofType(numbers, Integer.class) .enumerator(); checkIterable(enumerator); } private void checkIterable(Enumerator<Integer> enumerator) { assertTrue(enumerator.moveNext()); assertEquals(Integer.valueOf(2), enumerator.current()); assertTrue(enumerator.moveNext()); assertNull(enumerator.current()); assertTrue(enumerator.moveNext()); assertEquals(Integer.valueOf(5), enumerator.current()); assertFalse(enumerator.moveNext()); enumerator.reset(); assertTrue(enumerator.moveNext()); assertEquals(Integer.valueOf(2), enumerator.current()); } public void testConcat() { assertEquals( 5, Linq4j.asEnumerable(emps) .concat(Linq4j.asEnumerable(badEmps)) .count()); } public void testUnion() { assertEquals( 5, Linq4j.asEnumerable(emps) .union(Linq4j.asEnumerable(badEmps)) .union(Linq4j.asEnumerable(emps)) .count()); } public void testIntersect() { final Employee[] emps2 = { new Employee(150, "Theodore", 10), emps[3], }; assertEquals( 1, Linq4j.asEnumerable(emps) .intersect(Linq4j.asEnumerable(emps2)) .count()); } public void testExcept() { final Employee[] emps2 = { new Employee(150, "Theodore", 10), emps[3], }; assertEquals( 3, Linq4j.asEnumerable(emps) .except(Linq4j.asEnumerable(emps2)) .count()); } public void testGroupJoin() { // Note #1: Group join is a "left join": "bad employees" are filtered // out, but empty departments are not. // Note #2: Order of departments is preserved. String s = Linq4j.asEnumerable(depts) .groupJoin( Linq4j.asEnumerable(emps) .concat(Linq4j.asEnumerable(badEmps)), DEPT_DEPTNO_SELECTOR, EMP_DEPTNO_SELECTOR, new Function2<Department, Enumerable<Employee>, String>() { public String apply( Department v1, Enumerable<Employee> v2) { final StringBuilder buf = new StringBuilder("["); int n = 0; for (Employee employee : v2) { if (n++ > 0) { buf.append(", "); } buf.append(employee.name); } return buf.append("] work(s) in ").append(v1.name) .toString(); } } ).toList() .toString(); assertEquals( "[[Fred, Eric, Janet] work(s) in Sales, " + "[] work(s) in HR, " + "[Bill] work(s) in Marketing]", s); } public void testJoin() { // Note #1: Inner on both sides. Employees with bad departments, // and departments with no employees are eliminated. // Note #2: Order of employees is preserved. String s = Linq4j.asEnumerable(emps) .concat(Linq4j.asEnumerable(badEmps)) .join( Linq4j.asEnumerable(depts), EMP_DEPTNO_SELECTOR, DEPT_DEPTNO_SELECTOR, new Function2<Employee, Department, String>() { public String apply(Employee v1, Department v2) { return v1.name + " works in " + v2.name; } }) .orderBy(Functions.<String>identitySelector()) .toList() .toString(); assertEquals( "[Bill works in Marketing, " + "Eric works in Sales, " + "Fred works in Sales, " + "Janet works in Sales]", s); } public void testJoinCartesianProduct() { int n = Linq4j.asEnumerable(emps) .<Department, Integer, Integer>join( Linq4j.asEnumerable(depts), (Function1) ONE_SELECTOR, (Function1) ONE_SELECTOR, (Function2) PAIR_SELECTOR) .count(); assertEquals(12, n); // 4 employees times 3 departments } @SuppressWarnings("unchecked") public void testCartesianProductEnumerator() { final Enumerable<String> abc = Linq4j.asEnumerable(Arrays.asList("a", "b", "c")); final Enumerable<String> xy = Linq4j.asEnumerable(Arrays.asList("x", "y")); final Enumerator<List<String>> product0 = Linq4j.product( Arrays.asList(Linq4j.<String>emptyEnumerator())); assertFalse(product0.moveNext()); final Enumerator<List<String>> productFullEmpty = Linq4j.product( Arrays.asList( abc.enumerator(), Linq4j.<String>emptyEnumerator())); assertFalse(productFullEmpty.moveNext()); final Enumerator<List<String>> productEmptyFull = Linq4j.product( Arrays.asList( abc.enumerator(), Linq4j.<String>emptyEnumerator())); assertFalse(productEmptyFull.moveNext()); final Enumerator<List<String>> productAbcXy = Linq4j.product( Arrays.asList(abc.enumerator(), xy.enumerator())); assertTrue(productAbcXy.moveNext()); assertEquals(Arrays.asList("a", "x"), productAbcXy.current()); assertTrue(productAbcXy.moveNext()); assertEquals(Arrays.asList("a", "y"), productAbcXy.current()); assertTrue(productAbcXy.moveNext()); assertEquals(Arrays.asList("b", "x"), productAbcXy.current()); assertTrue(productAbcXy.moveNext()); assertTrue(productAbcXy.moveNext()); assertTrue(productAbcXy.moveNext()); assertFalse(productAbcXy.moveNext()); } public void testAsQueryable() { // "count" is an Enumerable method. final int n = Linq4j.asEnumerable(emps) .asQueryable() .count(); assertEquals(4, n); // "where" is a Queryable method // first, use a lambda ParameterExpression parameter = Expressions.parameter(Employee.class); final Queryable<Employee> nh = Linq4j.asEnumerable(emps) .asQueryable() .where( Expressions.lambda( Predicate1.class, Expressions.equal( Expressions.field( parameter, Employee.class, "deptno"), Expressions.constant(10)), parameter)); assertEquals(3, nh.count()); // second, use an expression final Queryable<Employee> nh2 = Linq4j.asEnumerable(emps) .asQueryable() .where( Expressions.lambda( new Predicate1<Employee>() { public boolean apply(Employee v1) { return v1.deptno == 10; } } )); assertEquals(3, nh2.count()); // use lambda, this time call whereN ParameterExpression parameterE = Expressions.parameter(Employee.class); ParameterExpression parameterN = Expressions.parameter(Integer.TYPE); final Queryable<Employee> nh3 = Linq4j.asEnumerable(emps) .asQueryable() .whereN( Expressions.lambda( Predicate2.class, Expressions.andAlso( Expressions.equal( Expressions.field( parameterE, Employee.class, "deptno"), Expressions.constant(10)), Expressions.lessThan( parameterN, Expressions.constant(3))), parameterE, parameterN)); assertEquals(2, nh3.count()); } public void testTake_enumerable() { final Enumerable<Department> enumerableDepts = Linq4j.asEnumerable(depts); final List<Department> enumerableDeptsResult = EnumerableDefaults.take(enumerableDepts, 2).toList(); assertEquals(2, enumerableDeptsResult.size()); assertEquals(depts[0], enumerableDeptsResult.get(0)); assertEquals(depts[1], enumerableDeptsResult.get(1)); } public void testTake_queryable() { final Queryable<Department> querableDepts = Linq4j.asEnumerable(depts).asQueryable(); final List<Department> queryableResult = QueryableDefaults.take(querableDepts, 2).toList(); assertEquals(2, queryableResult.size()); assertEquals(depts[0], queryableResult.get(0)); assertEquals(depts[1], queryableResult.get(1)); } public void testTake_enumerable_zero_or_negative_size() { assertEquals( 0, EnumerableDefaults.take(Linq4j.asEnumerable(depts), 0) .toList().size()); assertEquals( 0, EnumerableDefaults.take(Linq4j.asEnumerable(depts), -2) .toList().size()); } public void testTake_queryable_zero_or_negative_size() { assertEquals( 0, QueryableDefaults.take(Linq4j.asEnumerable(depts).asQueryable(), 0) .toList().size()); assertEquals( 0, QueryableDefaults.take(Linq4j.asEnumerable(depts).asQueryable(), -2) .toList().size()); } public void testTake_enumerable_greater_than_length() { final Enumerable<Department> enumerableDepts = Linq4j.asEnumerable(depts); final List<Department> depList = EnumerableDefaults.take(enumerableDepts, 5).toList(); assertEquals(3, depList.size()); assertEquals(depts[0], depList.get(0)); assertEquals(depts[1], depList.get(1)); assertEquals(depts[2], depList.get(2)); } public void testTake_queryable_greater_than_length() { final Enumerable<Department> enumerableDepts = Linq4j.asEnumerable(depts); final List<Department> depList = EnumerableDefaults.take(enumerableDepts, 5).toList(); assertEquals(3, depList.size()); assertEquals(depts[0], depList.get(0)); assertEquals(depts[1], depList.get(1)); assertEquals(depts[2], depList.get(2)); } public void testTakeWhile_enumerable_predicate() { final Enumerable<Department> enumerableDepts = Linq4j.asEnumerable(depts); final List<Department> deptList = EnumerableDefaults.takeWhile( enumerableDepts, new Predicate1<Department>() { public boolean apply(Department v1) { return v1.name.contains("e"); } }).toList(); // Only one department: // 0: Sales --> true // 1: HR --> false // 2: Marketing --> never get to it (we stop after false) assertEquals(1, deptList.size()); assertEquals(depts[0], deptList.get(0)); } public void testTakeWhile_enumerable_function() { final Enumerable<Department> enumerableDepts = Linq4j.asEnumerable(depts); final List<Department> deptList = EnumerableDefaults.takeWhile( enumerableDepts, new Predicate2<Department, Integer>() { int index = 0; public boolean apply(Department v1, Integer v2) { // Make sure we're passed the correct indices assertEquals( "Invalid index passed to function", index++, (int) v2); return 20 != v1.deptno; } }).toList(); assertEquals(1, deptList.size()); assertEquals(depts[0], deptList.get(0)); } public void testTakeWhile_queryable_functionexpression_predicate() { final Queryable<Department> queryableDepts = Linq4j.asEnumerable(depts).asQueryable(); Predicate1<Department> predicate = new Predicate1<Department>() { public boolean apply(Department v1) { return "HR".equals(v1.name); } }; List<Department> deptList = QueryableDefaults.takeWhile( queryableDepts, Expressions.lambda(predicate)) .toList(); assertEquals(0, deptList.size()); predicate = new Predicate1<Department>() { public boolean apply(Department v1) { return "Sales".equals(v1.name); } }; deptList = QueryableDefaults.takeWhile( queryableDepts, Expressions.lambda(predicate)) .toList(); assertEquals(1, deptList.size()); assertEquals(depts[0], deptList.get(0)); } public void testTakeWhileN() { final Queryable<Department> queryableDepts = Linq4j.asEnumerable(depts).asQueryable(); Predicate2<Department, Integer> function2 = new Predicate2<Department, Integer>() { int index = 0; public boolean apply(Department v1, Integer v2) { // Make sure we're passed the correct indices assertEquals( "Invalid index passed to function", index++, (int) v2); return v2 < 2; } }; final List<Department> deptList = QueryableDefaults.takeWhileN( queryableDepts, Expressions.lambda(function2)) .toList(); assertEquals(2, deptList.size()); assertEquals(depts[0], deptList.get(0)); assertEquals(depts[1], deptList.get(1)); } public void testTakeWhileN_no_match() { final Queryable<Department> queryableDepts = Linq4j.asEnumerable(depts).asQueryable(); Predicate2<Department, Integer> function2 = Functions.falsePredicate2(); final List<Department> deptList = QueryableDefaults.takeWhileN( queryableDepts, Expressions.lambda(function2)) .toList(); assertEquals(0, deptList.size()); } public void testSkip() { assertEquals(2, Linq4j.asEnumerable(depts).skip(1).count()); assertEquals( 2, Linq4j.asEnumerable(depts).skipWhile( new Predicate1<Department>() { public boolean apply(Department v1) { return v1.name.equals("Sales"); } }).count()); assertEquals( 3, Linq4j.asEnumerable(depts).skipWhile( new Predicate1<Department>() { public boolean apply(Department v1) { return !v1.name.equals("Sales"); } }).count()); assertEquals( 1, Linq4j.asEnumerable(depts).skipWhile( new Predicate2<Department, Integer>() { public boolean apply(Department v1, Integer v2) { return v1.name.equals("Sales") || v2 == 1; } }).count()); assertEquals( 2, Linq4j.asEnumerable(depts).asQueryable().skip(1).count()); assertEquals( 1, Linq4j.asEnumerable(depts).asQueryable().skipWhileN( Expressions.<Predicate2<Department, Integer>>lambda( new Predicate2<Department, Integer>() { public boolean apply(Department v1, Integer v2) { return v1.name.equals("Sales") || v2 == 1; } })).count()); } public void testOrderBy() { // Note: sort is stable. Records occur Fred, Eric, Janet in input. assertEquals( "[Employee(name: Fred, deptno:10)," + " Employee(name: Eric, deptno:10)," + " Employee(name: Janet, deptno:10)," + " Employee(name: Bill, deptno:30)]", Linq4j.asEnumerable(emps).orderBy(EMP_DEPTNO_SELECTOR) .toList().toString()); } public void testOrderByComparator() { assertEquals( "[Employee(name: Bill, deptno:30)," + " Employee(name: Eric, deptno:10)," + " Employee(name: Fred, deptno:10)," + " Employee(name: Janet, deptno:10)]", Linq4j.asEnumerable(emps) .orderBy(EMP_NAME_SELECTOR) .orderBy( EMP_DEPTNO_SELECTOR, Collections.<Integer>reverseOrder()) .toList().toString()); } public void testOrderByInSeries() { // OrderBy in series works because sort is stable. assertEquals( "[Employee(name: Eric, deptno:10)," + " Employee(name: Fred, deptno:10)," + " Employee(name: Janet, deptno:10)," + " Employee(name: Bill, deptno:30)]", Linq4j.asEnumerable(emps) .orderBy(EMP_NAME_SELECTOR) .orderBy(EMP_DEPTNO_SELECTOR) .toList().toString()); } public void testOrderByDescending() { assertEquals( "[Employee(name: Janet, deptno:10)," + " Employee(name: Fred, deptno:10)," + " Employee(name: Eric, deptno:10)," + " Employee(name: Bill, deptno:30)]", Linq4j.asEnumerable(emps) .orderByDescending(EMP_NAME_SELECTOR) .toList().toString()); } public void testReverse() { assertEquals( "[Employee(name: Janet, deptno:10)," + " Employee(name: Eric, deptno:10)," + " Employee(name: Bill, deptno:30)," + " Employee(name: Fred, deptno:10)]", Linq4j.asEnumerable(emps) .reverse() .toList() .toString()); } public static class Employee { public final int empno; public final String name; public final int deptno; public Employee(int empno, String name, int deptno) { this.empno = empno; this.name = name; this.deptno = deptno; } public String toString() { return "Employee(name: " + name + ", deptno:" + deptno + ")"; } } public static class Department { public final String name; public final int deptno; public final List<Employee> employees; public Department(String name, int deptno, List<Employee> employees) { this.name = name; this.deptno = deptno; this.employees = employees; } public String toString() { return "Department(name: " + name + ", deptno:" + deptno + ", employees: " + employees + ")"; } } // Cedric works in a non-existent department. public static final Employee[] badEmps = { new Employee(140, "Cedric", 40), }; public static final Employee[] emps = { new Employee(100, "Fred", 10), new Employee(110, "Bill", 30), new Employee(120, "Eric", 10), new Employee(130, "Janet", 10), }; public static final Department[] depts = { new Department("Sales", 10, Arrays.asList(emps[0], emps[2], emps[3])), new Department("HR", 20, Collections.<Employee>emptyList()), new Department("Marketing", 30, Arrays.asList(emps[1])), }; } // End Linq4jTest.java
src/test/java/net/hydromatic/linq4j/test/Linq4jTest.java
/* // Licensed to Julian Hyde under one or more contributor license // agreements. See the NOTICE file distributed with this work for // additional information regarding copyright ownership. // // Julian Hyde 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 net.hydromatic.linq4j.test; import net.hydromatic.linq4j.*; import net.hydromatic.linq4j.expressions.*; import net.hydromatic.linq4j.function.*; import junit.framework.TestCase; import java.util.*; /** * Tests for LINQ4J. */ public class Linq4jTest extends TestCase { public static final Function1<Employee, String> EMP_NAME_SELECTOR = new Function1<Employee, String>() { public String apply(Employee employee) { return employee.name; } }; public static final Function1<Employee, Integer> EMP_DEPTNO_SELECTOR = new Function1<Employee, Integer>() { public Integer apply(Employee employee) { return employee.deptno; } }; public static final Function1<Employee, Integer> EMP_EMPNO_SELECTOR = new Function1<Employee, Integer>() { public Integer apply(Employee employee) { return employee.empno; } }; public static final Function1<Department, Enumerable<Employee>> DEPT_EMPLOYEES_SELECTOR = new Function1<Department, Enumerable<Employee>>() { public Enumerable<Employee> apply(Department a0) { return Linq4j.asEnumerable(a0.employees); } }; public static final Function1<Department, String> DEPT_NAME_SELECTOR = new Function1<Department, String>() { public String apply(Department department) { return department.name; } }; public static final Function1<Department, Integer> DEPT_DEPTNO_SELECTOR = new Function1<Department, Integer>() { public Integer apply(Department department) { return department.deptno; } }; public static final IntegerFunction1<Department> DEPT_DEPTNO_SELECTOR2 = new IntegerFunction1<Department>() { public int apply(Department department) { return department.deptno; } }; public static final Function1<Object, Integer> ONE_SELECTOR = new Function1<Object, Integer>() { public Integer apply(Object employee) { return 1; } }; private static final Function2<Object, Object, Integer> PAIR_SELECTOR = new Function2<Object, Object, Integer>() { public Integer apply(Object employee, Object v2) { return 1; } }; public void testSelect() { List<String> names = Linq4j.asEnumerable(emps) .select(EMP_NAME_SELECTOR) .toList(); assertEquals("[Fred, Bill, Eric, Janet]", names.toString()); } public void testWhere() { List<String> names = Linq4j.asEnumerable(emps) .where( new Predicate1<Employee>() { public boolean apply(Employee employee) { return employee.deptno < 15; } }) .select(EMP_NAME_SELECTOR) .toList(); assertEquals("[Fred, Eric, Janet]", names.toString()); } public void testWhereIndexed() { // Returns every other employee. List<String> names = Linq4j.asEnumerable(emps) .where( new Predicate2<Employee, Integer>() { public boolean apply(Employee employee, Integer n) { return n % 2 == 0; } }) .select(EMP_NAME_SELECTOR) .toList(); assertEquals("[Fred, Eric]", names.toString()); } public void testSelectMany() { final List<String> nameSeqs = Linq4j.asEnumerable(depts) .selectMany(DEPT_EMPLOYEES_SELECTOR) .select( new Function2<Employee, Integer, String>() { public String apply(Employee v1, Integer v2) { return "#" + v2 + ": " + v1.name; } }) .toList(); assertEquals( "[#0: Fred, #1: Eric, #2: Janet, #3: Bill]", nameSeqs.toString()); } public void testCount() { final int count = Linq4j.asEnumerable(depts).count(); assertEquals(3, count); } public void testCountPredicate() { final int count = Linq4j.asEnumerable(depts).count( new Predicate1<Department>() { public boolean apply(Department v1) { return v1.employees.size() > 0; } }); assertEquals(2, count); } public void testLongCount() { final long count = Linq4j.asEnumerable(depts).longCount(); assertEquals(3, count); } public void testLongCountPredicate() { final long count = Linq4j.asEnumerable(depts).longCount( new Predicate1<Department>() { public boolean apply(Department v1) { return v1.employees.size() > 0; } }); assertEquals(2, count); } public void testAverageSelector() { assertEquals( 20, Linq4j.asEnumerable(depts).average(DEPT_DEPTNO_SELECTOR2)); } public void testMin() { assertEquals( 10, (int) Linq4j.asEnumerable(depts).select(DEPT_DEPTNO_SELECTOR) .min()); } public void testMinSelector() { assertEquals( 10, (int) Linq4j.asEnumerable(depts).min(DEPT_DEPTNO_SELECTOR)); } public void testMinSelector2() { assertEquals( 10, Linq4j.asEnumerable(depts).min(DEPT_DEPTNO_SELECTOR2)); } public void testMax() { assertEquals( 30, (int) Linq4j.asEnumerable(depts).select(DEPT_DEPTNO_SELECTOR) .max()); } public void testMaxSelector() { assertEquals( 30, (int) Linq4j.asEnumerable(depts).max(DEPT_DEPTNO_SELECTOR)); } public void testMaxSelector2() { assertEquals( 30, Linq4j.asEnumerable(depts).max(DEPT_DEPTNO_SELECTOR2)); } public void testAggregate() { assertEquals( "Sales,HR,Marketing", Linq4j.asEnumerable(depts) .select(DEPT_NAME_SELECTOR) .aggregate( null, new Function2<String, String, String>() { public String apply(String v1, String v2) { return v1 == null ? v2 : v1 + "," + v2; } })); } public void testToMap() { final Map<Integer, Employee> map = Linq4j.asEnumerable(emps) .toMap(EMP_EMPNO_SELECTOR); assertEquals(4, map.size()); assertTrue(map.get(110).name.equals("Bill")); } public void testToMap2() { final Map<Integer, Integer> map = Linq4j.asEnumerable(emps) .toMap(EMP_EMPNO_SELECTOR, EMP_DEPTNO_SELECTOR); assertEquals(4, map.size()); assertTrue(map.get(110) == 30); } public void testToLookup() { final Lookup<Integer, Employee> lookup = Linq4j.asEnumerable(emps).toLookup( EMP_DEPTNO_SELECTOR); int n = 0; for (Grouping<Integer, Employee> grouping : lookup) { ++n; switch (grouping.getKey()) { case 10: assertEquals(3, grouping.count()); break; case 30: assertEquals(1, grouping.count()); break; default: fail("unknown department number " + grouping); } } assertEquals(n, 2); } public void testToLookupSelector() { final Lookup<Integer, String> lookup = Linq4j.asEnumerable(emps).toLookup( EMP_DEPTNO_SELECTOR, EMP_NAME_SELECTOR); int n = 0; for (Grouping<Integer, String> grouping : lookup) { ++n; switch (grouping.getKey()) { case 10: assertEquals(3, grouping.count()); assertTrue(grouping.contains("Fred")); assertTrue(grouping.contains("Eric")); assertTrue(grouping.contains("Janet")); assertFalse(grouping.contains("Bill")); break; case 30: assertEquals(1, grouping.count()); assertTrue(grouping.contains("Bill")); assertFalse(grouping.contains("Fred")); break; default: fail("unknown department number " + grouping); } } assertEquals(n, 2); assertEquals( "[10:3, 30:1]", lookup.applyResultSelector( new Function2<Integer, Enumerable<String>, Object>() { public Object apply(Integer v1, Enumerable<String> v2) { return v1 + ":" + v2.count(); } } ) .toList() .toString()); } public void testToLookupSelectorComparer() { final Lookup<String, Employee> lookup = Linq4j.asEnumerable(emps).toLookup( EMP_NAME_SELECTOR, new EqualityComparer<String>() { public boolean equal(String v1, String v2) { return v1.length() == v2.length(); } public int hashCode(String s) { return s.length(); } }); assertEquals(2, lookup.size()); assertEquals("[Fred, Janet]", lookup.keySet().toString()); StringBuilder buf = new StringBuilder(); for (Grouping<String, Employee> grouping : lookup) { buf.append(grouping).append("\n"); } assertEquals( "Fred: [Employee(name: Fred, deptno:10), Employee(name: Bill, deptno:30), Employee(name: Eric, deptno:10)]\n" + "Janet: [Employee(name: Janet, deptno:10)]\n", buf.toString()); } /** * Tests the version of {@link ExtendedEnumerable#groupBy} * that uses an accumulator; does not build intermediate lists. */ public void testGroupBy() { String s = Linq4j.asEnumerable(emps) .groupBy( EMP_DEPTNO_SELECTOR, new Function0<String>() { public String apply() { return null; } }, new Function2<String, Employee, String>() { public String apply(String v1, Employee e0) { return v1 == null ? e0.name : (v1 + "+" + e0.name); } }, new Function2<Integer, String, String>() { public String apply(Integer v1, String v2) { return v1 + ": " + v2; } }) .toList() .toString(); assertEquals( "[10: Fred+Eric+Janet, 30: Bill]", s); } /** * Tests the version of * {@link ExtendedEnumerable#aggregate} * that has a result selector. Note how similar it is to * {@link #testGroupBy()}. */ public void testAggregate2() { String s = Linq4j.asEnumerable(emps) .aggregate( new Function0<String>() { public String apply() { return null; } }.apply(), new Function2<String, Employee, String>() { public String apply(String v1, Employee e0) { return v1 == null ? e0.name : (v1 + "+" + e0.name); } }, new Function1<String, String>() { public String apply(String v2) { return "<no key>: " + v2; } }) .toString(); assertEquals( "<no key>: Fred+Bill+Eric+Janet", s); } public void testCast() { final List<Number> numbers = Arrays.asList((Number) 2, null, 3.14, 5); final Enumerator<Integer> enumerator = Linq4j.asEnumerable(numbers) .cast(Integer.class) .enumerator(); checkCast(enumerator); } public void testIterableCast() { final List<Number> numbers = Arrays.asList((Number) 2, null, 3.14, 5); final Enumerator<Integer> enumerator = Linq4j.cast(numbers, Integer.class) .enumerator(); checkCast(enumerator); } private void checkCast(Enumerator<Integer> enumerator) { assertTrue(enumerator.moveNext()); assertEquals(Integer.valueOf(2), enumerator.current()); assertTrue(enumerator.moveNext()); assertNull(enumerator.current()); assertTrue(enumerator.moveNext()); try { Object x = enumerator.current(); fail("expected error, got " + x); } catch (ClassCastException e) { // good } assertTrue(enumerator.moveNext()); assertEquals(Integer.valueOf(5), enumerator.current()); assertFalse(enumerator.moveNext()); enumerator.reset(); assertTrue(enumerator.moveNext()); assertEquals(Integer.valueOf(2), enumerator.current()); } public void testOfType() { final List<Number> numbers = Arrays.asList((Number) 2, null, 3.14, 5); final Enumerator<Integer> enumerator = Linq4j.asEnumerable(numbers) .ofType(Integer.class) .enumerator(); checkIterable(enumerator); } public void testIterableOfType() { final List<Number> numbers = Arrays.asList((Number) 2, null, 3.14, 5); final Enumerator<Integer> enumerator = Linq4j.ofType(numbers, Integer.class) .enumerator(); checkIterable(enumerator); } private void checkIterable(Enumerator<Integer> enumerator) { assertTrue(enumerator.moveNext()); assertEquals(Integer.valueOf(2), enumerator.current()); assertTrue(enumerator.moveNext()); assertNull(enumerator.current()); assertTrue(enumerator.moveNext()); assertEquals(Integer.valueOf(5), enumerator.current()); assertFalse(enumerator.moveNext()); enumerator.reset(); assertTrue(enumerator.moveNext()); assertEquals(Integer.valueOf(2), enumerator.current()); } public void testConcat() { assertEquals( 5, Linq4j.asEnumerable(emps) .concat(Linq4j.asEnumerable(badEmps)) .count()); } public void testUnion() { assertEquals( 5, Linq4j.asEnumerable(emps) .union(Linq4j.asEnumerable(badEmps)) .union(Linq4j.asEnumerable(emps)) .count()); } public void testIntersect() { final Employee[] emps2 = { new Employee(150, "Theodore", 10), emps[3], }; assertEquals( 1, Linq4j.asEnumerable(emps) .intersect(Linq4j.asEnumerable(emps2)) .count()); } public void testExcept() { final Employee[] emps2 = { new Employee(150, "Theodore", 10), emps[3], }; assertEquals( 3, Linq4j.asEnumerable(emps) .except(Linq4j.asEnumerable(emps2)) .count()); } public void testGroupJoin() { // Note #1: Group join is a "left join": "bad employees" are filtered // out, but empty departments are not. // Note #2: Order of departments is preserved. String s = Linq4j.asEnumerable(depts) .groupJoin( Linq4j.asEnumerable(emps) .concat(Linq4j.asEnumerable(badEmps)), DEPT_DEPTNO_SELECTOR, EMP_DEPTNO_SELECTOR, new Function2<Department, Enumerable<Employee>, String>() { public String apply( Department v1, Enumerable<Employee> v2) { final StringBuilder buf = new StringBuilder("["); int n = 0; for (Employee employee : v2) { if (n++ > 0) { buf.append(", "); } buf.append(employee.name); } return buf.append("] work(s) in ").append(v1.name) .toString(); } } ).toList() .toString(); assertEquals( "[[Fred, Eric, Janet] work(s) in Sales, " + "[] work(s) in HR, " + "[Bill] work(s) in Marketing]", s); } public void testJoin() { // Note #1: Inner on both sides. Employees with bad departments, // and departments with no employees are eliminated. // Note #2: Order of employees is preserved. String s = Linq4j.asEnumerable(emps) .concat(Linq4j.asEnumerable(badEmps)) .join( Linq4j.asEnumerable(depts), EMP_DEPTNO_SELECTOR, DEPT_DEPTNO_SELECTOR, new Function2<Employee, Department, String>() { public String apply(Employee v1, Department v2) { return v1.name + " works in " + v2.name; } }) .toList() .toString(); assertEquals( "[Fred works in Sales, " + "Eric works in Sales, " + "Janet works in Sales, " + "Bill works in Marketing]", s); } public void testJoinCartesianProduct() { int n = Linq4j.asEnumerable(emps) .<Department, Integer, Integer>join( Linq4j.asEnumerable(depts), (Function1) ONE_SELECTOR, (Function1) ONE_SELECTOR, (Function2) PAIR_SELECTOR) .count(); assertEquals(12, n); // 4 employees times 3 departments } @SuppressWarnings("unchecked") public void testCartesianProductEnumerator() { final Enumerable<String> abc = Linq4j.asEnumerable(Arrays.asList("a", "b", "c")); final Enumerable<String> xy = Linq4j.asEnumerable(Arrays.asList("x", "y")); final Enumerator<List<String>> product0 = Linq4j.product( Arrays.asList(Linq4j.<String>emptyEnumerator())); assertFalse(product0.moveNext()); final Enumerator<List<String>> productFullEmpty = Linq4j.product( Arrays.asList( abc.enumerator(), Linq4j.<String>emptyEnumerator())); assertFalse(productFullEmpty.moveNext()); final Enumerator<List<String>> productEmptyFull = Linq4j.product( Arrays.asList( abc.enumerator(), Linq4j.<String>emptyEnumerator())); assertFalse(productEmptyFull.moveNext()); final Enumerator<List<String>> productAbcXy = Linq4j.product( Arrays.asList(abc.enumerator(), xy.enumerator())); assertTrue(productAbcXy.moveNext()); assertEquals(Arrays.asList("a", "x"), productAbcXy.current()); assertTrue(productAbcXy.moveNext()); assertEquals(Arrays.asList("a", "y"), productAbcXy.current()); assertTrue(productAbcXy.moveNext()); assertEquals(Arrays.asList("b", "x"), productAbcXy.current()); assertTrue(productAbcXy.moveNext()); assertTrue(productAbcXy.moveNext()); assertTrue(productAbcXy.moveNext()); assertFalse(productAbcXy.moveNext()); } public void testAsQueryable() { // "count" is an Enumerable method. final int n = Linq4j.asEnumerable(emps) .asQueryable() .count(); assertEquals(4, n); // "where" is a Queryable method // first, use a lambda ParameterExpression parameter = Expressions.parameter(Employee.class); final Queryable<Employee> nh = Linq4j.asEnumerable(emps) .asQueryable() .where( Expressions.lambda( Predicate1.class, Expressions.equal( Expressions.field( parameter, Employee.class, "deptno"), Expressions.constant(10)), parameter)); assertEquals(3, nh.count()); // second, use an expression final Queryable<Employee> nh2 = Linq4j.asEnumerable(emps) .asQueryable() .where( Expressions.lambda( new Predicate1<Employee>() { public boolean apply(Employee v1) { return v1.deptno == 10; } } )); assertEquals(3, nh2.count()); // use lambda, this time call whereN ParameterExpression parameterE = Expressions.parameter(Employee.class); ParameterExpression parameterN = Expressions.parameter(Integer.TYPE); final Queryable<Employee> nh3 = Linq4j.asEnumerable(emps) .asQueryable() .whereN( Expressions.lambda( Predicate2.class, Expressions.andAlso( Expressions.equal( Expressions.field( parameterE, Employee.class, "deptno"), Expressions.constant(10)), Expressions.lessThan( parameterN, Expressions.constant(3))), parameterE, parameterN)); assertEquals(2, nh3.count()); } public void testTake_enumerable() { final Enumerable<Department> enumerableDepts = Linq4j.asEnumerable(depts); final List<Department> enumerableDeptsResult = EnumerableDefaults.take(enumerableDepts, 2).toList(); assertEquals(2, enumerableDeptsResult.size()); assertEquals(depts[0], enumerableDeptsResult.get(0)); assertEquals(depts[1], enumerableDeptsResult.get(1)); } public void testTake_queryable() { final Queryable<Department> querableDepts = Linq4j.asEnumerable(depts).asQueryable(); final List<Department> queryableResult = QueryableDefaults.take(querableDepts, 2).toList(); assertEquals(2, queryableResult.size()); assertEquals(depts[0], queryableResult.get(0)); assertEquals(depts[1], queryableResult.get(1)); } public void testTake_enumerable_zero_or_negative_size() { assertEquals( 0, EnumerableDefaults.take(Linq4j.asEnumerable(depts), 0) .toList().size()); assertEquals( 0, EnumerableDefaults.take(Linq4j.asEnumerable(depts), -2) .toList().size()); } public void testTake_queryable_zero_or_negative_size() { assertEquals( 0, QueryableDefaults.take(Linq4j.asEnumerable(depts).asQueryable(), 0) .toList().size()); assertEquals( 0, QueryableDefaults.take(Linq4j.asEnumerable(depts).asQueryable(), -2) .toList().size()); } public void testTake_enumerable_greater_than_length() { final Enumerable<Department> enumerableDepts = Linq4j.asEnumerable(depts); final List<Department> depList = EnumerableDefaults.take(enumerableDepts, 5).toList(); assertEquals(3, depList.size()); assertEquals(depts[0], depList.get(0)); assertEquals(depts[1], depList.get(1)); assertEquals(depts[2], depList.get(2)); } public void testTake_queryable_greater_than_length() { final Enumerable<Department> enumerableDepts = Linq4j.asEnumerable(depts); final List<Department> depList = EnumerableDefaults.take(enumerableDepts, 5).toList(); assertEquals(3, depList.size()); assertEquals(depts[0], depList.get(0)); assertEquals(depts[1], depList.get(1)); assertEquals(depts[2], depList.get(2)); } public void testTakeWhile_enumerable_predicate() { final Enumerable<Department> enumerableDepts = Linq4j.asEnumerable(depts); final List<Department> deptList = EnumerableDefaults.takeWhile( enumerableDepts, new Predicate1<Department>() { public boolean apply(Department v1) { return v1.name.contains("e"); } }).toList(); // Only one department: // 0: Sales --> true // 1: HR --> false // 2: Marketing --> never get to it (we stop after false) assertEquals(1, deptList.size()); assertEquals(depts[0], deptList.get(0)); } public void testTakeWhile_enumerable_function() { final Enumerable<Department> enumerableDepts = Linq4j.asEnumerable(depts); final List<Department> deptList = EnumerableDefaults.takeWhile( enumerableDepts, new Predicate2<Department, Integer>() { int index = 0; public boolean apply(Department v1, Integer v2) { // Make sure we're passed the correct indices assertEquals( "Invalid index passed to function", index++, (int) v2); return 20 != v1.deptno; } }).toList(); assertEquals(1, deptList.size()); assertEquals(depts[0], deptList.get(0)); } public void testTakeWhile_queryable_functionexpression_predicate() { final Queryable<Department> queryableDepts = Linq4j.asEnumerable(depts).asQueryable(); Predicate1<Department> predicate = new Predicate1<Department>() { public boolean apply(Department v1) { return "HR".equals(v1.name); } }; List<Department> deptList = QueryableDefaults.takeWhile( queryableDepts, Expressions.lambda(predicate)) .toList(); assertEquals(0, deptList.size()); predicate = new Predicate1<Department>() { public boolean apply(Department v1) { return "Sales".equals(v1.name); } }; deptList = QueryableDefaults.takeWhile( queryableDepts, Expressions.lambda(predicate)) .toList(); assertEquals(1, deptList.size()); assertEquals(depts[0], deptList.get(0)); } public void testTakeWhileN() { final Queryable<Department> queryableDepts = Linq4j.asEnumerable(depts).asQueryable(); Predicate2<Department, Integer> function2 = new Predicate2<Department, Integer>() { int index = 0; public boolean apply(Department v1, Integer v2) { // Make sure we're passed the correct indices assertEquals( "Invalid index passed to function", index++, (int) v2); return v2 < 2; } }; final List<Department> deptList = QueryableDefaults.takeWhileN( queryableDepts, Expressions.lambda(function2)) .toList(); assertEquals(2, deptList.size()); assertEquals(depts[0], deptList.get(0)); assertEquals(depts[1], deptList.get(1)); } public void testTakeWhileN_no_match() { final Queryable<Department> queryableDepts = Linq4j.asEnumerable(depts).asQueryable(); Predicate2<Department, Integer> function2 = Functions.falsePredicate2(); final List<Department> deptList = QueryableDefaults.takeWhileN( queryableDepts, Expressions.lambda(function2)) .toList(); assertEquals(0, deptList.size()); } public void testSkip() { assertEquals(2, Linq4j.asEnumerable(depts).skip(1).count()); assertEquals( 2, Linq4j.asEnumerable(depts).skipWhile( new Predicate1<Department>() { public boolean apply(Department v1) { return v1.name.equals("Sales"); } }).count()); assertEquals( 3, Linq4j.asEnumerable(depts).skipWhile( new Predicate1<Department>() { public boolean apply(Department v1) { return !v1.name.equals("Sales"); } }).count()); assertEquals( 1, Linq4j.asEnumerable(depts).skipWhile( new Predicate2<Department, Integer>() { public boolean apply(Department v1, Integer v2) { return v1.name.equals("Sales") || v2 == 1; } }).count()); assertEquals( 2, Linq4j.asEnumerable(depts).asQueryable().skip(1).count()); assertEquals( 1, Linq4j.asEnumerable(depts).asQueryable().skipWhileN( Expressions.<Predicate2<Department, Integer>>lambda( new Predicate2<Department, Integer>() { public boolean apply(Department v1, Integer v2) { return v1.name.equals("Sales") || v2 == 1; } })).count()); } public void testOrderBy() { // Note: sort is stable. Records occur Fred, Eric, Janet in input. assertEquals( "[Employee(name: Fred, deptno:10)," + " Employee(name: Eric, deptno:10)," + " Employee(name: Janet, deptno:10)," + " Employee(name: Bill, deptno:30)]", Linq4j.asEnumerable(emps).orderBy(EMP_DEPTNO_SELECTOR) .toList().toString()); } public void testOrderByComparator() { assertEquals( "[Employee(name: Bill, deptno:30)," + " Employee(name: Eric, deptno:10)," + " Employee(name: Fred, deptno:10)," + " Employee(name: Janet, deptno:10)]", Linq4j.asEnumerable(emps) .orderBy(EMP_NAME_SELECTOR) .orderBy( EMP_DEPTNO_SELECTOR, Collections.<Integer>reverseOrder()) .toList().toString()); } public void testOrderByInSeries() { // OrderBy in series works because sort is stable. assertEquals( "[Employee(name: Eric, deptno:10)," + " Employee(name: Fred, deptno:10)," + " Employee(name: Janet, deptno:10)," + " Employee(name: Bill, deptno:30)]", Linq4j.asEnumerable(emps) .orderBy(EMP_NAME_SELECTOR) .orderBy(EMP_DEPTNO_SELECTOR) .toList().toString()); } public void testOrderByDescending() { assertEquals( "[Employee(name: Janet, deptno:10)," + " Employee(name: Fred, deptno:10)," + " Employee(name: Eric, deptno:10)," + " Employee(name: Bill, deptno:30)]", Linq4j.asEnumerable(emps) .orderByDescending(EMP_NAME_SELECTOR) .toList().toString()); } public void testReverse() { assertEquals( "[Employee(name: Janet, deptno:10)," + " Employee(name: Eric, deptno:10)," + " Employee(name: Bill, deptno:30)," + " Employee(name: Fred, deptno:10)]", Linq4j.asEnumerable(emps) .reverse() .toList() .toString()); } public static class Employee { public final int empno; public final String name; public final int deptno; public Employee(int empno, String name, int deptno) { this.empno = empno; this.name = name; this.deptno = deptno; } public String toString() { return "Employee(name: " + name + ", deptno:" + deptno + ")"; } } public static class Department { public final String name; public final int deptno; public final List<Employee> employees; public Department(String name, int deptno, List<Employee> employees) { this.name = name; this.deptno = deptno; this.employees = employees; } public String toString() { return "Department(name: " + name + ", deptno:" + deptno + ", employees: " + employees + ")"; } } // Cedric works in a non-existent department. public static final Employee[] badEmps = { new Employee(140, "Cedric", 40), }; public static final Employee[] emps = { new Employee(100, "Fred", 10), new Employee(110, "Bill", 30), new Employee(120, "Eric", 10), new Employee(130, "Janet", 10), }; public static final Department[] depts = { new Department("Sales", 10, Arrays.asList(emps[0], emps[2], emps[3])), new Department("HR", 20, Collections.<Employee>emptyList()), new Department("Marketing", 30, Arrays.asList(emps[1])), }; } // End Linq4jTest.java
Make tests deterministic (fixes for JDK 1.8).
src/test/java/net/hydromatic/linq4j/test/Linq4jTest.java
Make tests deterministic (fixes for JDK 1.8).
<ide><path>rc/test/java/net/hydromatic/linq4j/test/Linq4jTest.java <ide> assertEquals( <ide> "[10:3, 30:1]", <ide> lookup.applyResultSelector( <del> new Function2<Integer, Enumerable<String>, Object>() { <del> public Object apply(Integer v1, Enumerable<String> v2) { <add> new Function2<Integer, Enumerable<String>, String>() { <add> public String apply(Integer v1, Enumerable<String> v2) { <ide> return v1 + ":" + v2.count(); <ide> } <del> } <del> ) <del> .toList() <del> .toString()); <add> }) <add> .orderBy(Functions.<String>identitySelector()) <add> .toList().toString()); <ide> } <ide> <ide> public void testToLookupSelectorComparer() { <ide> } <ide> }); <ide> assertEquals(2, lookup.size()); <del> assertEquals("[Fred, Janet]", lookup.keySet().toString()); <add> assertEquals( <add> "[Fred, Janet]", <add> new TreeSet<String>(lookup.keySet()).toString()); <ide> <ide> StringBuilder buf = new StringBuilder(); <del> for (Grouping<String, Employee> grouping : lookup) { <add> for (Grouping<String, Employee> grouping : lookup.orderBy( <add> Linq4jTest.<String, Employee>groupingKeyExtractor())) <add> { <ide> buf.append(grouping).append("\n"); <ide> } <ide> assertEquals( <ide> "Fred: [Employee(name: Fred, deptno:10), Employee(name: Bill, deptno:30), Employee(name: Eric, deptno:10)]\n" <ide> + "Janet: [Employee(name: Janet, deptno:10)]\n", <ide> buf.toString()); <add> } <add> <add> private static <K extends Comparable, V> Function1<Grouping<K, V>, K> <add> groupingKeyExtractor() { <add> return new Function1<Grouping<K, V>, K>() { <add> public K apply(Grouping<K, V> a0) { <add> return a0.getKey(); <add> } <add> }; <ide> } <ide> <ide> /** <ide> String s = <ide> Linq4j.asEnumerable(emps) <ide> .groupBy( <del> EMP_DEPTNO_SELECTOR, <del> new Function0<String>() { <add> EMP_DEPTNO_SELECTOR, new Function0<String>() { <ide> public String apply() { <ide> return null; <ide> } <del> }, <del> new Function2<String, Employee, String>() { <add> }, new Function2<String, Employee, String>() { <ide> public String apply(String v1, Employee e0) { <ide> return v1 == null ? e0.name : (v1 + "+" + e0.name); <ide> } <del> }, <del> new Function2<Integer, String, String>() { <add> }, new Function2<Integer, String, String>() { <ide> public String apply(Integer v1, String v2) { <ide> return v1 + ": " + v2; <ide> } <del> }) <add> } <add> ) <add> .orderBy(Functions.<String>identitySelector()) <ide> .toList() <ide> .toString(); <ide> assertEquals( <ide> return v1.name + " works in " + v2.name; <ide> } <ide> }) <add> .orderBy(Functions.<String>identitySelector()) <ide> .toList() <ide> .toString(); <ide> assertEquals( <del> "[Fred works in Sales, " <add> "[Bill works in Marketing, " <ide> + "Eric works in Sales, " <del> + "Janet works in Sales, " <del> + "Bill works in Marketing]", <add> + "Fred works in Sales, " <add> + "Janet works in Sales]", <ide> s); <ide> } <ide>
Java
apache-2.0
562574978f22dfef6c1ed6b3fdcc99e36235bbb9
0
Encaitar/GameOfLife
package GOL; import org.junit.*; import static org.junit.Assert.*; /* * Any live call with fewer than two live neighbours dies,as if caused by * under-population. * Any live cell with two or three live neighbours lives on to the next * generation. * Any live cell with more than three live neighbours dies, as if by * overcrowding. * Any dead cell with exactly three live neighbours becomes a live cell, as if * by reproduction. */ public class AllTests { /* * Rule 1: Any live cell with fewer than two live neighbours dies, as if * caused by under-population. * * A cell with zero neighbours should die. */ @Test public void rule1_zeroNeighbours() { GameOfLife gameOfLife = new GameOfLife(); Coordinates coords = new Coordinates(1,1); gameOfLife.set(coords, GameOfLife.ALIVE); assertEquals("Pre-condition failed.", GameOfLife.ALIVE, gameOfLife.get(coords)); gameOfLife.step(); assertEquals("Test failed.", GameOfLife.DEAD, gameOfLife.get(coords)); } /* * Rule 1: Any live cell with fewer than two live neighbours dies, as if * caused by under-population. * * A cell with one neighbour should die. */ @Test public void rule1_oneNeighbour() { GameOfLife gameOfLife = new GameOfLife(); Coordinates coords = new Coordinates(1,1); gameOfLife.set(coords, GameOfLife.ALIVE); gameOfLife.set(coords.getX(), coords.getY()+1, GameOfLife.ALIVE); assertEquals("Pre-condition failed.", GameOfLife.ALIVE, gameOfLife.get(coords)); gameOfLife.step(); assertEquals("Test failed.", GameOfLife.DEAD, gameOfLife.get(coords)); } /* * Rule 2: Any live cell with two or three live neighbours lives on to the * next generation. * * A cell with two neighbours should stay alive. */ @Test public void rule2_twoNeighbours() { GameOfLife gameOfLife = new GameOfLife(); Coordinates coords = new Coordinates(1,1); gameOfLife.set(coords, GameOfLife.ALIVE); gameOfLife.set(coords.getX(), coords.getY()+1, GameOfLife.ALIVE); gameOfLife.set(coords.getX()+1, coords.getY(), GameOfLife.ALIVE); assertEquals("Pre-condition failed.", GameOfLife.ALIVE, gameOfLife.get(coords)); gameOfLife.step(); assertEquals("Test failed.", GameOfLife.ALIVE, gameOfLife.get(coords)); } /* * Rule 2: Any live cell with two or three live neighbours lives on to the * next generation. * * A cell with three neighbours should stay alive. */ @Test public void rule2_threeNeighbours() { GameOfLife gameOfLife = new GameOfLife(); Coordinates coords = new Coordinates(1,1); gameOfLife.set(coords, GameOfLife.ALIVE); gameOfLife.set(coords.getX(), coords.getY()+1, GameOfLife.ALIVE); gameOfLife.set(coords.getX()+1, coords.getY(), GameOfLife.ALIVE); gameOfLife.set(coords.getX()+1, coords.getY()+1, GameOfLife.ALIVE); assertEquals("Pre-condition failed.", GameOfLife.ALIVE, gameOfLife.get(coords)); gameOfLife.step(); assertEquals("Test failed.", GameOfLife.ALIVE, gameOfLife.get(coords)); } /* * Rule 3: Any live cell with more than three live neighbours dies, as if * by overcrowding. * * Four neighbours causes a live cell to die. */ @Test public void rule3_fourNeighbours() { GameOfLife gameOfLife = new GameOfLife(); Coordinates coords = new Coordinates(1,1); gameOfLife.set(coords, GameOfLife.ALIVE); gameOfLife.set(coords.getX()-1, coords.getY()-1, GameOfLife.ALIVE); gameOfLife.set(coords.getX(), coords.getY()+1, GameOfLife.ALIVE); gameOfLife.set(coords.getX()+1, coords.getY(), GameOfLife.ALIVE); gameOfLife.set(coords.getX()+1, coords.getY()+1, GameOfLife.ALIVE); assertEquals("Pre-condition failed.", GameOfLife.ALIVE, gameOfLife.get(coords)); gameOfLife.step(); assertEquals("Test failed.", GameOfLife.DEAD, gameOfLife.get(coords)); } /* * Rule 3: Any live cell with more than three live neighbours dies, as if * by overcrowding. * * Five neighbours causes a live cell to die. */ @Test public void rule3_fiveNeighbours() { GameOfLife gameOfLife = new GameOfLife(); Coordinates coords = new Coordinates(1,1); gameOfLife.set(coords, GameOfLife.ALIVE); gameOfLife.set(coords.getX()-1, coords.getY()-1, GameOfLife.ALIVE); gameOfLife.set(coords.getX()-1, coords.getY(), GameOfLife.ALIVE); gameOfLife.set(coords.getX(), coords.getY()+1, GameOfLife.ALIVE); gameOfLife.set(coords.getX()+1, coords.getY(), GameOfLife.ALIVE); gameOfLife.set(coords.getX()+1, coords.getY()+1, GameOfLife.ALIVE); assertEquals("Pre-condition failed.", GameOfLife.ALIVE, gameOfLife.get(coords)); gameOfLife.step(); assertEquals("Test failed.", GameOfLife.DEAD, gameOfLife.get(coords)); } /* * Rule 3: Any live cell with more than three live neighbours dies, as if * by overcrowding. * * Six neighbours causes a live cell to die. */ @Test public void rule3_sixNeighbours() { GameOfLife gameOfLife = new GameOfLife(); Coordinates coords = new Coordinates(1,1); gameOfLife.set(coords, GameOfLife.ALIVE); gameOfLife.set(coords.getX()-1, coords.getY()-1, GameOfLife.ALIVE); gameOfLife.set(coords.getX()-1, coords.getY(), GameOfLife.ALIVE); gameOfLife.set(coords.getX(), coords.getY()-1, GameOfLife.ALIVE); gameOfLife.set(coords.getX(), coords.getY()+1, GameOfLife.ALIVE); gameOfLife.set(coords.getX()+1, coords.getY(), GameOfLife.ALIVE); gameOfLife.set(coords.getX()+1, coords.getY()+1, GameOfLife.ALIVE); assertEquals("Pre-condition failed.", GameOfLife.ALIVE, gameOfLife.get(coords)); gameOfLife.step(); assertEquals("Test failed.", GameOfLife.DEAD, gameOfLife.get(coords)); } /* * Rule 3: Any live cell with more than three live neighbours dies, as if * by overcrowding. * * Seven neighbours causes a live cell to die. */ @Test public void rule3_sevenNeighbours() { GameOfLife gameOfLife = new GameOfLife(); Coordinates coords = new Coordinates(1,1); gameOfLife.set(coords, GameOfLife.ALIVE); gameOfLife.set(coords.getX()-1, coords.getY()-1, GameOfLife.ALIVE); gameOfLife.set(coords.getX()-1, coords.getY(), GameOfLife.ALIVE); gameOfLife.set(coords.getX(), coords.getY()-1, GameOfLife.ALIVE); gameOfLife.set(coords.getX(), coords.getY()+1, GameOfLife.ALIVE); gameOfLife.set(coords.getX()+1, coords.getY(), GameOfLife.ALIVE); gameOfLife.set(coords.getX()+1, coords.getY()+1, GameOfLife.ALIVE); gameOfLife.set(coords.getX()-1, coords.getY()+1, GameOfLife.ALIVE); assertEquals("Pre-condition failed.", GameOfLife.ALIVE, gameOfLife.get(coords)); gameOfLife.step(); assertEquals("Test failed.", GameOfLife.DEAD, gameOfLife.get(coords)); } /* * Rule 3: Any live cell with more than three live neighbours dies, as if * by overcrowding. * * Eight neighbours causes a live cell to die. */ @Test public void rule3_eightNeighbours() { GameOfLife gameOfLife = new GameOfLife(); Coordinates coords = new Coordinates(1,1); gameOfLife.set(coords, GameOfLife.ALIVE); gameOfLife.set(coords.getX()-1, coords.getY()-1, GameOfLife.ALIVE); gameOfLife.set(coords.getX()-1, coords.getY(), GameOfLife.ALIVE); gameOfLife.set(coords.getX(), coords.getY()-1, GameOfLife.ALIVE); gameOfLife.set(coords.getX(), coords.getY()+1, GameOfLife.ALIVE); gameOfLife.set(coords.getX()+1, coords.getY(), GameOfLife.ALIVE); gameOfLife.set(coords.getX()+1, coords.getY()+1, GameOfLife.ALIVE); gameOfLife.set(coords.getX()-1, coords.getY()+1, GameOfLife.ALIVE); gameOfLife.set(coords.getX()+1, coords.getY()-1, GameOfLife.ALIVE); assertEquals("Pre-condition failed.", GameOfLife.ALIVE, gameOfLife.get(coords)); gameOfLife.step(); assertEquals("Test failed.", GameOfLife.DEAD, gameOfLife.get(coords)); } /* * Rule 4: Any dead cell with exactly three live neighbours becomes a live * cell, as if by reproduction. * */ @Test public void rule4_exactlyThreeNeighbours() { GameOfLife gameOfLife = new GameOfLife(); Coordinates coords = new Coordinates(1,1); gameOfLife.set(coords.getX(), coords.getY()+1, GameOfLife.ALIVE); gameOfLife.set(coords.getX()+1, coords.getY(), GameOfLife.ALIVE); gameOfLife.set(coords.getX()+1, coords.getY()+1, GameOfLife.ALIVE); assertEquals("Pre-condition failed.", GameOfLife.DEAD, gameOfLife.get(coords)); gameOfLife.step(); assertEquals("Test failed.", GameOfLife.ALIVE, gameOfLife.get(coords)); } }
tests/GOL/AllTests.java
package GOL; import org.junit.*; import static org.junit.Assert.*; /* * Any live call with fewer than two live neighbours dies,as if caused by * under-population. * Any live cell with two or three live neighbours lives on to the next * generation. * Any live cell with more than three live neighbours dies, as if by * overcrowding. * Any dead cell with exactly three live neighbours becomes a live cell, as if * by reproduction. */ public class AllTests { /* * Rule 1: Any live cell with fewer than two live neighbours dies, as if * caused by under-population. * * A cell with zero neighbours should die. */ @Test public void rule1_zeroNeighbours() { GameOfLife gameOfLife = new GameOfLife(3,3); Coordinates coords = new Coordinates(1,1); gameOfLife.set(coords, GameOfLife.ALIVE); assertEquals("Pre-condition failed.", GameOfLife.ALIVE, gameOfLife.get(coords)); gameOfLife.step(); assertEquals("Test failed.", GameOfLife.DEAD, gameOfLife.get(coords)); } /* * Rule 1: Any live cell with fewer than two live neighbours dies, as if * caused by under-population. * * A cell with one neighbour should die. */ @Test public void rule1_oneNeighbour() { GameOfLife gameOfLife = new GameOfLife(3,3); Coordinates coords = new Coordinates(1,1); gameOfLife.set(coords, GameOfLife.ALIVE); gameOfLife.set(coords.getX(), coords.getY()+1, GameOfLife.ALIVE); assertEquals("Pre-condition failed.", GameOfLife.ALIVE, gameOfLife.get(coords)); gameOfLife.step(); assertEquals("Test failed.", GameOfLife.DEAD, gameOfLife.get(coords)); } /* * Rule 2: Any live cell with two or three live neighbours lives on to the * next generation. * * A cell with two neighbours should stay alive. */ @Test public void rule2_twoNeighbours() { GameOfLife gameOfLife = new GameOfLife(3,3); Coordinates coords = new Coordinates(1,1); gameOfLife.set(coords, GameOfLife.ALIVE); gameOfLife.set(coords.getX(), coords.getY()+1, GameOfLife.ALIVE); gameOfLife.set(coords.getX()+1, coords.getY(), GameOfLife.ALIVE); assertEquals("Pre-condition failed.", GameOfLife.ALIVE, gameOfLife.get(coords)); gameOfLife.step(); assertEquals("Test failed.", GameOfLife.ALIVE, gameOfLife.get(coords)); } /* * Rule 2: Any live cell with two or three live neighbours lives on to the * next generation. * * A cell with three neighbours should stay alive. */ @Test public void rule2_threeNeighbours() { GameOfLife gameOfLife = new GameOfLife(3,3); Coordinates coords = new Coordinates(1,1); gameOfLife.set(coords, GameOfLife.ALIVE); gameOfLife.set(coords.getX(), coords.getY()+1, GameOfLife.ALIVE); gameOfLife.set(coords.getX()+1, coords.getY(), GameOfLife.ALIVE); gameOfLife.set(coords.getX()+1, coords.getY()+1, GameOfLife.ALIVE); assertEquals("Pre-condition failed.", GameOfLife.ALIVE, gameOfLife.get(coords)); gameOfLife.step(); assertEquals("Test failed.", GameOfLife.ALIVE, gameOfLife.get(coords)); } /* * Rule 3: Any live cell with more than three live neighbours dies, as if * by overcrowding. * * Four neighbours causes a live cell to die. */ @Test public void rule3_fourNeighbours() { GameOfLife gameOfLife = new GameOfLife(3,3); Coordinates coords = new Coordinates(1,1); gameOfLife.set(coords, GameOfLife.ALIVE); gameOfLife.set(coords.getX()-1, coords.getY()-1, GameOfLife.ALIVE); gameOfLife.set(coords.getX(), coords.getY()+1, GameOfLife.ALIVE); gameOfLife.set(coords.getX()+1, coords.getY(), GameOfLife.ALIVE); gameOfLife.set(coords.getX()+1, coords.getY()+1, GameOfLife.ALIVE); assertEquals("Pre-condition failed.", GameOfLife.ALIVE, gameOfLife.get(coords)); gameOfLife.step(); assertEquals("Test failed.", GameOfLife.DEAD, gameOfLife.get(coords)); } /* * Rule 3: Any live cell with more than three live neighbours dies, as if * by overcrowding. * * Five neighbours causes a live cell to die. */ @Test public void rule3_fiveNeighbours() { GameOfLife gameOfLife = new GameOfLife(3,3); Coordinates coords = new Coordinates(1,1); gameOfLife.set(coords, GameOfLife.ALIVE); gameOfLife.set(coords.getX()-1, coords.getY()-1, GameOfLife.ALIVE); gameOfLife.set(coords.getX()-1, coords.getY(), GameOfLife.ALIVE); gameOfLife.set(coords.getX(), coords.getY()+1, GameOfLife.ALIVE); gameOfLife.set(coords.getX()+1, coords.getY(), GameOfLife.ALIVE); gameOfLife.set(coords.getX()+1, coords.getY()+1, GameOfLife.ALIVE); assertEquals("Pre-condition failed.", GameOfLife.ALIVE, gameOfLife.get(coords)); gameOfLife.step(); assertEquals("Test failed.", GameOfLife.DEAD, gameOfLife.get(coords)); } /* * Rule 3: Any live cell with more than three live neighbours dies, as if * by overcrowding. * * Six neighbours causes a live cell to die. */ @Test public void rule3_sixNeighbours() { GameOfLife gameOfLife = new GameOfLife(3,3); Coordinates coords = new Coordinates(1,1); gameOfLife.set(coords, GameOfLife.ALIVE); gameOfLife.set(coords.getX()-1, coords.getY()-1, GameOfLife.ALIVE); gameOfLife.set(coords.getX()-1, coords.getY(), GameOfLife.ALIVE); gameOfLife.set(coords.getX(), coords.getY()-1, GameOfLife.ALIVE); gameOfLife.set(coords.getX(), coords.getY()+1, GameOfLife.ALIVE); gameOfLife.set(coords.getX()+1, coords.getY(), GameOfLife.ALIVE); gameOfLife.set(coords.getX()+1, coords.getY()+1, GameOfLife.ALIVE); assertEquals("Pre-condition failed.", GameOfLife.ALIVE, gameOfLife.get(coords)); gameOfLife.step(); assertEquals("Test failed.", GameOfLife.DEAD, gameOfLife.get(coords)); } /* * Rule 3: Any live cell with more than three live neighbours dies, as if * by overcrowding. * * Seven neighbours causes a live cell to die. */ @Test public void rule3_sevenNeighbours() { GameOfLife gameOfLife = new GameOfLife(3,3); Coordinates coords = new Coordinates(1,1); gameOfLife.set(coords, GameOfLife.ALIVE); gameOfLife.set(coords.getX()-1, coords.getY()-1, GameOfLife.ALIVE); gameOfLife.set(coords.getX()-1, coords.getY(), GameOfLife.ALIVE); gameOfLife.set(coords.getX(), coords.getY()-1, GameOfLife.ALIVE); gameOfLife.set(coords.getX(), coords.getY()+1, GameOfLife.ALIVE); gameOfLife.set(coords.getX()+1, coords.getY(), GameOfLife.ALIVE); gameOfLife.set(coords.getX()+1, coords.getY()+1, GameOfLife.ALIVE); gameOfLife.set(coords.getX()-1, coords.getY()+1, GameOfLife.ALIVE); assertEquals("Pre-condition failed.", GameOfLife.ALIVE, gameOfLife.get(coords)); gameOfLife.step(); assertEquals("Test failed.", GameOfLife.DEAD, gameOfLife.get(coords)); } /* * Rule 3: Any live cell with more than three live neighbours dies, as if * by overcrowding. * * Eight neighbours causes a live cell to die. */ @Test public void rule3_eightNeighbours() { GameOfLife gameOfLife = new GameOfLife(3,3); Coordinates coords = new Coordinates(1,1); gameOfLife.set(coords, GameOfLife.ALIVE); gameOfLife.set(coords.getX()-1, coords.getY()-1, GameOfLife.ALIVE); gameOfLife.set(coords.getX()-1, coords.getY(), GameOfLife.ALIVE); gameOfLife.set(coords.getX(), coords.getY()-1, GameOfLife.ALIVE); gameOfLife.set(coords.getX(), coords.getY()+1, GameOfLife.ALIVE); gameOfLife.set(coords.getX()+1, coords.getY(), GameOfLife.ALIVE); gameOfLife.set(coords.getX()+1, coords.getY()+1, GameOfLife.ALIVE); gameOfLife.set(coords.getX()-1, coords.getY()+1, GameOfLife.ALIVE); gameOfLife.set(coords.getX()+1, coords.getY()-1, GameOfLife.ALIVE); assertEquals("Pre-condition failed.", GameOfLife.ALIVE, gameOfLife.get(coords)); gameOfLife.step(); assertEquals("Test failed.", GameOfLife.DEAD, gameOfLife.get(coords)); } /* * Rule 4: Any dead cell with exactly three live neighbours becomes a live * cell, as if by reproduction. * */ @Test public void rule4_exactlyThreeNeighbours() { GameOfLife gameOfLife = new GameOfLife(3,3); Coordinates coords = new Coordinates(1,1); gameOfLife.set(coords.getX(), coords.getY()+1, GameOfLife.ALIVE); gameOfLife.set(coords.getX()+1, coords.getY(), GameOfLife.ALIVE); gameOfLife.set(coords.getX()+1, coords.getY()+1, GameOfLife.ALIVE); assertEquals("Pre-condition failed.", GameOfLife.DEAD, gameOfLife.get(coords)); gameOfLife.step(); assertEquals("Test failed.", GameOfLife.ALIVE, gameOfLife.get(coords)); } }
update tests to match new memory issue fix.
tests/GOL/AllTests.java
update tests to match new memory issue fix.
<ide><path>ests/GOL/AllTests.java <ide> @Test <ide> public void rule1_zeroNeighbours() <ide> { <del> GameOfLife gameOfLife = new GameOfLife(3,3); <add> GameOfLife gameOfLife = new GameOfLife(); <ide> Coordinates coords = new Coordinates(1,1); <ide> gameOfLife.set(coords, GameOfLife.ALIVE); <ide> <ide> @Test <ide> public void rule1_oneNeighbour() <ide> { <del> GameOfLife gameOfLife = new GameOfLife(3,3); <add> GameOfLife gameOfLife = new GameOfLife(); <ide> Coordinates coords = new Coordinates(1,1); <ide> gameOfLife.set(coords, GameOfLife.ALIVE); <ide> gameOfLife.set(coords.getX(), coords.getY()+1, GameOfLife.ALIVE); <ide> @Test <ide> public void rule2_twoNeighbours() <ide> { <del> GameOfLife gameOfLife = new GameOfLife(3,3); <add> GameOfLife gameOfLife = new GameOfLife(); <ide> Coordinates coords = new Coordinates(1,1); <ide> gameOfLife.set(coords, GameOfLife.ALIVE); <ide> gameOfLife.set(coords.getX(), coords.getY()+1, GameOfLife.ALIVE); <ide> @Test <ide> public void rule2_threeNeighbours() <ide> { <del> GameOfLife gameOfLife = new GameOfLife(3,3); <add> GameOfLife gameOfLife = new GameOfLife(); <ide> Coordinates coords = new Coordinates(1,1); <ide> gameOfLife.set(coords, GameOfLife.ALIVE); <ide> gameOfLife.set(coords.getX(), coords.getY()+1, GameOfLife.ALIVE); <ide> @Test <ide> public void rule3_fourNeighbours() <ide> { <del> GameOfLife gameOfLife = new GameOfLife(3,3); <add> GameOfLife gameOfLife = new GameOfLife(); <ide> Coordinates coords = new Coordinates(1,1); <ide> gameOfLife.set(coords, GameOfLife.ALIVE); <ide> gameOfLife.set(coords.getX()-1, coords.getY()-1, GameOfLife.ALIVE); <ide> @Test <ide> public void rule3_fiveNeighbours() <ide> { <del> GameOfLife gameOfLife = new GameOfLife(3,3); <add> GameOfLife gameOfLife = new GameOfLife(); <ide> Coordinates coords = new Coordinates(1,1); <ide> gameOfLife.set(coords, GameOfLife.ALIVE); <ide> gameOfLife.set(coords.getX()-1, coords.getY()-1, GameOfLife.ALIVE); <ide> @Test <ide> public void rule3_sixNeighbours() <ide> { <del> GameOfLife gameOfLife = new GameOfLife(3,3); <add> GameOfLife gameOfLife = new GameOfLife(); <ide> Coordinates coords = new Coordinates(1,1); <ide> gameOfLife.set(coords, GameOfLife.ALIVE); <ide> gameOfLife.set(coords.getX()-1, coords.getY()-1, GameOfLife.ALIVE); <ide> @Test <ide> public void rule3_sevenNeighbours() <ide> { <del> GameOfLife gameOfLife = new GameOfLife(3,3); <add> GameOfLife gameOfLife = new GameOfLife(); <ide> Coordinates coords = new Coordinates(1,1); <ide> gameOfLife.set(coords, GameOfLife.ALIVE); <ide> gameOfLife.set(coords.getX()-1, coords.getY()-1, GameOfLife.ALIVE); <ide> @Test <ide> public void rule3_eightNeighbours() <ide> { <del> GameOfLife gameOfLife = new GameOfLife(3,3); <add> GameOfLife gameOfLife = new GameOfLife(); <ide> Coordinates coords = new Coordinates(1,1); <ide> gameOfLife.set(coords, GameOfLife.ALIVE); <ide> gameOfLife.set(coords.getX()-1, coords.getY()-1, GameOfLife.ALIVE); <ide> @Test <ide> public void rule4_exactlyThreeNeighbours() <ide> { <del> GameOfLife gameOfLife = new GameOfLife(3,3); <add> GameOfLife gameOfLife = new GameOfLife(); <ide> Coordinates coords = new Coordinates(1,1); <ide> gameOfLife.set(coords.getX(), coords.getY()+1, GameOfLife.ALIVE); <ide> gameOfLife.set(coords.getX()+1, coords.getY(), GameOfLife.ALIVE);
Java
apache-2.0
ab08139ce51dcd6412fe6c6c3a586f4bdc8d4f6a
0
JNOSQL/diana
/* * Copyright (c) 2017 Otávio Santana and others * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * and Apache License v2.0 which accompanies this distribution. * The Eclipse Public License is available at http://www.eclipse.org/legal/epl-v10.html * and the Apache License v2.0 is available at http://www.opensource.org/licenses/apache2.0.php. * * You may elect to redistribute this code under either of these licenses. * * Contributors: * * Otavio Santana */ package org.jnosql.artemis.key; import org.jnosql.artemis.PreparedStatement; import org.jnosql.diana.api.NonUniqueResultException; import org.jnosql.diana.api.Value; import org.jnosql.diana.api.key.BucketManager; import org.jnosql.diana.api.key.KeyValueEntity; import java.time.Duration; import java.util.Collections; import java.util.List; import java.util.Objects; import java.util.Optional; import java.util.function.UnaryOperator; import java.util.stream.Collectors; import java.util.stream.StreamSupport; import static java.util.Objects.requireNonNull; import static java.util.stream.Collectors.toList; /** * This class provides a skeletal implementation of the {@link KeyValueTemplate} interface, * to minimize the effort required to implement this interface. */ public abstract class AbstractKeyValueTemplate implements KeyValueTemplate { protected abstract KeyValueEntityConverter getConverter(); protected abstract BucketManager getManager(); protected abstract KeyValueWorkflow getFlow(); @Override public <T> T put(T entity) { requireNonNull(entity, "entity is required"); UnaryOperator<KeyValueEntity<?>> putAction = k -> { getManager().put(k); return k; }; return getFlow().flow(entity, putAction); } @Override public <T> T put(T entity, Duration ttl) { requireNonNull(entity, "entity is required"); requireNonNull(ttl, "ttl class is required"); UnaryOperator<KeyValueEntity<?>> putAction = k -> { getManager().put(k, ttl); return k; }; return getFlow().flow(entity, putAction); } @Override public <K, T> Optional<T> get(K key, Class<T> entityClass) { requireNonNull(key, "key is required"); requireNonNull(entityClass, "entity class is required"); Optional<Value> value = getManager().get(key); return value.map(v -> getConverter().toEntity(entityClass, KeyValueEntity.of(key, v))) .filter(Objects::nonNull); } @Override public <K, T> Iterable<T> get(Iterable<K> keys, Class<T> entityClass) { requireNonNull(keys, "keys is required"); requireNonNull(entityClass, "entity class is required"); for (K key : keys) { Optional<Value> value = getManager().get(key); } return StreamSupport.stream(keys.spliterator(), false) .map(k -> getManager().get(k) .map(v -> KeyValueEntity.of(k, v))) .filter(Optional::isPresent) .map(e -> getConverter().toEntity(entityClass, e.get())) .collect(Collectors.toList()); } @Override public <K> void remove(K key) { requireNonNull(key, "key is required"); getManager().remove(key); } @Override public <K> void remove(Iterable<K> keys) { requireNonNull(keys, "keys is required"); getManager().remove(keys); } @Override public <T> List<T> query(String query, Class<T> entityClass) { requireNonNull(query, "query is required"); List<Value> values = getManager().query(query); if (!values.isEmpty()) { requireNonNull(entityClass, "entityClass is required"); return values.stream().map(v -> v.get(entityClass)).collect(toList()); } return Collections.emptyList(); } @Override public <T> Optional<T> getSingleResult(String query, Class<T> entityClass) { List<T> result = query(query, entityClass); if (result.isEmpty()) { return Optional.empty(); } if (result.size() == 1) { return Optional.ofNullable(result.get(0)); } throw new NonUniqueResultException("No Unique result found to the query: " + query); } @Override public void query(String query) { requireNonNull(query, "query is required"); getManager().query(query); } @Override public <T> PreparedStatement prepare(String query, Class<T> entityClass) { requireNonNull(query, "query is required"); return new org.jnosql.artemis.key.KeyValuePreparedStatement(getManager().prepare(query), entityClass); } }
mapping/artemis-key-value/src/main/java/org/jnosql/artemis/key/AbstractKeyValueTemplate.java
/* * Copyright (c) 2017 Otávio Santana and others * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * and Apache License v2.0 which accompanies this distribution. * The Eclipse Public License is available at http://www.eclipse.org/legal/epl-v10.html * and the Apache License v2.0 is available at http://www.opensource.org/licenses/apache2.0.php. * * You may elect to redistribute this code under either of these licenses. * * Contributors: * * Otavio Santana */ package org.jnosql.artemis.key; import org.jnosql.artemis.PreparedStatement; import org.jnosql.diana.api.NonUniqueResultException; import org.jnosql.diana.api.Value; import org.jnosql.diana.api.key.BucketManager; import org.jnosql.diana.api.key.KeyValueEntity; import java.time.Duration; import java.util.Collections; import java.util.List; import java.util.Objects; import java.util.Optional; import java.util.function.UnaryOperator; import java.util.stream.StreamSupport; import static java.util.Objects.requireNonNull; import static java.util.stream.Collectors.toList; /** * This class provides a skeletal implementation of the {@link KeyValueTemplate} interface, * to minimize the effort required to implement this interface. */ public abstract class AbstractKeyValueTemplate implements KeyValueTemplate { protected abstract KeyValueEntityConverter getConverter(); protected abstract BucketManager getManager(); protected abstract KeyValueWorkflow getFlow(); @Override public <T> T put(T entity) { requireNonNull(entity, "entity is required"); UnaryOperator<KeyValueEntity<?>> putAction = k -> { getManager().put(k); return k; }; return getFlow().flow(entity, putAction); } @Override public <T> T put(T entity, Duration ttl) { requireNonNull(entity, "entity is required"); requireNonNull(ttl, "ttl class is required"); UnaryOperator<KeyValueEntity<?>> putAction = k -> { getManager().put(k, ttl); return k; }; return getFlow().flow(entity, putAction); } @Override public <K, T> Optional<T> get(K key, Class<T> entityClass) { requireNonNull(key, "key is required"); requireNonNull(entityClass, "entity class is required"); Optional<Value> value = getManager().get(key); return value.map(v -> getConverter().toEntity(entityClass, v)) .filter(Objects::nonNull); } @Override public <K, T> Iterable<T> get(Iterable<K> keys, Class<T> entityClass) { requireNonNull(keys, "keys is required"); requireNonNull(entityClass, "entity class is required"); return StreamSupport.stream(getManager() .get(keys).spliterator(), false) .map(v -> getConverter().toEntity(entityClass, v)) .filter(Objects::nonNull) .collect(toList()); } @Override public <K> void remove(K key) { requireNonNull(key, "key is required"); getManager().remove(key); } @Override public <K> void remove(Iterable<K> keys) { requireNonNull(keys, "keys is required"); getManager().remove(keys); } @Override public <T> List<T> query(String query, Class<T> entityClass) { requireNonNull(query, "query is required"); List<Value> values = getManager().query(query); if (!values.isEmpty()) { requireNonNull(entityClass, "entityClass is required"); return values.stream().map(v -> v.get(entityClass)).collect(toList()); } return Collections.emptyList(); } @Override public <T> Optional<T> getSingleResult(String query, Class<T> entityClass) { List<T> result = query(query, entityClass); if (result.isEmpty()) { return Optional.empty(); } if (result.size() == 1) { return Optional.ofNullable(result.get(0)); } throw new NonUniqueResultException("No Unique result found to the query: " + query); } @Override public void query(String query) { requireNonNull(query, "query is required"); getManager().query(query); } @Override public <T> PreparedStatement prepare(String query, Class<T> entityClass) { requireNonNull(query, "query is required"); return new org.jnosql.artemis.key.KeyValuePreparedStatement(getManager().prepare(query), entityClass); } }
fixes keyvalue template
mapping/artemis-key-value/src/main/java/org/jnosql/artemis/key/AbstractKeyValueTemplate.java
fixes keyvalue template
<ide><path>apping/artemis-key-value/src/main/java/org/jnosql/artemis/key/AbstractKeyValueTemplate.java <ide> import java.util.Objects; <ide> import java.util.Optional; <ide> import java.util.function.UnaryOperator; <add>import java.util.stream.Collectors; <ide> import java.util.stream.StreamSupport; <ide> <ide> import static java.util.Objects.requireNonNull; <ide> requireNonNull(entityClass, "entity class is required"); <ide> <ide> Optional<Value> value = getManager().get(key); <del> return value.map(v -> getConverter().toEntity(entityClass, v)) <add> return value.map(v -> getConverter().toEntity(entityClass, KeyValueEntity.of(key, v))) <ide> .filter(Objects::nonNull); <ide> } <ide> <ide> public <K, T> Iterable<T> get(Iterable<K> keys, Class<T> entityClass) { <ide> requireNonNull(keys, "keys is required"); <ide> requireNonNull(entityClass, "entity class is required"); <del> return StreamSupport.stream(getManager() <del> .get(keys).spliterator(), false) <del> .map(v -> getConverter().toEntity(entityClass, v)) <del> .filter(Objects::nonNull) <del> .collect(toList()); <add> for (K key : keys) { <add> Optional<Value> value = getManager().get(key); <add> <add> } <add> <add> return StreamSupport.stream(keys.spliterator(), false) <add> .map(k -> getManager().get(k) <add> .map(v -> KeyValueEntity.of(k, v))) <add> .filter(Optional::isPresent) <add> .map(e -> getConverter().toEntity(entityClass, e.get())) <add> .collect(Collectors.toList()); <ide> } <ide> <ide> @Override
Java
agpl-3.0
9cfcd2f4a8fe560e6870c32548ba967500018f03
0
ua-eas/kfs,kuali/kfs,UniversityOfHawaii/kfs,quikkian-ua-devops/kfs,ua-eas/kfs,UniversityOfHawaii/kfs,kkronenb/kfs,ua-eas/kfs-devops-automation-fork,quikkian-ua-devops/will-financials,ua-eas/kfs-devops-automation-fork,smith750/kfs,smith750/kfs,quikkian-ua-devops/kfs,quikkian-ua-devops/kfs,ua-eas/kfs,kuali/kfs,kkronenb/kfs,smith750/kfs,quikkian-ua-devops/will-financials,quikkian-ua-devops/will-financials,smith750/kfs,ua-eas/kfs-devops-automation-fork,UniversityOfHawaii/kfs,ua-eas/kfs-devops-automation-fork,quikkian-ua-devops/will-financials,ua-eas/kfs,quikkian-ua-devops/will-financials,kkronenb/kfs,kkronenb/kfs,ua-eas/kfs-devops-automation-fork,kuali/kfs,bhutchinson/kfs,bhutchinson/kfs,quikkian-ua-devops/kfs,UniversityOfHawaii/kfs,kuali/kfs,quikkian-ua-devops/kfs,bhutchinson/kfs,kuali/kfs,bhutchinson/kfs,ua-eas/kfs,UniversityOfHawaii/kfs,quikkian-ua-devops/will-financials,quikkian-ua-devops/kfs
/* * Copyright 2010 The Kuali Foundation. * * Licensed under the Educational Community 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.opensource.org/licenses/ecl1.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 org.kuali.kfs.module.endow.businessobject; import java.util.LinkedHashMap; import org.kuali.kfs.module.endow.EndowPropertyConstants; import org.kuali.rice.kns.bo.PersistableBusinessObjectBase; import org.kuali.rice.kns.util.KualiDecimal; import org.kuali.rice.kns.util.KualiInteger; /** * This is the generic class which contains all the elements on a typical Endowment Transaction Line. */ public abstract class EndowmentTransactionLineBase extends PersistableBusinessObjectBase implements EndowmentTransactionLine { private String documentNumber; private String transactionLineTypeCode; private KualiInteger transactionLineNumber; private String kemid; private String etranCode; private String transactionLineDescription; private String transactionIPIndicatorCode; private KualiDecimal transactionAmount; private boolean corpusIndicator; private KualiDecimal transactionUnits; private boolean linePosted; private KEMID kemidObj; private EndowmentTransactionCode etranCodeObj; private IncomePrincipalIndicator incomePrincipalIndicator; /** * Constructs a EndowmentTransactionLineBase.java. */ public EndowmentTransactionLineBase() { setTransactionAmount(KualiDecimal.ZERO); setTransactionUnits(KualiDecimal.ZERO); kemidObj = new KEMID(); etranCodeObj = new EndowmentTransactionCode(); incomePrincipalIndicator = new IncomePrincipalIndicator(); } /** * @see org.kuali.rice.kns.bo.BusinessObjectBase#toStringMapper() */ @Override protected LinkedHashMap toStringMapper() { LinkedHashMap m = new LinkedHashMap(); m.put(EndowPropertyConstants.TRANSACTION_LINE_DOCUMENT_NUMBER, this.documentNumber); m.put(EndowPropertyConstants.TRANSACTION_LINE_TYPE_CODE, this.transactionLineTypeCode); m.put(EndowPropertyConstants.TRANSACTION_LINE_NUMBER, this.transactionLineNumber); return m; } /** * Gets the documentNumber. * * @return documentNumber */ public String getDocumentNumber() { return documentNumber; } /** * Sets the documentNumber. * * @param documentNumber */ public void setDocumentNumber(String documentNumber) { this.documentNumber = documentNumber; } /** * @see org.kuali.kfs.module.endow.businessobject.EndowmentTransactionLine#getTransactionLineTypeCode() */ public String getTransactionLineTypeCode() { return transactionLineTypeCode; } /** * @see org.kuali.kfs.module.endow.businessobject.EndowmentTransactionLine#setTransactionLineTypeCode(java.lang.String) */ public void setTransactionLineTypeCode(String transactionLineTypeCode) { this.transactionLineTypeCode = transactionLineTypeCode; } /** * @see org.kuali.kfs.module.endow.businessobject.EndowmentTransactionLine#getTransactionLineNumber() */ public KualiInteger getTransactionLineNumber() { return transactionLineNumber; } /** * @see org.kuali.kfs.module.endow.businessobject.EndowmentTransactionLine#setTransactionLineNumber(org.kuali.rice.kns.util.KualiInteger) */ public void setTransactionLineNumber(KualiInteger transactionLineNumber) { this.transactionLineNumber = transactionLineNumber; } /** * @see org.kuali.kfs.module.endow.businessobject.EndowmentTransactionLine#getKemid() */ public String getKemid() { return kemid; } /** * @see org.kuali.kfs.module.endow.businessobject.EndowmentTransactionLine#setKemid(java.lang.String) */ public void setKemid(String kemid) { this.kemid = kemid; } /** * @see org.kuali.kfs.module.endow.businessobject.EndowmentTransactionLine#getEtranCode() */ public String getEtranCode() { return etranCode; } /** * @see org.kuali.kfs.module.endow.businessobject.EndowmentTransactionLine#setEtranCode(java.lang.String) */ public void setEtranCode(String etranCode) { this.etranCode = etranCode; } /** * @see org.kuali.kfs.module.endow.businessobject.EndowmentTransactionLine#getTransactionLineDescription() */ public String getTransactionLineDescription() { return transactionLineDescription; } /** * @see org.kuali.kfs.module.endow.businessobject.EndowmentTransactionLine#setTransactionLineDescription(java.lang.String) */ public void setTransactionLineDescription(String transactionLineDescription) { this.transactionLineDescription = transactionLineDescription; } /** * @see org.kuali.kfs.module.endow.businessobject.EndowmentTransactionLine#getTransactionAmount() */ public KualiDecimal getTransactionAmount() { return transactionAmount; } /** * @see org.kuali.kfs.module.endow.businessobject.EndowmentTransactionLine#setTransactionAmount(org.kuali.rice.kns.util.KualiDecimal) */ public void setTransactionAmount(KualiDecimal transactionAmount) { this.transactionAmount = transactionAmount; } /** * @see org.kuali.kfs.module.endow.businessobject.EndowmentTransactionLine#getCorpusIndicator() */ public boolean getCorpusIndicator() { return corpusIndicator; } /** * @see org.kuali.kfs.module.endow.businessobject.EndowmentTransactionLine#setCorpusIndicator(boolean) */ public void setCorpusIndicator(boolean corpusIndicator) { this.corpusIndicator = corpusIndicator; } /** * @see org.kuali.kfs.module.endow.businessobject.EndowmentTransactionLine#getTransactionUnits() */ public KualiDecimal getTransactionUnits() { return transactionUnits; } /** * @see org.kuali.kfs.module.endow.businessobject.EndowmentTransactionLine#setTransactionUnits(org.kuali.rice.kns.util.KualiDecimal) */ public void setTransactionUnits(KualiDecimal transactionUnits) { this.transactionUnits = transactionUnits; } /** * @see org.kuali.kfs.module.endow.businessobject.EndowmentTransactionLine#isLinePosted() */ public boolean isLinePosted() { return linePosted; } /** * @see org.kuali.kfs.module.endow.businessobject.EndowmentTransactionLine#setLinePosted(boolean) */ public void setLinePosted(boolean linePosted) { this.linePosted = linePosted; } /** * @see org.kuali.kfs.module.endow.businessobject.EndowmentTransactionLine#getTransactionIPIndicatorCode() */ public String getTransactionIPIndicatorCode() { return transactionIPIndicatorCode; } /** * @see org.kuali.kfs.module.endow.businessobject.EndowmentTransactionLine#setTransactionIPIndicatorCode(java.lang.String) */ public void setTransactionIPIndicatorCode(String transactionIPIndicatorCode) { this.transactionIPIndicatorCode = transactionIPIndicatorCode; } /** * @see org.kuali.kfs.module.endow.businessobject.EndowmentTransactionLine#getIncomePrincipalIndicator() */ public IncomePrincipalIndicator getIncomePrincipalIndicator() { return incomePrincipalIndicator; } /** * @see org.kuali.kfs.module.endow.businessobject.EndowmentTransactionLine#setIncomePrincipalIndicator(org.kuali.kfs.module.endow.businessobject.IncomePrincipalIndicator) */ public void setIncomePrincipalIndicator(IncomePrincipalIndicator incomePrincipalIndicator) { this.incomePrincipalIndicator = incomePrincipalIndicator; } /** * @see org.kuali.kfs.module.endow.businessobject.EndowmentTransactionLine#getKemidObj() */ public KEMID getKemidObj() { return kemidObj; } /** * @see org.kuali.kfs.module.endow.businessobject.EndowmentTransactionLine#setKemidObj(org.kuali.kfs.module.endow.businessobject.KEMID) */ public void setKemidObj(KEMID kemidObj) { this.kemidObj = kemidObj; } /** * @see org.kuali.kfs.module.endow.businessobject.EndowmentTransactionLine#getEtranCodeObj() */ public EndowmentTransactionCode getEtranCodeObj() { return etranCodeObj; } /** * @see org.kuali.kfs.module.endow.businessobject.EndowmentTransactionLine#setEtranCodeObj(org.kuali.kfs.module.endow.businessobject.EndowmentTransactionCode) */ public void setEtranCodeObj(EndowmentTransactionCode etranCodeObj) { this.etranCodeObj = etranCodeObj; } }
work/src/org/kuali/kfs/module/endow/businessobject/EndowmentTransactionLineBase.java
/* * Copyright 2010 The Kuali Foundation. * * Licensed under the Educational Community 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.opensource.org/licenses/ecl1.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 org.kuali.kfs.module.endow.businessobject; import java.util.LinkedHashMap; import org.kuali.rice.kns.bo.PersistableBusinessObjectBase; import org.kuali.rice.kns.util.KualiDecimal; import org.kuali.rice.kns.util.KualiInteger; /** * This is the generic class which contains all the elements on a typical Endowment Transaction Line. */ public abstract class EndowmentTransactionLineBase extends PersistableBusinessObjectBase implements EndowmentTransactionLine { private String documentNumber; private String transactionLineTypeCode; private KualiInteger transactionLineNumber; private String kemid; private String etranCode; private String transactionLineDescription; private String transactionIncomePrincipalIndicatorCode; private KualiDecimal transactionAmount; private boolean corpusIndicator; private KualiDecimal transactionUnits; private boolean linePosted; private KEMID kemidObj; private EndowmentTransactionCode etranCodeObj; private IncomePrincipalIndicator incomePrincipalIndicator; /** * Constructs a EndowmentTransactionLineBase.java. */ public EndowmentTransactionLineBase() { setTransactionAmount(KualiDecimal.ZERO); setTransactionUnits(KualiDecimal.ZERO); kemidObj = new KEMID(); etranCodeObj = new EndowmentTransactionCode(); incomePrincipalIndicator = new IncomePrincipalIndicator(); } /** * Gets the documentNumber. * * @return documentNumber */ public String getDocumentNumber() { return documentNumber; } /** * Sets the documentNumber. * * @param documentNumber */ public void setDocumentNumber(String documentNumber) { this.documentNumber = documentNumber; } /** * @see org.kuali.kfs.module.endow.businessobject.EndowmentTransactionLine#getTransactionLineTypeCode() */ public String getTransactionLineTypeCode() { return transactionLineTypeCode; } /** * @see org.kuali.kfs.module.endow.businessobject.EndowmentTransactionLine#setTransactionLineTypeCode(java.lang.String) */ public void setTransactionLineTypeCode(String transactionLineTypeCode) { this.transactionLineTypeCode = transactionLineTypeCode; } /** * @see org.kuali.kfs.module.endow.businessobject.EndowmentTransactionLine#getTransactionLineNumber() */ public KualiInteger getTransactionLineNumber() { return transactionLineNumber; } /** * @see org.kuali.kfs.module.endow.businessobject.EndowmentTransactionLine#setTransactionLineNumber(org.kuali.rice.kns.util.KualiInteger) */ public void setTransactionLineNumber(KualiInteger transactionLineNumber) { this.transactionLineNumber = transactionLineNumber; } /** * @see org.kuali.kfs.module.endow.businessobject.EndowmentTransactionLine#getKemid() */ public String getKemid() { return kemid; } /** * @see org.kuali.kfs.module.endow.businessobject.EndowmentTransactionLine#setKemid(java.lang.String) */ public void setKemid(String kemid) { this.kemid = kemid; } /** * @see org.kuali.kfs.module.endow.businessobject.EndowmentTransactionLine#getEtranCode() */ public String getEtranCode() { return etranCode; } /** * @see org.kuali.kfs.module.endow.businessobject.EndowmentTransactionLine#setEtranCode(java.lang.String) */ public void setEtranCode(String etranCode) { this.etranCode = etranCode; } /** * @see org.kuali.kfs.module.endow.businessobject.EndowmentTransactionLine#getTransactionLineDescription() */ public String getTransactionLineDescription() { return transactionLineDescription; } /** * @see org.kuali.kfs.module.endow.businessobject.EndowmentTransactionLine#setTransactionLineDescription(java.lang.String) */ public void setTransactionLineDescription(String transactionLineDescription) { this.transactionLineDescription = transactionLineDescription; } /** * @see org.kuali.kfs.module.endow.businessobject.EndowmentTransactionLine#getTransactionAmount() */ public KualiDecimal getTransactionAmount() { return transactionAmount; } /** * @see org.kuali.kfs.module.endow.businessobject.EndowmentTransactionLine#setTransactionAmount(org.kuali.rice.kns.util.KualiDecimal) */ public void setTransactionAmount(KualiDecimal transactionAmount) { this.transactionAmount = transactionAmount; } /** * @see org.kuali.kfs.module.endow.businessobject.EndowmentTransactionLine#getCorpusIndicator() */ public boolean getCorpusIndicator() { return corpusIndicator; } /** * @see org.kuali.kfs.module.endow.businessobject.EndowmentTransactionLine#setCorpusIndicator(boolean) */ public void setCorpusIndicator(boolean corpusIndicator) { this.corpusIndicator = corpusIndicator; } /** * @see org.kuali.kfs.module.endow.businessobject.EndowmentTransactionLine#getTransactionUnits() */ public KualiDecimal getTransactionUnits() { return transactionUnits; } /** * @see org.kuali.kfs.module.endow.businessobject.EndowmentTransactionLine#setTransactionUnits(org.kuali.rice.kns.util.KualiDecimal) */ public void setTransactionUnits(KualiDecimal transactionUnits) { this.transactionUnits = transactionUnits; } /** * @see org.kuali.kfs.module.endow.businessobject.EndowmentTransactionLine#isLinePosted() */ public boolean isLinePosted() { return linePosted; } /** * @see org.kuali.kfs.module.endow.businessobject.EndowmentTransactionLine#setLinePosted(boolean) */ public void setLinePosted(boolean linePosted) { this.linePosted = linePosted; } /** * @see org.kuali.kfs.module.endow.businessobject.EndowmentTransactionLine#getTransactionIncomePrincipalIndicatorCode() */ public String getTransactionIncomePrincipalIndicatorCode() { return transactionIncomePrincipalIndicatorCode; } /** * @see org.kuali.kfs.module.endow.businessobject.EndowmentTransactionLine#setTransactionIncomePrincipalIndicatorCode(java.lang.String) */ public void setTransactionIncomePrincipalIndicatorCode(String transactionIncomePrincipalIndicatorCode) { this.transactionIncomePrincipalIndicatorCode = transactionIncomePrincipalIndicatorCode; } @Override protected LinkedHashMap toStringMapper() { // TODO Auto-generated method stub return null; } /** * @see org.kuali.kfs.module.endow.businessobject.EndowmentTransactionLine#getIncomePrincipalIndicator() */ public IncomePrincipalIndicator getIncomePrincipalIndicator() { return incomePrincipalIndicator; } /** * @see org.kuali.kfs.module.endow.businessobject.EndowmentTransactionLine#setIncomePrincipalIndicator(org.kuali.kfs.module.endow.businessobject.IncomePrincipalIndicator) */ public void setIncomePrincipalIndicator(IncomePrincipalIndicator incomePrincipalIndicator) { this.incomePrincipalIndicator = incomePrincipalIndicator; } /** * This method... * @param kemidObj */ public void setKemidObj(KEMID kemidObj) { this.kemidObj = kemidObj; } /** * This method... * @param etranCodeObj */ public void setEtranCodeObj(EndowmentTransactionCode etranCodeObj) { this.etranCodeObj = etranCodeObj; } /** * @see org.kuali.kfs.module.endow.businessobject.EndowmentTransactionLine#getKemidObj() */ public KEMID getKemidObj() { return kemidObj; } /** * @see org.kuali.kfs.module.endow.businessobject.EndowmentTransactionLine#getEtranCodeObj() */ public EndowmentTransactionCode getEtranCodeObj() { return etranCodeObj; } }
code clean up
work/src/org/kuali/kfs/module/endow/businessobject/EndowmentTransactionLineBase.java
code clean up
<ide><path>ork/src/org/kuali/kfs/module/endow/businessobject/EndowmentTransactionLineBase.java <ide> <ide> import java.util.LinkedHashMap; <ide> <add>import org.kuali.kfs.module.endow.EndowPropertyConstants; <ide> import org.kuali.rice.kns.bo.PersistableBusinessObjectBase; <ide> import org.kuali.rice.kns.util.KualiDecimal; <ide> import org.kuali.rice.kns.util.KualiInteger; <ide> private String kemid; <ide> private String etranCode; <ide> private String transactionLineDescription; <del> private String transactionIncomePrincipalIndicatorCode; <add> private String transactionIPIndicatorCode; <ide> private KualiDecimal transactionAmount; <ide> private boolean corpusIndicator; <ide> private KualiDecimal transactionUnits; <ide> etranCodeObj = new EndowmentTransactionCode(); <ide> incomePrincipalIndicator = new IncomePrincipalIndicator(); <ide> } <add> <add> /** <add> * @see org.kuali.rice.kns.bo.BusinessObjectBase#toStringMapper() <add> */ <add> @Override <add> protected LinkedHashMap toStringMapper() { <add> LinkedHashMap m = new LinkedHashMap(); <add> m.put(EndowPropertyConstants.TRANSACTION_LINE_DOCUMENT_NUMBER, this.documentNumber); <add> m.put(EndowPropertyConstants.TRANSACTION_LINE_TYPE_CODE, this.transactionLineTypeCode); <add> m.put(EndowPropertyConstants.TRANSACTION_LINE_NUMBER, this.transactionLineNumber); <add> return m; <add> } <ide> <ide> /** <ide> * Gets the documentNumber. <ide> } <ide> <ide> /** <del> * @see org.kuali.kfs.module.endow.businessobject.EndowmentTransactionLine#getTransactionIncomePrincipalIndicatorCode() <del> */ <del> public String getTransactionIncomePrincipalIndicatorCode() { <del> return transactionIncomePrincipalIndicatorCode; <del> } <del> <del> /** <del> * @see org.kuali.kfs.module.endow.businessobject.EndowmentTransactionLine#setTransactionIncomePrincipalIndicatorCode(java.lang.String) <del> */ <del> public void setTransactionIncomePrincipalIndicatorCode(String transactionIncomePrincipalIndicatorCode) { <del> this.transactionIncomePrincipalIndicatorCode = transactionIncomePrincipalIndicatorCode; <del> } <del> <del> <del> @Override <del> protected LinkedHashMap toStringMapper() { <del> // TODO Auto-generated method stub <del> return null; <add> * @see org.kuali.kfs.module.endow.businessobject.EndowmentTransactionLine#getTransactionIPIndicatorCode() <add> */ <add> public String getTransactionIPIndicatorCode() { <add> return transactionIPIndicatorCode; <add> } <add> <add> /** <add> * @see org.kuali.kfs.module.endow.businessobject.EndowmentTransactionLine#setTransactionIPIndicatorCode(java.lang.String) <add> */ <add> public void setTransactionIPIndicatorCode(String transactionIPIndicatorCode) { <add> this.transactionIPIndicatorCode = transactionIPIndicatorCode; <ide> } <ide> <ide> /** <ide> public void setIncomePrincipalIndicator(IncomePrincipalIndicator incomePrincipalIndicator) { <ide> this.incomePrincipalIndicator = incomePrincipalIndicator; <ide> } <del> <del> /** <del> * This method... <del> * @param kemidObj <add> <add> /** <add> * @see org.kuali.kfs.module.endow.businessobject.EndowmentTransactionLine#getKemidObj() <add> */ <add> public KEMID getKemidObj() { <add> return kemidObj; <add> } <add> <add> /** <add> * @see org.kuali.kfs.module.endow.businessobject.EndowmentTransactionLine#setKemidObj(org.kuali.kfs.module.endow.businessobject.KEMID) <ide> */ <ide> public void setKemidObj(KEMID kemidObj) { <ide> this.kemidObj = kemidObj; <ide> } <ide> <ide> /** <del> * This method... <del> * @param etranCodeObj <add> * @see org.kuali.kfs.module.endow.businessobject.EndowmentTransactionLine#getEtranCodeObj() <add> */ <add> public EndowmentTransactionCode getEtranCodeObj() { <add> return etranCodeObj; <add> } <add> <add> /** <add> * @see org.kuali.kfs.module.endow.businessobject.EndowmentTransactionLine#setEtranCodeObj(org.kuali.kfs.module.endow.businessobject.EndowmentTransactionCode) <ide> */ <ide> public void setEtranCodeObj(EndowmentTransactionCode etranCodeObj) { <ide> this.etranCodeObj = etranCodeObj; <ide> } <ide> <del> /** <del> * @see org.kuali.kfs.module.endow.businessobject.EndowmentTransactionLine#getKemidObj() <del> */ <del> public KEMID getKemidObj() { <del> return kemidObj; <del> } <del> <del> /** <del> * @see org.kuali.kfs.module.endow.businessobject.EndowmentTransactionLine#getEtranCodeObj() <del> */ <del> public EndowmentTransactionCode getEtranCodeObj() { <del> return etranCodeObj; <del> } <del> <del> <ide> }
Java
mit
226987750aebef7d43504bf5c1936f5c439e3229
0
AuthorizeNet/sample-code-java,sunnyrajrathod/sample-code-java
package net.authorize.sample; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import net.authorize.sample.VisaCheckout.*; import net.authorize.sample.PaymentTransactions.*; import net.authorize.sample.PaypalExpressCheckout.*; import net.authorize.sample.PaypalExpressCheckout.Void; import net.authorize.sample.RecurringBilling.*; import net.authorize.sample.TransactionReporting.*; import net.authorize.sample.CustomerProfiles.*; import net.authorize.sample.MobileInappTransactions.*; import net.authorize.sample.FraudManagement.*; /** * Created by anetdeveloper on 8/5/15. */ public class SampleCode { public static void main( String[] args ) { if (args.length == 0) { SelectMethod(); } else if (args.length == 1) { RunMethod(args[0]); return; } else { ShowUsage(); } System.out.println(""); System.out.print("Press <Return> to finish ..."); BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); try{ int i = Integer.parseInt(br.readLine()); }catch(Exception ex){ } } private static void ShowUsage() { System.out.println("Usage : java -jar SampleCode.jar [CodeSampleName]"); System.out.println(""); System.out.println("Run with no parameter to select a method. Otherwise pass a method name."); System.out.println(""); System.out.println("Code Sample Names: "); ShowMethods(); } private static void SelectMethod() { System.out.println("Code Sample Names: "); System.out.println(""); ShowMethods(); System.out.println(""); System.out.print("Type a sample name & then press <Return> : "); BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); try{ RunMethod(br.readLine()); }catch(Exception ex){ System.out.println(ex.toString()); } } private static void ShowMethods() { System.out.println(" DecryptVisaCheckoutData"); System.out.println(" CreateVisaCheckoutTransaction"); System.out.println(" ChargeCreditCard"); System.out.println(" AuthorizeCreditCard"); System.out.println(" RefundTransaction"); System.out.println(" VoidTransaction"); System.out.println(" CreateCustomerProfileFromTransaction"); System.out.println(" CaptureFundsAuthorizedThroughAnotherChannel"); System.out.println(" CapturePreviouslyAuthorizedAmount"); System.out.println(" DebitBankAccount"); System.out.println(" CreditBankAccount"); System.out.println(" ChargeTokenizedCreditCard"); System.out.println(" CreateAnApplePayTransaction"); System.out.println(" CreateAnAndroidPayTransaction"); System.out.println(" CreateAnAcceptTransaction"); System.out.println(" ChargeCustomerProfile"); System.out.println(" CreateSubscription"); System.out.println(" CreateSubscriptionFromCustomerProfile"); System.out.println(" GetSubscription"); System.out.println(" GetSubscriptionStatus"); System.out.println(" CancelSubscription"); System.out.println(" UpdateSubscription"); System.out.println(" GetListOfSubscriptions"); System.out.println(" GetBatchStatistics"); System.out.println(" GetSettledBatchList"); System.out.println(" GetTransactionList"); System.out.println(" GetUnsettledTransactionList"); System.out.println(" GetTransactionDetails"); System.out.println(" CreateCustomerProfile"); System.out.println(" CreateCustomerPaymentProfile"); System.out.println(" CreateCustomerShippingAddress"); System.out.println(" DeleteCustomerPaymentProfile"); System.out.println(" DeleteCustomerProfile"); System.out.println(" DeleteCustomerShippingAddress"); System.out.println(" GetCustomerPaymentProfile"); System.out.println(" GetCustomerPaymentProfileList"); System.out.println(" GetCustomerProfile"); System.out.println(" GetCustomerProfileIds"); System.out.println(" GetCustomerShippingAddress"); System.out.println(" GetAcceptCustomerProfilePage"); System.out.println(" UpdateCustomerPaymentProfile"); System.out.println(" UpdateCustomerShippingAddress"); System.out.println(" ValidateCustomerPaymentProfile"); System.out.println(" PayPalAuthorizeCapture"); System.out.println(" PayPalVoid"); System.out.println(" PayPalAuthorizationOnly"); System.out.println(" PayPalAuthorizeCaptureContinue"); System.out.println(" PayPalGetDetails"); System.out.println(" PayPalPriorAuthorizationCapture"); System.out.println(" PayPalAuthorizeOnlyContinue"); System.out.println(" PayPalCredit"); System.out.println(" UpdateSplitTenderGroup"); System.out.println(" GetMerchantDetails"); System.out.println(" GetHeldTransactionList"); System.out.println(" ApproveOrDeclineHeldTransaction"); System.out.println(" GetHostedPaymentPage"); } private static void RunMethod(String methodName) { // These are default transaction keys. // You can create your own keys in seconds by signing up for a sandbox account here: https://developer.authorize.net/sandbox/ String apiLoginId = "5KP3u95bQpv"; String transactionKey = "346HZ32z3fP4hTG2"; //Update the payedId with which you want to run the sample code String payerId = "6ZSCSYG33VP8Q"; //Update the transactionId with which you want to run the sample code String transactionId = "123456"; String customerProfileId = "36731856"; String customerPaymentProfileId = "33211899"; String customerAddressId = "123"; String emailId = "[email protected]"; String subscriptionId = "2930242"; Double amount = 123.45; switch (methodName) { case "DecryptVisaCheckoutData": DecryptVisaCheckoutData.run(apiLoginId, transactionKey); break; case "CreateVisaCheckoutTransaction": CreateVisaCheckoutTransaction.run(apiLoginId, transactionKey); break; case "ChargeCreditCard": ChargeCreditCard.run(apiLoginId, transactionKey, amount); break; case "VoidTransaction": VoidTransaction.run(apiLoginId, transactionKey, transactionId); break; case "AuthorizeCreditCard": AuthorizeCreditCard.run(apiLoginId, transactionKey, amount); break; case "RefundTransaction": RefundTransaction.run(apiLoginId, transactionKey , amount, transactionId); break; case "CreateCustomerProfileFromTransaction": CreateCustomerProfileFromTransaction.run(apiLoginId, transactionKey, amount, emailId); break; case "CaptureFundsAuthorizedThroughAnotherChannel": CaptureFundsAuthorizedThroughAnotherChannel.run(apiLoginId, transactionKey, amount); break; case "CapturePreviouslyAuthorizedAmount": CapturePreviouslyAuthorizedAmount.run(apiLoginId, transactionKey, transactionId); break; case "DebitBankAccount": DebitBankAccount.run(apiLoginId, transactionKey, amount); break; case "CreditBankAccount": CreditBankAccount.run(apiLoginId, transactionKey, transactionId, amount); break; case "ChargeTokenizedCreditCard": ChargeTokenizedCreditCard.run(apiLoginId, transactionKey, amount); break; case "CreateAnApplePayTransaction": CreateAnApplePayTransaction.run(apiLoginId, transactionKey); break; case "CreateAnAndroidPayTransaction": CreateAnAndroidPayTransaction.run(apiLoginId, transactionKey); break; case "CreateAnAcceptTransaction": CreateAnAcceptTransaction.run(apiLoginId, transactionKey); break; case "ChargeCustomerProfile": ChargeCustomerProfile.run(apiLoginId, transactionKey, customerProfileId, customerPaymentProfileId, amount); break; case "ChargeCustomerProfilesMT": ChargeCustomerProfilesMT.run(); break; case "CreateSubscription": CreateSubscription.run(apiLoginId, transactionKey, (short)12, amount); break; case "CreateSubscriptionFromCustomerProfile": CreateSubscriptionFromCustomerProfile.run(apiLoginId, transactionKey, (short)12, amount, "123212", "123213", "123213"); break; case "GetSubscription": GetSubscription.run(apiLoginId, transactionKey, subscriptionId); break; case "GetSubscriptionStatus": GetSubscriptionStatus.run(apiLoginId, transactionKey, subscriptionId); break; case "CancelSubscription": CancelSubscription.run(apiLoginId, transactionKey, subscriptionId); break; case "UpdateSubscription": UpdateSubscription.run(apiLoginId, transactionKey, subscriptionId); break; case "GetListOfSubscriptions": GetListOfSubscriptions.run(apiLoginId, transactionKey); break; case "GetBatchStatistics": GetBatchStatistics.run(apiLoginId, transactionKey); break; case "GetSettledBatchList": GetSettledBatchList.run(apiLoginId, transactionKey); break; case "GetTransactionList": GetTransactionList.run(apiLoginId, transactionKey); break; case "GetUnsettledTransactionList": GetUnsettledTransactionList.run(apiLoginId, transactionKey); break; case "GetTransactionDetails": GetTransactionDetails.run(apiLoginId, transactionKey, transactionId); break; case "CreateCustomerProfile": CreateCustomerProfile.run(apiLoginId, transactionKey, emailId); break; case "CreateCustomerPaymentProfile": CreateCustomerPaymentProfile.run(apiLoginId, transactionKey, customerProfileId); break; case "CreateCustomerShippingAddress": CreateCustomerShippingAddress.run(apiLoginId, transactionKey, customerProfileId); break; case "DeleteCustomerPaymentProfile": DeleteCustomerPaymentProfile.run(apiLoginId, transactionKey, customerProfileId, customerPaymentProfileId); break; case "DeleteCustomerProfile": DeleteCustomerProfile.run(apiLoginId, transactionKey, customerProfileId); break; case "DeleteCustomerShippingAddress": DeleteCustomerShippingAddress.run(apiLoginId, transactionKey, customerProfileId, customerAddressId); break; case "GetCustomerPaymentProfile": GetCustomerPaymentProfile.run(apiLoginId, transactionKey, customerProfileId, customerPaymentProfileId); break; case "GetCustomerPaymentProfileList": GetCustomerPaymentProfileList.run(apiLoginId, transactionKey); break; case "GetCustomerProfile": GetCustomerProfile.run(apiLoginId, transactionKey, customerProfileId); break; case "GetCustomerProfileIds": GetCustomerProfileIds.run(apiLoginId, transactionKey); break; case "GetCustomerShippingAddress": GetCustomerShippingAddress.run(apiLoginId, transactionKey, customerProfileId, customerAddressId); break; case "GetAcceptCustomerProfilePage": GetAcceptCustomerProfilePage.run(apiLoginId, transactionKey, customerProfileId); break; case "UpdateCustomerPaymentProfile": UpdateCustomerPaymentProfile.run(apiLoginId, transactionKey, customerProfileId, customerPaymentProfileId); break; case "UpdateCustomerShippingAddress": UpdateCustomerShippingAddress.run(apiLoginId, transactionKey, customerProfileId, customerAddressId); break; case "ValidateCustomerPaymentProfile": ValidateCustomerPaymentProfile.run(apiLoginId, transactionKey, customerProfileId, customerPaymentProfileId); break; case "PayPalAuthorizeCapture": AuthorizationAndCapture.run(apiLoginId, transactionKey, amount); break; case "PayPalVoid": Void.run(apiLoginId, transactionKey, transactionId); break; case "PayPalAuthorizationOnly": AuthorizationOnly.run(apiLoginId, transactionKey, amount); break; case "PayPalAuthorizeCaptureContinue": AuthorizationAndCaptureContinue.run(apiLoginId, transactionKey, transactionId, payerId, amount); break; case "PayPalAuthorizeOnlyContinue": AuthorizationOnlyContinued.run(apiLoginId, transactionKey, transactionId, payerId, amount); break; case "PayPalCredit": Credit.run(apiLoginId, transactionKey, transactionId); break; case "PayPalGetDetails": GetDetails.run(apiLoginId, transactionKey, transactionId); case "PaypalPriorAuthorizationCapture": PriorAuthorizationCapture.run(apiLoginId, transactionKey, transactionId); break; case "UpdateSplitTenderGroup": UpdateSplitTenderGroup.run(apiLoginId, transactionKey); break; case "GetMerchantDetails": GetMerchantDetails.run(apiLoginId, transactionKey); break; case "GetHeldTransactionList": GetHeldTransactionList.run(apiLoginId, transactionKey); break; case "ApproveOrDeclineHeldTransaction": ApproveOrDeclineHeldTransaction.run(apiLoginId, transactionKey, transactionId); break; case "GetHostedPaymentPage": GetHostedPaymentPage.run(apiLoginId, transactionKey, amount); break; default: ShowUsage(); break; } } }
src/main/java/net/authorize/sample/SampleCode.java
package net.authorize.sample; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import net.authorize.sample.VisaCheckout.*; import net.authorize.sample.PaymentTransactions.*; import net.authorize.sample.PaypalExpressCheckout.*; import net.authorize.sample.PaypalExpressCheckout.Void; import net.authorize.sample.RecurringBilling.*; import net.authorize.sample.TransactionReporting.*; import net.authorize.sample.CustomerProfiles.*; import net.authorize.sample.MobileInappTransactions.*; /** * Created by anetdeveloper on 8/5/15. */ public class SampleCode { public static void main( String[] args ) { if (args.length == 0) { SelectMethod(); } else if (args.length == 1) { RunMethod(args[0]); return; } else { ShowUsage(); } System.out.println(""); System.out.print("Press <Return> to finish ..."); BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); try{ int i = Integer.parseInt(br.readLine()); }catch(Exception ex){ } } private static void ShowUsage() { System.out.println("Usage : java -jar SampleCode.jar [CodeSampleName]"); System.out.println(""); System.out.println("Run with no parameter to select a method. Otherwise pass a method name."); System.out.println(""); System.out.println("Code Sample Names: "); ShowMethods(); } private static void SelectMethod() { System.out.println("Code Sample Names: "); System.out.println(""); ShowMethods(); System.out.println(""); System.out.print("Type a sample name & then press <Return> : "); BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); try{ RunMethod(br.readLine()); }catch(Exception ex){ System.out.println(ex.toString()); } } private static void ShowMethods() { System.out.println(" DecryptVisaCheckoutData"); System.out.println(" CreateVisaCheckoutTransaction"); System.out.println(" ChargeCreditCard"); System.out.println(" AuthorizeCreditCard"); System.out.println(" RefundTransaction"); System.out.println(" VoidTransaction"); System.out.println(" CreateCustomerProfileFromTransaction"); System.out.println(" CaptureFundsAuthorizedThroughAnotherChannel"); System.out.println(" CapturePreviouslyAuthorizedAmount"); System.out.println(" DebitBankAccount"); System.out.println(" CreditBankAccount"); System.out.println(" ChargeTokenizedCreditCard"); System.out.println(" CreateAnApplePayTransaction"); System.out.println(" CreateAnAndroidPayTransaction"); System.out.println(" CreateAnAcceptTransaction"); System.out.println(" ChargeCustomerProfile"); System.out.println(" CreateSubscription"); System.out.println(" CreateSubscriptionFromCustomerProfile"); System.out.println(" GetSubscription"); System.out.println(" GetSubscriptionStatus"); System.out.println(" CancelSubscription"); System.out.println(" UpdateSubscription"); System.out.println(" GetListOfSubscriptions"); System.out.println(" GetBatchStatistics"); System.out.println(" GetSettledBatchList"); System.out.println(" GetTransactionList"); System.out.println(" GetUnsettledTransactionList"); System.out.println(" GetTransactionDetails"); System.out.println(" CreateCustomerProfile"); System.out.println(" CreateCustomerPaymentProfile"); System.out.println(" CreateCustomerShippingAddress"); System.out.println(" DeleteCustomerPaymentProfile"); System.out.println(" DeleteCustomerProfile"); System.out.println(" DeleteCustomerShippingAddress"); System.out.println(" GetCustomerPaymentProfile"); System.out.println(" GetCustomerPaymentProfileList"); System.out.println(" GetCustomerProfile"); System.out.println(" GetCustomerProfileIds"); System.out.println(" GetCustomerShippingAddress"); System.out.println(" GetAcceptCustomerProfilePage"); System.out.println(" UpdateCustomerPaymentProfile"); System.out.println(" UpdateCustomerShippingAddress"); System.out.println(" ValidateCustomerPaymentProfile"); System.out.println(" PayPalAuthorizeCapture"); System.out.println(" PayPalVoid"); System.out.println(" PayPalAuthorizationOnly"); System.out.println(" PayPalAuthorizeCaptureContinue"); System.out.println(" PayPalGetDetails"); System.out.println(" PayPalPriorAuthorizationCapture"); System.out.println(" PayPalAuthorizeOnlyContinue"); System.out.println(" PayPalCredit"); System.out.println(" UpdateSplitTenderGroup"); System.out.println(" GetMerchantDetails"); System.out.println(" GetHeldTransactionList"); System.out.println(" ApproveOrDeclineHeldTransaction"); System.out.println(" GetHostedPaymentPage"); } private static void RunMethod(String methodName) { // These are default transaction keys. // You can create your own keys in seconds by signing up for a sandbox account here: https://developer.authorize.net/sandbox/ String apiLoginId = "5KP3u95bQpv"; String transactionKey = "346HZ32z3fP4hTG2"; //Update the payedId with which you want to run the sample code String payerId = "6ZSCSYG33VP8Q"; //Update the transactionId with which you want to run the sample code String transactionId = "123456"; String customerProfileId = "36731856"; String customerPaymentProfileId = "33211899"; String customerAddressId = "123"; String emailId = "[email protected]"; String subscriptionId = "2930242"; Double amount = 123.45; switch (methodName) { case "DecryptVisaCheckoutData": DecryptVisaCheckoutData.run(apiLoginId, transactionKey); break; case "CreateVisaCheckoutTransaction": CreateVisaCheckoutTransaction.run(apiLoginId, transactionKey); break; case "ChargeCreditCard": ChargeCreditCard.run(apiLoginId, transactionKey, amount); break; case "VoidTransaction": VoidTransaction.run(apiLoginId, transactionKey, transactionId); break; case "AuthorizeCreditCard": AuthorizeCreditCard.run(apiLoginId, transactionKey, amount); break; case "RefundTransaction": RefundTransaction.run(apiLoginId, transactionKey , amount, transactionId); break; case "CreateCustomerProfileFromTransaction": CreateCustomerProfileFromTransaction.run(apiLoginId, transactionKey, amount, emailId); break; case "CaptureFundsAuthorizedThroughAnotherChannel": CaptureFundsAuthorizedThroughAnotherChannel.run(apiLoginId, transactionKey, amount); break; case "CapturePreviouslyAuthorizedAmount": CapturePreviouslyAuthorizedAmount.run(apiLoginId, transactionKey, transactionId); break; case "DebitBankAccount": DebitBankAccount.run(apiLoginId, transactionKey, amount); break; case "CreditBankAccount": CreditBankAccount.run(apiLoginId, transactionKey, transactionId, amount); break; case "ChargeTokenizedCreditCard": ChargeTokenizedCreditCard.run(apiLoginId, transactionKey, amount); break; case "CreateAnApplePayTransaction": CreateAnApplePayTransaction.run(apiLoginId, transactionKey); break; case "CreateAnAndroidPayTransaction": CreateAnAndroidPayTransaction.run(apiLoginId, transactionKey); break; case "CreateAnAcceptTransaction": CreateAnAcceptTransaction.run(apiLoginId, transactionKey); break; case "ChargeCustomerProfile": ChargeCustomerProfile.run(apiLoginId, transactionKey, customerProfileId, customerPaymentProfileId, amount); break; case "ChargeCustomerProfilesMT": ChargeCustomerProfilesMT.run(); break; case "CreateSubscription": CreateSubscription.run(apiLoginId, transactionKey, (short)12, amount); break; case "CreateSubscriptionFromCustomerProfile": CreateSubscriptionFromCustomerProfile.run(apiLoginId, transactionKey, (short)12, amount, "123212", "123213", "123213"); break; case "GetSubscription": GetSubscription.run(apiLoginId, transactionKey, subscriptionId); break; case "GetSubscriptionStatus": GetSubscriptionStatus.run(apiLoginId, transactionKey, subscriptionId); break; case "CancelSubscription": CancelSubscription.run(apiLoginId, transactionKey, subscriptionId); break; case "UpdateSubscription": UpdateSubscription.run(apiLoginId, transactionKey, subscriptionId); break; case "GetListOfSubscriptions": GetListOfSubscriptions.run(apiLoginId, transactionKey); break; case "GetBatchStatistics": GetBatchStatistics.run(apiLoginId, transactionKey); break; case "GetSettledBatchList": GetSettledBatchList.run(apiLoginId, transactionKey); break; case "GetTransactionList": GetTransactionList.run(apiLoginId, transactionKey); break; case "GetUnsettledTransactionList": GetUnsettledTransactionList.run(apiLoginId, transactionKey); break; case "GetTransactionDetails": GetTransactionDetails.run(apiLoginId, transactionKey, transactionId); break; case "CreateCustomerProfile": CreateCustomerProfile.run(apiLoginId, transactionKey, emailId); break; case "CreateCustomerPaymentProfile": CreateCustomerPaymentProfile.run(apiLoginId, transactionKey, customerProfileId); break; case "CreateCustomerShippingAddress": CreateCustomerShippingAddress.run(apiLoginId, transactionKey, customerProfileId); break; case "DeleteCustomerPaymentProfile": DeleteCustomerPaymentProfile.run(apiLoginId, transactionKey, customerProfileId, customerPaymentProfileId); break; case "DeleteCustomerProfile": DeleteCustomerProfile.run(apiLoginId, transactionKey, customerProfileId); break; case "DeleteCustomerShippingAddress": DeleteCustomerShippingAddress.run(apiLoginId, transactionKey, customerProfileId, customerAddressId); break; case "GetCustomerPaymentProfile": GetCustomerPaymentProfile.run(apiLoginId, transactionKey, customerProfileId, customerPaymentProfileId); break; case "GetCustomerPaymentProfileList": GetCustomerPaymentProfileList.run(apiLoginId, transactionKey); break; case "GetCustomerProfile": GetCustomerProfile.run(apiLoginId, transactionKey, customerProfileId); break; case "GetCustomerProfileIds": GetCustomerProfileIds.run(apiLoginId, transactionKey); break; case "GetCustomerShippingAddress": GetCustomerShippingAddress.run(apiLoginId, transactionKey, customerProfileId, customerAddressId); break; case "GetAcceptCustomerProfilePage": GetAcceptCustomerProfilePage.run(apiLoginId, transactionKey, customerProfileId); break; case "UpdateCustomerPaymentProfile": UpdateCustomerPaymentProfile.run(apiLoginId, transactionKey, customerProfileId, customerPaymentProfileId); break; case "UpdateCustomerShippingAddress": UpdateCustomerShippingAddress.run(apiLoginId, transactionKey, customerProfileId, customerAddressId); break; case "ValidateCustomerPaymentProfile": ValidateCustomerPaymentProfile.run(apiLoginId, transactionKey, customerProfileId, customerPaymentProfileId); break; case "PayPalAuthorizeCapture": AuthorizationAndCapture.run(apiLoginId, transactionKey, amount); break; case "PayPalVoid": Void.run(apiLoginId, transactionKey, transactionId); break; case "PayPalAuthorizationOnly": AuthorizationOnly.run(apiLoginId, transactionKey, amount); break; case "PayPalAuthorizeCaptureContinue": AuthorizationAndCaptureContinue.run(apiLoginId, transactionKey, transactionId, payerId, amount); break; case "PayPalAuthorizeOnlyContinue": AuthorizationOnlyContinued.run(apiLoginId, transactionKey, transactionId, payerId, amount); break; case "PayPalCredit": Credit.run(apiLoginId, transactionKey, transactionId); break; case "PayPalGetDetails": GetDetails.run(apiLoginId, transactionKey, transactionId); case "PaypalPriorAuthorizationCapture": PriorAuthorizationCapture.run(apiLoginId, transactionKey, transactionId); break; case "UpdateSplitTenderGroup": UpdateSplitTenderGroup.run(apiLoginId, transactionKey); break; case "GetMerchantDetails": GetMerchantDetails.run(apiLoginId, transactionKey); break; case "GetHeldTransactionList": GetHeldTransactionList.run(apiLoginId, transactionKey); break; case "ApproveOrDeclineHeldTransaction": ApproveOrDeclineHeldTransaction.run(apiLoginId, transactionKey, transactionId); break; case "GetHostedPaymentPage": GetHostedPaymentPage.run(apiLoginId, transactionKey, amount); break; default: ShowUsage(); break; } } }
fix the namespace for the main file
src/main/java/net/authorize/sample/SampleCode.java
fix the namespace for the main file
<ide><path>rc/main/java/net/authorize/sample/SampleCode.java <ide> import net.authorize.sample.TransactionReporting.*; <ide> import net.authorize.sample.CustomerProfiles.*; <ide> import net.authorize.sample.MobileInappTransactions.*; <add>import net.authorize.sample.FraudManagement.*; <ide> /** <ide> * Created by anetdeveloper on 8/5/15. <ide> */
Java
mit
938e08029308df5b30c02701a80c3a10dea57d71
0
amwenger/igv,amwenger/igv,godotgildor/igv,godotgildor/igv,godotgildor/igv,amwenger/igv,amwenger/igv,igvteam/igv,itenente/igv,itenente/igv,itenente/igv,amwenger/igv,igvteam/igv,igvteam/igv,godotgildor/igv,itenente/igv,godotgildor/igv,igvteam/igv,itenente/igv,igvteam/igv
/* * Copyright (c) 2007-2011 by The Broad Institute of MIT and Harvard. All Rights Reserved. * * This software is licensed under the terms of the GNU Lesser General Public License (LGPL), * Version 2.1 which is available at http://www.opensource.org/licenses/lgpl-2.1.php. * * THE SOFTWARE IS PROVIDED "AS IS." THE BROAD AND MIT MAKE NO REPRESENTATIONS OR * WARRANTES OF ANY KIND CONCERNING THE SOFTWARE, EXPRESS OR IMPLIED, INCLUDING, * WITHOUT LIMITATION, WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR * PURPOSE, NONINFRINGEMENT, OR THE ABSENCE OF LATENT OR OTHER DEFECTS, WHETHER * OR NOT DISCOVERABLE. IN NO EVENT SHALL THE BROAD OR MIT, OR THEIR RESPECTIVE * TRUSTEES, DIRECTORS, OFFICERS, EMPLOYEES, AND AFFILIATES BE LIABLE FOR ANY DAMAGES * OF ANY KIND, INCLUDING, WITHOUT LIMITATION, INCIDENTAL OR CONSEQUENTIAL DAMAGES, * ECONOMIC DAMAGES OR INJURY TO PROPERTY AND LOST PROFITS, REGARDLESS OF WHETHER * THE BROAD OR MIT SHALL BE ADVISED, SHALL HAVE OTHER REASON TO KNOW, OR IN FACT * SHALL KNOW OF THE POSSIBILITY OF THE FOREGOING. */ package org.broad.igv.session; import org.apache.log4j.Logger; import org.broad.igv.Globals; import org.broad.igv.feature.RegionOfInterest; import org.broad.igv.lists.GeneList; import org.broad.igv.lists.GeneListManager; import org.broad.igv.renderer.ColorScale; import org.broad.igv.renderer.ColorScaleFactory; import org.broad.igv.renderer.ContinuousColorScale; import org.broad.igv.renderer.DataRange; import org.broad.igv.track.*; import org.broad.igv.ui.IGV; import org.broad.igv.ui.TrackFilter; import org.broad.igv.ui.TrackFilterElement; import org.broad.igv.ui.color.ColorUtilities; import org.broad.igv.ui.panel.FrameManager; import org.broad.igv.ui.panel.ReferenceFrame; import org.broad.igv.ui.panel.TrackPanel; import org.broad.igv.ui.util.MessageUtils; import org.broad.igv.util.*; import org.broad.igv.util.FilterElement.BooleanOperator; import org.broad.igv.util.FilterElement.Operator; import org.w3c.dom.*; import org.xml.sax.SAXException; import javax.xml.parsers.DocumentBuilder; import javax.xml.parsers.DocumentBuilderFactory; import javax.xml.parsers.ParserConfigurationException; import java.awt.*; import java.io.File; import java.io.IOException; import java.io.InputStream; import java.util.*; import java.util.List; /** * Class to parse an IGV session file */ public class IGVSessionReader implements SessionReader { private static Logger log = Logger.getLogger(IGVSessionReader.class); private static String INPUT_FILE_KEY = "INPUT_FILE_KEY"; // Temporary values used in processing private Collection<ResourceLocator> dataFiles; private Collection<ResourceLocator> missingDataFiles; private static Map<String, String> attributeSynonymMap = new HashMap(); private boolean panelElementPresent = false; private int version; private IGV igv; /** * Map of track id -> track. It is important to maintin the order in which tracks are added, thus * the use of LinkedHashMap. */ Map<String, List<Track>> trackDictionary = Collections.synchronizedMap(new LinkedHashMap()); private Track geneTrack = null; private Track seqTrack = null; private boolean hasTrackElments; static { attributeSynonymMap.put("DATA FILE", "DATA SET"); attributeSynonymMap.put("TRACK NAME", "NAME"); } /** * Session Element types */ public static enum SessionElement { PANEL("Panel"), PANEL_LAYOUT("PanelLayout"), TRACK("Track"), COLOR_SCALE("ColorScale"), COLOR_SCALES("ColorScales"), DATA_TRACK("DataTrack"), DATA_TRACKS("DataTracks"), FEATURE_TRACKS("FeatureTracks"), DATA_FILE("DataFile"), RESOURCE("Resource"), RESOURCES("Resources"), FILES("Files"), FILTER_ELEMENT("FilterElement"), FILTER("Filter"), SESSION("Session"), GLOBAL("Global"), REGION("Region"), REGIONS("Regions"), DATA_RANGE("DataRange"), PREFERENCES("Preferences"), PROPERTY("Property"), GENE_LIST("GeneList"), HIDDEN_ATTRIBUTES("HiddenAttributes"), VISIBLE_ATTRIBUTES("VisibleAttributes"), ATTRIBUTE("Attribute"), VISIBLE_ATTRIBUTE("VisibleAttribute"), FRAME("Frame"); private String name; SessionElement(String name) { this.name = name; } public String getText() { return name; } @Override public String toString() { return getText(); } static public SessionElement findEnum(String value) { if (value == null) { return null; } else { return SessionElement.valueOf(value); } } } /** * Session Attribute types */ public static enum SessionAttribute { BOOLEAN_OPERATOR("booleanOperator"), COLOR("color"), ALT_COLOR("altColor"), COLOR_MODE("colorMode"), CHROMOSOME("chromosome"), END_INDEX("end"), EXPAND("expand"), SQUISH("squish"), DISPLAY_MODE("displayMode"), FILTER_MATCH("match"), FILTER_SHOW_ALL_TRACKS("showTracks"), GENOME("genome"), GROUP_TRACKS_BY("groupTracksBy"), HEIGHT("height"), ID("id"), ITEM("item"), LOCUS("locus"), NAME("name"), SAMPLE_ID("sampleID"), RESOURCE_TYPE("resourceType"), OPERATOR("operator"), RELATIVE_PATH("relativePath"), RENDERER("renderer"), SCALE("scale"), START_INDEX("start"), VALUE("value"), VERSION("version"), VISIBLE("visible"), WINDOW_FUNCTION("windowFunction"), RENDER_NAME("renderName"), GENOTYPE_HEIGHT("genotypeHeight"), VARIANT_HEIGHT("variantHeight"), PREVIOUS_HEIGHT("previousHeight"), FEATURE_WINDOW("featureVisibilityWindow"), DISPLAY_NAME("displayName"), COLOR_SCALE("colorScale"), //RESOURCE ATTRIBUTES PATH("path"), LABEL("label"), SERVER_URL("serverURL"), HYPERLINK("hyperlink"), INFOLINK("infolink"), URL("url"), FEATURE_URL("featureURL"), DESCRIPTION("description"), TYPE("type"), COVERAGE("coverage"), TRACK_LINE("trackLine"), CHR("chr"), START("start"), END("end"); //TODO Add the following into the Attributes /* boolean shadeBases; boolean shadeCenters; boolean flagUnmappedPairs; boolean showAllBases; int insertSizeThreshold; boolean colorByStrand; boolean colorByAmpliconStrand; */ private String name; SessionAttribute(String name) { this.name = name; } public String getText() { return name; } @Override public String toString() { return getText(); } static public SessionAttribute findEnum(String value) { if (value == null) { return null; } else { return SessionAttribute.valueOf(value); } } } public IGVSessionReader(IGV igv) { this.igv = igv; } /** * @param inputStream * @param session * @param sessionName @return * @throws RuntimeException */ public void loadSession(InputStream inputStream, Session session, String sessionName) { log.debug("Load session"); Document document = null; try { document = createDOMDocumentFromXmlFile(inputStream); } catch (Exception e) { log.error("Session Management Error", e); throw new RuntimeException(e); } NodeList tracks = document.getElementsByTagName("Track"); hasTrackElments = tracks.getLength() > 0; HashMap additionalInformation = new HashMap(); additionalInformation.put(INPUT_FILE_KEY, sessionName); NodeList nodes = document.getElementsByTagName(SessionElement.GLOBAL.getText()); if (nodes == null || nodes.getLength() == 0) { nodes = document.getElementsByTagName(SessionElement.SESSION.getText()); } processRootNode(session, nodes.item(0), additionalInformation); // Add tracks not explicitly set in file. It is legal to define sessions with the DataFile section only (no // Panel or Track elements). addLeftoverTracks(trackDictionary.values()); if (session.getGroupTracksBy() != null && session.getGroupTracksBy().length() > 0) { igv.setGroupByAttribute(session.getGroupTracksBy()); } if (session.isRemoveEmptyPanels()) { igv.getMainPanel().removeEmptyDataPanels(); } igv.resetOverlayTracks(); } private void processRootNode(Session session, Node node, HashMap additionalInformation) { if ((node == null) || (session == null)) { MessageUtils.showMessage("Invalid session file: root node not found"); return; } String nodeName = node.getNodeName(); if (!(nodeName.equalsIgnoreCase(SessionElement.GLOBAL.getText()) || nodeName.equalsIgnoreCase(SessionElement.SESSION.getText()))) { MessageUtils.showMessage("Session files must begin with a \"Global\" or \"Session\" element. Found: " + nodeName); } process(session, node, additionalInformation); Element element = (Element) node; // Load the genome, which can be an ID, or a path or URL to a .genome or indexed fasta file. String genome = getAttribute(element, SessionAttribute.GENOME.getText()); if (genome != null && genome.length() > 0) { // THis is a hack, and a bad one, but selecting a genome will actually "reset" the session so we have to // save the path and restore it. String sessionPath = session.getPath(); if (IGV.getInstance().getGenomeIds().contains(genome)) { IGV.getInstance().selectGenomeFromList(genome); } else { String genomePath = genome; if (!ParsingUtils.pathExists(genomePath)) { genomePath = getAbsolutePath(genome, session.getPath()); } if (ParsingUtils.pathExists(genomePath)) { try { IGV.getInstance().loadGenome(genomePath, null); } catch (IOException e) { throw new RuntimeException("Error loading genome: " + genome); } } else { MessageUtils.showMessage("Warning: Could not locate genome: " + genome); } } session.setPath(sessionPath); } session.setLocus(getAttribute(element, SessionAttribute.LOCUS.getText())); session.setGroupTracksBy(getAttribute(element, SessionAttribute.GROUP_TRACKS_BY.getText())); String removeEmptyTracks = getAttribute(element, "removeEmptyTracks"); if (removeEmptyTracks != null) { try { Boolean b = Boolean.parseBoolean(removeEmptyTracks); session.setRemoveEmptyPanels(b); } catch (Exception e) { log.error("Error parsing removeEmptyTracks string: " + removeEmptyTracks, e); } } String versionString = getAttribute(element, SessionAttribute.VERSION.getText()); try { version = Integer.parseInt(versionString); } catch (NumberFormatException e) { log.error("Non integer version number in session file: " + versionString); } session.setVersion(version); geneTrack = igv.getGeneTrack(); if (geneTrack != null) { trackDictionary.put(geneTrack.getId(), Arrays.asList(geneTrack)); } seqTrack = igv.getSequenceTrack(); if (seqTrack != null) { trackDictionary.put(seqTrack.getId(), Arrays.asList(seqTrack)); } NodeList elements = element.getChildNodes(); process(session, elements, additionalInformation); // ReferenceFrame.getInstance().invalidateLocationScale(); } //TODO Check to make sure tracks are not being created twice //TODO -- DONT DO THIS FOR NEW SESSIONS private void addLeftoverTracks(Collection<List<Track>> tmp) { Map<String, TrackPanel> trackPanelCache = new HashMap(); if (version < 3 || !panelElementPresent) { for (List<Track> tracks : tmp) { for (Track track : tracks) { if (track != geneTrack && track != seqTrack && track.getResourceLocator() != null) { TrackPanel panel = trackPanelCache.get(track.getResourceLocator().getPath()); if (panel == null) { panel = IGV.getInstance().getPanelFor(track.getResourceLocator()); trackPanelCache.put(track.getResourceLocator().getPath(), panel); } panel.addTrack(track); } } } } } /** * Process a single session element node. * * @param session * @param element */ private void process(Session session, Node element, HashMap additionalInformation) { if ((element == null) || (session == null)) { return; } String nodeName = element.getNodeName(); if (nodeName.equalsIgnoreCase(SessionElement.RESOURCES.getText()) || nodeName.equalsIgnoreCase(SessionElement.FILES.getText())) { processResources(session, (Element) element, additionalInformation); } else if (nodeName.equalsIgnoreCase(SessionElement.RESOURCE.getText()) || nodeName.equalsIgnoreCase(SessionElement.DATA_FILE.getText())) { processResource(session, (Element) element, additionalInformation); } else if (nodeName.equalsIgnoreCase(SessionElement.REGIONS.getText())) { processRegions(session, (Element) element, additionalInformation); } else if (nodeName.equalsIgnoreCase(SessionElement.REGION.getText())) { processRegion(session, (Element) element, additionalInformation); } else if (nodeName.equalsIgnoreCase(SessionElement.GENE_LIST.getText())) { processGeneList(session, (Element) element, additionalInformation); } else if (nodeName.equalsIgnoreCase(SessionElement.FILTER.getText())) { processFilter(session, (Element) element, additionalInformation); } else if (nodeName.equalsIgnoreCase(SessionElement.FILTER_ELEMENT.getText())) { processFilterElement(session, (Element) element, additionalInformation); } else if (nodeName.equalsIgnoreCase(SessionElement.COLOR_SCALES.getText())) { processColorScales(session, (Element) element, additionalInformation); } else if (nodeName.equalsIgnoreCase(SessionElement.COLOR_SCALE.getText())) { processColorScale(session, (Element) element, additionalInformation); } else if (nodeName.equalsIgnoreCase(SessionElement.PREFERENCES.getText())) { processPreferences(session, (Element) element, additionalInformation); } else if (nodeName.equalsIgnoreCase(SessionElement.DATA_TRACKS.getText()) || nodeName.equalsIgnoreCase(SessionElement.FEATURE_TRACKS.getText()) || nodeName.equalsIgnoreCase(SessionElement.PANEL.getText())) { processPanel(session, (Element) element, additionalInformation); } else if (nodeName.equalsIgnoreCase(SessionElement.PANEL_LAYOUT.getText())) { processPanelLayout(session, (Element) element, additionalInformation); } else if (nodeName.equalsIgnoreCase(SessionElement.HIDDEN_ATTRIBUTES.getText())) { processHiddenAttributes(session, (Element) element, additionalInformation); } else if (nodeName.equalsIgnoreCase(SessionElement.VISIBLE_ATTRIBUTES.getText())) { processVisibleAttributes(session, (Element) element, additionalInformation); } } private void processResources(Session session, Element element, HashMap additionalInformation) { dataFiles = new ArrayList(); missingDataFiles = new ArrayList(); NodeList elements = element.getChildNodes(); process(session, elements, additionalInformation); if (missingDataFiles.size() > 0) { StringBuffer message = new StringBuffer(); message.append("<html>The following data file(s) could not be located.<ul>"); for (ResourceLocator file : missingDataFiles) { if (file.isLocal()) { message.append("<li>"); message.append(file.getPath()); message.append("</li>"); } else { message.append("<li>Server: "); message.append(file.getServerURL()); message.append(" Path: "); message.append(file.getPath()); message.append("</li>"); } } message.append("</ul>"); message.append("Common reasons for this include: "); message.append("<ul><li>The session or data files have been moved.</li> "); message.append("<li>The data files are located on a drive that is not currently accessible.</li></ul>"); message.append("</html>"); MessageUtils.showMessage(message.toString()); } if (dataFiles.size() > 0) { final List<String> errors = new ArrayList<String>(); // Load files concurrently -- TODO, put a limit on # of threads? List<Thread> threads = new ArrayList(dataFiles.size()); long t0 = System.currentTimeMillis(); int i = 0; List<Runnable> synchronousLoads = new ArrayList<Runnable>(); for (final ResourceLocator locator : dataFiles) { Runnable runnable = new Runnable() { public void run() { List<Track> tracks = null; try { tracks = igv.load(locator); for (Track track : tracks) { if (track == null) log.info("Null track for resource " + locator.getPath()); String id = track.getId(); if (id == null) log.info("Null track id for resource " + locator.getPath()); List<Track> trackList = trackDictionary.get(id); if (trackList == null) { trackList = new ArrayList(); trackDictionary.put(id, trackList); } trackList.add(track); } } catch (Exception e) { log.error("Error loading resource " + locator.getPath(), e); String ms = "<b>" + locator.getPath() + "</b><br>&nbs;p&nbsp;" + e.toString() + "<br>"; errors.add(ms); } } }; boolean isAlignment = locator.getPath().endsWith(".bam") || locator.getPath().endsWith(".entries") || locator.getPath().endsWith(".sam"); // Run synchronously if in batch mode or if there are no "track" elments, or if this is an alignment file if (isAlignment || Globals.isBatch() || !hasTrackElments) { synchronousLoads.add(runnable); } else { Thread t = new Thread(runnable); threads.add(t); t.start(); } i++; } // Wait for all threads to complete for (Thread t : threads) { try { t.join(); } catch (InterruptedException ignore) { } } // Now load data that must be loaded synchronously for (Runnable runnable : synchronousLoads) { runnable.run(); } long dt = System.currentTimeMillis() - t0; log.debug("Total load time = " + dt); if (errors.size() > 0) { StringBuffer buf = new StringBuffer(); buf.append("<html>Errors were encountered loading the session:<br>"); for (String msg : errors) { buf.append(msg); } MessageUtils.showMessage(buf.toString()); } } dataFiles = null; } private void processResource(Session session, Element element, HashMap additionalInformation) { String nodeName = element.getNodeName(); boolean oldSession = nodeName.equals(SessionElement.DATA_FILE.getText()); String label = getAttribute(element, SessionAttribute.LABEL.getText()); String name = getAttribute(element, SessionAttribute.NAME.getText()); String sampleId = getAttribute(element, SessionAttribute.SAMPLE_ID.getText()); String description = getAttribute(element, SessionAttribute.DESCRIPTION.getText()); String type = getAttribute(element, SessionAttribute.TYPE.getText()); String coverage = getAttribute(element, SessionAttribute.COVERAGE.getText()); String trackLine = getAttribute(element, SessionAttribute.TRACK_LINE.getText()); String colorString = getAttribute(element, SessionAttribute.COLOR.getText()); String relPathValue = getAttribute(element, SessionAttribute.RELATIVE_PATH.getText()); boolean isRelativePath = ((relPathValue != null) && relPathValue.equalsIgnoreCase("true")); String serverURL = getAttribute(element, SessionAttribute.SERVER_URL.getText()); // Older sessions used the "name" attribute for the path. String path = getAttribute(element, SessionAttribute.PATH.getText()); if (oldSession && name != null) { path = name; int idx = name.lastIndexOf("/"); if (idx > 0 && idx + 1 < name.length()) { name = name.substring(idx + 1); } } ResourceLocator resourceLocator = new ResourceLocator(serverURL, path); if (isRelativePath) { final String sessionPath = session.getPath(); String absolutePath; if (sessionPath == null) { log.error("Null session path -- this is not expected"); MessageUtils.showMessage("Unexpected error loading session: null session path"); return; } absolutePath = getAbsolutePath(path, sessionPath); resourceLocator = new ResourceLocator(serverURL, absolutePath); } String url = getAttribute(element, SessionAttribute.URL.getText()); if (url == null) { url = getAttribute(element, SessionAttribute.FEATURE_URL.getText()); } resourceLocator.setUrl(url); String infolink = getAttribute(element, SessionAttribute.HYPERLINK.getText()); if (infolink == null) { infolink = getAttribute(element, SessionAttribute.INFOLINK.getText()); } resourceLocator.setInfolink(infolink); // Label is deprecated in favor of name. if (name != null) { resourceLocator.setName(name); } else { resourceLocator.setName(label); } resourceLocator.setSampleId(sampleId); resourceLocator.setDescription(description); // This test added to get around earlier bug in the writer if (type != null && !type.equals("local")) { resourceLocator.setType(type); } resourceLocator.setCoverage(coverage); resourceLocator.setTrackLine(trackLine); if (colorString != null) { try { Color c = ColorUtilities.stringToColor(colorString); resourceLocator.setColor(c); } catch (Exception e) { log.error("Error setting color: ", e); } } dataFiles.add(resourceLocator); NodeList elements = element.getChildNodes(); process(session, elements, additionalInformation); } private String getAbsolutePath(String path, String sessionPath) { String absolutePath; if (FileUtils.isRemote(sessionPath)) { int idx = sessionPath.lastIndexOf("/"); String basePath = sessionPath.substring(0, idx); absolutePath = basePath + "/" + path; } else { File parent = new File(sessionPath).getParentFile(); File file = new File(parent, path); absolutePath = file.getAbsolutePath(); } return absolutePath; } private void processRegions(Session session, Element element, HashMap additionalInformation) { session.clearRegionsOfInterest(); NodeList elements = element.getChildNodes(); process(session, elements, additionalInformation); } private void processRegion(Session session, Element element, HashMap additionalInformation) { String chromosome = getAttribute(element, SessionAttribute.CHROMOSOME.getText()); String start = getAttribute(element, SessionAttribute.START_INDEX.getText()); String end = getAttribute(element, SessionAttribute.END_INDEX.getText()); String description = getAttribute(element, SessionAttribute.DESCRIPTION.getText()); RegionOfInterest region = new RegionOfInterest(chromosome, new Integer(start), new Integer(end), description); IGV.getInstance().addRegionOfInterest(region); NodeList elements = element.getChildNodes(); process(session, elements, additionalInformation); } private void processHiddenAttributes(Session session, Element element, HashMap additionalInformation) { // session.clearRegionsOfInterest(); NodeList elements = element.getChildNodes(); if (elements.getLength() > 0) { Set<String> attributes = new HashSet(); for (int i = 0; i < elements.getLength(); i++) { Node childNode = elements.item(i); if (childNode.getNodeName().equals(IGVSessionReader.SessionElement.ATTRIBUTE.getText())) { attributes.add(((Element) childNode).getAttribute(IGVSessionReader.SessionAttribute.NAME.getText())); } } session.setHiddenAttributes(attributes); } } /** * For backward compatibility * * @param session * @param element * @param additionalInformation */ private void processVisibleAttributes(Session session, Element element, HashMap additionalInformation) { // session.clearRegionsOfInterest(); NodeList elements = element.getChildNodes(); if (elements.getLength() > 0) { Set<String> visibleAttributes = new HashSet(); for (int i = 0; i < elements.getLength(); i++) { Node childNode = elements.item(i); if (childNode.getNodeName().equals(IGVSessionReader.SessionElement.VISIBLE_ATTRIBUTE.getText())) { visibleAttributes.add(((Element) childNode).getAttribute(IGVSessionReader.SessionAttribute.NAME.getText())); } } final List<String> attributeNames = AttributeManager.getInstance().getAttributeNames(); Set<String> hiddenAttributes = new HashSet<String>(attributeNames); hiddenAttributes.removeAll(visibleAttributes); session.setHiddenAttributes(hiddenAttributes); } } private void processGeneList(Session session, Element element, HashMap additionalInformation) { String name = getAttribute(element, SessionAttribute.NAME.getText()); String txt = element.getTextContent(); String[] genes = txt.trim().split("\\s+"); GeneList gl = new GeneList(name, Arrays.asList(genes)); GeneListManager.getInstance().addGeneList(gl); session.setCurrentGeneList(gl); // Adjust frames processFrames(element); } private void processFrames(Element element) { NodeList elements = element.getChildNodes(); if (elements.getLength() > 0) { Map<String, ReferenceFrame> frames = new HashMap(); for (ReferenceFrame f : FrameManager.getFrames()) { frames.put(f.getName(), f); } List<ReferenceFrame> reorderedFrames = new ArrayList(); for (int i = 0; i < elements.getLength(); i++) { Node childNode = elements.item(i); if (childNode.getNodeName().equalsIgnoreCase(SessionElement.FRAME.getText())) { String frameName = getAttribute((Element) childNode, SessionAttribute.NAME.getText()); ReferenceFrame f = frames.get(frameName); if (f != null) { reorderedFrames.add(f); try { String chr = getAttribute((Element) childNode, SessionAttribute.CHR.getText()); final String startString = getAttribute((Element) childNode, SessionAttribute.START.getText()).replace(",", ""); final String endString = getAttribute((Element) childNode, SessionAttribute.END.getText()).replace(",", ""); int start = ParsingUtils.parseInt(startString); int end = ParsingUtils.parseInt(endString); f.setInterval(chr, start, end); } catch (NumberFormatException e) { e.printStackTrace(); //To change body of catch statement use File | Settings | File Templates. } } } } if (reorderedFrames.size() > 0) { FrameManager.setFrames(reorderedFrames); } } IGV.getInstance().resetFrames(); } private void processFilter(Session session, Element element, HashMap additionalInformation) { String match = getAttribute(element, SessionAttribute.FILTER_MATCH.getText()); String showAllTracks = getAttribute(element, SessionAttribute.FILTER_SHOW_ALL_TRACKS.getText()); String filterName = getAttribute(element, SessionAttribute.NAME.getText()); TrackFilter filter = new TrackFilter(filterName, null); additionalInformation.put(SessionElement.FILTER, filter); NodeList elements = element.getChildNodes(); process(session, elements, additionalInformation); // Save the filter session.setFilter(filter); // Set filter properties if ("all".equalsIgnoreCase(match)) { IGV.getInstance().setFilterMatchAll(true); } else if ("any".equalsIgnoreCase(match)) { IGV.getInstance().setFilterMatchAll(false); } if ("true".equalsIgnoreCase(showAllTracks)) { IGV.getInstance().setFilterShowAllTracks(true); } else { IGV.getInstance().setFilterShowAllTracks(false); } } private void processFilterElement(Session session, Element element, HashMap additionalInformation) { TrackFilter filter = (TrackFilter) additionalInformation.get(SessionElement.FILTER); String item = getAttribute(element, SessionAttribute.ITEM.getText()); String operator = getAttribute(element, SessionAttribute.OPERATOR.getText()); String value = getAttribute(element, SessionAttribute.VALUE.getText()); String booleanOperator = getAttribute(element, SessionAttribute.BOOLEAN_OPERATOR.getText()); TrackFilterElement trackFilterElement = new TrackFilterElement(filter, item, Operator.findEnum(operator), value, BooleanOperator.findEnum(booleanOperator)); filter.add(trackFilterElement); NodeList elements = element.getChildNodes(); process(session, elements, additionalInformation); } /** * A counter to generate unique panel names. Needed for backward-compatibility of old session files. */ private int panelCounter = 1; private void processPanel(Session session, Element element, HashMap additionalInformation) { panelElementPresent = true; String panelName = element.getAttribute("name"); if (panelName == null) { panelName = "Panel" + panelCounter++; } List<Track> panelTracks = new ArrayList(); NodeList elements = element.getChildNodes(); for (int i = 0; i < elements.getLength(); i++) { Node childNode = elements.item(i); if (childNode.getNodeName().equalsIgnoreCase(SessionElement.DATA_TRACK.getText()) || // Is this a track? childNode.getNodeName().equalsIgnoreCase(SessionElement.TRACK.getText())) { List<Track> tracks = processTrack(session, (Element) childNode, additionalInformation); if (tracks != null) { panelTracks.addAll(tracks); } } else { process(session, childNode, additionalInformation); } } TrackPanel panel = IGV.getInstance().getTrackPanel(panelName); panel.addTracks(panelTracks); } private void processPanelLayout(Session session, Element element, HashMap additionalInformation) { String nodeName = element.getNodeName(); String panelName = nodeName; NamedNodeMap tNodeMap = element.getAttributes(); for (int i = 0; i < tNodeMap.getLength(); i++) { Node node = tNodeMap.item(i); String name = node.getNodeName(); if (name.equals("dividerFractions")) { String value = node.getNodeValue(); String[] tokens = value.split(","); double[] divs = new double[tokens.length]; try { for (int j = 0; j < tokens.length; j++) { divs[j] = Double.parseDouble(tokens[j]); } session.setDividerFractions(divs); } catch (NumberFormatException e) { log.error("Error parsing divider locations", e); } } } } /** * Process a track element. This should return a single track, but could return multiple tracks since the * uniqueness of the track id is not enforced. * * @param session * @param element * @param additionalInformation * @return */ private List<Track> processTrack(Session session, Element element, HashMap additionalInformation) { String id = getAttribute(element, SessionAttribute.ID.getText()); // TODo -- put in utility method, extacts attributes from element **Definitely need to do this HashMap<String, String> tAttributes = new HashMap(); HashMap<String, String> drAttributes = null; NamedNodeMap tNodeMap = element.getAttributes(); for (int i = 0; i < tNodeMap.getLength(); i++) { Node node = tNodeMap.item(i); String value = node.getNodeValue(); if (value != null && value.length() > 0) { tAttributes.put(node.getNodeName(), value); } } if (element.hasChildNodes()) { drAttributes = new HashMap(); Node childNode = element.getFirstChild(); Node sibNode = childNode.getNextSibling(); String sibName = sibNode.getNodeName(); if (sibName.equals(SessionElement.DATA_RANGE.getText())) { NamedNodeMap drNodeMap = sibNode.getAttributes(); for (int i = 0; i < drNodeMap.getLength(); i++) { Node node = drNodeMap.item(i); String value = node.getNodeValue(); if (value != null && value.length() > 0) { drAttributes.put(node.getNodeName(), value); } } } } // Get matching tracks. The trackNameDictionary is used for pre V 2 files, where ID was loosely defined List<Track> matchedTracks = trackDictionary.get(id); if (matchedTracks == null) { log.info("Warning. No tracks were found with id: " + id + " in session file"); } else { for (final Track track : matchedTracks) { // Special case for sequence & gene tracks, they need to be removed before being placed. if (version >= 4 && track == geneTrack || track == seqTrack) { igv.removeTracks(Arrays.asList(track)); } track.restorePersistentState(tAttributes); if (drAttributes != null) { DataRange dr = track.getDataRange(); dr.restorePersistentState(drAttributes); track.setDataRange(dr); } } trackDictionary.remove(id); } NodeList elements = element.getChildNodes(); process(session, elements, additionalInformation); return matchedTracks; } private void processColorScales(Session session, Element element, HashMap additionalInformation) { NodeList elements = element.getChildNodes(); process(session, elements, additionalInformation); } private void processColorScale(Session session, Element element, HashMap additionalInformation) { String trackType = getAttribute(element, SessionAttribute.TYPE.getText()); String value = getAttribute(element, SessionAttribute.VALUE.getText()); setColorScaleSet(session, trackType, value); NodeList elements = element.getChildNodes(); process(session, elements, additionalInformation); } private void processPreferences(Session session, Element element, HashMap additionalInformation) { NodeList elements = element.getChildNodes(); for (int i = 0; i < elements.getLength(); i++) { Node child = elements.item(i); if (child.getNodeName().equalsIgnoreCase(SessionElement.PROPERTY.getText())) { Element childNode = (Element) child; String name = getAttribute(childNode, SessionAttribute.NAME.getText()); String value = getAttribute(childNode, SessionAttribute.VALUE.getText()); session.setPreference(name, value); } } } /** * Process a list of session element nodes. * * @param session * @param elements */ private void process(Session session, NodeList elements, HashMap additionalInformation) { for (int i = 0; i < elements.getLength(); i++) { Node childNode = elements.item(i); process(session, childNode, additionalInformation); } } /** * Reads an xml from an input file and creates DOM document. * * @param * @return * @throws ParserConfigurationException * @throws IOException * @throws SAXException */ private Document createDOMDocumentFromXmlFile(InputStream inputStream) throws ParserConfigurationException, IOException, SAXException { DocumentBuilder documentBuilder = DocumentBuilderFactory.newInstance().newDocumentBuilder(); Document xmlDocument = documentBuilder.parse(inputStream); return xmlDocument; } public void setColorScaleSet(Session session, String type, String value) { if (type == null | value == null) { return; } TrackType trackType = TrackType.OTHER; if (TrackType.ALLELE_SPECIFIC_COPY_NUMBER.name().equalsIgnoreCase(type)) { trackType = TrackType.ALLELE_SPECIFIC_COPY_NUMBER; } else if (TrackType.CHIP.name().equalsIgnoreCase(type)) { trackType = TrackType.CHIP; } else if (TrackType.COPY_NUMBER.name().equalsIgnoreCase(type)) { trackType = TrackType.COPY_NUMBER; } else if (TrackType.DNA_METHYLATION.name().equalsIgnoreCase(type)) { trackType = TrackType.DNA_METHYLATION; } else if (TrackType.OTHER.name().equalsIgnoreCase(type)) { trackType = TrackType.OTHER; } else if (TrackType.GENE_EXPRESSION.name().equalsIgnoreCase(type)) { trackType = TrackType.GENE_EXPRESSION; } else if (TrackType.LOH.name().equalsIgnoreCase(type)) { trackType = TrackType.LOH; } else if (TrackType.MUTATION.name().equalsIgnoreCase(type)) { trackType = TrackType.MUTATION; } else if (TrackType.PHASTCON.name().equalsIgnoreCase(type)) { trackType = TrackType.PHASTCON; } else if (TrackType.TILING_ARRAY.name().equalsIgnoreCase(type)) { trackType = TrackType.TILING_ARRAY; } // TODO -- refactor to remove instanceof / cast. Currently only ContinuousColorScale is handled ColorScale colorScale = ColorScaleFactory.getScaleFromString(value); if (colorScale instanceof ContinuousColorScale) { session.setColorScale(trackType, (ContinuousColorScale) colorScale); } // ColorScaleFactory.setColorScale(trackType, colorScale); } private String getAttribute(Element element, String key) { String value = element.getAttribute(key); if (value != null) { if (value.trim().equals("")) { value = null; } } return value; } }
src/org/broad/igv/session/IGVSessionReader.java
/* * Copyright (c) 2007-2011 by The Broad Institute of MIT and Harvard. All Rights Reserved. * * This software is licensed under the terms of the GNU Lesser General Public License (LGPL), * Version 2.1 which is available at http://www.opensource.org/licenses/lgpl-2.1.php. * * THE SOFTWARE IS PROVIDED "AS IS." THE BROAD AND MIT MAKE NO REPRESENTATIONS OR * WARRANTES OF ANY KIND CONCERNING THE SOFTWARE, EXPRESS OR IMPLIED, INCLUDING, * WITHOUT LIMITATION, WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR * PURPOSE, NONINFRINGEMENT, OR THE ABSENCE OF LATENT OR OTHER DEFECTS, WHETHER * OR NOT DISCOVERABLE. IN NO EVENT SHALL THE BROAD OR MIT, OR THEIR RESPECTIVE * TRUSTEES, DIRECTORS, OFFICERS, EMPLOYEES, AND AFFILIATES BE LIABLE FOR ANY DAMAGES * OF ANY KIND, INCLUDING, WITHOUT LIMITATION, INCIDENTAL OR CONSEQUENTIAL DAMAGES, * ECONOMIC DAMAGES OR INJURY TO PROPERTY AND LOST PROFITS, REGARDLESS OF WHETHER * THE BROAD OR MIT SHALL BE ADVISED, SHALL HAVE OTHER REASON TO KNOW, OR IN FACT * SHALL KNOW OF THE POSSIBILITY OF THE FOREGOING. */ package org.broad.igv.session; import org.apache.log4j.Logger; import org.broad.igv.Globals; import org.broad.igv.feature.RegionOfInterest; import org.broad.igv.lists.GeneList; import org.broad.igv.lists.GeneListManager; import org.broad.igv.renderer.ColorScale; import org.broad.igv.renderer.ColorScaleFactory; import org.broad.igv.renderer.ContinuousColorScale; import org.broad.igv.renderer.DataRange; import org.broad.igv.track.*; import org.broad.igv.ui.IGV; import org.broad.igv.ui.TrackFilter; import org.broad.igv.ui.TrackFilterElement; import org.broad.igv.ui.color.ColorUtilities; import org.broad.igv.ui.panel.FrameManager; import org.broad.igv.ui.panel.ReferenceFrame; import org.broad.igv.ui.panel.TrackPanel; import org.broad.igv.ui.util.MessageUtils; import org.broad.igv.util.*; import org.broad.igv.util.FilterElement.BooleanOperator; import org.broad.igv.util.FilterElement.Operator; import org.w3c.dom.*; import org.xml.sax.SAXException; import javax.xml.parsers.DocumentBuilder; import javax.xml.parsers.DocumentBuilderFactory; import javax.xml.parsers.ParserConfigurationException; import java.awt.*; import java.io.File; import java.io.IOException; import java.io.InputStream; import java.util.*; import java.util.List; /** * Class to parse an IGV session file */ public class IGVSessionReader implements SessionReader { private static Logger log = Logger.getLogger(IGVSessionReader.class); private static String INPUT_FILE_KEY = "INPUT_FILE_KEY"; // Temporary values used in processing private Collection<ResourceLocator> dataFiles; private Collection<ResourceLocator> missingDataFiles; private static Map<String, String> attributeSynonymMap = new HashMap(); private boolean panelElementPresent = false; private int version; private IGV igv; /** * Map of track id -> track. It is important to maintin the order in which tracks are added, thus * the use of LinkedHashMap. */ Map<String, List<Track>> trackDictionary = Collections.synchronizedMap(new LinkedHashMap()); private Track geneTrack = null; private Track seqTrack = null; private boolean hasTrackElments; static { attributeSynonymMap.put("DATA FILE", "DATA SET"); attributeSynonymMap.put("TRACK NAME", "NAME"); } /** * Session Element types */ public static enum SessionElement { PANEL("Panel"), PANEL_LAYOUT("PanelLayout"), TRACK("Track"), COLOR_SCALE("ColorScale"), COLOR_SCALES("ColorScales"), DATA_TRACK("DataTrack"), DATA_TRACKS("DataTracks"), FEATURE_TRACKS("FeatureTracks"), DATA_FILE("DataFile"), RESOURCE("Resource"), RESOURCES("Resources"), FILES("Files"), FILTER_ELEMENT("FilterElement"), FILTER("Filter"), SESSION("Session"), GLOBAL("Global"), REGION("Region"), REGIONS("Regions"), DATA_RANGE("DataRange"), PREFERENCES("Preferences"), PROPERTY("Property"), GENE_LIST("GeneList"), HIDDEN_ATTRIBUTES("HiddenAttributes"), VISIBLE_ATTRIBUTES("VisibleAttributes"), ATTRIBUTE("Attribute"), VISIBLE_ATTRIBUTE("VisibleAttribute"), FRAME("Frame"); private String name; SessionElement(String name) { this.name = name; } public String getText() { return name; } @Override public String toString() { return getText(); } static public SessionElement findEnum(String value) { if (value == null) { return null; } else { return SessionElement.valueOf(value); } } } /** * Session Attribute types */ public static enum SessionAttribute { BOOLEAN_OPERATOR("booleanOperator"), COLOR("color"), ALT_COLOR("altColor"), COLOR_MODE("colorMode"), CHROMOSOME("chromosome"), END_INDEX("end"), EXPAND("expand"), SQUISH("squish"), DISPLAY_MODE("displayMode"), FILTER_MATCH("match"), FILTER_SHOW_ALL_TRACKS("showTracks"), GENOME("genome"), GROUP_TRACKS_BY("groupTracksBy"), HEIGHT("height"), ID("id"), ITEM("item"), LOCUS("locus"), NAME("name"), SAMPLE_ID("sampleID"), RESOURCE_TYPE("resourceType"), OPERATOR("operator"), RELATIVE_PATH("relativePath"), RENDERER("renderer"), SCALE("scale"), START_INDEX("start"), VALUE("value"), VERSION("version"), VISIBLE("visible"), WINDOW_FUNCTION("windowFunction"), RENDER_NAME("renderName"), GENOTYPE_HEIGHT("genotypeHeight"), VARIANT_HEIGHT("variantHeight"), PREVIOUS_HEIGHT("previousHeight"), FEATURE_WINDOW("featureVisibilityWindow"), DISPLAY_NAME("displayName"), COLOR_SCALE("colorScale"), //RESOURCE ATTRIBUTES PATH("path"), LABEL("label"), SERVER_URL("serverURL"), HYPERLINK("hyperlink"), INFOLINK("infolink"), URL("url"), FEATURE_URL("featureURL"), DESCRIPTION("description"), TYPE("type"), COVERAGE("coverage"), TRACK_LINE("trackLine"), CHR("chr"), START("start"), END("end"); //TODO Add the following into the Attributes /* boolean shadeBases; boolean shadeCenters; boolean flagUnmappedPairs; boolean showAllBases; int insertSizeThreshold; boolean colorByStrand; boolean colorByAmpliconStrand; */ private String name; SessionAttribute(String name) { this.name = name; } public String getText() { return name; } @Override public String toString() { return getText(); } static public SessionAttribute findEnum(String value) { if (value == null) { return null; } else { return SessionAttribute.valueOf(value); } } } public IGVSessionReader(IGV igv) { this.igv = igv; } /** * @param inputStream * @param session * @param sessionName @return * @throws RuntimeException */ public void loadSession(InputStream inputStream, Session session, String sessionName) { log.debug("Load session"); Document document = null; try { document = createDOMDocumentFromXmlFile(inputStream); } catch (Exception e) { log.error("Session Management Error", e); throw new RuntimeException(e); } NodeList tracks = document.getElementsByTagName("Track"); hasTrackElments = tracks.getLength() > 0; HashMap additionalInformation = new HashMap(); additionalInformation.put(INPUT_FILE_KEY, sessionName); NodeList nodes = document.getElementsByTagName(SessionElement.GLOBAL.getText()); if (nodes == null || nodes.getLength() == 0) { nodes = document.getElementsByTagName(SessionElement.SESSION.getText()); } processRootNode(session, nodes.item(0), additionalInformation); // Add tracks not explicitly set in file. It is legal to define sessions with the DataFile section only (no // Panel or Track elements). addLeftoverTracks(trackDictionary.values()); if (session.getGroupTracksBy() != null && session.getGroupTracksBy().length() > 0) { igv.setGroupByAttribute(session.getGroupTracksBy()); } if (session.isRemoveEmptyPanels()) { igv.getMainPanel().removeEmptyDataPanels(); } igv.resetOverlayTracks(); } private void processRootNode(Session session, Node node, HashMap additionalInformation) { if ((node == null) || (session == null)) { MessageUtils.showMessage("Invalid session file: root node not found"); return; } String nodeName = node.getNodeName(); if (!(nodeName.equalsIgnoreCase(SessionElement.GLOBAL.getText()) || nodeName.equalsIgnoreCase(SessionElement.SESSION.getText()))) { MessageUtils.showMessage("Session files must begin with a \"Global\" or \"Session\" element. Found: " + nodeName); } process(session, node, additionalInformation); Element element = (Element) node; // Load the genome, which can be an ID, or a path or URL to a .genome or indexed fasta file. String genome = getAttribute(element, SessionAttribute.GENOME.getText()); if (genome != null && genome.length() > 0) { // THis is a hack, and a bad one, but selecting a genome will actually "reset" the session so we have to // save the path and restore it. String sessionPath = session.getPath(); if (IGV.getInstance().getGenomeIds().contains(genome)) { IGV.getInstance().selectGenomeFromList(genome); } else { String genomePath = genome; if (!ParsingUtils.pathExists(genomePath)) { genomePath = getAbsolutePath(genome, session.getPath()); } if (ParsingUtils.pathExists(genomePath)) { try { IGV.getInstance().loadGenome(genome, null); } catch (IOException e) { throw new RuntimeException("Error loading genome: " + genome); } } else { MessageUtils.showMessage("Warning: Could not locate genome: " + genome); } } session.setPath(sessionPath); } session.setLocus(getAttribute(element, SessionAttribute.LOCUS.getText())); session.setGroupTracksBy(getAttribute(element, SessionAttribute.GROUP_TRACKS_BY.getText())); String removeEmptyTracks = getAttribute(element, "removeEmptyTracks"); if (removeEmptyTracks != null) { try { Boolean b = Boolean.parseBoolean(removeEmptyTracks); session.setRemoveEmptyPanels(b); } catch (Exception e) { log.error("Error parsing removeEmptyTracks string: " + removeEmptyTracks, e); } } String versionString = getAttribute(element, SessionAttribute.VERSION.getText()); try { version = Integer.parseInt(versionString); } catch (NumberFormatException e) { log.error("Non integer version number in session file: " + versionString); } session.setVersion(version); geneTrack = igv.getGeneTrack(); if (geneTrack != null) { trackDictionary.put(geneTrack.getId(), Arrays.asList(geneTrack)); } seqTrack = igv.getSequenceTrack(); if (seqTrack != null) { trackDictionary.put(seqTrack.getId(), Arrays.asList(seqTrack)); } NodeList elements = element.getChildNodes(); process(session, elements, additionalInformation); // ReferenceFrame.getInstance().invalidateLocationScale(); } //TODO Check to make sure tracks are not being created twice //TODO -- DONT DO THIS FOR NEW SESSIONS private void addLeftoverTracks(Collection<List<Track>> tmp) { Map<String, TrackPanel> trackPanelCache = new HashMap(); if (version < 3 || !panelElementPresent) { for (List<Track> tracks : tmp) { for (Track track : tracks) { if (track != geneTrack && track != seqTrack && track.getResourceLocator() != null) { TrackPanel panel = trackPanelCache.get(track.getResourceLocator().getPath()); if (panel == null) { panel = IGV.getInstance().getPanelFor(track.getResourceLocator()); trackPanelCache.put(track.getResourceLocator().getPath(), panel); } panel.addTrack(track); } } } } } /** * Process a single session element node. * * @param session * @param element */ private void process(Session session, Node element, HashMap additionalInformation) { if ((element == null) || (session == null)) { return; } String nodeName = element.getNodeName(); if (nodeName.equalsIgnoreCase(SessionElement.RESOURCES.getText()) || nodeName.equalsIgnoreCase(SessionElement.FILES.getText())) { processResources(session, (Element) element, additionalInformation); } else if (nodeName.equalsIgnoreCase(SessionElement.RESOURCE.getText()) || nodeName.equalsIgnoreCase(SessionElement.DATA_FILE.getText())) { processResource(session, (Element) element, additionalInformation); } else if (nodeName.equalsIgnoreCase(SessionElement.REGIONS.getText())) { processRegions(session, (Element) element, additionalInformation); } else if (nodeName.equalsIgnoreCase(SessionElement.REGION.getText())) { processRegion(session, (Element) element, additionalInformation); } else if (nodeName.equalsIgnoreCase(SessionElement.GENE_LIST.getText())) { processGeneList(session, (Element) element, additionalInformation); } else if (nodeName.equalsIgnoreCase(SessionElement.FILTER.getText())) { processFilter(session, (Element) element, additionalInformation); } else if (nodeName.equalsIgnoreCase(SessionElement.FILTER_ELEMENT.getText())) { processFilterElement(session, (Element) element, additionalInformation); } else if (nodeName.equalsIgnoreCase(SessionElement.COLOR_SCALES.getText())) { processColorScales(session, (Element) element, additionalInformation); } else if (nodeName.equalsIgnoreCase(SessionElement.COLOR_SCALE.getText())) { processColorScale(session, (Element) element, additionalInformation); } else if (nodeName.equalsIgnoreCase(SessionElement.PREFERENCES.getText())) { processPreferences(session, (Element) element, additionalInformation); } else if (nodeName.equalsIgnoreCase(SessionElement.DATA_TRACKS.getText()) || nodeName.equalsIgnoreCase(SessionElement.FEATURE_TRACKS.getText()) || nodeName.equalsIgnoreCase(SessionElement.PANEL.getText())) { processPanel(session, (Element) element, additionalInformation); } else if (nodeName.equalsIgnoreCase(SessionElement.PANEL_LAYOUT.getText())) { processPanelLayout(session, (Element) element, additionalInformation); } else if (nodeName.equalsIgnoreCase(SessionElement.HIDDEN_ATTRIBUTES.getText())) { processHiddenAttributes(session, (Element) element, additionalInformation); } else if (nodeName.equalsIgnoreCase(SessionElement.VISIBLE_ATTRIBUTES.getText())) { processVisibleAttributes(session, (Element) element, additionalInformation); } } private void processResources(Session session, Element element, HashMap additionalInformation) { dataFiles = new ArrayList(); missingDataFiles = new ArrayList(); NodeList elements = element.getChildNodes(); process(session, elements, additionalInformation); if (missingDataFiles.size() > 0) { StringBuffer message = new StringBuffer(); message.append("<html>The following data file(s) could not be located.<ul>"); for (ResourceLocator file : missingDataFiles) { if (file.isLocal()) { message.append("<li>"); message.append(file.getPath()); message.append("</li>"); } else { message.append("<li>Server: "); message.append(file.getServerURL()); message.append(" Path: "); message.append(file.getPath()); message.append("</li>"); } } message.append("</ul>"); message.append("Common reasons for this include: "); message.append("<ul><li>The session or data files have been moved.</li> "); message.append("<li>The data files are located on a drive that is not currently accessible.</li></ul>"); message.append("</html>"); MessageUtils.showMessage(message.toString()); } if (dataFiles.size() > 0) { final List<String> errors = new ArrayList<String>(); // Load files concurrently -- TODO, put a limit on # of threads? List<Thread> threads = new ArrayList(dataFiles.size()); long t0 = System.currentTimeMillis(); int i = 0; List<Runnable> synchronousLoads = new ArrayList<Runnable>(); for (final ResourceLocator locator : dataFiles) { Runnable runnable = new Runnable() { public void run() { List<Track> tracks = null; try { tracks = igv.load(locator); for (Track track : tracks) { if (track == null) log.info("Null track for resource " + locator.getPath()); String id = track.getId(); if (id == null) log.info("Null track id for resource " + locator.getPath()); List<Track> trackList = trackDictionary.get(id); if (trackList == null) { trackList = new ArrayList(); trackDictionary.put(id, trackList); } trackList.add(track); } } catch (Exception e) { log.error("Error loading resource " + locator.getPath(), e); String ms = "<b>" + locator.getPath() + "</b><br>&nbs;p&nbsp;" + e.toString() + "<br>"; errors.add(ms); } } }; boolean isAlignment = locator.getPath().endsWith(".bam") || locator.getPath().endsWith(".entries") || locator.getPath().endsWith(".sam"); // Run synchronously if in batch mode or if there are no "track" elments, or if this is an alignment file if (isAlignment || Globals.isBatch() || !hasTrackElments) { synchronousLoads.add(runnable); } else { Thread t = new Thread(runnable); threads.add(t); t.start(); } i++; } // Wait for all threads to complete for (Thread t : threads) { try { t.join(); } catch (InterruptedException ignore) { } } // Now load data that must be loaded synchronously for (Runnable runnable : synchronousLoads) { runnable.run(); } long dt = System.currentTimeMillis() - t0; log.debug("Total load time = " + dt); if (errors.size() > 0) { StringBuffer buf = new StringBuffer(); buf.append("<html>Errors were encountered loading the session:<br>"); for (String msg : errors) { buf.append(msg); } MessageUtils.showMessage(buf.toString()); } } dataFiles = null; } private void processResource(Session session, Element element, HashMap additionalInformation) { String nodeName = element.getNodeName(); boolean oldSession = nodeName.equals(SessionElement.DATA_FILE.getText()); String label = getAttribute(element, SessionAttribute.LABEL.getText()); String name = getAttribute(element, SessionAttribute.NAME.getText()); String sampleId = getAttribute(element, SessionAttribute.SAMPLE_ID.getText()); String description = getAttribute(element, SessionAttribute.DESCRIPTION.getText()); String type = getAttribute(element, SessionAttribute.TYPE.getText()); String coverage = getAttribute(element, SessionAttribute.COVERAGE.getText()); String trackLine = getAttribute(element, SessionAttribute.TRACK_LINE.getText()); String colorString = getAttribute(element, SessionAttribute.COLOR.getText()); String relPathValue = getAttribute(element, SessionAttribute.RELATIVE_PATH.getText()); boolean isRelativePath = ((relPathValue != null) && relPathValue.equalsIgnoreCase("true")); String serverURL = getAttribute(element, SessionAttribute.SERVER_URL.getText()); // Older sessions used the "name" attribute for the path. String path = getAttribute(element, SessionAttribute.PATH.getText()); if (oldSession && name != null) { path = name; int idx = name.lastIndexOf("/"); if (idx > 0 && idx + 1 < name.length()) { name = name.substring(idx + 1); } } ResourceLocator resourceLocator = new ResourceLocator(serverURL, path); if (isRelativePath) { final String sessionPath = session.getPath(); String absolutePath; if (sessionPath == null) { log.error("Null session path -- this is not expected"); MessageUtils.showMessage("Unexpected error loading session: null session path"); return; } absolutePath = getAbsolutePath(path, sessionPath); resourceLocator = new ResourceLocator(serverURL, absolutePath); } String url = getAttribute(element, SessionAttribute.URL.getText()); if (url == null) { url = getAttribute(element, SessionAttribute.FEATURE_URL.getText()); } resourceLocator.setUrl(url); String infolink = getAttribute(element, SessionAttribute.HYPERLINK.getText()); if (infolink == null) { infolink = getAttribute(element, SessionAttribute.INFOLINK.getText()); } resourceLocator.setInfolink(infolink); // Label is deprecated in favor of name. if (name != null) { resourceLocator.setName(name); } else { resourceLocator.setName(label); } resourceLocator.setSampleId(sampleId); resourceLocator.setDescription(description); // This test added to get around earlier bug in the writer if (type != null && !type.equals("local")) { resourceLocator.setType(type); } resourceLocator.setCoverage(coverage); resourceLocator.setTrackLine(trackLine); if (colorString != null) { try { Color c = ColorUtilities.stringToColor(colorString); resourceLocator.setColor(c); } catch (Exception e) { log.error("Error setting color: ", e); } } dataFiles.add(resourceLocator); NodeList elements = element.getChildNodes(); process(session, elements, additionalInformation); } private String getAbsolutePath(String path, String sessionPath) { String absolutePath; if (FileUtils.isRemote(sessionPath)) { int idx = sessionPath.lastIndexOf("/"); String basePath = sessionPath.substring(0, idx); absolutePath = basePath + "/" + path; } else { File parent = new File(sessionPath).getParentFile(); File file = new File(parent, path); absolutePath = file.getAbsolutePath(); } return absolutePath; } private void processRegions(Session session, Element element, HashMap additionalInformation) { session.clearRegionsOfInterest(); NodeList elements = element.getChildNodes(); process(session, elements, additionalInformation); } private void processRegion(Session session, Element element, HashMap additionalInformation) { String chromosome = getAttribute(element, SessionAttribute.CHROMOSOME.getText()); String start = getAttribute(element, SessionAttribute.START_INDEX.getText()); String end = getAttribute(element, SessionAttribute.END_INDEX.getText()); String description = getAttribute(element, SessionAttribute.DESCRIPTION.getText()); RegionOfInterest region = new RegionOfInterest(chromosome, new Integer(start), new Integer(end), description); IGV.getInstance().addRegionOfInterest(region); NodeList elements = element.getChildNodes(); process(session, elements, additionalInformation); } private void processHiddenAttributes(Session session, Element element, HashMap additionalInformation) { // session.clearRegionsOfInterest(); NodeList elements = element.getChildNodes(); if (elements.getLength() > 0) { Set<String> attributes = new HashSet(); for (int i = 0; i < elements.getLength(); i++) { Node childNode = elements.item(i); if (childNode.getNodeName().equals(IGVSessionReader.SessionElement.ATTRIBUTE.getText())) { attributes.add(((Element) childNode).getAttribute(IGVSessionReader.SessionAttribute.NAME.getText())); } } session.setHiddenAttributes(attributes); } } /** * For backward compatibility * * @param session * @param element * @param additionalInformation */ private void processVisibleAttributes(Session session, Element element, HashMap additionalInformation) { // session.clearRegionsOfInterest(); NodeList elements = element.getChildNodes(); if (elements.getLength() > 0) { Set<String> visibleAttributes = new HashSet(); for (int i = 0; i < elements.getLength(); i++) { Node childNode = elements.item(i); if (childNode.getNodeName().equals(IGVSessionReader.SessionElement.VISIBLE_ATTRIBUTE.getText())) { visibleAttributes.add(((Element) childNode).getAttribute(IGVSessionReader.SessionAttribute.NAME.getText())); } } final List<String> attributeNames = AttributeManager.getInstance().getAttributeNames(); Set<String> hiddenAttributes = new HashSet<String>(attributeNames); hiddenAttributes.removeAll(visibleAttributes); session.setHiddenAttributes(hiddenAttributes); } } private void processGeneList(Session session, Element element, HashMap additionalInformation) { String name = getAttribute(element, SessionAttribute.NAME.getText()); String txt = element.getTextContent(); String[] genes = txt.trim().split("\\s+"); GeneList gl = new GeneList(name, Arrays.asList(genes)); GeneListManager.getInstance().addGeneList(gl); session.setCurrentGeneList(gl); // Adjust frames processFrames(element); } private void processFrames(Element element) { NodeList elements = element.getChildNodes(); if (elements.getLength() > 0) { Map<String, ReferenceFrame> frames = new HashMap(); for (ReferenceFrame f : FrameManager.getFrames()) { frames.put(f.getName(), f); } List<ReferenceFrame> reorderedFrames = new ArrayList(); for (int i = 0; i < elements.getLength(); i++) { Node childNode = elements.item(i); if (childNode.getNodeName().equalsIgnoreCase(SessionElement.FRAME.getText())) { String frameName = getAttribute((Element) childNode, SessionAttribute.NAME.getText()); ReferenceFrame f = frames.get(frameName); if (f != null) { reorderedFrames.add(f); try { String chr = getAttribute((Element) childNode, SessionAttribute.CHR.getText()); final String startString = getAttribute((Element) childNode, SessionAttribute.START.getText()).replace(",", ""); final String endString = getAttribute((Element) childNode, SessionAttribute.END.getText()).replace(",", ""); int start = ParsingUtils.parseInt(startString); int end = ParsingUtils.parseInt(endString); f.setInterval(chr, start, end); } catch (NumberFormatException e) { e.printStackTrace(); //To change body of catch statement use File | Settings | File Templates. } } } } if (reorderedFrames.size() > 0) { FrameManager.setFrames(reorderedFrames); } } IGV.getInstance().resetFrames(); } private void processFilter(Session session, Element element, HashMap additionalInformation) { String match = getAttribute(element, SessionAttribute.FILTER_MATCH.getText()); String showAllTracks = getAttribute(element, SessionAttribute.FILTER_SHOW_ALL_TRACKS.getText()); String filterName = getAttribute(element, SessionAttribute.NAME.getText()); TrackFilter filter = new TrackFilter(filterName, null); additionalInformation.put(SessionElement.FILTER, filter); NodeList elements = element.getChildNodes(); process(session, elements, additionalInformation); // Save the filter session.setFilter(filter); // Set filter properties if ("all".equalsIgnoreCase(match)) { IGV.getInstance().setFilterMatchAll(true); } else if ("any".equalsIgnoreCase(match)) { IGV.getInstance().setFilterMatchAll(false); } if ("true".equalsIgnoreCase(showAllTracks)) { IGV.getInstance().setFilterShowAllTracks(true); } else { IGV.getInstance().setFilterShowAllTracks(false); } } private void processFilterElement(Session session, Element element, HashMap additionalInformation) { TrackFilter filter = (TrackFilter) additionalInformation.get(SessionElement.FILTER); String item = getAttribute(element, SessionAttribute.ITEM.getText()); String operator = getAttribute(element, SessionAttribute.OPERATOR.getText()); String value = getAttribute(element, SessionAttribute.VALUE.getText()); String booleanOperator = getAttribute(element, SessionAttribute.BOOLEAN_OPERATOR.getText()); TrackFilterElement trackFilterElement = new TrackFilterElement(filter, item, Operator.findEnum(operator), value, BooleanOperator.findEnum(booleanOperator)); filter.add(trackFilterElement); NodeList elements = element.getChildNodes(); process(session, elements, additionalInformation); } /** * A counter to generate unique panel names. Needed for backward-compatibility of old session files. */ private int panelCounter = 1; private void processPanel(Session session, Element element, HashMap additionalInformation) { panelElementPresent = true; String panelName = element.getAttribute("name"); if (panelName == null) { panelName = "Panel" + panelCounter++; } List<Track> panelTracks = new ArrayList(); NodeList elements = element.getChildNodes(); for (int i = 0; i < elements.getLength(); i++) { Node childNode = elements.item(i); if (childNode.getNodeName().equalsIgnoreCase(SessionElement.DATA_TRACK.getText()) || // Is this a track? childNode.getNodeName().equalsIgnoreCase(SessionElement.TRACK.getText())) { List<Track> tracks = processTrack(session, (Element) childNode, additionalInformation); if (tracks != null) { panelTracks.addAll(tracks); } } else { process(session, childNode, additionalInformation); } } TrackPanel panel = IGV.getInstance().getTrackPanel(panelName); panel.addTracks(panelTracks); } private void processPanelLayout(Session session, Element element, HashMap additionalInformation) { String nodeName = element.getNodeName(); String panelName = nodeName; NamedNodeMap tNodeMap = element.getAttributes(); for (int i = 0; i < tNodeMap.getLength(); i++) { Node node = tNodeMap.item(i); String name = node.getNodeName(); if (name.equals("dividerFractions")) { String value = node.getNodeValue(); String[] tokens = value.split(","); double[] divs = new double[tokens.length]; try { for (int j = 0; j < tokens.length; j++) { divs[j] = Double.parseDouble(tokens[j]); } session.setDividerFractions(divs); } catch (NumberFormatException e) { log.error("Error parsing divider locations", e); } } } } /** * Process a track element. This should return a single track, but could return multiple tracks since the * uniqueness of the track id is not enforced. * * @param session * @param element * @param additionalInformation * @return */ private List<Track> processTrack(Session session, Element element, HashMap additionalInformation) { String id = getAttribute(element, SessionAttribute.ID.getText()); // TODo -- put in utility method, extacts attributes from element **Definitely need to do this HashMap<String, String> tAttributes = new HashMap(); HashMap<String, String> drAttributes = null; NamedNodeMap tNodeMap = element.getAttributes(); for (int i = 0; i < tNodeMap.getLength(); i++) { Node node = tNodeMap.item(i); String value = node.getNodeValue(); if (value != null && value.length() > 0) { tAttributes.put(node.getNodeName(), value); } } if (element.hasChildNodes()) { drAttributes = new HashMap(); Node childNode = element.getFirstChild(); Node sibNode = childNode.getNextSibling(); String sibName = sibNode.getNodeName(); if (sibName.equals(SessionElement.DATA_RANGE.getText())) { NamedNodeMap drNodeMap = sibNode.getAttributes(); for (int i = 0; i < drNodeMap.getLength(); i++) { Node node = drNodeMap.item(i); String value = node.getNodeValue(); if (value != null && value.length() > 0) { drAttributes.put(node.getNodeName(), value); } } } } // Get matching tracks. The trackNameDictionary is used for pre V 2 files, where ID was loosely defined List<Track> matchedTracks = trackDictionary.get(id); if (matchedTracks == null) { log.info("Warning. No tracks were found with id: " + id + " in session file"); } else { for (final Track track : matchedTracks) { // Special case for sequence & gene tracks, they need to be removed before being placed. if (version >= 4 && track == geneTrack || track == seqTrack) { igv.removeTracks(Arrays.asList(track)); } track.restorePersistentState(tAttributes); if (drAttributes != null) { DataRange dr = track.getDataRange(); dr.restorePersistentState(drAttributes); track.setDataRange(dr); } } trackDictionary.remove(id); } NodeList elements = element.getChildNodes(); process(session, elements, additionalInformation); return matchedTracks; } private void processColorScales(Session session, Element element, HashMap additionalInformation) { NodeList elements = element.getChildNodes(); process(session, elements, additionalInformation); } private void processColorScale(Session session, Element element, HashMap additionalInformation) { String trackType = getAttribute(element, SessionAttribute.TYPE.getText()); String value = getAttribute(element, SessionAttribute.VALUE.getText()); setColorScaleSet(session, trackType, value); NodeList elements = element.getChildNodes(); process(session, elements, additionalInformation); } private void processPreferences(Session session, Element element, HashMap additionalInformation) { NodeList elements = element.getChildNodes(); for (int i = 0; i < elements.getLength(); i++) { Node child = elements.item(i); if (child.getNodeName().equalsIgnoreCase(SessionElement.PROPERTY.getText())) { Element childNode = (Element) child; String name = getAttribute(childNode, SessionAttribute.NAME.getText()); String value = getAttribute(childNode, SessionAttribute.VALUE.getText()); session.setPreference(name, value); } } } /** * Process a list of session element nodes. * * @param session * @param elements */ private void process(Session session, NodeList elements, HashMap additionalInformation) { for (int i = 0; i < elements.getLength(); i++) { Node childNode = elements.item(i); process(session, childNode, additionalInformation); } } /** * Reads an xml from an input file and creates DOM document. * * @param * @return * @throws ParserConfigurationException * @throws IOException * @throws SAXException */ private Document createDOMDocumentFromXmlFile(InputStream inputStream) throws ParserConfigurationException, IOException, SAXException { DocumentBuilder documentBuilder = DocumentBuilderFactory.newInstance().newDocumentBuilder(); Document xmlDocument = documentBuilder.parse(inputStream); return xmlDocument; } public void setColorScaleSet(Session session, String type, String value) { if (type == null | value == null) { return; } TrackType trackType = TrackType.OTHER; if (TrackType.ALLELE_SPECIFIC_COPY_NUMBER.name().equalsIgnoreCase(type)) { trackType = TrackType.ALLELE_SPECIFIC_COPY_NUMBER; } else if (TrackType.CHIP.name().equalsIgnoreCase(type)) { trackType = TrackType.CHIP; } else if (TrackType.COPY_NUMBER.name().equalsIgnoreCase(type)) { trackType = TrackType.COPY_NUMBER; } else if (TrackType.DNA_METHYLATION.name().equalsIgnoreCase(type)) { trackType = TrackType.DNA_METHYLATION; } else if (TrackType.OTHER.name().equalsIgnoreCase(type)) { trackType = TrackType.OTHER; } else if (TrackType.GENE_EXPRESSION.name().equalsIgnoreCase(type)) { trackType = TrackType.GENE_EXPRESSION; } else if (TrackType.LOH.name().equalsIgnoreCase(type)) { trackType = TrackType.LOH; } else if (TrackType.MUTATION.name().equalsIgnoreCase(type)) { trackType = TrackType.MUTATION; } else if (TrackType.PHASTCON.name().equalsIgnoreCase(type)) { trackType = TrackType.PHASTCON; } else if (TrackType.TILING_ARRAY.name().equalsIgnoreCase(type)) { trackType = TrackType.TILING_ARRAY; } // TODO -- refactor to remove instanceof / cast. Currently only ContinuousColorScale is handled ColorScale colorScale = ColorScaleFactory.getScaleFromString(value); if (colorScale instanceof ContinuousColorScale) { session.setColorScale(trackType, (ContinuousColorScale) colorScale); } // ColorScaleFactory.setColorScale(trackType, colorScale); } private String getAttribute(Element element, String key) { String value = element.getAttribute(key); if (value != null) { if (value.trim().equals("")) { value = null; } } return value; } }
Fix for "relative path" sessions. Now accepts relative paths to genome files git-svn-id: b5cf87c434d9ee7c8f18865e4378c9faabe04646@1720 17392f64-ead8-4cea-ae29-09b3ab513800
src/org/broad/igv/session/IGVSessionReader.java
Fix for "relative path" sessions. Now accepts relative paths to genome files
<ide><path>rc/org/broad/igv/session/IGVSessionReader.java <ide> } <ide> if (ParsingUtils.pathExists(genomePath)) { <ide> try { <del> IGV.getInstance().loadGenome(genome, null); <add> IGV.getInstance().loadGenome(genomePath, null); <ide> } catch (IOException e) { <ide> throw new RuntimeException("Error loading genome: " + genome); <ide> }
Java
mit
8cf12f52264ee33215f3c17da65b12bcda6d323e
0
SpongePowered/Sponge,SpongePowered/Sponge,SpongePowered/Sponge,SpongePowered/SpongeCommon,SpongePowered/SpongeCommon
/* * This file is part of Sponge, licensed under the MIT License (MIT). * * Copyright (c) SpongePowered <https://www.spongepowered.org> * Copyright (c) contributors * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package org.spongepowered.common.data.nbt; import com.google.common.collect.ImmutableList; import net.minecraft.nbt.NBTTagCompound; import net.minecraft.nbt.NBTTagList; import org.spongepowered.api.data.DataContainer; import org.spongepowered.api.data.DataHolder; import org.spongepowered.api.data.DataTransactionResult; import org.spongepowered.api.data.DataView; import org.spongepowered.api.data.manipulator.DataManipulator; import org.spongepowered.api.data.manipulator.DataManipulatorBuilder; import org.spongepowered.api.data.persistence.InvalidDataException; import org.spongepowered.common.SpongeImpl; import org.spongepowered.common.data.SpongeDataManager; import org.spongepowered.common.data.persistence.NbtTranslator; import org.spongepowered.common.data.persistence.SerializedDataTransaction; import org.spongepowered.common.data.util.DataQueries; import org.spongepowered.common.data.util.DataUtil; import org.spongepowered.common.data.util.NbtDataUtil; import org.spongepowered.common.interfaces.data.IMixinCustomDataHolder; import java.util.ArrayList; import java.util.List; import java.util.Optional; import javax.annotation.Nullable; public class CustomDataNbtUtil { public static DataTransactionResult apply(NBTTagCompound compound, DataManipulator<?, ?> manipulator) { if (!compound.hasKey(NbtDataUtil.FORGE_DATA, NbtDataUtil.TAG_COMPOUND)) { compound.setTag(NbtDataUtil.FORGE_DATA, new NBTTagCompound()); } final NBTTagCompound forgeCompound = compound.getCompoundTag(NbtDataUtil.FORGE_DATA); if (!forgeCompound.hasKey(NbtDataUtil.SPONGE_DATA, NbtDataUtil.TAG_COMPOUND)) { forgeCompound.setTag(NbtDataUtil.SPONGE_DATA, new NBTTagCompound()); } final NBTTagCompound spongeTag = forgeCompound.getCompoundTag(NbtDataUtil.SPONGE_DATA); boolean isReplacing; // Validate that the custom manipulator isn't already existing in the compound final NBTTagList list; if (spongeTag.hasKey(NbtDataUtil.CUSTOM_MANIPULATOR_TAG_LIST, NbtDataUtil.TAG_LIST)) { list = spongeTag.getTagList(NbtDataUtil.CUSTOM_MANIPULATOR_TAG_LIST, NbtDataUtil.TAG_COMPOUND); for (int i = 0; i < list.tagCount(); i++) { final NBTTagCompound dataCompound = list.getCompoundTagAt(i); final String clazzName = dataCompound.getString(NbtDataUtil.CUSTOM_DATA_CLASS); if (manipulator.getClass().getName().equals(clazzName)) { final NBTTagCompound current = dataCompound.getCompoundTag(NbtDataUtil.CUSTOM_DATA); final DataContainer currentView = NbtTranslator.getInstance().translate(current); DataManipulator<?, ?> existing = deserialize(clazzName, currentView); isReplacing = existing != null; final DataContainer container = manipulator.toContainer(); final NBTTagCompound newCompound = NbtTranslator.getInstance().translateData(container); dataCompound.setTag(NbtDataUtil.CUSTOM_DATA_CLASS, newCompound); if (isReplacing) { return DataTransactionResult.successReplaceResult(manipulator.getValues(), existing.getValues()); } return DataTransactionResult.successReplaceResult(manipulator.getValues(), ImmutableList.of()); } } } else { list = new NBTTagList(); spongeTag.setTag(NbtDataUtil.CUSTOM_MANIPULATOR_TAG_LIST, list); } // We are now adding to the list, not replacing final NBTTagCompound newCompound = new NBTTagCompound(); newCompound.setString(NbtDataUtil.CUSTOM_DATA_CLASS, manipulator.getClass().getName()); final DataContainer dataContainer = manipulator.toContainer(); final NBTTagCompound dataCompound = NbtTranslator.getInstance().translateData(dataContainer); newCompound.setTag(NbtDataUtil.CUSTOM_DATA, dataCompound); list.appendTag(newCompound); return DataTransactionResult.builder().result(DataTransactionResult.Type.SUCCESS).success(manipulator.getValues()).build(); } public static DataTransactionResult apply(DataView view, DataManipulator<?, ?> manipulator) { if (!view.contains(DataQueries.Compatibility.Forge.ROOT)) { view.set(DataQueries.Compatibility.Forge.ROOT, DataContainer.createNew()); } final DataView forgeCompound = view.getView(DataQueries.Compatibility.Forge.ROOT).orElseThrow(DataUtil.dataNotFound()); if (!forgeCompound.contains(DataQueries.General.SPONGE_ROOT)) { forgeCompound.set(DataQueries.General.SPONGE_ROOT, DataContainer.createNew()); } final DataView spongeTag = forgeCompound.getView(DataQueries.General.SPONGE_ROOT).orElseThrow(DataUtil.dataNotFound()); boolean isReplacing; // Validate that the custom manipulator isn't already existing in the compound final List<DataView> customData; if (spongeTag.contains(DataQueries.General.CUSTOM_MANIPULATOR_LIST)) { customData = spongeTag.getViewList(DataQueries.General.CUSTOM_MANIPULATOR_LIST).orElseThrow(DataUtil.dataNotFound()); for (DataView dataView : customData) { final String dataId = dataView.getString(DataQueries.DATA_ID).orElseThrow(DataUtil.dataNotFound()); if (DataUtil.getRegistrationFor(manipulator).getId().equals(dataId)) { final DataView existingData = dataView.getView(DataQueries.INTERNAL_DATA).orElseThrow(DataUtil.dataNotFound()); DataManipulator<?, ?> existing = deserialize(dataId, existingData); isReplacing = existing != null; final DataContainer container = manipulator.toContainer(); dataView.set(DataQueries.INTERNAL_DATA, container); if (isReplacing) { return DataTransactionResult.successReplaceResult(manipulator.getValues(), existing.getValues()); } return DataTransactionResult.successReplaceResult(manipulator.getValues(), ImmutableList.of()); } } } else { customData = new ArrayList<>(); } final DataContainer container = DataContainer.createNew(); container.set(DataQueries.DATA_ID, DataUtil.getRegistrationFor(manipulator).getId()); container.set(DataQueries.INTERNAL_DATA, manipulator.toContainer()); customData.add(container); spongeTag.set(DataQueries.General.CUSTOM_MANIPULATOR_LIST, customData); return DataTransactionResult.builder().result(DataTransactionResult.Type.SUCCESS).success(manipulator.getValues()).build(); } public static DataTransactionResult remove(NBTTagCompound data, Class<? extends DataManipulator<?, ?>> containerClass) { if (!data.hasKey(NbtDataUtil.FORGE_DATA, NbtDataUtil.TAG_COMPOUND)) { return DataTransactionResult.successNoData(); } final NBTTagCompound forgeTag = data.getCompoundTag(NbtDataUtil.FORGE_DATA); if (!forgeTag.hasKey(NbtDataUtil.SPONGE_DATA, NbtDataUtil.TAG_COMPOUND)) { return DataTransactionResult.successNoData(); } final NBTTagCompound spongeData = forgeTag.getCompoundTag(NbtDataUtil.SPONGE_DATA); if (!spongeData.hasKey(NbtDataUtil.CUSTOM_MANIPULATOR_TAG_LIST, NbtDataUtil.TAG_LIST)) { return DataTransactionResult.successNoData(); } final NBTTagList dataList = spongeData.getTagList(NbtDataUtil.CUSTOM_MANIPULATOR_TAG_LIST, NbtDataUtil.TAG_COMPOUND); if (dataList.tagCount() == 0) { return DataTransactionResult.successNoData(); } boolean isRemoving; for (int i = 0; i < dataList.tagCount(); i++) { final NBTTagCompound dataCompound = dataList.getCompoundTagAt(i); final String dataClass = dataCompound.getString(NbtDataUtil.CUSTOM_DATA_CLASS); if (containerClass.getName().equals(dataClass)) { final NBTTagCompound current = dataCompound.getCompoundTag(NbtDataUtil.CUSTOM_DATA); final DataContainer currentView = NbtTranslator.getInstance().translate(current); DataManipulator<?, ?> existing = deserialize(dataClass, currentView); isRemoving = existing != null; dataList.removeTag(i); if (isRemoving) { return DataTransactionResult.successRemove(existing.getValues()); } return DataTransactionResult.successNoData(); } } return DataTransactionResult.successNoData(); } @SuppressWarnings({"unchecked", "rawtypes"}) @Nullable private static DataManipulator<?, ?> deserialize(String dataClass, DataView view) { try { final Class<?> clazz = Class.forName(dataClass); final Optional<DataManipulatorBuilder<?, ?>> optional = SpongeDataManager.getInstance().getBuilder((Class) clazz); if (optional.isPresent()) { final Optional<? extends DataManipulator<?, ?>> manipulatorOptional = optional.get().build(view); if (manipulatorOptional.isPresent()) { return manipulatorOptional.get(); } } } catch (Exception e) { new InvalidDataException("Could not translate " + dataClass + "! Don't worry though, we'll try to translate the rest of the data.", e).printStackTrace(); } return null; } @SuppressWarnings("unchecked") public static void readCustomData(NBTTagCompound compound, DataHolder dataHolder) { if (dataHolder instanceof IMixinCustomDataHolder) { if (compound.hasKey(NbtDataUtil.CUSTOM_MANIPULATOR_TAG_LIST, NbtDataUtil.TAG_LIST)) { final NBTTagList list = compound.getTagList(NbtDataUtil.CUSTOM_MANIPULATOR_TAG_LIST, NbtDataUtil.TAG_COMPOUND); final ImmutableList.Builder<DataView> builder = ImmutableList.builder(); if (list != null && list.tagCount() != 0) { for (int i = 0; i < list.tagCount(); i++) { final NBTTagCompound internal = list.getCompoundTagAt(i); builder.add(NbtTranslator.getInstance().translateFrom(internal)); } } try { final SerializedDataTransaction transaction = DataUtil.deserializeManipulatorList(builder.build()); final List<DataManipulator<?, ?>> manipulators = transaction.deserializedManipulators; for (DataManipulator<?, ?> manipulator : manipulators) { dataHolder.offer(manipulator); } if (!transaction.failedData.isEmpty()) { ((IMixinCustomDataHolder) dataHolder).addFailedData(transaction.failedData); } } catch (InvalidDataException e) { SpongeImpl.getLogger().error("Could not translate custom plugin data! ", e); } } if (compound.hasKey(NbtDataUtil.FAILED_CUSTOM_DATA, NbtDataUtil.TAG_LIST)) { final NBTTagList list = compound.getTagList(NbtDataUtil.FAILED_CUSTOM_DATA, NbtDataUtil.TAG_COMPOUND); final ImmutableList.Builder<DataView> builder = ImmutableList.builder(); if (list != null && list.tagCount() != 0) { for (int i = 0; i < list.tagCount(); i++) { final NBTTagCompound internal = list.getCompoundTagAt(i); builder.add(NbtTranslator.getInstance().translateFrom(internal)); } } // We want to attempt to refresh the failed data if it does succeed in getting read. compound.removeTag(NbtDataUtil.FAILED_CUSTOM_DATA); // Re-attempt to deserialize custom data final SerializedDataTransaction transaction = DataUtil.deserializeManipulatorList(builder.build()); final List<DataManipulator<?, ?>> manipulators = transaction.deserializedManipulators; List<Class<? extends DataManipulator<?, ?>>> classesLoaded = new ArrayList<>(); for (DataManipulator<?, ?> manipulator : manipulators) { if (!classesLoaded.contains(manipulator.getClass())) { classesLoaded.add((Class<? extends DataManipulator<?, ?>>) manipulator.getClass()); // If for any reason a failed data was not deserialized, but // there already exists new data, we just simply want to // ignore the failed data for removal. if (!((IMixinCustomDataHolder) dataHolder).getCustom(manipulator.getClass()).isPresent()) { dataHolder.offer(manipulator); } } } if (!transaction.failedData.isEmpty()) { ((IMixinCustomDataHolder) dataHolder).addFailedData(transaction.failedData); } } } } public static void writeCustomData(NBTTagCompound compound, DataHolder dataHolder) { if (dataHolder instanceof IMixinCustomDataHolder) { final List<DataManipulator<?, ?>> manipulators = ((IMixinCustomDataHolder) dataHolder).getCustomManipulators(); if (!manipulators.isEmpty()) { final List<DataView> manipulatorViews = DataUtil.getSerializedManipulatorList(manipulators); final NBTTagList manipulatorTagList = new NBTTagList(); for (DataView dataView : manipulatorViews) { manipulatorTagList.appendTag(NbtTranslator.getInstance().translateData(dataView)); } compound.setTag(NbtDataUtil.CUSTOM_MANIPULATOR_TAG_LIST, manipulatorTagList); } final List<DataView> failedData = ((IMixinCustomDataHolder) dataHolder).getFailedData(); if (!failedData.isEmpty()) { final NBTTagList failedList = new NBTTagList(); for (DataView failedDatum : failedData) { failedList.appendTag(NbtTranslator.getInstance().translateData(failedDatum)); } compound.setTag(NbtDataUtil.FAILED_CUSTOM_DATA, failedList); } } } }
src/main/java/org/spongepowered/common/data/nbt/CustomDataNbtUtil.java
/* * This file is part of Sponge, licensed under the MIT License (MIT). * * Copyright (c) SpongePowered <https://www.spongepowered.org> * Copyright (c) contributors * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package org.spongepowered.common.data.nbt; import com.google.common.collect.ImmutableList; import net.minecraft.nbt.NBTTagCompound; import net.minecraft.nbt.NBTTagList; import org.spongepowered.api.data.DataContainer; import org.spongepowered.api.data.DataHolder; import org.spongepowered.api.data.DataTransactionResult; import org.spongepowered.api.data.DataView; import org.spongepowered.api.data.manipulator.DataManipulator; import org.spongepowered.api.data.manipulator.DataManipulatorBuilder; import org.spongepowered.api.data.persistence.InvalidDataException; import org.spongepowered.common.SpongeImpl; import org.spongepowered.common.data.SpongeDataManager; import org.spongepowered.common.data.persistence.NbtTranslator; import org.spongepowered.common.data.persistence.SerializedDataTransaction; import org.spongepowered.common.data.util.DataQueries; import org.spongepowered.common.data.util.DataUtil; import org.spongepowered.common.data.util.NbtDataUtil; import org.spongepowered.common.interfaces.data.IMixinCustomDataHolder; import java.util.ArrayList; import java.util.List; import java.util.Optional; import javax.annotation.Nullable; public class CustomDataNbtUtil { public static DataTransactionResult apply(NBTTagCompound compound, DataManipulator<?, ?> manipulator) { if (!compound.hasKey(NbtDataUtil.FORGE_DATA, NbtDataUtil.TAG_COMPOUND)) { compound.setTag(NbtDataUtil.FORGE_DATA, new NBTTagCompound()); } final NBTTagCompound forgeCompound = compound.getCompoundTag(NbtDataUtil.FORGE_DATA); if (!forgeCompound.hasKey(NbtDataUtil.SPONGE_DATA, NbtDataUtil.TAG_COMPOUND)) { forgeCompound.setTag(NbtDataUtil.SPONGE_DATA, new NBTTagCompound()); } final NBTTagCompound spongeTag = forgeCompound.getCompoundTag(NbtDataUtil.SPONGE_DATA); boolean isReplacing; // Validate that the custom manipulator isn't already existing in the compound final NBTTagList list; if (spongeTag.hasKey(NbtDataUtil.CUSTOM_MANIPULATOR_TAG_LIST, NbtDataUtil.TAG_LIST)) { list = spongeTag.getTagList(NbtDataUtil.CUSTOM_MANIPULATOR_TAG_LIST, NbtDataUtil.TAG_COMPOUND); for (int i = 0; i < list.tagCount(); i++) { final NBTTagCompound dataCompound = list.getCompoundTagAt(i); final String clazzName = dataCompound.getString(NbtDataUtil.CUSTOM_DATA_CLASS); if (manipulator.getClass().getName().equals(clazzName)) { final NBTTagCompound current = dataCompound.getCompoundTag(NbtDataUtil.CUSTOM_DATA); final DataContainer currentView = NbtTranslator.getInstance().translate(current); DataManipulator<?, ?> existing = deserialize(clazzName, currentView); isReplacing = existing != null; final DataContainer container = manipulator.toContainer(); final NBTTagCompound newCompound = NbtTranslator.getInstance().translateData(container); dataCompound.setTag(NbtDataUtil.CUSTOM_DATA_CLASS, newCompound); if (isReplacing) { return DataTransactionResult.successReplaceResult(manipulator.getValues(), existing.getValues()); } return DataTransactionResult.successReplaceResult(manipulator.getValues(), ImmutableList.of()); } } } else { list = new NBTTagList(); spongeTag.setTag(NbtDataUtil.CUSTOM_MANIPULATOR_TAG_LIST, list); } // We are now adding to the list, not replacing final NBTTagCompound newCompound = new NBTTagCompound(); newCompound.setString(NbtDataUtil.CUSTOM_DATA_CLASS, manipulator.getClass().getName()); final DataContainer dataContainer = manipulator.toContainer(); final NBTTagCompound dataCompound = NbtTranslator.getInstance().translateData(dataContainer); newCompound.setTag(NbtDataUtil.CUSTOM_DATA, dataCompound); list.appendTag(newCompound); return DataTransactionResult.builder().result(DataTransactionResult.Type.SUCCESS).success(manipulator.getValues()).build(); } public static DataTransactionResult apply(DataView view, DataManipulator<?, ?> manipulator) { if (!view.contains(DataQueries.Compatibility.Forge.ROOT)) { view.set(DataQueries.Compatibility.Forge.ROOT, DataContainer.createNew()); } final DataView forgeCompound = view.getView(DataQueries.Compatibility.Forge.ROOT).orElseThrow(DataUtil.dataNotFound()); if (!forgeCompound.contains(DataQueries.General.SPONGE_ROOT)) { forgeCompound.set(DataQueries.General.SPONGE_ROOT, DataContainer.createNew()); } final DataView spongeTag = forgeCompound.getView(DataQueries.General.SPONGE_ROOT).orElseThrow(DataUtil.dataNotFound()); boolean isReplacing; // Validate that the custom manipulator isn't already existing in the compound final List<DataView> customData; if (spongeTag.contains(DataQueries.General.CUSTOM_MANIPULATOR_LIST)) { customData = spongeTag.getViewList(DataQueries.General.CUSTOM_MANIPULATOR_LIST).orElseThrow(DataUtil.dataNotFound()); for (DataView dataView : customData) { final String dataId = dataView.getString(DataQueries.DATA_ID).orElseThrow(DataUtil.dataNotFound()); if (DataUtil.getRegistrationFor(manipulator).getId().equals(dataId)) { final DataView existingData = dataView.getView(DataQueries.INTERNAL_DATA).orElseThrow(DataUtil.dataNotFound()); DataManipulator<?, ?> existing = deserialize(dataId, existingData); isReplacing = existing != null; final DataContainer container = manipulator.toContainer(); dataView.set(DataQueries.INTERNAL_DATA, container); if (isReplacing) { return DataTransactionResult.successReplaceResult(manipulator.getValues(), existing.getValues()); } return DataTransactionResult.successReplaceResult(manipulator.getValues(), ImmutableList.of()); } } } else { customData = new ArrayList<>(); } final DataContainer container = DataContainer.createNew(); container.set(DataQueries.DATA_ID, DataUtil.getRegistrationFor(manipulator).getId()); container.set(DataQueries.INTERNAL_DATA, manipulator.toContainer()); customData.add(container); spongeTag.set(DataQueries.General.CUSTOM_MANIPULATOR_LIST, customData); return DataTransactionResult.builder().result(DataTransactionResult.Type.SUCCESS).success(manipulator.getValues()).build(); } public static DataTransactionResult remove(NBTTagCompound data, Class<? extends DataManipulator<?, ?>> containerClass) { if (!data.hasKey(NbtDataUtil.FORGE_DATA, NbtDataUtil.TAG_COMPOUND)) { return DataTransactionResult.successNoData(); } final NBTTagCompound forgeTag = data.getCompoundTag(NbtDataUtil.FORGE_DATA); if (!forgeTag.hasKey(NbtDataUtil.SPONGE_DATA, NbtDataUtil.TAG_COMPOUND)) { return DataTransactionResult.successNoData(); } final NBTTagCompound spongeData = forgeTag.getCompoundTag(NbtDataUtil.SPONGE_DATA); if (!spongeData.hasKey(NbtDataUtil.CUSTOM_MANIPULATOR_TAG_LIST, NbtDataUtil.TAG_LIST)) { return DataTransactionResult.successNoData(); } final NBTTagList dataList = spongeData.getTagList(NbtDataUtil.CUSTOM_MANIPULATOR_TAG_LIST, NbtDataUtil.TAG_COMPOUND); if (dataList.tagCount() == 0) { return DataTransactionResult.successNoData(); } boolean isRemoving; for (int i = 0; i < dataList.tagCount(); i++) { final NBTTagCompound dataCompound = dataList.getCompoundTagAt(i); final String dataClass = dataCompound.getString(NbtDataUtil.CUSTOM_DATA_CLASS); if (containerClass.getName().equals(dataClass)) { final NBTTagCompound current = dataCompound.getCompoundTag(NbtDataUtil.CUSTOM_DATA); final DataContainer currentView = NbtTranslator.getInstance().translate(current); DataManipulator<?, ?> existing = deserialize(dataClass, currentView); isRemoving = existing != null; dataList.removeTag(i); if (isRemoving) { return DataTransactionResult.successRemove(existing.getValues()); } return DataTransactionResult.successNoData(); } } return DataTransactionResult.successNoData(); } @SuppressWarnings({"unchecked", "rawtypes"}) @Nullable private static DataManipulator<?, ?> deserialize(String dataClass, DataView view) { try { final Class<?> clazz = Class.forName(dataClass); final Optional<DataManipulatorBuilder<?, ?>> optional = SpongeDataManager.getInstance().getBuilder((Class) clazz); if (optional.isPresent()) { final Optional<? extends DataManipulator<?, ?>> manipulatorOptional = optional.get().build(view); if (manipulatorOptional.isPresent()) { return manipulatorOptional.get(); } } } catch (Exception e) { new InvalidDataException("Could not translate " + dataClass + "! Don't worry though, we'll try to translate the rest of the data.", e).printStackTrace(); } return null; } public static void readCustomData(NBTTagCompound compound, DataHolder dataHolder) { if (dataHolder instanceof IMixinCustomDataHolder) { if (compound.hasKey(NbtDataUtil.CUSTOM_MANIPULATOR_TAG_LIST, NbtDataUtil.TAG_LIST)) { final NBTTagList list = compound.getTagList(NbtDataUtil.CUSTOM_MANIPULATOR_TAG_LIST, NbtDataUtil.TAG_COMPOUND); final ImmutableList.Builder<DataView> builder = ImmutableList.builder(); if (list != null && list.tagCount() != 0) { for (int i = 0; i < list.tagCount(); i++) { final NBTTagCompound internal = list.getCompoundTagAt(i); builder.add(NbtTranslator.getInstance().translateFrom(internal)); } } try { final SerializedDataTransaction transaction = DataUtil.deserializeManipulatorList(builder.build()); final List<DataManipulator<?, ?>> manipulators = transaction.deserializedManipulators; for (DataManipulator<?, ?> manipulator : manipulators) { dataHolder.offer(manipulator); } if (!transaction.failedData.isEmpty()) { ((IMixinCustomDataHolder) dataHolder).addFailedData(transaction.failedData); } } catch (InvalidDataException e) { SpongeImpl.getLogger().error("Could not translate custom plugin data! ", e); } } if (compound.hasKey(NbtDataUtil.FAILED_CUSTOM_DATA, NbtDataUtil.TAG_LIST)) { final NBTTagList list = compound.getTagList(NbtDataUtil.FAILED_CUSTOM_DATA, NbtDataUtil.TAG_COMPOUND); final ImmutableList.Builder<DataView> builder = ImmutableList.builder(); if (list != null && list.tagCount() != 0) { for (int i = 0; i < list.tagCount(); i++) { final NBTTagCompound internal = list.getCompoundTagAt(i); builder.add(NbtTranslator.getInstance().translateFrom(internal)); } } // Re-attempt to deserialize custom data final SerializedDataTransaction transaction = DataUtil.deserializeManipulatorList(builder.build()); final List<DataManipulator<?, ?>> manipulators = transaction.deserializedManipulators; for (DataManipulator<?, ?> manipulator : manipulators) { dataHolder.offer(manipulator); } if (!transaction.failedData.isEmpty()) { ((IMixinCustomDataHolder) dataHolder).addFailedData(transaction.failedData); } } } } public static void writeCustomData(NBTTagCompound compound, DataHolder dataHolder) { if (dataHolder instanceof IMixinCustomDataHolder) { final List<DataManipulator<?, ?>> manipulators = ((IMixinCustomDataHolder) dataHolder).getCustomManipulators(); if (!manipulators.isEmpty()) { final List<DataView> manipulatorViews = DataUtil.getSerializedManipulatorList(manipulators); final NBTTagList manipulatorTagList = new NBTTagList(); for (DataView dataView : manipulatorViews) { manipulatorTagList.appendTag(NbtTranslator.getInstance().translateData(dataView)); } compound.setTag(NbtDataUtil.CUSTOM_MANIPULATOR_TAG_LIST, manipulatorTagList); } final List<DataView> failedData = ((IMixinCustomDataHolder) dataHolder).getFailedData(); if (!failedData.isEmpty()) { final NBTTagList failedList = new NBTTagList(); for (DataView failedDatum : failedData) { failedList.appendTag(NbtTranslator.getInstance().translateData(failedDatum)); } compound.setTag(NbtDataUtil.FAILED_CUSTOM_DATA, failedList); } } } }
Fix failed data not being removed after successful deserialization. Fixes #1683. Signed-off-by: Gabriel Harris-Rouquette <[email protected]>
src/main/java/org/spongepowered/common/data/nbt/CustomDataNbtUtil.java
Fix failed data not being removed after successful deserialization. Fixes #1683.
<ide><path>rc/main/java/org/spongepowered/common/data/nbt/CustomDataNbtUtil.java <ide> return null; <ide> } <ide> <add> @SuppressWarnings("unchecked") <ide> public static void readCustomData(NBTTagCompound compound, DataHolder dataHolder) { <ide> if (dataHolder instanceof IMixinCustomDataHolder) { <ide> if (compound.hasKey(NbtDataUtil.CUSTOM_MANIPULATOR_TAG_LIST, NbtDataUtil.TAG_LIST)) { <ide> final NBTTagCompound internal = list.getCompoundTagAt(i); <ide> builder.add(NbtTranslator.getInstance().translateFrom(internal)); <ide> } <del> } <add> <add> } <add> // We want to attempt to refresh the failed data if it does succeed in getting read. <add> compound.removeTag(NbtDataUtil.FAILED_CUSTOM_DATA); <ide> // Re-attempt to deserialize custom data <ide> final SerializedDataTransaction transaction = DataUtil.deserializeManipulatorList(builder.build()); <ide> final List<DataManipulator<?, ?>> manipulators = transaction.deserializedManipulators; <add> List<Class<? extends DataManipulator<?, ?>>> classesLoaded = new ArrayList<>(); <ide> for (DataManipulator<?, ?> manipulator : manipulators) { <del> dataHolder.offer(manipulator); <add> if (!classesLoaded.contains(manipulator.getClass())) { <add> classesLoaded.add((Class<? extends DataManipulator<?, ?>>) manipulator.getClass()); <add> // If for any reason a failed data was not deserialized, but <add> // there already exists new data, we just simply want to <add> // ignore the failed data for removal. <add> if (!((IMixinCustomDataHolder) dataHolder).getCustom(manipulator.getClass()).isPresent()) { <add> dataHolder.offer(manipulator); <add> } <add> } <ide> } <ide> if (!transaction.failedData.isEmpty()) { <ide> ((IMixinCustomDataHolder) dataHolder).addFailedData(transaction.failedData);
Java
apache-2.0
4bc202deca5a3bf500cc5c8ef16c9e4d7e04edf4
0
eclipseek/disruptor,azureplus/disruptor,chanakaudaya/disruptor,jasonchaffee/disruptor,epickrram/disruptor,Spikhalskiy/disruptor,DerekYangYC/disruptor,qiaochao911/disruptor,eclipseek/disruptor,fengshao0907/disruptor,DerekYangYC/disruptor,LMAX-Exchange/disruptor,sgulinski/disruptor,isururanawaka/disruptor,newsky/disruptor,isururanawaka/disruptor,brennangaunce/disruptor,DerekYangYC/disruptor,AllenRay/disruptor,simmeryson/MyDisruptor,tharanga-abeyseela/disruptor,qiaochao911/disruptor,brennangaunce/disruptor,tharanga-abeyseela/disruptor,eliocapelati/disruptor,xiexingguang/disruptor,killbug2004/disruptor,AllenRay/disruptor,jasonchaffee/disruptor,azureplus/disruptor,AllenRay/disruptor,xiexingguang/disruptor,vvertigo/disruptor,biddyweb/disruptor,pengzj/disruptor,sgulinski/disruptor,LMAX-Exchange/disruptor,qiaochao911/disruptor,hejunbinlan/disruptor,xiexingguang/disruptor,midnight0532/read-disruptor,adamweixuan/disruptor,sgulinski/disruptor,Spikhalskiy/disruptor,chanakaudaya/disruptor,iacdingping/disruptor,adamweixuan/disruptor,midnight0532/read-disruptor,Spikhalskiy/disruptor,brennangaunce/disruptor,hejunbinlan/disruptor,cherrydocker/disruptor,vvertigo/disruptor,pengzj/disruptor,epickrram/disruptor,adamweixuan/disruptor,cherrydocker/disruptor,eclipseek/disruptor,newsky/disruptor,epickrram/disruptor,tharanga-abeyseela/disruptor,chanakaudaya/disruptor,simmeryson/MyDisruptor,fengshao0907/disruptor,jasonchaffee/disruptor,biddyweb/disruptor,cherrydocker/disruptor,isururanawaka/disruptor,HappyYang/disruptor,iacdingping/disruptor,killbug2004/disruptor,newsky/disruptor,azureplus/disruptor,killbug2004/disruptor,HappyYang/disruptor,fengshao0907/disruptor,midnight0532/read-disruptor,vvertigo/disruptor,eliocapelati/disruptor,iacdingping/disruptor,HappyYang/disruptor,pengzj/disruptor,hejunbinlan/disruptor,biddyweb/disruptor,eliocapelati/disruptor
/* * Copyright 2011 LMAX 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 com.lmax.disruptor; import java.util.concurrent.atomic.AtomicBoolean; import java.util.concurrent.locks.Condition; import java.util.concurrent.locks.Lock; import java.util.concurrent.locks.ReentrantLock; /** * Blocking strategy that uses a lock and condition variable for {@link EventProcessor}s waiting on a barrier. * * This strategy can be used when throughput and low-latency are not as important as CPU resource. */ public final class LiteBlockingWaitStrategy implements WaitStrategy { private final Lock lock = new ReentrantLock(); private final Condition processorNotifyCondition = lock.newCondition(); private final AtomicBoolean signalNeeded = new AtomicBoolean(false); @Override public long waitFor(long sequence, Sequence cursorSequence, Sequence dependentSequence, SequenceBarrier barrier) throws AlertException, InterruptedException { long availableSequence; if ((availableSequence = cursorSequence.get()) < sequence) { lock.lock(); try { do { signalNeeded.getAndSet(true); if ((availableSequence = cursorSequence.get()) >= sequence) { break; } barrier.checkAlert(); processorNotifyCondition.await(); } while ((availableSequence = cursorSequence.get()) < sequence); } finally { lock.unlock(); } } while ((availableSequence = dependentSequence.get()) < sequence) { barrier.checkAlert(); } return availableSequence; } @Override public void signalAllWhenBlocking() { if (signalNeeded.getAndSet(false)) { lock.lock(); try { processorNotifyCondition.signalAll(); } finally { lock.unlock(); } } } }
src/main/java/com/lmax/disruptor/LiteBlockingWaitStrategy.java
/* * Copyright 2011 LMAX 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 com.lmax.disruptor; import java.util.concurrent.atomic.AtomicBoolean; import java.util.concurrent.locks.Condition; import java.util.concurrent.locks.Lock; import java.util.concurrent.locks.ReentrantLock; /** * Blocking strategy that uses a lock and condition variable for {@link EventProcessor}s waiting on a barrier. * * This strategy can be used when throughput and low-latency are not as important as CPU resource. */ public final class LiteBlockingWaitStrategy implements WaitStrategy { private final Lock lock = new ReentrantLock(); private final Condition processorNotifyCondition = lock.newCondition(); private final AtomicBoolean signalNeeded = new AtomicBoolean(false); @Override public long waitFor(long sequence, Sequence cursorSequence, Sequence dependentSequence, SequenceBarrier barrier) throws AlertException, InterruptedException { long availableSequence; if ((availableSequence = cursorSequence.get()) < sequence) { lock.lock(); try { do { signalNeeded.set(true); if ((availableSequence = cursorSequence.get()) >= sequence) { break; } barrier.checkAlert(); processorNotifyCondition.await(); } while ((availableSequence = cursorSequence.get()) < sequence); } finally { lock.unlock(); } } while ((availableSequence = dependentSequence.get()) < sequence) { barrier.checkAlert(); } return availableSequence; } @Override public void signalAllWhenBlocking() { if (signalNeeded.getAndSet(false)) { lock.lock(); try { processorNotifyCondition.signalAll(); } finally { lock.unlock(); } } } }
Update LiteBlockingWaitStrategy with getAndSet for signalNeeded flag
src/main/java/com/lmax/disruptor/LiteBlockingWaitStrategy.java
Update LiteBlockingWaitStrategy with getAndSet for signalNeeded flag
<ide><path>rc/main/java/com/lmax/disruptor/LiteBlockingWaitStrategy.java <ide> { <ide> do <ide> { <del> signalNeeded.set(true); <add> signalNeeded.getAndSet(true); <ide> <ide> if ((availableSequence = cursorSequence.get()) >= sequence) <ide> {
Java
apache-2.0
1d6709531c8040bc11ac7ead700a80b896e85672
0
nssales/OG-Platform,nssales/OG-Platform,jerome79/OG-Platform,jeorme/OG-Platform,McLeodMoores/starling,ChinaQuants/OG-Platform,ChinaQuants/OG-Platform,jeorme/OG-Platform,ChinaQuants/OG-Platform,DevStreet/FinanceAnalytics,codeaudit/OG-Platform,jerome79/OG-Platform,codeaudit/OG-Platform,ChinaQuants/OG-Platform,DevStreet/FinanceAnalytics,jerome79/OG-Platform,DevStreet/FinanceAnalytics,jeorme/OG-Platform,nssales/OG-Platform,jeorme/OG-Platform,McLeodMoores/starling,codeaudit/OG-Platform,McLeodMoores/starling,McLeodMoores/starling,nssales/OG-Platform,jerome79/OG-Platform,DevStreet/FinanceAnalytics,codeaudit/OG-Platform
/** * Copyright (C) 2011 - present by OpenGamma Inc. and the OpenGamma group of companies * * Please see distribution for license. */ package com.opengamma.bbg.loader; import static com.opengamma.bbg.BloombergConstants.*; import static com.opengamma.bbg.util.BloombergDataUtils.isValidField; import java.util.Collections; import java.util.Set; import javax.time.calendar.ZonedDateTime; import org.fudgemsg.FudgeMsg; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import com.google.common.collect.ImmutableSet; import com.google.common.collect.Sets; import com.opengamma.bbg.ReferenceDataProvider; import com.opengamma.bbg.util.BloombergDataUtils; import com.opengamma.core.id.ExternalSchemes; import com.opengamma.financial.security.future.EquityFutureSecurity; import com.opengamma.id.ExternalId; import com.opengamma.master.security.ManageableSecurity; import com.opengamma.util.money.Currency; import com.opengamma.util.time.Expiry; /** Creates EquityFutureSecurity from fields loaded from Bloomberg */ public class EquityFutureLoader extends SecurityLoader { /** Logger. */ private static final Logger s_logger = LoggerFactory.getLogger(EquityFutureLoader.class); /** The fields to load from Bloomberg */ private static final Set<String> BLOOMBERG_EQUITY_FUTURE_FIELDS = Collections.unmodifiableSet(Sets.newHashSet( FIELD_FUT_LONG_NAME, FIELD_FUT_LAST_TRADE_DT, FIELD_FUT_TRADING_HRS, FIELD_ID_MIC_PRIM_EXCH, FIELD_CRNCY, FIELD_MARKET_SECTOR_DES, FIELD_PARSEKYABLE_DES, FIELD_UNDL_SPOT_TICKER, FIELD_ID_BBG_UNIQUE, FIELD_ID_CUSIP, FIELD_ID_ISIN, FIELD_ID_SEDOL1, FIELD_FUT_VAL_PT, FIELD_FUTURES_CATEGORY)); /** The set of valid Bloomberg 'Futures Category Types' that will map to EquityFutureSecurity */ public static final Set<String> VALID_SECURITY_TYPES = ImmutableSet.of(BLOOMBERG_EQUITY_INDEX_TYPE); /** * Creates an instance. * @param referenceDataProvider the provider, not null */ public EquityFutureLoader(ReferenceDataProvider referenceDataProvider) { super(s_logger, referenceDataProvider, SecurityType.EQUITY_FUTURE); } //------------------------------------------------------------------------- @Override protected ManageableSecurity createSecurity(FudgeMsg fieldData) { String expiryDate = fieldData.getString(FIELD_FUT_LAST_TRADE_DT); String futureTradingHours = fieldData.getString(FIELD_FUT_TRADING_HRS); String micExchangeCode = fieldData.getString(FIELD_ID_MIC_PRIM_EXCH); String currencyStr = fieldData.getString(FIELD_CRNCY); String underlyingTicker = fieldData.getString(FIELD_UNDL_SPOT_TICKER); String name = BloombergDataUtils.removeDuplicateWhiteSpace(fieldData.getString(FIELD_FUT_LONG_NAME), " "); String category = BloombergDataUtils.removeDuplicateWhiteSpace(fieldData.getString(FIELD_FUTURES_CATEGORY), " "); String bbgUnique = fieldData.getString(FIELD_ID_BBG_UNIQUE); String marketSector = fieldData.getString(FIELD_MARKET_SECTOR_DES); String unitAmount = fieldData.getString(FIELD_FUT_VAL_PT); if (!isValidField(bbgUnique)) { s_logger.warn("bbgUnique is null, cannot construct EquityFutureSecurity"); return null; } if (!isValidField(expiryDate)) { s_logger.warn("expiry date is null, cannot construct EquityFutureSecurity"); return null; } if (!isValidField(futureTradingHours)) { s_logger.warn("futures trading hours is null, cannot construct EquityFutureSecurity"); return null; } if (!isValidField(micExchangeCode)) { s_logger.warn("settlement exchange is null, cannot construct EquityFutureSecurity"); return null; } if (!isValidField(currencyStr)) { s_logger.info("currency is null, cannot construct EquityFutureSecurity"); return null; } if (!isValidField(category)) { s_logger.info("category is null, cannot construct EquityFutureSecurity"); return null; } ExternalId underlying = null; if (underlyingTicker != null) { underlying = ExternalSchemes.bloombergTickerSecurityId(underlyingTicker + " " + marketSector); } Currency currency = Currency.parse(currencyStr); Expiry expiry = decodeExpiry(expiryDate, futureTradingHours); if (expiry == null) { return null; } // FIXME: Case - treatment of Settlement Date s_logger.warn("Creating EquityFutureSecurity - settlementDate set equal to expiryDate. Missing lag."); ZonedDateTime settlementDate = expiry.getExpiry(); EquityFutureSecurity security = new EquityFutureSecurity(expiry, micExchangeCode, micExchangeCode, currency, Double.valueOf(unitAmount), settlementDate, underlying, category); security.setName(name); // set identifiers parseIdentifiers(fieldData, security); return security; } @Override protected Set<String> getBloombergFields() { return BLOOMBERG_EQUITY_FUTURE_FIELDS; } }
projects/OG-Bloomberg/src/com/opengamma/bbg/loader/EquityFutureLoader.java
/** * Copyright (C) 2011 - present by OpenGamma Inc. and the OpenGamma group of companies * * Please see distribution for license. */ package com.opengamma.bbg.loader; import static com.opengamma.bbg.BloombergConstants.*; import static com.opengamma.bbg.util.BloombergDataUtils.isValidField; import java.util.Collections; import java.util.Set; import javax.time.calendar.ZonedDateTime; import org.fudgemsg.FudgeMsg; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import com.google.common.collect.ImmutableSet; import com.google.common.collect.Sets; import com.opengamma.bbg.ReferenceDataProvider; import com.opengamma.bbg.util.BloombergDataUtils; import com.opengamma.core.id.ExternalSchemes; import com.opengamma.financial.security.future.EquityFutureSecurity; import com.opengamma.id.ExternalId; import com.opengamma.master.security.ManageableSecurity; import com.opengamma.util.money.Currency; import com.opengamma.util.time.Expiry; /** Creates EquityFutureSecurity from fields loaded from Bloomberg */ public class EquityFutureLoader extends SecurityLoader { /** Logger. */ private static final Logger s_logger = LoggerFactory.getLogger(EquityFutureLoader.class); /** The fields to load from Bloomberg */ private static final Set<String> BLOOMBERG_EQUITY_FUTURE_FIELDS = Collections.unmodifiableSet(Sets.newHashSet( FIELD_FUT_LONG_NAME, FIELD_FUT_LAST_TRADE_DT, FIELD_FUT_TRADING_HRS, FIELD_ID_MIC_PRIM_EXCH, FIELD_CRNCY, FIELD_MARKET_SECTOR_DES, FIELD_PARSEKYABLE_DES, FIELD_UNDL_SPOT_TICKER, FIELD_ID_BBG_UNIQUE, FIELD_ID_CUSIP, FIELD_ID_ISIN, FIELD_ID_SEDOL1, FIELD_FUT_VAL_PT, FIELD_FUTURES_CATEGORY)); /** The set of valid Bloomberg 'Futures Category Types' that will map to EquityFutureSecurity */ public static final Set<String> VALID_SECURITY_TYPES = ImmutableSet.of(BLOOMBERG_EQUITY_INDEX_TYPE); /** * Creates an instance. * @param referenceDataProvider the provider, not null */ public EquityFutureLoader(ReferenceDataProvider referenceDataProvider) { super(s_logger, referenceDataProvider, SecurityType.EQUITY_FUTURE); } //------------------------------------------------------------------------- @Override protected ManageableSecurity createSecurity(FudgeMsg fieldData) { String expiryDate = fieldData.getString(FIELD_FUT_LAST_TRADE_DT); String futureTradingHours = fieldData.getString(FIELD_FUT_TRADING_HRS); String micExchangeCode = fieldData.getString(FIELD_ID_MIC_PRIM_EXCH); String currencyStr = fieldData.getString(FIELD_CRNCY); String underlyingTicker = fieldData.getString(FIELD_UNDL_SPOT_TICKER); String name = BloombergDataUtils.removeDuplicateWhiteSpace(fieldData.getString(FIELD_FUT_LONG_NAME), " "); String category = BloombergDataUtils.removeDuplicateWhiteSpace(fieldData.getString(FIELD_FUTURES_CATEGORY), " "); String bbgUnique = fieldData.getString(FIELD_ID_BBG_UNIQUE); String marketSector = fieldData.getString(FIELD_MARKET_SECTOR_DES); String unitAmount = fieldData.getString(FIELD_FUT_VAL_PT); if (!isValidField(bbgUnique)) { s_logger.warn("bbgUnique is null, cannot construct EquityFutureSecurity"); return null; } if (!isValidField(expiryDate)) { s_logger.warn("expiry date is null, cannot construct EquityFutureSecurity"); return null; } if (!isValidField(futureTradingHours)) { s_logger.warn("futures trading hours is null, cannot construct EquityFutureSecurity"); return null; } if (!isValidField(micExchangeCode)) { s_logger.warn("settlement exchange is null, cannot construct EquityFutureSecurity"); return null; } if (!isValidField(currencyStr)) { s_logger.info("currency is null, cannot construct EquityFutureSecurity"); return null; } ExternalId underlying = null; if (underlyingTicker != null) { underlying = ExternalSchemes.bloombergTickerSecurityId(underlyingTicker + " " + marketSector); } Currency currency = Currency.parse(currencyStr); Expiry expiry = decodeExpiry(expiryDate, futureTradingHours); if (expiry == null) { return null; } // FIXME: Case - treatment of Settlement Date s_logger.warn("Creating EquityFutureSecurity - settlementDate set equal to expiryDate. Missing lag."); ZonedDateTime settlementDate = expiry.getExpiry(); EquityFutureSecurity security = new EquityFutureSecurity(expiry, micExchangeCode, micExchangeCode, currency, Double.valueOf(unitAmount), settlementDate, underlying, category); security.setName(name); // set identifiers parseIdentifiers(fieldData, security); return security; } @Override protected Set<String> getBloombergFields() { return BLOOMBERG_EQUITY_FUTURE_FIELDS; } }
Handle missing category (cherry-picking from commit cad86a6ceb7132f563aa396a715bee3888aeead7)
projects/OG-Bloomberg/src/com/opengamma/bbg/loader/EquityFutureLoader.java
Handle missing category
<ide><path>rojects/OG-Bloomberg/src/com/opengamma/bbg/loader/EquityFutureLoader.java <ide> s_logger.info("currency is null, cannot construct EquityFutureSecurity"); <ide> return null; <ide> } <add> if (!isValidField(category)) { <add> s_logger.info("category is null, cannot construct EquityFutureSecurity"); <add> return null; <add> } <ide> ExternalId underlying = null; <ide> if (underlyingTicker != null) { <ide> underlying = ExternalSchemes.bloombergTickerSecurityId(underlyingTicker + " " + marketSector);
Java
apache-2.0
3cbfa482efa59da857bbee31f804e5fefcce2fa3
0
mjwheatley/cordova-plugin-android-fingerprint-auth,mjwheatley/cordova-plugin-android-fingerprint-auth
/* * Copyright (C) 2015 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.cordova.plugin.android.fingerprintauth; import android.app.DialogFragment; import android.app.KeyguardManager; import android.content.Context; import android.content.DialogInterface; import android.content.Intent; import android.content.SharedPreferences; import android.hardware.fingerprint.FingerprintManager; import android.os.Bundle; import android.util.Log; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.view.inputmethod.InputMethodManager; import android.widget.Button; import android.widget.ImageView; import android.widget.TextView; import android.widget.Toast; /** * A dialog which uses fingerprint APIs to authenticate the user, and falls back to password * authentication if fingerprint is not available. */ public class FingerprintAuthenticationDialogFragment extends DialogFragment implements FingerprintUiHelper.Callback { private static final String TAG = "FingerprintAuthDialog"; private static final int REQUEST_CODE_CONFIRM_DEVICE_CREDENTIALS = 1; private Button mCancelButton; private Button mSecondDialogButton; private View mFingerprintContent; private Stage mStage = Stage.FINGERPRINT; private KeyguardManager mKeyguardManager; private FingerprintManager.CryptoObject mCryptoObject; private FingerprintUiHelper mFingerprintUiHelper; FingerprintUiHelper.FingerprintUiHelperBuilder mFingerprintUiHelperBuilder; public FingerprintAuthenticationDialogFragment() { } @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); // Do not create a new Fragment when the Activity is re-created such as orientation changes. setRetainInstance(true); setStyle(DialogFragment.STYLE_NO_TITLE, android.R.style.Theme_Material_Light_Dialog); mKeyguardManager = (KeyguardManager) getContext().getSystemService(Context.KEYGUARD_SERVICE); mFingerprintUiHelperBuilder = new FingerprintUiHelper.FingerprintUiHelperBuilder( getContext(), getContext().getSystemService(FingerprintManager.class)); } @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { Bundle args = getArguments(); Log.d(TAG, "disableBackup: " + FingerprintAuth.mDisableBackup); // Inflate layout int fingerprint_dialog_container_id = getResources() .getIdentifier("fingerprint_dialog_container", "layout", FingerprintAuth.packageName); View v = inflater.inflate(fingerprint_dialog_container_id, container, false); // Set dialog Title int fingerprint_auth_dialog_title_id = getResources() .getIdentifier("fingerprint_auth_dialog_title", "id", FingerprintAuth.packageName); TextView dialogTitleTextView = (TextView) v.findViewById(fingerprint_auth_dialog_title_id); if (null != FingerprintAuth.mDialogTitle) { dialogTitleTextView.setText(FingerprintAuth.mDialogTitle); } // Set dialog message int fingerprint_description_id = getResources() .getIdentifier("fingerprint_description", "id", FingerprintAuth.packageName); TextView dialogMessageTextView = (TextView) v.findViewById(fingerprint_description_id); if (null != FingerprintAuth.mDialogMessage) { dialogMessageTextView.setText(FingerprintAuth.mDialogMessage); } // Set dialog hing int fingerprint_hint_id = getResources() .getIdentifier("fingerprint_status", "id", FingerprintAuth.packageName); TextView dialogHintTextView = (TextView) v.findViewById(fingerprint_hint_id); if (null != FingerprintAuth.mDialogHint) { dialogHintTextView.setText(FingerprintAuth.mDialogHint); } int cancel_button_id = getResources() .getIdentifier("cancel_button", "id", FingerprintAuth.packageName); mCancelButton = (Button) v.findViewById(cancel_button_id); mCancelButton.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { FingerprintAuth.onCancelled(); dismissAllowingStateLoss(); } }); int second_dialog_button_id = getResources() .getIdentifier("second_dialog_button", "id", FingerprintAuth.packageName); mSecondDialogButton = (Button) v.findViewById(second_dialog_button_id); if (FingerprintAuth.mDisableBackup) { mSecondDialogButton.setVisibility(View.GONE); } mSecondDialogButton.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { goToBackup(); } }); int fingerprint_container_id = getResources() .getIdentifier("fingerprint_container", "id", FingerprintAuth.packageName); mFingerprintContent = v.findViewById(fingerprint_container_id); int new_fingerprint_enrolled_description_id = getResources() .getIdentifier("new_fingerprint_enrolled_description", "id", FingerprintAuth.packageName); int fingerprint_icon_id = getResources() .getIdentifier("fingerprint_icon", "id", FingerprintAuth.packageName); int fingerprint_status_id = getResources() .getIdentifier("fingerprint_status", "id", FingerprintAuth.packageName); mFingerprintUiHelper = mFingerprintUiHelperBuilder.build( (ImageView) v.findViewById(fingerprint_icon_id), (TextView) v.findViewById(fingerprint_status_id), this); updateStage(); // If fingerprint authentication is not available, switch immediately to the backup // (password) screen. if (!mFingerprintUiHelper.isFingerprintAuthAvailable()) { goToBackup(); } return v; } @Override public void onResume() { super.onResume(); if (mStage == Stage.FINGERPRINT) { mFingerprintUiHelper.startListening(mCryptoObject); } } public void setStage(Stage stage) { mStage = stage; } @Override public void onPause() { super.onPause(); mFingerprintUiHelper.stopListening(); } /** * Sets the crypto object to be passed in when authenticating with fingerprint. */ public void setCryptoObject(FingerprintManager.CryptoObject cryptoObject) { mCryptoObject = cryptoObject; } /** * Switches to backup (password) screen. This either can happen when fingerprint is not * available or the user chooses to use the password authentication method by pressing the * button. This can also happen when the user had too many fingerprint attempts. */ private void goToBackup() { mStage = Stage.BACKUP; updateStage(); } private void updateStage() { int cancel_id = getResources() .getIdentifier("cancel", "string", FingerprintAuth.packageName); switch (mStage) { case FINGERPRINT: mCancelButton.setText(cancel_id); int use_backup_id = getResources() .getIdentifier("use_backup", "string", FingerprintAuth.packageName); mSecondDialogButton.setText(use_backup_id); mFingerprintContent.setVisibility(View.VISIBLE); break; case NEW_FINGERPRINT_ENROLLED: // Intentional fall through case BACKUP: if (mStage == Stage.NEW_FINGERPRINT_ENROLLED) { } if (!mKeyguardManager.isKeyguardSecure()) { // Show a message that the user hasn't set up a lock screen. int secure_lock_screen_required_id = getResources() .getIdentifier("secure_lock_screen_required", "string", FingerprintAuth.packageName); Toast.makeText(getContext(), getString(secure_lock_screen_required_id), Toast.LENGTH_LONG).show(); return; } if (FingerprintAuth.mDisableBackup) { FingerprintAuth.onError("backup disabled"); return; } showAuthenticationScreen(); break; } } private void showAuthenticationScreen() { // Create the Confirm Credentials screen. You can customize the title and description. Or // we will provide a generic one for you if you leave it null Intent intent = mKeyguardManager.createConfirmDeviceCredentialIntent(null, null); if (intent != null) { startActivityForResult(intent, REQUEST_CODE_CONFIRM_DEVICE_CREDENTIALS); } } @Override public void onActivityResult(int requestCode, int resultCode, Intent data) { if (requestCode == REQUEST_CODE_CONFIRM_DEVICE_CREDENTIALS) { // Challenge completed, proceed with using cipher if (resultCode == getActivity().RESULT_OK) { FingerprintAuth.onAuthenticated(false /* used backup */, null); } else { // The user canceled or didn’t complete the lock screen // operation. Go to error/cancellation flow. FingerprintAuth.onCancelled(); } dismissAllowingStateLoss(); } } @Override public void onAuthenticated(FingerprintManager.AuthenticationResult result) { // Callback from FingerprintUiHelper. Let the activity know that authentication was // successful. FingerprintAuth.onAuthenticated(true /* withFingerprint */, result); dismissAllowingStateLoss(); } @Override public void onError(CharSequence errString) { if (!FingerprintAuth.mDisableBackup) { if (getActivity() != null && isAdded()) { goToBackup(); } } else { FingerprintAuth.onError(errString); dismissAllowingStateLoss(); } } @Override public void onCancel(DialogInterface dialog) { super.onCancel(dialog); FingerprintAuth.onCancelled(); } /** * Enumeration to indicate which authentication method the user is trying to authenticate with. */ public enum Stage { FINGERPRINT, NEW_FINGERPRINT_ENROLLED, BACKUP } }
src/android/FingerprintAuthenticationDialogFragment.java
/* * Copyright (C) 2015 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.cordova.plugin.android.fingerprintauth; import android.app.DialogFragment; import android.app.KeyguardManager; import android.content.Context; import android.content.DialogInterface; import android.content.Intent; import android.content.SharedPreferences; import android.hardware.fingerprint.FingerprintManager; import android.os.Bundle; import android.util.Log; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.view.inputmethod.InputMethodManager; import android.widget.Button; import android.widget.ImageView; import android.widget.TextView; import android.widget.Toast; /** * A dialog which uses fingerprint APIs to authenticate the user, and falls back to password * authentication if fingerprint is not available. */ public class FingerprintAuthenticationDialogFragment extends DialogFragment implements FingerprintUiHelper.Callback { private static final String TAG = "FingerprintAuthDialog"; private static final int REQUEST_CODE_CONFIRM_DEVICE_CREDENTIALS = 1; private Button mCancelButton; private Button mSecondDialogButton; private View mFingerprintContent; private Stage mStage = Stage.FINGERPRINT; private KeyguardManager mKeyguardManager; private FingerprintManager.CryptoObject mCryptoObject; private FingerprintUiHelper mFingerprintUiHelper; FingerprintUiHelper.FingerprintUiHelperBuilder mFingerprintUiHelperBuilder; public FingerprintAuthenticationDialogFragment() { } @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); // Do not create a new Fragment when the Activity is re-created such as orientation changes. setRetainInstance(true); setStyle(DialogFragment.STYLE_NO_TITLE, android.R.style.Theme_Material_Light_Dialog); mKeyguardManager = (KeyguardManager) getContext().getSystemService(Context.KEYGUARD_SERVICE); mFingerprintUiHelperBuilder = new FingerprintUiHelper.FingerprintUiHelperBuilder( getContext(), getContext().getSystemService(FingerprintManager.class)); } @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { Bundle args = getArguments(); Log.d(TAG, "disableBackup: " + FingerprintAuth.mDisableBackup); // Inflate layout int fingerprint_dialog_container_id = getResources() .getIdentifier("fingerprint_dialog_container", "layout", FingerprintAuth.packageName); View v = inflater.inflate(fingerprint_dialog_container_id, container, false); // Set dialog Title int fingerprint_auth_dialog_title_id = getResources() .getIdentifier("fingerprint_auth_dialog_title", "id", FingerprintAuth.packageName); TextView dialogTitleTextView = (TextView) v.findViewById(fingerprint_auth_dialog_title_id); if (null != FingerprintAuth.mDialogTitle) { dialogTitleTextView.setText(FingerprintAuth.mDialogTitle); } // Set dialog message int fingerprint_description_id = getResources() .getIdentifier("fingerprint_description", "id", FingerprintAuth.packageName); TextView dialogMessageTextView = (TextView) v.findViewById(fingerprint_description_id); if (null != FingerprintAuth.mDialogMessage) { dialogMessageTextView.setText(FingerprintAuth.mDialogMessage); } // Set dialog hing int fingerprint_hint_id = getResources() .getIdentifier("fingerprint_status", "id", FingerprintAuth.packageName); TextView dialogHintTextView = (TextView) v.findViewById(fingerprint_hint_id); if (null != FingerprintAuth.mDialogHint) { dialogHintTextView.setText(FingerprintAuth.mDialogHint); } int cancel_button_id = getResources() .getIdentifier("cancel_button", "id", FingerprintAuth.packageName); mCancelButton = (Button) v.findViewById(cancel_button_id); mCancelButton.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { FingerprintAuth.onCancelled(); dismiss(); } }); int second_dialog_button_id = getResources() .getIdentifier("second_dialog_button", "id", FingerprintAuth.packageName); mSecondDialogButton = (Button) v.findViewById(second_dialog_button_id); if (FingerprintAuth.mDisableBackup) { mSecondDialogButton.setVisibility(View.GONE); } mSecondDialogButton.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { goToBackup(); } }); int fingerprint_container_id = getResources() .getIdentifier("fingerprint_container", "id", FingerprintAuth.packageName); mFingerprintContent = v.findViewById(fingerprint_container_id); int new_fingerprint_enrolled_description_id = getResources() .getIdentifier("new_fingerprint_enrolled_description", "id", FingerprintAuth.packageName); int fingerprint_icon_id = getResources() .getIdentifier("fingerprint_icon", "id", FingerprintAuth.packageName); int fingerprint_status_id = getResources() .getIdentifier("fingerprint_status", "id", FingerprintAuth.packageName); mFingerprintUiHelper = mFingerprintUiHelperBuilder.build( (ImageView) v.findViewById(fingerprint_icon_id), (TextView) v.findViewById(fingerprint_status_id), this); updateStage(); // If fingerprint authentication is not available, switch immediately to the backup // (password) screen. if (!mFingerprintUiHelper.isFingerprintAuthAvailable()) { goToBackup(); } return v; } @Override public void onResume() { super.onResume(); if (mStage == Stage.FINGERPRINT) { mFingerprintUiHelper.startListening(mCryptoObject); } } public void setStage(Stage stage) { mStage = stage; } @Override public void onPause() { super.onPause(); mFingerprintUiHelper.stopListening(); } /** * Sets the crypto object to be passed in when authenticating with fingerprint. */ public void setCryptoObject(FingerprintManager.CryptoObject cryptoObject) { mCryptoObject = cryptoObject; } /** * Switches to backup (password) screen. This either can happen when fingerprint is not * available or the user chooses to use the password authentication method by pressing the * button. This can also happen when the user had too many fingerprint attempts. */ private void goToBackup() { mStage = Stage.BACKUP; updateStage(); } private void updateStage() { int cancel_id = getResources() .getIdentifier("cancel", "string", FingerprintAuth.packageName); switch (mStage) { case FINGERPRINT: mCancelButton.setText(cancel_id); int use_backup_id = getResources() .getIdentifier("use_backup", "string", FingerprintAuth.packageName); mSecondDialogButton.setText(use_backup_id); mFingerprintContent.setVisibility(View.VISIBLE); break; case NEW_FINGERPRINT_ENROLLED: // Intentional fall through case BACKUP: if (mStage == Stage.NEW_FINGERPRINT_ENROLLED) { } if (!mKeyguardManager.isKeyguardSecure()) { // Show a message that the user hasn't set up a lock screen. int secure_lock_screen_required_id = getResources() .getIdentifier("secure_lock_screen_required", "string", FingerprintAuth.packageName); Toast.makeText(getContext(), getString(secure_lock_screen_required_id), Toast.LENGTH_LONG).show(); return; } if (FingerprintAuth.mDisableBackup) { FingerprintAuth.onError("backup disabled"); return; } showAuthenticationScreen(); break; } } private void showAuthenticationScreen() { // Create the Confirm Credentials screen. You can customize the title and description. Or // we will provide a generic one for you if you leave it null Intent intent = mKeyguardManager.createConfirmDeviceCredentialIntent(null, null); if (intent != null) { startActivityForResult(intent, REQUEST_CODE_CONFIRM_DEVICE_CREDENTIALS); } } @Override public void onActivityResult(int requestCode, int resultCode, Intent data) { if (requestCode == REQUEST_CODE_CONFIRM_DEVICE_CREDENTIALS) { // Challenge completed, proceed with using cipher if (resultCode == getActivity().RESULT_OK) { FingerprintAuth.onAuthenticated(false /* used backup */, null); } else { // The user canceled or didn’t complete the lock screen // operation. Go to error/cancellation flow. FingerprintAuth.onCancelled(); } dismiss(); } } @Override public void onAuthenticated(FingerprintManager.AuthenticationResult result) { // Callback from FingerprintUiHelper. Let the activity know that authentication was // successful. FingerprintAuth.onAuthenticated(true /* withFingerprint */, result); dismiss(); } @Override public void onError(CharSequence errString) { if (!FingerprintAuth.mDisableBackup) { if (getActivity() != null && isAdded()) { goToBackup(); } } else { FingerprintAuth.onError(errString); dismiss(); } } @Override public void onCancel(DialogInterface dialog) { super.onCancel(dialog); FingerprintAuth.onCancelled(); } /** * Enumeration to indicate which authentication method the user is trying to authenticate with. */ public enum Stage { FINGERPRINT, NEW_FINGERPRINT_ENROLLED, BACKUP } }
Dismiss fragment in a safer way
src/android/FingerprintAuthenticationDialogFragment.java
Dismiss fragment in a safer way
<ide><path>rc/android/FingerprintAuthenticationDialogFragment.java <ide> @Override <ide> public void onClick(View view) { <ide> FingerprintAuth.onCancelled(); <del> dismiss(); <add> dismissAllowingStateLoss(); <ide> } <ide> }); <ide> <ide> // operation. Go to error/cancellation flow. <ide> FingerprintAuth.onCancelled(); <ide> } <del> dismiss(); <add> dismissAllowingStateLoss(); <ide> } <ide> } <ide> <ide> // Callback from FingerprintUiHelper. Let the activity know that authentication was <ide> // successful. <ide> FingerprintAuth.onAuthenticated(true /* withFingerprint */, result); <del> dismiss(); <add> dismissAllowingStateLoss(); <ide> } <ide> <ide> @Override <ide> } <ide> } else { <ide> FingerprintAuth.onError(errString); <del> dismiss(); <add> dismissAllowingStateLoss(); <ide> <ide> } <ide> }
JavaScript
mit
018806b7a1f869265af84beff608ca4742e9f5df
0
ollien/Crisscut
/*jshint eqnull: true */ var url = require("url"); var querystring = require("querystring"); module.exports = Crisscut; function Crisscut(routes) { this.routeTree = { path: "/", type: "explicit", children: [], callback: undefined }; if (routes !== undefined) { routes = correctRoutes(routes); addRoutesToRouteTree(this, routes); console.log(JSON.stringify(this.routeTree)); } } Crisscut.prototype.route = function (req, res, errCallback) { var parsedUrl = url.parse(req.url); var rawUrl = parsedUrl.pathname; var rawArguments = parsedUrl.query; var routeResult = findRouteFromUrl(this, rawUrl); if (routeResult != null) { var methods = routeResult.methods; var args = routeResult.args; var method = req.method.toLowerCase(); var parsedUrlArgs = querystring.parse(rawArguments); parsedUrlArgs = parsedUrlArgs === null ? {} : parsedUrlArgs; if (methods.hasOwnProperty(method)) { methods[method].apply({}, [req, res].concat(args, parsedUrlArgs)); } else if (methods.hasOwnProperty("on")) { methods.on.apply({}, [req, res].concat(args, parsedUrlArgs)); } else if (errCallback != null) { errCallback(methodNotAllowed(rawUrl, method)); } } else if (errCallback != null) { errCallback(pathNotFound(rawUrl)); } }; Crisscut.prototype.addRoute = function (method, route, func, callback) { var result = findRouteInTree(this, route); method = method.toLowerCase(); if (result != null) { result.functions[method] = func; } else { var checkObj = {}; checkObj[route] = {}; checkObj[route][method] = func; var corrected = correctRoute(checkObj); route = getKey(corrected); addRouteToRouteTree(this, route, corrected[route]); } if (callback != null) { callback(); } }; Crisscut.prototype.on = function (route, func, callback) { this.addRoute("on", route, func, callback); return this; }; Crisscut.prototype.get = function (route, func, callback) { this.addRoute("get", route, func, callback); return this; }; Crisscut.prototype.post = function (route, func, callback) { this.addRoute("post", route, func, callback); return this; }; Crisscut.prototype.put = function (route, func, callback) { this.addRoute("put", route, func, callback); return this; }; Crisscut.prototype.delete = function (route, func, callback) { this.addRoute("delete", route, func, callback); return this; }; Crisscut.prototype.trace = function (route, func, callback) { this.addRoute("trace", route, func, callback); return this; }; Crisscut.prototype.options = function (route, func, callback) { this.addRoute("options", route, func, callback); return this; }; Crisscut.prototype.connect = function (route, func, callback) { this.addRoute("connect", route, func, callback); return this; }; Crisscut.prototype.patch = function (route, func, callback) { this.addRoute("patch", route, func, callback); return this; }; function correctRoute(route) { var key = getKey(route); if (key === null) { return null; } var original = key; var value = route[key]; if (key[0] === "/" && key.length > 1) { //Routes must not begin with a /, unless they are / key = key.substring(1); } if (key[key.length - 1] === "/" && key.length > 1) { //Routes must not end with a /, unless of course, they are to the homepage. key = key.substring(0, key.length - 1); } if (key !== original) { delete route[original]; route[key] = value; } if (typeof route[key] === "object") { Object.keys(route[key]).forEach(function (item) { if (item !== item.toLowerCase()) { var value = route[key][item]; delete route[key][item]; route[key][item.toLowerCase()] = value; } }); } return route; } function correctRoutes(routes) { Object.keys(routes).forEach(function (route) { var obj = {}; obj[route] = routes[route]; var corrected = correctRoute(obj); if (corrected === null) { throw new Error("Error with object in correctRoutes"); } delete routes[route]; var key = getKey(corrected); routes[key] = corrected[key]; }); return routes; } function addRouteToRouteTree(router, route, functions, parentNode) { if (route.length === 0) { return; //No point in adding a route that literally is nothing. } if (route === "/") { // We already have a root element pre-made, we can just add a function in router.routeTree.functions = functions; return; } var routeSplit = route.split("/"); if (parentNode === undefined || parentNode === null) { parentNode = router.routeTree; } var index = findObjectWithPropertyValueInArray(parentNode.children, "path", routeSplit[0]); if (index > -1) { routeSplit.shift(); if (routeSplit.length > 0) { addRouteToRouteTree(router, routeSplit.join("/"), functions, parentNode.children[index]); } else { parentNode.children[index].functions = functions; } } else { var type = routeSplit[0][0] === ":" ? "variable" : "explicit"; var wild = false; var leaf = null; if (type === "variable") { if (routeSplit[0][1] === "(" && routeSplit[0][routeSplit[0].length - 1] === ")") { type = "regex"; } else if (routeSplit[0][1] === "(" && routeSplit[0][routeSplit[0].length - 2] === ")" && routeSplit[0][routeSplit[0].length - 1] === "*") { type = "regex"; wild = true; } } if (type === "variable") { index = findObjectWithPropertyValueInArray(parentNode.children, "type", "variable"); if (index > -1) { routeSplit.shift(); addRouteToRouteTree(router, routeSplit.join("/"), functions, parentNode.children[index]); } else { leaf = createLeaf(routeSplit[0], type, false); parentNode.children.push(leaf); routeSplit.shift(); if (routeSplit.length > 0) { addRouteToRouteTree(router, routeSplit.join("/"), functions, leaf); } else { leaf.functions = functions; } } } else { leaf = createLeaf(routeSplit[0], type, wild); parentNode.children.push(leaf); routeSplit.shift(); if (routeSplit.length > 0) { addRouteToRouteTree(router, routeSplit.join("/"), functions, leaf); } else { leaf.functions = functions; } } } } function addRoutesToRouteTree(router, routes) { Object.keys(routes).forEach(function (route) { addRouteToRouteTree(router, route, routes[route]); }); } function findRouteFromUrl(router, url, parentNode, args) { if (parentNode === null || parentNode === undefined) { parentNode = router.routeTree; } if (args === null || args === undefined) { args = []; } if (url === "/") { if (parentNode.functions == null) { return null; } else { return { methods: parentNode.functions, args: args }; } } else { if (url[0] === "/") { url = url.substring(1); } if (url[url.length - 1] === "/") { url = url.substring(0, url.length - 1); } } var urlSplit = url.split("/"); var index = findObjectWithPropertyValueInArray(parentNode.children, "path", urlSplit[0]); var methods = null; //If we have an explicit route, use it, otherwise, we need to do some searching. if (index > -1) { urlSplit.shift(); if (urlSplit.length > 0) { return findRouteFromUrl(router, urlSplit.join("/"), parentNode.children[index], args); } else { methods = parentNode.children[index].functions; if (methods === null || methods === undefined) { return null; } return { methods: methods, args: args }; } } else { var regexIndexes = findObjectsWithPropertyValueInArray(parentNode.children, "type", "regex"); var variableIndex = findObjectWithPropertyValueInArray(parentNode.children, "type", "variable"); //There should only ever be one variable in the tree. for (var i = 0; i < regexIndexes.length; i++) { index = regexIndexes[i]; var regex = parentNode.children[index].wild ? parentNode.children[index].path.substring(1, parentNode.children[index].path.length - 1) : parentNode.children[index].path.substring(1); var match = urlSplit[0].match(regex); if (match && match[0] === urlSplit[0]) { //We need to check if the regex was wildcard, in which case we need to keep going through the loop if (parentNode.children[index].wild) { var matches = []; matches.push(urlSplit[0]); urlSplit.shift(); while (urlSplit.length > 0) { match = urlSplit[0].match(regex); if (match && match[0] === urlSplit[0]) { matches.push(urlSplit[0]); urlSplit.shift(); } else { break; } } args.push(matches.join("/")); } else { args.push(urlSplit[0]); urlSplit.shift(); } if (urlSplit.length > 0) { return findRouteFromUrl(router, urlSplit.join("/"), parentNode.children[index], args); } else { methods = parentNode.children[index].functions; if (methods === null || methods === undefined) { //If it turns out there"s nothing for this route, we shouldn"t use it. In this case, we take out the argument and throw them back into urlSplit urlSplit.push(args.pop()); continue; } return { methods: methods, args: args }; } } } //If we haven"t matched regex, we can see if we have a variable. otherwise, we return null. if (variableIndex > -1) { args.push(urlSplit[0]); urlSplit.shift(); if (urlSplit.length > 0) { return findRouteFromUrl(router, urlSplit.join("/"), parentNode.children[variableIndex], args); } else { methods = parentNode.children[variableIndex].functions; if (methods === null || methods === undefined) { return null; } return { methods: methods, args: args }; } } } } function createLeaf(name, type, wild, functions) { return { path: name, type: type, wild: wild, children: [], functions: functions }; } function findRouteInTree(router, route, parentNode) { if (parentNode === undefined || parentNode === null) { parentNode = router.routeTree; } if (route === "/") { return parentNode; } var routeSplit = route.split("/"); var index = findObjectWithPropertyValueInArray(parentNode.children, "path", routeSplit[0]); if (index > -1) { routeSplit.shift(); if (routeSplit.length > 0) { return findRouteInTree(router, routeSplit.join("/"), parentNode.children[index]); } else { return parentNode.children[index]; } } //This checks if we need to find a variable. Regex is already checked for with the above block else if (routeSplit[0][0] === ":") { index = findObjectWithPropertyValueInArray(parentNode.children, "type", "variable"); if (index > -1) { routeSplit.shift(); if (routeSplit.length > 0) { return findRouteInTree(router, routeSplit.join("/"), parentNode.children[index]); } else { return parentNode.children[index]; } } } return null; } function pathNotFound(path) { return { errorCode: 404, error: path + " is not a known route." }; } function methodNotAllowed(path, method) { return { errorCode: 405, error: method.toUpperCase() + " is not allowed on " + path }; } function arrayHasObjectWithProperty(array, property) { for (var i = 0; i < array.length; i++) { if (array[i].hasOwnProperty(property)) { return true; } } return false; } function arrayHasObjectWithPropertyValue(array, property, value) { for (var i = 0; i < array.length; i++) { if (array[i].hasOwnProperty(property) && array[i][property] === value) { return false; } } return true; } function findObjectWithPropertyValueInArray(array, property, value) { for (var i = 0; i < array.length; i++) { if (array[i].hasOwnProperty(property) && array[i][property] === value) { return i; } } return -1; } function findObjectsWithPropertyValueInArray(array, property, value) { var results = []; for (var i = 0; i < array.length; i++) { if (array[i].hasOwnProperty(property) && array[i][property] === value) { results.push(i); } } return results; } function getKey(obj) { var keys = Object.keys(obj); if (keys.length === 1) { return keys[0]; } else { return null; } } function clone(object) { return JSON.parse(JSON.stringify(object)); }
index.js
/*jshint eqnull: true */ var url = require("url"); var querystring = require("querystring"); module.exports = Crisscut; function Crisscut(routes) { this.routeTree = { path: "/", type: "explicit", children: [], callback: undefined }; if (routes !== undefined) { routes = correctRoutes(routes); addRoutesToRouteTree(this, routes); console.log(JSON.stringify(this.routeTree)); } } Crisscut.prototype.route = function (req, res, errCallback) { var parsedUrl = url.parse(req.url); var rawUrl = parsedUrl.pathname; var rawArguments = parsedUrl.query; var routeResult = findRouteFromUrl(this, rawUrl); if (routeResult != null) { var methods = routeResult.methods; var args = routeResult.args; var method = req.method.toLowerCase(); var parsedUrlArgs = querystring.parse(rawArguments); parsedUrlArgs = parsedUrlArgs === null ? {} : parsedUrlArgs; if (methods.hasOwnProperty(method)) { methods[method].apply({}, [req, res].concat(args, parsedUrlArgs)); } else if (methods.hasOwnProperty("on")) { methods.on.apply({}, [req, res].concat(args, parsedUrlArgs)); } else if (errCallback != null) { errCallback(methodNotAllowed(rawUrl, method)); } } else if (errCallback != null) { errCallback(pathNotFound(rawUrl)); } }; Crisscut.prototype.addRoute = function (method, route, func, callback) { var result = findRouteInTree(this, route); method = method.toLowerCase(); if (result != null) { result.functions[method] = func; } else { var checkObj = {}; checkObj[route] = {}; checkObj[route][method] = func; var corrected = correctRoute(checkObj); route = getKey(corrected); addRouteToRouteTree(this, route, corrected[route]); } if (callback != null) { callback(); } }; Crisscut.prototype.on = function (route, func, callback) { this.addRoute("on", route, func, callback); return this; }; Crisscut.prototype.get = function (route, func, callback) { this.addRoute("get", route, func, callback); return this; }; Crisscut.prototype.post = function (route, func, callback) { this.addRoute("post", route, func, callback); return this; }; Crisscut.prototype.put = function (route, func, callback) { this.addRoute("put", route, func, callback); return this; }; Crisscut.prototype.delete = function (route, func, callback) { this.addRoute("delete", route, func, callback); return this; }; Crisscut.prototype.trace = function (route, func, callback) { this.addRoute("trace", route, func, callback); return this; }; Crisscut.prototype.options = function (route, func, callback) { this.addRoute("options", route, func, callback); return this; }; Crisscut.prototype.connect = function (route, func, callback) { this.addRoute("connect", route, func, callback); return this; }; Crisscut.prototype.patch = function (route, func, callback) { this.addRoute("patch", route, func, callback); return this; }; function correctRoute(route) { var key = getKey(route); if (key === null) { return null; } var original = key; var value = route[key]; if (key[0] === "/" && key.length > 1) { //Routes must not begin with a /, unless they are / key = key.substring(1); } if (key[key.length - 1] === "/" && key.length > 1) { //Routes must not end with a /, unless of course, they are to the homepage. key = key.substring(0, key.length - 1); } if (key !== original) { delete route[original]; route[key] = value; } if (typeof route[key] === "object") { Object.keys(route[key]).forEach(function (item) { if (item !== item.toLowerCase()) { var value = route[key][item]; delete route[key][item]; route[key][item.toLowerCase()] = value; } }); } return route; } function correctRoutes(routes) { Object.keys(routes).forEach(function (route) { var obj = {}; obj[route] = routes[route]; var corrected = correctRoute(obj); if (corrected === null) { throw new Error("Error with object in correctRoutes"); } delete routes[route]; var key = getKey(corrected); routes[key] = corrected[key]; }); return routes; } function addRouteToRouteTree(router, route, functions, parentNode) { if (route.length === 0) { return; //No point in adding a route that literally is nothing. } if (route === "/") { // We already have a root element pre-made, we can just add a function in router.routeTree.functions = functions; return; } var routeSplit = route.split("/"); if (parentNode === undefined || parentNode === null) { parentNode = router.routeTree; } var index = findObjectWithPropertyValueInArray(parentNode.children, "path", routeSplit[0]); if (index > -1) { routeSplit.shift(); if (routeSplit.length > 0) { addRouteToRouteTree(router, routeSplit.join("/"), functions, parentNode.children[index]); } else { parentNode.children[index].functions = functions; } } else { var type = routeSplit[0][0] === ":" ? "variable" : "explicit"; var wild = false; if (type === "variable") { if (routeSplit[0][1] === "(" && routeSplit[0][routeSplit[0].length - 1] === ")") { type = "regex"; } else if (routeSplit[0][1] === "(" && routeSplit[0][routeSplit[0].length - 2] === ")" && routeSplit[0][routeSplit[0].length - 1] === "*") { type = "regex"; wild = true; } } if (type === "variable") { index = findObjectWithPropertyValueInArray(parentNode.children, "type", "variable"); if (index > -1) { routeSplit.shift(); addRouteToRouteTree(router, routeSplit.join("/"), functions, parentNode.children[index]); } else { var leaf = createLeaf(routeSplit[0], type, false); parentNode.children.push(leaf); routeSplit.shift(); if (routeSplit.length > 0) { addRouteToRouteTree(router, routeSplit.join("/"), functions, leaf); } else { leaf.functions = functions; } } } else { var leaf = createLeaf(routeSplit[0], type, wild); parentNode.children.push(leaf); routeSplit.shift(); if (routeSplit.length > 0) { addRouteToRouteTree(router, routeSplit.join("/"), functions, leaf); } else { leaf.functions = functions; } } } } function addRoutesToRouteTree(router, routes) { Object.keys(routes).forEach(function (route) { addRouteToRouteTree(router, route, routes[route]); }); } function findRouteFromUrl(router, url, parentNode, args) { if (parentNode === null || parentNode === undefined) { parentNode = router.routeTree; } if (args === null || args === undefined) { args = []; } if (url === "/") { if (parentNode.functions == null) { return null; } else { return { methods: parentNode.functions, args: args }; } } else { if (url[0] === "/") { url = url.substring(1); } if (url[url.length - 1] === "/") { url = url.substring(0, url.length - 1); } } var urlSplit = url.split("/"); var index = findObjectWithPropertyValueInArray(parentNode.children, "path", urlSplit[0]); //If we have an explicit route, use it, otherwise, we need to do some searching. if (index > -1) { urlSplit.shift(); if (urlSplit.length > 0) { return findRouteFromUrl(router, urlSplit.join("/"), parentNode.children[index], args); } else { var methods = parentNode.children[index].functions; if (methods === null || methods === undefined) { return null; } return { methods: methods, args: args }; } } else { var regexIndexes = findObjectsWithPropertyValueInArray(parentNode.children, "type", "regex"); var variableIndex = findObjectWithPropertyValueInArray(parentNode.children, "type", "variable"); //There should only ever be one variable in the tree. for (var i = 0; i < regexIndexes.length; i++) { var index = regexIndexes[i]; var regex = parentNode.children[index].wild ? parentNode.children[index].path.substring(1, parentNode.children[index].path.length - 1) : parentNode.children[index].path.substring(1); var match = urlSplit[0].match(regex); if (match && match[0] === urlSplit[0]) { //We need to check if the regex was wildcard, in which case we need to keep going through the loop if (parentNode.children[index].wild) { var matches = []; matches.push(urlSplit[0]); urlSplit.shift(); while (urlSplit.length > 0) { match = urlSplit[0].match(regex); if (match && match[0] === urlSplit[0]) { matches.push(urlSplit[0]); urlSplit.shift(); } else { break; } } args.push(matches.join("/")); } else { args.push(urlSplit[0]); urlSplit.shift(); } if (urlSplit.length > 0) { return findRouteFromUrl(router, urlSplit.join("/"), parentNode.children[index], args); } else { var methods = parentNode.children[index].functions; if (methods === null || methods === undefined) { //If it turns out there"s nothing for this route, we shouldn"t use it. In this case, we take out the argument and throw them back into urlSplit urlSplit.push(args.pop()); continue; } return { methods: methods, args: args }; } } } //If we haven"t matched regex, we can see if we have a variable. otherwise, we return null. if (variableIndex > -1) { args.push(urlSplit[0]); urlSplit.shift(); if (urlSplit.length > 0) { return findRouteFromUrl(router, urlSplit.join("/"), parentNode.children[variableIndex], args); } else { var methods = parentNode.children[variableIndex].functions; if (methods === null || methods === undefined) { return null; } return { methods: methods, args: args }; } } } } function createLeaf(name, type, wild, functions) { return { path: name, type: type, wild: wild, children: [], functions: functions }; } function findRouteInTree(router, route, parentNode) { if (parentNode === undefined || parentNode === null) { parentNode = router.routeTree; } if (route === "/") { return parentNode; } var routeSplit = route.split("/"); var index = findObjectWithPropertyValueInArray(parentNode.children, "path", routeSplit[0]); if (index > -1) { routeSplit.shift(); if (routeSplit.length > 0) { return findRouteInTree(router, routeSplit.join("/"), parentNode.children[index]); } else { return parentNode.children[index]; } } //This checks if we need to find a variable. Regex is already checked for with the above block else if (routeSplit[0][0] === ":") { index = findObjectWithPropertyValueInArray(parentNode.children, "type", "variable"); if (index > -1) { routeSplit.shift(); if (routeSplit.length > 0) { return findRouteInTree(router, routeSplit.join("/"), parentNode.children[index]); } else { return parentNode.children[index]; } } } return null; } function pathNotFound(path) { return { errorCode: 404, error: path + " is not a known route." }; } function methodNotAllowed(path, method) { return { errorCode: 405, error: method.toUpperCase() + " is not allowed on " + path }; } function arrayHasObjectWithProperty(array, property) { for (var i = 0; i < array.length; i++) { if (array[i].hasOwnProperty(property)) { return true; } } return false; } function arrayHasObjectWithPropertyValue(array, property, value) { for (var i = 0; i < array.length; i++) { if (array[i].hasOwnProperty(property) && array[i][property] === value) { return false; } } return true; } function findObjectWithPropertyValueInArray(array, property, value) { for (var i = 0; i < array.length; i++) { if (array[i].hasOwnProperty(property) && array[i][property] === value) { return i; } } return -1; } function findObjectsWithPropertyValueInArray(array, property, value) { var results = []; for (var i = 0; i < array.length; i++) { if (array[i].hasOwnProperty(property) && array[i][property] === value) { results.push(i); } } return results; } function getKey(obj) { var keys = Object.keys(obj); if (keys.length === 1) { return keys[0]; } else { return null; } } function clone(object) { return JSON.parse(JSON.stringify(object)); }
Run jshint on codebase
index.js
Run jshint on codebase
<ide><path>ndex.js <ide> else { <ide> var type = routeSplit[0][0] === ":" ? "variable" : "explicit"; <ide> var wild = false; <add> var leaf = null; <ide> <ide> if (type === "variable") { <ide> if (routeSplit[0][1] === "(" && routeSplit[0][routeSplit[0].length - 1] === ")") { <ide> } <ide> <ide> else { <del> var leaf = createLeaf(routeSplit[0], type, false); <add> leaf = createLeaf(routeSplit[0], type, false); <ide> parentNode.children.push(leaf); <ide> routeSplit.shift(); <ide> if (routeSplit.length > 0) { <ide> } <ide> <ide> else { <del> var leaf = createLeaf(routeSplit[0], type, wild); <add> leaf = createLeaf(routeSplit[0], type, wild); <ide> parentNode.children.push(leaf); <ide> routeSplit.shift(); <ide> if (routeSplit.length > 0) { <ide> } <ide> var urlSplit = url.split("/"); <ide> var index = findObjectWithPropertyValueInArray(parentNode.children, "path", urlSplit[0]); <add> var methods = null; <ide> <ide> //If we have an explicit route, use it, otherwise, we need to do some searching. <ide> if (index > -1) { <ide> } <ide> <ide> else { <del> var methods = parentNode.children[index].functions; <add> methods = parentNode.children[index].functions; <ide> if (methods === null || methods === undefined) { <ide> return null; <ide> } <ide> var variableIndex = findObjectWithPropertyValueInArray(parentNode.children, "type", "variable"); <ide> //There should only ever be one variable in the tree. <ide> for (var i = 0; i < regexIndexes.length; i++) { <del> var index = regexIndexes[i]; <add> index = regexIndexes[i]; <ide> var regex = parentNode.children[index].wild ? parentNode.children[index].path.substring(1, parentNode.children[index].path.length - 1) : parentNode.children[index].path.substring(1); <ide> var match = urlSplit[0].match(regex); <ide> if (match && match[0] === urlSplit[0]) { <ide> } <ide> <ide> else { <del> var methods = parentNode.children[index].functions; <add> methods = parentNode.children[index].functions; <ide> if (methods === null || methods === undefined) { <ide> //If it turns out there"s nothing for this route, we shouldn"t use it. In this case, we take out the argument and throw them back into urlSplit <ide> urlSplit.push(args.pop()); <ide> } <ide> <ide> else { <del> var methods = parentNode.children[variableIndex].functions; <add> methods = parentNode.children[variableIndex].functions; <ide> if (methods === null || methods === undefined) { <ide> return null; <ide> }
Java
agpl-3.0
1e83b1254a3756682d895c2abc3584fed9090bfb
0
OpenLMIS/openlmis-fulfillment,OpenLMIS/openlmis-fulfillment,OpenLMIS/openlmis-fulfillment,OpenLMIS/openlmis-fulfillment
/* * This program is part of the OpenLMIS logistics management information system platform software. * Copyright © 2017 VillageReach * * This program is free software: you can redistribute it and/or modify it under the terms * of the GNU Affero 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 Affero General Public License for more details. You should have received a copy of * the GNU Affero General Public License along with this program. If not, see * http://www.gnu.org/licenses.  For additional information contact [email protected].  */ package org.openlmis.fulfillment.service; import static org.hamcrest.Matchers.arrayContaining; import static org.hamcrest.Matchers.hasProperty; import static org.mockito.Mockito.inOrder; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.never; import static org.mockito.Mockito.when; import static org.openlmis.fulfillment.i18n.MessageKeys.ERROR_PERMISSION_MISSING; import static org.openlmis.fulfillment.service.PermissionService.ORDERS_EDIT; import static org.openlmis.fulfillment.service.PermissionService.ORDERS_TRANSFER; import static org.openlmis.fulfillment.service.PermissionService.ORDERS_VIEW; import static org.openlmis.fulfillment.service.PermissionService.PODS_MANAGE; import static org.openlmis.fulfillment.service.PermissionService.SHIPMENTS_EDIT; import static org.openlmis.fulfillment.service.PermissionService.SHIPMENTS_VIEW; import static org.openlmis.fulfillment.service.PermissionService.SYSTEM_SETTINGS_MANAGE; import static org.openlmis.fulfillment.testutils.OAuth2AuthenticationDataBuilder.API_KEY_PREFIX; import static org.openlmis.fulfillment.testutils.OAuth2AuthenticationDataBuilder.SERVICE_CLIENT_ID; import com.google.common.collect.Lists; import org.junit.Before; import org.junit.Rule; import org.junit.Test; import org.junit.rules.ExpectedException; import org.junit.runner.RunWith; import org.mockito.InOrder; import org.mockito.InjectMocks; import org.mockito.Mock; import org.mockito.runners.MockitoJUnitRunner; import org.openlmis.fulfillment.domain.Order; import org.openlmis.fulfillment.domain.ProofOfDelivery; import org.openlmis.fulfillment.domain.Shipment; import org.openlmis.fulfillment.repository.OrderRepository; import org.openlmis.fulfillment.service.referencedata.RightDto; import org.openlmis.fulfillment.service.referencedata.UserDto; import org.openlmis.fulfillment.service.referencedata.UserReferenceDataService; import org.openlmis.fulfillment.testutils.OAuth2AuthenticationDataBuilder; import org.openlmis.fulfillment.testutils.ShipmentDataBuilder; import org.openlmis.fulfillment.util.AuthenticationHelper; import org.openlmis.fulfillment.web.MissingPermissionException; import org.openlmis.fulfillment.web.shipment.ShipmentDto; import org.openlmis.fulfillment.web.util.ObjectReferenceDto; import org.springframework.security.core.context.SecurityContext; import org.springframework.security.core.context.SecurityContextHolder; import org.springframework.security.oauth2.provider.OAuth2Authentication; import org.springframework.test.util.ReflectionTestUtils; import java.util.UUID; @SuppressWarnings("PMD.TooManyMethods") @RunWith(MockitoJUnitRunner.class) public class PermissionServiceTest { @Rule public final ExpectedException exception = ExpectedException.none(); @Mock private UserReferenceDataService userReferenceDataService; @Mock private AuthenticationHelper authenticationHelper; @Mock private OrderRepository orderRepository; @InjectMocks private PermissionService permissionService; @Mock private UserDto user; @Mock private RightDto fulfillmentOrdersEditRight; @Mock private RightDto fulfillmentTransferOrderRight; @Mock private RightDto fulfillmentManagePodRight; @Mock private RightDto shipmentsViewRight; @Mock private RightDto shipmentsEditRight; @Mock private RightDto fulfillmentOrdersViewRight; @Mock private RightDto systemSettingsManageRight; private UUID userId = UUID.randomUUID(); private UUID fulfillmentTransferOrderRightId = UUID.randomUUID(); private UUID fulfillmentManagePodRightId = UUID.randomUUID(); private UUID fulfillmentOrdersViewRightId = UUID.randomUUID(); private UUID fulfillmentOrdersEditRightId = UUID.randomUUID(); private UUID shipmentsViewRightId = UUID.randomUUID(); private UUID shipmentsEditRightId = UUID.randomUUID(); private UUID systemSettingsManageRightId = UUID.randomUUID(); private UUID programId = UUID.randomUUID(); private UUID facilityId = UUID.randomUUID(); private Order order; private ProofOfDelivery proofOfDelivery; private SecurityContext securityContext; private OAuth2Authentication userClient; private OAuth2Authentication trustedClient; private OAuth2Authentication apiKeyClient; private ShipmentDto shipmentDto; private Shipment shipment; @Before public void setUp() { securityContext = mock(SecurityContext.class); SecurityContextHolder.setContext(securityContext); trustedClient = new OAuth2AuthenticationDataBuilder().buildServiceAuthentication(); userClient = new OAuth2AuthenticationDataBuilder().buildUserAuthentication(); apiKeyClient = new OAuth2AuthenticationDataBuilder().buildApiKeyAuthentication(); order = createOrder(); proofOfDelivery = new ProofOfDelivery(order); shipment = createShipment(); when(orderRepository.findOne(order.getId())).thenReturn(order); when(user.getId()).thenReturn(userId); mockRight(fulfillmentTransferOrderRight, fulfillmentTransferOrderRightId, ORDERS_TRANSFER); mockRight(fulfillmentManagePodRight, fulfillmentManagePodRightId, PODS_MANAGE); mockRight(fulfillmentOrdersViewRight, fulfillmentOrdersViewRightId, ORDERS_VIEW); mockRight(fulfillmentOrdersEditRight, fulfillmentOrdersEditRightId, ORDERS_EDIT); mockRight(systemSettingsManageRight, systemSettingsManageRightId, SYSTEM_SETTINGS_MANAGE); mockRight(shipmentsEditRight, shipmentsEditRightId, SHIPMENTS_EDIT); mockRight(shipmentsViewRight, shipmentsViewRightId, SHIPMENTS_VIEW); when(authenticationHelper.getCurrentUser()).thenReturn(user); when(securityContext.getAuthentication()).thenReturn(userClient); ReflectionTestUtils.setField(permissionService, "serviceTokenClientId", SERVICE_CLIENT_ID); ReflectionTestUtils.setField(permissionService, "apiKeyPrefix", API_KEY_PREFIX); } @Test public void canTransferOrder() throws Exception { when(securityContext.getAuthentication()).thenReturn(userClient); mockFulfillmentHasRight(fulfillmentTransferOrderRightId, true, facilityId); permissionService.canTransferOrder(order); InOrder order = inOrder(authenticationHelper, userReferenceDataService); verifyFulfillmentRight(order, ORDERS_TRANSFER, fulfillmentTransferOrderRightId, facilityId); } @Test public void cannotTransferOrder() throws Exception { when(securityContext.getAuthentication()).thenReturn(userClient); expectException(ORDERS_TRANSFER); permissionService.canTransferOrder(order); } @Test public void canManageSystemSettingsByServiceToken() { when(securityContext.getAuthentication()).thenReturn(trustedClient); //If endpoint does not allow for service level token authorization, method will throw Exception. permissionService.canManageSystemSettings(); InOrder order = inOrder(authenticationHelper, userReferenceDataService); order.verify(authenticationHelper, never()).getCurrentUser(); order.verify(authenticationHelper, never()).getRight(SYSTEM_SETTINGS_MANAGE); order.verify(userReferenceDataService, never()).hasRight(userId, systemSettingsManageRightId, null, null, null); } @Test public void cannotManageSystemSettingsByApiKeyToken() { when(securityContext.getAuthentication()).thenReturn(apiKeyClient); expectException(SYSTEM_SETTINGS_MANAGE); //If endpoint does not allow for service level token authorization, method will throw Exception. permissionService.canManageSystemSettings(); } @Test public void canManageSystemSettingsByUserToken() { when(securityContext.getAuthentication()).thenReturn(userClient); mockFulfillmentHasRight(systemSettingsManageRightId, true, null); permissionService.canManageSystemSettings(); InOrder order = inOrder(authenticationHelper, userReferenceDataService); verifyFulfillmentRight(order, SYSTEM_SETTINGS_MANAGE, systemSettingsManageRightId, null); } @Test public void cannotManageSystemSettingsByUserToken() throws Exception { when(securityContext.getAuthentication()).thenReturn(userClient); expectException(SYSTEM_SETTINGS_MANAGE); permissionService.canManageSystemSettings(); } @Test public void canManagePod() throws Exception { mockFulfillmentHasRight(fulfillmentManagePodRightId, true, facilityId); when(securityContext.getAuthentication()).thenReturn(userClient); permissionService.canManagePod(proofOfDelivery); InOrder order = inOrder(authenticationHelper, userReferenceDataService); verifyFulfillmentRight(order, PODS_MANAGE, fulfillmentManagePodRightId, facilityId); } @Test public void cannotManagePod() throws Exception { when(securityContext.getAuthentication()).thenReturn(userClient); expectException(PODS_MANAGE); permissionService.canManagePod(proofOfDelivery); } @Test public void canViewOrder() throws Exception { when(securityContext.getAuthentication()).thenReturn(userClient); mockFulfillmentHasRight(fulfillmentOrdersViewRightId, true, facilityId); permissionService.canViewOrder(order); InOrder order = inOrder(authenticationHelper, userReferenceDataService); verifyFulfillmentRight(order, ORDERS_VIEW, fulfillmentOrdersViewRightId, facilityId); } @Test public void cannotViewOrder() throws Exception { when(securityContext.getAuthentication()).thenReturn(userClient); expectException(ORDERS_VIEW); permissionService.canViewOrder(order); } @Test public void canEditOrder() throws Exception { when(securityContext.getAuthentication()).thenReturn(userClient); mockFulfillmentHasRight(fulfillmentOrdersEditRightId, true, facilityId); permissionService.canEditOrder(order); InOrder order = inOrder(authenticationHelper, userReferenceDataService); verifyFulfillmentRight(order, ORDERS_EDIT, fulfillmentOrdersEditRightId, facilityId); } @Test public void cannotEditOrder() throws Exception { when(securityContext.getAuthentication()).thenReturn(userClient); expectException(ORDERS_EDIT); permissionService.canEditOrder(order); } @Test public void canManageShipment() throws Exception { mockFulfillmentHasRight(shipmentsEditRightId, true, facilityId); permissionService.canEditShipment(shipmentDto); InOrder order = inOrder(authenticationHelper, userReferenceDataService); verifyFulfillmentRight(order, SHIPMENTS_EDIT, shipmentsEditRightId, facilityId); } @Test public void cannotManageShipmentWhenUserHasNoRights() throws Exception { expectException(SHIPMENTS_EDIT); permissionService.canEditShipment(shipmentDto); } @Test public void cannotManageShipmentWhenOrderIsNotFound() throws Exception { mockFulfillmentHasRight(fulfillmentOrdersEditRightId, true, facilityId); when(orderRepository.findOne(order.getId())).thenReturn(null); expectException(SHIPMENTS_EDIT); permissionService.canEditShipment(shipmentDto); } @Test public void canViewShipment() throws Exception { mockFulfillmentHasRight(shipmentsViewRightId, true, facilityId); permissionService.canViewShipment(shipment); InOrder order = inOrder(authenticationHelper, userReferenceDataService); verifyFulfillmentRight(order, SHIPMENTS_VIEW, shipmentsViewRightId, facilityId); } @Test public void cannotViewShipmentWhenUserHasNoRights() throws Exception { expectException(SHIPMENTS_VIEW); permissionService.canViewShipment(shipment); } private Order createOrder() { Order order = new Order(); order.setCreatedById(userId); order.setProgramId(programId); order.setSupplyingFacilityId(facilityId); order.setOrderLineItems(Lists.newArrayList()); order.setId(UUID.randomUUID()); return order; } private Shipment createShipment() { shipment = new ShipmentDataBuilder().withOrder(order).build(); shipmentDto = new ShipmentDto(); shipmentDto.setOrder(new ObjectReferenceDto(order.getId())); return shipment; } private void mockRight(RightDto right, UUID rightId, String rightName) { when(authenticationHelper.getRight(rightName)) .thenReturn(right); when(right.getId()).thenReturn(rightId, rightId); } private void mockFulfillmentHasRight(UUID rightId, boolean assign, UUID facility) { ResultDto<Boolean> resultDto = new ResultDto<>(assign); when(userReferenceDataService .hasRight(userId, rightId, null, null, facility) ).thenReturn(resultDto); } private void expectException(String rightName) { exception.expect(MissingPermissionException.class); exception.expect(hasProperty("params", arrayContaining(rightName))); exception.expectMessage(ERROR_PERMISSION_MISSING); } private void verifyFulfillmentRight(InOrder order, String rightName, UUID rightId, UUID facility) { order.verify(authenticationHelper).getCurrentUser(); order.verify(authenticationHelper).getRight(rightName); order.verify(userReferenceDataService).hasRight(userId, rightId, null, null, facility); } }
src/test/java/org/openlmis/fulfillment/service/PermissionServiceTest.java
/* * This program is part of the OpenLMIS logistics management information system platform software. * Copyright © 2017 VillageReach * * This program is free software: you can redistribute it and/or modify it under the terms * of the GNU Affero 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 Affero General Public License for more details. You should have received a copy of * the GNU Affero General Public License along with this program. If not, see * http://www.gnu.org/licenses.  For additional information contact [email protected].  */ package org.openlmis.fulfillment.service; import static org.hamcrest.Matchers.arrayContaining; import static org.hamcrest.Matchers.hasProperty; import static org.mockito.Mockito.inOrder; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.never; import static org.mockito.Mockito.when; import static org.openlmis.fulfillment.i18n.MessageKeys.ERROR_PERMISSION_MISSING; import static org.openlmis.fulfillment.service.PermissionService.ORDERS_EDIT; import static org.openlmis.fulfillment.service.PermissionService.ORDERS_TRANSFER; import static org.openlmis.fulfillment.service.PermissionService.ORDERS_VIEW; import static org.openlmis.fulfillment.service.PermissionService.PODS_MANAGE; import static org.openlmis.fulfillment.service.PermissionService.SHIPMENTS_EDIT; import static org.openlmis.fulfillment.service.PermissionService.SHIPMENTS_VIEW; import static org.openlmis.fulfillment.service.PermissionService.SYSTEM_SETTINGS_MANAGE; import static org.openlmis.fulfillment.testutils.OAuth2AuthenticationDataBuilder.API_KEY_PREFIX; import static org.openlmis.fulfillment.testutils.OAuth2AuthenticationDataBuilder.SERVICE_CLIENT_ID; import com.google.common.collect.Lists; import org.junit.Before; import org.junit.Rule; import org.junit.Test; import org.junit.rules.ExpectedException; import org.junit.runner.RunWith; import org.mockito.InOrder; import org.mockito.InjectMocks; import org.mockito.Mock; import org.mockito.runners.MockitoJUnitRunner; import org.openlmis.fulfillment.domain.Order; import org.openlmis.fulfillment.domain.ProofOfDelivery; import org.openlmis.fulfillment.domain.Shipment; import org.openlmis.fulfillment.repository.OrderRepository; import org.openlmis.fulfillment.service.referencedata.RightDto; import org.openlmis.fulfillment.service.referencedata.UserDto; import org.openlmis.fulfillment.service.referencedata.UserReferenceDataService; import org.openlmis.fulfillment.testutils.OAuth2AuthenticationDataBuilder; import org.openlmis.fulfillment.testutils.ShipmentDataBuilder; import org.openlmis.fulfillment.util.AuthenticationHelper; import org.openlmis.fulfillment.web.MissingPermissionException; import org.openlmis.fulfillment.web.shipment.ShipmentDto; import org.openlmis.fulfillment.web.util.ObjectReferenceDto; import org.springframework.security.core.context.SecurityContext; import org.springframework.security.core.context.SecurityContextHolder; import org.springframework.security.oauth2.provider.OAuth2Authentication; import org.springframework.test.util.ReflectionTestUtils; import java.util.UUID; @SuppressWarnings("PMD.TooManyMethods") @RunWith(MockitoJUnitRunner.class) public class PermissionServiceTest { @Rule public final ExpectedException exception = ExpectedException.none(); @Mock private UserReferenceDataService userReferenceDataService; @Mock private AuthenticationHelper authenticationHelper; @Mock private OrderRepository orderRepository; @InjectMocks private PermissionService permissionService; @Mock private UserDto user; @Mock private RightDto fulfillmentOrdersEditRight; @Mock private RightDto fulfillmentTransferOrderRight; @Mock private RightDto fulfillmentManagePodRight; @Mock private RightDto shipmentsViewRight; @Mock private RightDto shipmentsEditRight; @Mock private RightDto fulfillmentOrdersViewRight; @Mock private RightDto systemSettingsManageRight; private UUID userId = UUID.randomUUID(); private UUID fulfillmentTransferOrderRightId = UUID.randomUUID(); private UUID fulfillmentManagePodRightId = UUID.randomUUID(); private UUID fulfillmentOrdersViewRightId = UUID.randomUUID(); private UUID fulfillmentOrdersEditRightId = UUID.randomUUID(); private UUID shipmentsViewRightId = UUID.randomUUID(); private UUID shipmentsEditRightId = UUID.randomUUID(); private UUID systemSettingsManageRightId = UUID.randomUUID(); private UUID programId = UUID.randomUUID(); private UUID facilityId = UUID.randomUUID(); private Order order = new Order(); private ProofOfDelivery proofOfDelivery; private SecurityContext securityContext; private OAuth2Authentication userClient; private OAuth2Authentication trustedClient; private OAuth2Authentication apiKeyClient; private ShipmentDto shipmentDto; private Shipment shipment; @Before public void setUp() { securityContext = mock(SecurityContext.class); SecurityContextHolder.setContext(securityContext); trustedClient = new OAuth2AuthenticationDataBuilder().buildServiceAuthentication(); userClient = new OAuth2AuthenticationDataBuilder().buildUserAuthentication(); apiKeyClient = new OAuth2AuthenticationDataBuilder().buildApiKeyAuthentication(); order.setCreatedById(userId); order.setProgramId(programId); order.setSupplyingFacilityId(facilityId); order.setOrderLineItems(Lists.newArrayList()); order.setId(UUID.randomUUID()); proofOfDelivery = new ProofOfDelivery(order); shipment = new ShipmentDataBuilder().withOrder(order).build(); shipmentDto = new ShipmentDto(); shipmentDto.setOrder(new ObjectReferenceDto(order.getId())); when(orderRepository.findOne(order.getId())).thenReturn(order); when(user.getId()).thenReturn(userId); when(fulfillmentTransferOrderRight.getId()).thenReturn(fulfillmentTransferOrderRightId); when(fulfillmentManagePodRight.getId()).thenReturn(fulfillmentManagePodRightId); when(fulfillmentOrdersViewRight.getId()).thenReturn(fulfillmentOrdersViewRightId); when(fulfillmentOrdersEditRight.getId()).thenReturn(fulfillmentOrdersEditRightId); when(systemSettingsManageRight.getId()).thenReturn(systemSettingsManageRightId); when(shipmentsEditRight.getId()).thenReturn(shipmentsEditRightId); when(shipmentsViewRight.getId()).thenReturn(shipmentsViewRightId); when(authenticationHelper.getCurrentUser()).thenReturn(user); when(securityContext.getAuthentication()).thenReturn(userClient); when(authenticationHelper.getRight(ORDERS_TRANSFER)) .thenReturn(fulfillmentTransferOrderRight); when(authenticationHelper.getRight(PODS_MANAGE)) .thenReturn(fulfillmentManagePodRight); when(authenticationHelper.getRight(ORDERS_VIEW)) .thenReturn(fulfillmentOrdersViewRight); when(authenticationHelper.getRight(ORDERS_EDIT)) .thenReturn(fulfillmentOrdersEditRight); when(authenticationHelper.getRight(SYSTEM_SETTINGS_MANAGE)) .thenReturn(systemSettingsManageRight); when(authenticationHelper.getRight(SHIPMENTS_VIEW)).thenReturn(shipmentsViewRight); when(authenticationHelper.getRight(SHIPMENTS_EDIT)).thenReturn(shipmentsEditRight); ReflectionTestUtils.setField(permissionService, "serviceTokenClientId", SERVICE_CLIENT_ID); ReflectionTestUtils.setField(permissionService, "apiKeyPrefix", API_KEY_PREFIX); } @Test public void canTransferOrder() throws Exception { when(securityContext.getAuthentication()).thenReturn(userClient); mockFulfillmentHasRight(fulfillmentTransferOrderRightId, true, facilityId); permissionService.canTransferOrder(order); InOrder order = inOrder(authenticationHelper, userReferenceDataService); verifyFulfillmentRight(order, ORDERS_TRANSFER, fulfillmentTransferOrderRightId, facilityId); } @Test public void cannotTransferOrder() throws Exception { when(securityContext.getAuthentication()).thenReturn(userClient); expectException(ORDERS_TRANSFER); permissionService.canTransferOrder(order); } @Test public void canManageSystemSettingsByServiceToken() { when(securityContext.getAuthentication()).thenReturn(trustedClient); //If endpoint does not allow for service level token authorization, method will throw Exception. permissionService.canManageSystemSettings(); InOrder order = inOrder(authenticationHelper, userReferenceDataService); order.verify(authenticationHelper, never()).getCurrentUser(); order.verify(authenticationHelper, never()).getRight(SYSTEM_SETTINGS_MANAGE); order.verify(userReferenceDataService, never()).hasRight(userId, systemSettingsManageRightId, null, null, null); } @Test public void cannotManageSystemSettingsByApiKeyToken() { when(securityContext.getAuthentication()).thenReturn(apiKeyClient); expectException(SYSTEM_SETTINGS_MANAGE); //If endpoint does not allow for service level token authorization, method will throw Exception. permissionService.canManageSystemSettings(); } @Test public void canManageSystemSettingsByUserToken() { when(securityContext.getAuthentication()).thenReturn(userClient); mockFulfillmentHasRight(systemSettingsManageRightId, true, null); permissionService.canManageSystemSettings(); InOrder order = inOrder(authenticationHelper, userReferenceDataService); verifyFulfillmentRight(order, SYSTEM_SETTINGS_MANAGE, systemSettingsManageRightId, null); } @Test public void cannotManageSystemSettingsByUserToken() throws Exception { when(securityContext.getAuthentication()).thenReturn(userClient); expectException(SYSTEM_SETTINGS_MANAGE); permissionService.canManageSystemSettings(); } @Test public void canManagePod() throws Exception { mockFulfillmentHasRight(fulfillmentManagePodRightId, true, facilityId); when(securityContext.getAuthentication()).thenReturn(userClient); permissionService.canManagePod(proofOfDelivery); InOrder order = inOrder(authenticationHelper, userReferenceDataService); verifyFulfillmentRight(order, PODS_MANAGE, fulfillmentManagePodRightId, facilityId); } @Test public void cannotManagePod() throws Exception { when(securityContext.getAuthentication()).thenReturn(userClient); expectException(PODS_MANAGE); permissionService.canManagePod(proofOfDelivery); } @Test public void canViewOrder() throws Exception { when(securityContext.getAuthentication()).thenReturn(userClient); mockFulfillmentHasRight(fulfillmentOrdersViewRightId, true, facilityId); permissionService.canViewOrder(order); InOrder order = inOrder(authenticationHelper, userReferenceDataService); verifyFulfillmentRight(order, ORDERS_VIEW, fulfillmentOrdersViewRightId, facilityId); } @Test public void cannotViewOrder() throws Exception { when(securityContext.getAuthentication()).thenReturn(userClient); expectException(ORDERS_VIEW); permissionService.canViewOrder(order); } @Test public void canEditOrder() throws Exception { when(securityContext.getAuthentication()).thenReturn(userClient); mockFulfillmentHasRight(fulfillmentOrdersEditRightId, true, facilityId); permissionService.canEditOrder(order); InOrder order = inOrder(authenticationHelper, userReferenceDataService); verifyFulfillmentRight(order, ORDERS_EDIT, fulfillmentOrdersEditRightId, facilityId); } @Test public void cannotEditOrder() throws Exception { when(securityContext.getAuthentication()).thenReturn(userClient); expectException(ORDERS_EDIT); permissionService.canEditOrder(order); } @Test public void canManageShipment() throws Exception { mockFulfillmentHasRight(shipmentsEditRightId, true, facilityId); permissionService.canEditShipment(shipmentDto); InOrder order = inOrder(authenticationHelper, userReferenceDataService); verifyFulfillmentRight(order, SHIPMENTS_EDIT, shipmentsEditRightId, facilityId); } @Test public void cannotManageShipmentWhenUserHasNoRights() throws Exception { expectException(SHIPMENTS_EDIT); permissionService.canEditShipment(shipmentDto); } @Test public void cannotManageShipmentWhenOrderIsNotFound() throws Exception { mockFulfillmentHasRight(fulfillmentOrdersEditRightId, true, facilityId); when(orderRepository.findOne(order.getId())).thenReturn(null); expectException(SHIPMENTS_EDIT); permissionService.canEditShipment(shipmentDto); } @Test public void canViewShipment() throws Exception { mockFulfillmentHasRight(shipmentsViewRightId, true, facilityId); permissionService.canViewShipment(shipment); InOrder order = inOrder(authenticationHelper, userReferenceDataService); verifyFulfillmentRight(order, SHIPMENTS_VIEW, shipmentsViewRightId, facilityId); } @Test public void cannotViewShipmentWhenUserHasNoRights() throws Exception { expectException(SHIPMENTS_VIEW); permissionService.canViewShipment(shipment); } private void mockFulfillmentHasRight(UUID rightId, boolean assign, UUID facility) { ResultDto<Boolean> resultDto = new ResultDto<>(assign); when(userReferenceDataService .hasRight(userId, rightId, null, null, facility) ).thenReturn(resultDto); } private void expectException(String rightName) { exception.expect(MissingPermissionException.class); exception.expect(hasProperty("params", arrayContaining(rightName))); exception.expectMessage(ERROR_PERMISSION_MISSING); } private void verifyFulfillmentRight(InOrder order, String rightName, UUID rightId, UUID facility) { order.verify(authenticationHelper).getCurrentUser(); order.verify(authenticationHelper).getRight(rightName); order.verify(userReferenceDataService).hasRight(userId, rightId, null, null, facility); } }
OLMIS-3663: cleanup in permission service test
src/test/java/org/openlmis/fulfillment/service/PermissionServiceTest.java
OLMIS-3663: cleanup in permission service test
<ide><path>rc/test/java/org/openlmis/fulfillment/service/PermissionServiceTest.java <ide> private UUID systemSettingsManageRightId = UUID.randomUUID(); <ide> private UUID programId = UUID.randomUUID(); <ide> private UUID facilityId = UUID.randomUUID(); <del> private Order order = new Order(); <add> private Order order; <ide> private ProofOfDelivery proofOfDelivery; <ide> private SecurityContext securityContext; <ide> private OAuth2Authentication userClient; <ide> <ide> @Before <ide> public void setUp() { <del> <ide> securityContext = mock(SecurityContext.class); <ide> SecurityContextHolder.setContext(securityContext); <ide> <ide> userClient = new OAuth2AuthenticationDataBuilder().buildUserAuthentication(); <ide> apiKeyClient = new OAuth2AuthenticationDataBuilder().buildApiKeyAuthentication(); <ide> <add> order = createOrder(); <add> proofOfDelivery = new ProofOfDelivery(order); <add> shipment = createShipment(); <add> <add> when(orderRepository.findOne(order.getId())).thenReturn(order); <add> when(user.getId()).thenReturn(userId); <add> <add> mockRight(fulfillmentTransferOrderRight, fulfillmentTransferOrderRightId, ORDERS_TRANSFER); <add> mockRight(fulfillmentManagePodRight, fulfillmentManagePodRightId, PODS_MANAGE); <add> mockRight(fulfillmentOrdersViewRight, fulfillmentOrdersViewRightId, ORDERS_VIEW); <add> mockRight(fulfillmentOrdersEditRight, fulfillmentOrdersEditRightId, ORDERS_EDIT); <add> mockRight(systemSettingsManageRight, systemSettingsManageRightId, SYSTEM_SETTINGS_MANAGE); <add> mockRight(shipmentsEditRight, shipmentsEditRightId, SHIPMENTS_EDIT); <add> mockRight(shipmentsViewRight, shipmentsViewRightId, SHIPMENTS_VIEW); <add> <add> when(authenticationHelper.getCurrentUser()).thenReturn(user); <add> when(securityContext.getAuthentication()).thenReturn(userClient); <add> <add> ReflectionTestUtils.setField(permissionService, "serviceTokenClientId", SERVICE_CLIENT_ID); <add> ReflectionTestUtils.setField(permissionService, "apiKeyPrefix", API_KEY_PREFIX); <add> } <add> <add> @Test <add> public void canTransferOrder() throws Exception { <add> when(securityContext.getAuthentication()).thenReturn(userClient); <add> <add> mockFulfillmentHasRight(fulfillmentTransferOrderRightId, true, facilityId); <add> <add> permissionService.canTransferOrder(order); <add> <add> InOrder order = inOrder(authenticationHelper, userReferenceDataService); <add> verifyFulfillmentRight(order, ORDERS_TRANSFER, fulfillmentTransferOrderRightId, facilityId); <add> } <add> <add> @Test <add> public void cannotTransferOrder() throws Exception { <add> when(securityContext.getAuthentication()).thenReturn(userClient); <add> expectException(ORDERS_TRANSFER); <add> <add> permissionService.canTransferOrder(order); <add> } <add> <add> @Test <add> public void canManageSystemSettingsByServiceToken() { <add> when(securityContext.getAuthentication()).thenReturn(trustedClient); <add> //If endpoint does not allow for service level token authorization, method will throw Exception. <add> permissionService.canManageSystemSettings(); <add> <add> InOrder order = inOrder(authenticationHelper, userReferenceDataService); <add> <add> order.verify(authenticationHelper, never()).getCurrentUser(); <add> order.verify(authenticationHelper, never()).getRight(SYSTEM_SETTINGS_MANAGE); <add> order.verify(userReferenceDataService, never()).hasRight(userId, systemSettingsManageRightId, <add> null, null, null); <add> } <add> <add> @Test <add> public void cannotManageSystemSettingsByApiKeyToken() { <add> when(securityContext.getAuthentication()).thenReturn(apiKeyClient); <add> expectException(SYSTEM_SETTINGS_MANAGE); <add> <add> //If endpoint does not allow for service level token authorization, method will throw Exception. <add> permissionService.canManageSystemSettings(); <add> } <add> <add> @Test <add> public void canManageSystemSettingsByUserToken() { <add> when(securityContext.getAuthentication()).thenReturn(userClient); <add> <add> mockFulfillmentHasRight(systemSettingsManageRightId, true, null); <add> <add> permissionService.canManageSystemSettings(); <add> <add> InOrder order = inOrder(authenticationHelper, userReferenceDataService); <add> verifyFulfillmentRight(order, SYSTEM_SETTINGS_MANAGE, systemSettingsManageRightId, null); <add> } <add> <add> @Test <add> public void cannotManageSystemSettingsByUserToken() throws Exception { <add> when(securityContext.getAuthentication()).thenReturn(userClient); <add> expectException(SYSTEM_SETTINGS_MANAGE); <add> <add> permissionService.canManageSystemSettings(); <add> } <add> <add> @Test <add> public void canManagePod() throws Exception { <add> mockFulfillmentHasRight(fulfillmentManagePodRightId, true, facilityId); <add> when(securityContext.getAuthentication()).thenReturn(userClient); <add> <add> <add> permissionService.canManagePod(proofOfDelivery); <add> <add> InOrder order = inOrder(authenticationHelper, userReferenceDataService); <add> verifyFulfillmentRight(order, PODS_MANAGE, fulfillmentManagePodRightId, facilityId); <add> } <add> <add> @Test <add> public void cannotManagePod() throws Exception { <add> when(securityContext.getAuthentication()).thenReturn(userClient); <add> <add> expectException(PODS_MANAGE); <add> <add> permissionService.canManagePod(proofOfDelivery); <add> } <add> <add> @Test <add> public void canViewOrder() throws Exception { <add> when(securityContext.getAuthentication()).thenReturn(userClient); <add> <add> mockFulfillmentHasRight(fulfillmentOrdersViewRightId, true, facilityId); <add> <add> permissionService.canViewOrder(order); <add> <add> InOrder order = inOrder(authenticationHelper, userReferenceDataService); <add> verifyFulfillmentRight(order, ORDERS_VIEW, fulfillmentOrdersViewRightId, facilityId); <add> } <add> <add> @Test <add> public void cannotViewOrder() throws Exception { <add> when(securityContext.getAuthentication()).thenReturn(userClient); <add> <add> expectException(ORDERS_VIEW); <add> <add> permissionService.canViewOrder(order); <add> } <add> <add> @Test <add> public void canEditOrder() throws Exception { <add> when(securityContext.getAuthentication()).thenReturn(userClient); <add> <add> mockFulfillmentHasRight(fulfillmentOrdersEditRightId, true, facilityId); <add> <add> permissionService.canEditOrder(order); <add> <add> InOrder order = inOrder(authenticationHelper, userReferenceDataService); <add> verifyFulfillmentRight(order, ORDERS_EDIT, fulfillmentOrdersEditRightId, facilityId); <add> } <add> <add> @Test <add> public void cannotEditOrder() throws Exception { <add> when(securityContext.getAuthentication()).thenReturn(userClient); <add> <add> expectException(ORDERS_EDIT); <add> <add> permissionService.canEditOrder(order); <add> } <add> <add> @Test <add> public void canManageShipment() throws Exception { <add> mockFulfillmentHasRight(shipmentsEditRightId, true, facilityId); <add> <add> permissionService.canEditShipment(shipmentDto); <add> <add> InOrder order = inOrder(authenticationHelper, userReferenceDataService); <add> verifyFulfillmentRight(order, SHIPMENTS_EDIT, shipmentsEditRightId, facilityId); <add> } <add> <add> @Test <add> public void cannotManageShipmentWhenUserHasNoRights() throws Exception { <add> expectException(SHIPMENTS_EDIT); <add> <add> permissionService.canEditShipment(shipmentDto); <add> } <add> <add> @Test <add> public void cannotManageShipmentWhenOrderIsNotFound() throws Exception { <add> mockFulfillmentHasRight(fulfillmentOrdersEditRightId, true, facilityId); <add> when(orderRepository.findOne(order.getId())).thenReturn(null); <add> expectException(SHIPMENTS_EDIT); <add> <add> permissionService.canEditShipment(shipmentDto); <add> } <add> <add> @Test <add> public void canViewShipment() throws Exception { <add> mockFulfillmentHasRight(shipmentsViewRightId, true, facilityId); <add> <add> permissionService.canViewShipment(shipment); <add> <add> InOrder order = inOrder(authenticationHelper, userReferenceDataService); <add> verifyFulfillmentRight(order, SHIPMENTS_VIEW, shipmentsViewRightId, facilityId); <add> } <add> <add> @Test <add> public void cannotViewShipmentWhenUserHasNoRights() throws Exception { <add> expectException(SHIPMENTS_VIEW); <add> <add> permissionService.canViewShipment(shipment); <add> } <add> <add> private Order createOrder() { <add> Order order = new Order(); <ide> order.setCreatedById(userId); <ide> order.setProgramId(programId); <ide> order.setSupplyingFacilityId(facilityId); <ide> order.setOrderLineItems(Lists.newArrayList()); <ide> order.setId(UUID.randomUUID()); <del> <del> proofOfDelivery = new ProofOfDelivery(order); <del> <add> return order; <add> } <add> <add> private Shipment createShipment() { <ide> shipment = new ShipmentDataBuilder().withOrder(order).build(); <ide> shipmentDto = new ShipmentDto(); <ide> shipmentDto.setOrder(new ObjectReferenceDto(order.getId())); <del> <del> when(orderRepository.findOne(order.getId())).thenReturn(order); <del> <del> when(user.getId()).thenReturn(userId); <del> <del> when(fulfillmentTransferOrderRight.getId()).thenReturn(fulfillmentTransferOrderRightId); <del> when(fulfillmentManagePodRight.getId()).thenReturn(fulfillmentManagePodRightId); <del> when(fulfillmentOrdersViewRight.getId()).thenReturn(fulfillmentOrdersViewRightId); <del> when(fulfillmentOrdersEditRight.getId()).thenReturn(fulfillmentOrdersEditRightId); <del> when(systemSettingsManageRight.getId()).thenReturn(systemSettingsManageRightId); <del> when(shipmentsEditRight.getId()).thenReturn(shipmentsEditRightId); <del> when(shipmentsViewRight.getId()).thenReturn(shipmentsViewRightId); <del> <del> when(authenticationHelper.getCurrentUser()).thenReturn(user); <del> when(securityContext.getAuthentication()).thenReturn(userClient); <del> <del> when(authenticationHelper.getRight(ORDERS_TRANSFER)) <del> .thenReturn(fulfillmentTransferOrderRight); <del> when(authenticationHelper.getRight(PODS_MANAGE)) <del> .thenReturn(fulfillmentManagePodRight); <del> when(authenticationHelper.getRight(ORDERS_VIEW)) <del> .thenReturn(fulfillmentOrdersViewRight); <del> when(authenticationHelper.getRight(ORDERS_EDIT)) <del> .thenReturn(fulfillmentOrdersEditRight); <del> when(authenticationHelper.getRight(SYSTEM_SETTINGS_MANAGE)) <del> .thenReturn(systemSettingsManageRight); <del> when(authenticationHelper.getRight(SHIPMENTS_VIEW)).thenReturn(shipmentsViewRight); <del> when(authenticationHelper.getRight(SHIPMENTS_EDIT)).thenReturn(shipmentsEditRight); <del> <del> ReflectionTestUtils.setField(permissionService, "serviceTokenClientId", SERVICE_CLIENT_ID); <del> ReflectionTestUtils.setField(permissionService, "apiKeyPrefix", API_KEY_PREFIX); <del> } <del> <del> @Test <del> public void canTransferOrder() throws Exception { <del> when(securityContext.getAuthentication()).thenReturn(userClient); <del> <del> mockFulfillmentHasRight(fulfillmentTransferOrderRightId, true, facilityId); <del> <del> permissionService.canTransferOrder(order); <del> <del> InOrder order = inOrder(authenticationHelper, userReferenceDataService); <del> verifyFulfillmentRight(order, ORDERS_TRANSFER, fulfillmentTransferOrderRightId, facilityId); <del> } <del> <del> @Test <del> public void cannotTransferOrder() throws Exception { <del> when(securityContext.getAuthentication()).thenReturn(userClient); <del> expectException(ORDERS_TRANSFER); <del> <del> permissionService.canTransferOrder(order); <del> } <del> <del> @Test <del> public void canManageSystemSettingsByServiceToken() { <del> when(securityContext.getAuthentication()).thenReturn(trustedClient); <del> //If endpoint does not allow for service level token authorization, method will throw Exception. <del> permissionService.canManageSystemSettings(); <del> <del> InOrder order = inOrder(authenticationHelper, userReferenceDataService); <del> <del> order.verify(authenticationHelper, never()).getCurrentUser(); <del> order.verify(authenticationHelper, never()).getRight(SYSTEM_SETTINGS_MANAGE); <del> order.verify(userReferenceDataService, never()).hasRight(userId, systemSettingsManageRightId, <del> null, null, null); <del> } <del> <del> @Test <del> public void cannotManageSystemSettingsByApiKeyToken() { <del> when(securityContext.getAuthentication()).thenReturn(apiKeyClient); <del> expectException(SYSTEM_SETTINGS_MANAGE); <del> <del> //If endpoint does not allow for service level token authorization, method will throw Exception. <del> permissionService.canManageSystemSettings(); <del> } <del> <del> @Test <del> public void canManageSystemSettingsByUserToken() { <del> when(securityContext.getAuthentication()).thenReturn(userClient); <del> <del> mockFulfillmentHasRight(systemSettingsManageRightId, true, null); <del> <del> permissionService.canManageSystemSettings(); <del> <del> InOrder order = inOrder(authenticationHelper, userReferenceDataService); <del> verifyFulfillmentRight(order, SYSTEM_SETTINGS_MANAGE, systemSettingsManageRightId, null); <del> } <del> <del> @Test <del> public void cannotManageSystemSettingsByUserToken() throws Exception { <del> when(securityContext.getAuthentication()).thenReturn(userClient); <del> expectException(SYSTEM_SETTINGS_MANAGE); <del> <del> permissionService.canManageSystemSettings(); <del> } <del> <del> @Test <del> public void canManagePod() throws Exception { <del> mockFulfillmentHasRight(fulfillmentManagePodRightId, true, facilityId); <del> when(securityContext.getAuthentication()).thenReturn(userClient); <del> <del> <del> permissionService.canManagePod(proofOfDelivery); <del> <del> InOrder order = inOrder(authenticationHelper, userReferenceDataService); <del> verifyFulfillmentRight(order, PODS_MANAGE, fulfillmentManagePodRightId, facilityId); <del> } <del> <del> @Test <del> public void cannotManagePod() throws Exception { <del> when(securityContext.getAuthentication()).thenReturn(userClient); <del> <del> expectException(PODS_MANAGE); <del> <del> permissionService.canManagePod(proofOfDelivery); <del> } <del> <del> @Test <del> public void canViewOrder() throws Exception { <del> when(securityContext.getAuthentication()).thenReturn(userClient); <del> <del> mockFulfillmentHasRight(fulfillmentOrdersViewRightId, true, facilityId); <del> <del> permissionService.canViewOrder(order); <del> <del> InOrder order = inOrder(authenticationHelper, userReferenceDataService); <del> verifyFulfillmentRight(order, ORDERS_VIEW, fulfillmentOrdersViewRightId, facilityId); <del> } <del> <del> @Test <del> public void cannotViewOrder() throws Exception { <del> when(securityContext.getAuthentication()).thenReturn(userClient); <del> <del> expectException(ORDERS_VIEW); <del> <del> permissionService.canViewOrder(order); <del> } <del> <del> @Test <del> public void canEditOrder() throws Exception { <del> when(securityContext.getAuthentication()).thenReturn(userClient); <del> <del> mockFulfillmentHasRight(fulfillmentOrdersEditRightId, true, facilityId); <del> <del> permissionService.canEditOrder(order); <del> <del> InOrder order = inOrder(authenticationHelper, userReferenceDataService); <del> verifyFulfillmentRight(order, ORDERS_EDIT, fulfillmentOrdersEditRightId, facilityId); <del> } <del> <del> @Test <del> public void cannotEditOrder() throws Exception { <del> when(securityContext.getAuthentication()).thenReturn(userClient); <del> <del> expectException(ORDERS_EDIT); <del> <del> permissionService.canEditOrder(order); <del> } <del> <del> @Test <del> public void canManageShipment() throws Exception { <del> mockFulfillmentHasRight(shipmentsEditRightId, true, facilityId); <del> <del> permissionService.canEditShipment(shipmentDto); <del> <del> InOrder order = inOrder(authenticationHelper, userReferenceDataService); <del> verifyFulfillmentRight(order, SHIPMENTS_EDIT, shipmentsEditRightId, facilityId); <del> } <del> <del> @Test <del> public void cannotManageShipmentWhenUserHasNoRights() throws Exception { <del> expectException(SHIPMENTS_EDIT); <del> <del> permissionService.canEditShipment(shipmentDto); <del> } <del> <del> @Test <del> public void cannotManageShipmentWhenOrderIsNotFound() throws Exception { <del> mockFulfillmentHasRight(fulfillmentOrdersEditRightId, true, facilityId); <del> when(orderRepository.findOne(order.getId())).thenReturn(null); <del> expectException(SHIPMENTS_EDIT); <del> <del> permissionService.canEditShipment(shipmentDto); <del> } <del> <del> @Test <del> public void canViewShipment() throws Exception { <del> mockFulfillmentHasRight(shipmentsViewRightId, true, facilityId); <del> <del> permissionService.canViewShipment(shipment); <del> <del> InOrder order = inOrder(authenticationHelper, userReferenceDataService); <del> verifyFulfillmentRight(order, SHIPMENTS_VIEW, shipmentsViewRightId, facilityId); <del> } <del> <del> @Test <del> public void cannotViewShipmentWhenUserHasNoRights() throws Exception { <del> expectException(SHIPMENTS_VIEW); <del> <del> permissionService.canViewShipment(shipment); <add> return shipment; <add> } <add> <add> private void mockRight(RightDto right, UUID rightId, String rightName) { <add> when(authenticationHelper.getRight(rightName)) <add> .thenReturn(right); <add> when(right.getId()).thenReturn(rightId, rightId); <ide> } <ide> <ide> private void mockFulfillmentHasRight(UUID rightId, boolean assign, UUID facility) {
JavaScript
mit
8dea5533d1627cdef434f0ed3f539f4cb6b300fc
0
maxbeier/pretty-print,maxbeier/pretty-print
const bodyParser = require('body-parser'); const compress = require('compression'); const execFile = require('child_process').execFile; const express = require('express'); const fs = require('fs'); const MercuryClient = require('mercury-client'); const path = require('path'); const sha256 = require('sha256'); const stream = require('stream'); const striptags = require('striptags'); require('dotenv').config(); const app = express(); app.use(compress()); app.use(bodyParser.text()); app.use(express.static(path.resolve('static'))); app.set('views', path.resolve('templates')); app.set('view engine', 'pug'); app.listen(process.env.PORT || 3000); app.get('/', (req, res) => { loadArticle(req.query.url) .then(article => res.render('index', article)) .catch(error => res.render('index', { error })); }); app.post('/', (req, res) => { const content = req.body; const hash = sha256(content); const file = `articles/${hash}.pdf`; const success = () => res.location(file).status(201).send(); fs.exists(`static/${file}`, (exists) => { if (exists) return success(); return generatePDF(content, hash) .then(success) .catch(err => res.status(500).send(err)); }); }); function loadArticle(url) { if (!url) return Promise.resolve(null); return new MercuryClient(process.env.MERCURY_KEY).parse(url) .then(article => pandoc(['--from=html', '--to=markdown', '--no-wrap'], article.content) .then((markdown) => { article.markdown = clean(markdown); return article; })); } function generatePDF(content, filename) { const folder = path.resolve('static/articles'); const remove = () => fs.unlink(`${folder}/${filename}.pdf`, console.log); const params = [ `--output=${filename}.pdf`, `--template=${path.resolve('templates/article.tex')}`, '--from=markdown', '--latex-engine=xelatex', '--variable', 'fontsize=10pt', '--variable', 'geometry:a4paper, landscape, twocolumn, columnsep=2cm, top=2cm, bottom=2cm, left=2cm, right=2cm', ]; return pandoc(params, content, folder) .then(() => setTimeout(remove, 15 * 60 * 1000)); // remove after 15 minutes; } function pandoc(params, input, cwd) { return new Promise((resolve, reject) => { const child = execFile('pandoc', params, { cwd }, (err, stdout, stderr) => { if (err || stderr) return reject(err || stderr); return resolve(stdout); }); const stdinStream = new stream.Readable(); stdinStream.push(input); stdinStream.push(null); // EOF stdinStream.pipe(child.stdin); }); } function clean(content) { return striptags(content) // remove html tags .replace(/\\\n/g, '\n') // remove trailing slashes .replace(/(\n\s*?\n)\s*\n/g, '$1') // reduce multiple line breaks but preserve whitespace .trim(); // remove surrounding whitespace }
index.js
const bodyParser = require('body-parser'); const compress = require('compression'); const execFile = require('child_process').execFile; const express = require('express'); const fs = require('fs'); const MercuryClient = require('mercury-client'); const path = require('path'); const sha256 = require('sha256'); const stream = require('stream'); const striptags = require('striptags'); require('dotenv').config(); const app = express(); app.use(compress()); app.use(bodyParser.text()); app.use(express.static(path.resolve('static'))); app.set('views', path.resolve('templates')); app.set('view engine', 'pug'); app.listen(process.env.PORT || 3000); app.get('/', (req, res) => { loadArticle(req.query.url) .then(article => res.render('index', article)) .catch(error => res.render('index', { error })); }); app.post('/', (req, res) => { const content = req.body; const hash = sha256(content); const file = `articles/${hash}.pdf`; const success = () => res.location(file).status(201).send(); fs.exists(`static/${file}`, (exists) => { if (exists) return success(); return generatePDF(content, hash) .then(success) .catch(err => res.status(500).send(err)); }); }); function loadArticle(url) { if (!url) return Promise.resolve(null); return new MercuryClient(process.env.MERCURY_KEY).parse(url) .then(article => pandoc(['--from=html', '--to=markdown', '--no-wrap'], article.content) .then((markdown) => { article.markdown = clean(markdown); return article; })); } function generatePDF(content, filename) { const folder = path.resolve('static/articles'); const remove = () => fs.unlinkSync(`${folder}/${filename}.pdf`); const params = [ `--output=${filename}.pdf`, `--template=${path.resolve('templates/article.tex')}`, '--from=markdown', '--latex-engine=xelatex', '--variable', 'fontsize=10pt', '--variable', 'geometry:a4paper, landscape, twocolumn, columnsep=2cm, top=2cm, bottom=2cm, left=2cm, right=2cm', ]; return pandoc(params, content, folder) .then(() => setTimeout(remove, 15 * 60 * 1000)); // remove after 15 minutes; } function pandoc(params, input, cwd) { return new Promise((resolve, reject) => { const child = execFile('pandoc', params, { cwd }, (err, stdout, stderr) => { if (err || stderr) return reject(err || stderr); return resolve(stdout); }); const stdinStream = new stream.Readable(); stdinStream.push(input); stdinStream.push(null); // EOF stdinStream.pipe(child.stdin); }); } function clean(content) { return striptags(content) // remove html tags .replace(/\\\n/g, '\n') // remove trailing slashes .replace(/(\n\s*?\n)\s*\n/g, '$1') // reduce multiple line breaks but preserve whitespace .trim(); // remove surrounding whitespace }
don’t crash if file can’t be deleted
index.js
don’t crash if file can’t be deleted
<ide><path>ndex.js <ide> <ide> function generatePDF(content, filename) { <ide> const folder = path.resolve('static/articles'); <del> const remove = () => fs.unlinkSync(`${folder}/${filename}.pdf`); <add> const remove = () => fs.unlink(`${folder}/${filename}.pdf`, console.log); <ide> const params = [ <ide> `--output=${filename}.pdf`, <ide> `--template=${path.resolve('templates/article.tex')}`,
Java
bsd-3-clause
8ba52d0edeb0952fdec89ebb66b6474d24fb25c0
0
frc-4931/2015-Robot,Zabot/2015-Robot
/* * FRC 4931 (http://www.evilletech.com) * * Open source software. Licensed under the FIRST BSD license file in the * root directory of this project's Git repository. */ /* * FRC 4931 (http://www.evilletech.com) * * Open source software. Licensed under the FIRST BSD license file in the * root directory of this project's Git repository. */ /* * FRC 4931 (http://www.evilletech.com) * * Open source software. Licensed under the FIRST BSD license file in the * root directory of this project's Git repository. */ package org.frc4931.robot.component; import org.frc4931.utils.Operations; public final class LeadScrew { public enum Position { UNKNOWN, LOW, SHELF, TOTE, TOTE_ON_SHELF } public enum Direction { STOPPED, DOWN, UP } private final Motor motor; private final Switch low; private final Switch shelf; private final Switch tote; private final Switch toteOnShelf; private Position lastPosition; private Direction lastDirection; public LeadScrew(Motor motor, Switch low, Switch shelf, Switch tote, Switch toteOnShelf) { this.motor = motor; this.low = low; this.shelf = shelf; this.tote = tote; this.toteOnShelf = toteOnShelf; lastPosition = Position.UNKNOWN; lastDirection = getDirection(); } private void moveDown(double speed) { motor.setSpeed(-Math.abs(speed)); } private void moveUp(double speed) { motor.setSpeed(Math.abs(speed)); } private void updateLast() { Position newPosition = getPosition(); if (newPosition != Position.UNKNOWN && newPosition != lastPosition) { lastPosition = getPosition(); lastDirection = getDirection(); } } public boolean isLow() { return low.isTriggered(); } public boolean isAtShelf() { return shelf.isTriggered(); } public boolean isAtTote() { return tote.isTriggered(); } public boolean isAtToteOnShelf() { return toteOnShelf.isTriggered(); } public void moveTowardsLow(double speed) { if (isLow()) { motor.stop(); } else { moveDown(speed); } updateLast(); } public void moveTowardsShelf(double speed) { if (isAtShelf()) { motor.stop(); } else { switch (lastPosition) { case LOW: moveUp(speed); break; case SHELF: if (lastDirection == Direction.DOWN) { moveUp(speed); } else if (lastDirection == Direction.UP) { moveDown(speed); } break; case TOTE: case TOTE_ON_SHELF: moveDown(speed); break; } } updateLast(); } public void moveTowardsTote(double speed) { if (isAtTote()) { motor.stop(); } else { switch (lastPosition) { case LOW: case SHELF: moveUp(speed); break; case TOTE: if (lastDirection == Direction.DOWN) { moveUp(speed); } else if (lastDirection == Direction.UP) { moveDown(speed); } break; case TOTE_ON_SHELF: moveDown(speed); break; } } updateLast(); } public void moveTowardsToteOnShelf(double speed) { if (isAtToteOnShelf()) { motor.stop(); } else { moveUp(speed); } updateLast(); } public Position getPosition() { if (isLow() && !isAtShelf() && !isAtTote() && !isAtToteOnShelf()) { return Position.LOW; } else if (!isLow() && isAtShelf() && !isAtTote() && !isAtToteOnShelf()) { return Position.SHELF; } else if (!isLow() && !isAtShelf() && isAtTote() && !isAtToteOnShelf()) { return Position.TOTE; } else if (!isLow() && !isAtShelf() && !isAtTote() && isAtToteOnShelf()) { return Position.TOTE_ON_SHELF; } else { return Position.UNKNOWN; } } public Direction getDirection() { switch (Operations.fuzzyCompare(motor.getSpeed(), 0)) { case -1: return Direction.DOWN; case 0: return Direction.STOPPED; case 1: return Direction.UP; default: return null; } } public Position getLastPosition() { return lastPosition; } public Direction getLastDirection() { return lastDirection; } }
RobotFramework/src/org/frc4931/robot/component/LeadScrew.java
/* * FRC 4931 (http://www.evilletech.com) * * Open source software. Licensed under the FIRST BSD license file in the * root directory of this project's Git repository. */ /* * FRC 4931 (http://www.evilletech.com) * * Open source software. Licensed under the FIRST BSD license file in the * root directory of this project's Git repository. */ package org.frc4931.robot.component; import org.frc4931.utils.Operations; public final class LeadScrew { public enum Position { UNKNOWN, LOW, SHELF, TOTE, TOTE_ON_SHELF } public enum Direction { STILL, DOWN, UP } private final Motor motor; private final Switch low; private final Switch shelf; private final Switch tote; private final Switch toteOnShelf; private Position lastPosition; private int lastDirection; public LeadScrew(Motor motor, Switch low, Switch shelf, Switch tote, Switch toteOnShelf) { this.motor = motor; this.low = low; this.shelf = shelf; this.tote = tote; this.toteOnShelf = toteOnShelf; lastPosition = Position.UNKNOWN; lastDirection = getDirection(); } private void moveDown(double speed) { motor.setSpeed(-Math.abs(speed)); } private void moveUp(double speed) { motor.setSpeed(Math.abs(speed)); } private int getDirection() { return Operations.fuzzyCompare(motor.getSpeed(), 0); } private void updateLast() { if (isLow()) { lastPosition = Position.LOW; lastDirection = getDirection(); } else if (isAtShelf()) { lastPosition = Position.SHELF; lastDirection = getDirection(); } else if (isAtTote()) { lastPosition = Position.TOTE; lastDirection = getDirection(); } else if (isAtToteOnShelf()) { lastPosition = Position.TOTE_ON_SHELF; lastDirection = getDirection(); } } public boolean isLow() { return low.isTriggered(); } public boolean isAtShelf() { return shelf.isTriggered(); } public boolean isAtTote() { return tote.isTriggered(); } public boolean isAtToteOnShelf() { return toteOnShelf.isTriggered(); } public void moveTowardsLow(double speed) { if (isLow()) { motor.stop(); } else { moveDown(speed); } updateLast(); } public void moveTowardsShelf(double speed) { if (isAtShelf()) { motor.stop(); } else { switch (lastPosition) { case LOW: moveUp(speed); break; case SHELF: if (lastDirection < 0) { moveUp(speed); } else if (lastDirection > 0) { moveDown(speed); } break; case TOTE: case TOTE_ON_SHELF: moveDown(speed); break; } } updateLast(); } public void moveTowardsTote(double speed) { if (isAtTote()) { motor.stop(); } else { switch (lastPosition) { case LOW: case SHELF: moveUp(speed); break; case TOTE: if (lastDirection < 0) { moveUp(speed); } else if (lastDirection > 0) { moveDown(speed); } break; case TOTE_ON_SHELF: moveDown(speed); break; } } updateLast(); } public void moveTowardsToteOnShelf(double speed) { if (isAtToteOnShelf()) { motor.stop(); } else { moveUp(speed); } updateLast(); } }
LeadScrew fixes
RobotFramework/src/org/frc4931/robot/component/LeadScrew.java
LeadScrew fixes
<ide><path>obotFramework/src/org/frc4931/robot/component/LeadScrew.java <add>/* <add> * FRC 4931 (http://www.evilletech.com) <add> * <add> * Open source software. Licensed under the FIRST BSD license file in the <add> * root directory of this project's Git repository. <add> */ <add> <ide> /* <ide> * FRC 4931 (http://www.evilletech.com) <ide> * <ide> } <ide> <ide> public enum Direction { <del> STILL, DOWN, UP <add> STOPPED, DOWN, UP <ide> } <ide> <ide> private final Motor motor; <ide> private final Switch tote; <ide> private final Switch toteOnShelf; <ide> private Position lastPosition; <del> private int lastDirection; <add> private Direction lastDirection; <ide> <ide> public LeadScrew(Motor motor, Switch low, Switch shelf, Switch tote, Switch toteOnShelf) { <ide> this.motor = motor; <ide> motor.setSpeed(Math.abs(speed)); <ide> } <ide> <del> private int getDirection() { <del> return Operations.fuzzyCompare(motor.getSpeed(), 0); <del> } <del> <ide> private void updateLast() { <del> if (isLow()) { <del> lastPosition = Position.LOW; <del> lastDirection = getDirection(); <del> } else if (isAtShelf()) { <del> lastPosition = Position.SHELF; <del> lastDirection = getDirection(); <del> } else if (isAtTote()) { <del> lastPosition = Position.TOTE; <del> lastDirection = getDirection(); <del> } else if (isAtToteOnShelf()) { <del> lastPosition = Position.TOTE_ON_SHELF; <add> Position newPosition = getPosition(); <add> if (newPosition != Position.UNKNOWN && newPosition != lastPosition) { <add> lastPosition = getPosition(); <ide> lastDirection = getDirection(); <ide> } <ide> } <ide> moveUp(speed); <ide> break; <ide> case SHELF: <del> if (lastDirection < 0) { <add> if (lastDirection == Direction.DOWN) { <ide> moveUp(speed); <del> } else if (lastDirection > 0) { <add> } else if (lastDirection == Direction.UP) { <ide> moveDown(speed); <ide> } <ide> break; <ide> moveUp(speed); <ide> break; <ide> case TOTE: <del> if (lastDirection < 0) { <add> if (lastDirection == Direction.DOWN) { <ide> moveUp(speed); <del> } else if (lastDirection > 0) { <add> } else if (lastDirection == Direction.UP) { <ide> moveDown(speed); <ide> } <ide> break; <ide> } <ide> updateLast(); <ide> } <add> <add> public Position getPosition() { <add> if (isLow() && !isAtShelf() && !isAtTote() && !isAtToteOnShelf()) { <add> return Position.LOW; <add> } else if (!isLow() && isAtShelf() && !isAtTote() && !isAtToteOnShelf()) { <add> return Position.SHELF; <add> } else if (!isLow() && !isAtShelf() && isAtTote() && !isAtToteOnShelf()) { <add> return Position.TOTE; <add> } else if (!isLow() && !isAtShelf() && !isAtTote() && isAtToteOnShelf()) { <add> return Position.TOTE_ON_SHELF; <add> } else { <add> return Position.UNKNOWN; <add> } <add> } <add> <add> public Direction getDirection() { <add> switch (Operations.fuzzyCompare(motor.getSpeed(), 0)) { <add> case -1: <add> return Direction.DOWN; <add> case 0: <add> return Direction.STOPPED; <add> case 1: <add> return Direction.UP; <add> default: <add> return null; <add> } <add> } <add> <add> public Position getLastPosition() { <add> return lastPosition; <add> } <add> <add> public Direction getLastDirection() { <add> return lastDirection; <add> } <ide> }