repo_name
stringlengths
7
104
file_path
stringlengths
13
198
context
stringlengths
67
7.15k
import_statement
stringlengths
16
4.43k
code
stringlengths
40
6.98k
prompt
stringlengths
227
8.27k
next_line
stringlengths
8
795
abel533/DBMetadata
DBMetadata-swing/src/main/java/com/github/abel533/view/panel/ChoosePanel.java
// Path: DBMetadata-swing/src/main/java/com/github/abel533/Code.java // public class Code { // public static Font TEXT_MSG = new Font("Monospaced", Font.PLAIN, 10); // public static Font TEXT_FONT = new Font(I18n.key("tools.text.font"), Font.PLAIN, 14); // public static Font TEXT_TABLE = new Font(I18n.key("tools.text.font"), Font.PLAIN, 12); // public static Font TEXT_BUTTON = new Font(I18n.key("tools.text.font"), Font.BOLD, 14); // } // // Path: DBMetadata-swing/src/main/java/com/github/abel533/utils/I18n.java // public class I18n { // private static final String SUFFIX = ".properties"; // private static ResourceBundle[] resourceBundles; // private static Set<String> baseNameList; // // static { // init(null); // } // // private static void initBaseNameList() { // File[] files = new File(Path.LANGUAGE).listFiles(new FilenameFilter() { // @Override // public boolean accept(File dir, String name) { // if (name.endsWith(SUFFIX)) { // return true; // } // return false; // } // }); // baseNameList = new HashSet<String>(); // for (int i = 0; i < files.length; i++) { // String fileName = files[i].getName(); // int index = fileName.indexOf('_'); // if (index == -1) { // baseNameList.add("language/" + fileName.substring(0, fileName.lastIndexOf('.'))); // } else { // baseNameList.add("language/" + fileName.substring(0, index)); // } // } // } // // /** // * 初始化 - 可以设置语言 // * // * @param locale // */ // public static void init(Locale locale) { // if (locale != null) { // Locale.setDefault(locale); // } // if (baseNameList == null || baseNameList.size() == 0) { // initBaseNameList(); // } // resourceBundles = new ResourceBundle[baseNameList.size()]; // int i = 0; // for (String baseName : baseNameList) { // resourceBundles[i] = ResourceBundle.getBundle(baseName); // i++; // } // } // // public static String key(String key) { // for (int i = 0; i < resourceBundles.length; i++) { // if (resourceBundles[i].containsKey(key)) { // return resourceBundles[i].getString(key); // } // } // throw new RuntimeException("key:" + key + " not exists!"); // } // // /** // * 可配参数,如:查找{0}字段 // * // * @param key // * @param args // * @return // */ // public static String key(String key, Object... args) { // return MessageFormat.format(key(key), args); // } // }
import com.github.abel533.Code; import com.github.abel533.utils.I18n; import javax.swing.*; import java.awt.*;
package com.github.abel533.view.panel; public class ChoosePanel extends JPanel { private static final long serialVersionUID = 1L; private JComboBox<String> comboBoxCatalog; private JComboBox<String> comboBoxSchema; private JButton buttonOK; public ChoosePanel() {
// Path: DBMetadata-swing/src/main/java/com/github/abel533/Code.java // public class Code { // public static Font TEXT_MSG = new Font("Monospaced", Font.PLAIN, 10); // public static Font TEXT_FONT = new Font(I18n.key("tools.text.font"), Font.PLAIN, 14); // public static Font TEXT_TABLE = new Font(I18n.key("tools.text.font"), Font.PLAIN, 12); // public static Font TEXT_BUTTON = new Font(I18n.key("tools.text.font"), Font.BOLD, 14); // } // // Path: DBMetadata-swing/src/main/java/com/github/abel533/utils/I18n.java // public class I18n { // private static final String SUFFIX = ".properties"; // private static ResourceBundle[] resourceBundles; // private static Set<String> baseNameList; // // static { // init(null); // } // // private static void initBaseNameList() { // File[] files = new File(Path.LANGUAGE).listFiles(new FilenameFilter() { // @Override // public boolean accept(File dir, String name) { // if (name.endsWith(SUFFIX)) { // return true; // } // return false; // } // }); // baseNameList = new HashSet<String>(); // for (int i = 0; i < files.length; i++) { // String fileName = files[i].getName(); // int index = fileName.indexOf('_'); // if (index == -1) { // baseNameList.add("language/" + fileName.substring(0, fileName.lastIndexOf('.'))); // } else { // baseNameList.add("language/" + fileName.substring(0, index)); // } // } // } // // /** // * 初始化 - 可以设置语言 // * // * @param locale // */ // public static void init(Locale locale) { // if (locale != null) { // Locale.setDefault(locale); // } // if (baseNameList == null || baseNameList.size() == 0) { // initBaseNameList(); // } // resourceBundles = new ResourceBundle[baseNameList.size()]; // int i = 0; // for (String baseName : baseNameList) { // resourceBundles[i] = ResourceBundle.getBundle(baseName); // i++; // } // } // // public static String key(String key) { // for (int i = 0; i < resourceBundles.length; i++) { // if (resourceBundles[i].containsKey(key)) { // return resourceBundles[i].getString(key); // } // } // throw new RuntimeException("key:" + key + " not exists!"); // } // // /** // * 可配参数,如:查找{0}字段 // * // * @param key // * @param args // * @return // */ // public static String key(String key, Object... args) { // return MessageFormat.format(key(key), args); // } // } // Path: DBMetadata-swing/src/main/java/com/github/abel533/view/panel/ChoosePanel.java import com.github.abel533.Code; import com.github.abel533.utils.I18n; import javax.swing.*; import java.awt.*; package com.github.abel533.view.panel; public class ChoosePanel extends JPanel { private static final long serialVersionUID = 1L; private JComboBox<String> comboBoxCatalog; private JComboBox<String> comboBoxSchema; private JButton buttonOK; public ChoosePanel() {
JLabel lblTitle = new JLabel(I18n.key("tools.load.label.tip"));
abel533/DBMetadata
DBMetadata-swing/src/main/java/com/github/abel533/view/panel/ChoosePanel.java
// Path: DBMetadata-swing/src/main/java/com/github/abel533/Code.java // public class Code { // public static Font TEXT_MSG = new Font("Monospaced", Font.PLAIN, 10); // public static Font TEXT_FONT = new Font(I18n.key("tools.text.font"), Font.PLAIN, 14); // public static Font TEXT_TABLE = new Font(I18n.key("tools.text.font"), Font.PLAIN, 12); // public static Font TEXT_BUTTON = new Font(I18n.key("tools.text.font"), Font.BOLD, 14); // } // // Path: DBMetadata-swing/src/main/java/com/github/abel533/utils/I18n.java // public class I18n { // private static final String SUFFIX = ".properties"; // private static ResourceBundle[] resourceBundles; // private static Set<String> baseNameList; // // static { // init(null); // } // // private static void initBaseNameList() { // File[] files = new File(Path.LANGUAGE).listFiles(new FilenameFilter() { // @Override // public boolean accept(File dir, String name) { // if (name.endsWith(SUFFIX)) { // return true; // } // return false; // } // }); // baseNameList = new HashSet<String>(); // for (int i = 0; i < files.length; i++) { // String fileName = files[i].getName(); // int index = fileName.indexOf('_'); // if (index == -1) { // baseNameList.add("language/" + fileName.substring(0, fileName.lastIndexOf('.'))); // } else { // baseNameList.add("language/" + fileName.substring(0, index)); // } // } // } // // /** // * 初始化 - 可以设置语言 // * // * @param locale // */ // public static void init(Locale locale) { // if (locale != null) { // Locale.setDefault(locale); // } // if (baseNameList == null || baseNameList.size() == 0) { // initBaseNameList(); // } // resourceBundles = new ResourceBundle[baseNameList.size()]; // int i = 0; // for (String baseName : baseNameList) { // resourceBundles[i] = ResourceBundle.getBundle(baseName); // i++; // } // } // // public static String key(String key) { // for (int i = 0; i < resourceBundles.length; i++) { // if (resourceBundles[i].containsKey(key)) { // return resourceBundles[i].getString(key); // } // } // throw new RuntimeException("key:" + key + " not exists!"); // } // // /** // * 可配参数,如:查找{0}字段 // * // * @param key // * @param args // * @return // */ // public static String key(String key, Object... args) { // return MessageFormat.format(key(key), args); // } // }
import com.github.abel533.Code; import com.github.abel533.utils.I18n; import javax.swing.*; import java.awt.*;
package com.github.abel533.view.panel; public class ChoosePanel extends JPanel { private static final long serialVersionUID = 1L; private JComboBox<String> comboBoxCatalog; private JComboBox<String> comboBoxSchema; private JButton buttonOK; public ChoosePanel() { JLabel lblTitle = new JLabel(I18n.key("tools.load.label.tip")); JLabel lblCatalog = new JLabel(I18n.key("tools.load.label.catalog")); comboBoxCatalog = new JComboBox<String>(); JLabel lblSchema = new JLabel(I18n.key("tools.load.label.schema")); comboBoxSchema = new JComboBox<String>(); buttonOK = new JButton(I18n.key("tools.load.btn.ok")); GridBagLayout layout = new GridBagLayout(); this.setLayout(layout); GridBagConstraints c = new GridBagConstraints(); c.insets = new Insets(10, 5, 10, 5); c.fill = GridBagConstraints.BOTH; c.gridwidth = 0; c.weightx = 1; c.weighty = 0;
// Path: DBMetadata-swing/src/main/java/com/github/abel533/Code.java // public class Code { // public static Font TEXT_MSG = new Font("Monospaced", Font.PLAIN, 10); // public static Font TEXT_FONT = new Font(I18n.key("tools.text.font"), Font.PLAIN, 14); // public static Font TEXT_TABLE = new Font(I18n.key("tools.text.font"), Font.PLAIN, 12); // public static Font TEXT_BUTTON = new Font(I18n.key("tools.text.font"), Font.BOLD, 14); // } // // Path: DBMetadata-swing/src/main/java/com/github/abel533/utils/I18n.java // public class I18n { // private static final String SUFFIX = ".properties"; // private static ResourceBundle[] resourceBundles; // private static Set<String> baseNameList; // // static { // init(null); // } // // private static void initBaseNameList() { // File[] files = new File(Path.LANGUAGE).listFiles(new FilenameFilter() { // @Override // public boolean accept(File dir, String name) { // if (name.endsWith(SUFFIX)) { // return true; // } // return false; // } // }); // baseNameList = new HashSet<String>(); // for (int i = 0; i < files.length; i++) { // String fileName = files[i].getName(); // int index = fileName.indexOf('_'); // if (index == -1) { // baseNameList.add("language/" + fileName.substring(0, fileName.lastIndexOf('.'))); // } else { // baseNameList.add("language/" + fileName.substring(0, index)); // } // } // } // // /** // * 初始化 - 可以设置语言 // * // * @param locale // */ // public static void init(Locale locale) { // if (locale != null) { // Locale.setDefault(locale); // } // if (baseNameList == null || baseNameList.size() == 0) { // initBaseNameList(); // } // resourceBundles = new ResourceBundle[baseNameList.size()]; // int i = 0; // for (String baseName : baseNameList) { // resourceBundles[i] = ResourceBundle.getBundle(baseName); // i++; // } // } // // public static String key(String key) { // for (int i = 0; i < resourceBundles.length; i++) { // if (resourceBundles[i].containsKey(key)) { // return resourceBundles[i].getString(key); // } // } // throw new RuntimeException("key:" + key + " not exists!"); // } // // /** // * 可配参数,如:查找{0}字段 // * // * @param key // * @param args // * @return // */ // public static String key(String key, Object... args) { // return MessageFormat.format(key(key), args); // } // } // Path: DBMetadata-swing/src/main/java/com/github/abel533/view/panel/ChoosePanel.java import com.github.abel533.Code; import com.github.abel533.utils.I18n; import javax.swing.*; import java.awt.*; package com.github.abel533.view.panel; public class ChoosePanel extends JPanel { private static final long serialVersionUID = 1L; private JComboBox<String> comboBoxCatalog; private JComboBox<String> comboBoxSchema; private JButton buttonOK; public ChoosePanel() { JLabel lblTitle = new JLabel(I18n.key("tools.load.label.tip")); JLabel lblCatalog = new JLabel(I18n.key("tools.load.label.catalog")); comboBoxCatalog = new JComboBox<String>(); JLabel lblSchema = new JLabel(I18n.key("tools.load.label.schema")); comboBoxSchema = new JComboBox<String>(); buttonOK = new JButton(I18n.key("tools.load.btn.ok")); GridBagLayout layout = new GridBagLayout(); this.setLayout(layout); GridBagConstraints c = new GridBagConstraints(); c.insets = new Insets(10, 5, 10, 5); c.fill = GridBagConstraints.BOTH; c.gridwidth = 0; c.weightx = 1; c.weighty = 0;
lblTitle.setFont(Code.TEXT_FONT);
abel533/DBMetadata
DBMetadata-swing/src/main/java/com/github/abel533/view/panel/ControlPanel.java
// Path: DBMetadata-swing/src/main/java/com/github/abel533/utils/I18n.java // public class I18n { // private static final String SUFFIX = ".properties"; // private static ResourceBundle[] resourceBundles; // private static Set<String> baseNameList; // // static { // init(null); // } // // private static void initBaseNameList() { // File[] files = new File(Path.LANGUAGE).listFiles(new FilenameFilter() { // @Override // public boolean accept(File dir, String name) { // if (name.endsWith(SUFFIX)) { // return true; // } // return false; // } // }); // baseNameList = new HashSet<String>(); // for (int i = 0; i < files.length; i++) { // String fileName = files[i].getName(); // int index = fileName.indexOf('_'); // if (index == -1) { // baseNameList.add("language/" + fileName.substring(0, fileName.lastIndexOf('.'))); // } else { // baseNameList.add("language/" + fileName.substring(0, index)); // } // } // } // // /** // * 初始化 - 可以设置语言 // * // * @param locale // */ // public static void init(Locale locale) { // if (locale != null) { // Locale.setDefault(locale); // } // if (baseNameList == null || baseNameList.size() == 0) { // initBaseNameList(); // } // resourceBundles = new ResourceBundle[baseNameList.size()]; // int i = 0; // for (String baseName : baseNameList) { // resourceBundles[i] = ResourceBundle.getBundle(baseName); // i++; // } // } // // public static String key(String key) { // for (int i = 0; i < resourceBundles.length; i++) { // if (resourceBundles[i].containsKey(key)) { // return resourceBundles[i].getString(key); // } // } // throw new RuntimeException("key:" + key + " not exists!"); // } // // /** // * 可配参数,如:查找{0}字段 // * // * @param key // * @param args // * @return // */ // public static String key(String key, Object... args) { // return MessageFormat.format(key(key), args); // } // }
import com.github.abel533.utils.I18n; import javax.swing.*; import java.awt.*;
package com.github.abel533.view.panel; /** * 主界面中,可以重新选择数据库,重新加载 * * @author liuzh * @since 2015-03-20 */ public class ControlPanel extends JPanel { private static final long serialVersionUID = 1L; private JSlider sliderFontsize; private JButton changeDatabase; private JComboBox<String> comboBoxCatalog; private JComboBox<String> comboBoxSchema; private JButton btnReload; /** * Create the panel. */ public ControlPanel() { GridBagLayout layout = new GridBagLayout(); this.setLayout(layout); GridBagConstraints c = new GridBagConstraints();
// Path: DBMetadata-swing/src/main/java/com/github/abel533/utils/I18n.java // public class I18n { // private static final String SUFFIX = ".properties"; // private static ResourceBundle[] resourceBundles; // private static Set<String> baseNameList; // // static { // init(null); // } // // private static void initBaseNameList() { // File[] files = new File(Path.LANGUAGE).listFiles(new FilenameFilter() { // @Override // public boolean accept(File dir, String name) { // if (name.endsWith(SUFFIX)) { // return true; // } // return false; // } // }); // baseNameList = new HashSet<String>(); // for (int i = 0; i < files.length; i++) { // String fileName = files[i].getName(); // int index = fileName.indexOf('_'); // if (index == -1) { // baseNameList.add("language/" + fileName.substring(0, fileName.lastIndexOf('.'))); // } else { // baseNameList.add("language/" + fileName.substring(0, index)); // } // } // } // // /** // * 初始化 - 可以设置语言 // * // * @param locale // */ // public static void init(Locale locale) { // if (locale != null) { // Locale.setDefault(locale); // } // if (baseNameList == null || baseNameList.size() == 0) { // initBaseNameList(); // } // resourceBundles = new ResourceBundle[baseNameList.size()]; // int i = 0; // for (String baseName : baseNameList) { // resourceBundles[i] = ResourceBundle.getBundle(baseName); // i++; // } // } // // public static String key(String key) { // for (int i = 0; i < resourceBundles.length; i++) { // if (resourceBundles[i].containsKey(key)) { // return resourceBundles[i].getString(key); // } // } // throw new RuntimeException("key:" + key + " not exists!"); // } // // /** // * 可配参数,如:查找{0}字段 // * // * @param key // * @param args // * @return // */ // public static String key(String key, Object... args) { // return MessageFormat.format(key(key), args); // } // } // Path: DBMetadata-swing/src/main/java/com/github/abel533/view/panel/ControlPanel.java import com.github.abel533.utils.I18n; import javax.swing.*; import java.awt.*; package com.github.abel533.view.panel; /** * 主界面中,可以重新选择数据库,重新加载 * * @author liuzh * @since 2015-03-20 */ public class ControlPanel extends JPanel { private static final long serialVersionUID = 1L; private JSlider sliderFontsize; private JButton changeDatabase; private JComboBox<String> comboBoxCatalog; private JComboBox<String> comboBoxSchema; private JButton btnReload; /** * Create the panel. */ public ControlPanel() { GridBagLayout layout = new GridBagLayout(); this.setLayout(layout); GridBagConstraints c = new GridBagConstraints();
JLabel labelFontsize = new JLabel(I18n.key("tools.controlpanel.fontsize"));
abel533/DBMetadata
DBMetadata-swing/src/main/java/com/github/abel533/component/JTextPwd.java
// Path: DBMetadata-swing/src/main/java/com/github/abel533/Code.java // public class Code { // public static Font TEXT_MSG = new Font("Monospaced", Font.PLAIN, 10); // public static Font TEXT_FONT = new Font(I18n.key("tools.text.font"), Font.PLAIN, 14); // public static Font TEXT_TABLE = new Font(I18n.key("tools.text.font"), Font.PLAIN, 12); // public static Font TEXT_BUTTON = new Font(I18n.key("tools.text.font"), Font.BOLD, 14); // }
import com.github.abel533.Code; import javax.swing.*; import java.awt.*; import java.awt.image.BufferedImage;
package com.github.abel533.component; /** * @author liuzh */ public class JTextPwd extends JPasswordField { private static final long serialVersionUID = 1L; private BufferedImage buffer = null; public JTextPwd() { super();
// Path: DBMetadata-swing/src/main/java/com/github/abel533/Code.java // public class Code { // public static Font TEXT_MSG = new Font("Monospaced", Font.PLAIN, 10); // public static Font TEXT_FONT = new Font(I18n.key("tools.text.font"), Font.PLAIN, 14); // public static Font TEXT_TABLE = new Font(I18n.key("tools.text.font"), Font.PLAIN, 12); // public static Font TEXT_BUTTON = new Font(I18n.key("tools.text.font"), Font.BOLD, 14); // } // Path: DBMetadata-swing/src/main/java/com/github/abel533/component/JTextPwd.java import com.github.abel533.Code; import javax.swing.*; import java.awt.*; import java.awt.image.BufferedImage; package com.github.abel533.component; /** * @author liuzh */ public class JTextPwd extends JPasswordField { private static final long serialVersionUID = 1L; private BufferedImage buffer = null; public JTextPwd() { super();
setFont(Code.TEXT_FONT);
abel533/DBMetadata
DBMetadata-core/src/main/java/com/github/abel533/database/IntrospectedBase.java
// Path: DBMetadata-core/src/main/java/com/github/abel533/utils/StringUtils.java // public class StringUtils { // // public static String getNotNull(Object value) { // if (value == null) { // return ""; // } // return value.toString(); // } // // public static boolean isEmpty(String value) { // if (value == null || value.length() == 0) { // return true; // } // return false; // } // // public static boolean isNotEmpty(String value) { // return !isEmpty(value); // } // // public static boolean isEmpty(List<?> value) { // if (value == null || value.size() == 0) { // return true; // } // return false; // } // // public static boolean isNotEmpty(List<?> value) { // return !isEmpty(value); // } // }
import com.github.abel533.utils.StringUtils;
package com.github.abel533.database; public class IntrospectedBase { protected String name; protected String remarks; /** * 根据条件进行过滤 * * @param searchText * @param searchComment * @param matchType * @param caseSensitive * @return */ public boolean filter(String searchText, String searchComment, MatchType matchType, boolean caseSensitive) {
// Path: DBMetadata-core/src/main/java/com/github/abel533/utils/StringUtils.java // public class StringUtils { // // public static String getNotNull(Object value) { // if (value == null) { // return ""; // } // return value.toString(); // } // // public static boolean isEmpty(String value) { // if (value == null || value.length() == 0) { // return true; // } // return false; // } // // public static boolean isNotEmpty(String value) { // return !isEmpty(value); // } // // public static boolean isEmpty(List<?> value) { // if (value == null || value.size() == 0) { // return true; // } // return false; // } // // public static boolean isNotEmpty(List<?> value) { // return !isEmpty(value); // } // } // Path: DBMetadata-core/src/main/java/com/github/abel533/database/IntrospectedBase.java import com.github.abel533.utils.StringUtils; package com.github.abel533.database; public class IntrospectedBase { protected String name; protected String remarks; /** * 根据条件进行过滤 * * @param searchText * @param searchComment * @param matchType * @param caseSensitive * @return */ public boolean filter(String searchText, String searchComment, MatchType matchType, boolean caseSensitive) {
if (StringUtils.isNotEmpty(searchText)) {
abel533/DBMetadata
DBMetadata-swing/src/main/java/com/github/abel533/Code.java
// Path: DBMetadata-swing/src/main/java/com/github/abel533/utils/I18n.java // public class I18n { // private static final String SUFFIX = ".properties"; // private static ResourceBundle[] resourceBundles; // private static Set<String> baseNameList; // // static { // init(null); // } // // private static void initBaseNameList() { // File[] files = new File(Path.LANGUAGE).listFiles(new FilenameFilter() { // @Override // public boolean accept(File dir, String name) { // if (name.endsWith(SUFFIX)) { // return true; // } // return false; // } // }); // baseNameList = new HashSet<String>(); // for (int i = 0; i < files.length; i++) { // String fileName = files[i].getName(); // int index = fileName.indexOf('_'); // if (index == -1) { // baseNameList.add("language/" + fileName.substring(0, fileName.lastIndexOf('.'))); // } else { // baseNameList.add("language/" + fileName.substring(0, index)); // } // } // } // // /** // * 初始化 - 可以设置语言 // * // * @param locale // */ // public static void init(Locale locale) { // if (locale != null) { // Locale.setDefault(locale); // } // if (baseNameList == null || baseNameList.size() == 0) { // initBaseNameList(); // } // resourceBundles = new ResourceBundle[baseNameList.size()]; // int i = 0; // for (String baseName : baseNameList) { // resourceBundles[i] = ResourceBundle.getBundle(baseName); // i++; // } // } // // public static String key(String key) { // for (int i = 0; i < resourceBundles.length; i++) { // if (resourceBundles[i].containsKey(key)) { // return resourceBundles[i].getString(key); // } // } // throw new RuntimeException("key:" + key + " not exists!"); // } // // /** // * 可配参数,如:查找{0}字段 // * // * @param key // * @param args // * @return // */ // public static String key(String key, Object... args) { // return MessageFormat.format(key(key), args); // } // }
import com.github.abel533.utils.I18n; import java.awt.*;
package com.github.abel533; /** * @author liuzh */ public class Code { public static Font TEXT_MSG = new Font("Monospaced", Font.PLAIN, 10);
// Path: DBMetadata-swing/src/main/java/com/github/abel533/utils/I18n.java // public class I18n { // private static final String SUFFIX = ".properties"; // private static ResourceBundle[] resourceBundles; // private static Set<String> baseNameList; // // static { // init(null); // } // // private static void initBaseNameList() { // File[] files = new File(Path.LANGUAGE).listFiles(new FilenameFilter() { // @Override // public boolean accept(File dir, String name) { // if (name.endsWith(SUFFIX)) { // return true; // } // return false; // } // }); // baseNameList = new HashSet<String>(); // for (int i = 0; i < files.length; i++) { // String fileName = files[i].getName(); // int index = fileName.indexOf('_'); // if (index == -1) { // baseNameList.add("language/" + fileName.substring(0, fileName.lastIndexOf('.'))); // } else { // baseNameList.add("language/" + fileName.substring(0, index)); // } // } // } // // /** // * 初始化 - 可以设置语言 // * // * @param locale // */ // public static void init(Locale locale) { // if (locale != null) { // Locale.setDefault(locale); // } // if (baseNameList == null || baseNameList.size() == 0) { // initBaseNameList(); // } // resourceBundles = new ResourceBundle[baseNameList.size()]; // int i = 0; // for (String baseName : baseNameList) { // resourceBundles[i] = ResourceBundle.getBundle(baseName); // i++; // } // } // // public static String key(String key) { // for (int i = 0; i < resourceBundles.length; i++) { // if (resourceBundles[i].containsKey(key)) { // return resourceBundles[i].getString(key); // } // } // throw new RuntimeException("key:" + key + " not exists!"); // } // // /** // * 可配参数,如:查找{0}字段 // * // * @param key // * @param args // * @return // */ // public static String key(String key, Object... args) { // return MessageFormat.format(key(key), args); // } // } // Path: DBMetadata-swing/src/main/java/com/github/abel533/Code.java import com.github.abel533.utils.I18n; import java.awt.*; package com.github.abel533; /** * @author liuzh */ public class Code { public static Font TEXT_MSG = new Font("Monospaced", Font.PLAIN, 10);
public static Font TEXT_FONT = new Font(I18n.key("tools.text.font"), Font.PLAIN, 14);
SailFlorve/RunHDU
app/src/main/java/com/cxsj/runhdu/Model/LoginModel.java
// Path: app/src/main/java/com/cxsj/runhdu/bean/gson/Status.java // public class Status { // @SerializedName("Result") // private boolean result; // // @SerializedName("Message") // private String message; // // @SerializedName("Which") // private int which; // // public boolean getResult() { // return result; // } // // public String getMessage() { // return message; // } // // public int getWhich() { // return which; // } // // } // // Path: app/src/main/java/com/cxsj/runhdu/constant/URLs.java // public class URLs { // public static final String DOWNLOAD = "http://d1.51gugu.com/170258/RunHDU"; // public static final String LOGIN = "http://112.74.115.231:8080/CXSJ/Login"; // public static final String REGISTER="http://112.74.115.231:8080/CXSJ/Register"; // public static final String GET_RUN_INFO = "http://112.74.115.231:8080/chuangxinshijian/ReadAll"; // public static final String UPLOAD_RUN_INFO = "http://112.74.115.231:8080/chuangxinshijian/Write"; // public static final String CLEAR_DATA = "http://112.74.115.231:8080/chuangxinshijian/ClearTheTable"; // public static final String UPDATE_URL = "http://112.74.115.231:8080/chuangxinshijian/VersionCompare"; // public static final String GET_RUN_TIMES = "http://112.74.115.231:8080/chuangxinshijian/ReadUserNameAndTimesOnly"; // public static final String UPLOAD_ALL_INFO = "http://112.74.115.231:8080/chuangxinshijian/WriteByJson"; // public static final String UPLOAD_PROFILE = "http://112.74.115.231:8080/CXSJ/UploadHead"; // public static final String PROFILE_URL = "http://112.74.115.231:8080/CXSJ/Image/"; // public static final String FEEDBACK_URL = "http://112.74.115.231:8080/chuangxinshijian/WriteFeedback"; // public static final String SUNNY_RUN_QUERY_API = "http://hdu.sunnysport.org.cn/api/student/achievements/"; // public static final String SUNNY_RUN_INFO_API = "http://hdu.sunnysport.org.cn/api/student/info/"; // public static final String DELETE_ITEM = "http://112.74.115.231:8080/chuangxinshijian/ClearByUserNameAndRunId"; // public static final String APPLY_FRIEND = "http://112.74.115.231:8080/CXSJ/Apply"; // public static final String REPLY_FRIEND = "http://112.74.115.231:8080/CXSJ/BeFriend"; // public static final String GET_FRIEND = "http://112.74.115.231:8080/CXSJ/MyFriends"; // public static final String DELETE_FRIEND = "http://112.74.115.231:8080/CXSJ/DeleteFriend"; // public static final String OFF_LINE = "http://112.74.115.231:8080/CXSJ/Xiaxian"; // } // // Path: app/src/main/java/com/cxsj/runhdu/utils/HttpUtil.java // public class HttpUtil { // private static RequestManager manager; // // public static RequestManager load(String url) { // manager = new RequestManager(); // manager.url(url); // return manager; // } // // public static class RequestManager { // private Request.Builder requestBuilder = new Request.Builder(); // private FormBody.Builder formBuilder = new FormBody.Builder(); // private Call call; // // private void url(String url) { // formBuilder = new FormBody.Builder(); // requestBuilder = new Request.Builder(); // // requestBuilder = requestBuilder.url(url); // } // // private void cancel() { // if (call != null) { // call.cancel(); // } // } // // public RequestManager addHeader(String key, String value) { // requestBuilder.addHeader(key, value); // return this; // } // // public RequestManager addParam(String key, String value) { // formBuilder = formBuilder.add(key, value); // return this; // } // // public void post(Callback callback) { // OkHttpClient client = new OkHttpClient.Builder() // .connectTimeout(3, TimeUnit.SECONDS) // .followRedirects(false) // .followSslRedirects(false) // .build(); // // Request request = requestBuilder.post(formBuilder.build()).build(); // client.newCall(request).enqueue(callback); // } // // public void get(Callback callback) { // OkHttpClient client = new OkHttpClient.Builder().build(); // Request request = requestBuilder.build(); // call = client.newCall(request); // call.enqueue(callback); // } // } // }
import com.cxsj.runhdu.bean.gson.Status; import com.cxsj.runhdu.constant.URLs; import com.cxsj.runhdu.utils.HttpUtil; import com.google.gson.Gson; import com.google.gson.JsonSyntaxException; import java.io.IOException; import okhttp3.Call; import okhttp3.Callback; import okhttp3.Response;
package com.cxsj.runhdu.Model; /** * Created by SailFlorve on 2017/8/25 0025. * 登录与注册数据请求 */ public class LoginModel extends BaseModel { public interface LoginCallback { void onLoginSuccess(); void onLoginFailure(String msg, int which); } private static Callback getCallback(LoginCallback callback) { return new Callback() { @Override public void onFailure(Call call, IOException e) { mHandler.post(() -> callback.onLoginFailure(CONNECT_FAILED, 0)); } @Override public void onResponse(Call call, Response response) throws IOException { String json = response.body().string(); try { mHandler.post(() -> {
// Path: app/src/main/java/com/cxsj/runhdu/bean/gson/Status.java // public class Status { // @SerializedName("Result") // private boolean result; // // @SerializedName("Message") // private String message; // // @SerializedName("Which") // private int which; // // public boolean getResult() { // return result; // } // // public String getMessage() { // return message; // } // // public int getWhich() { // return which; // } // // } // // Path: app/src/main/java/com/cxsj/runhdu/constant/URLs.java // public class URLs { // public static final String DOWNLOAD = "http://d1.51gugu.com/170258/RunHDU"; // public static final String LOGIN = "http://112.74.115.231:8080/CXSJ/Login"; // public static final String REGISTER="http://112.74.115.231:8080/CXSJ/Register"; // public static final String GET_RUN_INFO = "http://112.74.115.231:8080/chuangxinshijian/ReadAll"; // public static final String UPLOAD_RUN_INFO = "http://112.74.115.231:8080/chuangxinshijian/Write"; // public static final String CLEAR_DATA = "http://112.74.115.231:8080/chuangxinshijian/ClearTheTable"; // public static final String UPDATE_URL = "http://112.74.115.231:8080/chuangxinshijian/VersionCompare"; // public static final String GET_RUN_TIMES = "http://112.74.115.231:8080/chuangxinshijian/ReadUserNameAndTimesOnly"; // public static final String UPLOAD_ALL_INFO = "http://112.74.115.231:8080/chuangxinshijian/WriteByJson"; // public static final String UPLOAD_PROFILE = "http://112.74.115.231:8080/CXSJ/UploadHead"; // public static final String PROFILE_URL = "http://112.74.115.231:8080/CXSJ/Image/"; // public static final String FEEDBACK_URL = "http://112.74.115.231:8080/chuangxinshijian/WriteFeedback"; // public static final String SUNNY_RUN_QUERY_API = "http://hdu.sunnysport.org.cn/api/student/achievements/"; // public static final String SUNNY_RUN_INFO_API = "http://hdu.sunnysport.org.cn/api/student/info/"; // public static final String DELETE_ITEM = "http://112.74.115.231:8080/chuangxinshijian/ClearByUserNameAndRunId"; // public static final String APPLY_FRIEND = "http://112.74.115.231:8080/CXSJ/Apply"; // public static final String REPLY_FRIEND = "http://112.74.115.231:8080/CXSJ/BeFriend"; // public static final String GET_FRIEND = "http://112.74.115.231:8080/CXSJ/MyFriends"; // public static final String DELETE_FRIEND = "http://112.74.115.231:8080/CXSJ/DeleteFriend"; // public static final String OFF_LINE = "http://112.74.115.231:8080/CXSJ/Xiaxian"; // } // // Path: app/src/main/java/com/cxsj/runhdu/utils/HttpUtil.java // public class HttpUtil { // private static RequestManager manager; // // public static RequestManager load(String url) { // manager = new RequestManager(); // manager.url(url); // return manager; // } // // public static class RequestManager { // private Request.Builder requestBuilder = new Request.Builder(); // private FormBody.Builder formBuilder = new FormBody.Builder(); // private Call call; // // private void url(String url) { // formBuilder = new FormBody.Builder(); // requestBuilder = new Request.Builder(); // // requestBuilder = requestBuilder.url(url); // } // // private void cancel() { // if (call != null) { // call.cancel(); // } // } // // public RequestManager addHeader(String key, String value) { // requestBuilder.addHeader(key, value); // return this; // } // // public RequestManager addParam(String key, String value) { // formBuilder = formBuilder.add(key, value); // return this; // } // // public void post(Callback callback) { // OkHttpClient client = new OkHttpClient.Builder() // .connectTimeout(3, TimeUnit.SECONDS) // .followRedirects(false) // .followSslRedirects(false) // .build(); // // Request request = requestBuilder.post(formBuilder.build()).build(); // client.newCall(request).enqueue(callback); // } // // public void get(Callback callback) { // OkHttpClient client = new OkHttpClient.Builder().build(); // Request request = requestBuilder.build(); // call = client.newCall(request); // call.enqueue(callback); // } // } // } // Path: app/src/main/java/com/cxsj/runhdu/Model/LoginModel.java import com.cxsj.runhdu.bean.gson.Status; import com.cxsj.runhdu.constant.URLs; import com.cxsj.runhdu.utils.HttpUtil; import com.google.gson.Gson; import com.google.gson.JsonSyntaxException; import java.io.IOException; import okhttp3.Call; import okhttp3.Callback; import okhttp3.Response; package com.cxsj.runhdu.Model; /** * Created by SailFlorve on 2017/8/25 0025. * 登录与注册数据请求 */ public class LoginModel extends BaseModel { public interface LoginCallback { void onLoginSuccess(); void onLoginFailure(String msg, int which); } private static Callback getCallback(LoginCallback callback) { return new Callback() { @Override public void onFailure(Call call, IOException e) { mHandler.post(() -> callback.onLoginFailure(CONNECT_FAILED, 0)); } @Override public void onResponse(Call call, Response response) throws IOException { String json = response.body().string(); try { mHandler.post(() -> {
Status status = null;
SailFlorve/RunHDU
app/src/main/java/com/cxsj/runhdu/Model/LoginModel.java
// Path: app/src/main/java/com/cxsj/runhdu/bean/gson/Status.java // public class Status { // @SerializedName("Result") // private boolean result; // // @SerializedName("Message") // private String message; // // @SerializedName("Which") // private int which; // // public boolean getResult() { // return result; // } // // public String getMessage() { // return message; // } // // public int getWhich() { // return which; // } // // } // // Path: app/src/main/java/com/cxsj/runhdu/constant/URLs.java // public class URLs { // public static final String DOWNLOAD = "http://d1.51gugu.com/170258/RunHDU"; // public static final String LOGIN = "http://112.74.115.231:8080/CXSJ/Login"; // public static final String REGISTER="http://112.74.115.231:8080/CXSJ/Register"; // public static final String GET_RUN_INFO = "http://112.74.115.231:8080/chuangxinshijian/ReadAll"; // public static final String UPLOAD_RUN_INFO = "http://112.74.115.231:8080/chuangxinshijian/Write"; // public static final String CLEAR_DATA = "http://112.74.115.231:8080/chuangxinshijian/ClearTheTable"; // public static final String UPDATE_URL = "http://112.74.115.231:8080/chuangxinshijian/VersionCompare"; // public static final String GET_RUN_TIMES = "http://112.74.115.231:8080/chuangxinshijian/ReadUserNameAndTimesOnly"; // public static final String UPLOAD_ALL_INFO = "http://112.74.115.231:8080/chuangxinshijian/WriteByJson"; // public static final String UPLOAD_PROFILE = "http://112.74.115.231:8080/CXSJ/UploadHead"; // public static final String PROFILE_URL = "http://112.74.115.231:8080/CXSJ/Image/"; // public static final String FEEDBACK_URL = "http://112.74.115.231:8080/chuangxinshijian/WriteFeedback"; // public static final String SUNNY_RUN_QUERY_API = "http://hdu.sunnysport.org.cn/api/student/achievements/"; // public static final String SUNNY_RUN_INFO_API = "http://hdu.sunnysport.org.cn/api/student/info/"; // public static final String DELETE_ITEM = "http://112.74.115.231:8080/chuangxinshijian/ClearByUserNameAndRunId"; // public static final String APPLY_FRIEND = "http://112.74.115.231:8080/CXSJ/Apply"; // public static final String REPLY_FRIEND = "http://112.74.115.231:8080/CXSJ/BeFriend"; // public static final String GET_FRIEND = "http://112.74.115.231:8080/CXSJ/MyFriends"; // public static final String DELETE_FRIEND = "http://112.74.115.231:8080/CXSJ/DeleteFriend"; // public static final String OFF_LINE = "http://112.74.115.231:8080/CXSJ/Xiaxian"; // } // // Path: app/src/main/java/com/cxsj/runhdu/utils/HttpUtil.java // public class HttpUtil { // private static RequestManager manager; // // public static RequestManager load(String url) { // manager = new RequestManager(); // manager.url(url); // return manager; // } // // public static class RequestManager { // private Request.Builder requestBuilder = new Request.Builder(); // private FormBody.Builder formBuilder = new FormBody.Builder(); // private Call call; // // private void url(String url) { // formBuilder = new FormBody.Builder(); // requestBuilder = new Request.Builder(); // // requestBuilder = requestBuilder.url(url); // } // // private void cancel() { // if (call != null) { // call.cancel(); // } // } // // public RequestManager addHeader(String key, String value) { // requestBuilder.addHeader(key, value); // return this; // } // // public RequestManager addParam(String key, String value) { // formBuilder = formBuilder.add(key, value); // return this; // } // // public void post(Callback callback) { // OkHttpClient client = new OkHttpClient.Builder() // .connectTimeout(3, TimeUnit.SECONDS) // .followRedirects(false) // .followSslRedirects(false) // .build(); // // Request request = requestBuilder.post(formBuilder.build()).build(); // client.newCall(request).enqueue(callback); // } // // public void get(Callback callback) { // OkHttpClient client = new OkHttpClient.Builder().build(); // Request request = requestBuilder.build(); // call = client.newCall(request); // call.enqueue(callback); // } // } // }
import com.cxsj.runhdu.bean.gson.Status; import com.cxsj.runhdu.constant.URLs; import com.cxsj.runhdu.utils.HttpUtil; import com.google.gson.Gson; import com.google.gson.JsonSyntaxException; import java.io.IOException; import okhttp3.Call; import okhttp3.Callback; import okhttp3.Response;
public void onFailure(Call call, IOException e) { mHandler.post(() -> callback.onLoginFailure(CONNECT_FAILED, 0)); } @Override public void onResponse(Call call, Response response) throws IOException { String json = response.body().string(); try { mHandler.post(() -> { Status status = null; status = new Gson().fromJson(json, Status.class); if (status == null) { callback.onLoginFailure(RETURN_DATA_ERROR, 0); } else { if (status.getResult()) { callback.onLoginSuccess(); } else { callback.onLoginFailure(status.getMessage(), status.getWhich()); } } }); } catch (JsonSyntaxException e) { callback.onLoginFailure(RETURN_DATA_ERROR, 0); e.printStackTrace(); } } }; } public static void login(String username, String passwordMD5, LoginCallback callback) {
// Path: app/src/main/java/com/cxsj/runhdu/bean/gson/Status.java // public class Status { // @SerializedName("Result") // private boolean result; // // @SerializedName("Message") // private String message; // // @SerializedName("Which") // private int which; // // public boolean getResult() { // return result; // } // // public String getMessage() { // return message; // } // // public int getWhich() { // return which; // } // // } // // Path: app/src/main/java/com/cxsj/runhdu/constant/URLs.java // public class URLs { // public static final String DOWNLOAD = "http://d1.51gugu.com/170258/RunHDU"; // public static final String LOGIN = "http://112.74.115.231:8080/CXSJ/Login"; // public static final String REGISTER="http://112.74.115.231:8080/CXSJ/Register"; // public static final String GET_RUN_INFO = "http://112.74.115.231:8080/chuangxinshijian/ReadAll"; // public static final String UPLOAD_RUN_INFO = "http://112.74.115.231:8080/chuangxinshijian/Write"; // public static final String CLEAR_DATA = "http://112.74.115.231:8080/chuangxinshijian/ClearTheTable"; // public static final String UPDATE_URL = "http://112.74.115.231:8080/chuangxinshijian/VersionCompare"; // public static final String GET_RUN_TIMES = "http://112.74.115.231:8080/chuangxinshijian/ReadUserNameAndTimesOnly"; // public static final String UPLOAD_ALL_INFO = "http://112.74.115.231:8080/chuangxinshijian/WriteByJson"; // public static final String UPLOAD_PROFILE = "http://112.74.115.231:8080/CXSJ/UploadHead"; // public static final String PROFILE_URL = "http://112.74.115.231:8080/CXSJ/Image/"; // public static final String FEEDBACK_URL = "http://112.74.115.231:8080/chuangxinshijian/WriteFeedback"; // public static final String SUNNY_RUN_QUERY_API = "http://hdu.sunnysport.org.cn/api/student/achievements/"; // public static final String SUNNY_RUN_INFO_API = "http://hdu.sunnysport.org.cn/api/student/info/"; // public static final String DELETE_ITEM = "http://112.74.115.231:8080/chuangxinshijian/ClearByUserNameAndRunId"; // public static final String APPLY_FRIEND = "http://112.74.115.231:8080/CXSJ/Apply"; // public static final String REPLY_FRIEND = "http://112.74.115.231:8080/CXSJ/BeFriend"; // public static final String GET_FRIEND = "http://112.74.115.231:8080/CXSJ/MyFriends"; // public static final String DELETE_FRIEND = "http://112.74.115.231:8080/CXSJ/DeleteFriend"; // public static final String OFF_LINE = "http://112.74.115.231:8080/CXSJ/Xiaxian"; // } // // Path: app/src/main/java/com/cxsj/runhdu/utils/HttpUtil.java // public class HttpUtil { // private static RequestManager manager; // // public static RequestManager load(String url) { // manager = new RequestManager(); // manager.url(url); // return manager; // } // // public static class RequestManager { // private Request.Builder requestBuilder = new Request.Builder(); // private FormBody.Builder formBuilder = new FormBody.Builder(); // private Call call; // // private void url(String url) { // formBuilder = new FormBody.Builder(); // requestBuilder = new Request.Builder(); // // requestBuilder = requestBuilder.url(url); // } // // private void cancel() { // if (call != null) { // call.cancel(); // } // } // // public RequestManager addHeader(String key, String value) { // requestBuilder.addHeader(key, value); // return this; // } // // public RequestManager addParam(String key, String value) { // formBuilder = formBuilder.add(key, value); // return this; // } // // public void post(Callback callback) { // OkHttpClient client = new OkHttpClient.Builder() // .connectTimeout(3, TimeUnit.SECONDS) // .followRedirects(false) // .followSslRedirects(false) // .build(); // // Request request = requestBuilder.post(formBuilder.build()).build(); // client.newCall(request).enqueue(callback); // } // // public void get(Callback callback) { // OkHttpClient client = new OkHttpClient.Builder().build(); // Request request = requestBuilder.build(); // call = client.newCall(request); // call.enqueue(callback); // } // } // } // Path: app/src/main/java/com/cxsj/runhdu/Model/LoginModel.java import com.cxsj.runhdu.bean.gson.Status; import com.cxsj.runhdu.constant.URLs; import com.cxsj.runhdu.utils.HttpUtil; import com.google.gson.Gson; import com.google.gson.JsonSyntaxException; import java.io.IOException; import okhttp3.Call; import okhttp3.Callback; import okhttp3.Response; public void onFailure(Call call, IOException e) { mHandler.post(() -> callback.onLoginFailure(CONNECT_FAILED, 0)); } @Override public void onResponse(Call call, Response response) throws IOException { String json = response.body().string(); try { mHandler.post(() -> { Status status = null; status = new Gson().fromJson(json, Status.class); if (status == null) { callback.onLoginFailure(RETURN_DATA_ERROR, 0); } else { if (status.getResult()) { callback.onLoginSuccess(); } else { callback.onLoginFailure(status.getMessage(), status.getWhich()); } } }); } catch (JsonSyntaxException e) { callback.onLoginFailure(RETURN_DATA_ERROR, 0); e.printStackTrace(); } } }; } public static void login(String username, String passwordMD5, LoginCallback callback) {
HttpUtil.load(URLs.LOGIN)
SailFlorve/RunHDU
app/src/main/java/com/cxsj/runhdu/Model/LoginModel.java
// Path: app/src/main/java/com/cxsj/runhdu/bean/gson/Status.java // public class Status { // @SerializedName("Result") // private boolean result; // // @SerializedName("Message") // private String message; // // @SerializedName("Which") // private int which; // // public boolean getResult() { // return result; // } // // public String getMessage() { // return message; // } // // public int getWhich() { // return which; // } // // } // // Path: app/src/main/java/com/cxsj/runhdu/constant/URLs.java // public class URLs { // public static final String DOWNLOAD = "http://d1.51gugu.com/170258/RunHDU"; // public static final String LOGIN = "http://112.74.115.231:8080/CXSJ/Login"; // public static final String REGISTER="http://112.74.115.231:8080/CXSJ/Register"; // public static final String GET_RUN_INFO = "http://112.74.115.231:8080/chuangxinshijian/ReadAll"; // public static final String UPLOAD_RUN_INFO = "http://112.74.115.231:8080/chuangxinshijian/Write"; // public static final String CLEAR_DATA = "http://112.74.115.231:8080/chuangxinshijian/ClearTheTable"; // public static final String UPDATE_URL = "http://112.74.115.231:8080/chuangxinshijian/VersionCompare"; // public static final String GET_RUN_TIMES = "http://112.74.115.231:8080/chuangxinshijian/ReadUserNameAndTimesOnly"; // public static final String UPLOAD_ALL_INFO = "http://112.74.115.231:8080/chuangxinshijian/WriteByJson"; // public static final String UPLOAD_PROFILE = "http://112.74.115.231:8080/CXSJ/UploadHead"; // public static final String PROFILE_URL = "http://112.74.115.231:8080/CXSJ/Image/"; // public static final String FEEDBACK_URL = "http://112.74.115.231:8080/chuangxinshijian/WriteFeedback"; // public static final String SUNNY_RUN_QUERY_API = "http://hdu.sunnysport.org.cn/api/student/achievements/"; // public static final String SUNNY_RUN_INFO_API = "http://hdu.sunnysport.org.cn/api/student/info/"; // public static final String DELETE_ITEM = "http://112.74.115.231:8080/chuangxinshijian/ClearByUserNameAndRunId"; // public static final String APPLY_FRIEND = "http://112.74.115.231:8080/CXSJ/Apply"; // public static final String REPLY_FRIEND = "http://112.74.115.231:8080/CXSJ/BeFriend"; // public static final String GET_FRIEND = "http://112.74.115.231:8080/CXSJ/MyFriends"; // public static final String DELETE_FRIEND = "http://112.74.115.231:8080/CXSJ/DeleteFriend"; // public static final String OFF_LINE = "http://112.74.115.231:8080/CXSJ/Xiaxian"; // } // // Path: app/src/main/java/com/cxsj/runhdu/utils/HttpUtil.java // public class HttpUtil { // private static RequestManager manager; // // public static RequestManager load(String url) { // manager = new RequestManager(); // manager.url(url); // return manager; // } // // public static class RequestManager { // private Request.Builder requestBuilder = new Request.Builder(); // private FormBody.Builder formBuilder = new FormBody.Builder(); // private Call call; // // private void url(String url) { // formBuilder = new FormBody.Builder(); // requestBuilder = new Request.Builder(); // // requestBuilder = requestBuilder.url(url); // } // // private void cancel() { // if (call != null) { // call.cancel(); // } // } // // public RequestManager addHeader(String key, String value) { // requestBuilder.addHeader(key, value); // return this; // } // // public RequestManager addParam(String key, String value) { // formBuilder = formBuilder.add(key, value); // return this; // } // // public void post(Callback callback) { // OkHttpClient client = new OkHttpClient.Builder() // .connectTimeout(3, TimeUnit.SECONDS) // .followRedirects(false) // .followSslRedirects(false) // .build(); // // Request request = requestBuilder.post(formBuilder.build()).build(); // client.newCall(request).enqueue(callback); // } // // public void get(Callback callback) { // OkHttpClient client = new OkHttpClient.Builder().build(); // Request request = requestBuilder.build(); // call = client.newCall(request); // call.enqueue(callback); // } // } // }
import com.cxsj.runhdu.bean.gson.Status; import com.cxsj.runhdu.constant.URLs; import com.cxsj.runhdu.utils.HttpUtil; import com.google.gson.Gson; import com.google.gson.JsonSyntaxException; import java.io.IOException; import okhttp3.Call; import okhttp3.Callback; import okhttp3.Response;
public void onFailure(Call call, IOException e) { mHandler.post(() -> callback.onLoginFailure(CONNECT_FAILED, 0)); } @Override public void onResponse(Call call, Response response) throws IOException { String json = response.body().string(); try { mHandler.post(() -> { Status status = null; status = new Gson().fromJson(json, Status.class); if (status == null) { callback.onLoginFailure(RETURN_DATA_ERROR, 0); } else { if (status.getResult()) { callback.onLoginSuccess(); } else { callback.onLoginFailure(status.getMessage(), status.getWhich()); } } }); } catch (JsonSyntaxException e) { callback.onLoginFailure(RETURN_DATA_ERROR, 0); e.printStackTrace(); } } }; } public static void login(String username, String passwordMD5, LoginCallback callback) {
// Path: app/src/main/java/com/cxsj/runhdu/bean/gson/Status.java // public class Status { // @SerializedName("Result") // private boolean result; // // @SerializedName("Message") // private String message; // // @SerializedName("Which") // private int which; // // public boolean getResult() { // return result; // } // // public String getMessage() { // return message; // } // // public int getWhich() { // return which; // } // // } // // Path: app/src/main/java/com/cxsj/runhdu/constant/URLs.java // public class URLs { // public static final String DOWNLOAD = "http://d1.51gugu.com/170258/RunHDU"; // public static final String LOGIN = "http://112.74.115.231:8080/CXSJ/Login"; // public static final String REGISTER="http://112.74.115.231:8080/CXSJ/Register"; // public static final String GET_RUN_INFO = "http://112.74.115.231:8080/chuangxinshijian/ReadAll"; // public static final String UPLOAD_RUN_INFO = "http://112.74.115.231:8080/chuangxinshijian/Write"; // public static final String CLEAR_DATA = "http://112.74.115.231:8080/chuangxinshijian/ClearTheTable"; // public static final String UPDATE_URL = "http://112.74.115.231:8080/chuangxinshijian/VersionCompare"; // public static final String GET_RUN_TIMES = "http://112.74.115.231:8080/chuangxinshijian/ReadUserNameAndTimesOnly"; // public static final String UPLOAD_ALL_INFO = "http://112.74.115.231:8080/chuangxinshijian/WriteByJson"; // public static final String UPLOAD_PROFILE = "http://112.74.115.231:8080/CXSJ/UploadHead"; // public static final String PROFILE_URL = "http://112.74.115.231:8080/CXSJ/Image/"; // public static final String FEEDBACK_URL = "http://112.74.115.231:8080/chuangxinshijian/WriteFeedback"; // public static final String SUNNY_RUN_QUERY_API = "http://hdu.sunnysport.org.cn/api/student/achievements/"; // public static final String SUNNY_RUN_INFO_API = "http://hdu.sunnysport.org.cn/api/student/info/"; // public static final String DELETE_ITEM = "http://112.74.115.231:8080/chuangxinshijian/ClearByUserNameAndRunId"; // public static final String APPLY_FRIEND = "http://112.74.115.231:8080/CXSJ/Apply"; // public static final String REPLY_FRIEND = "http://112.74.115.231:8080/CXSJ/BeFriend"; // public static final String GET_FRIEND = "http://112.74.115.231:8080/CXSJ/MyFriends"; // public static final String DELETE_FRIEND = "http://112.74.115.231:8080/CXSJ/DeleteFriend"; // public static final String OFF_LINE = "http://112.74.115.231:8080/CXSJ/Xiaxian"; // } // // Path: app/src/main/java/com/cxsj/runhdu/utils/HttpUtil.java // public class HttpUtil { // private static RequestManager manager; // // public static RequestManager load(String url) { // manager = new RequestManager(); // manager.url(url); // return manager; // } // // public static class RequestManager { // private Request.Builder requestBuilder = new Request.Builder(); // private FormBody.Builder formBuilder = new FormBody.Builder(); // private Call call; // // private void url(String url) { // formBuilder = new FormBody.Builder(); // requestBuilder = new Request.Builder(); // // requestBuilder = requestBuilder.url(url); // } // // private void cancel() { // if (call != null) { // call.cancel(); // } // } // // public RequestManager addHeader(String key, String value) { // requestBuilder.addHeader(key, value); // return this; // } // // public RequestManager addParam(String key, String value) { // formBuilder = formBuilder.add(key, value); // return this; // } // // public void post(Callback callback) { // OkHttpClient client = new OkHttpClient.Builder() // .connectTimeout(3, TimeUnit.SECONDS) // .followRedirects(false) // .followSslRedirects(false) // .build(); // // Request request = requestBuilder.post(formBuilder.build()).build(); // client.newCall(request).enqueue(callback); // } // // public void get(Callback callback) { // OkHttpClient client = new OkHttpClient.Builder().build(); // Request request = requestBuilder.build(); // call = client.newCall(request); // call.enqueue(callback); // } // } // } // Path: app/src/main/java/com/cxsj/runhdu/Model/LoginModel.java import com.cxsj.runhdu.bean.gson.Status; import com.cxsj.runhdu.constant.URLs; import com.cxsj.runhdu.utils.HttpUtil; import com.google.gson.Gson; import com.google.gson.JsonSyntaxException; import java.io.IOException; import okhttp3.Call; import okhttp3.Callback; import okhttp3.Response; public void onFailure(Call call, IOException e) { mHandler.post(() -> callback.onLoginFailure(CONNECT_FAILED, 0)); } @Override public void onResponse(Call call, Response response) throws IOException { String json = response.body().string(); try { mHandler.post(() -> { Status status = null; status = new Gson().fromJson(json, Status.class); if (status == null) { callback.onLoginFailure(RETURN_DATA_ERROR, 0); } else { if (status.getResult()) { callback.onLoginSuccess(); } else { callback.onLoginFailure(status.getMessage(), status.getWhich()); } } }); } catch (JsonSyntaxException e) { callback.onLoginFailure(RETURN_DATA_ERROR, 0); e.printStackTrace(); } } }; } public static void login(String username, String passwordMD5, LoginCallback callback) {
HttpUtil.load(URLs.LOGIN)
SailFlorve/RunHDU
app/src/main/java/com/cxsj/runhdu/bean/gson/Running.java
// Path: app/src/main/java/com/cxsj/runhdu/bean/sport/RunningInfo.java // public class RunningInfo extends DataSupport implements Serializable { // // // private String runId; // // private String runMode; // // private String year; // // private String month; // // private String date; // // private String startTime; // // private String duration; // // private int steps; // // private int distance; // // private int energy; // // private float speed; // // private String trailList; // // public RunningInfo() { // } // // public RunningInfo(String runId, // String runMode, // String year, // String month, // String date, // String startTime, // String duration, // int steps, // int distance, // int energy, // float speed, // String trailList) { // this.runId = runId; // this.runMode = runMode; // this.year = year; // this.month = month; // this.date = date; // this.startTime = startTime; // this.duration = duration; // this.steps = steps; // this.distance = distance; // this.energy = energy; // this.speed = speed; // this.trailList = ZipUtil.compress(trailList); // } // // public String getYear() { // return year; // } // // public void setYear(String year) { // this.year = year; // } // // public String getMonth() { // return month; // } // // public void setMonth(String month) { // this.month = month; // } // // public String getDate() { // return date; // } // // public void setDate(String date) { // this.date = date; // } // // public String getStartTime() { // return startTime; // } // // public void setStartTime(String startTime) { // this.startTime = startTime; // } // // public String getDuration() { // return duration; // } // // public void setDuration(String duration) { // this.duration = duration; // } // // public int getSteps() { // return steps; // } // // public void setSteps(int steps) { // this.steps = steps; // } // // public int getDistance() { // return distance; // } // // public void setDistance(int distance) { // this.distance = distance; // } // // public int getEnergy() { // return energy; // } // // public void setEnergy(int energy) { // this.energy = energy; // } // // public float getSpeed() { // return speed; // } // // public void setSpeed(float speed) { // this.speed = speed; // } // // public String getTrailList() { // return ZipUtil.decompress(trailList); // } // // public String getCompressedTrailList() { // return trailList; // } // // public void setTrailList(String trailList) { // this.trailList = ZipUtil.compress(trailList); // } // // public String getRunId() { // return runId; // } // // public void setRunId(String runId) { // this.runId = runId; // } // // public String getRunMode() { // return runMode; // } // // public void setRunMode(String runMode) { // this.runMode = runMode; // } // }
import com.cxsj.runhdu.bean.sport.RunningInfo; import com.google.gson.annotations.SerializedName; import java.util.List;
package com.cxsj.runhdu.bean.gson; /** * 获取跑步信息的json实体类 */ public class Running { @SerializedName("userName") public String username; public int times;
// Path: app/src/main/java/com/cxsj/runhdu/bean/sport/RunningInfo.java // public class RunningInfo extends DataSupport implements Serializable { // // // private String runId; // // private String runMode; // // private String year; // // private String month; // // private String date; // // private String startTime; // // private String duration; // // private int steps; // // private int distance; // // private int energy; // // private float speed; // // private String trailList; // // public RunningInfo() { // } // // public RunningInfo(String runId, // String runMode, // String year, // String month, // String date, // String startTime, // String duration, // int steps, // int distance, // int energy, // float speed, // String trailList) { // this.runId = runId; // this.runMode = runMode; // this.year = year; // this.month = month; // this.date = date; // this.startTime = startTime; // this.duration = duration; // this.steps = steps; // this.distance = distance; // this.energy = energy; // this.speed = speed; // this.trailList = ZipUtil.compress(trailList); // } // // public String getYear() { // return year; // } // // public void setYear(String year) { // this.year = year; // } // // public String getMonth() { // return month; // } // // public void setMonth(String month) { // this.month = month; // } // // public String getDate() { // return date; // } // // public void setDate(String date) { // this.date = date; // } // // public String getStartTime() { // return startTime; // } // // public void setStartTime(String startTime) { // this.startTime = startTime; // } // // public String getDuration() { // return duration; // } // // public void setDuration(String duration) { // this.duration = duration; // } // // public int getSteps() { // return steps; // } // // public void setSteps(int steps) { // this.steps = steps; // } // // public int getDistance() { // return distance; // } // // public void setDistance(int distance) { // this.distance = distance; // } // // public int getEnergy() { // return energy; // } // // public void setEnergy(int energy) { // this.energy = energy; // } // // public float getSpeed() { // return speed; // } // // public void setSpeed(float speed) { // this.speed = speed; // } // // public String getTrailList() { // return ZipUtil.decompress(trailList); // } // // public String getCompressedTrailList() { // return trailList; // } // // public void setTrailList(String trailList) { // this.trailList = ZipUtil.compress(trailList); // } // // public String getRunId() { // return runId; // } // // public void setRunId(String runId) { // this.runId = runId; // } // // public String getRunMode() { // return runMode; // } // // public void setRunMode(String runMode) { // this.runMode = runMode; // } // } // Path: app/src/main/java/com/cxsj/runhdu/bean/gson/Running.java import com.cxsj.runhdu.bean.sport.RunningInfo; import com.google.gson.annotations.SerializedName; import java.util.List; package com.cxsj.runhdu.bean.gson; /** * 获取跑步信息的json实体类 */ public class Running { @SerializedName("userName") public String username; public int times;
public List<RunningInfo> dataList;
SailFlorve/RunHDU
app/src/main/java/com/cxsj/runhdu/utils/Utility.java
// Path: app/src/main/java/com/cxsj/runhdu/constant/Types.java // public class Types { // public final static int TYPE_YEAR = 1000; // public final static int TYPE_MONTH = 1001; // public final static int TYPE_DATE = 1002; // public final static int TYPE_HOUR = 1003; // public final static int TYPE_MINUTE = 1004; // public final static int TYPE_SECOND = 1005; // public final static int TYPE_MONTH_DATE = 1006; // public final static int TYPE_CURRENT_TIME = 1007; // public final static int TYPE_AM_PM = 1008; // public final static int TYPE_CHANGE_PROFILE = 1009; // public final static int TYPE_CHANGE_MENU_BG = 1010; // public final static int MANUAL_UPDATE = 1011; // public final static int AUTO_UPDATE = 1012; // public final static int TYPE_SAVE_PROFILE = 1013; // public final static int TYPE_STRING_FORM=1014; // } // // Path: app/src/main/java/com/cxsj/runhdu/constant/URLs.java // public class URLs { // public static final String DOWNLOAD = "http://d1.51gugu.com/170258/RunHDU"; // public static final String LOGIN = "http://112.74.115.231:8080/CXSJ/Login"; // public static final String REGISTER="http://112.74.115.231:8080/CXSJ/Register"; // public static final String GET_RUN_INFO = "http://112.74.115.231:8080/chuangxinshijian/ReadAll"; // public static final String UPLOAD_RUN_INFO = "http://112.74.115.231:8080/chuangxinshijian/Write"; // public static final String CLEAR_DATA = "http://112.74.115.231:8080/chuangxinshijian/ClearTheTable"; // public static final String UPDATE_URL = "http://112.74.115.231:8080/chuangxinshijian/VersionCompare"; // public static final String GET_RUN_TIMES = "http://112.74.115.231:8080/chuangxinshijian/ReadUserNameAndTimesOnly"; // public static final String UPLOAD_ALL_INFO = "http://112.74.115.231:8080/chuangxinshijian/WriteByJson"; // public static final String UPLOAD_PROFILE = "http://112.74.115.231:8080/CXSJ/UploadHead"; // public static final String PROFILE_URL = "http://112.74.115.231:8080/CXSJ/Image/"; // public static final String FEEDBACK_URL = "http://112.74.115.231:8080/chuangxinshijian/WriteFeedback"; // public static final String SUNNY_RUN_QUERY_API = "http://hdu.sunnysport.org.cn/api/student/achievements/"; // public static final String SUNNY_RUN_INFO_API = "http://hdu.sunnysport.org.cn/api/student/info/"; // public static final String DELETE_ITEM = "http://112.74.115.231:8080/chuangxinshijian/ClearByUserNameAndRunId"; // public static final String APPLY_FRIEND = "http://112.74.115.231:8080/CXSJ/Apply"; // public static final String REPLY_FRIEND = "http://112.74.115.231:8080/CXSJ/BeFriend"; // public static final String GET_FRIEND = "http://112.74.115.231:8080/CXSJ/MyFriends"; // public static final String DELETE_FRIEND = "http://112.74.115.231:8080/CXSJ/DeleteFriend"; // public static final String OFF_LINE = "http://112.74.115.231:8080/CXSJ/Xiaxian"; // }
import android.annotation.SuppressLint; import android.content.Context; import android.content.pm.PackageManager; import android.content.res.Resources; import android.location.LocationManager; import android.net.ConnectivityManager; import android.net.NetworkInfo; import android.net.Uri; import android.telephony.TelephonyManager; import android.widget.ImageView; import android.widget.Toast; import com.baidu.mapapi.model.LatLng; import com.baidu.mapapi.utils.DistanceUtil; import com.bumptech.glide.Glide; import com.bumptech.glide.signature.StringSignature; import com.cxsj.runhdu.R; import com.cxsj.runhdu.constant.Types; import com.cxsj.runhdu.constant.URLs; import java.text.SimpleDateFormat; import java.util.Calendar; import java.util.Date; import java.util.List; import java.util.Locale;
/** * @param d 需要处理的数字 * @param num 保留位数(只能是1或者2) * @return 保留num位小数后的字符串 */ public static String formatDecimal(double d, int num) { if (num == 2) { return String.format("%.2f", d); } else { return String.format("%.1f", d); } } /** * 获取特定类型的时间的字符串表示 * * @param type 获取的时间类型, * Types.TYPE_AM_PM:返回上午/下午/晚上 * Types.TYPE_MONTH_DATE:返回日期,例如2月15日 * Types.TYPE_CURRENT_TIME:返回时间,例如18:23 * 其他类型:Calendar.TYPE * @return 类型字符串 */ @SuppressLint("WrongConstant") public static String getTime(int type) { Calendar calendar = Calendar.getInstance(); calendar.setTime(new Date()); switch (type) {
// Path: app/src/main/java/com/cxsj/runhdu/constant/Types.java // public class Types { // public final static int TYPE_YEAR = 1000; // public final static int TYPE_MONTH = 1001; // public final static int TYPE_DATE = 1002; // public final static int TYPE_HOUR = 1003; // public final static int TYPE_MINUTE = 1004; // public final static int TYPE_SECOND = 1005; // public final static int TYPE_MONTH_DATE = 1006; // public final static int TYPE_CURRENT_TIME = 1007; // public final static int TYPE_AM_PM = 1008; // public final static int TYPE_CHANGE_PROFILE = 1009; // public final static int TYPE_CHANGE_MENU_BG = 1010; // public final static int MANUAL_UPDATE = 1011; // public final static int AUTO_UPDATE = 1012; // public final static int TYPE_SAVE_PROFILE = 1013; // public final static int TYPE_STRING_FORM=1014; // } // // Path: app/src/main/java/com/cxsj/runhdu/constant/URLs.java // public class URLs { // public static final String DOWNLOAD = "http://d1.51gugu.com/170258/RunHDU"; // public static final String LOGIN = "http://112.74.115.231:8080/CXSJ/Login"; // public static final String REGISTER="http://112.74.115.231:8080/CXSJ/Register"; // public static final String GET_RUN_INFO = "http://112.74.115.231:8080/chuangxinshijian/ReadAll"; // public static final String UPLOAD_RUN_INFO = "http://112.74.115.231:8080/chuangxinshijian/Write"; // public static final String CLEAR_DATA = "http://112.74.115.231:8080/chuangxinshijian/ClearTheTable"; // public static final String UPDATE_URL = "http://112.74.115.231:8080/chuangxinshijian/VersionCompare"; // public static final String GET_RUN_TIMES = "http://112.74.115.231:8080/chuangxinshijian/ReadUserNameAndTimesOnly"; // public static final String UPLOAD_ALL_INFO = "http://112.74.115.231:8080/chuangxinshijian/WriteByJson"; // public static final String UPLOAD_PROFILE = "http://112.74.115.231:8080/CXSJ/UploadHead"; // public static final String PROFILE_URL = "http://112.74.115.231:8080/CXSJ/Image/"; // public static final String FEEDBACK_URL = "http://112.74.115.231:8080/chuangxinshijian/WriteFeedback"; // public static final String SUNNY_RUN_QUERY_API = "http://hdu.sunnysport.org.cn/api/student/achievements/"; // public static final String SUNNY_RUN_INFO_API = "http://hdu.sunnysport.org.cn/api/student/info/"; // public static final String DELETE_ITEM = "http://112.74.115.231:8080/chuangxinshijian/ClearByUserNameAndRunId"; // public static final String APPLY_FRIEND = "http://112.74.115.231:8080/CXSJ/Apply"; // public static final String REPLY_FRIEND = "http://112.74.115.231:8080/CXSJ/BeFriend"; // public static final String GET_FRIEND = "http://112.74.115.231:8080/CXSJ/MyFriends"; // public static final String DELETE_FRIEND = "http://112.74.115.231:8080/CXSJ/DeleteFriend"; // public static final String OFF_LINE = "http://112.74.115.231:8080/CXSJ/Xiaxian"; // } // Path: app/src/main/java/com/cxsj/runhdu/utils/Utility.java import android.annotation.SuppressLint; import android.content.Context; import android.content.pm.PackageManager; import android.content.res.Resources; import android.location.LocationManager; import android.net.ConnectivityManager; import android.net.NetworkInfo; import android.net.Uri; import android.telephony.TelephonyManager; import android.widget.ImageView; import android.widget.Toast; import com.baidu.mapapi.model.LatLng; import com.baidu.mapapi.utils.DistanceUtil; import com.bumptech.glide.Glide; import com.bumptech.glide.signature.StringSignature; import com.cxsj.runhdu.R; import com.cxsj.runhdu.constant.Types; import com.cxsj.runhdu.constant.URLs; import java.text.SimpleDateFormat; import java.util.Calendar; import java.util.Date; import java.util.List; import java.util.Locale; /** * @param d 需要处理的数字 * @param num 保留位数(只能是1或者2) * @return 保留num位小数后的字符串 */ public static String formatDecimal(double d, int num) { if (num == 2) { return String.format("%.2f", d); } else { return String.format("%.1f", d); } } /** * 获取特定类型的时间的字符串表示 * * @param type 获取的时间类型, * Types.TYPE_AM_PM:返回上午/下午/晚上 * Types.TYPE_MONTH_DATE:返回日期,例如2月15日 * Types.TYPE_CURRENT_TIME:返回时间,例如18:23 * 其他类型:Calendar.TYPE * @return 类型字符串 */ @SuppressLint("WrongConstant") public static String getTime(int type) { Calendar calendar = Calendar.getInstance(); calendar.setTime(new Date()); switch (type) {
case Types.TYPE_AM_PM:
SailFlorve/RunHDU
app/src/main/java/com/cxsj/runhdu/utils/Utility.java
// Path: app/src/main/java/com/cxsj/runhdu/constant/Types.java // public class Types { // public final static int TYPE_YEAR = 1000; // public final static int TYPE_MONTH = 1001; // public final static int TYPE_DATE = 1002; // public final static int TYPE_HOUR = 1003; // public final static int TYPE_MINUTE = 1004; // public final static int TYPE_SECOND = 1005; // public final static int TYPE_MONTH_DATE = 1006; // public final static int TYPE_CURRENT_TIME = 1007; // public final static int TYPE_AM_PM = 1008; // public final static int TYPE_CHANGE_PROFILE = 1009; // public final static int TYPE_CHANGE_MENU_BG = 1010; // public final static int MANUAL_UPDATE = 1011; // public final static int AUTO_UPDATE = 1012; // public final static int TYPE_SAVE_PROFILE = 1013; // public final static int TYPE_STRING_FORM=1014; // } // // Path: app/src/main/java/com/cxsj/runhdu/constant/URLs.java // public class URLs { // public static final String DOWNLOAD = "http://d1.51gugu.com/170258/RunHDU"; // public static final String LOGIN = "http://112.74.115.231:8080/CXSJ/Login"; // public static final String REGISTER="http://112.74.115.231:8080/CXSJ/Register"; // public static final String GET_RUN_INFO = "http://112.74.115.231:8080/chuangxinshijian/ReadAll"; // public static final String UPLOAD_RUN_INFO = "http://112.74.115.231:8080/chuangxinshijian/Write"; // public static final String CLEAR_DATA = "http://112.74.115.231:8080/chuangxinshijian/ClearTheTable"; // public static final String UPDATE_URL = "http://112.74.115.231:8080/chuangxinshijian/VersionCompare"; // public static final String GET_RUN_TIMES = "http://112.74.115.231:8080/chuangxinshijian/ReadUserNameAndTimesOnly"; // public static final String UPLOAD_ALL_INFO = "http://112.74.115.231:8080/chuangxinshijian/WriteByJson"; // public static final String UPLOAD_PROFILE = "http://112.74.115.231:8080/CXSJ/UploadHead"; // public static final String PROFILE_URL = "http://112.74.115.231:8080/CXSJ/Image/"; // public static final String FEEDBACK_URL = "http://112.74.115.231:8080/chuangxinshijian/WriteFeedback"; // public static final String SUNNY_RUN_QUERY_API = "http://hdu.sunnysport.org.cn/api/student/achievements/"; // public static final String SUNNY_RUN_INFO_API = "http://hdu.sunnysport.org.cn/api/student/info/"; // public static final String DELETE_ITEM = "http://112.74.115.231:8080/chuangxinshijian/ClearByUserNameAndRunId"; // public static final String APPLY_FRIEND = "http://112.74.115.231:8080/CXSJ/Apply"; // public static final String REPLY_FRIEND = "http://112.74.115.231:8080/CXSJ/BeFriend"; // public static final String GET_FRIEND = "http://112.74.115.231:8080/CXSJ/MyFriends"; // public static final String DELETE_FRIEND = "http://112.74.115.231:8080/CXSJ/DeleteFriend"; // public static final String OFF_LINE = "http://112.74.115.231:8080/CXSJ/Xiaxian"; // }
import android.annotation.SuppressLint; import android.content.Context; import android.content.pm.PackageManager; import android.content.res.Resources; import android.location.LocationManager; import android.net.ConnectivityManager; import android.net.NetworkInfo; import android.net.Uri; import android.telephony.TelephonyManager; import android.widget.ImageView; import android.widget.Toast; import com.baidu.mapapi.model.LatLng; import com.baidu.mapapi.utils.DistanceUtil; import com.bumptech.glide.Glide; import com.bumptech.glide.signature.StringSignature; import com.cxsj.runhdu.R; import com.cxsj.runhdu.constant.Types; import com.cxsj.runhdu.constant.URLs; import java.text.SimpleDateFormat; import java.util.Calendar; import java.util.Date; import java.util.List; import java.util.Locale;
} else { return "晚上"; } case Types.TYPE_MONTH_DATE: return new SimpleDateFormat("M月d日", Locale.getDefault()).format(new Date()); case Types.TYPE_CURRENT_TIME: return new SimpleDateFormat("HH:mm", Locale.getDefault()).format(new Date()); case Types.TYPE_MONTH: return String.valueOf(calendar.get(Calendar.MONTH) + 1); case Types.TYPE_STRING_FORM: return new SimpleDateFormat("yyyyMMddHHmmss", Locale.getDefault()).format(new Date()); default: return String.valueOf(calendar.get(type)); } } /** * 返回计时器时间字符串的分钟数量。 * * @return 两个时间间隔的分钟数 */ public static int getMinutes(String time) { String[] times = time.split(":"); int minutes = Integer.parseInt(times[1]); int hours = Integer.parseInt(times[0]); int seconds = Integer.parseInt(times[2]); return hours * 60 + minutes + seconds / 60; } public static Uri getDownloadUri(String latestVersion) {
// Path: app/src/main/java/com/cxsj/runhdu/constant/Types.java // public class Types { // public final static int TYPE_YEAR = 1000; // public final static int TYPE_MONTH = 1001; // public final static int TYPE_DATE = 1002; // public final static int TYPE_HOUR = 1003; // public final static int TYPE_MINUTE = 1004; // public final static int TYPE_SECOND = 1005; // public final static int TYPE_MONTH_DATE = 1006; // public final static int TYPE_CURRENT_TIME = 1007; // public final static int TYPE_AM_PM = 1008; // public final static int TYPE_CHANGE_PROFILE = 1009; // public final static int TYPE_CHANGE_MENU_BG = 1010; // public final static int MANUAL_UPDATE = 1011; // public final static int AUTO_UPDATE = 1012; // public final static int TYPE_SAVE_PROFILE = 1013; // public final static int TYPE_STRING_FORM=1014; // } // // Path: app/src/main/java/com/cxsj/runhdu/constant/URLs.java // public class URLs { // public static final String DOWNLOAD = "http://d1.51gugu.com/170258/RunHDU"; // public static final String LOGIN = "http://112.74.115.231:8080/CXSJ/Login"; // public static final String REGISTER="http://112.74.115.231:8080/CXSJ/Register"; // public static final String GET_RUN_INFO = "http://112.74.115.231:8080/chuangxinshijian/ReadAll"; // public static final String UPLOAD_RUN_INFO = "http://112.74.115.231:8080/chuangxinshijian/Write"; // public static final String CLEAR_DATA = "http://112.74.115.231:8080/chuangxinshijian/ClearTheTable"; // public static final String UPDATE_URL = "http://112.74.115.231:8080/chuangxinshijian/VersionCompare"; // public static final String GET_RUN_TIMES = "http://112.74.115.231:8080/chuangxinshijian/ReadUserNameAndTimesOnly"; // public static final String UPLOAD_ALL_INFO = "http://112.74.115.231:8080/chuangxinshijian/WriteByJson"; // public static final String UPLOAD_PROFILE = "http://112.74.115.231:8080/CXSJ/UploadHead"; // public static final String PROFILE_URL = "http://112.74.115.231:8080/CXSJ/Image/"; // public static final String FEEDBACK_URL = "http://112.74.115.231:8080/chuangxinshijian/WriteFeedback"; // public static final String SUNNY_RUN_QUERY_API = "http://hdu.sunnysport.org.cn/api/student/achievements/"; // public static final String SUNNY_RUN_INFO_API = "http://hdu.sunnysport.org.cn/api/student/info/"; // public static final String DELETE_ITEM = "http://112.74.115.231:8080/chuangxinshijian/ClearByUserNameAndRunId"; // public static final String APPLY_FRIEND = "http://112.74.115.231:8080/CXSJ/Apply"; // public static final String REPLY_FRIEND = "http://112.74.115.231:8080/CXSJ/BeFriend"; // public static final String GET_FRIEND = "http://112.74.115.231:8080/CXSJ/MyFriends"; // public static final String DELETE_FRIEND = "http://112.74.115.231:8080/CXSJ/DeleteFriend"; // public static final String OFF_LINE = "http://112.74.115.231:8080/CXSJ/Xiaxian"; // } // Path: app/src/main/java/com/cxsj/runhdu/utils/Utility.java import android.annotation.SuppressLint; import android.content.Context; import android.content.pm.PackageManager; import android.content.res.Resources; import android.location.LocationManager; import android.net.ConnectivityManager; import android.net.NetworkInfo; import android.net.Uri; import android.telephony.TelephonyManager; import android.widget.ImageView; import android.widget.Toast; import com.baidu.mapapi.model.LatLng; import com.baidu.mapapi.utils.DistanceUtil; import com.bumptech.glide.Glide; import com.bumptech.glide.signature.StringSignature; import com.cxsj.runhdu.R; import com.cxsj.runhdu.constant.Types; import com.cxsj.runhdu.constant.URLs; import java.text.SimpleDateFormat; import java.util.Calendar; import java.util.Date; import java.util.List; import java.util.Locale; } else { return "晚上"; } case Types.TYPE_MONTH_DATE: return new SimpleDateFormat("M月d日", Locale.getDefault()).format(new Date()); case Types.TYPE_CURRENT_TIME: return new SimpleDateFormat("HH:mm", Locale.getDefault()).format(new Date()); case Types.TYPE_MONTH: return String.valueOf(calendar.get(Calendar.MONTH) + 1); case Types.TYPE_STRING_FORM: return new SimpleDateFormat("yyyyMMddHHmmss", Locale.getDefault()).format(new Date()); default: return String.valueOf(calendar.get(type)); } } /** * 返回计时器时间字符串的分钟数量。 * * @return 两个时间间隔的分钟数 */ public static int getMinutes(String time) { String[] times = time.split(":"); int minutes = Integer.parseInt(times[1]); int hours = Integer.parseInt(times[0]); int seconds = Integer.parseInt(times[2]); return hours * 60 + minutes + seconds / 60; } public static Uri getDownloadUri(String latestVersion) {
return Uri.parse(URLs.DOWNLOAD + latestVersion.replace(".", "") + ".apk");
SailFlorve/RunHDU
app/src/main/java/com/cxsj/runhdu/bean/sport/RunningInfo.java
// Path: app/src/main/java/com/cxsj/runhdu/utils/ZipUtil.java // public class ZipUtil { // /** // * Gzip 压缩数据 // * // * @param unGzipStr // * @return // */ // public static String compress(String unGzipStr) { // // if (TextUtils.isEmpty(unGzipStr)) { // return "0"; // } // try { // ByteArrayOutputStream baos = new ByteArrayOutputStream(); // GZIPOutputStream gzip = new GZIPOutputStream(baos); // gzip.write(unGzipStr.getBytes()); // gzip.close(); // byte[] encode = baos.toByteArray(); // baos.flush(); // baos.close(); // return Base64.encodeToString(encode, Base64.DEFAULT); // } catch (UnsupportedEncodingException e) { // e.printStackTrace(); // } catch (IOException e) { // e.printStackTrace(); // } // // return "0"; // } // // /** // * Gzip解压数据 // * // * @param gzipStr // * @return // */ // public static String decompress(String gzipStr) { // if (TextUtils.isEmpty(gzipStr)) { // return null; // } // byte[] t; // try { // t = Base64.decode(gzipStr, Base64.DEFAULT); // } catch (Exception e) { // e.printStackTrace(); // return "0"; // } // try { // ByteArrayOutputStream out = new ByteArrayOutputStream(); // ByteArrayInputStream in = new ByteArrayInputStream(t); // GZIPInputStream gzip = new GZIPInputStream(in); // byte[] buffer = new byte[1024]; // int n; // while ((n = gzip.read(buffer, 0, buffer.length)) > 0) { // out.write(buffer, 0, n); // } // gzip.close(); // in.close(); // out.close(); // return out.toString(); // } catch (IOException e) { // e.printStackTrace(); // return "0"; // } // } // // /** // * Zip 压缩数据 // * // * @param unZipStr // * @return // */ // public static String compressForZip(String unZipStr) { // // if (TextUtils.isEmpty(unZipStr)) { // return "0"; // } // try { // ByteArrayOutputStream baos = new ByteArrayOutputStream(); // ZipOutputStream zip = new ZipOutputStream(baos); // zip.putNextEntry(new ZipEntry("0")); // zip.write(unZipStr.getBytes()); // zip.closeEntry(); // zip.close(); // byte[] encode = baos.toByteArray(); // baos.flush(); // baos.close(); // return Base64.encodeToString(encode, Base64.DEFAULT); // } catch (UnsupportedEncodingException e) { // e.printStackTrace(); // } catch (IOException e) { // e.printStackTrace(); // } // // return "0"; // } // // /** // * Zip解压数据 // * // * @param zipStr // * @return // */ // public static String decompressForZip(String zipStr) { // // if (TextUtils.isEmpty(zipStr)) { // return "0"; // } // byte[] t = Base64.decode(zipStr, Base64.DEFAULT); // try { // ByteArrayOutputStream out = new ByteArrayOutputStream(); // ByteArrayInputStream in = new ByteArrayInputStream(t); // ZipInputStream zip = new ZipInputStream(in); // zip.getNextEntry(); // byte[] buffer = new byte[1024]; // int n = 0; // while ((n = zip.read(buffer, 0, buffer.length)) > 0) { // out.write(buffer, 0, n); // } // zip.close(); // in.close(); // out.close(); // return out.toString(); // } catch (IOException e) { // e.printStackTrace(); // } // return "0"; // } // }
import com.cxsj.runhdu.utils.ZipUtil; import org.litepal.crud.DataSupport; import java.io.Serializable;
private float speed; private String trailList; public RunningInfo() { } public RunningInfo(String runId, String runMode, String year, String month, String date, String startTime, String duration, int steps, int distance, int energy, float speed, String trailList) { this.runId = runId; this.runMode = runMode; this.year = year; this.month = month; this.date = date; this.startTime = startTime; this.duration = duration; this.steps = steps; this.distance = distance; this.energy = energy; this.speed = speed;
// Path: app/src/main/java/com/cxsj/runhdu/utils/ZipUtil.java // public class ZipUtil { // /** // * Gzip 压缩数据 // * // * @param unGzipStr // * @return // */ // public static String compress(String unGzipStr) { // // if (TextUtils.isEmpty(unGzipStr)) { // return "0"; // } // try { // ByteArrayOutputStream baos = new ByteArrayOutputStream(); // GZIPOutputStream gzip = new GZIPOutputStream(baos); // gzip.write(unGzipStr.getBytes()); // gzip.close(); // byte[] encode = baos.toByteArray(); // baos.flush(); // baos.close(); // return Base64.encodeToString(encode, Base64.DEFAULT); // } catch (UnsupportedEncodingException e) { // e.printStackTrace(); // } catch (IOException e) { // e.printStackTrace(); // } // // return "0"; // } // // /** // * Gzip解压数据 // * // * @param gzipStr // * @return // */ // public static String decompress(String gzipStr) { // if (TextUtils.isEmpty(gzipStr)) { // return null; // } // byte[] t; // try { // t = Base64.decode(gzipStr, Base64.DEFAULT); // } catch (Exception e) { // e.printStackTrace(); // return "0"; // } // try { // ByteArrayOutputStream out = new ByteArrayOutputStream(); // ByteArrayInputStream in = new ByteArrayInputStream(t); // GZIPInputStream gzip = new GZIPInputStream(in); // byte[] buffer = new byte[1024]; // int n; // while ((n = gzip.read(buffer, 0, buffer.length)) > 0) { // out.write(buffer, 0, n); // } // gzip.close(); // in.close(); // out.close(); // return out.toString(); // } catch (IOException e) { // e.printStackTrace(); // return "0"; // } // } // // /** // * Zip 压缩数据 // * // * @param unZipStr // * @return // */ // public static String compressForZip(String unZipStr) { // // if (TextUtils.isEmpty(unZipStr)) { // return "0"; // } // try { // ByteArrayOutputStream baos = new ByteArrayOutputStream(); // ZipOutputStream zip = new ZipOutputStream(baos); // zip.putNextEntry(new ZipEntry("0")); // zip.write(unZipStr.getBytes()); // zip.closeEntry(); // zip.close(); // byte[] encode = baos.toByteArray(); // baos.flush(); // baos.close(); // return Base64.encodeToString(encode, Base64.DEFAULT); // } catch (UnsupportedEncodingException e) { // e.printStackTrace(); // } catch (IOException e) { // e.printStackTrace(); // } // // return "0"; // } // // /** // * Zip解压数据 // * // * @param zipStr // * @return // */ // public static String decompressForZip(String zipStr) { // // if (TextUtils.isEmpty(zipStr)) { // return "0"; // } // byte[] t = Base64.decode(zipStr, Base64.DEFAULT); // try { // ByteArrayOutputStream out = new ByteArrayOutputStream(); // ByteArrayInputStream in = new ByteArrayInputStream(t); // ZipInputStream zip = new ZipInputStream(in); // zip.getNextEntry(); // byte[] buffer = new byte[1024]; // int n = 0; // while ((n = zip.read(buffer, 0, buffer.length)) > 0) { // out.write(buffer, 0, n); // } // zip.close(); // in.close(); // out.close(); // return out.toString(); // } catch (IOException e) { // e.printStackTrace(); // } // return "0"; // } // } // Path: app/src/main/java/com/cxsj/runhdu/bean/sport/RunningInfo.java import com.cxsj.runhdu.utils.ZipUtil; import org.litepal.crud.DataSupport; import java.io.Serializable; private float speed; private String trailList; public RunningInfo() { } public RunningInfo(String runId, String runMode, String year, String month, String date, String startTime, String duration, int steps, int distance, int energy, float speed, String trailList) { this.runId = runId; this.runMode = runMode; this.year = year; this.month = month; this.date = date; this.startTime = startTime; this.duration = duration; this.steps = steps; this.distance = distance; this.energy = energy; this.speed = speed;
this.trailList = ZipUtil.compress(trailList);
SailFlorve/RunHDU
app/src/main/java/com/cxsj/runhdu/WelcomeActivity.java
// Path: app/src/main/java/com/cxsj/runhdu/Model/LoginModel.java // public class LoginModel extends BaseModel { // public interface LoginCallback { // void onLoginSuccess(); // // void onLoginFailure(String msg, int which); // } // // private static Callback getCallback(LoginCallback callback) { // return new Callback() { // @Override // public void onFailure(Call call, IOException e) { // mHandler.post(() -> callback.onLoginFailure(CONNECT_FAILED, 0)); // } // // @Override // public void onResponse(Call call, Response response) throws IOException { // String json = response.body().string(); // try { // mHandler.post(() -> { // Status status = null; // status = new Gson().fromJson(json, Status.class); // if (status == null) { // callback.onLoginFailure(RETURN_DATA_ERROR, 0); // } else { // if (status.getResult()) { // callback.onLoginSuccess(); // } else { // callback.onLoginFailure(status.getMessage(), status.getWhich()); // } // } // }); // } catch (JsonSyntaxException e) { // callback.onLoginFailure(RETURN_DATA_ERROR, 0); // e.printStackTrace(); // } // } // }; // } // // public static void login(String username, String passwordMD5, LoginCallback callback) { // HttpUtil.load(URLs.LOGIN) // .addParam("name", username) // .addParam("password", passwordMD5) // .post(getCallback(callback)); // } // // public static void register(String username, String passwordMD5, LoginCallback callback) { // HttpUtil.load(URLs.REGISTER) // //传加密后的用户名and密码 // .addParam("name", username) // .addParam("password", passwordMD5) // .post(getCallback(callback)); // } // } // // Path: app/src/main/java/com/cxsj/runhdu/utils/ActivityManager.java // public class ActivityManager { // // private static String TAG = "ActivityManager"; // private static List<Activity> activities = new ArrayList<>(); // // public static void addActivity(Activity activity) { // Log.d(TAG, "addActivity: "+activity.getLocalClassName()); // activities.add(activity); // } // // public static void removeActivity(Activity activity) { // if (activity != null) { // Log.d(TAG, "removeActivity: "+activity.getLocalClassName()); // activities.remove(activity); // } // } // // public static void finishAll() { // for (Activity activity : activities) { // if (activity != null) { // Log.d(TAG, "finishAll: " + activity.getLocalClassName()); // activity.finish(); // } // } // } // } // // Path: app/src/main/java/com/cxsj/runhdu/utils/AnimationUtil.java // public class AnimationUtil { // private static final String TAG = AnimationUtil.class.getSimpleName(); // // /** // * 从控件所在位置移动到控件的底部 // * // * @return // */ // public static TranslateAnimation moveToViewBottom() { // TranslateAnimation mHiddenAction = new TranslateAnimation(Animation.RELATIVE_TO_SELF, 0.0f, // Animation.RELATIVE_TO_SELF, 0.0f, Animation.RELATIVE_TO_SELF, // 0.0f, Animation.RELATIVE_TO_SELF, 5.0f); // mHiddenAction.setDuration(2500); // return mHiddenAction; // } // // /** // * 从控件的底部移动到控件所在位置 // * // * @return // */ // public static TranslateAnimation moveToViewLocation() { // TranslateAnimation mHiddenAction = new TranslateAnimation(Animation.RELATIVE_TO_SELF, 0.0f, // Animation.RELATIVE_TO_SELF, 0.0f, Animation.RELATIVE_TO_SELF, // 5.0f, Animation.RELATIVE_TO_SELF, 0.0f); // mHiddenAction.setDuration(1500); // return mHiddenAction; // } // // }
import android.os.Bundle; import android.text.TextUtils; import android.util.Log; import android.view.View; import android.widget.Button; import android.widget.Toast; import com.cxsj.runhdu.Model.LoginModel; import com.cxsj.runhdu.utils.ActivityManager; import com.cxsj.runhdu.utils.AnimationUtil;
setContentView(R.layout.activity_welcome); loginButton = (Button) findViewById(R.id.welcome_login_button); registerButton = (Button) findViewById(R.id.welcome_register_button); //用户名不为空时,执行登录,跳转到MainActivity if (!TextUtils.isEmpty(username)) { doLogin(); } else { showButtons(); } loginButton.setOnClickListener(v -> toActivity(WelcomeActivity.this, LoginActivity.class)); registerButton.setOnClickListener(v -> toActivity(WelcomeActivity.this, RegisterActivity.class)); } @Override public void onBackPressed() { if (loginButton.getVisibility() != View.GONE) { super.onBackPressed(); } } //显示登录注册按钮 private void showButtons() { loginButton.setVisibility(View.VISIBLE); registerButton.setVisibility(View.VISIBLE);
// Path: app/src/main/java/com/cxsj/runhdu/Model/LoginModel.java // public class LoginModel extends BaseModel { // public interface LoginCallback { // void onLoginSuccess(); // // void onLoginFailure(String msg, int which); // } // // private static Callback getCallback(LoginCallback callback) { // return new Callback() { // @Override // public void onFailure(Call call, IOException e) { // mHandler.post(() -> callback.onLoginFailure(CONNECT_FAILED, 0)); // } // // @Override // public void onResponse(Call call, Response response) throws IOException { // String json = response.body().string(); // try { // mHandler.post(() -> { // Status status = null; // status = new Gson().fromJson(json, Status.class); // if (status == null) { // callback.onLoginFailure(RETURN_DATA_ERROR, 0); // } else { // if (status.getResult()) { // callback.onLoginSuccess(); // } else { // callback.onLoginFailure(status.getMessage(), status.getWhich()); // } // } // }); // } catch (JsonSyntaxException e) { // callback.onLoginFailure(RETURN_DATA_ERROR, 0); // e.printStackTrace(); // } // } // }; // } // // public static void login(String username, String passwordMD5, LoginCallback callback) { // HttpUtil.load(URLs.LOGIN) // .addParam("name", username) // .addParam("password", passwordMD5) // .post(getCallback(callback)); // } // // public static void register(String username, String passwordMD5, LoginCallback callback) { // HttpUtil.load(URLs.REGISTER) // //传加密后的用户名and密码 // .addParam("name", username) // .addParam("password", passwordMD5) // .post(getCallback(callback)); // } // } // // Path: app/src/main/java/com/cxsj/runhdu/utils/ActivityManager.java // public class ActivityManager { // // private static String TAG = "ActivityManager"; // private static List<Activity> activities = new ArrayList<>(); // // public static void addActivity(Activity activity) { // Log.d(TAG, "addActivity: "+activity.getLocalClassName()); // activities.add(activity); // } // // public static void removeActivity(Activity activity) { // if (activity != null) { // Log.d(TAG, "removeActivity: "+activity.getLocalClassName()); // activities.remove(activity); // } // } // // public static void finishAll() { // for (Activity activity : activities) { // if (activity != null) { // Log.d(TAG, "finishAll: " + activity.getLocalClassName()); // activity.finish(); // } // } // } // } // // Path: app/src/main/java/com/cxsj/runhdu/utils/AnimationUtil.java // public class AnimationUtil { // private static final String TAG = AnimationUtil.class.getSimpleName(); // // /** // * 从控件所在位置移动到控件的底部 // * // * @return // */ // public static TranslateAnimation moveToViewBottom() { // TranslateAnimation mHiddenAction = new TranslateAnimation(Animation.RELATIVE_TO_SELF, 0.0f, // Animation.RELATIVE_TO_SELF, 0.0f, Animation.RELATIVE_TO_SELF, // 0.0f, Animation.RELATIVE_TO_SELF, 5.0f); // mHiddenAction.setDuration(2500); // return mHiddenAction; // } // // /** // * 从控件的底部移动到控件所在位置 // * // * @return // */ // public static TranslateAnimation moveToViewLocation() { // TranslateAnimation mHiddenAction = new TranslateAnimation(Animation.RELATIVE_TO_SELF, 0.0f, // Animation.RELATIVE_TO_SELF, 0.0f, Animation.RELATIVE_TO_SELF, // 5.0f, Animation.RELATIVE_TO_SELF, 0.0f); // mHiddenAction.setDuration(1500); // return mHiddenAction; // } // // } // Path: app/src/main/java/com/cxsj/runhdu/WelcomeActivity.java import android.os.Bundle; import android.text.TextUtils; import android.util.Log; import android.view.View; import android.widget.Button; import android.widget.Toast; import com.cxsj.runhdu.Model.LoginModel; import com.cxsj.runhdu.utils.ActivityManager; import com.cxsj.runhdu.utils.AnimationUtil; setContentView(R.layout.activity_welcome); loginButton = (Button) findViewById(R.id.welcome_login_button); registerButton = (Button) findViewById(R.id.welcome_register_button); //用户名不为空时,执行登录,跳转到MainActivity if (!TextUtils.isEmpty(username)) { doLogin(); } else { showButtons(); } loginButton.setOnClickListener(v -> toActivity(WelcomeActivity.this, LoginActivity.class)); registerButton.setOnClickListener(v -> toActivity(WelcomeActivity.this, RegisterActivity.class)); } @Override public void onBackPressed() { if (loginButton.getVisibility() != View.GONE) { super.onBackPressed(); } } //显示登录注册按钮 private void showButtons() { loginButton.setVisibility(View.VISIBLE); registerButton.setVisibility(View.VISIBLE);
loginButton.setAnimation(AnimationUtil.moveToViewLocation());
SailFlorve/RunHDU
app/src/main/java/com/cxsj/runhdu/WelcomeActivity.java
// Path: app/src/main/java/com/cxsj/runhdu/Model/LoginModel.java // public class LoginModel extends BaseModel { // public interface LoginCallback { // void onLoginSuccess(); // // void onLoginFailure(String msg, int which); // } // // private static Callback getCallback(LoginCallback callback) { // return new Callback() { // @Override // public void onFailure(Call call, IOException e) { // mHandler.post(() -> callback.onLoginFailure(CONNECT_FAILED, 0)); // } // // @Override // public void onResponse(Call call, Response response) throws IOException { // String json = response.body().string(); // try { // mHandler.post(() -> { // Status status = null; // status = new Gson().fromJson(json, Status.class); // if (status == null) { // callback.onLoginFailure(RETURN_DATA_ERROR, 0); // } else { // if (status.getResult()) { // callback.onLoginSuccess(); // } else { // callback.onLoginFailure(status.getMessage(), status.getWhich()); // } // } // }); // } catch (JsonSyntaxException e) { // callback.onLoginFailure(RETURN_DATA_ERROR, 0); // e.printStackTrace(); // } // } // }; // } // // public static void login(String username, String passwordMD5, LoginCallback callback) { // HttpUtil.load(URLs.LOGIN) // .addParam("name", username) // .addParam("password", passwordMD5) // .post(getCallback(callback)); // } // // public static void register(String username, String passwordMD5, LoginCallback callback) { // HttpUtil.load(URLs.REGISTER) // //传加密后的用户名and密码 // .addParam("name", username) // .addParam("password", passwordMD5) // .post(getCallback(callback)); // } // } // // Path: app/src/main/java/com/cxsj/runhdu/utils/ActivityManager.java // public class ActivityManager { // // private static String TAG = "ActivityManager"; // private static List<Activity> activities = new ArrayList<>(); // // public static void addActivity(Activity activity) { // Log.d(TAG, "addActivity: "+activity.getLocalClassName()); // activities.add(activity); // } // // public static void removeActivity(Activity activity) { // if (activity != null) { // Log.d(TAG, "removeActivity: "+activity.getLocalClassName()); // activities.remove(activity); // } // } // // public static void finishAll() { // for (Activity activity : activities) { // if (activity != null) { // Log.d(TAG, "finishAll: " + activity.getLocalClassName()); // activity.finish(); // } // } // } // } // // Path: app/src/main/java/com/cxsj/runhdu/utils/AnimationUtil.java // public class AnimationUtil { // private static final String TAG = AnimationUtil.class.getSimpleName(); // // /** // * 从控件所在位置移动到控件的底部 // * // * @return // */ // public static TranslateAnimation moveToViewBottom() { // TranslateAnimation mHiddenAction = new TranslateAnimation(Animation.RELATIVE_TO_SELF, 0.0f, // Animation.RELATIVE_TO_SELF, 0.0f, Animation.RELATIVE_TO_SELF, // 0.0f, Animation.RELATIVE_TO_SELF, 5.0f); // mHiddenAction.setDuration(2500); // return mHiddenAction; // } // // /** // * 从控件的底部移动到控件所在位置 // * // * @return // */ // public static TranslateAnimation moveToViewLocation() { // TranslateAnimation mHiddenAction = new TranslateAnimation(Animation.RELATIVE_TO_SELF, 0.0f, // Animation.RELATIVE_TO_SELF, 0.0f, Animation.RELATIVE_TO_SELF, // 5.0f, Animation.RELATIVE_TO_SELF, 0.0f); // mHiddenAction.setDuration(1500); // return mHiddenAction; // } // // }
import android.os.Bundle; import android.text.TextUtils; import android.util.Log; import android.view.View; import android.widget.Button; import android.widget.Toast; import com.cxsj.runhdu.Model.LoginModel; import com.cxsj.runhdu.utils.ActivityManager; import com.cxsj.runhdu.utils.AnimationUtil;
loginButton.setOnClickListener(v -> toActivity(WelcomeActivity.this, LoginActivity.class)); registerButton.setOnClickListener(v -> toActivity(WelcomeActivity.this, RegisterActivity.class)); } @Override public void onBackPressed() { if (loginButton.getVisibility() != View.GONE) { super.onBackPressed(); } } //显示登录注册按钮 private void showButtons() { loginButton.setVisibility(View.VISIBLE); registerButton.setVisibility(View.VISIBLE); loginButton.setAnimation(AnimationUtil.moveToViewLocation()); registerButton.setAnimation(AnimationUtil.moveToViewLocation()); } private void doLogin() { LoginModel.login(username, (String) defaultPrefs.get("MD5Pw", ""), WelcomeActivity.this); } @Override public void onLoginSuccess() { closeProgressDialog(); toActivity(WelcomeActivity.this, MainActivity.class);
// Path: app/src/main/java/com/cxsj/runhdu/Model/LoginModel.java // public class LoginModel extends BaseModel { // public interface LoginCallback { // void onLoginSuccess(); // // void onLoginFailure(String msg, int which); // } // // private static Callback getCallback(LoginCallback callback) { // return new Callback() { // @Override // public void onFailure(Call call, IOException e) { // mHandler.post(() -> callback.onLoginFailure(CONNECT_FAILED, 0)); // } // // @Override // public void onResponse(Call call, Response response) throws IOException { // String json = response.body().string(); // try { // mHandler.post(() -> { // Status status = null; // status = new Gson().fromJson(json, Status.class); // if (status == null) { // callback.onLoginFailure(RETURN_DATA_ERROR, 0); // } else { // if (status.getResult()) { // callback.onLoginSuccess(); // } else { // callback.onLoginFailure(status.getMessage(), status.getWhich()); // } // } // }); // } catch (JsonSyntaxException e) { // callback.onLoginFailure(RETURN_DATA_ERROR, 0); // e.printStackTrace(); // } // } // }; // } // // public static void login(String username, String passwordMD5, LoginCallback callback) { // HttpUtil.load(URLs.LOGIN) // .addParam("name", username) // .addParam("password", passwordMD5) // .post(getCallback(callback)); // } // // public static void register(String username, String passwordMD5, LoginCallback callback) { // HttpUtil.load(URLs.REGISTER) // //传加密后的用户名and密码 // .addParam("name", username) // .addParam("password", passwordMD5) // .post(getCallback(callback)); // } // } // // Path: app/src/main/java/com/cxsj/runhdu/utils/ActivityManager.java // public class ActivityManager { // // private static String TAG = "ActivityManager"; // private static List<Activity> activities = new ArrayList<>(); // // public static void addActivity(Activity activity) { // Log.d(TAG, "addActivity: "+activity.getLocalClassName()); // activities.add(activity); // } // // public static void removeActivity(Activity activity) { // if (activity != null) { // Log.d(TAG, "removeActivity: "+activity.getLocalClassName()); // activities.remove(activity); // } // } // // public static void finishAll() { // for (Activity activity : activities) { // if (activity != null) { // Log.d(TAG, "finishAll: " + activity.getLocalClassName()); // activity.finish(); // } // } // } // } // // Path: app/src/main/java/com/cxsj/runhdu/utils/AnimationUtil.java // public class AnimationUtil { // private static final String TAG = AnimationUtil.class.getSimpleName(); // // /** // * 从控件所在位置移动到控件的底部 // * // * @return // */ // public static TranslateAnimation moveToViewBottom() { // TranslateAnimation mHiddenAction = new TranslateAnimation(Animation.RELATIVE_TO_SELF, 0.0f, // Animation.RELATIVE_TO_SELF, 0.0f, Animation.RELATIVE_TO_SELF, // 0.0f, Animation.RELATIVE_TO_SELF, 5.0f); // mHiddenAction.setDuration(2500); // return mHiddenAction; // } // // /** // * 从控件的底部移动到控件所在位置 // * // * @return // */ // public static TranslateAnimation moveToViewLocation() { // TranslateAnimation mHiddenAction = new TranslateAnimation(Animation.RELATIVE_TO_SELF, 0.0f, // Animation.RELATIVE_TO_SELF, 0.0f, Animation.RELATIVE_TO_SELF, // 5.0f, Animation.RELATIVE_TO_SELF, 0.0f); // mHiddenAction.setDuration(1500); // return mHiddenAction; // } // // } // Path: app/src/main/java/com/cxsj/runhdu/WelcomeActivity.java import android.os.Bundle; import android.text.TextUtils; import android.util.Log; import android.view.View; import android.widget.Button; import android.widget.Toast; import com.cxsj.runhdu.Model.LoginModel; import com.cxsj.runhdu.utils.ActivityManager; import com.cxsj.runhdu.utils.AnimationUtil; loginButton.setOnClickListener(v -> toActivity(WelcomeActivity.this, LoginActivity.class)); registerButton.setOnClickListener(v -> toActivity(WelcomeActivity.this, RegisterActivity.class)); } @Override public void onBackPressed() { if (loginButton.getVisibility() != View.GONE) { super.onBackPressed(); } } //显示登录注册按钮 private void showButtons() { loginButton.setVisibility(View.VISIBLE); registerButton.setVisibility(View.VISIBLE); loginButton.setAnimation(AnimationUtil.moveToViewLocation()); registerButton.setAnimation(AnimationUtil.moveToViewLocation()); } private void doLogin() { LoginModel.login(username, (String) defaultPrefs.get("MD5Pw", ""), WelcomeActivity.this); } @Override public void onLoginSuccess() { closeProgressDialog(); toActivity(WelcomeActivity.this, MainActivity.class);
ActivityManager.finishAll();
SailFlorve/RunHDU
app/src/main/java/com/cxsj/runhdu/Model/FriendModel.java
// Path: app/src/main/java/com/cxsj/runhdu/bean/gson/MyFriend.java // public class MyFriend { // @SerializedName("MyFriends") // private List<FriendInfo> friendList; // // @SerializedName("ApplyLists") // private List<ApplicantInfo> applyList; // // public List<FriendInfo> getFriendList() { // return friendList; // } // // public void setFriendList(List<FriendInfo> friendList) { // this.friendList = friendList; // } // // public List<ApplicantInfo> getApplyList() { // return applyList; // } // // public void setApplyList(List<ApplicantInfo> applyList) { // this.applyList = applyList; // } // // public class ApplicantInfo{ // @SerializedName("Applicant") // private String applicant; // // @SerializedName("ApplyDate") // private String date; // // public String getApplicant() { // return applicant; // } // // public void setApplicant(String applicant) { // this.applicant = applicant; // } // // public String getDate() { // return date; // } // // public void setDate(String date) { // this.date = date; // } // } // } // // Path: app/src/main/java/com/cxsj/runhdu/constant/URLs.java // public class URLs { // public static final String DOWNLOAD = "http://d1.51gugu.com/170258/RunHDU"; // public static final String LOGIN = "http://112.74.115.231:8080/CXSJ/Login"; // public static final String REGISTER="http://112.74.115.231:8080/CXSJ/Register"; // public static final String GET_RUN_INFO = "http://112.74.115.231:8080/chuangxinshijian/ReadAll"; // public static final String UPLOAD_RUN_INFO = "http://112.74.115.231:8080/chuangxinshijian/Write"; // public static final String CLEAR_DATA = "http://112.74.115.231:8080/chuangxinshijian/ClearTheTable"; // public static final String UPDATE_URL = "http://112.74.115.231:8080/chuangxinshijian/VersionCompare"; // public static final String GET_RUN_TIMES = "http://112.74.115.231:8080/chuangxinshijian/ReadUserNameAndTimesOnly"; // public static final String UPLOAD_ALL_INFO = "http://112.74.115.231:8080/chuangxinshijian/WriteByJson"; // public static final String UPLOAD_PROFILE = "http://112.74.115.231:8080/CXSJ/UploadHead"; // public static final String PROFILE_URL = "http://112.74.115.231:8080/CXSJ/Image/"; // public static final String FEEDBACK_URL = "http://112.74.115.231:8080/chuangxinshijian/WriteFeedback"; // public static final String SUNNY_RUN_QUERY_API = "http://hdu.sunnysport.org.cn/api/student/achievements/"; // public static final String SUNNY_RUN_INFO_API = "http://hdu.sunnysport.org.cn/api/student/info/"; // public static final String DELETE_ITEM = "http://112.74.115.231:8080/chuangxinshijian/ClearByUserNameAndRunId"; // public static final String APPLY_FRIEND = "http://112.74.115.231:8080/CXSJ/Apply"; // public static final String REPLY_FRIEND = "http://112.74.115.231:8080/CXSJ/BeFriend"; // public static final String GET_FRIEND = "http://112.74.115.231:8080/CXSJ/MyFriends"; // public static final String DELETE_FRIEND = "http://112.74.115.231:8080/CXSJ/DeleteFriend"; // public static final String OFF_LINE = "http://112.74.115.231:8080/CXSJ/Xiaxian"; // } // // Path: app/src/main/java/com/cxsj/runhdu/utils/HttpUtil.java // public class HttpUtil { // private static RequestManager manager; // // public static RequestManager load(String url) { // manager = new RequestManager(); // manager.url(url); // return manager; // } // // public static class RequestManager { // private Request.Builder requestBuilder = new Request.Builder(); // private FormBody.Builder formBuilder = new FormBody.Builder(); // private Call call; // // private void url(String url) { // formBuilder = new FormBody.Builder(); // requestBuilder = new Request.Builder(); // // requestBuilder = requestBuilder.url(url); // } // // private void cancel() { // if (call != null) { // call.cancel(); // } // } // // public RequestManager addHeader(String key, String value) { // requestBuilder.addHeader(key, value); // return this; // } // // public RequestManager addParam(String key, String value) { // formBuilder = formBuilder.add(key, value); // return this; // } // // public void post(Callback callback) { // OkHttpClient client = new OkHttpClient.Builder() // .connectTimeout(3, TimeUnit.SECONDS) // .followRedirects(false) // .followSslRedirects(false) // .build(); // // Request request = requestBuilder.post(formBuilder.build()).build(); // client.newCall(request).enqueue(callback); // } // // public void get(Callback callback) { // OkHttpClient client = new OkHttpClient.Builder().build(); // Request request = requestBuilder.build(); // call = client.newCall(request); // call.enqueue(callback); // } // } // }
import com.cxsj.runhdu.bean.gson.MyFriend; import com.cxsj.runhdu.constant.URLs; import com.cxsj.runhdu.utils.HttpUtil; import com.google.gson.Gson; import com.google.gson.JsonSyntaxException; import java.io.IOException; import okhttp3.Call; import okhttp3.Callback; import okhttp3.Response;
package com.cxsj.runhdu.Model; /** * Created by SailFlorve on 2017/8/25 0025. * 好友相关数据请求 */ public class FriendModel extends BaseModel { public interface GetFriendCallback {
// Path: app/src/main/java/com/cxsj/runhdu/bean/gson/MyFriend.java // public class MyFriend { // @SerializedName("MyFriends") // private List<FriendInfo> friendList; // // @SerializedName("ApplyLists") // private List<ApplicantInfo> applyList; // // public List<FriendInfo> getFriendList() { // return friendList; // } // // public void setFriendList(List<FriendInfo> friendList) { // this.friendList = friendList; // } // // public List<ApplicantInfo> getApplyList() { // return applyList; // } // // public void setApplyList(List<ApplicantInfo> applyList) { // this.applyList = applyList; // } // // public class ApplicantInfo{ // @SerializedName("Applicant") // private String applicant; // // @SerializedName("ApplyDate") // private String date; // // public String getApplicant() { // return applicant; // } // // public void setApplicant(String applicant) { // this.applicant = applicant; // } // // public String getDate() { // return date; // } // // public void setDate(String date) { // this.date = date; // } // } // } // // Path: app/src/main/java/com/cxsj/runhdu/constant/URLs.java // public class URLs { // public static final String DOWNLOAD = "http://d1.51gugu.com/170258/RunHDU"; // public static final String LOGIN = "http://112.74.115.231:8080/CXSJ/Login"; // public static final String REGISTER="http://112.74.115.231:8080/CXSJ/Register"; // public static final String GET_RUN_INFO = "http://112.74.115.231:8080/chuangxinshijian/ReadAll"; // public static final String UPLOAD_RUN_INFO = "http://112.74.115.231:8080/chuangxinshijian/Write"; // public static final String CLEAR_DATA = "http://112.74.115.231:8080/chuangxinshijian/ClearTheTable"; // public static final String UPDATE_URL = "http://112.74.115.231:8080/chuangxinshijian/VersionCompare"; // public static final String GET_RUN_TIMES = "http://112.74.115.231:8080/chuangxinshijian/ReadUserNameAndTimesOnly"; // public static final String UPLOAD_ALL_INFO = "http://112.74.115.231:8080/chuangxinshijian/WriteByJson"; // public static final String UPLOAD_PROFILE = "http://112.74.115.231:8080/CXSJ/UploadHead"; // public static final String PROFILE_URL = "http://112.74.115.231:8080/CXSJ/Image/"; // public static final String FEEDBACK_URL = "http://112.74.115.231:8080/chuangxinshijian/WriteFeedback"; // public static final String SUNNY_RUN_QUERY_API = "http://hdu.sunnysport.org.cn/api/student/achievements/"; // public static final String SUNNY_RUN_INFO_API = "http://hdu.sunnysport.org.cn/api/student/info/"; // public static final String DELETE_ITEM = "http://112.74.115.231:8080/chuangxinshijian/ClearByUserNameAndRunId"; // public static final String APPLY_FRIEND = "http://112.74.115.231:8080/CXSJ/Apply"; // public static final String REPLY_FRIEND = "http://112.74.115.231:8080/CXSJ/BeFriend"; // public static final String GET_FRIEND = "http://112.74.115.231:8080/CXSJ/MyFriends"; // public static final String DELETE_FRIEND = "http://112.74.115.231:8080/CXSJ/DeleteFriend"; // public static final String OFF_LINE = "http://112.74.115.231:8080/CXSJ/Xiaxian"; // } // // Path: app/src/main/java/com/cxsj/runhdu/utils/HttpUtil.java // public class HttpUtil { // private static RequestManager manager; // // public static RequestManager load(String url) { // manager = new RequestManager(); // manager.url(url); // return manager; // } // // public static class RequestManager { // private Request.Builder requestBuilder = new Request.Builder(); // private FormBody.Builder formBuilder = new FormBody.Builder(); // private Call call; // // private void url(String url) { // formBuilder = new FormBody.Builder(); // requestBuilder = new Request.Builder(); // // requestBuilder = requestBuilder.url(url); // } // // private void cancel() { // if (call != null) { // call.cancel(); // } // } // // public RequestManager addHeader(String key, String value) { // requestBuilder.addHeader(key, value); // return this; // } // // public RequestManager addParam(String key, String value) { // formBuilder = formBuilder.add(key, value); // return this; // } // // public void post(Callback callback) { // OkHttpClient client = new OkHttpClient.Builder() // .connectTimeout(3, TimeUnit.SECONDS) // .followRedirects(false) // .followSslRedirects(false) // .build(); // // Request request = requestBuilder.post(formBuilder.build()).build(); // client.newCall(request).enqueue(callback); // } // // public void get(Callback callback) { // OkHttpClient client = new OkHttpClient.Builder().build(); // Request request = requestBuilder.build(); // call = client.newCall(request); // call.enqueue(callback); // } // } // } // Path: app/src/main/java/com/cxsj/runhdu/Model/FriendModel.java import com.cxsj.runhdu.bean.gson.MyFriend; import com.cxsj.runhdu.constant.URLs; import com.cxsj.runhdu.utils.HttpUtil; import com.google.gson.Gson; import com.google.gson.JsonSyntaxException; import java.io.IOException; import okhttp3.Call; import okhttp3.Callback; import okhttp3.Response; package com.cxsj.runhdu.Model; /** * Created by SailFlorve on 2017/8/25 0025. * 好友相关数据请求 */ public class FriendModel extends BaseModel { public interface GetFriendCallback {
void onSuccess(String json, MyFriend myFriend);
SailFlorve/RunHDU
app/src/main/java/com/cxsj/runhdu/HelpActivity.java
// Path: app/src/main/java/com/cxsj/runhdu/adapters/HelpAdapter.java // public class HelpAdapter extends ArrayAdapter<HelpItem> { // private int resourceId; // public HelpAdapter(Context context, int textViewResourceId, List<HelpItem> objects){ // super(context,textViewResourceId,objects); // resourceId = textViewResourceId; // } // // @NonNull // @Override // public View getView(int position, View convertView, ViewGroup parent) { // HelpItem help_item = getItem(position); // View view = LayoutInflater.from(getContext()).inflate(resourceId,parent,false); // TextView title = (TextView) view.findViewById(R.id.help_title); // TextView info = (TextView) view.findViewById(R.id.help_info); // title.setText(help_item.getTitle()); // info.setText(help_item.getInfo()); // return view; // } // } // // Path: app/src/main/java/com/cxsj/runhdu/bean/HelpItem.java // public class HelpItem { // private String title; // private String info; // // public HelpItem(String title, String info){ // this.title = title; // this.info = info; // } // public String getTitle(){ // return title; // } // // public String getInfo() { // return info; // } // }
import android.animation.ValueAnimator; import android.os.Bundle; import android.view.View; import android.widget.ImageView; import android.widget.ListView; import android.widget.TextView; import com.cxsj.runhdu.adapters.HelpAdapter; import com.cxsj.runhdu.bean.HelpItem; import java.util.ArrayList; import java.util.List; import static android.view.View.MeasureSpec.makeMeasureSpec;
package com.cxsj.runhdu; /** * 帮助 */ public class HelpActivity extends BaseActivity { private List<HelpItem> helpList = new ArrayList<>(); private final int duration = 200; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_help); setToolbar(R.id.help_toolbar, true); initHelpItem();
// Path: app/src/main/java/com/cxsj/runhdu/adapters/HelpAdapter.java // public class HelpAdapter extends ArrayAdapter<HelpItem> { // private int resourceId; // public HelpAdapter(Context context, int textViewResourceId, List<HelpItem> objects){ // super(context,textViewResourceId,objects); // resourceId = textViewResourceId; // } // // @NonNull // @Override // public View getView(int position, View convertView, ViewGroup parent) { // HelpItem help_item = getItem(position); // View view = LayoutInflater.from(getContext()).inflate(resourceId,parent,false); // TextView title = (TextView) view.findViewById(R.id.help_title); // TextView info = (TextView) view.findViewById(R.id.help_info); // title.setText(help_item.getTitle()); // info.setText(help_item.getInfo()); // return view; // } // } // // Path: app/src/main/java/com/cxsj/runhdu/bean/HelpItem.java // public class HelpItem { // private String title; // private String info; // // public HelpItem(String title, String info){ // this.title = title; // this.info = info; // } // public String getTitle(){ // return title; // } // // public String getInfo() { // return info; // } // } // Path: app/src/main/java/com/cxsj/runhdu/HelpActivity.java import android.animation.ValueAnimator; import android.os.Bundle; import android.view.View; import android.widget.ImageView; import android.widget.ListView; import android.widget.TextView; import com.cxsj.runhdu.adapters.HelpAdapter; import com.cxsj.runhdu.bean.HelpItem; import java.util.ArrayList; import java.util.List; import static android.view.View.MeasureSpec.makeMeasureSpec; package com.cxsj.runhdu; /** * 帮助 */ public class HelpActivity extends BaseActivity { private List<HelpItem> helpList = new ArrayList<>(); private final int duration = 200; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_help); setToolbar(R.id.help_toolbar, true); initHelpItem();
HelpAdapter adapter = new HelpAdapter(HelpActivity.this, R.layout.help_item, helpList);
SailFlorve/RunHDU
app/src/main/java/com/cxsj/runhdu/FeedbackActivity.java
// Path: app/src/main/java/com/cxsj/runhdu/constant/URLs.java // public class URLs { // public static final String DOWNLOAD = "http://d1.51gugu.com/170258/RunHDU"; // public static final String LOGIN = "http://112.74.115.231:8080/CXSJ/Login"; // public static final String REGISTER="http://112.74.115.231:8080/CXSJ/Register"; // public static final String GET_RUN_INFO = "http://112.74.115.231:8080/chuangxinshijian/ReadAll"; // public static final String UPLOAD_RUN_INFO = "http://112.74.115.231:8080/chuangxinshijian/Write"; // public static final String CLEAR_DATA = "http://112.74.115.231:8080/chuangxinshijian/ClearTheTable"; // public static final String UPDATE_URL = "http://112.74.115.231:8080/chuangxinshijian/VersionCompare"; // public static final String GET_RUN_TIMES = "http://112.74.115.231:8080/chuangxinshijian/ReadUserNameAndTimesOnly"; // public static final String UPLOAD_ALL_INFO = "http://112.74.115.231:8080/chuangxinshijian/WriteByJson"; // public static final String UPLOAD_PROFILE = "http://112.74.115.231:8080/CXSJ/UploadHead"; // public static final String PROFILE_URL = "http://112.74.115.231:8080/CXSJ/Image/"; // public static final String FEEDBACK_URL = "http://112.74.115.231:8080/chuangxinshijian/WriteFeedback"; // public static final String SUNNY_RUN_QUERY_API = "http://hdu.sunnysport.org.cn/api/student/achievements/"; // public static final String SUNNY_RUN_INFO_API = "http://hdu.sunnysport.org.cn/api/student/info/"; // public static final String DELETE_ITEM = "http://112.74.115.231:8080/chuangxinshijian/ClearByUserNameAndRunId"; // public static final String APPLY_FRIEND = "http://112.74.115.231:8080/CXSJ/Apply"; // public static final String REPLY_FRIEND = "http://112.74.115.231:8080/CXSJ/BeFriend"; // public static final String GET_FRIEND = "http://112.74.115.231:8080/CXSJ/MyFriends"; // public static final String DELETE_FRIEND = "http://112.74.115.231:8080/CXSJ/DeleteFriend"; // public static final String OFF_LINE = "http://112.74.115.231:8080/CXSJ/Xiaxian"; // } // // Path: app/src/main/java/com/cxsj/runhdu/utils/HttpUtil.java // public class HttpUtil { // private static RequestManager manager; // // public static RequestManager load(String url) { // manager = new RequestManager(); // manager.url(url); // return manager; // } // // public static class RequestManager { // private Request.Builder requestBuilder = new Request.Builder(); // private FormBody.Builder formBuilder = new FormBody.Builder(); // private Call call; // // private void url(String url) { // formBuilder = new FormBody.Builder(); // requestBuilder = new Request.Builder(); // // requestBuilder = requestBuilder.url(url); // } // // private void cancel() { // if (call != null) { // call.cancel(); // } // } // // public RequestManager addHeader(String key, String value) { // requestBuilder.addHeader(key, value); // return this; // } // // public RequestManager addParam(String key, String value) { // formBuilder = formBuilder.add(key, value); // return this; // } // // public void post(Callback callback) { // OkHttpClient client = new OkHttpClient.Builder() // .connectTimeout(3, TimeUnit.SECONDS) // .followRedirects(false) // .followSslRedirects(false) // .build(); // // Request request = requestBuilder.post(formBuilder.build()).build(); // client.newCall(request).enqueue(callback); // } // // public void get(Callback callback) { // OkHttpClient client = new OkHttpClient.Builder().build(); // Request request = requestBuilder.build(); // call = client.newCall(request); // call.enqueue(callback); // } // } // }
import android.os.Bundle; import android.support.design.widget.Snackbar; import android.text.TextUtils; import android.widget.EditText; import android.widget.LinearLayout; import android.widget.Toast; import com.cxsj.runhdu.constant.URLs; import com.cxsj.runhdu.utils.HttpUtil; import com.dd.CircularProgressButton; import java.io.IOException; import okhttp3.Call; import okhttp3.Callback; import okhttp3.Response;
package com.cxsj.runhdu; /** * 用户反馈Activity */ public class FeedbackActivity extends BaseActivity { private LinearLayout rootLayout; private EditText feedbackText; private EditText contactText; private CircularProgressButton feedbackButton; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_feedback); setToolbar(R.id.feedback_toolbar, true); feedbackText = (EditText) findViewById(R.id.feedback_text); contactText = (EditText) findViewById(R.id.feedback_contact); feedbackButton = (CircularProgressButton) findViewById(R.id.feedback_button); rootLayout = (LinearLayout) findViewById(R.id.feedback_root_layout); feedbackButton.setIndeterminateProgressMode(true); feedbackButton.setOnClickListener(v -> { String feedbackStr = feedbackText.getText().toString(); String contactStr = contactText.getText().toString(); if (TextUtils.isEmpty(feedbackStr)) { Toast.makeText(this, "请输入反馈信息!", Toast.LENGTH_SHORT).show(); return; } if (TextUtils.isEmpty(contactStr)) contactStr = "未填写"; feedbackButton.setProgress(50); //提交反馈
// Path: app/src/main/java/com/cxsj/runhdu/constant/URLs.java // public class URLs { // public static final String DOWNLOAD = "http://d1.51gugu.com/170258/RunHDU"; // public static final String LOGIN = "http://112.74.115.231:8080/CXSJ/Login"; // public static final String REGISTER="http://112.74.115.231:8080/CXSJ/Register"; // public static final String GET_RUN_INFO = "http://112.74.115.231:8080/chuangxinshijian/ReadAll"; // public static final String UPLOAD_RUN_INFO = "http://112.74.115.231:8080/chuangxinshijian/Write"; // public static final String CLEAR_DATA = "http://112.74.115.231:8080/chuangxinshijian/ClearTheTable"; // public static final String UPDATE_URL = "http://112.74.115.231:8080/chuangxinshijian/VersionCompare"; // public static final String GET_RUN_TIMES = "http://112.74.115.231:8080/chuangxinshijian/ReadUserNameAndTimesOnly"; // public static final String UPLOAD_ALL_INFO = "http://112.74.115.231:8080/chuangxinshijian/WriteByJson"; // public static final String UPLOAD_PROFILE = "http://112.74.115.231:8080/CXSJ/UploadHead"; // public static final String PROFILE_URL = "http://112.74.115.231:8080/CXSJ/Image/"; // public static final String FEEDBACK_URL = "http://112.74.115.231:8080/chuangxinshijian/WriteFeedback"; // public static final String SUNNY_RUN_QUERY_API = "http://hdu.sunnysport.org.cn/api/student/achievements/"; // public static final String SUNNY_RUN_INFO_API = "http://hdu.sunnysport.org.cn/api/student/info/"; // public static final String DELETE_ITEM = "http://112.74.115.231:8080/chuangxinshijian/ClearByUserNameAndRunId"; // public static final String APPLY_FRIEND = "http://112.74.115.231:8080/CXSJ/Apply"; // public static final String REPLY_FRIEND = "http://112.74.115.231:8080/CXSJ/BeFriend"; // public static final String GET_FRIEND = "http://112.74.115.231:8080/CXSJ/MyFriends"; // public static final String DELETE_FRIEND = "http://112.74.115.231:8080/CXSJ/DeleteFriend"; // public static final String OFF_LINE = "http://112.74.115.231:8080/CXSJ/Xiaxian"; // } // // Path: app/src/main/java/com/cxsj/runhdu/utils/HttpUtil.java // public class HttpUtil { // private static RequestManager manager; // // public static RequestManager load(String url) { // manager = new RequestManager(); // manager.url(url); // return manager; // } // // public static class RequestManager { // private Request.Builder requestBuilder = new Request.Builder(); // private FormBody.Builder formBuilder = new FormBody.Builder(); // private Call call; // // private void url(String url) { // formBuilder = new FormBody.Builder(); // requestBuilder = new Request.Builder(); // // requestBuilder = requestBuilder.url(url); // } // // private void cancel() { // if (call != null) { // call.cancel(); // } // } // // public RequestManager addHeader(String key, String value) { // requestBuilder.addHeader(key, value); // return this; // } // // public RequestManager addParam(String key, String value) { // formBuilder = formBuilder.add(key, value); // return this; // } // // public void post(Callback callback) { // OkHttpClient client = new OkHttpClient.Builder() // .connectTimeout(3, TimeUnit.SECONDS) // .followRedirects(false) // .followSslRedirects(false) // .build(); // // Request request = requestBuilder.post(formBuilder.build()).build(); // client.newCall(request).enqueue(callback); // } // // public void get(Callback callback) { // OkHttpClient client = new OkHttpClient.Builder().build(); // Request request = requestBuilder.build(); // call = client.newCall(request); // call.enqueue(callback); // } // } // } // Path: app/src/main/java/com/cxsj/runhdu/FeedbackActivity.java import android.os.Bundle; import android.support.design.widget.Snackbar; import android.text.TextUtils; import android.widget.EditText; import android.widget.LinearLayout; import android.widget.Toast; import com.cxsj.runhdu.constant.URLs; import com.cxsj.runhdu.utils.HttpUtil; import com.dd.CircularProgressButton; import java.io.IOException; import okhttp3.Call; import okhttp3.Callback; import okhttp3.Response; package com.cxsj.runhdu; /** * 用户反馈Activity */ public class FeedbackActivity extends BaseActivity { private LinearLayout rootLayout; private EditText feedbackText; private EditText contactText; private CircularProgressButton feedbackButton; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_feedback); setToolbar(R.id.feedback_toolbar, true); feedbackText = (EditText) findViewById(R.id.feedback_text); contactText = (EditText) findViewById(R.id.feedback_contact); feedbackButton = (CircularProgressButton) findViewById(R.id.feedback_button); rootLayout = (LinearLayout) findViewById(R.id.feedback_root_layout); feedbackButton.setIndeterminateProgressMode(true); feedbackButton.setOnClickListener(v -> { String feedbackStr = feedbackText.getText().toString(); String contactStr = contactText.getText().toString(); if (TextUtils.isEmpty(feedbackStr)) { Toast.makeText(this, "请输入反馈信息!", Toast.LENGTH_SHORT).show(); return; } if (TextUtils.isEmpty(contactStr)) contactStr = "未填写"; feedbackButton.setProgress(50); //提交反馈
HttpUtil.load(URLs.FEEDBACK_URL)
SailFlorve/RunHDU
app/src/main/java/com/cxsj/runhdu/FeedbackActivity.java
// Path: app/src/main/java/com/cxsj/runhdu/constant/URLs.java // public class URLs { // public static final String DOWNLOAD = "http://d1.51gugu.com/170258/RunHDU"; // public static final String LOGIN = "http://112.74.115.231:8080/CXSJ/Login"; // public static final String REGISTER="http://112.74.115.231:8080/CXSJ/Register"; // public static final String GET_RUN_INFO = "http://112.74.115.231:8080/chuangxinshijian/ReadAll"; // public static final String UPLOAD_RUN_INFO = "http://112.74.115.231:8080/chuangxinshijian/Write"; // public static final String CLEAR_DATA = "http://112.74.115.231:8080/chuangxinshijian/ClearTheTable"; // public static final String UPDATE_URL = "http://112.74.115.231:8080/chuangxinshijian/VersionCompare"; // public static final String GET_RUN_TIMES = "http://112.74.115.231:8080/chuangxinshijian/ReadUserNameAndTimesOnly"; // public static final String UPLOAD_ALL_INFO = "http://112.74.115.231:8080/chuangxinshijian/WriteByJson"; // public static final String UPLOAD_PROFILE = "http://112.74.115.231:8080/CXSJ/UploadHead"; // public static final String PROFILE_URL = "http://112.74.115.231:8080/CXSJ/Image/"; // public static final String FEEDBACK_URL = "http://112.74.115.231:8080/chuangxinshijian/WriteFeedback"; // public static final String SUNNY_RUN_QUERY_API = "http://hdu.sunnysport.org.cn/api/student/achievements/"; // public static final String SUNNY_RUN_INFO_API = "http://hdu.sunnysport.org.cn/api/student/info/"; // public static final String DELETE_ITEM = "http://112.74.115.231:8080/chuangxinshijian/ClearByUserNameAndRunId"; // public static final String APPLY_FRIEND = "http://112.74.115.231:8080/CXSJ/Apply"; // public static final String REPLY_FRIEND = "http://112.74.115.231:8080/CXSJ/BeFriend"; // public static final String GET_FRIEND = "http://112.74.115.231:8080/CXSJ/MyFriends"; // public static final String DELETE_FRIEND = "http://112.74.115.231:8080/CXSJ/DeleteFriend"; // public static final String OFF_LINE = "http://112.74.115.231:8080/CXSJ/Xiaxian"; // } // // Path: app/src/main/java/com/cxsj/runhdu/utils/HttpUtil.java // public class HttpUtil { // private static RequestManager manager; // // public static RequestManager load(String url) { // manager = new RequestManager(); // manager.url(url); // return manager; // } // // public static class RequestManager { // private Request.Builder requestBuilder = new Request.Builder(); // private FormBody.Builder formBuilder = new FormBody.Builder(); // private Call call; // // private void url(String url) { // formBuilder = new FormBody.Builder(); // requestBuilder = new Request.Builder(); // // requestBuilder = requestBuilder.url(url); // } // // private void cancel() { // if (call != null) { // call.cancel(); // } // } // // public RequestManager addHeader(String key, String value) { // requestBuilder.addHeader(key, value); // return this; // } // // public RequestManager addParam(String key, String value) { // formBuilder = formBuilder.add(key, value); // return this; // } // // public void post(Callback callback) { // OkHttpClient client = new OkHttpClient.Builder() // .connectTimeout(3, TimeUnit.SECONDS) // .followRedirects(false) // .followSslRedirects(false) // .build(); // // Request request = requestBuilder.post(formBuilder.build()).build(); // client.newCall(request).enqueue(callback); // } // // public void get(Callback callback) { // OkHttpClient client = new OkHttpClient.Builder().build(); // Request request = requestBuilder.build(); // call = client.newCall(request); // call.enqueue(callback); // } // } // }
import android.os.Bundle; import android.support.design.widget.Snackbar; import android.text.TextUtils; import android.widget.EditText; import android.widget.LinearLayout; import android.widget.Toast; import com.cxsj.runhdu.constant.URLs; import com.cxsj.runhdu.utils.HttpUtil; import com.dd.CircularProgressButton; import java.io.IOException; import okhttp3.Call; import okhttp3.Callback; import okhttp3.Response;
package com.cxsj.runhdu; /** * 用户反馈Activity */ public class FeedbackActivity extends BaseActivity { private LinearLayout rootLayout; private EditText feedbackText; private EditText contactText; private CircularProgressButton feedbackButton; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_feedback); setToolbar(R.id.feedback_toolbar, true); feedbackText = (EditText) findViewById(R.id.feedback_text); contactText = (EditText) findViewById(R.id.feedback_contact); feedbackButton = (CircularProgressButton) findViewById(R.id.feedback_button); rootLayout = (LinearLayout) findViewById(R.id.feedback_root_layout); feedbackButton.setIndeterminateProgressMode(true); feedbackButton.setOnClickListener(v -> { String feedbackStr = feedbackText.getText().toString(); String contactStr = contactText.getText().toString(); if (TextUtils.isEmpty(feedbackStr)) { Toast.makeText(this, "请输入反馈信息!", Toast.LENGTH_SHORT).show(); return; } if (TextUtils.isEmpty(contactStr)) contactStr = "未填写"; feedbackButton.setProgress(50); //提交反馈
// Path: app/src/main/java/com/cxsj/runhdu/constant/URLs.java // public class URLs { // public static final String DOWNLOAD = "http://d1.51gugu.com/170258/RunHDU"; // public static final String LOGIN = "http://112.74.115.231:8080/CXSJ/Login"; // public static final String REGISTER="http://112.74.115.231:8080/CXSJ/Register"; // public static final String GET_RUN_INFO = "http://112.74.115.231:8080/chuangxinshijian/ReadAll"; // public static final String UPLOAD_RUN_INFO = "http://112.74.115.231:8080/chuangxinshijian/Write"; // public static final String CLEAR_DATA = "http://112.74.115.231:8080/chuangxinshijian/ClearTheTable"; // public static final String UPDATE_URL = "http://112.74.115.231:8080/chuangxinshijian/VersionCompare"; // public static final String GET_RUN_TIMES = "http://112.74.115.231:8080/chuangxinshijian/ReadUserNameAndTimesOnly"; // public static final String UPLOAD_ALL_INFO = "http://112.74.115.231:8080/chuangxinshijian/WriteByJson"; // public static final String UPLOAD_PROFILE = "http://112.74.115.231:8080/CXSJ/UploadHead"; // public static final String PROFILE_URL = "http://112.74.115.231:8080/CXSJ/Image/"; // public static final String FEEDBACK_URL = "http://112.74.115.231:8080/chuangxinshijian/WriteFeedback"; // public static final String SUNNY_RUN_QUERY_API = "http://hdu.sunnysport.org.cn/api/student/achievements/"; // public static final String SUNNY_RUN_INFO_API = "http://hdu.sunnysport.org.cn/api/student/info/"; // public static final String DELETE_ITEM = "http://112.74.115.231:8080/chuangxinshijian/ClearByUserNameAndRunId"; // public static final String APPLY_FRIEND = "http://112.74.115.231:8080/CXSJ/Apply"; // public static final String REPLY_FRIEND = "http://112.74.115.231:8080/CXSJ/BeFriend"; // public static final String GET_FRIEND = "http://112.74.115.231:8080/CXSJ/MyFriends"; // public static final String DELETE_FRIEND = "http://112.74.115.231:8080/CXSJ/DeleteFriend"; // public static final String OFF_LINE = "http://112.74.115.231:8080/CXSJ/Xiaxian"; // } // // Path: app/src/main/java/com/cxsj/runhdu/utils/HttpUtil.java // public class HttpUtil { // private static RequestManager manager; // // public static RequestManager load(String url) { // manager = new RequestManager(); // manager.url(url); // return manager; // } // // public static class RequestManager { // private Request.Builder requestBuilder = new Request.Builder(); // private FormBody.Builder formBuilder = new FormBody.Builder(); // private Call call; // // private void url(String url) { // formBuilder = new FormBody.Builder(); // requestBuilder = new Request.Builder(); // // requestBuilder = requestBuilder.url(url); // } // // private void cancel() { // if (call != null) { // call.cancel(); // } // } // // public RequestManager addHeader(String key, String value) { // requestBuilder.addHeader(key, value); // return this; // } // // public RequestManager addParam(String key, String value) { // formBuilder = formBuilder.add(key, value); // return this; // } // // public void post(Callback callback) { // OkHttpClient client = new OkHttpClient.Builder() // .connectTimeout(3, TimeUnit.SECONDS) // .followRedirects(false) // .followSslRedirects(false) // .build(); // // Request request = requestBuilder.post(formBuilder.build()).build(); // client.newCall(request).enqueue(callback); // } // // public void get(Callback callback) { // OkHttpClient client = new OkHttpClient.Builder().build(); // Request request = requestBuilder.build(); // call = client.newCall(request); // call.enqueue(callback); // } // } // } // Path: app/src/main/java/com/cxsj/runhdu/FeedbackActivity.java import android.os.Bundle; import android.support.design.widget.Snackbar; import android.text.TextUtils; import android.widget.EditText; import android.widget.LinearLayout; import android.widget.Toast; import com.cxsj.runhdu.constant.URLs; import com.cxsj.runhdu.utils.HttpUtil; import com.dd.CircularProgressButton; import java.io.IOException; import okhttp3.Call; import okhttp3.Callback; import okhttp3.Response; package com.cxsj.runhdu; /** * 用户反馈Activity */ public class FeedbackActivity extends BaseActivity { private LinearLayout rootLayout; private EditText feedbackText; private EditText contactText; private CircularProgressButton feedbackButton; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_feedback); setToolbar(R.id.feedback_toolbar, true); feedbackText = (EditText) findViewById(R.id.feedback_text); contactText = (EditText) findViewById(R.id.feedback_contact); feedbackButton = (CircularProgressButton) findViewById(R.id.feedback_button); rootLayout = (LinearLayout) findViewById(R.id.feedback_root_layout); feedbackButton.setIndeterminateProgressMode(true); feedbackButton.setOnClickListener(v -> { String feedbackStr = feedbackText.getText().toString(); String contactStr = contactText.getText().toString(); if (TextUtils.isEmpty(feedbackStr)) { Toast.makeText(this, "请输入反馈信息!", Toast.LENGTH_SHORT).show(); return; } if (TextUtils.isEmpty(contactStr)) contactStr = "未填写"; feedbackButton.setProgress(50); //提交反馈
HttpUtil.load(URLs.FEEDBACK_URL)
SailFlorve/RunHDU
app/src/main/java/com/cxsj/runhdu/Model/AppModel.java
// Path: app/src/main/java/com/cxsj/runhdu/bean/gson/UpdateInfo.java // public class UpdateInfo { // private boolean isUpdate; // private String latestVersion; // private String currentVersion; // private String statement; // // public boolean isUpdate() { // return isUpdate; // } // // public void setUpdate(boolean update) { // isUpdate = update; // } // // public String getLatestVersion() { // return latestVersion; // } // // public void setLatestVersion(String latestVersion) { // this.latestVersion = latestVersion; // } // // public String getCurrentVersion() { // return currentVersion; // } // // public void setCurrentVersion(String currentVersion) { // this.currentVersion = currentVersion; // } // // public String getStatement() { // return statement; // } // // public void setStatement(String statement) { // this.statement = statement; // } // } // // Path: app/src/main/java/com/cxsj/runhdu/constant/URLs.java // public class URLs { // public static final String DOWNLOAD = "http://d1.51gugu.com/170258/RunHDU"; // public static final String LOGIN = "http://112.74.115.231:8080/CXSJ/Login"; // public static final String REGISTER="http://112.74.115.231:8080/CXSJ/Register"; // public static final String GET_RUN_INFO = "http://112.74.115.231:8080/chuangxinshijian/ReadAll"; // public static final String UPLOAD_RUN_INFO = "http://112.74.115.231:8080/chuangxinshijian/Write"; // public static final String CLEAR_DATA = "http://112.74.115.231:8080/chuangxinshijian/ClearTheTable"; // public static final String UPDATE_URL = "http://112.74.115.231:8080/chuangxinshijian/VersionCompare"; // public static final String GET_RUN_TIMES = "http://112.74.115.231:8080/chuangxinshijian/ReadUserNameAndTimesOnly"; // public static final String UPLOAD_ALL_INFO = "http://112.74.115.231:8080/chuangxinshijian/WriteByJson"; // public static final String UPLOAD_PROFILE = "http://112.74.115.231:8080/CXSJ/UploadHead"; // public static final String PROFILE_URL = "http://112.74.115.231:8080/CXSJ/Image/"; // public static final String FEEDBACK_URL = "http://112.74.115.231:8080/chuangxinshijian/WriteFeedback"; // public static final String SUNNY_RUN_QUERY_API = "http://hdu.sunnysport.org.cn/api/student/achievements/"; // public static final String SUNNY_RUN_INFO_API = "http://hdu.sunnysport.org.cn/api/student/info/"; // public static final String DELETE_ITEM = "http://112.74.115.231:8080/chuangxinshijian/ClearByUserNameAndRunId"; // public static final String APPLY_FRIEND = "http://112.74.115.231:8080/CXSJ/Apply"; // public static final String REPLY_FRIEND = "http://112.74.115.231:8080/CXSJ/BeFriend"; // public static final String GET_FRIEND = "http://112.74.115.231:8080/CXSJ/MyFriends"; // public static final String DELETE_FRIEND = "http://112.74.115.231:8080/CXSJ/DeleteFriend"; // public static final String OFF_LINE = "http://112.74.115.231:8080/CXSJ/Xiaxian"; // } // // Path: app/src/main/java/com/cxsj/runhdu/utils/HttpUtil.java // public class HttpUtil { // private static RequestManager manager; // // public static RequestManager load(String url) { // manager = new RequestManager(); // manager.url(url); // return manager; // } // // public static class RequestManager { // private Request.Builder requestBuilder = new Request.Builder(); // private FormBody.Builder formBuilder = new FormBody.Builder(); // private Call call; // // private void url(String url) { // formBuilder = new FormBody.Builder(); // requestBuilder = new Request.Builder(); // // requestBuilder = requestBuilder.url(url); // } // // private void cancel() { // if (call != null) { // call.cancel(); // } // } // // public RequestManager addHeader(String key, String value) { // requestBuilder.addHeader(key, value); // return this; // } // // public RequestManager addParam(String key, String value) { // formBuilder = formBuilder.add(key, value); // return this; // } // // public void post(Callback callback) { // OkHttpClient client = new OkHttpClient.Builder() // .connectTimeout(3, TimeUnit.SECONDS) // .followRedirects(false) // .followSslRedirects(false) // .build(); // // Request request = requestBuilder.post(formBuilder.build()).build(); // client.newCall(request).enqueue(callback); // } // // public void get(Callback callback) { // OkHttpClient client = new OkHttpClient.Builder().build(); // Request request = requestBuilder.build(); // call = client.newCall(request); // call.enqueue(callback); // } // } // }
import android.content.Context; import com.cxsj.runhdu.R; import com.cxsj.runhdu.bean.gson.UpdateInfo; import com.cxsj.runhdu.constant.URLs; import com.cxsj.runhdu.utils.HttpUtil; import com.google.gson.Gson; import com.google.gson.JsonSyntaxException; import java.io.IOException; import okhttp3.Call; import okhttp3.Callback; import okhttp3.Response;
package com.cxsj.runhdu.Model; /** * Created by SailFlorve on 2017/8/25 0025. * APP相关的数据请求封装 */ public class AppModel extends BaseModel { public interface UpdateCheckCallback {
// Path: app/src/main/java/com/cxsj/runhdu/bean/gson/UpdateInfo.java // public class UpdateInfo { // private boolean isUpdate; // private String latestVersion; // private String currentVersion; // private String statement; // // public boolean isUpdate() { // return isUpdate; // } // // public void setUpdate(boolean update) { // isUpdate = update; // } // // public String getLatestVersion() { // return latestVersion; // } // // public void setLatestVersion(String latestVersion) { // this.latestVersion = latestVersion; // } // // public String getCurrentVersion() { // return currentVersion; // } // // public void setCurrentVersion(String currentVersion) { // this.currentVersion = currentVersion; // } // // public String getStatement() { // return statement; // } // // public void setStatement(String statement) { // this.statement = statement; // } // } // // Path: app/src/main/java/com/cxsj/runhdu/constant/URLs.java // public class URLs { // public static final String DOWNLOAD = "http://d1.51gugu.com/170258/RunHDU"; // public static final String LOGIN = "http://112.74.115.231:8080/CXSJ/Login"; // public static final String REGISTER="http://112.74.115.231:8080/CXSJ/Register"; // public static final String GET_RUN_INFO = "http://112.74.115.231:8080/chuangxinshijian/ReadAll"; // public static final String UPLOAD_RUN_INFO = "http://112.74.115.231:8080/chuangxinshijian/Write"; // public static final String CLEAR_DATA = "http://112.74.115.231:8080/chuangxinshijian/ClearTheTable"; // public static final String UPDATE_URL = "http://112.74.115.231:8080/chuangxinshijian/VersionCompare"; // public static final String GET_RUN_TIMES = "http://112.74.115.231:8080/chuangxinshijian/ReadUserNameAndTimesOnly"; // public static final String UPLOAD_ALL_INFO = "http://112.74.115.231:8080/chuangxinshijian/WriteByJson"; // public static final String UPLOAD_PROFILE = "http://112.74.115.231:8080/CXSJ/UploadHead"; // public static final String PROFILE_URL = "http://112.74.115.231:8080/CXSJ/Image/"; // public static final String FEEDBACK_URL = "http://112.74.115.231:8080/chuangxinshijian/WriteFeedback"; // public static final String SUNNY_RUN_QUERY_API = "http://hdu.sunnysport.org.cn/api/student/achievements/"; // public static final String SUNNY_RUN_INFO_API = "http://hdu.sunnysport.org.cn/api/student/info/"; // public static final String DELETE_ITEM = "http://112.74.115.231:8080/chuangxinshijian/ClearByUserNameAndRunId"; // public static final String APPLY_FRIEND = "http://112.74.115.231:8080/CXSJ/Apply"; // public static final String REPLY_FRIEND = "http://112.74.115.231:8080/CXSJ/BeFriend"; // public static final String GET_FRIEND = "http://112.74.115.231:8080/CXSJ/MyFriends"; // public static final String DELETE_FRIEND = "http://112.74.115.231:8080/CXSJ/DeleteFriend"; // public static final String OFF_LINE = "http://112.74.115.231:8080/CXSJ/Xiaxian"; // } // // Path: app/src/main/java/com/cxsj/runhdu/utils/HttpUtil.java // public class HttpUtil { // private static RequestManager manager; // // public static RequestManager load(String url) { // manager = new RequestManager(); // manager.url(url); // return manager; // } // // public static class RequestManager { // private Request.Builder requestBuilder = new Request.Builder(); // private FormBody.Builder formBuilder = new FormBody.Builder(); // private Call call; // // private void url(String url) { // formBuilder = new FormBody.Builder(); // requestBuilder = new Request.Builder(); // // requestBuilder = requestBuilder.url(url); // } // // private void cancel() { // if (call != null) { // call.cancel(); // } // } // // public RequestManager addHeader(String key, String value) { // requestBuilder.addHeader(key, value); // return this; // } // // public RequestManager addParam(String key, String value) { // formBuilder = formBuilder.add(key, value); // return this; // } // // public void post(Callback callback) { // OkHttpClient client = new OkHttpClient.Builder() // .connectTimeout(3, TimeUnit.SECONDS) // .followRedirects(false) // .followSslRedirects(false) // .build(); // // Request request = requestBuilder.post(formBuilder.build()).build(); // client.newCall(request).enqueue(callback); // } // // public void get(Callback callback) { // OkHttpClient client = new OkHttpClient.Builder().build(); // Request request = requestBuilder.build(); // call = client.newCall(request); // call.enqueue(callback); // } // } // } // Path: app/src/main/java/com/cxsj/runhdu/Model/AppModel.java import android.content.Context; import com.cxsj.runhdu.R; import com.cxsj.runhdu.bean.gson.UpdateInfo; import com.cxsj.runhdu.constant.URLs; import com.cxsj.runhdu.utils.HttpUtil; import com.google.gson.Gson; import com.google.gson.JsonSyntaxException; import java.io.IOException; import okhttp3.Call; import okhttp3.Callback; import okhttp3.Response; package com.cxsj.runhdu.Model; /** * Created by SailFlorve on 2017/8/25 0025. * APP相关的数据请求封装 */ public class AppModel extends BaseModel { public interface UpdateCheckCallback {
void onSuccess(UpdateInfo updateInfo);
SailFlorve/RunHDU
app/src/main/java/com/cxsj/runhdu/Model/AppModel.java
// Path: app/src/main/java/com/cxsj/runhdu/bean/gson/UpdateInfo.java // public class UpdateInfo { // private boolean isUpdate; // private String latestVersion; // private String currentVersion; // private String statement; // // public boolean isUpdate() { // return isUpdate; // } // // public void setUpdate(boolean update) { // isUpdate = update; // } // // public String getLatestVersion() { // return latestVersion; // } // // public void setLatestVersion(String latestVersion) { // this.latestVersion = latestVersion; // } // // public String getCurrentVersion() { // return currentVersion; // } // // public void setCurrentVersion(String currentVersion) { // this.currentVersion = currentVersion; // } // // public String getStatement() { // return statement; // } // // public void setStatement(String statement) { // this.statement = statement; // } // } // // Path: app/src/main/java/com/cxsj/runhdu/constant/URLs.java // public class URLs { // public static final String DOWNLOAD = "http://d1.51gugu.com/170258/RunHDU"; // public static final String LOGIN = "http://112.74.115.231:8080/CXSJ/Login"; // public static final String REGISTER="http://112.74.115.231:8080/CXSJ/Register"; // public static final String GET_RUN_INFO = "http://112.74.115.231:8080/chuangxinshijian/ReadAll"; // public static final String UPLOAD_RUN_INFO = "http://112.74.115.231:8080/chuangxinshijian/Write"; // public static final String CLEAR_DATA = "http://112.74.115.231:8080/chuangxinshijian/ClearTheTable"; // public static final String UPDATE_URL = "http://112.74.115.231:8080/chuangxinshijian/VersionCompare"; // public static final String GET_RUN_TIMES = "http://112.74.115.231:8080/chuangxinshijian/ReadUserNameAndTimesOnly"; // public static final String UPLOAD_ALL_INFO = "http://112.74.115.231:8080/chuangxinshijian/WriteByJson"; // public static final String UPLOAD_PROFILE = "http://112.74.115.231:8080/CXSJ/UploadHead"; // public static final String PROFILE_URL = "http://112.74.115.231:8080/CXSJ/Image/"; // public static final String FEEDBACK_URL = "http://112.74.115.231:8080/chuangxinshijian/WriteFeedback"; // public static final String SUNNY_RUN_QUERY_API = "http://hdu.sunnysport.org.cn/api/student/achievements/"; // public static final String SUNNY_RUN_INFO_API = "http://hdu.sunnysport.org.cn/api/student/info/"; // public static final String DELETE_ITEM = "http://112.74.115.231:8080/chuangxinshijian/ClearByUserNameAndRunId"; // public static final String APPLY_FRIEND = "http://112.74.115.231:8080/CXSJ/Apply"; // public static final String REPLY_FRIEND = "http://112.74.115.231:8080/CXSJ/BeFriend"; // public static final String GET_FRIEND = "http://112.74.115.231:8080/CXSJ/MyFriends"; // public static final String DELETE_FRIEND = "http://112.74.115.231:8080/CXSJ/DeleteFriend"; // public static final String OFF_LINE = "http://112.74.115.231:8080/CXSJ/Xiaxian"; // } // // Path: app/src/main/java/com/cxsj/runhdu/utils/HttpUtil.java // public class HttpUtil { // private static RequestManager manager; // // public static RequestManager load(String url) { // manager = new RequestManager(); // manager.url(url); // return manager; // } // // public static class RequestManager { // private Request.Builder requestBuilder = new Request.Builder(); // private FormBody.Builder formBuilder = new FormBody.Builder(); // private Call call; // // private void url(String url) { // formBuilder = new FormBody.Builder(); // requestBuilder = new Request.Builder(); // // requestBuilder = requestBuilder.url(url); // } // // private void cancel() { // if (call != null) { // call.cancel(); // } // } // // public RequestManager addHeader(String key, String value) { // requestBuilder.addHeader(key, value); // return this; // } // // public RequestManager addParam(String key, String value) { // formBuilder = formBuilder.add(key, value); // return this; // } // // public void post(Callback callback) { // OkHttpClient client = new OkHttpClient.Builder() // .connectTimeout(3, TimeUnit.SECONDS) // .followRedirects(false) // .followSslRedirects(false) // .build(); // // Request request = requestBuilder.post(formBuilder.build()).build(); // client.newCall(request).enqueue(callback); // } // // public void get(Callback callback) { // OkHttpClient client = new OkHttpClient.Builder().build(); // Request request = requestBuilder.build(); // call = client.newCall(request); // call.enqueue(callback); // } // } // }
import android.content.Context; import com.cxsj.runhdu.R; import com.cxsj.runhdu.bean.gson.UpdateInfo; import com.cxsj.runhdu.constant.URLs; import com.cxsj.runhdu.utils.HttpUtil; import com.google.gson.Gson; import com.google.gson.JsonSyntaxException; import java.io.IOException; import okhttp3.Call; import okhttp3.Callback; import okhttp3.Response;
package com.cxsj.runhdu.Model; /** * Created by SailFlorve on 2017/8/25 0025. * APP相关的数据请求封装 */ public class AppModel extends BaseModel { public interface UpdateCheckCallback { void onSuccess(UpdateInfo updateInfo); void onFailure(String msg); } public static void checkUpdate(Context context, AppModel.UpdateCheckCallback callback) { final String currentVersion = context.getResources().getString(R.string.current_version);
// Path: app/src/main/java/com/cxsj/runhdu/bean/gson/UpdateInfo.java // public class UpdateInfo { // private boolean isUpdate; // private String latestVersion; // private String currentVersion; // private String statement; // // public boolean isUpdate() { // return isUpdate; // } // // public void setUpdate(boolean update) { // isUpdate = update; // } // // public String getLatestVersion() { // return latestVersion; // } // // public void setLatestVersion(String latestVersion) { // this.latestVersion = latestVersion; // } // // public String getCurrentVersion() { // return currentVersion; // } // // public void setCurrentVersion(String currentVersion) { // this.currentVersion = currentVersion; // } // // public String getStatement() { // return statement; // } // // public void setStatement(String statement) { // this.statement = statement; // } // } // // Path: app/src/main/java/com/cxsj/runhdu/constant/URLs.java // public class URLs { // public static final String DOWNLOAD = "http://d1.51gugu.com/170258/RunHDU"; // public static final String LOGIN = "http://112.74.115.231:8080/CXSJ/Login"; // public static final String REGISTER="http://112.74.115.231:8080/CXSJ/Register"; // public static final String GET_RUN_INFO = "http://112.74.115.231:8080/chuangxinshijian/ReadAll"; // public static final String UPLOAD_RUN_INFO = "http://112.74.115.231:8080/chuangxinshijian/Write"; // public static final String CLEAR_DATA = "http://112.74.115.231:8080/chuangxinshijian/ClearTheTable"; // public static final String UPDATE_URL = "http://112.74.115.231:8080/chuangxinshijian/VersionCompare"; // public static final String GET_RUN_TIMES = "http://112.74.115.231:8080/chuangxinshijian/ReadUserNameAndTimesOnly"; // public static final String UPLOAD_ALL_INFO = "http://112.74.115.231:8080/chuangxinshijian/WriteByJson"; // public static final String UPLOAD_PROFILE = "http://112.74.115.231:8080/CXSJ/UploadHead"; // public static final String PROFILE_URL = "http://112.74.115.231:8080/CXSJ/Image/"; // public static final String FEEDBACK_URL = "http://112.74.115.231:8080/chuangxinshijian/WriteFeedback"; // public static final String SUNNY_RUN_QUERY_API = "http://hdu.sunnysport.org.cn/api/student/achievements/"; // public static final String SUNNY_RUN_INFO_API = "http://hdu.sunnysport.org.cn/api/student/info/"; // public static final String DELETE_ITEM = "http://112.74.115.231:8080/chuangxinshijian/ClearByUserNameAndRunId"; // public static final String APPLY_FRIEND = "http://112.74.115.231:8080/CXSJ/Apply"; // public static final String REPLY_FRIEND = "http://112.74.115.231:8080/CXSJ/BeFriend"; // public static final String GET_FRIEND = "http://112.74.115.231:8080/CXSJ/MyFriends"; // public static final String DELETE_FRIEND = "http://112.74.115.231:8080/CXSJ/DeleteFriend"; // public static final String OFF_LINE = "http://112.74.115.231:8080/CXSJ/Xiaxian"; // } // // Path: app/src/main/java/com/cxsj/runhdu/utils/HttpUtil.java // public class HttpUtil { // private static RequestManager manager; // // public static RequestManager load(String url) { // manager = new RequestManager(); // manager.url(url); // return manager; // } // // public static class RequestManager { // private Request.Builder requestBuilder = new Request.Builder(); // private FormBody.Builder formBuilder = new FormBody.Builder(); // private Call call; // // private void url(String url) { // formBuilder = new FormBody.Builder(); // requestBuilder = new Request.Builder(); // // requestBuilder = requestBuilder.url(url); // } // // private void cancel() { // if (call != null) { // call.cancel(); // } // } // // public RequestManager addHeader(String key, String value) { // requestBuilder.addHeader(key, value); // return this; // } // // public RequestManager addParam(String key, String value) { // formBuilder = formBuilder.add(key, value); // return this; // } // // public void post(Callback callback) { // OkHttpClient client = new OkHttpClient.Builder() // .connectTimeout(3, TimeUnit.SECONDS) // .followRedirects(false) // .followSslRedirects(false) // .build(); // // Request request = requestBuilder.post(formBuilder.build()).build(); // client.newCall(request).enqueue(callback); // } // // public void get(Callback callback) { // OkHttpClient client = new OkHttpClient.Builder().build(); // Request request = requestBuilder.build(); // call = client.newCall(request); // call.enqueue(callback); // } // } // } // Path: app/src/main/java/com/cxsj/runhdu/Model/AppModel.java import android.content.Context; import com.cxsj.runhdu.R; import com.cxsj.runhdu.bean.gson.UpdateInfo; import com.cxsj.runhdu.constant.URLs; import com.cxsj.runhdu.utils.HttpUtil; import com.google.gson.Gson; import com.google.gson.JsonSyntaxException; import java.io.IOException; import okhttp3.Call; import okhttp3.Callback; import okhttp3.Response; package com.cxsj.runhdu.Model; /** * Created by SailFlorve on 2017/8/25 0025. * APP相关的数据请求封装 */ public class AppModel extends BaseModel { public interface UpdateCheckCallback { void onSuccess(UpdateInfo updateInfo); void onFailure(String msg); } public static void checkUpdate(Context context, AppModel.UpdateCheckCallback callback) { final String currentVersion = context.getResources().getString(R.string.current_version);
HttpUtil.load(URLs.UPDATE_URL)
SailFlorve/RunHDU
app/src/main/java/com/cxsj/runhdu/Model/AppModel.java
// Path: app/src/main/java/com/cxsj/runhdu/bean/gson/UpdateInfo.java // public class UpdateInfo { // private boolean isUpdate; // private String latestVersion; // private String currentVersion; // private String statement; // // public boolean isUpdate() { // return isUpdate; // } // // public void setUpdate(boolean update) { // isUpdate = update; // } // // public String getLatestVersion() { // return latestVersion; // } // // public void setLatestVersion(String latestVersion) { // this.latestVersion = latestVersion; // } // // public String getCurrentVersion() { // return currentVersion; // } // // public void setCurrentVersion(String currentVersion) { // this.currentVersion = currentVersion; // } // // public String getStatement() { // return statement; // } // // public void setStatement(String statement) { // this.statement = statement; // } // } // // Path: app/src/main/java/com/cxsj/runhdu/constant/URLs.java // public class URLs { // public static final String DOWNLOAD = "http://d1.51gugu.com/170258/RunHDU"; // public static final String LOGIN = "http://112.74.115.231:8080/CXSJ/Login"; // public static final String REGISTER="http://112.74.115.231:8080/CXSJ/Register"; // public static final String GET_RUN_INFO = "http://112.74.115.231:8080/chuangxinshijian/ReadAll"; // public static final String UPLOAD_RUN_INFO = "http://112.74.115.231:8080/chuangxinshijian/Write"; // public static final String CLEAR_DATA = "http://112.74.115.231:8080/chuangxinshijian/ClearTheTable"; // public static final String UPDATE_URL = "http://112.74.115.231:8080/chuangxinshijian/VersionCompare"; // public static final String GET_RUN_TIMES = "http://112.74.115.231:8080/chuangxinshijian/ReadUserNameAndTimesOnly"; // public static final String UPLOAD_ALL_INFO = "http://112.74.115.231:8080/chuangxinshijian/WriteByJson"; // public static final String UPLOAD_PROFILE = "http://112.74.115.231:8080/CXSJ/UploadHead"; // public static final String PROFILE_URL = "http://112.74.115.231:8080/CXSJ/Image/"; // public static final String FEEDBACK_URL = "http://112.74.115.231:8080/chuangxinshijian/WriteFeedback"; // public static final String SUNNY_RUN_QUERY_API = "http://hdu.sunnysport.org.cn/api/student/achievements/"; // public static final String SUNNY_RUN_INFO_API = "http://hdu.sunnysport.org.cn/api/student/info/"; // public static final String DELETE_ITEM = "http://112.74.115.231:8080/chuangxinshijian/ClearByUserNameAndRunId"; // public static final String APPLY_FRIEND = "http://112.74.115.231:8080/CXSJ/Apply"; // public static final String REPLY_FRIEND = "http://112.74.115.231:8080/CXSJ/BeFriend"; // public static final String GET_FRIEND = "http://112.74.115.231:8080/CXSJ/MyFriends"; // public static final String DELETE_FRIEND = "http://112.74.115.231:8080/CXSJ/DeleteFriend"; // public static final String OFF_LINE = "http://112.74.115.231:8080/CXSJ/Xiaxian"; // } // // Path: app/src/main/java/com/cxsj/runhdu/utils/HttpUtil.java // public class HttpUtil { // private static RequestManager manager; // // public static RequestManager load(String url) { // manager = new RequestManager(); // manager.url(url); // return manager; // } // // public static class RequestManager { // private Request.Builder requestBuilder = new Request.Builder(); // private FormBody.Builder formBuilder = new FormBody.Builder(); // private Call call; // // private void url(String url) { // formBuilder = new FormBody.Builder(); // requestBuilder = new Request.Builder(); // // requestBuilder = requestBuilder.url(url); // } // // private void cancel() { // if (call != null) { // call.cancel(); // } // } // // public RequestManager addHeader(String key, String value) { // requestBuilder.addHeader(key, value); // return this; // } // // public RequestManager addParam(String key, String value) { // formBuilder = formBuilder.add(key, value); // return this; // } // // public void post(Callback callback) { // OkHttpClient client = new OkHttpClient.Builder() // .connectTimeout(3, TimeUnit.SECONDS) // .followRedirects(false) // .followSslRedirects(false) // .build(); // // Request request = requestBuilder.post(formBuilder.build()).build(); // client.newCall(request).enqueue(callback); // } // // public void get(Callback callback) { // OkHttpClient client = new OkHttpClient.Builder().build(); // Request request = requestBuilder.build(); // call = client.newCall(request); // call.enqueue(callback); // } // } // }
import android.content.Context; import com.cxsj.runhdu.R; import com.cxsj.runhdu.bean.gson.UpdateInfo; import com.cxsj.runhdu.constant.URLs; import com.cxsj.runhdu.utils.HttpUtil; import com.google.gson.Gson; import com.google.gson.JsonSyntaxException; import java.io.IOException; import okhttp3.Call; import okhttp3.Callback; import okhttp3.Response;
package com.cxsj.runhdu.Model; /** * Created by SailFlorve on 2017/8/25 0025. * APP相关的数据请求封装 */ public class AppModel extends BaseModel { public interface UpdateCheckCallback { void onSuccess(UpdateInfo updateInfo); void onFailure(String msg); } public static void checkUpdate(Context context, AppModel.UpdateCheckCallback callback) { final String currentVersion = context.getResources().getString(R.string.current_version);
// Path: app/src/main/java/com/cxsj/runhdu/bean/gson/UpdateInfo.java // public class UpdateInfo { // private boolean isUpdate; // private String latestVersion; // private String currentVersion; // private String statement; // // public boolean isUpdate() { // return isUpdate; // } // // public void setUpdate(boolean update) { // isUpdate = update; // } // // public String getLatestVersion() { // return latestVersion; // } // // public void setLatestVersion(String latestVersion) { // this.latestVersion = latestVersion; // } // // public String getCurrentVersion() { // return currentVersion; // } // // public void setCurrentVersion(String currentVersion) { // this.currentVersion = currentVersion; // } // // public String getStatement() { // return statement; // } // // public void setStatement(String statement) { // this.statement = statement; // } // } // // Path: app/src/main/java/com/cxsj/runhdu/constant/URLs.java // public class URLs { // public static final String DOWNLOAD = "http://d1.51gugu.com/170258/RunHDU"; // public static final String LOGIN = "http://112.74.115.231:8080/CXSJ/Login"; // public static final String REGISTER="http://112.74.115.231:8080/CXSJ/Register"; // public static final String GET_RUN_INFO = "http://112.74.115.231:8080/chuangxinshijian/ReadAll"; // public static final String UPLOAD_RUN_INFO = "http://112.74.115.231:8080/chuangxinshijian/Write"; // public static final String CLEAR_DATA = "http://112.74.115.231:8080/chuangxinshijian/ClearTheTable"; // public static final String UPDATE_URL = "http://112.74.115.231:8080/chuangxinshijian/VersionCompare"; // public static final String GET_RUN_TIMES = "http://112.74.115.231:8080/chuangxinshijian/ReadUserNameAndTimesOnly"; // public static final String UPLOAD_ALL_INFO = "http://112.74.115.231:8080/chuangxinshijian/WriteByJson"; // public static final String UPLOAD_PROFILE = "http://112.74.115.231:8080/CXSJ/UploadHead"; // public static final String PROFILE_URL = "http://112.74.115.231:8080/CXSJ/Image/"; // public static final String FEEDBACK_URL = "http://112.74.115.231:8080/chuangxinshijian/WriteFeedback"; // public static final String SUNNY_RUN_QUERY_API = "http://hdu.sunnysport.org.cn/api/student/achievements/"; // public static final String SUNNY_RUN_INFO_API = "http://hdu.sunnysport.org.cn/api/student/info/"; // public static final String DELETE_ITEM = "http://112.74.115.231:8080/chuangxinshijian/ClearByUserNameAndRunId"; // public static final String APPLY_FRIEND = "http://112.74.115.231:8080/CXSJ/Apply"; // public static final String REPLY_FRIEND = "http://112.74.115.231:8080/CXSJ/BeFriend"; // public static final String GET_FRIEND = "http://112.74.115.231:8080/CXSJ/MyFriends"; // public static final String DELETE_FRIEND = "http://112.74.115.231:8080/CXSJ/DeleteFriend"; // public static final String OFF_LINE = "http://112.74.115.231:8080/CXSJ/Xiaxian"; // } // // Path: app/src/main/java/com/cxsj/runhdu/utils/HttpUtil.java // public class HttpUtil { // private static RequestManager manager; // // public static RequestManager load(String url) { // manager = new RequestManager(); // manager.url(url); // return manager; // } // // public static class RequestManager { // private Request.Builder requestBuilder = new Request.Builder(); // private FormBody.Builder formBuilder = new FormBody.Builder(); // private Call call; // // private void url(String url) { // formBuilder = new FormBody.Builder(); // requestBuilder = new Request.Builder(); // // requestBuilder = requestBuilder.url(url); // } // // private void cancel() { // if (call != null) { // call.cancel(); // } // } // // public RequestManager addHeader(String key, String value) { // requestBuilder.addHeader(key, value); // return this; // } // // public RequestManager addParam(String key, String value) { // formBuilder = formBuilder.add(key, value); // return this; // } // // public void post(Callback callback) { // OkHttpClient client = new OkHttpClient.Builder() // .connectTimeout(3, TimeUnit.SECONDS) // .followRedirects(false) // .followSslRedirects(false) // .build(); // // Request request = requestBuilder.post(formBuilder.build()).build(); // client.newCall(request).enqueue(callback); // } // // public void get(Callback callback) { // OkHttpClient client = new OkHttpClient.Builder().build(); // Request request = requestBuilder.build(); // call = client.newCall(request); // call.enqueue(callback); // } // } // } // Path: app/src/main/java/com/cxsj/runhdu/Model/AppModel.java import android.content.Context; import com.cxsj.runhdu.R; import com.cxsj.runhdu.bean.gson.UpdateInfo; import com.cxsj.runhdu.constant.URLs; import com.cxsj.runhdu.utils.HttpUtil; import com.google.gson.Gson; import com.google.gson.JsonSyntaxException; import java.io.IOException; import okhttp3.Call; import okhttp3.Callback; import okhttp3.Response; package com.cxsj.runhdu.Model; /** * Created by SailFlorve on 2017/8/25 0025. * APP相关的数据请求封装 */ public class AppModel extends BaseModel { public interface UpdateCheckCallback { void onSuccess(UpdateInfo updateInfo); void onFailure(String msg); } public static void checkUpdate(Context context, AppModel.UpdateCheckCallback callback) { final String currentVersion = context.getResources().getString(R.string.current_version);
HttpUtil.load(URLs.UPDATE_URL)
SailFlorve/RunHDU
app/src/main/java/com/cxsj/runhdu/Model/BaseModel.java
// Path: app/src/main/java/com/cxsj/runhdu/bean/gson/Status.java // public class Status { // @SerializedName("Result") // private boolean result; // // @SerializedName("Message") // private String message; // // @SerializedName("Which") // private int which; // // public boolean getResult() { // return result; // } // // public String getMessage() { // return message; // } // // public int getWhich() { // return which; // } // // }
import android.os.Handler; import android.os.Looper; import android.util.Log; import com.cxsj.runhdu.bean.gson.Status; import com.google.gson.Gson; import com.google.gson.JsonSyntaxException; import java.io.IOException; import okhttp3.Call; import okhttp3.Callback; import okhttp3.Response;
package com.cxsj.runhdu.Model; /** * Created by SailFlorve on 2017/8/25 0025. * 所有model基类 */ public class BaseModel { protected static final String TAG = ""; static final String CONNECT_FAILED = "网络连接失败。"; static final String RETURN_DATA_ERROR = "服务器数据出错。"; static Handler mHandler = new Handler(Looper.getMainLooper()); public interface BaseCallback { void onFailure(String msg); void onSuccess(); } /** * 检查服务器返回为true还是false */ private static void checkStatusResponse(Response response, BaseCallback callback) throws IOException { String result = response.body().string(); Log.d(TAG, "checkStatusResponse: " + result); mHandler.post(() -> { if (result.equals("true")) { callback.onSuccess(); } else { callback.onFailure(RETURN_DATA_ERROR); } }); } private static void checkJsonStatusResponse(Response response, BaseCallback callback) throws IOException { String jsonStr = response.body().string(); Log.d(TAG, "checkJsonStatusResponse: " + jsonStr); mHandler.post(() -> {
// Path: app/src/main/java/com/cxsj/runhdu/bean/gson/Status.java // public class Status { // @SerializedName("Result") // private boolean result; // // @SerializedName("Message") // private String message; // // @SerializedName("Which") // private int which; // // public boolean getResult() { // return result; // } // // public String getMessage() { // return message; // } // // public int getWhich() { // return which; // } // // } // Path: app/src/main/java/com/cxsj/runhdu/Model/BaseModel.java import android.os.Handler; import android.os.Looper; import android.util.Log; import com.cxsj.runhdu.bean.gson.Status; import com.google.gson.Gson; import com.google.gson.JsonSyntaxException; import java.io.IOException; import okhttp3.Call; import okhttp3.Callback; import okhttp3.Response; package com.cxsj.runhdu.Model; /** * Created by SailFlorve on 2017/8/25 0025. * 所有model基类 */ public class BaseModel { protected static final String TAG = ""; static final String CONNECT_FAILED = "网络连接失败。"; static final String RETURN_DATA_ERROR = "服务器数据出错。"; static Handler mHandler = new Handler(Looper.getMainLooper()); public interface BaseCallback { void onFailure(String msg); void onSuccess(); } /** * 检查服务器返回为true还是false */ private static void checkStatusResponse(Response response, BaseCallback callback) throws IOException { String result = response.body().string(); Log.d(TAG, "checkStatusResponse: " + result); mHandler.post(() -> { if (result.equals("true")) { callback.onSuccess(); } else { callback.onFailure(RETURN_DATA_ERROR); } }); } private static void checkJsonStatusResponse(Response response, BaseCallback callback) throws IOException { String jsonStr = response.body().string(); Log.d(TAG, "checkJsonStatusResponse: " + jsonStr); mHandler.post(() -> {
Status status = null;
SailFlorve/RunHDU
app/src/main/java/com/cxsj/runhdu/utils/ImageUtil.java
// Path: app/src/main/java/com/cxsj/runhdu/constant/Types.java // public class Types { // public final static int TYPE_YEAR = 1000; // public final static int TYPE_MONTH = 1001; // public final static int TYPE_DATE = 1002; // public final static int TYPE_HOUR = 1003; // public final static int TYPE_MINUTE = 1004; // public final static int TYPE_SECOND = 1005; // public final static int TYPE_MONTH_DATE = 1006; // public final static int TYPE_CURRENT_TIME = 1007; // public final static int TYPE_AM_PM = 1008; // public final static int TYPE_CHANGE_PROFILE = 1009; // public final static int TYPE_CHANGE_MENU_BG = 1010; // public final static int MANUAL_UPDATE = 1011; // public final static int AUTO_UPDATE = 1012; // public final static int TYPE_SAVE_PROFILE = 1013; // public final static int TYPE_STRING_FORM=1014; // } // // Path: app/src/main/java/com/cxsj/runhdu/constant/URLs.java // public class URLs { // public static final String DOWNLOAD = "http://d1.51gugu.com/170258/RunHDU"; // public static final String LOGIN = "http://112.74.115.231:8080/CXSJ/Login"; // public static final String REGISTER="http://112.74.115.231:8080/CXSJ/Register"; // public static final String GET_RUN_INFO = "http://112.74.115.231:8080/chuangxinshijian/ReadAll"; // public static final String UPLOAD_RUN_INFO = "http://112.74.115.231:8080/chuangxinshijian/Write"; // public static final String CLEAR_DATA = "http://112.74.115.231:8080/chuangxinshijian/ClearTheTable"; // public static final String UPDATE_URL = "http://112.74.115.231:8080/chuangxinshijian/VersionCompare"; // public static final String GET_RUN_TIMES = "http://112.74.115.231:8080/chuangxinshijian/ReadUserNameAndTimesOnly"; // public static final String UPLOAD_ALL_INFO = "http://112.74.115.231:8080/chuangxinshijian/WriteByJson"; // public static final String UPLOAD_PROFILE = "http://112.74.115.231:8080/CXSJ/UploadHead"; // public static final String PROFILE_URL = "http://112.74.115.231:8080/CXSJ/Image/"; // public static final String FEEDBACK_URL = "http://112.74.115.231:8080/chuangxinshijian/WriteFeedback"; // public static final String SUNNY_RUN_QUERY_API = "http://hdu.sunnysport.org.cn/api/student/achievements/"; // public static final String SUNNY_RUN_INFO_API = "http://hdu.sunnysport.org.cn/api/student/info/"; // public static final String DELETE_ITEM = "http://112.74.115.231:8080/chuangxinshijian/ClearByUserNameAndRunId"; // public static final String APPLY_FRIEND = "http://112.74.115.231:8080/CXSJ/Apply"; // public static final String REPLY_FRIEND = "http://112.74.115.231:8080/CXSJ/BeFriend"; // public static final String GET_FRIEND = "http://112.74.115.231:8080/CXSJ/MyFriends"; // public static final String DELETE_FRIEND = "http://112.74.115.231:8080/CXSJ/DeleteFriend"; // public static final String OFF_LINE = "http://112.74.115.231:8080/CXSJ/Xiaxian"; // }
import android.app.Activity; import android.content.Context; import android.content.Intent; import android.graphics.Bitmap; import android.graphics.Rect; import android.net.Uri; import android.os.Environment; import android.test.ActivityTestCase; import android.util.Base64; import android.view.View; import com.baidu.mapapi.map.BitmapDescriptor; import com.cxsj.runhdu.constant.Types; import com.cxsj.runhdu.constant.URLs; import java.io.ByteArrayOutputStream; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.IOException; import okhttp3.Call; import okhttp3.Callback; import okhttp3.Response;
package com.cxsj.runhdu.utils; /** * Created by Sail on 2017/5/21 0021. * 图片处理工具 */ public class ImageUtil { /** * 保存图片到相册。 * * @param context 上下文 * @param bitmap * @param fileName 保存的路径 */ public static String saveToSDCard(Context context, Bitmap bitmap, String fileName) { FileOutputStream fos; String saveDir = context.getExternalFilesDir(Environment.DIRECTORY_PICTURES) + fileName; try { fos = new FileOutputStream(saveDir); if (null != fos) { bitmap.compress(Bitmap.CompressFormat.JPEG, 90, fos); fos.flush(); fos.close(); return saveDir; } } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } return null; } /** * 保存图片至服务器 * * @param username * @param bitmap */ public static void saveToServer(String username, Bitmap bitmap) { ByteArrayOutputStream bos = new ByteArrayOutputStream(); bitmap.compress(Bitmap.CompressFormat.PNG, 100, bos); byte[] imgArray = bos.toByteArray(); String imgStr = Base64.encodeToString(imgArray, Base64.DEFAULT);
// Path: app/src/main/java/com/cxsj/runhdu/constant/Types.java // public class Types { // public final static int TYPE_YEAR = 1000; // public final static int TYPE_MONTH = 1001; // public final static int TYPE_DATE = 1002; // public final static int TYPE_HOUR = 1003; // public final static int TYPE_MINUTE = 1004; // public final static int TYPE_SECOND = 1005; // public final static int TYPE_MONTH_DATE = 1006; // public final static int TYPE_CURRENT_TIME = 1007; // public final static int TYPE_AM_PM = 1008; // public final static int TYPE_CHANGE_PROFILE = 1009; // public final static int TYPE_CHANGE_MENU_BG = 1010; // public final static int MANUAL_UPDATE = 1011; // public final static int AUTO_UPDATE = 1012; // public final static int TYPE_SAVE_PROFILE = 1013; // public final static int TYPE_STRING_FORM=1014; // } // // Path: app/src/main/java/com/cxsj/runhdu/constant/URLs.java // public class URLs { // public static final String DOWNLOAD = "http://d1.51gugu.com/170258/RunHDU"; // public static final String LOGIN = "http://112.74.115.231:8080/CXSJ/Login"; // public static final String REGISTER="http://112.74.115.231:8080/CXSJ/Register"; // public static final String GET_RUN_INFO = "http://112.74.115.231:8080/chuangxinshijian/ReadAll"; // public static final String UPLOAD_RUN_INFO = "http://112.74.115.231:8080/chuangxinshijian/Write"; // public static final String CLEAR_DATA = "http://112.74.115.231:8080/chuangxinshijian/ClearTheTable"; // public static final String UPDATE_URL = "http://112.74.115.231:8080/chuangxinshijian/VersionCompare"; // public static final String GET_RUN_TIMES = "http://112.74.115.231:8080/chuangxinshijian/ReadUserNameAndTimesOnly"; // public static final String UPLOAD_ALL_INFO = "http://112.74.115.231:8080/chuangxinshijian/WriteByJson"; // public static final String UPLOAD_PROFILE = "http://112.74.115.231:8080/CXSJ/UploadHead"; // public static final String PROFILE_URL = "http://112.74.115.231:8080/CXSJ/Image/"; // public static final String FEEDBACK_URL = "http://112.74.115.231:8080/chuangxinshijian/WriteFeedback"; // public static final String SUNNY_RUN_QUERY_API = "http://hdu.sunnysport.org.cn/api/student/achievements/"; // public static final String SUNNY_RUN_INFO_API = "http://hdu.sunnysport.org.cn/api/student/info/"; // public static final String DELETE_ITEM = "http://112.74.115.231:8080/chuangxinshijian/ClearByUserNameAndRunId"; // public static final String APPLY_FRIEND = "http://112.74.115.231:8080/CXSJ/Apply"; // public static final String REPLY_FRIEND = "http://112.74.115.231:8080/CXSJ/BeFriend"; // public static final String GET_FRIEND = "http://112.74.115.231:8080/CXSJ/MyFriends"; // public static final String DELETE_FRIEND = "http://112.74.115.231:8080/CXSJ/DeleteFriend"; // public static final String OFF_LINE = "http://112.74.115.231:8080/CXSJ/Xiaxian"; // } // Path: app/src/main/java/com/cxsj/runhdu/utils/ImageUtil.java import android.app.Activity; import android.content.Context; import android.content.Intent; import android.graphics.Bitmap; import android.graphics.Rect; import android.net.Uri; import android.os.Environment; import android.test.ActivityTestCase; import android.util.Base64; import android.view.View; import com.baidu.mapapi.map.BitmapDescriptor; import com.cxsj.runhdu.constant.Types; import com.cxsj.runhdu.constant.URLs; import java.io.ByteArrayOutputStream; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.IOException; import okhttp3.Call; import okhttp3.Callback; import okhttp3.Response; package com.cxsj.runhdu.utils; /** * Created by Sail on 2017/5/21 0021. * 图片处理工具 */ public class ImageUtil { /** * 保存图片到相册。 * * @param context 上下文 * @param bitmap * @param fileName 保存的路径 */ public static String saveToSDCard(Context context, Bitmap bitmap, String fileName) { FileOutputStream fos; String saveDir = context.getExternalFilesDir(Environment.DIRECTORY_PICTURES) + fileName; try { fos = new FileOutputStream(saveDir); if (null != fos) { bitmap.compress(Bitmap.CompressFormat.JPEG, 90, fos); fos.flush(); fos.close(); return saveDir; } } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } return null; } /** * 保存图片至服务器 * * @param username * @param bitmap */ public static void saveToServer(String username, Bitmap bitmap) { ByteArrayOutputStream bos = new ByteArrayOutputStream(); bitmap.compress(Bitmap.CompressFormat.PNG, 100, bos); byte[] imgArray = bos.toByteArray(); String imgStr = Base64.encodeToString(imgArray, Base64.DEFAULT);
HttpUtil.load(URLs.UPLOAD_PROFILE)
SailFlorve/RunHDU
app/src/main/java/com/cxsj/runhdu/utils/ImageUtil.java
// Path: app/src/main/java/com/cxsj/runhdu/constant/Types.java // public class Types { // public final static int TYPE_YEAR = 1000; // public final static int TYPE_MONTH = 1001; // public final static int TYPE_DATE = 1002; // public final static int TYPE_HOUR = 1003; // public final static int TYPE_MINUTE = 1004; // public final static int TYPE_SECOND = 1005; // public final static int TYPE_MONTH_DATE = 1006; // public final static int TYPE_CURRENT_TIME = 1007; // public final static int TYPE_AM_PM = 1008; // public final static int TYPE_CHANGE_PROFILE = 1009; // public final static int TYPE_CHANGE_MENU_BG = 1010; // public final static int MANUAL_UPDATE = 1011; // public final static int AUTO_UPDATE = 1012; // public final static int TYPE_SAVE_PROFILE = 1013; // public final static int TYPE_STRING_FORM=1014; // } // // Path: app/src/main/java/com/cxsj/runhdu/constant/URLs.java // public class URLs { // public static final String DOWNLOAD = "http://d1.51gugu.com/170258/RunHDU"; // public static final String LOGIN = "http://112.74.115.231:8080/CXSJ/Login"; // public static final String REGISTER="http://112.74.115.231:8080/CXSJ/Register"; // public static final String GET_RUN_INFO = "http://112.74.115.231:8080/chuangxinshijian/ReadAll"; // public static final String UPLOAD_RUN_INFO = "http://112.74.115.231:8080/chuangxinshijian/Write"; // public static final String CLEAR_DATA = "http://112.74.115.231:8080/chuangxinshijian/ClearTheTable"; // public static final String UPDATE_URL = "http://112.74.115.231:8080/chuangxinshijian/VersionCompare"; // public static final String GET_RUN_TIMES = "http://112.74.115.231:8080/chuangxinshijian/ReadUserNameAndTimesOnly"; // public static final String UPLOAD_ALL_INFO = "http://112.74.115.231:8080/chuangxinshijian/WriteByJson"; // public static final String UPLOAD_PROFILE = "http://112.74.115.231:8080/CXSJ/UploadHead"; // public static final String PROFILE_URL = "http://112.74.115.231:8080/CXSJ/Image/"; // public static final String FEEDBACK_URL = "http://112.74.115.231:8080/chuangxinshijian/WriteFeedback"; // public static final String SUNNY_RUN_QUERY_API = "http://hdu.sunnysport.org.cn/api/student/achievements/"; // public static final String SUNNY_RUN_INFO_API = "http://hdu.sunnysport.org.cn/api/student/info/"; // public static final String DELETE_ITEM = "http://112.74.115.231:8080/chuangxinshijian/ClearByUserNameAndRunId"; // public static final String APPLY_FRIEND = "http://112.74.115.231:8080/CXSJ/Apply"; // public static final String REPLY_FRIEND = "http://112.74.115.231:8080/CXSJ/BeFriend"; // public static final String GET_FRIEND = "http://112.74.115.231:8080/CXSJ/MyFriends"; // public static final String DELETE_FRIEND = "http://112.74.115.231:8080/CXSJ/DeleteFriend"; // public static final String OFF_LINE = "http://112.74.115.231:8080/CXSJ/Xiaxian"; // }
import android.app.Activity; import android.content.Context; import android.content.Intent; import android.graphics.Bitmap; import android.graphics.Rect; import android.net.Uri; import android.os.Environment; import android.test.ActivityTestCase; import android.util.Base64; import android.view.View; import com.baidu.mapapi.map.BitmapDescriptor; import com.cxsj.runhdu.constant.Types; import com.cxsj.runhdu.constant.URLs; import java.io.ByteArrayOutputStream; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.IOException; import okhttp3.Call; import okhttp3.Callback; import okhttp3.Response;
} public static Bitmap takeScreenShot(View view) { view.setDrawingCacheEnabled(true); Bitmap tBitmap = view.getDrawingCache(); tBitmap = Bitmap.createBitmap(tBitmap); view.setDrawingCacheEnabled(false); if (tBitmap != null) { return tBitmap; } else { return null; } } public static void openPhotoChooser(Activity activity, int resultCode) { Intent intent = new Intent(Intent.ACTION_PICK); intent.setType("image/*");//相片类型 activity.startActivityForResult(intent, resultCode); } public static void openPhotoCutter(Activity activity, Uri uri) { Intent intent = new Intent("com.android.camera.action.CROP"); intent.setDataAndType(uri, "image/*"); intent.putExtra("crop", "true"); intent.putExtra("aspectX", 1); intent.putExtra("aspectY", 1); intent.putExtra("outputX", 192); intent.putExtra("outputY", 192); intent.putExtra("return-data", true); intent.putExtra("outputFormat", Bitmap.CompressFormat.JPEG.toString());
// Path: app/src/main/java/com/cxsj/runhdu/constant/Types.java // public class Types { // public final static int TYPE_YEAR = 1000; // public final static int TYPE_MONTH = 1001; // public final static int TYPE_DATE = 1002; // public final static int TYPE_HOUR = 1003; // public final static int TYPE_MINUTE = 1004; // public final static int TYPE_SECOND = 1005; // public final static int TYPE_MONTH_DATE = 1006; // public final static int TYPE_CURRENT_TIME = 1007; // public final static int TYPE_AM_PM = 1008; // public final static int TYPE_CHANGE_PROFILE = 1009; // public final static int TYPE_CHANGE_MENU_BG = 1010; // public final static int MANUAL_UPDATE = 1011; // public final static int AUTO_UPDATE = 1012; // public final static int TYPE_SAVE_PROFILE = 1013; // public final static int TYPE_STRING_FORM=1014; // } // // Path: app/src/main/java/com/cxsj/runhdu/constant/URLs.java // public class URLs { // public static final String DOWNLOAD = "http://d1.51gugu.com/170258/RunHDU"; // public static final String LOGIN = "http://112.74.115.231:8080/CXSJ/Login"; // public static final String REGISTER="http://112.74.115.231:8080/CXSJ/Register"; // public static final String GET_RUN_INFO = "http://112.74.115.231:8080/chuangxinshijian/ReadAll"; // public static final String UPLOAD_RUN_INFO = "http://112.74.115.231:8080/chuangxinshijian/Write"; // public static final String CLEAR_DATA = "http://112.74.115.231:8080/chuangxinshijian/ClearTheTable"; // public static final String UPDATE_URL = "http://112.74.115.231:8080/chuangxinshijian/VersionCompare"; // public static final String GET_RUN_TIMES = "http://112.74.115.231:8080/chuangxinshijian/ReadUserNameAndTimesOnly"; // public static final String UPLOAD_ALL_INFO = "http://112.74.115.231:8080/chuangxinshijian/WriteByJson"; // public static final String UPLOAD_PROFILE = "http://112.74.115.231:8080/CXSJ/UploadHead"; // public static final String PROFILE_URL = "http://112.74.115.231:8080/CXSJ/Image/"; // public static final String FEEDBACK_URL = "http://112.74.115.231:8080/chuangxinshijian/WriteFeedback"; // public static final String SUNNY_RUN_QUERY_API = "http://hdu.sunnysport.org.cn/api/student/achievements/"; // public static final String SUNNY_RUN_INFO_API = "http://hdu.sunnysport.org.cn/api/student/info/"; // public static final String DELETE_ITEM = "http://112.74.115.231:8080/chuangxinshijian/ClearByUserNameAndRunId"; // public static final String APPLY_FRIEND = "http://112.74.115.231:8080/CXSJ/Apply"; // public static final String REPLY_FRIEND = "http://112.74.115.231:8080/CXSJ/BeFriend"; // public static final String GET_FRIEND = "http://112.74.115.231:8080/CXSJ/MyFriends"; // public static final String DELETE_FRIEND = "http://112.74.115.231:8080/CXSJ/DeleteFriend"; // public static final String OFF_LINE = "http://112.74.115.231:8080/CXSJ/Xiaxian"; // } // Path: app/src/main/java/com/cxsj/runhdu/utils/ImageUtil.java import android.app.Activity; import android.content.Context; import android.content.Intent; import android.graphics.Bitmap; import android.graphics.Rect; import android.net.Uri; import android.os.Environment; import android.test.ActivityTestCase; import android.util.Base64; import android.view.View; import com.baidu.mapapi.map.BitmapDescriptor; import com.cxsj.runhdu.constant.Types; import com.cxsj.runhdu.constant.URLs; import java.io.ByteArrayOutputStream; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.IOException; import okhttp3.Call; import okhttp3.Callback; import okhttp3.Response; } public static Bitmap takeScreenShot(View view) { view.setDrawingCacheEnabled(true); Bitmap tBitmap = view.getDrawingCache(); tBitmap = Bitmap.createBitmap(tBitmap); view.setDrawingCacheEnabled(false); if (tBitmap != null) { return tBitmap; } else { return null; } } public static void openPhotoChooser(Activity activity, int resultCode) { Intent intent = new Intent(Intent.ACTION_PICK); intent.setType("image/*");//相片类型 activity.startActivityForResult(intent, resultCode); } public static void openPhotoCutter(Activity activity, Uri uri) { Intent intent = new Intent("com.android.camera.action.CROP"); intent.setDataAndType(uri, "image/*"); intent.putExtra("crop", "true"); intent.putExtra("aspectX", 1); intent.putExtra("aspectY", 1); intent.putExtra("outputX", 192); intent.putExtra("outputY", 192); intent.putExtra("return-data", true); intent.putExtra("outputFormat", Bitmap.CompressFormat.JPEG.toString());
activity.startActivityForResult(intent, Types.TYPE_SAVE_PROFILE);
SailFlorve/RunHDU
app/src/main/java/com/cxsj/runhdu/utils/StatusJsonCheckHelper.java
// Path: app/src/main/java/com/cxsj/runhdu/bean/gson/Status.java // public class Status { // @SerializedName("Result") // private boolean result; // // @SerializedName("Message") // private String message; // // @SerializedName("Which") // private int which; // // public boolean getResult() { // return result; // } // // public String getMessage() { // return message; // } // // public int getWhich() { // return which; // } // // }
import com.cxsj.runhdu.bean.gson.Status; import com.google.gson.Gson; import com.google.gson.JsonSyntaxException;
package com.cxsj.runhdu.utils; /** * Created by Sail on 2017/5/21 0021. * 返回的状态类JSON检查。 */ public class StatusJsonCheckHelper { public interface CheckCallback { void onPass(); void onFailure(String msg, int which); } public static void check(String json, CheckCallback callback) {
// Path: app/src/main/java/com/cxsj/runhdu/bean/gson/Status.java // public class Status { // @SerializedName("Result") // private boolean result; // // @SerializedName("Message") // private String message; // // @SerializedName("Which") // private int which; // // public boolean getResult() { // return result; // } // // public String getMessage() { // return message; // } // // public int getWhich() { // return which; // } // // } // Path: app/src/main/java/com/cxsj/runhdu/utils/StatusJsonCheckHelper.java import com.cxsj.runhdu.bean.gson.Status; import com.google.gson.Gson; import com.google.gson.JsonSyntaxException; package com.cxsj.runhdu.utils; /** * Created by Sail on 2017/5/21 0021. * 返回的状态类JSON检查。 */ public class StatusJsonCheckHelper { public interface CheckCallback { void onPass(); void onFailure(String msg, int which); } public static void check(String json, CheckCallback callback) {
Status status = null;
SailFlorve/RunHDU
app/src/main/java/com/cxsj/runhdu/BaseActivity.java
// Path: app/src/main/java/com/cxsj/runhdu/utils/ActivityManager.java // public class ActivityManager { // // private static String TAG = "ActivityManager"; // private static List<Activity> activities = new ArrayList<>(); // // public static void addActivity(Activity activity) { // Log.d(TAG, "addActivity: "+activity.getLocalClassName()); // activities.add(activity); // } // // public static void removeActivity(Activity activity) { // if (activity != null) { // Log.d(TAG, "removeActivity: "+activity.getLocalClassName()); // activities.remove(activity); // } // } // // public static void finishAll() { // for (Activity activity : activities) { // if (activity != null) { // Log.d(TAG, "finishAll: " + activity.getLocalClassName()); // activity.finish(); // } // } // } // } // // Path: app/src/main/java/com/cxsj/runhdu/utils/Prefs.java // public class Prefs { // // private SharedPreferences prefs; // private SharedPreferences.Editor editor; // // public Prefs(Context context) { // prefs = PreferenceManager.getDefaultSharedPreferences(context); // editor = prefs.edit(); // } // // public Prefs(Context context, String fileName) { // if (fileName == null) { // prefs = PreferenceManager.getDefaultSharedPreferences(context); // } else { // prefs = context.getSharedPreferences(fileName, Context.MODE_PRIVATE); // } // editor = prefs.edit(); // } // // public void put(String key, Object object) { // if (object == null) { // return; // } // if (object instanceof Integer) { // editor.putInt(key, (Integer) object); // } // // if (object instanceof String) { // editor.putString(key, (String) object); // } // // if (object instanceof Boolean) { // editor.putBoolean(key, (Boolean) object); // } // editor.apply(); // } // // public Object get(String key, Object defaultValue) { // if (defaultValue instanceof Integer) { // return prefs.getInt(key, (int) defaultValue); // } // // if (defaultValue instanceof String || defaultValue == null) { // return prefs.getString(key, (String) defaultValue); // } // // if (defaultValue instanceof Boolean) { // return prefs.getBoolean(key, (Boolean) defaultValue); // } // return null; // } // }
import android.annotation.SuppressLint; import android.app.ProgressDialog; import android.content.Context; import android.content.Intent; import android.content.pm.PackageManager; import android.os.Bundle; import android.support.annotation.ColorRes; import android.support.annotation.DimenRes; import android.support.annotation.NonNull; import android.support.annotation.StringRes; import android.support.v4.app.ActivityCompat; import android.support.v4.content.ContextCompat; import android.support.v7.app.AlertDialog; import android.support.v7.app.AppCompatActivity; import android.support.v7.widget.Toolbar; import android.view.MenuItem; import com.cxsj.runhdu.utils.ActivityManager; import com.cxsj.runhdu.utils.Prefs; import java.util.ArrayList; import java.util.List;
package com.cxsj.runhdu; /** * Created by Sail on 2017/4/13 0013. * 所有Activity的基类 */ @SuppressLint("Registered") public class BaseActivity extends AppCompatActivity { private ProgressDialog progressDialog;
// Path: app/src/main/java/com/cxsj/runhdu/utils/ActivityManager.java // public class ActivityManager { // // private static String TAG = "ActivityManager"; // private static List<Activity> activities = new ArrayList<>(); // // public static void addActivity(Activity activity) { // Log.d(TAG, "addActivity: "+activity.getLocalClassName()); // activities.add(activity); // } // // public static void removeActivity(Activity activity) { // if (activity != null) { // Log.d(TAG, "removeActivity: "+activity.getLocalClassName()); // activities.remove(activity); // } // } // // public static void finishAll() { // for (Activity activity : activities) { // if (activity != null) { // Log.d(TAG, "finishAll: " + activity.getLocalClassName()); // activity.finish(); // } // } // } // } // // Path: app/src/main/java/com/cxsj/runhdu/utils/Prefs.java // public class Prefs { // // private SharedPreferences prefs; // private SharedPreferences.Editor editor; // // public Prefs(Context context) { // prefs = PreferenceManager.getDefaultSharedPreferences(context); // editor = prefs.edit(); // } // // public Prefs(Context context, String fileName) { // if (fileName == null) { // prefs = PreferenceManager.getDefaultSharedPreferences(context); // } else { // prefs = context.getSharedPreferences(fileName, Context.MODE_PRIVATE); // } // editor = prefs.edit(); // } // // public void put(String key, Object object) { // if (object == null) { // return; // } // if (object instanceof Integer) { // editor.putInt(key, (Integer) object); // } // // if (object instanceof String) { // editor.putString(key, (String) object); // } // // if (object instanceof Boolean) { // editor.putBoolean(key, (Boolean) object); // } // editor.apply(); // } // // public Object get(String key, Object defaultValue) { // if (defaultValue instanceof Integer) { // return prefs.getInt(key, (int) defaultValue); // } // // if (defaultValue instanceof String || defaultValue == null) { // return prefs.getString(key, (String) defaultValue); // } // // if (defaultValue instanceof Boolean) { // return prefs.getBoolean(key, (Boolean) defaultValue); // } // return null; // } // } // Path: app/src/main/java/com/cxsj/runhdu/BaseActivity.java import android.annotation.SuppressLint; import android.app.ProgressDialog; import android.content.Context; import android.content.Intent; import android.content.pm.PackageManager; import android.os.Bundle; import android.support.annotation.ColorRes; import android.support.annotation.DimenRes; import android.support.annotation.NonNull; import android.support.annotation.StringRes; import android.support.v4.app.ActivityCompat; import android.support.v4.content.ContextCompat; import android.support.v7.app.AlertDialog; import android.support.v7.app.AppCompatActivity; import android.support.v7.widget.Toolbar; import android.view.MenuItem; import com.cxsj.runhdu.utils.ActivityManager; import com.cxsj.runhdu.utils.Prefs; import java.util.ArrayList; import java.util.List; package com.cxsj.runhdu; /** * Created by Sail on 2017/4/13 0013. * 所有Activity的基类 */ @SuppressLint("Registered") public class BaseActivity extends AppCompatActivity { private ProgressDialog progressDialog;
protected Prefs prefs;
SailFlorve/RunHDU
app/src/main/java/com/cxsj/runhdu/BaseActivity.java
// Path: app/src/main/java/com/cxsj/runhdu/utils/ActivityManager.java // public class ActivityManager { // // private static String TAG = "ActivityManager"; // private static List<Activity> activities = new ArrayList<>(); // // public static void addActivity(Activity activity) { // Log.d(TAG, "addActivity: "+activity.getLocalClassName()); // activities.add(activity); // } // // public static void removeActivity(Activity activity) { // if (activity != null) { // Log.d(TAG, "removeActivity: "+activity.getLocalClassName()); // activities.remove(activity); // } // } // // public static void finishAll() { // for (Activity activity : activities) { // if (activity != null) { // Log.d(TAG, "finishAll: " + activity.getLocalClassName()); // activity.finish(); // } // } // } // } // // Path: app/src/main/java/com/cxsj/runhdu/utils/Prefs.java // public class Prefs { // // private SharedPreferences prefs; // private SharedPreferences.Editor editor; // // public Prefs(Context context) { // prefs = PreferenceManager.getDefaultSharedPreferences(context); // editor = prefs.edit(); // } // // public Prefs(Context context, String fileName) { // if (fileName == null) { // prefs = PreferenceManager.getDefaultSharedPreferences(context); // } else { // prefs = context.getSharedPreferences(fileName, Context.MODE_PRIVATE); // } // editor = prefs.edit(); // } // // public void put(String key, Object object) { // if (object == null) { // return; // } // if (object instanceof Integer) { // editor.putInt(key, (Integer) object); // } // // if (object instanceof String) { // editor.putString(key, (String) object); // } // // if (object instanceof Boolean) { // editor.putBoolean(key, (Boolean) object); // } // editor.apply(); // } // // public Object get(String key, Object defaultValue) { // if (defaultValue instanceof Integer) { // return prefs.getInt(key, (int) defaultValue); // } // // if (defaultValue instanceof String || defaultValue == null) { // return prefs.getString(key, (String) defaultValue); // } // // if (defaultValue instanceof Boolean) { // return prefs.getBoolean(key, (Boolean) defaultValue); // } // return null; // } // }
import android.annotation.SuppressLint; import android.app.ProgressDialog; import android.content.Context; import android.content.Intent; import android.content.pm.PackageManager; import android.os.Bundle; import android.support.annotation.ColorRes; import android.support.annotation.DimenRes; import android.support.annotation.NonNull; import android.support.annotation.StringRes; import android.support.v4.app.ActivityCompat; import android.support.v4.content.ContextCompat; import android.support.v7.app.AlertDialog; import android.support.v7.app.AppCompatActivity; import android.support.v7.widget.Toolbar; import android.view.MenuItem; import com.cxsj.runhdu.utils.ActivityManager; import com.cxsj.runhdu.utils.Prefs; import java.util.ArrayList; import java.util.List;
package com.cxsj.runhdu; /** * Created by Sail on 2017/4/13 0013. * 所有Activity的基类 */ @SuppressLint("Registered") public class BaseActivity extends AppCompatActivity { private ProgressDialog progressDialog; protected Prefs prefs; protected Prefs defaultPrefs; protected String username; protected boolean isSyncOn = true; protected final String TAG = "BaseActivity"; protected PermissionCallback permissionCallback; protected interface PermissionCallback { void onGranted(); void onDenied(List<String> permissions); } @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState);
// Path: app/src/main/java/com/cxsj/runhdu/utils/ActivityManager.java // public class ActivityManager { // // private static String TAG = "ActivityManager"; // private static List<Activity> activities = new ArrayList<>(); // // public static void addActivity(Activity activity) { // Log.d(TAG, "addActivity: "+activity.getLocalClassName()); // activities.add(activity); // } // // public static void removeActivity(Activity activity) { // if (activity != null) { // Log.d(TAG, "removeActivity: "+activity.getLocalClassName()); // activities.remove(activity); // } // } // // public static void finishAll() { // for (Activity activity : activities) { // if (activity != null) { // Log.d(TAG, "finishAll: " + activity.getLocalClassName()); // activity.finish(); // } // } // } // } // // Path: app/src/main/java/com/cxsj/runhdu/utils/Prefs.java // public class Prefs { // // private SharedPreferences prefs; // private SharedPreferences.Editor editor; // // public Prefs(Context context) { // prefs = PreferenceManager.getDefaultSharedPreferences(context); // editor = prefs.edit(); // } // // public Prefs(Context context, String fileName) { // if (fileName == null) { // prefs = PreferenceManager.getDefaultSharedPreferences(context); // } else { // prefs = context.getSharedPreferences(fileName, Context.MODE_PRIVATE); // } // editor = prefs.edit(); // } // // public void put(String key, Object object) { // if (object == null) { // return; // } // if (object instanceof Integer) { // editor.putInt(key, (Integer) object); // } // // if (object instanceof String) { // editor.putString(key, (String) object); // } // // if (object instanceof Boolean) { // editor.putBoolean(key, (Boolean) object); // } // editor.apply(); // } // // public Object get(String key, Object defaultValue) { // if (defaultValue instanceof Integer) { // return prefs.getInt(key, (int) defaultValue); // } // // if (defaultValue instanceof String || defaultValue == null) { // return prefs.getString(key, (String) defaultValue); // } // // if (defaultValue instanceof Boolean) { // return prefs.getBoolean(key, (Boolean) defaultValue); // } // return null; // } // } // Path: app/src/main/java/com/cxsj/runhdu/BaseActivity.java import android.annotation.SuppressLint; import android.app.ProgressDialog; import android.content.Context; import android.content.Intent; import android.content.pm.PackageManager; import android.os.Bundle; import android.support.annotation.ColorRes; import android.support.annotation.DimenRes; import android.support.annotation.NonNull; import android.support.annotation.StringRes; import android.support.v4.app.ActivityCompat; import android.support.v4.content.ContextCompat; import android.support.v7.app.AlertDialog; import android.support.v7.app.AppCompatActivity; import android.support.v7.widget.Toolbar; import android.view.MenuItem; import com.cxsj.runhdu.utils.ActivityManager; import com.cxsj.runhdu.utils.Prefs; import java.util.ArrayList; import java.util.List; package com.cxsj.runhdu; /** * Created by Sail on 2017/4/13 0013. * 所有Activity的基类 */ @SuppressLint("Registered") public class BaseActivity extends AppCompatActivity { private ProgressDialog progressDialog; protected Prefs prefs; protected Prefs defaultPrefs; protected String username; protected boolean isSyncOn = true; protected final String TAG = "BaseActivity"; protected PermissionCallback permissionCallback; protected interface PermissionCallback { void onGranted(); void onDenied(List<String> permissions); } @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState);
ActivityManager.addActivity(this);
castagna/jena-grande
src/main/java/org/apache/jena/grande/mapreduce/io/NodeWritable.java
// Path: src/main/java/org/apache/jena/grande/JenaGrandeException.java // @SuppressWarnings("serial") // public class JenaGrandeException extends JenaException { // // public JenaGrandeException() { super() ; } // public JenaGrandeException(String msg) { super(msg) ; } // public JenaGrandeException(Throwable th) { super(th) ; } // public JenaGrandeException(String msg, Throwable th) { super(msg, th) ; } // // } // // Path: src/main/java/org/apache/jena/grande/NodeEncoder.java // public class NodeEncoder { // // private static final PrefixMap emptyPrefixMap = new PrefixMap(); // // public static String asString(Node node) { // StringWriter sw = new StringWriter() ; // NodeFmtLib.serialize(sw, node, null, emptyPrefixMap); // return sw.toString() ; // } // // public static String asString(Node node, PrefixMap prefixMap) { // StringWriter sw = new StringWriter() ; // NodeFmtLib.serialize(sw, node, null, prefixMap); // return sw.toString() ; // } // // public static Node asNode(String str) { // return NodeFactory.parseNode(str); // } // // }
import com.hp.hpl.jena.graph.Node; import java.io.DataInput; import java.io.DataOutput; import java.io.IOException; import java.io.StringWriter; import java.io.UnsupportedEncodingException; import org.apache.hadoop.io.BinaryComparable; import org.apache.hadoop.io.WritableComparable; import org.apache.hadoop.io.WritableUtils; import org.apache.jena.grande.JenaGrandeException; import org.apache.jena.grande.NodeEncoder; import org.openjena.riot.out.OutputLangUtils;
/* * 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.jena.grande.mapreduce.io; public class NodeWritable extends BinaryComparable implements WritableComparable<BinaryComparable> { private Node node; private byte[] bytes; private int length; public NodeWritable(){ this( Node.ANY ); } public NodeWritable(Node node) { this.node = node; this.bytes = toBytes(node); this.length = bytes.length; } @Override public void readFields(DataInput in) throws IOException { length = WritableUtils.readVInt(in); bytes = new byte[length]; in.readFully(bytes, 0, length);
// Path: src/main/java/org/apache/jena/grande/JenaGrandeException.java // @SuppressWarnings("serial") // public class JenaGrandeException extends JenaException { // // public JenaGrandeException() { super() ; } // public JenaGrandeException(String msg) { super(msg) ; } // public JenaGrandeException(Throwable th) { super(th) ; } // public JenaGrandeException(String msg, Throwable th) { super(msg, th) ; } // // } // // Path: src/main/java/org/apache/jena/grande/NodeEncoder.java // public class NodeEncoder { // // private static final PrefixMap emptyPrefixMap = new PrefixMap(); // // public static String asString(Node node) { // StringWriter sw = new StringWriter() ; // NodeFmtLib.serialize(sw, node, null, emptyPrefixMap); // return sw.toString() ; // } // // public static String asString(Node node, PrefixMap prefixMap) { // StringWriter sw = new StringWriter() ; // NodeFmtLib.serialize(sw, node, null, prefixMap); // return sw.toString() ; // } // // public static Node asNode(String str) { // return NodeFactory.parseNode(str); // } // // } // Path: src/main/java/org/apache/jena/grande/mapreduce/io/NodeWritable.java import com.hp.hpl.jena.graph.Node; import java.io.DataInput; import java.io.DataOutput; import java.io.IOException; import java.io.StringWriter; import java.io.UnsupportedEncodingException; import org.apache.hadoop.io.BinaryComparable; import org.apache.hadoop.io.WritableComparable; import org.apache.hadoop.io.WritableUtils; import org.apache.jena.grande.JenaGrandeException; import org.apache.jena.grande.NodeEncoder; import org.openjena.riot.out.OutputLangUtils; /* * 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.jena.grande.mapreduce.io; public class NodeWritable extends BinaryComparable implements WritableComparable<BinaryComparable> { private Node node; private byte[] bytes; private int length; public NodeWritable(){ this( Node.ANY ); } public NodeWritable(Node node) { this.node = node; this.bytes = toBytes(node); this.length = bytes.length; } @Override public void readFields(DataInput in) throws IOException { length = WritableUtils.readVInt(in); bytes = new byte[length]; in.readFully(bytes, 0, length);
node = NodeEncoder.asNode(new String(bytes));
castagna/jena-grande
src/main/java/org/apache/jena/grande/mapreduce/io/NodeWritable.java
// Path: src/main/java/org/apache/jena/grande/JenaGrandeException.java // @SuppressWarnings("serial") // public class JenaGrandeException extends JenaException { // // public JenaGrandeException() { super() ; } // public JenaGrandeException(String msg) { super(msg) ; } // public JenaGrandeException(Throwable th) { super(th) ; } // public JenaGrandeException(String msg, Throwable th) { super(msg, th) ; } // // } // // Path: src/main/java/org/apache/jena/grande/NodeEncoder.java // public class NodeEncoder { // // private static final PrefixMap emptyPrefixMap = new PrefixMap(); // // public static String asString(Node node) { // StringWriter sw = new StringWriter() ; // NodeFmtLib.serialize(sw, node, null, emptyPrefixMap); // return sw.toString() ; // } // // public static String asString(Node node, PrefixMap prefixMap) { // StringWriter sw = new StringWriter() ; // NodeFmtLib.serialize(sw, node, null, prefixMap); // return sw.toString() ; // } // // public static Node asNode(String str) { // return NodeFactory.parseNode(str); // } // // }
import com.hp.hpl.jena.graph.Node; import java.io.DataInput; import java.io.DataOutput; import java.io.IOException; import java.io.StringWriter; import java.io.UnsupportedEncodingException; import org.apache.hadoop.io.BinaryComparable; import org.apache.hadoop.io.WritableComparable; import org.apache.hadoop.io.WritableUtils; import org.apache.jena.grande.JenaGrandeException; import org.apache.jena.grande.NodeEncoder; import org.openjena.riot.out.OutputLangUtils;
node = NodeEncoder.asNode(new String(bytes)); } @Override public void write(DataOutput out) throws IOException { WritableUtils.writeVInt(out, length); out.write(bytes, 0, length); } @Override public byte[] getBytes() { return bytes; } @Override public int getLength() { return length; } public Node getNode() { return node; } private byte[] toBytes(Node node) { StringWriter out = new StringWriter(); out.getBuffer().length(); OutputLangUtils.output(out, node, null, null); try { return out.toString().getBytes("UTF-8"); } catch (UnsupportedEncodingException e) {
// Path: src/main/java/org/apache/jena/grande/JenaGrandeException.java // @SuppressWarnings("serial") // public class JenaGrandeException extends JenaException { // // public JenaGrandeException() { super() ; } // public JenaGrandeException(String msg) { super(msg) ; } // public JenaGrandeException(Throwable th) { super(th) ; } // public JenaGrandeException(String msg, Throwable th) { super(msg, th) ; } // // } // // Path: src/main/java/org/apache/jena/grande/NodeEncoder.java // public class NodeEncoder { // // private static final PrefixMap emptyPrefixMap = new PrefixMap(); // // public static String asString(Node node) { // StringWriter sw = new StringWriter() ; // NodeFmtLib.serialize(sw, node, null, emptyPrefixMap); // return sw.toString() ; // } // // public static String asString(Node node, PrefixMap prefixMap) { // StringWriter sw = new StringWriter() ; // NodeFmtLib.serialize(sw, node, null, prefixMap); // return sw.toString() ; // } // // public static Node asNode(String str) { // return NodeFactory.parseNode(str); // } // // } // Path: src/main/java/org/apache/jena/grande/mapreduce/io/NodeWritable.java import com.hp.hpl.jena.graph.Node; import java.io.DataInput; import java.io.DataOutput; import java.io.IOException; import java.io.StringWriter; import java.io.UnsupportedEncodingException; import org.apache.hadoop.io.BinaryComparable; import org.apache.hadoop.io.WritableComparable; import org.apache.hadoop.io.WritableUtils; import org.apache.jena.grande.JenaGrandeException; import org.apache.jena.grande.NodeEncoder; import org.openjena.riot.out.OutputLangUtils; node = NodeEncoder.asNode(new String(bytes)); } @Override public void write(DataOutput out) throws IOException { WritableUtils.writeVInt(out, length); out.write(bytes, 0, length); } @Override public byte[] getBytes() { return bytes; } @Override public int getLength() { return length; } public Node getNode() { return node; } private byte[] toBytes(Node node) { StringWriter out = new StringWriter(); out.getBuffer().length(); OutputLangUtils.output(out, node, null, null); try { return out.toString().getBytes("UTF-8"); } catch (UnsupportedEncodingException e) {
throw new JenaGrandeException(e);
castagna/jena-grande
src/main/java/org/apache/jena/grande/giraph/pagerank/memory/PlainPageRank.java
// Path: src/main/java/org/apache/jena/grande/MemoryUtil.java // public class MemoryUtil { // // private static final Logger LOG = LoggerFactory.getLogger(MemoryUtil.class); // // public static long getUsedMemory() { // System.gc() ; // System.gc() ; // System.gc() ; // // return ( Runtime.getRuntime().totalMemory() - Runtime.getRuntime().freeMemory() ) / ( 1024 * 1024 ) ; // } // // public static void printUsedMemory() { // LOG.debug (String.format("memory used is %d MB", getUsedMemory())) ; // } // // }
import java.io.BufferedReader; import java.io.IOException; import java.util.HashMap; import java.util.HashSet; import java.util.Map; import java.util.StringTokenizer; import org.apache.jena.grande.MemoryUtil; import org.slf4j.Logger; import org.slf4j.LoggerFactory;
/* * 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.jena.grande.giraph.pagerank.memory; public class PlainPageRank { private static final Logger LOG = LoggerFactory.getLogger(PlainPageRank.class); private Graph graph = new Graph() ; private Map<String, Double> pagerank_current = new HashMap<String, Double>() ; private Map<String, Double> pagerank_new = new HashMap<String, Double>() ; private double dumping_factor ; private int iterations ; public PlainPageRank ( BufferedReader in, double dumping_factor, int iterations ) { this.dumping_factor = dumping_factor ; this.iterations = iterations ; try {
// Path: src/main/java/org/apache/jena/grande/MemoryUtil.java // public class MemoryUtil { // // private static final Logger LOG = LoggerFactory.getLogger(MemoryUtil.class); // // public static long getUsedMemory() { // System.gc() ; // System.gc() ; // System.gc() ; // // return ( Runtime.getRuntime().totalMemory() - Runtime.getRuntime().freeMemory() ) / ( 1024 * 1024 ) ; // } // // public static void printUsedMemory() { // LOG.debug (String.format("memory used is %d MB", getUsedMemory())) ; // } // // } // Path: src/main/java/org/apache/jena/grande/giraph/pagerank/memory/PlainPageRank.java import java.io.BufferedReader; import java.io.IOException; import java.util.HashMap; import java.util.HashSet; import java.util.Map; import java.util.StringTokenizer; import org.apache.jena.grande.MemoryUtil; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /* * 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.jena.grande.giraph.pagerank.memory; public class PlainPageRank { private static final Logger LOG = LoggerFactory.getLogger(PlainPageRank.class); private Graph graph = new Graph() ; private Map<String, Double> pagerank_current = new HashMap<String, Double>() ; private Map<String, Double> pagerank_new = new HashMap<String, Double>() ; private double dumping_factor ; private int iterations ; public PlainPageRank ( BufferedReader in, double dumping_factor, int iterations ) { this.dumping_factor = dumping_factor ; this.iterations = iterations ; try {
MemoryUtil.printUsedMemory() ;
castagna/jena-grande
src/main/java/org/apache/jena/grande/pig/RdfStorage.java
// Path: src/main/java/org/apache/jena/grande/NodeEncoder.java // public class NodeEncoder { // // private static final PrefixMap emptyPrefixMap = new PrefixMap(); // // public static String asString(Node node) { // StringWriter sw = new StringWriter() ; // NodeFmtLib.serialize(sw, node, null, emptyPrefixMap); // return sw.toString() ; // } // // public static String asString(Node node, PrefixMap prefixMap) { // StringWriter sw = new StringWriter() ; // NodeFmtLib.serialize(sw, node, null, prefixMap); // return sw.toString() ; // } // // public static Node asNode(String str) { // return NodeFactory.parseNode(str); // } // // } // // Path: src/main/java/org/apache/jena/grande/mapreduce/io/QuadWritable.java // public class QuadWritable extends BinaryComparable implements WritableComparable<BinaryComparable> { // // private Quad quad; // private byte[] bytes; // private int length; // // public QuadWritable(){ // this( new Quad(Node.ANY, Node.ANY, Node.ANY, Node.ANY) ); // } // // public QuadWritable(Quad quad) { // this.quad = quad; // this.bytes = toBytes(quad); // this.length = bytes.length; // } // // @Override // public void readFields(DataInput in) throws IOException { // length = WritableUtils.readVInt(in); // bytes = new byte[length]; // in.readFully(bytes, 0, length); // Tokenizer tokenizer = TokenizerFactory.makeTokenizerASCII(new String(bytes)) ; // LangNQuads parser = new LangNQuads(tokenizer, RiotLib.profile(Lang.NQUADS, null), null) ; // quad = parser.next(); // } // // @Override // public void write(DataOutput out) throws IOException { // WritableUtils.writeVInt(out, length); // out.write(bytes, 0, length); // } // // @Override // public byte[] getBytes() { // return bytes; // } // // @Override // public int getLength() { // return length; // } // // public Quad getQuad() { // return quad; // } // // private byte[] toBytes(Quad quad) { // StringWriter out = new StringWriter(); // out.getBuffer().length(); // OutputLangUtils.output(out, quad, null, null); // try { // return out.toString().getBytes("UTF-8"); // } catch (UnsupportedEncodingException e) { // throw new JenaGrandeException(e); // } // } // // @Override // public String toString() { // return quad.toString(); // } // }
import java.io.IOException; import org.apache.hadoop.fs.Path; import org.apache.hadoop.io.LongWritable; import org.apache.hadoop.io.NullWritable; import org.apache.hadoop.io.compress.BZip2Codec; import org.apache.hadoop.io.compress.CompressionCodec; import org.apache.hadoop.io.compress.GzipCodec; import org.apache.hadoop.mapreduce.InputFormat; import org.apache.hadoop.mapreduce.Job; import org.apache.hadoop.mapreduce.OutputFormat; import org.apache.hadoop.mapreduce.RecordReader; import org.apache.hadoop.mapreduce.RecordWriter; import org.apache.hadoop.mapreduce.lib.input.FileInputFormat; import org.apache.hadoop.mapreduce.lib.output.FileOutputFormat; import org.apache.jena.grande.NodeEncoder; import org.apache.jena.grande.mapreduce.io.QuadWritable; import org.apache.pig.FileInputLoadFunc; import org.apache.pig.LoadFunc; import org.apache.pig.ResourceSchema; import org.apache.pig.StoreFunc; import org.apache.pig.StoreFuncInterface; import org.apache.pig.backend.hadoop.executionengine.mapReduceLayer.PigSplit; import org.apache.pig.data.Tuple; import org.apache.pig.data.TupleFactory; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import com.hp.hpl.jena.graph.Node; import com.hp.hpl.jena.sparql.core.Quad;
/* * 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.jena.grande.pig; public class RdfStorage extends FileInputLoadFunc implements StoreFuncInterface { private static final Logger log = LoggerFactory.getLogger(RdfStorage.class); private String location;
// Path: src/main/java/org/apache/jena/grande/NodeEncoder.java // public class NodeEncoder { // // private static final PrefixMap emptyPrefixMap = new PrefixMap(); // // public static String asString(Node node) { // StringWriter sw = new StringWriter() ; // NodeFmtLib.serialize(sw, node, null, emptyPrefixMap); // return sw.toString() ; // } // // public static String asString(Node node, PrefixMap prefixMap) { // StringWriter sw = new StringWriter() ; // NodeFmtLib.serialize(sw, node, null, prefixMap); // return sw.toString() ; // } // // public static Node asNode(String str) { // return NodeFactory.parseNode(str); // } // // } // // Path: src/main/java/org/apache/jena/grande/mapreduce/io/QuadWritable.java // public class QuadWritable extends BinaryComparable implements WritableComparable<BinaryComparable> { // // private Quad quad; // private byte[] bytes; // private int length; // // public QuadWritable(){ // this( new Quad(Node.ANY, Node.ANY, Node.ANY, Node.ANY) ); // } // // public QuadWritable(Quad quad) { // this.quad = quad; // this.bytes = toBytes(quad); // this.length = bytes.length; // } // // @Override // public void readFields(DataInput in) throws IOException { // length = WritableUtils.readVInt(in); // bytes = new byte[length]; // in.readFully(bytes, 0, length); // Tokenizer tokenizer = TokenizerFactory.makeTokenizerASCII(new String(bytes)) ; // LangNQuads parser = new LangNQuads(tokenizer, RiotLib.profile(Lang.NQUADS, null), null) ; // quad = parser.next(); // } // // @Override // public void write(DataOutput out) throws IOException { // WritableUtils.writeVInt(out, length); // out.write(bytes, 0, length); // } // // @Override // public byte[] getBytes() { // return bytes; // } // // @Override // public int getLength() { // return length; // } // // public Quad getQuad() { // return quad; // } // // private byte[] toBytes(Quad quad) { // StringWriter out = new StringWriter(); // out.getBuffer().length(); // OutputLangUtils.output(out, quad, null, null); // try { // return out.toString().getBytes("UTF-8"); // } catch (UnsupportedEncodingException e) { // throw new JenaGrandeException(e); // } // } // // @Override // public String toString() { // return quad.toString(); // } // } // Path: src/main/java/org/apache/jena/grande/pig/RdfStorage.java import java.io.IOException; import org.apache.hadoop.fs.Path; import org.apache.hadoop.io.LongWritable; import org.apache.hadoop.io.NullWritable; import org.apache.hadoop.io.compress.BZip2Codec; import org.apache.hadoop.io.compress.CompressionCodec; import org.apache.hadoop.io.compress.GzipCodec; import org.apache.hadoop.mapreduce.InputFormat; import org.apache.hadoop.mapreduce.Job; import org.apache.hadoop.mapreduce.OutputFormat; import org.apache.hadoop.mapreduce.RecordReader; import org.apache.hadoop.mapreduce.RecordWriter; import org.apache.hadoop.mapreduce.lib.input.FileInputFormat; import org.apache.hadoop.mapreduce.lib.output.FileOutputFormat; import org.apache.jena.grande.NodeEncoder; import org.apache.jena.grande.mapreduce.io.QuadWritable; import org.apache.pig.FileInputLoadFunc; import org.apache.pig.LoadFunc; import org.apache.pig.ResourceSchema; import org.apache.pig.StoreFunc; import org.apache.pig.StoreFuncInterface; import org.apache.pig.backend.hadoop.executionengine.mapReduceLayer.PigSplit; import org.apache.pig.data.Tuple; import org.apache.pig.data.TupleFactory; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import com.hp.hpl.jena.graph.Node; import com.hp.hpl.jena.sparql.core.Quad; /* * 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.jena.grande.pig; public class RdfStorage extends FileInputLoadFunc implements StoreFuncInterface { private static final Logger log = LoggerFactory.getLogger(RdfStorage.class); private String location;
private RecordReader<LongWritable, QuadWritable> reader;
castagna/jena-grande
src/main/java/org/apache/jena/grande/pig/RdfStorage.java
// Path: src/main/java/org/apache/jena/grande/NodeEncoder.java // public class NodeEncoder { // // private static final PrefixMap emptyPrefixMap = new PrefixMap(); // // public static String asString(Node node) { // StringWriter sw = new StringWriter() ; // NodeFmtLib.serialize(sw, node, null, emptyPrefixMap); // return sw.toString() ; // } // // public static String asString(Node node, PrefixMap prefixMap) { // StringWriter sw = new StringWriter() ; // NodeFmtLib.serialize(sw, node, null, prefixMap); // return sw.toString() ; // } // // public static Node asNode(String str) { // return NodeFactory.parseNode(str); // } // // } // // Path: src/main/java/org/apache/jena/grande/mapreduce/io/QuadWritable.java // public class QuadWritable extends BinaryComparable implements WritableComparable<BinaryComparable> { // // private Quad quad; // private byte[] bytes; // private int length; // // public QuadWritable(){ // this( new Quad(Node.ANY, Node.ANY, Node.ANY, Node.ANY) ); // } // // public QuadWritable(Quad quad) { // this.quad = quad; // this.bytes = toBytes(quad); // this.length = bytes.length; // } // // @Override // public void readFields(DataInput in) throws IOException { // length = WritableUtils.readVInt(in); // bytes = new byte[length]; // in.readFully(bytes, 0, length); // Tokenizer tokenizer = TokenizerFactory.makeTokenizerASCII(new String(bytes)) ; // LangNQuads parser = new LangNQuads(tokenizer, RiotLib.profile(Lang.NQUADS, null), null) ; // quad = parser.next(); // } // // @Override // public void write(DataOutput out) throws IOException { // WritableUtils.writeVInt(out, length); // out.write(bytes, 0, length); // } // // @Override // public byte[] getBytes() { // return bytes; // } // // @Override // public int getLength() { // return length; // } // // public Quad getQuad() { // return quad; // } // // private byte[] toBytes(Quad quad) { // StringWriter out = new StringWriter(); // out.getBuffer().length(); // OutputLangUtils.output(out, quad, null, null); // try { // return out.toString().getBytes("UTF-8"); // } catch (UnsupportedEncodingException e) { // throw new JenaGrandeException(e); // } // } // // @Override // public String toString() { // return quad.toString(); // } // }
import java.io.IOException; import org.apache.hadoop.fs.Path; import org.apache.hadoop.io.LongWritable; import org.apache.hadoop.io.NullWritable; import org.apache.hadoop.io.compress.BZip2Codec; import org.apache.hadoop.io.compress.CompressionCodec; import org.apache.hadoop.io.compress.GzipCodec; import org.apache.hadoop.mapreduce.InputFormat; import org.apache.hadoop.mapreduce.Job; import org.apache.hadoop.mapreduce.OutputFormat; import org.apache.hadoop.mapreduce.RecordReader; import org.apache.hadoop.mapreduce.RecordWriter; import org.apache.hadoop.mapreduce.lib.input.FileInputFormat; import org.apache.hadoop.mapreduce.lib.output.FileOutputFormat; import org.apache.jena.grande.NodeEncoder; import org.apache.jena.grande.mapreduce.io.QuadWritable; import org.apache.pig.FileInputLoadFunc; import org.apache.pig.LoadFunc; import org.apache.pig.ResourceSchema; import org.apache.pig.StoreFunc; import org.apache.pig.StoreFuncInterface; import org.apache.pig.backend.hadoop.executionengine.mapReduceLayer.PigSplit; import org.apache.pig.data.Tuple; import org.apache.pig.data.TupleFactory; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import com.hp.hpl.jena.graph.Node; import com.hp.hpl.jena.sparql.core.Quad;
@Override public void setLocation(String location, Job job) throws IOException { log.debug("setLocation({}, {})", location, job); this.location = location; FileInputFormat.setInputPaths(job, location); } @Override public InputFormat<LongWritable, QuadWritable> getInputFormat() throws IOException { InputFormat<LongWritable, QuadWritable> inputFormat = new NQuadsPigInputFormat(); log.debug("getInputFormat() --> {}", inputFormat); return inputFormat; } @SuppressWarnings("unchecked") @Override public void prepareToRead(@SuppressWarnings("rawtypes") RecordReader reader, PigSplit split) throws IOException { log.debug("prepareToRead({}, {})", reader, split); this.reader = reader; } private final TupleFactory tupleFactory = TupleFactory.getInstance(); @Override public Tuple getNext() throws IOException { Tuple tuple = null; try { if ( reader.nextKeyValue() ) { QuadWritable quad = reader.getCurrentValue(); tuple = tupleFactory.newTuple(4);
// Path: src/main/java/org/apache/jena/grande/NodeEncoder.java // public class NodeEncoder { // // private static final PrefixMap emptyPrefixMap = new PrefixMap(); // // public static String asString(Node node) { // StringWriter sw = new StringWriter() ; // NodeFmtLib.serialize(sw, node, null, emptyPrefixMap); // return sw.toString() ; // } // // public static String asString(Node node, PrefixMap prefixMap) { // StringWriter sw = new StringWriter() ; // NodeFmtLib.serialize(sw, node, null, prefixMap); // return sw.toString() ; // } // // public static Node asNode(String str) { // return NodeFactory.parseNode(str); // } // // } // // Path: src/main/java/org/apache/jena/grande/mapreduce/io/QuadWritable.java // public class QuadWritable extends BinaryComparable implements WritableComparable<BinaryComparable> { // // private Quad quad; // private byte[] bytes; // private int length; // // public QuadWritable(){ // this( new Quad(Node.ANY, Node.ANY, Node.ANY, Node.ANY) ); // } // // public QuadWritable(Quad quad) { // this.quad = quad; // this.bytes = toBytes(quad); // this.length = bytes.length; // } // // @Override // public void readFields(DataInput in) throws IOException { // length = WritableUtils.readVInt(in); // bytes = new byte[length]; // in.readFully(bytes, 0, length); // Tokenizer tokenizer = TokenizerFactory.makeTokenizerASCII(new String(bytes)) ; // LangNQuads parser = new LangNQuads(tokenizer, RiotLib.profile(Lang.NQUADS, null), null) ; // quad = parser.next(); // } // // @Override // public void write(DataOutput out) throws IOException { // WritableUtils.writeVInt(out, length); // out.write(bytes, 0, length); // } // // @Override // public byte[] getBytes() { // return bytes; // } // // @Override // public int getLength() { // return length; // } // // public Quad getQuad() { // return quad; // } // // private byte[] toBytes(Quad quad) { // StringWriter out = new StringWriter(); // out.getBuffer().length(); // OutputLangUtils.output(out, quad, null, null); // try { // return out.toString().getBytes("UTF-8"); // } catch (UnsupportedEncodingException e) { // throw new JenaGrandeException(e); // } // } // // @Override // public String toString() { // return quad.toString(); // } // } // Path: src/main/java/org/apache/jena/grande/pig/RdfStorage.java import java.io.IOException; import org.apache.hadoop.fs.Path; import org.apache.hadoop.io.LongWritable; import org.apache.hadoop.io.NullWritable; import org.apache.hadoop.io.compress.BZip2Codec; import org.apache.hadoop.io.compress.CompressionCodec; import org.apache.hadoop.io.compress.GzipCodec; import org.apache.hadoop.mapreduce.InputFormat; import org.apache.hadoop.mapreduce.Job; import org.apache.hadoop.mapreduce.OutputFormat; import org.apache.hadoop.mapreduce.RecordReader; import org.apache.hadoop.mapreduce.RecordWriter; import org.apache.hadoop.mapreduce.lib.input.FileInputFormat; import org.apache.hadoop.mapreduce.lib.output.FileOutputFormat; import org.apache.jena.grande.NodeEncoder; import org.apache.jena.grande.mapreduce.io.QuadWritable; import org.apache.pig.FileInputLoadFunc; import org.apache.pig.LoadFunc; import org.apache.pig.ResourceSchema; import org.apache.pig.StoreFunc; import org.apache.pig.StoreFuncInterface; import org.apache.pig.backend.hadoop.executionengine.mapReduceLayer.PigSplit; import org.apache.pig.data.Tuple; import org.apache.pig.data.TupleFactory; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import com.hp.hpl.jena.graph.Node; import com.hp.hpl.jena.sparql.core.Quad; @Override public void setLocation(String location, Job job) throws IOException { log.debug("setLocation({}, {})", location, job); this.location = location; FileInputFormat.setInputPaths(job, location); } @Override public InputFormat<LongWritable, QuadWritable> getInputFormat() throws IOException { InputFormat<LongWritable, QuadWritable> inputFormat = new NQuadsPigInputFormat(); log.debug("getInputFormat() --> {}", inputFormat); return inputFormat; } @SuppressWarnings("unchecked") @Override public void prepareToRead(@SuppressWarnings("rawtypes") RecordReader reader, PigSplit split) throws IOException { log.debug("prepareToRead({}, {})", reader, split); this.reader = reader; } private final TupleFactory tupleFactory = TupleFactory.getInstance(); @Override public Tuple getNext() throws IOException { Tuple tuple = null; try { if ( reader.nextKeyValue() ) { QuadWritable quad = reader.getCurrentValue(); tuple = tupleFactory.newTuple(4);
tuple.set(0, NodeEncoder.asString(quad.getQuad().getGraph()));
castagna/jena-grande
src/main/java/org/apache/jena/grande/mapreduce/io/TripleWritable.java
// Path: src/main/java/org/apache/jena/grande/JenaGrandeException.java // @SuppressWarnings("serial") // public class JenaGrandeException extends JenaException { // // public JenaGrandeException() { super() ; } // public JenaGrandeException(String msg) { super(msg) ; } // public JenaGrandeException(Throwable th) { super(th) ; } // public JenaGrandeException(String msg, Throwable th) { super(msg, th) ; } // // }
import org.openjena.riot.out.OutputLangUtils; import org.openjena.riot.system.RiotLib; import org.openjena.riot.tokens.Tokenizer; import org.openjena.riot.tokens.TokenizerFactory; import com.hp.hpl.jena.graph.Node; import com.hp.hpl.jena.graph.Triple; import java.io.DataInput; import java.io.DataOutput; import java.io.IOException; import java.io.StringWriter; import java.io.UnsupportedEncodingException; import org.apache.hadoop.io.BinaryComparable; import org.apache.hadoop.io.WritableComparable; import org.apache.hadoop.io.WritableUtils; import org.apache.jena.grande.JenaGrandeException; import org.openjena.riot.Lang; import org.openjena.riot.lang.LangNTriples;
triple = parser.next(); } @Override public void write(DataOutput out) throws IOException { WritableUtils.writeVInt(out, length); out.write(bytes, 0, length); } @Override public byte[] getBytes() { return bytes; } @Override public int getLength() { return length; } public Triple getTriple() { return triple; } private byte[] toBytes(Triple triple) { StringWriter out = new StringWriter(); out.getBuffer().length(); OutputLangUtils.output(out, triple, null, null); try { return out.toString().getBytes("UTF-8"); } catch (UnsupportedEncodingException e) {
// Path: src/main/java/org/apache/jena/grande/JenaGrandeException.java // @SuppressWarnings("serial") // public class JenaGrandeException extends JenaException { // // public JenaGrandeException() { super() ; } // public JenaGrandeException(String msg) { super(msg) ; } // public JenaGrandeException(Throwable th) { super(th) ; } // public JenaGrandeException(String msg, Throwable th) { super(msg, th) ; } // // } // Path: src/main/java/org/apache/jena/grande/mapreduce/io/TripleWritable.java import org.openjena.riot.out.OutputLangUtils; import org.openjena.riot.system.RiotLib; import org.openjena.riot.tokens.Tokenizer; import org.openjena.riot.tokens.TokenizerFactory; import com.hp.hpl.jena.graph.Node; import com.hp.hpl.jena.graph.Triple; import java.io.DataInput; import java.io.DataOutput; import java.io.IOException; import java.io.StringWriter; import java.io.UnsupportedEncodingException; import org.apache.hadoop.io.BinaryComparable; import org.apache.hadoop.io.WritableComparable; import org.apache.hadoop.io.WritableUtils; import org.apache.jena.grande.JenaGrandeException; import org.openjena.riot.Lang; import org.openjena.riot.lang.LangNTriples; triple = parser.next(); } @Override public void write(DataOutput out) throws IOException { WritableUtils.writeVInt(out, length); out.write(bytes, 0, length); } @Override public byte[] getBytes() { return bytes; } @Override public int getLength() { return length; } public Triple getTriple() { return triple; } private byte[] toBytes(Triple triple) { StringWriter out = new StringWriter(); out.getBuffer().length(); OutputLangUtils.output(out, triple, null, null); try { return out.toString().getBytes("UTF-8"); } catch (UnsupportedEncodingException e) {
throw new JenaGrandeException(e);
castagna/jena-grande
src/main/java/org/apache/jena/grande/giraph/TurtleVertexInputFormat.java
// Path: src/main/java/org/apache/jena/grande/NodeEncoder.java // public class NodeEncoder { // // private static final PrefixMap emptyPrefixMap = new PrefixMap(); // // public static String asString(Node node) { // StringWriter sw = new StringWriter() ; // NodeFmtLib.serialize(sw, node, null, emptyPrefixMap); // return sw.toString() ; // } // // public static String asString(Node node, PrefixMap prefixMap) { // StringWriter sw = new StringWriter() ; // NodeFmtLib.serialize(sw, node, null, prefixMap); // return sw.toString() ; // } // // public static Node asNode(String str) { // return NodeFactory.parseNode(str); // } // // } // // Path: src/main/java/org/apache/jena/grande/mapreduce/io/NodeWritable.java // public class NodeWritable extends BinaryComparable implements WritableComparable<BinaryComparable> { // // private Node node; // private byte[] bytes; // private int length; // // public NodeWritable(){ // this( Node.ANY ); // } // // public NodeWritable(Node node) { // this.node = node; // this.bytes = toBytes(node); // this.length = bytes.length; // } // // @Override // public void readFields(DataInput in) throws IOException { // length = WritableUtils.readVInt(in); // bytes = new byte[length]; // in.readFully(bytes, 0, length); // node = NodeEncoder.asNode(new String(bytes)); // } // // @Override // public void write(DataOutput out) throws IOException { // WritableUtils.writeVInt(out, length); // out.write(bytes, 0, length); // } // // @Override // public byte[] getBytes() { // return bytes; // } // // @Override // public int getLength() { // return length; // } // // public Node getNode() { // return node; // } // // private byte[] toBytes(Node node) { // StringWriter out = new StringWriter(); // out.getBuffer().length(); // OutputLangUtils.output(out, node, null, null); // try { // return out.toString().getBytes("UTF-8"); // } catch (UnsupportedEncodingException e) { // throw new JenaGrandeException(e); // } // } // // @Override // public String toString() { // return node.toString(); // } // // }
import java.io.IOException; import java.util.Map; import org.apache.giraph.graph.BspUtils; import org.apache.giraph.graph.Vertex; import org.apache.giraph.io.TextVertexInputFormat; import org.apache.hadoop.conf.Configuration; import org.apache.hadoop.io.IntWritable; import org.apache.hadoop.io.Text; import org.apache.hadoop.mapreduce.InputSplit; import org.apache.hadoop.mapreduce.TaskAttemptContext; import org.apache.jena.grande.NodeEncoder; import org.apache.jena.grande.mapreduce.io.NodeWritable; import org.openjena.riot.Lang; import org.openjena.riot.RiotLoader; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import com.google.common.collect.Maps; import com.hp.hpl.jena.graph.Graph; import com.hp.hpl.jena.graph.Node; import com.hp.hpl.jena.graph.Triple; import com.hp.hpl.jena.sparql.vocabulary.FOAF; import com.hp.hpl.jena.util.iterator.ExtendedIterator;
log.debug("createVertexReader({}, {}) --> {}", new Object[]{split, context, result}); return result; } public class TurtleVertexReader extends TextVertexReader { private final Logger log = LoggerFactory.getLogger(TurtleVertexReader.class); @Override public boolean nextVertex() throws IOException, InterruptedException { boolean result = getRecordReader().nextKeyValue(); log.debug("nextVertex() --> {}", result); return result; } @Override public Vertex<NodeWritable, IntWritable, NodeWritable, IntWritable> getCurrentVertex() throws IOException, InterruptedException { Configuration conf = getContext().getConfiguration(); Vertex<NodeWritable, IntWritable, NodeWritable, IntWritable> vertex = BspUtils.createVertex(conf); Text line = getRecordReader().getCurrentValue(); NodeWritable vertexId = getVertexId(line); Graph graph = RiotLoader.graphFromString(line.toString(), Lang.TURTLE, ""); Map<NodeWritable, NodeWritable> edgeMap = getEdgeMap(vertexId, graph); vertex.initialize(vertexId, null, edgeMap); log.debug("getCurrentVertex() --> {}", vertex); return vertex; } private NodeWritable getVertexId( Text line ) { String str = line.toString();
// Path: src/main/java/org/apache/jena/grande/NodeEncoder.java // public class NodeEncoder { // // private static final PrefixMap emptyPrefixMap = new PrefixMap(); // // public static String asString(Node node) { // StringWriter sw = new StringWriter() ; // NodeFmtLib.serialize(sw, node, null, emptyPrefixMap); // return sw.toString() ; // } // // public static String asString(Node node, PrefixMap prefixMap) { // StringWriter sw = new StringWriter() ; // NodeFmtLib.serialize(sw, node, null, prefixMap); // return sw.toString() ; // } // // public static Node asNode(String str) { // return NodeFactory.parseNode(str); // } // // } // // Path: src/main/java/org/apache/jena/grande/mapreduce/io/NodeWritable.java // public class NodeWritable extends BinaryComparable implements WritableComparable<BinaryComparable> { // // private Node node; // private byte[] bytes; // private int length; // // public NodeWritable(){ // this( Node.ANY ); // } // // public NodeWritable(Node node) { // this.node = node; // this.bytes = toBytes(node); // this.length = bytes.length; // } // // @Override // public void readFields(DataInput in) throws IOException { // length = WritableUtils.readVInt(in); // bytes = new byte[length]; // in.readFully(bytes, 0, length); // node = NodeEncoder.asNode(new String(bytes)); // } // // @Override // public void write(DataOutput out) throws IOException { // WritableUtils.writeVInt(out, length); // out.write(bytes, 0, length); // } // // @Override // public byte[] getBytes() { // return bytes; // } // // @Override // public int getLength() { // return length; // } // // public Node getNode() { // return node; // } // // private byte[] toBytes(Node node) { // StringWriter out = new StringWriter(); // out.getBuffer().length(); // OutputLangUtils.output(out, node, null, null); // try { // return out.toString().getBytes("UTF-8"); // } catch (UnsupportedEncodingException e) { // throw new JenaGrandeException(e); // } // } // // @Override // public String toString() { // return node.toString(); // } // // } // Path: src/main/java/org/apache/jena/grande/giraph/TurtleVertexInputFormat.java import java.io.IOException; import java.util.Map; import org.apache.giraph.graph.BspUtils; import org.apache.giraph.graph.Vertex; import org.apache.giraph.io.TextVertexInputFormat; import org.apache.hadoop.conf.Configuration; import org.apache.hadoop.io.IntWritable; import org.apache.hadoop.io.Text; import org.apache.hadoop.mapreduce.InputSplit; import org.apache.hadoop.mapreduce.TaskAttemptContext; import org.apache.jena.grande.NodeEncoder; import org.apache.jena.grande.mapreduce.io.NodeWritable; import org.openjena.riot.Lang; import org.openjena.riot.RiotLoader; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import com.google.common.collect.Maps; import com.hp.hpl.jena.graph.Graph; import com.hp.hpl.jena.graph.Node; import com.hp.hpl.jena.graph.Triple; import com.hp.hpl.jena.sparql.vocabulary.FOAF; import com.hp.hpl.jena.util.iterator.ExtendedIterator; log.debug("createVertexReader({}, {}) --> {}", new Object[]{split, context, result}); return result; } public class TurtleVertexReader extends TextVertexReader { private final Logger log = LoggerFactory.getLogger(TurtleVertexReader.class); @Override public boolean nextVertex() throws IOException, InterruptedException { boolean result = getRecordReader().nextKeyValue(); log.debug("nextVertex() --> {}", result); return result; } @Override public Vertex<NodeWritable, IntWritable, NodeWritable, IntWritable> getCurrentVertex() throws IOException, InterruptedException { Configuration conf = getContext().getConfiguration(); Vertex<NodeWritable, IntWritable, NodeWritable, IntWritable> vertex = BspUtils.createVertex(conf); Text line = getRecordReader().getCurrentValue(); NodeWritable vertexId = getVertexId(line); Graph graph = RiotLoader.graphFromString(line.toString(), Lang.TURTLE, ""); Map<NodeWritable, NodeWritable> edgeMap = getEdgeMap(vertexId, graph); vertex.initialize(vertexId, null, edgeMap); log.debug("getCurrentVertex() --> {}", vertex); return vertex; } private NodeWritable getVertexId( Text line ) { String str = line.toString();
NodeWritable vertexId = new NodeWritable(NodeEncoder.asNode(str.substring(0, str.indexOf(' '))));
castagna/jena-grande
src/main/java/org/apache/jena/grande/Utils.java
// Path: src/main/java/org/apache/jena/grande/mapreduce/io/MapReduceLabelToNode.java // public class MapReduceLabelToNode extends LabelToNode { // // private static final Logger log = LoggerFactory.getLogger(MapReduceLabelToNode.class); // // public MapReduceLabelToNode(JobContext context, Path path) { // super(new SingleScopePolicy(), new MapReduceAllocator(context, path)); // } // // private static class SingleScopePolicy implements ScopePolicy<String, Node, Node> { // private Map<String, Node> map = new HashMap<String, Node>() ; // @Override public Map<String, Node> getScope(Node scope) { return map ; } // @Override public void clear() { map.clear(); } // } // // private static class MapReduceAllocator implements Allocator<String, Node> { // // private String runId ; // private Path path ; // // public MapReduceAllocator (JobContext context, Path path) { // // This is to ensure that blank node allocation policy is constant when subsequent MapReduce jobs need that // this.runId = context.getConfiguration().get(Constants.RUN_ID); // if ( this.runId == null ) { // this.runId = String.valueOf(System.currentTimeMillis()); // log.warn("runId was not set, it has now been set to {}. Sequence of MapReduce jobs must handle carefully blank nodes.", runId); // } // this.path = path; // log.debug("MapReduceAllocator({}, {})", runId, path) ; // } // // @Override // public Node create(String label) { // String strLabel = "mrbnode_" + runId.hashCode() + "_" + path.hashCode() + "_" + label; // log.debug ("create({}) = {}", label, strLabel); // return Node.createAnon(new AnonId(strLabel)) ; // } // // @Override public void reset() {} // }; // // }
import org.openjena.riot.system.Prologue; import org.slf4j.Logger; import org.apache.hadoop.conf.Configuration; import org.apache.hadoop.fs.Path; import org.apache.hadoop.mapreduce.Job; import org.apache.hadoop.mapreduce.JobContext; import org.apache.hadoop.mapreduce.lib.input.FileInputFormat; import org.apache.hadoop.mapreduce.lib.output.FileOutputFormat; import org.apache.jena.grande.mapreduce.io.MapReduceLabelToNode; import org.openjena.riot.ErrorHandlerFactory; import org.openjena.riot.lang.LabelToNode; import org.openjena.riot.system.IRIResolver; import org.openjena.riot.system.ParserProfile; import org.openjena.riot.system.ParserProfileBase;
/* * 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.jena.grande; public class Utils { public static ParserProfile createParserProfile(JobContext context, Path path) { Prologue prologue = new Prologue(null, IRIResolver.createNoResolve());
// Path: src/main/java/org/apache/jena/grande/mapreduce/io/MapReduceLabelToNode.java // public class MapReduceLabelToNode extends LabelToNode { // // private static final Logger log = LoggerFactory.getLogger(MapReduceLabelToNode.class); // // public MapReduceLabelToNode(JobContext context, Path path) { // super(new SingleScopePolicy(), new MapReduceAllocator(context, path)); // } // // private static class SingleScopePolicy implements ScopePolicy<String, Node, Node> { // private Map<String, Node> map = new HashMap<String, Node>() ; // @Override public Map<String, Node> getScope(Node scope) { return map ; } // @Override public void clear() { map.clear(); } // } // // private static class MapReduceAllocator implements Allocator<String, Node> { // // private String runId ; // private Path path ; // // public MapReduceAllocator (JobContext context, Path path) { // // This is to ensure that blank node allocation policy is constant when subsequent MapReduce jobs need that // this.runId = context.getConfiguration().get(Constants.RUN_ID); // if ( this.runId == null ) { // this.runId = String.valueOf(System.currentTimeMillis()); // log.warn("runId was not set, it has now been set to {}. Sequence of MapReduce jobs must handle carefully blank nodes.", runId); // } // this.path = path; // log.debug("MapReduceAllocator({}, {})", runId, path) ; // } // // @Override // public Node create(String label) { // String strLabel = "mrbnode_" + runId.hashCode() + "_" + path.hashCode() + "_" + label; // log.debug ("create({}) = {}", label, strLabel); // return Node.createAnon(new AnonId(strLabel)) ; // } // // @Override public void reset() {} // }; // // } // Path: src/main/java/org/apache/jena/grande/Utils.java import org.openjena.riot.system.Prologue; import org.slf4j.Logger; import org.apache.hadoop.conf.Configuration; import org.apache.hadoop.fs.Path; import org.apache.hadoop.mapreduce.Job; import org.apache.hadoop.mapreduce.JobContext; import org.apache.hadoop.mapreduce.lib.input.FileInputFormat; import org.apache.hadoop.mapreduce.lib.output.FileOutputFormat; import org.apache.jena.grande.mapreduce.io.MapReduceLabelToNode; import org.openjena.riot.ErrorHandlerFactory; import org.openjena.riot.lang.LabelToNode; import org.openjena.riot.system.IRIResolver; import org.openjena.riot.system.ParserProfile; import org.openjena.riot.system.ParserProfileBase; /* * 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.jena.grande; public class Utils { public static ParserProfile createParserProfile(JobContext context, Path path) { Prologue prologue = new Prologue(null, IRIResolver.createNoResolve());
LabelToNode labelMapping = new MapReduceLabelToNode(context, path);
castagna/jena-grande
src/main/java/org/apache/jena/grande/mapreduce/Counters.java
// Path: src/main/java/org/apache/jena/grande/Constants.java // public class Constants { // // public static final String RUN_ID = "runId"; // // public static final String OPTION_USE_COMPRESSION = "useCompression"; // public static final boolean OPTION_USE_COMPRESSION_DEFAULT = false; // // public static final String OPTION_OVERWRITE_OUTPUT = "overwriteOutput"; // public static final boolean OPTION_OVERWRITE_OUTPUT_DEFAULT = false; // // public static final String OPTION_RUN_LOCAL = "runLocal"; // public static final boolean OPTION_RUN_LOCAL_DEFAULT = false; // // public static final String OPTION_NUM_REDUCERS = "numReducers"; // public static final int OPTION_NUM_REDUCERS_DEFAULT = 20; // // public static final String RDF_2_ADJACENCY_LIST = "rdf2adjacencylist"; // // // public static final PrefixMap defaultPrefixMap = new PrefixMap(); // static { // defaultPrefixMap.add("rdf", RDF.getURI()); // defaultPrefixMap.add("rdfs", RDFS.getURI()); // defaultPrefixMap.add("owl", OWL.getURI()); // defaultPrefixMap.add("xsd", XSD.getURI()); // defaultPrefixMap.add("foaf", FOAF.getURI()); // defaultPrefixMap.add("dc", DC.getURI()); // defaultPrefixMap.add("dcterms", DCTerms.getURI()); // defaultPrefixMap.add("dctypes", DCTypes.getURI()); // } // // // MapReduce counters // // public static final String JENA_GRANDE_COUNTER_GROUPNAME = "TDBLoader4 Counters"; // public static final String JENA_GRANDE_COUNTER_MALFORMED = "Malformed"; // public static final String JENA_GRANDE_COUNTER_QUADS = "Quads (including duplicates)"; // public static final String JENA_GRANDE_COUNTER_TRIPLES = "Triples (including duplicates)"; // public static final String JENA_GRANDE_COUNTER_DUPLICATES = "Duplicates (quads or triples)"; // public static final String JENA_GRANDE_COUNTER_RDFNODES = "RDF nodes"; // public static final String JENA_GRANDE_COUNTER_RECORDS = "Index records"; // // // Event types // // public static EventType eventQuad = new EventType("quad"); // public static EventType eventTriple = new EventType("triple"); // public static EventType eventDuplicate = new EventType("duplicate"); // public static EventType eventMalformed = new EventType("malformed"); // public static EventType eventRdfNode = new EventType("RDF node"); // public static EventType eventRecord = new EventType("record"); // public static EventType eventTick = new EventType("tick"); // // } // // Path: src/main/java/org/apache/jena/grande/JenaGrandeException.java // @SuppressWarnings("serial") // public class JenaGrandeException extends JenaException { // // public JenaGrandeException() { super() ; } // public JenaGrandeException(String msg) { super(msg) ; } // public JenaGrandeException(Throwable th) { super(th) ; } // public JenaGrandeException(String msg, Throwable th) { super(msg, th) ; } // // }
import org.apache.hadoop.mapreduce.Counter; import org.apache.hadoop.mapreduce.TaskInputOutputContext; import org.apache.jena.grande.Constants; import org.apache.jena.grande.JenaGrandeException; import org.openjena.atlas.event.Event; import org.openjena.atlas.event.EventListener; import org.openjena.atlas.event.EventManager; import org.openjena.atlas.event.EventType;
/* * 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.jena.grande.mapreduce; public class Counters implements EventListener { private final TaskInputOutputContext<?,?,?,?> context; private Counter counterTriples = null; private Counter counterQuads = null; private Counter counterDuplicates = null; private Counter counterMalformed = null; private Counter counterRdfNodes = null; private Counter counterRecords = null; private long numTriples = 0L; private long numQuads = 0L; private long numDuplicates = 0L; private long numMalformed = 0L; private long numRdfNodes = 0L; private long numRecords = 0L; private long n = 0L; private int tick; public Counters (TaskInputOutputContext<?,?,?,?> context) { this(context, 1000); } public Counters (TaskInputOutputContext<?,?,?,?> context, int tick) { this.context = context; this.tick = tick;
// Path: src/main/java/org/apache/jena/grande/Constants.java // public class Constants { // // public static final String RUN_ID = "runId"; // // public static final String OPTION_USE_COMPRESSION = "useCompression"; // public static final boolean OPTION_USE_COMPRESSION_DEFAULT = false; // // public static final String OPTION_OVERWRITE_OUTPUT = "overwriteOutput"; // public static final boolean OPTION_OVERWRITE_OUTPUT_DEFAULT = false; // // public static final String OPTION_RUN_LOCAL = "runLocal"; // public static final boolean OPTION_RUN_LOCAL_DEFAULT = false; // // public static final String OPTION_NUM_REDUCERS = "numReducers"; // public static final int OPTION_NUM_REDUCERS_DEFAULT = 20; // // public static final String RDF_2_ADJACENCY_LIST = "rdf2adjacencylist"; // // // public static final PrefixMap defaultPrefixMap = new PrefixMap(); // static { // defaultPrefixMap.add("rdf", RDF.getURI()); // defaultPrefixMap.add("rdfs", RDFS.getURI()); // defaultPrefixMap.add("owl", OWL.getURI()); // defaultPrefixMap.add("xsd", XSD.getURI()); // defaultPrefixMap.add("foaf", FOAF.getURI()); // defaultPrefixMap.add("dc", DC.getURI()); // defaultPrefixMap.add("dcterms", DCTerms.getURI()); // defaultPrefixMap.add("dctypes", DCTypes.getURI()); // } // // // MapReduce counters // // public static final String JENA_GRANDE_COUNTER_GROUPNAME = "TDBLoader4 Counters"; // public static final String JENA_GRANDE_COUNTER_MALFORMED = "Malformed"; // public static final String JENA_GRANDE_COUNTER_QUADS = "Quads (including duplicates)"; // public static final String JENA_GRANDE_COUNTER_TRIPLES = "Triples (including duplicates)"; // public static final String JENA_GRANDE_COUNTER_DUPLICATES = "Duplicates (quads or triples)"; // public static final String JENA_GRANDE_COUNTER_RDFNODES = "RDF nodes"; // public static final String JENA_GRANDE_COUNTER_RECORDS = "Index records"; // // // Event types // // public static EventType eventQuad = new EventType("quad"); // public static EventType eventTriple = new EventType("triple"); // public static EventType eventDuplicate = new EventType("duplicate"); // public static EventType eventMalformed = new EventType("malformed"); // public static EventType eventRdfNode = new EventType("RDF node"); // public static EventType eventRecord = new EventType("record"); // public static EventType eventTick = new EventType("tick"); // // } // // Path: src/main/java/org/apache/jena/grande/JenaGrandeException.java // @SuppressWarnings("serial") // public class JenaGrandeException extends JenaException { // // public JenaGrandeException() { super() ; } // public JenaGrandeException(String msg) { super(msg) ; } // public JenaGrandeException(Throwable th) { super(th) ; } // public JenaGrandeException(String msg, Throwable th) { super(msg, th) ; } // // } // Path: src/main/java/org/apache/jena/grande/mapreduce/Counters.java import org.apache.hadoop.mapreduce.Counter; import org.apache.hadoop.mapreduce.TaskInputOutputContext; import org.apache.jena.grande.Constants; import org.apache.jena.grande.JenaGrandeException; import org.openjena.atlas.event.Event; import org.openjena.atlas.event.EventListener; import org.openjena.atlas.event.EventManager; import org.openjena.atlas.event.EventType; /* * 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.jena.grande.mapreduce; public class Counters implements EventListener { private final TaskInputOutputContext<?,?,?,?> context; private Counter counterTriples = null; private Counter counterQuads = null; private Counter counterDuplicates = null; private Counter counterMalformed = null; private Counter counterRdfNodes = null; private Counter counterRecords = null; private long numTriples = 0L; private long numQuads = 0L; private long numDuplicates = 0L; private long numMalformed = 0L; private long numRdfNodes = 0L; private long numRecords = 0L; private long n = 0L; private int tick; public Counters (TaskInputOutputContext<?,?,?,?> context) { this(context, 1000); } public Counters (TaskInputOutputContext<?,?,?,?> context, int tick) { this.context = context; this.tick = tick;
EventManager.register(this, Constants.eventQuad, this);
castagna/jena-grande
src/main/java/org/apache/jena/grande/mapreduce/Counters.java
// Path: src/main/java/org/apache/jena/grande/Constants.java // public class Constants { // // public static final String RUN_ID = "runId"; // // public static final String OPTION_USE_COMPRESSION = "useCompression"; // public static final boolean OPTION_USE_COMPRESSION_DEFAULT = false; // // public static final String OPTION_OVERWRITE_OUTPUT = "overwriteOutput"; // public static final boolean OPTION_OVERWRITE_OUTPUT_DEFAULT = false; // // public static final String OPTION_RUN_LOCAL = "runLocal"; // public static final boolean OPTION_RUN_LOCAL_DEFAULT = false; // // public static final String OPTION_NUM_REDUCERS = "numReducers"; // public static final int OPTION_NUM_REDUCERS_DEFAULT = 20; // // public static final String RDF_2_ADJACENCY_LIST = "rdf2adjacencylist"; // // // public static final PrefixMap defaultPrefixMap = new PrefixMap(); // static { // defaultPrefixMap.add("rdf", RDF.getURI()); // defaultPrefixMap.add("rdfs", RDFS.getURI()); // defaultPrefixMap.add("owl", OWL.getURI()); // defaultPrefixMap.add("xsd", XSD.getURI()); // defaultPrefixMap.add("foaf", FOAF.getURI()); // defaultPrefixMap.add("dc", DC.getURI()); // defaultPrefixMap.add("dcterms", DCTerms.getURI()); // defaultPrefixMap.add("dctypes", DCTypes.getURI()); // } // // // MapReduce counters // // public static final String JENA_GRANDE_COUNTER_GROUPNAME = "TDBLoader4 Counters"; // public static final String JENA_GRANDE_COUNTER_MALFORMED = "Malformed"; // public static final String JENA_GRANDE_COUNTER_QUADS = "Quads (including duplicates)"; // public static final String JENA_GRANDE_COUNTER_TRIPLES = "Triples (including duplicates)"; // public static final String JENA_GRANDE_COUNTER_DUPLICATES = "Duplicates (quads or triples)"; // public static final String JENA_GRANDE_COUNTER_RDFNODES = "RDF nodes"; // public static final String JENA_GRANDE_COUNTER_RECORDS = "Index records"; // // // Event types // // public static EventType eventQuad = new EventType("quad"); // public static EventType eventTriple = new EventType("triple"); // public static EventType eventDuplicate = new EventType("duplicate"); // public static EventType eventMalformed = new EventType("malformed"); // public static EventType eventRdfNode = new EventType("RDF node"); // public static EventType eventRecord = new EventType("record"); // public static EventType eventTick = new EventType("tick"); // // } // // Path: src/main/java/org/apache/jena/grande/JenaGrandeException.java // @SuppressWarnings("serial") // public class JenaGrandeException extends JenaException { // // public JenaGrandeException() { super() ; } // public JenaGrandeException(String msg) { super(msg) ; } // public JenaGrandeException(Throwable th) { super(th) ; } // public JenaGrandeException(String msg, Throwable th) { super(msg, th) ; } // // }
import org.apache.hadoop.mapreduce.Counter; import org.apache.hadoop.mapreduce.TaskInputOutputContext; import org.apache.jena.grande.Constants; import org.apache.jena.grande.JenaGrandeException; import org.openjena.atlas.event.Event; import org.openjena.atlas.event.EventListener; import org.openjena.atlas.event.EventManager; import org.openjena.atlas.event.EventType;
this.tick = tick; } public int getTick() { return tick; } @Override public void event(Object dest, Event event) { if ( this.equals(dest) ) { EventType type = event.getType(); if ( type.equals(Constants.eventQuad) ) { if ( counterQuads == null ) counterQuads = context.getCounter(Constants.JENA_GRANDE_COUNTER_GROUPNAME, Constants.JENA_GRANDE_COUNTER_QUADS); numQuads++; } else if ( type.equals(Constants.eventTriple) ) { if ( counterTriples == null ) counterTriples = context.getCounter(Constants.JENA_GRANDE_COUNTER_GROUPNAME, Constants.JENA_GRANDE_COUNTER_TRIPLES); numTriples++; } else if ( type.equals(Constants.eventDuplicate) ) { if ( counterDuplicates == null ) counterDuplicates = context.getCounter(Constants.JENA_GRANDE_COUNTER_GROUPNAME, Constants.JENA_GRANDE_COUNTER_DUPLICATES); numDuplicates++; } else if ( type.equals(Constants.eventMalformed) ) { if ( counterMalformed == null ) counterMalformed = context.getCounter(Constants.JENA_GRANDE_COUNTER_GROUPNAME, Constants.JENA_GRANDE_COUNTER_MALFORMED); numMalformed++; } else if ( type.equals(Constants.eventRdfNode) ) { if ( counterRdfNodes == null ) counterRdfNodes = context.getCounter(Constants.JENA_GRANDE_COUNTER_GROUPNAME, Constants.JENA_GRANDE_COUNTER_RDFNODES); numRdfNodes++; } else if ( type.equals(Constants.eventRecord) ) { if ( counterRecords == null ) counterRecords = context.getCounter(Constants.JENA_GRANDE_COUNTER_GROUPNAME, Constants.JENA_GRANDE_COUNTER_RECORDS); numRecords++; } else {
// Path: src/main/java/org/apache/jena/grande/Constants.java // public class Constants { // // public static final String RUN_ID = "runId"; // // public static final String OPTION_USE_COMPRESSION = "useCompression"; // public static final boolean OPTION_USE_COMPRESSION_DEFAULT = false; // // public static final String OPTION_OVERWRITE_OUTPUT = "overwriteOutput"; // public static final boolean OPTION_OVERWRITE_OUTPUT_DEFAULT = false; // // public static final String OPTION_RUN_LOCAL = "runLocal"; // public static final boolean OPTION_RUN_LOCAL_DEFAULT = false; // // public static final String OPTION_NUM_REDUCERS = "numReducers"; // public static final int OPTION_NUM_REDUCERS_DEFAULT = 20; // // public static final String RDF_2_ADJACENCY_LIST = "rdf2adjacencylist"; // // // public static final PrefixMap defaultPrefixMap = new PrefixMap(); // static { // defaultPrefixMap.add("rdf", RDF.getURI()); // defaultPrefixMap.add("rdfs", RDFS.getURI()); // defaultPrefixMap.add("owl", OWL.getURI()); // defaultPrefixMap.add("xsd", XSD.getURI()); // defaultPrefixMap.add("foaf", FOAF.getURI()); // defaultPrefixMap.add("dc", DC.getURI()); // defaultPrefixMap.add("dcterms", DCTerms.getURI()); // defaultPrefixMap.add("dctypes", DCTypes.getURI()); // } // // // MapReduce counters // // public static final String JENA_GRANDE_COUNTER_GROUPNAME = "TDBLoader4 Counters"; // public static final String JENA_GRANDE_COUNTER_MALFORMED = "Malformed"; // public static final String JENA_GRANDE_COUNTER_QUADS = "Quads (including duplicates)"; // public static final String JENA_GRANDE_COUNTER_TRIPLES = "Triples (including duplicates)"; // public static final String JENA_GRANDE_COUNTER_DUPLICATES = "Duplicates (quads or triples)"; // public static final String JENA_GRANDE_COUNTER_RDFNODES = "RDF nodes"; // public static final String JENA_GRANDE_COUNTER_RECORDS = "Index records"; // // // Event types // // public static EventType eventQuad = new EventType("quad"); // public static EventType eventTriple = new EventType("triple"); // public static EventType eventDuplicate = new EventType("duplicate"); // public static EventType eventMalformed = new EventType("malformed"); // public static EventType eventRdfNode = new EventType("RDF node"); // public static EventType eventRecord = new EventType("record"); // public static EventType eventTick = new EventType("tick"); // // } // // Path: src/main/java/org/apache/jena/grande/JenaGrandeException.java // @SuppressWarnings("serial") // public class JenaGrandeException extends JenaException { // // public JenaGrandeException() { super() ; } // public JenaGrandeException(String msg) { super(msg) ; } // public JenaGrandeException(Throwable th) { super(th) ; } // public JenaGrandeException(String msg, Throwable th) { super(msg, th) ; } // // } // Path: src/main/java/org/apache/jena/grande/mapreduce/Counters.java import org.apache.hadoop.mapreduce.Counter; import org.apache.hadoop.mapreduce.TaskInputOutputContext; import org.apache.jena.grande.Constants; import org.apache.jena.grande.JenaGrandeException; import org.openjena.atlas.event.Event; import org.openjena.atlas.event.EventListener; import org.openjena.atlas.event.EventManager; import org.openjena.atlas.event.EventType; this.tick = tick; } public int getTick() { return tick; } @Override public void event(Object dest, Event event) { if ( this.equals(dest) ) { EventType type = event.getType(); if ( type.equals(Constants.eventQuad) ) { if ( counterQuads == null ) counterQuads = context.getCounter(Constants.JENA_GRANDE_COUNTER_GROUPNAME, Constants.JENA_GRANDE_COUNTER_QUADS); numQuads++; } else if ( type.equals(Constants.eventTriple) ) { if ( counterTriples == null ) counterTriples = context.getCounter(Constants.JENA_GRANDE_COUNTER_GROUPNAME, Constants.JENA_GRANDE_COUNTER_TRIPLES); numTriples++; } else if ( type.equals(Constants.eventDuplicate) ) { if ( counterDuplicates == null ) counterDuplicates = context.getCounter(Constants.JENA_GRANDE_COUNTER_GROUPNAME, Constants.JENA_GRANDE_COUNTER_DUPLICATES); numDuplicates++; } else if ( type.equals(Constants.eventMalformed) ) { if ( counterMalformed == null ) counterMalformed = context.getCounter(Constants.JENA_GRANDE_COUNTER_GROUPNAME, Constants.JENA_GRANDE_COUNTER_MALFORMED); numMalformed++; } else if ( type.equals(Constants.eventRdfNode) ) { if ( counterRdfNodes == null ) counterRdfNodes = context.getCounter(Constants.JENA_GRANDE_COUNTER_GROUPNAME, Constants.JENA_GRANDE_COUNTER_RDFNODES); numRdfNodes++; } else if ( type.equals(Constants.eventRecord) ) { if ( counterRecords == null ) counterRecords = context.getCounter(Constants.JENA_GRANDE_COUNTER_GROUPNAME, Constants.JENA_GRANDE_COUNTER_RECORDS); numRecords++; } else {
throw new JenaGrandeException("Unsupported event type: " + type);
castagna/jena-grande
src/main/java/org/apache/jena/grande/mapreduce/io/MapReduceLabelToNode.java
// Path: src/main/java/org/apache/jena/grande/Constants.java // public class Constants { // // public static final String RUN_ID = "runId"; // // public static final String OPTION_USE_COMPRESSION = "useCompression"; // public static final boolean OPTION_USE_COMPRESSION_DEFAULT = false; // // public static final String OPTION_OVERWRITE_OUTPUT = "overwriteOutput"; // public static final boolean OPTION_OVERWRITE_OUTPUT_DEFAULT = false; // // public static final String OPTION_RUN_LOCAL = "runLocal"; // public static final boolean OPTION_RUN_LOCAL_DEFAULT = false; // // public static final String OPTION_NUM_REDUCERS = "numReducers"; // public static final int OPTION_NUM_REDUCERS_DEFAULT = 20; // // public static final String RDF_2_ADJACENCY_LIST = "rdf2adjacencylist"; // // // public static final PrefixMap defaultPrefixMap = new PrefixMap(); // static { // defaultPrefixMap.add("rdf", RDF.getURI()); // defaultPrefixMap.add("rdfs", RDFS.getURI()); // defaultPrefixMap.add("owl", OWL.getURI()); // defaultPrefixMap.add("xsd", XSD.getURI()); // defaultPrefixMap.add("foaf", FOAF.getURI()); // defaultPrefixMap.add("dc", DC.getURI()); // defaultPrefixMap.add("dcterms", DCTerms.getURI()); // defaultPrefixMap.add("dctypes", DCTypes.getURI()); // } // // // MapReduce counters // // public static final String JENA_GRANDE_COUNTER_GROUPNAME = "TDBLoader4 Counters"; // public static final String JENA_GRANDE_COUNTER_MALFORMED = "Malformed"; // public static final String JENA_GRANDE_COUNTER_QUADS = "Quads (including duplicates)"; // public static final String JENA_GRANDE_COUNTER_TRIPLES = "Triples (including duplicates)"; // public static final String JENA_GRANDE_COUNTER_DUPLICATES = "Duplicates (quads or triples)"; // public static final String JENA_GRANDE_COUNTER_RDFNODES = "RDF nodes"; // public static final String JENA_GRANDE_COUNTER_RECORDS = "Index records"; // // // Event types // // public static EventType eventQuad = new EventType("quad"); // public static EventType eventTriple = new EventType("triple"); // public static EventType eventDuplicate = new EventType("duplicate"); // public static EventType eventMalformed = new EventType("malformed"); // public static EventType eventRdfNode = new EventType("RDF node"); // public static EventType eventRecord = new EventType("record"); // public static EventType eventTick = new EventType("tick"); // // }
import java.util.HashMap; import java.util.Map; import org.apache.hadoop.fs.Path; import org.apache.hadoop.mapreduce.JobContext; import org.apache.jena.grande.Constants; import org.openjena.riot.lang.LabelToNode; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import com.hp.hpl.jena.graph.Node; import com.hp.hpl.jena.rdf.model.AnonId;
/* * 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.jena.grande.mapreduce.io; public class MapReduceLabelToNode extends LabelToNode { private static final Logger log = LoggerFactory.getLogger(MapReduceLabelToNode.class); public MapReduceLabelToNode(JobContext context, Path path) { super(new SingleScopePolicy(), new MapReduceAllocator(context, path)); } private static class SingleScopePolicy implements ScopePolicy<String, Node, Node> { private Map<String, Node> map = new HashMap<String, Node>() ; @Override public Map<String, Node> getScope(Node scope) { return map ; } @Override public void clear() { map.clear(); } } private static class MapReduceAllocator implements Allocator<String, Node> { private String runId ; private Path path ; public MapReduceAllocator (JobContext context, Path path) { // This is to ensure that blank node allocation policy is constant when subsequent MapReduce jobs need that
// Path: src/main/java/org/apache/jena/grande/Constants.java // public class Constants { // // public static final String RUN_ID = "runId"; // // public static final String OPTION_USE_COMPRESSION = "useCompression"; // public static final boolean OPTION_USE_COMPRESSION_DEFAULT = false; // // public static final String OPTION_OVERWRITE_OUTPUT = "overwriteOutput"; // public static final boolean OPTION_OVERWRITE_OUTPUT_DEFAULT = false; // // public static final String OPTION_RUN_LOCAL = "runLocal"; // public static final boolean OPTION_RUN_LOCAL_DEFAULT = false; // // public static final String OPTION_NUM_REDUCERS = "numReducers"; // public static final int OPTION_NUM_REDUCERS_DEFAULT = 20; // // public static final String RDF_2_ADJACENCY_LIST = "rdf2adjacencylist"; // // // public static final PrefixMap defaultPrefixMap = new PrefixMap(); // static { // defaultPrefixMap.add("rdf", RDF.getURI()); // defaultPrefixMap.add("rdfs", RDFS.getURI()); // defaultPrefixMap.add("owl", OWL.getURI()); // defaultPrefixMap.add("xsd", XSD.getURI()); // defaultPrefixMap.add("foaf", FOAF.getURI()); // defaultPrefixMap.add("dc", DC.getURI()); // defaultPrefixMap.add("dcterms", DCTerms.getURI()); // defaultPrefixMap.add("dctypes", DCTypes.getURI()); // } // // // MapReduce counters // // public static final String JENA_GRANDE_COUNTER_GROUPNAME = "TDBLoader4 Counters"; // public static final String JENA_GRANDE_COUNTER_MALFORMED = "Malformed"; // public static final String JENA_GRANDE_COUNTER_QUADS = "Quads (including duplicates)"; // public static final String JENA_GRANDE_COUNTER_TRIPLES = "Triples (including duplicates)"; // public static final String JENA_GRANDE_COUNTER_DUPLICATES = "Duplicates (quads or triples)"; // public static final String JENA_GRANDE_COUNTER_RDFNODES = "RDF nodes"; // public static final String JENA_GRANDE_COUNTER_RECORDS = "Index records"; // // // Event types // // public static EventType eventQuad = new EventType("quad"); // public static EventType eventTriple = new EventType("triple"); // public static EventType eventDuplicate = new EventType("duplicate"); // public static EventType eventMalformed = new EventType("malformed"); // public static EventType eventRdfNode = new EventType("RDF node"); // public static EventType eventRecord = new EventType("record"); // public static EventType eventTick = new EventType("tick"); // // } // Path: src/main/java/org/apache/jena/grande/mapreduce/io/MapReduceLabelToNode.java import java.util.HashMap; import java.util.Map; import org.apache.hadoop.fs.Path; import org.apache.hadoop.mapreduce.JobContext; import org.apache.jena.grande.Constants; import org.openjena.riot.lang.LabelToNode; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import com.hp.hpl.jena.graph.Node; import com.hp.hpl.jena.rdf.model.AnonId; /* * 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.jena.grande.mapreduce.io; public class MapReduceLabelToNode extends LabelToNode { private static final Logger log = LoggerFactory.getLogger(MapReduceLabelToNode.class); public MapReduceLabelToNode(JobContext context, Path path) { super(new SingleScopePolicy(), new MapReduceAllocator(context, path)); } private static class SingleScopePolicy implements ScopePolicy<String, Node, Node> { private Map<String, Node> map = new HashMap<String, Node>() ; @Override public Map<String, Node> getScope(Node scope) { return map ; } @Override public void clear() { map.clear(); } } private static class MapReduceAllocator implements Allocator<String, Node> { private String runId ; private Path path ; public MapReduceAllocator (JobContext context, Path path) { // This is to ensure that blank node allocation policy is constant when subsequent MapReduce jobs need that
this.runId = context.getConfiguration().get(Constants.RUN_ID);
castagna/jena-grande
src/main/java/org/apache/jena/grande/examples/Run.java
// Path: src/main/java/org/apache/jena/grande/NodeEncoder.java // public class NodeEncoder { // // private static final PrefixMap emptyPrefixMap = new PrefixMap(); // // public static String asString(Node node) { // StringWriter sw = new StringWriter() ; // NodeFmtLib.serialize(sw, node, null, emptyPrefixMap); // return sw.toString() ; // } // // public static String asString(Node node, PrefixMap prefixMap) { // StringWriter sw = new StringWriter() ; // NodeFmtLib.serialize(sw, node, null, prefixMap); // return sw.toString() ; // } // // public static Node asNode(String str) { // return NodeFactory.parseNode(str); // } // // }
import org.apache.jena.grande.NodeEncoder; import com.hp.hpl.jena.graph.Node; import com.hp.hpl.jena.sparql.util.NodeFactory;
/* * 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.jena.grande.examples; public class Run { public static void main(String[] args) { Node node = NodeFactory.parseNode("\"\"\"This\nis\na\ntest.\"\"\""); System.out.println(node.getLiteralLexicalForm());
// Path: src/main/java/org/apache/jena/grande/NodeEncoder.java // public class NodeEncoder { // // private static final PrefixMap emptyPrefixMap = new PrefixMap(); // // public static String asString(Node node) { // StringWriter sw = new StringWriter() ; // NodeFmtLib.serialize(sw, node, null, emptyPrefixMap); // return sw.toString() ; // } // // public static String asString(Node node, PrefixMap prefixMap) { // StringWriter sw = new StringWriter() ; // NodeFmtLib.serialize(sw, node, null, prefixMap); // return sw.toString() ; // } // // public static Node asNode(String str) { // return NodeFactory.parseNode(str); // } // // } // Path: src/main/java/org/apache/jena/grande/examples/Run.java import org.apache.jena.grande.NodeEncoder; import com.hp.hpl.jena.graph.Node; import com.hp.hpl.jena.sparql.util.NodeFactory; /* * 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.jena.grande.examples; public class Run { public static void main(String[] args) { Node node = NodeFactory.parseNode("\"\"\"This\nis\na\ntest.\"\"\""); System.out.println(node.getLiteralLexicalForm());
System.out.println(NodeEncoder.asString(node));
castagna/jena-grande
src/main/java/org/apache/jena/grande/pig/NQuadsPigOutputFormat.java
// Path: src/main/java/org/apache/jena/grande/mapreduce/io/NQuadsOutputFormat.java // public class NQuadsOutputFormat extends FileOutputFormat<NullWritable, QuadWritable> { // // @Override // public RecordWriter<NullWritable, QuadWritable> getRecordWriter(TaskAttemptContext context) throws IOException, InterruptedException { // Configuration conf = context.getConfiguration(); // boolean isCompressed = getCompressOutput(context); // CompressionCodec codec = null; // String extension = ""; // if (isCompressed) { // Class<? extends CompressionCodec> codecClass = getOutputCompressorClass(context, GzipCodec.class); // codec = (CompressionCodec) ReflectionUtils.newInstance(codecClass, conf); // extension = codec.getDefaultExtension(); // } // Path file = getDefaultWorkFile(context, extension); // FileSystem fs = file.getFileSystem(conf); // if (!isCompressed) { // FSDataOutputStream fileOut = fs.create(file, false); // return new QuadRecordWriter(new OutputStreamWriter(fileOut)); // } else { // FSDataOutputStream fileOut = fs.create(file, false); // return new QuadRecordWriter(new OutputStreamWriter(codec.createOutputStream(fileOut))); // } // } // // } // // Path: src/main/java/org/apache/jena/grande/mapreduce/io/QuadWritable.java // public class QuadWritable extends BinaryComparable implements WritableComparable<BinaryComparable> { // // private Quad quad; // private byte[] bytes; // private int length; // // public QuadWritable(){ // this( new Quad(Node.ANY, Node.ANY, Node.ANY, Node.ANY) ); // } // // public QuadWritable(Quad quad) { // this.quad = quad; // this.bytes = toBytes(quad); // this.length = bytes.length; // } // // @Override // public void readFields(DataInput in) throws IOException { // length = WritableUtils.readVInt(in); // bytes = new byte[length]; // in.readFully(bytes, 0, length); // Tokenizer tokenizer = TokenizerFactory.makeTokenizerASCII(new String(bytes)) ; // LangNQuads parser = new LangNQuads(tokenizer, RiotLib.profile(Lang.NQUADS, null), null) ; // quad = parser.next(); // } // // @Override // public void write(DataOutput out) throws IOException { // WritableUtils.writeVInt(out, length); // out.write(bytes, 0, length); // } // // @Override // public byte[] getBytes() { // return bytes; // } // // @Override // public int getLength() { // return length; // } // // public Quad getQuad() { // return quad; // } // // private byte[] toBytes(Quad quad) { // StringWriter out = new StringWriter(); // out.getBuffer().length(); // OutputLangUtils.output(out, quad, null, null); // try { // return out.toString().getBytes("UTF-8"); // } catch (UnsupportedEncodingException e) { // throw new JenaGrandeException(e); // } // } // // @Override // public String toString() { // return quad.toString(); // } // }
import java.io.IOException; import org.apache.hadoop.io.NullWritable; import org.apache.hadoop.mapreduce.RecordWriter; import org.apache.hadoop.mapreduce.TaskAttemptContext; import org.apache.jena.grande.mapreduce.io.NQuadsOutputFormat; import org.apache.jena.grande.mapreduce.io.QuadWritable; import org.slf4j.Logger; import org.slf4j.LoggerFactory;
/* * 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.jena.grande.pig; public class NQuadsPigOutputFormat extends NQuadsOutputFormat { private static final Logger log = LoggerFactory.getLogger(NQuadsPigOutputFormat.class); @Override
// Path: src/main/java/org/apache/jena/grande/mapreduce/io/NQuadsOutputFormat.java // public class NQuadsOutputFormat extends FileOutputFormat<NullWritable, QuadWritable> { // // @Override // public RecordWriter<NullWritable, QuadWritable> getRecordWriter(TaskAttemptContext context) throws IOException, InterruptedException { // Configuration conf = context.getConfiguration(); // boolean isCompressed = getCompressOutput(context); // CompressionCodec codec = null; // String extension = ""; // if (isCompressed) { // Class<? extends CompressionCodec> codecClass = getOutputCompressorClass(context, GzipCodec.class); // codec = (CompressionCodec) ReflectionUtils.newInstance(codecClass, conf); // extension = codec.getDefaultExtension(); // } // Path file = getDefaultWorkFile(context, extension); // FileSystem fs = file.getFileSystem(conf); // if (!isCompressed) { // FSDataOutputStream fileOut = fs.create(file, false); // return new QuadRecordWriter(new OutputStreamWriter(fileOut)); // } else { // FSDataOutputStream fileOut = fs.create(file, false); // return new QuadRecordWriter(new OutputStreamWriter(codec.createOutputStream(fileOut))); // } // } // // } // // Path: src/main/java/org/apache/jena/grande/mapreduce/io/QuadWritable.java // public class QuadWritable extends BinaryComparable implements WritableComparable<BinaryComparable> { // // private Quad quad; // private byte[] bytes; // private int length; // // public QuadWritable(){ // this( new Quad(Node.ANY, Node.ANY, Node.ANY, Node.ANY) ); // } // // public QuadWritable(Quad quad) { // this.quad = quad; // this.bytes = toBytes(quad); // this.length = bytes.length; // } // // @Override // public void readFields(DataInput in) throws IOException { // length = WritableUtils.readVInt(in); // bytes = new byte[length]; // in.readFully(bytes, 0, length); // Tokenizer tokenizer = TokenizerFactory.makeTokenizerASCII(new String(bytes)) ; // LangNQuads parser = new LangNQuads(tokenizer, RiotLib.profile(Lang.NQUADS, null), null) ; // quad = parser.next(); // } // // @Override // public void write(DataOutput out) throws IOException { // WritableUtils.writeVInt(out, length); // out.write(bytes, 0, length); // } // // @Override // public byte[] getBytes() { // return bytes; // } // // @Override // public int getLength() { // return length; // } // // public Quad getQuad() { // return quad; // } // // private byte[] toBytes(Quad quad) { // StringWriter out = new StringWriter(); // out.getBuffer().length(); // OutputLangUtils.output(out, quad, null, null); // try { // return out.toString().getBytes("UTF-8"); // } catch (UnsupportedEncodingException e) { // throw new JenaGrandeException(e); // } // } // // @Override // public String toString() { // return quad.toString(); // } // } // Path: src/main/java/org/apache/jena/grande/pig/NQuadsPigOutputFormat.java import java.io.IOException; import org.apache.hadoop.io.NullWritable; import org.apache.hadoop.mapreduce.RecordWriter; import org.apache.hadoop.mapreduce.TaskAttemptContext; import org.apache.jena.grande.mapreduce.io.NQuadsOutputFormat; import org.apache.jena.grande.mapreduce.io.QuadWritable; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /* * 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.jena.grande.pig; public class NQuadsPigOutputFormat extends NQuadsOutputFormat { private static final Logger log = LoggerFactory.getLogger(NQuadsPigOutputFormat.class); @Override
public RecordWriter<NullWritable, QuadWritable> getRecordWriter(TaskAttemptContext context) throws IOException, InterruptedException {
castagna/jena-grande
src/main/java/org/apache/jena/grande/examples/RunPigSparql2PigLatin.java
// Path: src/main/java/org/apache/jena/grande/pig/Sparql2PigLatinWriter.java // public class Sparql2PigLatinWriter extends OpVisitorBase { // // private Writer out = null; // // public Sparql2PigLatinWriter(Writer out) { // super(); // this.out = out; // } // // public Sparql2PigLatinWriter(OutputStream out) { // this(FileUtils.asPrintWriterUTF8(out)); // } // // public void visit(OpBGP opBGP) { // try { // List<Triple> patterns = opBGP.getPattern().getList(); // boolean first = true; // // for (Triple triple : patterns) { // String filter = null; // // if (!triple.getSubject().isVariable()) { // if (first) filter = "FILTER dataset BY "; // filter.concat("( s == '" + out(triple.getSubject()) + "' )"); // first = false; // } // // if (!triple.getPredicate().isVariable()) { // if ( first ) { // filter = "FILTER dataset BY "; // } else { // filter = filter.concat(" AND ") ; // } // filter = filter.concat("( p == '" + out(triple.getPredicate()) + "' )"); // first = false; // } // // if (!triple.getObject().isVariable()) { // if ( first ) { // filter = "FILTER dataset BY "; // } else { // filter = filter.concat(" AND ") ; // } // filter = filter.concat("( o == '" + out(triple.getObject()) + "' )"); // first = false; // } // // if (filter != null) { // out.write(filter); // } // } // } catch (IOException e) { // e.printStackTrace(); // } // } // // private String out(Node node) { // return NodeEncoder.asString(node); // } // // }
import java.io.IOException; import java.io.StringWriter; import org.apache.jena.grande.pig.Sparql2PigLatinWriter; import com.hp.hpl.jena.query.Query; import com.hp.hpl.jena.query.QueryFactory; import com.hp.hpl.jena.sparql.algebra.Algebra; import com.hp.hpl.jena.sparql.algebra.Op;
/* * 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.jena.grande.examples; public class RunPigSparql2PigLatin { public static void main(String[] args) throws IOException { Query query = QueryFactory.read("src/test/resources/query.rq"); // PrintUtils.printOp(IndentedWriter.stdout, query, true); Op op = Algebra.compile(query); StringWriter out = new StringWriter();
// Path: src/main/java/org/apache/jena/grande/pig/Sparql2PigLatinWriter.java // public class Sparql2PigLatinWriter extends OpVisitorBase { // // private Writer out = null; // // public Sparql2PigLatinWriter(Writer out) { // super(); // this.out = out; // } // // public Sparql2PigLatinWriter(OutputStream out) { // this(FileUtils.asPrintWriterUTF8(out)); // } // // public void visit(OpBGP opBGP) { // try { // List<Triple> patterns = opBGP.getPattern().getList(); // boolean first = true; // // for (Triple triple : patterns) { // String filter = null; // // if (!triple.getSubject().isVariable()) { // if (first) filter = "FILTER dataset BY "; // filter.concat("( s == '" + out(triple.getSubject()) + "' )"); // first = false; // } // // if (!triple.getPredicate().isVariable()) { // if ( first ) { // filter = "FILTER dataset BY "; // } else { // filter = filter.concat(" AND ") ; // } // filter = filter.concat("( p == '" + out(triple.getPredicate()) + "' )"); // first = false; // } // // if (!triple.getObject().isVariable()) { // if ( first ) { // filter = "FILTER dataset BY "; // } else { // filter = filter.concat(" AND ") ; // } // filter = filter.concat("( o == '" + out(triple.getObject()) + "' )"); // first = false; // } // // if (filter != null) { // out.write(filter); // } // } // } catch (IOException e) { // e.printStackTrace(); // } // } // // private String out(Node node) { // return NodeEncoder.asString(node); // } // // } // Path: src/main/java/org/apache/jena/grande/examples/RunPigSparql2PigLatin.java import java.io.IOException; import java.io.StringWriter; import org.apache.jena.grande.pig.Sparql2PigLatinWriter; import com.hp.hpl.jena.query.Query; import com.hp.hpl.jena.query.QueryFactory; import com.hp.hpl.jena.sparql.algebra.Algebra; import com.hp.hpl.jena.sparql.algebra.Op; /* * 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.jena.grande.examples; public class RunPigSparql2PigLatin { public static void main(String[] args) throws IOException { Query query = QueryFactory.read("src/test/resources/query.rq"); // PrintUtils.printOp(IndentedWriter.stdout, query, true); Op op = Algebra.compile(query); StringWriter out = new StringWriter();
op.visit(new Sparql2PigLatinWriter(out));
castagna/jena-grande
src/main/java/org/apache/jena/grande/pig/NTriplesPigOutputFormat.java
// Path: src/main/java/org/apache/jena/grande/mapreduce/io/TripleRecordWriter.java // public class TripleRecordWriter extends RecordWriter<NullWritable, TripleWritable> { // // @Override // public void write(NullWritable key, TripleWritable value) throws IOException, InterruptedException { // // TODO Auto-generated method stub // } // // @Override // public void close(TaskAttemptContext context) throws IOException, InterruptedException { // // TODO Auto-generated method stub // } // // // } // // Path: src/main/java/org/apache/jena/grande/mapreduce/io/TripleWritable.java // public class TripleWritable extends BinaryComparable implements WritableComparable<BinaryComparable> { // // private Triple triple; // private byte[] bytes; // private int length; // // public TripleWritable(){ // this( new Triple(Node.ANY, Node.ANY, Node.ANY) ); // } // // public TripleWritable(Triple triple) { // this.triple = triple; // this.bytes = toBytes(triple); // this.length = bytes.length; // } // // @Override // public void readFields(DataInput in) throws IOException { // length = WritableUtils.readVInt(in); // bytes = new byte[length]; // in.readFully(bytes, 0, length); // Tokenizer tokenizer = TokenizerFactory.makeTokenizerASCII(new String(bytes)) ; // LangNTriples parser = new LangNTriples(tokenizer, RiotLib.profile(Lang.NTRIPLES, null), null) ; // triple = parser.next(); // } // // @Override // public void write(DataOutput out) throws IOException { // WritableUtils.writeVInt(out, length); // out.write(bytes, 0, length); // } // // @Override // public byte[] getBytes() { // return bytes; // } // // @Override // public int getLength() { // return length; // } // // public Triple getTriple() { // return triple; // } // // private byte[] toBytes(Triple triple) { // StringWriter out = new StringWriter(); // out.getBuffer().length(); // OutputLangUtils.output(out, triple, null, null); // try { // return out.toString().getBytes("UTF-8"); // } catch (UnsupportedEncodingException e) { // throw new JenaGrandeException(e); // } // } // // @Override // public String toString() { // return triple.toString(); // } // }
import java.io.IOException; import org.apache.hadoop.io.NullWritable; import org.apache.hadoop.mapreduce.RecordWriter; import org.apache.hadoop.mapreduce.TaskAttemptContext; import org.apache.hadoop.mapreduce.lib.output.FileOutputFormat; import org.apache.jena.grande.mapreduce.io.TripleRecordWriter; import org.apache.jena.grande.mapreduce.io.TripleWritable; import org.slf4j.Logger; import org.slf4j.LoggerFactory;
/* * 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.jena.grande.pig; public class NTriplesPigOutputFormat extends FileOutputFormat<NullWritable, TripleWritable> { private static final Logger log = LoggerFactory.getLogger(NTriplesPigOutputFormat.class); @Override public RecordWriter<NullWritable, TripleWritable> getRecordWriter(TaskAttemptContext context) throws IOException, InterruptedException {
// Path: src/main/java/org/apache/jena/grande/mapreduce/io/TripleRecordWriter.java // public class TripleRecordWriter extends RecordWriter<NullWritable, TripleWritable> { // // @Override // public void write(NullWritable key, TripleWritable value) throws IOException, InterruptedException { // // TODO Auto-generated method stub // } // // @Override // public void close(TaskAttemptContext context) throws IOException, InterruptedException { // // TODO Auto-generated method stub // } // // // } // // Path: src/main/java/org/apache/jena/grande/mapreduce/io/TripleWritable.java // public class TripleWritable extends BinaryComparable implements WritableComparable<BinaryComparable> { // // private Triple triple; // private byte[] bytes; // private int length; // // public TripleWritable(){ // this( new Triple(Node.ANY, Node.ANY, Node.ANY) ); // } // // public TripleWritable(Triple triple) { // this.triple = triple; // this.bytes = toBytes(triple); // this.length = bytes.length; // } // // @Override // public void readFields(DataInput in) throws IOException { // length = WritableUtils.readVInt(in); // bytes = new byte[length]; // in.readFully(bytes, 0, length); // Tokenizer tokenizer = TokenizerFactory.makeTokenizerASCII(new String(bytes)) ; // LangNTriples parser = new LangNTriples(tokenizer, RiotLib.profile(Lang.NTRIPLES, null), null) ; // triple = parser.next(); // } // // @Override // public void write(DataOutput out) throws IOException { // WritableUtils.writeVInt(out, length); // out.write(bytes, 0, length); // } // // @Override // public byte[] getBytes() { // return bytes; // } // // @Override // public int getLength() { // return length; // } // // public Triple getTriple() { // return triple; // } // // private byte[] toBytes(Triple triple) { // StringWriter out = new StringWriter(); // out.getBuffer().length(); // OutputLangUtils.output(out, triple, null, null); // try { // return out.toString().getBytes("UTF-8"); // } catch (UnsupportedEncodingException e) { // throw new JenaGrandeException(e); // } // } // // @Override // public String toString() { // return triple.toString(); // } // } // Path: src/main/java/org/apache/jena/grande/pig/NTriplesPigOutputFormat.java import java.io.IOException; import org.apache.hadoop.io.NullWritable; import org.apache.hadoop.mapreduce.RecordWriter; import org.apache.hadoop.mapreduce.TaskAttemptContext; import org.apache.hadoop.mapreduce.lib.output.FileOutputFormat; import org.apache.jena.grande.mapreduce.io.TripleRecordWriter; import org.apache.jena.grande.mapreduce.io.TripleWritable; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /* * 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.jena.grande.pig; public class NTriplesPigOutputFormat extends FileOutputFormat<NullWritable, TripleWritable> { private static final Logger log = LoggerFactory.getLogger(NTriplesPigOutputFormat.class); @Override public RecordWriter<NullWritable, TripleWritable> getRecordWriter(TaskAttemptContext context) throws IOException, InterruptedException {
RecordWriter<NullWritable, TripleWritable> recordWriter = new TripleRecordWriter();
castagna/jena-grande
src/main/java/org/apache/jena/grande/pig/Sparql2PigLatinWriter.java
// Path: src/main/java/org/apache/jena/grande/NodeEncoder.java // public class NodeEncoder { // // private static final PrefixMap emptyPrefixMap = new PrefixMap(); // // public static String asString(Node node) { // StringWriter sw = new StringWriter() ; // NodeFmtLib.serialize(sw, node, null, emptyPrefixMap); // return sw.toString() ; // } // // public static String asString(Node node, PrefixMap prefixMap) { // StringWriter sw = new StringWriter() ; // NodeFmtLib.serialize(sw, node, null, prefixMap); // return sw.toString() ; // } // // public static Node asNode(String str) { // return NodeFactory.parseNode(str); // } // // }
import java.io.IOException; import java.io.OutputStream; import java.io.Writer; import java.util.List; import org.apache.jena.grande.NodeEncoder; import com.hp.hpl.jena.graph.Node; import com.hp.hpl.jena.graph.Triple; import com.hp.hpl.jena.sparql.algebra.OpVisitorBase; import com.hp.hpl.jena.sparql.algebra.op.OpBGP; import com.hp.hpl.jena.util.FileUtils;
if (!triple.getPredicate().isVariable()) { if ( first ) { filter = "FILTER dataset BY "; } else { filter = filter.concat(" AND ") ; } filter = filter.concat("( p == '" + out(triple.getPredicate()) + "' )"); first = false; } if (!triple.getObject().isVariable()) { if ( first ) { filter = "FILTER dataset BY "; } else { filter = filter.concat(" AND ") ; } filter = filter.concat("( o == '" + out(triple.getObject()) + "' )"); first = false; } if (filter != null) { out.write(filter); } } } catch (IOException e) { e.printStackTrace(); } } private String out(Node node) {
// Path: src/main/java/org/apache/jena/grande/NodeEncoder.java // public class NodeEncoder { // // private static final PrefixMap emptyPrefixMap = new PrefixMap(); // // public static String asString(Node node) { // StringWriter sw = new StringWriter() ; // NodeFmtLib.serialize(sw, node, null, emptyPrefixMap); // return sw.toString() ; // } // // public static String asString(Node node, PrefixMap prefixMap) { // StringWriter sw = new StringWriter() ; // NodeFmtLib.serialize(sw, node, null, prefixMap); // return sw.toString() ; // } // // public static Node asNode(String str) { // return NodeFactory.parseNode(str); // } // // } // Path: src/main/java/org/apache/jena/grande/pig/Sparql2PigLatinWriter.java import java.io.IOException; import java.io.OutputStream; import java.io.Writer; import java.util.List; import org.apache.jena.grande.NodeEncoder; import com.hp.hpl.jena.graph.Node; import com.hp.hpl.jena.graph.Triple; import com.hp.hpl.jena.sparql.algebra.OpVisitorBase; import com.hp.hpl.jena.sparql.algebra.op.OpBGP; import com.hp.hpl.jena.util.FileUtils; if (!triple.getPredicate().isVariable()) { if ( first ) { filter = "FILTER dataset BY "; } else { filter = filter.concat(" AND ") ; } filter = filter.concat("( p == '" + out(triple.getPredicate()) + "' )"); first = false; } if (!triple.getObject().isVariable()) { if ( first ) { filter = "FILTER dataset BY "; } else { filter = filter.concat(" AND ") ; } filter = filter.concat("( o == '" + out(triple.getObject()) + "' )"); first = false; } if (filter != null) { out.write(filter); } } } catch (IOException e) { e.printStackTrace(); } } private String out(Node node) {
return NodeEncoder.asString(node);
castagna/jena-grande
src/main/java/org/apache/jena/grande/mapreduce/io/QuadWritable.java
// Path: src/main/java/org/apache/jena/grande/JenaGrandeException.java // @SuppressWarnings("serial") // public class JenaGrandeException extends JenaException { // // public JenaGrandeException() { super() ; } // public JenaGrandeException(String msg) { super(msg) ; } // public JenaGrandeException(Throwable th) { super(th) ; } // public JenaGrandeException(String msg, Throwable th) { super(msg, th) ; } // // }
import org.openjena.riot.out.OutputLangUtils; import org.openjena.riot.system.RiotLib; import org.openjena.riot.tokens.Tokenizer; import org.openjena.riot.tokens.TokenizerFactory; import com.hp.hpl.jena.graph.Node; import com.hp.hpl.jena.sparql.core.Quad; import java.io.DataInput; import java.io.DataOutput; import java.io.IOException; import java.io.StringWriter; import java.io.UnsupportedEncodingException; import org.apache.hadoop.io.BinaryComparable; import org.apache.hadoop.io.WritableComparable; import org.apache.hadoop.io.WritableUtils; import org.apache.jena.grande.JenaGrandeException; import org.openjena.riot.Lang; import org.openjena.riot.lang.LangNQuads;
quad = parser.next(); } @Override public void write(DataOutput out) throws IOException { WritableUtils.writeVInt(out, length); out.write(bytes, 0, length); } @Override public byte[] getBytes() { return bytes; } @Override public int getLength() { return length; } public Quad getQuad() { return quad; } private byte[] toBytes(Quad quad) { StringWriter out = new StringWriter(); out.getBuffer().length(); OutputLangUtils.output(out, quad, null, null); try { return out.toString().getBytes("UTF-8"); } catch (UnsupportedEncodingException e) {
// Path: src/main/java/org/apache/jena/grande/JenaGrandeException.java // @SuppressWarnings("serial") // public class JenaGrandeException extends JenaException { // // public JenaGrandeException() { super() ; } // public JenaGrandeException(String msg) { super(msg) ; } // public JenaGrandeException(Throwable th) { super(th) ; } // public JenaGrandeException(String msg, Throwable th) { super(msg, th) ; } // // } // Path: src/main/java/org/apache/jena/grande/mapreduce/io/QuadWritable.java import org.openjena.riot.out.OutputLangUtils; import org.openjena.riot.system.RiotLib; import org.openjena.riot.tokens.Tokenizer; import org.openjena.riot.tokens.TokenizerFactory; import com.hp.hpl.jena.graph.Node; import com.hp.hpl.jena.sparql.core.Quad; import java.io.DataInput; import java.io.DataOutput; import java.io.IOException; import java.io.StringWriter; import java.io.UnsupportedEncodingException; import org.apache.hadoop.io.BinaryComparable; import org.apache.hadoop.io.WritableComparable; import org.apache.hadoop.io.WritableUtils; import org.apache.jena.grande.JenaGrandeException; import org.openjena.riot.Lang; import org.openjena.riot.lang.LangNQuads; quad = parser.next(); } @Override public void write(DataOutput out) throws IOException { WritableUtils.writeVInt(out, length); out.write(bytes, 0, length); } @Override public byte[] getBytes() { return bytes; } @Override public int getLength() { return length; } public Quad getQuad() { return quad; } private byte[] toBytes(Quad quad) { StringWriter out = new StringWriter(); out.getBuffer().length(); OutputLangUtils.output(out, quad, null, null); try { return out.toString().getBytes("UTF-8"); } catch (UnsupportedEncodingException e) {
throw new JenaGrandeException(e);
castagna/jena-grande
src/main/java/org/apache/jena/grande/mapreduce/io/TripleRecordReader.java
// Path: src/main/java/org/apache/jena/grande/Utils.java // public class Utils { // // public static ParserProfile createParserProfile(JobContext context, Path path) { // Prologue prologue = new Prologue(null, IRIResolver.createNoResolve()); // LabelToNode labelMapping = new MapReduceLabelToNode(context, path); // return new ParserProfileBase(prologue, ErrorHandlerFactory.errorHandlerStd, labelMapping); // } // // public static String toString(String[] args) { // StringBuffer sb = new StringBuffer(); // sb.append("{"); // for ( String arg : args ) sb.append(arg).append(", "); // if ( sb.length() > 2 ) sb.delete(sb.length()-2, sb.length()); // sb.append("}"); // return sb.toString(); // } // // public static void log(Job job, Logger log) throws ClassNotFoundException { // log.debug ("{} -> {} ({}, {}) -> {}#{} ({}, {}) -> {}", // new Object[]{ // job.getInputFormatClass().getSimpleName(), job.getMapperClass().getSimpleName(), job.getMapOutputKeyClass().getSimpleName(), job.getMapOutputValueClass().getSimpleName(), // job.getReducerClass().getSimpleName(), job.getNumReduceTasks(), job.getOutputKeyClass().getSimpleName(), job.getOutputValueClass().getSimpleName(), job.getOutputFormatClass().getSimpleName() // } // ); // Path[] inputs = FileInputFormat.getInputPaths(job); // Path output = FileOutputFormat.getOutputPath(job); // log.debug("input: {}", inputs[0]); // log.debug("output: {}", output); // } // // public static void setReducers(Job job, Configuration configuration, Logger log) { // boolean runLocal = configuration.getBoolean(Constants.OPTION_RUN_LOCAL, Constants.OPTION_RUN_LOCAL_DEFAULT); // int num_reducers = configuration.getInt(Constants.OPTION_NUM_REDUCERS, Constants.OPTION_NUM_REDUCERS_DEFAULT); // // // TODO: should we comment this out and let Hadoop decide the number of reducers? // if ( runLocal ) { // if (log != null) log.debug("Setting number of reducers to {}", 1); // job.setNumReduceTasks(1); // } else { // job.setNumReduceTasks(num_reducers); // if (log != null) log.debug("Setting number of reducers to {}", num_reducers); // } // } // // }
import java.io.IOException; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.apache.hadoop.conf.Configuration; import org.apache.hadoop.fs.FSDataInputStream; import org.apache.hadoop.fs.FileSystem; import org.apache.hadoop.fs.Path; import org.apache.hadoop.fs.Seekable; import org.apache.hadoop.io.LongWritable; import org.apache.hadoop.io.Text; import org.apache.hadoop.io.compress.CodecPool; import org.apache.hadoop.io.compress.CompressionCodec; import org.apache.hadoop.io.compress.CompressionCodecFactory; import org.apache.hadoop.io.compress.Decompressor; import org.apache.hadoop.mapreduce.InputSplit; import org.apache.hadoop.mapreduce.RecordReader; import org.apache.hadoop.mapreduce.TaskAttemptContext; import org.apache.hadoop.mapreduce.lib.input.FileSplit; import org.apache.hadoop.util.LineReader; import org.apache.jena.grande.Utils; import org.openjena.riot.lang.LangNTriples; import org.openjena.riot.system.ParserProfile; import org.openjena.riot.tokens.Tokenizer; import org.openjena.riot.tokens.TokenizerFactory;
/* * 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.jena.grande.mapreduce.io; public class TripleRecordReader extends RecordReader<LongWritable, TripleWritable> { private static final Log LOG = LogFactory.getLog(TripleRecordReader.class); public static final String MAX_LINE_LENGTH = "mapreduce.input.linerecordreader.line.maxlength"; private LongWritable key = null; private Text value = null; private TripleWritable triple = null; private long start; private long pos; private long end; private LineReader in; private FSDataInputStream fileIn; private Seekable filePosition; private ParserProfile profile; private int maxLineLength; // private Counter inputByteCounter; private CompressionCodecFactory compressionCodecs = null; private CompressionCodec codec; private Decompressor decompressor; // @SuppressWarnings({ "unchecked", "rawtypes" }) @Override public void initialize(InputSplit genericSplit, TaskAttemptContext context) throws IOException, InterruptedException { FileSplit split = (FileSplit) genericSplit; // RIOT configuration
// Path: src/main/java/org/apache/jena/grande/Utils.java // public class Utils { // // public static ParserProfile createParserProfile(JobContext context, Path path) { // Prologue prologue = new Prologue(null, IRIResolver.createNoResolve()); // LabelToNode labelMapping = new MapReduceLabelToNode(context, path); // return new ParserProfileBase(prologue, ErrorHandlerFactory.errorHandlerStd, labelMapping); // } // // public static String toString(String[] args) { // StringBuffer sb = new StringBuffer(); // sb.append("{"); // for ( String arg : args ) sb.append(arg).append(", "); // if ( sb.length() > 2 ) sb.delete(sb.length()-2, sb.length()); // sb.append("}"); // return sb.toString(); // } // // public static void log(Job job, Logger log) throws ClassNotFoundException { // log.debug ("{} -> {} ({}, {}) -> {}#{} ({}, {}) -> {}", // new Object[]{ // job.getInputFormatClass().getSimpleName(), job.getMapperClass().getSimpleName(), job.getMapOutputKeyClass().getSimpleName(), job.getMapOutputValueClass().getSimpleName(), // job.getReducerClass().getSimpleName(), job.getNumReduceTasks(), job.getOutputKeyClass().getSimpleName(), job.getOutputValueClass().getSimpleName(), job.getOutputFormatClass().getSimpleName() // } // ); // Path[] inputs = FileInputFormat.getInputPaths(job); // Path output = FileOutputFormat.getOutputPath(job); // log.debug("input: {}", inputs[0]); // log.debug("output: {}", output); // } // // public static void setReducers(Job job, Configuration configuration, Logger log) { // boolean runLocal = configuration.getBoolean(Constants.OPTION_RUN_LOCAL, Constants.OPTION_RUN_LOCAL_DEFAULT); // int num_reducers = configuration.getInt(Constants.OPTION_NUM_REDUCERS, Constants.OPTION_NUM_REDUCERS_DEFAULT); // // // TODO: should we comment this out and let Hadoop decide the number of reducers? // if ( runLocal ) { // if (log != null) log.debug("Setting number of reducers to {}", 1); // job.setNumReduceTasks(1); // } else { // job.setNumReduceTasks(num_reducers); // if (log != null) log.debug("Setting number of reducers to {}", num_reducers); // } // } // // } // Path: src/main/java/org/apache/jena/grande/mapreduce/io/TripleRecordReader.java import java.io.IOException; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.apache.hadoop.conf.Configuration; import org.apache.hadoop.fs.FSDataInputStream; import org.apache.hadoop.fs.FileSystem; import org.apache.hadoop.fs.Path; import org.apache.hadoop.fs.Seekable; import org.apache.hadoop.io.LongWritable; import org.apache.hadoop.io.Text; import org.apache.hadoop.io.compress.CodecPool; import org.apache.hadoop.io.compress.CompressionCodec; import org.apache.hadoop.io.compress.CompressionCodecFactory; import org.apache.hadoop.io.compress.Decompressor; import org.apache.hadoop.mapreduce.InputSplit; import org.apache.hadoop.mapreduce.RecordReader; import org.apache.hadoop.mapreduce.TaskAttemptContext; import org.apache.hadoop.mapreduce.lib.input.FileSplit; import org.apache.hadoop.util.LineReader; import org.apache.jena.grande.Utils; import org.openjena.riot.lang.LangNTriples; import org.openjena.riot.system.ParserProfile; import org.openjena.riot.tokens.Tokenizer; import org.openjena.riot.tokens.TokenizerFactory; /* * 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.jena.grande.mapreduce.io; public class TripleRecordReader extends RecordReader<LongWritable, TripleWritable> { private static final Log LOG = LogFactory.getLog(TripleRecordReader.class); public static final String MAX_LINE_LENGTH = "mapreduce.input.linerecordreader.line.maxlength"; private LongWritable key = null; private Text value = null; private TripleWritable triple = null; private long start; private long pos; private long end; private LineReader in; private FSDataInputStream fileIn; private Seekable filePosition; private ParserProfile profile; private int maxLineLength; // private Counter inputByteCounter; private CompressionCodecFactory compressionCodecs = null; private CompressionCodec codec; private Decompressor decompressor; // @SuppressWarnings({ "unchecked", "rawtypes" }) @Override public void initialize(InputSplit genericSplit, TaskAttemptContext context) throws IOException, InterruptedException { FileSplit split = (FileSplit) genericSplit; // RIOT configuration
profile = Utils.createParserProfile(context, split.getPath());
castagna/jena-grande
src/test/java/org/apache/jena/grande/mapreduce/TestRdf2AdjacencyList.java
// Path: src/main/java/org/apache/jena/grande/Constants.java // public class Constants { // // public static final String RUN_ID = "runId"; // // public static final String OPTION_USE_COMPRESSION = "useCompression"; // public static final boolean OPTION_USE_COMPRESSION_DEFAULT = false; // // public static final String OPTION_OVERWRITE_OUTPUT = "overwriteOutput"; // public static final boolean OPTION_OVERWRITE_OUTPUT_DEFAULT = false; // // public static final String OPTION_RUN_LOCAL = "runLocal"; // public static final boolean OPTION_RUN_LOCAL_DEFAULT = false; // // public static final String OPTION_NUM_REDUCERS = "numReducers"; // public static final int OPTION_NUM_REDUCERS_DEFAULT = 20; // // public static final String RDF_2_ADJACENCY_LIST = "rdf2adjacencylist"; // // // public static final PrefixMap defaultPrefixMap = new PrefixMap(); // static { // defaultPrefixMap.add("rdf", RDF.getURI()); // defaultPrefixMap.add("rdfs", RDFS.getURI()); // defaultPrefixMap.add("owl", OWL.getURI()); // defaultPrefixMap.add("xsd", XSD.getURI()); // defaultPrefixMap.add("foaf", FOAF.getURI()); // defaultPrefixMap.add("dc", DC.getURI()); // defaultPrefixMap.add("dcterms", DCTerms.getURI()); // defaultPrefixMap.add("dctypes", DCTypes.getURI()); // } // // // MapReduce counters // // public static final String JENA_GRANDE_COUNTER_GROUPNAME = "TDBLoader4 Counters"; // public static final String JENA_GRANDE_COUNTER_MALFORMED = "Malformed"; // public static final String JENA_GRANDE_COUNTER_QUADS = "Quads (including duplicates)"; // public static final String JENA_GRANDE_COUNTER_TRIPLES = "Triples (including duplicates)"; // public static final String JENA_GRANDE_COUNTER_DUPLICATES = "Duplicates (quads or triples)"; // public static final String JENA_GRANDE_COUNTER_RDFNODES = "RDF nodes"; // public static final String JENA_GRANDE_COUNTER_RECORDS = "Index records"; // // // Event types // // public static EventType eventQuad = new EventType("quad"); // public static EventType eventTriple = new EventType("triple"); // public static EventType eventDuplicate = new EventType("duplicate"); // public static EventType eventMalformed = new EventType("malformed"); // public static EventType eventRdfNode = new EventType("RDF node"); // public static EventType eventRecord = new EventType("record"); // public static EventType eventTick = new EventType("tick"); // // } // // Path: src/main/java/cmd/rdf2adjacencylist.java // public class rdf2adjacencylist extends Configured implements Tool { // // @Override // public int run(String[] args) throws Exception { // if ( args.length != 2 ) { // System.err.printf("Usage: %s [generic options] <input> <output>\n", getClass().getName()); // ToolRunner.printGenericCommandUsage(System.err); // return -1; // } // // Configuration configuration = getConf(); // boolean overrideOutput = configuration.getBoolean(Constants.OPTION_OVERWRITE_OUTPUT, Constants.OPTION_OVERWRITE_OUTPUT_DEFAULT); // // FileSystem fs = FileSystem.get(new Path(args[1]).toUri(), configuration); // if ( overrideOutput ) { // fs.delete(new Path(args[1]), true); // } // // Tool tool = new Rdf2AdjacencyListDriver(configuration); // tool.run(new String[] { args[0], args[1] }); // // return 0; // } // // public static void main(String[] args) throws Exception { // int exitCode = ToolRunner.run(new rdf2adjacencylist(), args); // System.exit(exitCode); // } // // }
import com.hp.hpl.jena.graph.Graph; import com.hp.hpl.jena.rdf.model.Model; import com.hp.hpl.jena.rdf.model.ModelFactory; import com.hp.hpl.jena.util.FileManager; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertTrue; import org.apache.hadoop.util.ToolRunner; import org.apache.jena.grande.Constants; import org.junit.Test; import org.openjena.atlas.io.IO; import org.openjena.riot.Lang; import org.openjena.riot.RiotLoader; import cmd.rdf2adjacencylist;
/* * 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.jena.grande.mapreduce; public class TestRdf2AdjacencyList { private static String output = "target/output" ; @Test public void test() throws Exception { String input = "src/test/resources/data2.nt" ; String[] args = new String[] {
// Path: src/main/java/org/apache/jena/grande/Constants.java // public class Constants { // // public static final String RUN_ID = "runId"; // // public static final String OPTION_USE_COMPRESSION = "useCompression"; // public static final boolean OPTION_USE_COMPRESSION_DEFAULT = false; // // public static final String OPTION_OVERWRITE_OUTPUT = "overwriteOutput"; // public static final boolean OPTION_OVERWRITE_OUTPUT_DEFAULT = false; // // public static final String OPTION_RUN_LOCAL = "runLocal"; // public static final boolean OPTION_RUN_LOCAL_DEFAULT = false; // // public static final String OPTION_NUM_REDUCERS = "numReducers"; // public static final int OPTION_NUM_REDUCERS_DEFAULT = 20; // // public static final String RDF_2_ADJACENCY_LIST = "rdf2adjacencylist"; // // // public static final PrefixMap defaultPrefixMap = new PrefixMap(); // static { // defaultPrefixMap.add("rdf", RDF.getURI()); // defaultPrefixMap.add("rdfs", RDFS.getURI()); // defaultPrefixMap.add("owl", OWL.getURI()); // defaultPrefixMap.add("xsd", XSD.getURI()); // defaultPrefixMap.add("foaf", FOAF.getURI()); // defaultPrefixMap.add("dc", DC.getURI()); // defaultPrefixMap.add("dcterms", DCTerms.getURI()); // defaultPrefixMap.add("dctypes", DCTypes.getURI()); // } // // // MapReduce counters // // public static final String JENA_GRANDE_COUNTER_GROUPNAME = "TDBLoader4 Counters"; // public static final String JENA_GRANDE_COUNTER_MALFORMED = "Malformed"; // public static final String JENA_GRANDE_COUNTER_QUADS = "Quads (including duplicates)"; // public static final String JENA_GRANDE_COUNTER_TRIPLES = "Triples (including duplicates)"; // public static final String JENA_GRANDE_COUNTER_DUPLICATES = "Duplicates (quads or triples)"; // public static final String JENA_GRANDE_COUNTER_RDFNODES = "RDF nodes"; // public static final String JENA_GRANDE_COUNTER_RECORDS = "Index records"; // // // Event types // // public static EventType eventQuad = new EventType("quad"); // public static EventType eventTriple = new EventType("triple"); // public static EventType eventDuplicate = new EventType("duplicate"); // public static EventType eventMalformed = new EventType("malformed"); // public static EventType eventRdfNode = new EventType("RDF node"); // public static EventType eventRecord = new EventType("record"); // public static EventType eventTick = new EventType("tick"); // // } // // Path: src/main/java/cmd/rdf2adjacencylist.java // public class rdf2adjacencylist extends Configured implements Tool { // // @Override // public int run(String[] args) throws Exception { // if ( args.length != 2 ) { // System.err.printf("Usage: %s [generic options] <input> <output>\n", getClass().getName()); // ToolRunner.printGenericCommandUsage(System.err); // return -1; // } // // Configuration configuration = getConf(); // boolean overrideOutput = configuration.getBoolean(Constants.OPTION_OVERWRITE_OUTPUT, Constants.OPTION_OVERWRITE_OUTPUT_DEFAULT); // // FileSystem fs = FileSystem.get(new Path(args[1]).toUri(), configuration); // if ( overrideOutput ) { // fs.delete(new Path(args[1]), true); // } // // Tool tool = new Rdf2AdjacencyListDriver(configuration); // tool.run(new String[] { args[0], args[1] }); // // return 0; // } // // public static void main(String[] args) throws Exception { // int exitCode = ToolRunner.run(new rdf2adjacencylist(), args); // System.exit(exitCode); // } // // } // Path: src/test/java/org/apache/jena/grande/mapreduce/TestRdf2AdjacencyList.java import com.hp.hpl.jena.graph.Graph; import com.hp.hpl.jena.rdf.model.Model; import com.hp.hpl.jena.rdf.model.ModelFactory; import com.hp.hpl.jena.util.FileManager; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertTrue; import org.apache.hadoop.util.ToolRunner; import org.apache.jena.grande.Constants; import org.junit.Test; import org.openjena.atlas.io.IO; import org.openjena.riot.Lang; import org.openjena.riot.RiotLoader; import cmd.rdf2adjacencylist; /* * 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.jena.grande.mapreduce; public class TestRdf2AdjacencyList { private static String output = "target/output" ; @Test public void test() throws Exception { String input = "src/test/resources/data2.nt" ; String[] args = new String[] {
"-D", Constants.OPTION_OVERWRITE_OUTPUT + "=true",
castagna/jena-grande
src/test/java/org/apache/jena/grande/mapreduce/TestRdf2AdjacencyList.java
// Path: src/main/java/org/apache/jena/grande/Constants.java // public class Constants { // // public static final String RUN_ID = "runId"; // // public static final String OPTION_USE_COMPRESSION = "useCompression"; // public static final boolean OPTION_USE_COMPRESSION_DEFAULT = false; // // public static final String OPTION_OVERWRITE_OUTPUT = "overwriteOutput"; // public static final boolean OPTION_OVERWRITE_OUTPUT_DEFAULT = false; // // public static final String OPTION_RUN_LOCAL = "runLocal"; // public static final boolean OPTION_RUN_LOCAL_DEFAULT = false; // // public static final String OPTION_NUM_REDUCERS = "numReducers"; // public static final int OPTION_NUM_REDUCERS_DEFAULT = 20; // // public static final String RDF_2_ADJACENCY_LIST = "rdf2adjacencylist"; // // // public static final PrefixMap defaultPrefixMap = new PrefixMap(); // static { // defaultPrefixMap.add("rdf", RDF.getURI()); // defaultPrefixMap.add("rdfs", RDFS.getURI()); // defaultPrefixMap.add("owl", OWL.getURI()); // defaultPrefixMap.add("xsd", XSD.getURI()); // defaultPrefixMap.add("foaf", FOAF.getURI()); // defaultPrefixMap.add("dc", DC.getURI()); // defaultPrefixMap.add("dcterms", DCTerms.getURI()); // defaultPrefixMap.add("dctypes", DCTypes.getURI()); // } // // // MapReduce counters // // public static final String JENA_GRANDE_COUNTER_GROUPNAME = "TDBLoader4 Counters"; // public static final String JENA_GRANDE_COUNTER_MALFORMED = "Malformed"; // public static final String JENA_GRANDE_COUNTER_QUADS = "Quads (including duplicates)"; // public static final String JENA_GRANDE_COUNTER_TRIPLES = "Triples (including duplicates)"; // public static final String JENA_GRANDE_COUNTER_DUPLICATES = "Duplicates (quads or triples)"; // public static final String JENA_GRANDE_COUNTER_RDFNODES = "RDF nodes"; // public static final String JENA_GRANDE_COUNTER_RECORDS = "Index records"; // // // Event types // // public static EventType eventQuad = new EventType("quad"); // public static EventType eventTriple = new EventType("triple"); // public static EventType eventDuplicate = new EventType("duplicate"); // public static EventType eventMalformed = new EventType("malformed"); // public static EventType eventRdfNode = new EventType("RDF node"); // public static EventType eventRecord = new EventType("record"); // public static EventType eventTick = new EventType("tick"); // // } // // Path: src/main/java/cmd/rdf2adjacencylist.java // public class rdf2adjacencylist extends Configured implements Tool { // // @Override // public int run(String[] args) throws Exception { // if ( args.length != 2 ) { // System.err.printf("Usage: %s [generic options] <input> <output>\n", getClass().getName()); // ToolRunner.printGenericCommandUsage(System.err); // return -1; // } // // Configuration configuration = getConf(); // boolean overrideOutput = configuration.getBoolean(Constants.OPTION_OVERWRITE_OUTPUT, Constants.OPTION_OVERWRITE_OUTPUT_DEFAULT); // // FileSystem fs = FileSystem.get(new Path(args[1]).toUri(), configuration); // if ( overrideOutput ) { // fs.delete(new Path(args[1]), true); // } // // Tool tool = new Rdf2AdjacencyListDriver(configuration); // tool.run(new String[] { args[0], args[1] }); // // return 0; // } // // public static void main(String[] args) throws Exception { // int exitCode = ToolRunner.run(new rdf2adjacencylist(), args); // System.exit(exitCode); // } // // }
import com.hp.hpl.jena.graph.Graph; import com.hp.hpl.jena.rdf.model.Model; import com.hp.hpl.jena.rdf.model.ModelFactory; import com.hp.hpl.jena.util.FileManager; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertTrue; import org.apache.hadoop.util.ToolRunner; import org.apache.jena.grande.Constants; import org.junit.Test; import org.openjena.atlas.io.IO; import org.openjena.riot.Lang; import org.openjena.riot.RiotLoader; import cmd.rdf2adjacencylist;
/* * 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.jena.grande.mapreduce; public class TestRdf2AdjacencyList { private static String output = "target/output" ; @Test public void test() throws Exception { String input = "src/test/resources/data2.nt" ; String[] args = new String[] { "-D", Constants.OPTION_OVERWRITE_OUTPUT + "=true", "-D", Constants.OPTION_RUN_LOCAL + "=true", input, output };
// Path: src/main/java/org/apache/jena/grande/Constants.java // public class Constants { // // public static final String RUN_ID = "runId"; // // public static final String OPTION_USE_COMPRESSION = "useCompression"; // public static final boolean OPTION_USE_COMPRESSION_DEFAULT = false; // // public static final String OPTION_OVERWRITE_OUTPUT = "overwriteOutput"; // public static final boolean OPTION_OVERWRITE_OUTPUT_DEFAULT = false; // // public static final String OPTION_RUN_LOCAL = "runLocal"; // public static final boolean OPTION_RUN_LOCAL_DEFAULT = false; // // public static final String OPTION_NUM_REDUCERS = "numReducers"; // public static final int OPTION_NUM_REDUCERS_DEFAULT = 20; // // public static final String RDF_2_ADJACENCY_LIST = "rdf2adjacencylist"; // // // public static final PrefixMap defaultPrefixMap = new PrefixMap(); // static { // defaultPrefixMap.add("rdf", RDF.getURI()); // defaultPrefixMap.add("rdfs", RDFS.getURI()); // defaultPrefixMap.add("owl", OWL.getURI()); // defaultPrefixMap.add("xsd", XSD.getURI()); // defaultPrefixMap.add("foaf", FOAF.getURI()); // defaultPrefixMap.add("dc", DC.getURI()); // defaultPrefixMap.add("dcterms", DCTerms.getURI()); // defaultPrefixMap.add("dctypes", DCTypes.getURI()); // } // // // MapReduce counters // // public static final String JENA_GRANDE_COUNTER_GROUPNAME = "TDBLoader4 Counters"; // public static final String JENA_GRANDE_COUNTER_MALFORMED = "Malformed"; // public static final String JENA_GRANDE_COUNTER_QUADS = "Quads (including duplicates)"; // public static final String JENA_GRANDE_COUNTER_TRIPLES = "Triples (including duplicates)"; // public static final String JENA_GRANDE_COUNTER_DUPLICATES = "Duplicates (quads or triples)"; // public static final String JENA_GRANDE_COUNTER_RDFNODES = "RDF nodes"; // public static final String JENA_GRANDE_COUNTER_RECORDS = "Index records"; // // // Event types // // public static EventType eventQuad = new EventType("quad"); // public static EventType eventTriple = new EventType("triple"); // public static EventType eventDuplicate = new EventType("duplicate"); // public static EventType eventMalformed = new EventType("malformed"); // public static EventType eventRdfNode = new EventType("RDF node"); // public static EventType eventRecord = new EventType("record"); // public static EventType eventTick = new EventType("tick"); // // } // // Path: src/main/java/cmd/rdf2adjacencylist.java // public class rdf2adjacencylist extends Configured implements Tool { // // @Override // public int run(String[] args) throws Exception { // if ( args.length != 2 ) { // System.err.printf("Usage: %s [generic options] <input> <output>\n", getClass().getName()); // ToolRunner.printGenericCommandUsage(System.err); // return -1; // } // // Configuration configuration = getConf(); // boolean overrideOutput = configuration.getBoolean(Constants.OPTION_OVERWRITE_OUTPUT, Constants.OPTION_OVERWRITE_OUTPUT_DEFAULT); // // FileSystem fs = FileSystem.get(new Path(args[1]).toUri(), configuration); // if ( overrideOutput ) { // fs.delete(new Path(args[1]), true); // } // // Tool tool = new Rdf2AdjacencyListDriver(configuration); // tool.run(new String[] { args[0], args[1] }); // // return 0; // } // // public static void main(String[] args) throws Exception { // int exitCode = ToolRunner.run(new rdf2adjacencylist(), args); // System.exit(exitCode); // } // // } // Path: src/test/java/org/apache/jena/grande/mapreduce/TestRdf2AdjacencyList.java import com.hp.hpl.jena.graph.Graph; import com.hp.hpl.jena.rdf.model.Model; import com.hp.hpl.jena.rdf.model.ModelFactory; import com.hp.hpl.jena.util.FileManager; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertTrue; import org.apache.hadoop.util.ToolRunner; import org.apache.jena.grande.Constants; import org.junit.Test; import org.openjena.atlas.io.IO; import org.openjena.riot.Lang; import org.openjena.riot.RiotLoader; import cmd.rdf2adjacencylist; /* * 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.jena.grande.mapreduce; public class TestRdf2AdjacencyList { private static String output = "target/output" ; @Test public void test() throws Exception { String input = "src/test/resources/data2.nt" ; String[] args = new String[] { "-D", Constants.OPTION_OVERWRITE_OUTPUT + "=true", "-D", Constants.OPTION_RUN_LOCAL + "=true", input, output };
assertEquals ( 0, ToolRunner.run(new rdf2adjacencylist(), args) );
castagna/jena-grande
src/main/java/org/apache/jena/grande/mapreduce/io/QuadRecordReader.java
// Path: src/main/java/org/apache/jena/grande/Utils.java // public class Utils { // // public static ParserProfile createParserProfile(JobContext context, Path path) { // Prologue prologue = new Prologue(null, IRIResolver.createNoResolve()); // LabelToNode labelMapping = new MapReduceLabelToNode(context, path); // return new ParserProfileBase(prologue, ErrorHandlerFactory.errorHandlerStd, labelMapping); // } // // public static String toString(String[] args) { // StringBuffer sb = new StringBuffer(); // sb.append("{"); // for ( String arg : args ) sb.append(arg).append(", "); // if ( sb.length() > 2 ) sb.delete(sb.length()-2, sb.length()); // sb.append("}"); // return sb.toString(); // } // // public static void log(Job job, Logger log) throws ClassNotFoundException { // log.debug ("{} -> {} ({}, {}) -> {}#{} ({}, {}) -> {}", // new Object[]{ // job.getInputFormatClass().getSimpleName(), job.getMapperClass().getSimpleName(), job.getMapOutputKeyClass().getSimpleName(), job.getMapOutputValueClass().getSimpleName(), // job.getReducerClass().getSimpleName(), job.getNumReduceTasks(), job.getOutputKeyClass().getSimpleName(), job.getOutputValueClass().getSimpleName(), job.getOutputFormatClass().getSimpleName() // } // ); // Path[] inputs = FileInputFormat.getInputPaths(job); // Path output = FileOutputFormat.getOutputPath(job); // log.debug("input: {}", inputs[0]); // log.debug("output: {}", output); // } // // public static void setReducers(Job job, Configuration configuration, Logger log) { // boolean runLocal = configuration.getBoolean(Constants.OPTION_RUN_LOCAL, Constants.OPTION_RUN_LOCAL_DEFAULT); // int num_reducers = configuration.getInt(Constants.OPTION_NUM_REDUCERS, Constants.OPTION_NUM_REDUCERS_DEFAULT); // // // TODO: should we comment this out and let Hadoop decide the number of reducers? // if ( runLocal ) { // if (log != null) log.debug("Setting number of reducers to {}", 1); // job.setNumReduceTasks(1); // } else { // job.setNumReduceTasks(num_reducers); // if (log != null) log.debug("Setting number of reducers to {}", num_reducers); // } // } // // }
import java.io.IOException; import org.apache.hadoop.conf.Configuration; import org.apache.hadoop.fs.FSDataInputStream; import org.apache.hadoop.fs.FileSystem; import org.apache.hadoop.fs.Path; import org.apache.hadoop.io.LongWritable; import org.apache.hadoop.io.Text; import org.apache.hadoop.io.compress.CompressionCodec; import org.apache.hadoop.io.compress.CompressionCodecFactory; import org.apache.hadoop.mapreduce.InputSplit; import org.apache.hadoop.mapreduce.RecordReader; import org.apache.hadoop.mapreduce.TaskAttemptContext; import org.apache.hadoop.mapreduce.lib.input.FileSplit; import org.apache.hadoop.util.LineReader; import org.apache.jena.grande.Utils; import org.openjena.riot.lang.LangNQuads; import org.openjena.riot.system.ParserProfile; import org.openjena.riot.tokens.Tokenizer; import org.openjena.riot.tokens.TokenizerFactory; import org.slf4j.Logger; import org.slf4j.LoggerFactory;
/* * 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.jena.grande.mapreduce.io; public class QuadRecordReader extends RecordReader<LongWritable, QuadWritable> { private static final Logger log = LoggerFactory.getLogger(QuadRecordReader.class); public static final String MAX_LINE_LENGTH = "mapreduce.input.linerecordreader.line.maxlength"; private CompressionCodecFactory compressionCodecs = null; private long start; private long pos; private long end; private LineReader in; private int maxLineLength; private LongWritable key = null; private Text value = null; private QuadWritable quad = null; private ParserProfile profile = null; @Override public void initialize(InputSplit genericSplit, TaskAttemptContext context) throws IOException, InterruptedException { log.debug("initialize({}, {})", genericSplit, context); FileSplit split = (FileSplit) genericSplit;
// Path: src/main/java/org/apache/jena/grande/Utils.java // public class Utils { // // public static ParserProfile createParserProfile(JobContext context, Path path) { // Prologue prologue = new Prologue(null, IRIResolver.createNoResolve()); // LabelToNode labelMapping = new MapReduceLabelToNode(context, path); // return new ParserProfileBase(prologue, ErrorHandlerFactory.errorHandlerStd, labelMapping); // } // // public static String toString(String[] args) { // StringBuffer sb = new StringBuffer(); // sb.append("{"); // for ( String arg : args ) sb.append(arg).append(", "); // if ( sb.length() > 2 ) sb.delete(sb.length()-2, sb.length()); // sb.append("}"); // return sb.toString(); // } // // public static void log(Job job, Logger log) throws ClassNotFoundException { // log.debug ("{} -> {} ({}, {}) -> {}#{} ({}, {}) -> {}", // new Object[]{ // job.getInputFormatClass().getSimpleName(), job.getMapperClass().getSimpleName(), job.getMapOutputKeyClass().getSimpleName(), job.getMapOutputValueClass().getSimpleName(), // job.getReducerClass().getSimpleName(), job.getNumReduceTasks(), job.getOutputKeyClass().getSimpleName(), job.getOutputValueClass().getSimpleName(), job.getOutputFormatClass().getSimpleName() // } // ); // Path[] inputs = FileInputFormat.getInputPaths(job); // Path output = FileOutputFormat.getOutputPath(job); // log.debug("input: {}", inputs[0]); // log.debug("output: {}", output); // } // // public static void setReducers(Job job, Configuration configuration, Logger log) { // boolean runLocal = configuration.getBoolean(Constants.OPTION_RUN_LOCAL, Constants.OPTION_RUN_LOCAL_DEFAULT); // int num_reducers = configuration.getInt(Constants.OPTION_NUM_REDUCERS, Constants.OPTION_NUM_REDUCERS_DEFAULT); // // // TODO: should we comment this out and let Hadoop decide the number of reducers? // if ( runLocal ) { // if (log != null) log.debug("Setting number of reducers to {}", 1); // job.setNumReduceTasks(1); // } else { // job.setNumReduceTasks(num_reducers); // if (log != null) log.debug("Setting number of reducers to {}", num_reducers); // } // } // // } // Path: src/main/java/org/apache/jena/grande/mapreduce/io/QuadRecordReader.java import java.io.IOException; import org.apache.hadoop.conf.Configuration; import org.apache.hadoop.fs.FSDataInputStream; import org.apache.hadoop.fs.FileSystem; import org.apache.hadoop.fs.Path; import org.apache.hadoop.io.LongWritable; import org.apache.hadoop.io.Text; import org.apache.hadoop.io.compress.CompressionCodec; import org.apache.hadoop.io.compress.CompressionCodecFactory; import org.apache.hadoop.mapreduce.InputSplit; import org.apache.hadoop.mapreduce.RecordReader; import org.apache.hadoop.mapreduce.TaskAttemptContext; import org.apache.hadoop.mapreduce.lib.input.FileSplit; import org.apache.hadoop.util.LineReader; import org.apache.jena.grande.Utils; import org.openjena.riot.lang.LangNQuads; import org.openjena.riot.system.ParserProfile; import org.openjena.riot.tokens.Tokenizer; import org.openjena.riot.tokens.TokenizerFactory; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /* * 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.jena.grande.mapreduce.io; public class QuadRecordReader extends RecordReader<LongWritable, QuadWritable> { private static final Logger log = LoggerFactory.getLogger(QuadRecordReader.class); public static final String MAX_LINE_LENGTH = "mapreduce.input.linerecordreader.line.maxlength"; private CompressionCodecFactory compressionCodecs = null; private long start; private long pos; private long end; private LineReader in; private int maxLineLength; private LongWritable key = null; private Text value = null; private QuadWritable quad = null; private ParserProfile profile = null; @Override public void initialize(InputSplit genericSplit, TaskAttemptContext context) throws IOException, InterruptedException { log.debug("initialize({}, {})", genericSplit, context); FileSplit split = (FileSplit) genericSplit;
profile = Utils.createParserProfile(context, split.getPath()); // RIOT configuration
castagna/jena-grande
src/main/java/org/apache/jena/grande/hbase/HBaseQuadSink.java
// Path: src/main/java/org/apache/jena/grande/NodeEncoder.java // public class NodeEncoder { // // private static final PrefixMap emptyPrefixMap = new PrefixMap(); // // public static String asString(Node node) { // StringWriter sw = new StringWriter() ; // NodeFmtLib.serialize(sw, node, null, emptyPrefixMap); // return sw.toString() ; // } // // public static String asString(Node node, PrefixMap prefixMap) { // StringWriter sw = new StringWriter() ; // NodeFmtLib.serialize(sw, node, null, prefixMap); // return sw.toString() ; // } // // public static Node asNode(String str) { // return NodeFactory.parseNode(str); // } // // }
import java.io.IOException; import org.apache.hadoop.hbase.client.HTable; import org.apache.hadoop.hbase.client.Put; import org.apache.hadoop.hbase.util.Bytes; import org.apache.jena.grande.NodeEncoder; import org.openjena.atlas.lib.Sink; import org.openjena.atlas.logging.ProgressLogger; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import com.hp.hpl.jena.sparql.core.Quad;
/* * 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.jena.grande.hbase; public class HBaseQuadSink implements Sink<Quad> { private static final Logger log = LoggerFactory.getLogger( HBaseQuadSink.class ); // private static final byte[] family = Bytes.toBytes("SPOG"); private static final byte[] p = Bytes.toBytes("P"); private static final byte[] o = Bytes.toBytes("O"); private static final byte[] g = Bytes.toBytes("G"); private HTable table; private ProgressLogger logger = new ProgressLogger(log, "quads", 1000, 100000); private boolean started = false; public HBaseQuadSink ( HTable table ) { this.table = table; this.table.setAutoFlush(false); // table.getTableDescriptor().hasFamily(familyName); // table.getTableDescriptor().getFamily(new byte[]{}); // table.getTableDescriptor().get } @Override public void send ( Quad quad ) {
// Path: src/main/java/org/apache/jena/grande/NodeEncoder.java // public class NodeEncoder { // // private static final PrefixMap emptyPrefixMap = new PrefixMap(); // // public static String asString(Node node) { // StringWriter sw = new StringWriter() ; // NodeFmtLib.serialize(sw, node, null, emptyPrefixMap); // return sw.toString() ; // } // // public static String asString(Node node, PrefixMap prefixMap) { // StringWriter sw = new StringWriter() ; // NodeFmtLib.serialize(sw, node, null, prefixMap); // return sw.toString() ; // } // // public static Node asNode(String str) { // return NodeFactory.parseNode(str); // } // // } // Path: src/main/java/org/apache/jena/grande/hbase/HBaseQuadSink.java import java.io.IOException; import org.apache.hadoop.hbase.client.HTable; import org.apache.hadoop.hbase.client.Put; import org.apache.hadoop.hbase.util.Bytes; import org.apache.jena.grande.NodeEncoder; import org.openjena.atlas.lib.Sink; import org.openjena.atlas.logging.ProgressLogger; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import com.hp.hpl.jena.sparql.core.Quad; /* * 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.jena.grande.hbase; public class HBaseQuadSink implements Sink<Quad> { private static final Logger log = LoggerFactory.getLogger( HBaseQuadSink.class ); // private static final byte[] family = Bytes.toBytes("SPOG"); private static final byte[] p = Bytes.toBytes("P"); private static final byte[] o = Bytes.toBytes("O"); private static final byte[] g = Bytes.toBytes("G"); private HTable table; private ProgressLogger logger = new ProgressLogger(log, "quads", 1000, 100000); private boolean started = false; public HBaseQuadSink ( HTable table ) { this.table = table; this.table.setAutoFlush(false); // table.getTableDescriptor().hasFamily(familyName); // table.getTableDescriptor().getFamily(new byte[]{}); // table.getTableDescriptor().get } @Override public void send ( Quad quad ) {
Put put = new Put(NodeEncoder.asString(quad.getSubject()).getBytes());
castagna/jena-grande
src/test/java/org/apache/jena/grande/giraph/pagerank/memory/JungPageRank.java
// Path: src/main/java/org/apache/jena/grande/MemoryUtil.java // public class MemoryUtil { // // private static final Logger LOG = LoggerFactory.getLogger(MemoryUtil.class); // // public static long getUsedMemory() { // System.gc() ; // System.gc() ; // System.gc() ; // // return ( Runtime.getRuntime().totalMemory() - Runtime.getRuntime().freeMemory() ) / ( 1024 * 1024 ) ; // } // // public static void printUsedMemory() { // LOG.debug (String.format("memory used is %d MB", getUsedMemory())) ; // } // // }
import org.apache.jena.grande.MemoryUtil; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import edu.uci.ics.jung.algorithms.scoring.PageRank; import edu.uci.ics.jung.graph.DirectedSparseGraph; import java.io.BufferedReader; import java.io.File; import java.io.FileInputStream; import java.io.IOException; import java.io.InputStreamReader; import java.util.HashMap; import java.util.HashSet; import java.util.Map; import java.util.StringTokenizer;
int edgeCnt = 0; String line; while ((line = in.readLine()) != null) { StringTokenizer st = new StringTokenizer(line); String source = null; if ( st.hasMoreTokens() ) { source = st.nextToken(); if (graph.addVertex(source)) LOG.debug(String.format("Added verted %s to the graph", source)); } HashSet<String> seen = new HashSet<String>() ; while ( st.hasMoreTokens() ) { String destination = st.nextToken(); if (graph.addVertex(destination)) // implicit dangling nodes LOG.debug(String.format("Added verted %s to the graph", destination)); if (!destination.equals(source)) { // no self-references if (!seen.contains(destination)) { // no duplicate links graph.addEdge(new Integer(edgeCnt++), source, destination); seen.add(destination) ; } } } } in.close(); LOG.debug(String.format("Loaded %d nodes and %d links in %d ms", graph.getVertexCount(), graph.getEdgeCount(), (System.currentTimeMillis()-start))); } public Map<String, Double> compute() throws IOException {
// Path: src/main/java/org/apache/jena/grande/MemoryUtil.java // public class MemoryUtil { // // private static final Logger LOG = LoggerFactory.getLogger(MemoryUtil.class); // // public static long getUsedMemory() { // System.gc() ; // System.gc() ; // System.gc() ; // // return ( Runtime.getRuntime().totalMemory() - Runtime.getRuntime().freeMemory() ) / ( 1024 * 1024 ) ; // } // // public static void printUsedMemory() { // LOG.debug (String.format("memory used is %d MB", getUsedMemory())) ; // } // // } // Path: src/test/java/org/apache/jena/grande/giraph/pagerank/memory/JungPageRank.java import org.apache.jena.grande.MemoryUtil; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import edu.uci.ics.jung.algorithms.scoring.PageRank; import edu.uci.ics.jung.graph.DirectedSparseGraph; import java.io.BufferedReader; import java.io.File; import java.io.FileInputStream; import java.io.IOException; import java.io.InputStreamReader; import java.util.HashMap; import java.util.HashSet; import java.util.Map; import java.util.StringTokenizer; int edgeCnt = 0; String line; while ((line = in.readLine()) != null) { StringTokenizer st = new StringTokenizer(line); String source = null; if ( st.hasMoreTokens() ) { source = st.nextToken(); if (graph.addVertex(source)) LOG.debug(String.format("Added verted %s to the graph", source)); } HashSet<String> seen = new HashSet<String>() ; while ( st.hasMoreTokens() ) { String destination = st.nextToken(); if (graph.addVertex(destination)) // implicit dangling nodes LOG.debug(String.format("Added verted %s to the graph", destination)); if (!destination.equals(source)) { // no self-references if (!seen.contains(destination)) { // no duplicate links graph.addEdge(new Integer(edgeCnt++), source, destination); seen.add(destination) ; } } } } in.close(); LOG.debug(String.format("Loaded %d nodes and %d links in %d ms", graph.getVertexCount(), graph.getEdgeCount(), (System.currentTimeMillis()-start))); } public Map<String, Double> compute() throws IOException {
MemoryUtil.printUsedMemory() ;
castagna/jena-grande
src/test/java/dev/RunGiraphSSSPS.java
// Path: src/main/java/org/apache/jena/grande/giraph/sssps/SingleSourceShortestPaths.java // public class SingleSourceShortestPaths extends EdgeListVertex<IntWritable, IntWritable, NullWritable, IntWritable> implements Tool { // // private static final Logger log = LoggerFactory.getLogger(SingleSourceShortestPaths.class); // // public static final String SOURCE_VERTEX = "giraph.example.source"; // public static final int SOURCE_VERTEX_DEFAULT = 3; // // // @Override // public int run(String[] args) throws Exception { // log.debug("run({})", Utils.toString(args)); // Preconditions.checkArgument(args.length == 4, "run: Must have 4 arguments <input path> <output path> <source vertex> <# of workers>"); // // Configuration configuration = getConf(); // boolean overrideOutput = configuration.getBoolean(Constants.OPTION_OVERWRITE_OUTPUT, Constants.OPTION_OVERWRITE_OUTPUT_DEFAULT); // FileSystem fs = FileSystem.get(new Path(args[1]).toUri(), configuration); // if ( overrideOutput ) { // fs.delete(new Path(args[1]), true); // } // // GiraphConfiguration giraphConfiguration = new GiraphConfiguration(getConf()); // giraphConfiguration.setVertexClass(getClass()); // giraphConfiguration.setVertexInputFormatClass(IntIntNullIntTextInputFormat.class); // giraphConfiguration.setVertexOutputFormatClass(IdWithValueTextOutputFormat.class); // giraphConfiguration.set(SOURCE_VERTEX, args[2]); // giraphConfiguration.setWorkerConfiguration(Integer.parseInt(args[3]), Integer.parseInt(args[3]), 100.0f); // // GiraphJob job = new GiraphJob(giraphConfiguration, getClass().getName()); // FileInputFormat.addInputPath(job.getInternalJob(), new Path(args[0])); // FileOutputFormat.setOutputPath(job.getInternalJob(), new Path(args[1])); // return job.run(true) ? 0 : -1; // } // // @Override // public void compute(Iterable<IntWritable> msgIterator) throws IOException { // log.debug("compute(...)::{}#{} ...", getId(), getSuperstep()); // if ( ( getSuperstep() == 0 ) || ( getSuperstep() == 1 ) ) { // setValue(new IntWritable(Integer.MAX_VALUE)); // } // int minDist = isSource() ? 0 : Integer.MAX_VALUE; // log.debug("compute(...)::{}#{}: min = {}, value = {}", new Object[]{getId(), getSuperstep(), minDist, getValue()}); // for ( IntWritable msg : msgIterator ) { // log.debug("compute(...)::{}#{}: <--[{}]-- from ?", new Object[]{getId(), getSuperstep(), msg}); // minDist = Math.min(minDist, msg.get()); // log.debug("compute(...)::{}#{}: min = {}", new Object[]{getId(), getSuperstep(), minDist}); // } // if (minDist < getValue().get()) { // setValue(new IntWritable(minDist)); // log.debug("compute(...)::{}#{}: value = {}", new Object[]{getId(), getSuperstep(), getValue()}); // for (Edge<IntWritable,NullWritable> edge : getEdges()) { // log.debug("compute(...)::{}#{}: {} --[{}]--> {}", new Object[]{getId(), getSuperstep(), getId(), minDist+1, edge.getTargetVertexId()}); // sendMessage(edge.getTargetVertexId(), new IntWritable(minDist + 1)); // } // } // voteToHalt(); // } // // private boolean isSource() { // boolean result = getId().get() == getConf().getInt(SOURCE_VERTEX, SOURCE_VERTEX_DEFAULT); // log.debug("isSource() --> {}", result); // return result; // } // // @Override // public void setConf(Configuration conf) { // super.setConf(new ImmutableClassesGiraphConfiguration<IntWritable, IntWritable, NullWritable, IntWritable>(conf)); // } // // public static void main(String[] args) throws Exception { // log.debug("main({})", Utils.toString(args)); // System.exit(ToolRunner.run(new SingleSourceShortestPaths(), args)); // } // // }
import java.util.HashMap; import org.apache.giraph.io.IdWithValueTextOutputFormat; import org.apache.giraph.io.IntIntNullIntTextInputFormat; import org.apache.giraph.utils.InternalVertexRunner; import org.apache.jena.grande.giraph.sssps.SingleSourceShortestPaths;
/* * 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 dev; public class RunGiraphSSSPS { public static final String[] data = new String[] { "1 2 5", "2 1 3 5", "3 2 4", "4 3 5 6", "5 1 2 4", "6 4", }; public static void main(String[] args) throws Exception { Iterable<String> results = InternalVertexRunner.run(
// Path: src/main/java/org/apache/jena/grande/giraph/sssps/SingleSourceShortestPaths.java // public class SingleSourceShortestPaths extends EdgeListVertex<IntWritable, IntWritable, NullWritable, IntWritable> implements Tool { // // private static final Logger log = LoggerFactory.getLogger(SingleSourceShortestPaths.class); // // public static final String SOURCE_VERTEX = "giraph.example.source"; // public static final int SOURCE_VERTEX_DEFAULT = 3; // // // @Override // public int run(String[] args) throws Exception { // log.debug("run({})", Utils.toString(args)); // Preconditions.checkArgument(args.length == 4, "run: Must have 4 arguments <input path> <output path> <source vertex> <# of workers>"); // // Configuration configuration = getConf(); // boolean overrideOutput = configuration.getBoolean(Constants.OPTION_OVERWRITE_OUTPUT, Constants.OPTION_OVERWRITE_OUTPUT_DEFAULT); // FileSystem fs = FileSystem.get(new Path(args[1]).toUri(), configuration); // if ( overrideOutput ) { // fs.delete(new Path(args[1]), true); // } // // GiraphConfiguration giraphConfiguration = new GiraphConfiguration(getConf()); // giraphConfiguration.setVertexClass(getClass()); // giraphConfiguration.setVertexInputFormatClass(IntIntNullIntTextInputFormat.class); // giraphConfiguration.setVertexOutputFormatClass(IdWithValueTextOutputFormat.class); // giraphConfiguration.set(SOURCE_VERTEX, args[2]); // giraphConfiguration.setWorkerConfiguration(Integer.parseInt(args[3]), Integer.parseInt(args[3]), 100.0f); // // GiraphJob job = new GiraphJob(giraphConfiguration, getClass().getName()); // FileInputFormat.addInputPath(job.getInternalJob(), new Path(args[0])); // FileOutputFormat.setOutputPath(job.getInternalJob(), new Path(args[1])); // return job.run(true) ? 0 : -1; // } // // @Override // public void compute(Iterable<IntWritable> msgIterator) throws IOException { // log.debug("compute(...)::{}#{} ...", getId(), getSuperstep()); // if ( ( getSuperstep() == 0 ) || ( getSuperstep() == 1 ) ) { // setValue(new IntWritable(Integer.MAX_VALUE)); // } // int minDist = isSource() ? 0 : Integer.MAX_VALUE; // log.debug("compute(...)::{}#{}: min = {}, value = {}", new Object[]{getId(), getSuperstep(), minDist, getValue()}); // for ( IntWritable msg : msgIterator ) { // log.debug("compute(...)::{}#{}: <--[{}]-- from ?", new Object[]{getId(), getSuperstep(), msg}); // minDist = Math.min(minDist, msg.get()); // log.debug("compute(...)::{}#{}: min = {}", new Object[]{getId(), getSuperstep(), minDist}); // } // if (minDist < getValue().get()) { // setValue(new IntWritable(minDist)); // log.debug("compute(...)::{}#{}: value = {}", new Object[]{getId(), getSuperstep(), getValue()}); // for (Edge<IntWritable,NullWritable> edge : getEdges()) { // log.debug("compute(...)::{}#{}: {} --[{}]--> {}", new Object[]{getId(), getSuperstep(), getId(), minDist+1, edge.getTargetVertexId()}); // sendMessage(edge.getTargetVertexId(), new IntWritable(minDist + 1)); // } // } // voteToHalt(); // } // // private boolean isSource() { // boolean result = getId().get() == getConf().getInt(SOURCE_VERTEX, SOURCE_VERTEX_DEFAULT); // log.debug("isSource() --> {}", result); // return result; // } // // @Override // public void setConf(Configuration conf) { // super.setConf(new ImmutableClassesGiraphConfiguration<IntWritable, IntWritable, NullWritable, IntWritable>(conf)); // } // // public static void main(String[] args) throws Exception { // log.debug("main({})", Utils.toString(args)); // System.exit(ToolRunner.run(new SingleSourceShortestPaths(), args)); // } // // } // Path: src/test/java/dev/RunGiraphSSSPS.java import java.util.HashMap; import org.apache.giraph.io.IdWithValueTextOutputFormat; import org.apache.giraph.io.IntIntNullIntTextInputFormat; import org.apache.giraph.utils.InternalVertexRunner; import org.apache.jena.grande.giraph.sssps.SingleSourceShortestPaths; /* * 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 dev; public class RunGiraphSSSPS { public static final String[] data = new String[] { "1 2 5", "2 1 3 5", "3 2 4", "4 3 5 6", "5 1 2 4", "6 4", }; public static void main(String[] args) throws Exception { Iterable<String> results = InternalVertexRunner.run(
SingleSourceShortestPaths.class,
lightblueseas/jcommons-lang
src/test/java/de/alpharogroup/lang/util/ManifestVersionTest.java
// Path: src/main/java/de/alpharogroup/lang/thread/ThreadDataBean.java // @Data // @NoArgsConstructor // @AllArgsConstructor // @Builder(toBuilder = true) // public class ThreadDataBean // { // public static ThreadDataBean of(final Thread thread) // { // return ThreadDataBean.builder().priority(thread.getPriority()).alive(thread.isAlive()) // .daemon(thread.isDaemon()).interrupted(thread.isInterrupted()) // .threadGroup(thread.getThreadGroup().getName()).name(thread.getName()).build(); // } // // private boolean alive; // private boolean daemon; // private boolean interrupted; // private String name; // private Integer priority; // // private String threadGroup; // }
import org.meanbean.test.BeanTester; import org.testng.annotations.Test; import de.alpharogroup.evaluate.object.api.ContractViolation; import de.alpharogroup.evaluate.object.checkers.EqualsHashCodeAndToStringCheck; import de.alpharogroup.evaluate.object.verifier.ContractVerifier; import de.alpharogroup.lang.thread.ThreadDataBean; import lombok.SneakyThrows; import static org.testng.AssertJUnit.assertEquals; import static org.testng.AssertJUnit.assertNotNull; import java.util.Optional; import java.util.jar.Attributes;
/** * The MIT License * * Copyright (C) 2015 Asterios Raptis * * 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 de.alpharogroup.lang.util; /** * The unit test class for the class {@link ManifestVersion}. */ public class ManifestVersionTest { /** * Test method for {@link ManifestVersion#equals(Object)} , {@link ManifestVersion#hashCode()} * and {@link ManifestVersion#toString()} */ @Test(enabled = true) @SneakyThrows public void testEqualsHashcodeAndToStringWithClassSilently() { Optional<ContractViolation> expected; Optional<ContractViolation> actual; actual = EqualsHashCodeAndToStringCheck.equalsHashcodeAndToString( ManifestVersionFactory.get(Object.class),
// Path: src/main/java/de/alpharogroup/lang/thread/ThreadDataBean.java // @Data // @NoArgsConstructor // @AllArgsConstructor // @Builder(toBuilder = true) // public class ThreadDataBean // { // public static ThreadDataBean of(final Thread thread) // { // return ThreadDataBean.builder().priority(thread.getPriority()).alive(thread.isAlive()) // .daemon(thread.isDaemon()).interrupted(thread.isInterrupted()) // .threadGroup(thread.getThreadGroup().getName()).name(thread.getName()).build(); // } // // private boolean alive; // private boolean daemon; // private boolean interrupted; // private String name; // private Integer priority; // // private String threadGroup; // } // Path: src/test/java/de/alpharogroup/lang/util/ManifestVersionTest.java import org.meanbean.test.BeanTester; import org.testng.annotations.Test; import de.alpharogroup.evaluate.object.api.ContractViolation; import de.alpharogroup.evaluate.object.checkers.EqualsHashCodeAndToStringCheck; import de.alpharogroup.evaluate.object.verifier.ContractVerifier; import de.alpharogroup.lang.thread.ThreadDataBean; import lombok.SneakyThrows; import static org.testng.AssertJUnit.assertEquals; import static org.testng.AssertJUnit.assertNotNull; import java.util.Optional; import java.util.jar.Attributes; /** * The MIT License * * Copyright (C) 2015 Asterios Raptis * * 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 de.alpharogroup.lang.util; /** * The unit test class for the class {@link ManifestVersion}. */ public class ManifestVersionTest { /** * Test method for {@link ManifestVersion#equals(Object)} , {@link ManifestVersion#hashCode()} * and {@link ManifestVersion#toString()} */ @Test(enabled = true) @SneakyThrows public void testEqualsHashcodeAndToStringWithClassSilently() { Optional<ContractViolation> expected; Optional<ContractViolation> actual; actual = EqualsHashCodeAndToStringCheck.equalsHashcodeAndToString( ManifestVersionFactory.get(Object.class),
ManifestVersionFactory.get(ThreadDataBean.class),
lightblueseas/jcommons-lang
src/test/java/de/alpharogroup/io/annotations/ImportResourcesExtensionsTest.java
// Path: src/test/java/de/alpharogroup/io/OtherPage.java // @ImportResource(index = 1, resourceName = "OtherPage.js", resourceType = "js") // public class OtherPage // { // }
import java.util.Map; import org.meanbean.factories.ObjectCreationException; import org.meanbean.test.BeanTestException; import org.meanbean.test.BeanTester; import org.testng.annotations.Test; import de.alpharogroup.io.OtherPage; import static org.testng.AssertJUnit.assertEquals; import static org.testng.AssertJUnit.assertNotNull; import static org.testng.AssertJUnit.assertTrue; import java.io.IOException; import java.net.URISyntaxException;
assertEquals(expected, actual); final ImportResource jsResource = somePageResources[1]; expectedIndex = 2; actualIndex = jsResource.index(); assertTrue(expectedIndex == actualIndex); expected = "TestPage.js"; actual = jsResource.resourceName(); assertEquals(expected, actual); expected = "js"; actual = jsResource.resourceType(); assertEquals(expected, actual); final ImportResource jsResource2 = somePageResources[2]; expectedIndex = 2; actualIndex = jsResource2.index(); assertTrue(expectedIndex == actualIndex); expected = "TestPanel.js"; actual = jsResource2.resourceName(); assertEquals(expected, actual); expected = "js"; actual = jsResource2.resourceType(); assertEquals(expected, actual);
// Path: src/test/java/de/alpharogroup/io/OtherPage.java // @ImportResource(index = 1, resourceName = "OtherPage.js", resourceType = "js") // public class OtherPage // { // } // Path: src/test/java/de/alpharogroup/io/annotations/ImportResourcesExtensionsTest.java import java.util.Map; import org.meanbean.factories.ObjectCreationException; import org.meanbean.test.BeanTestException; import org.meanbean.test.BeanTester; import org.testng.annotations.Test; import de.alpharogroup.io.OtherPage; import static org.testng.AssertJUnit.assertEquals; import static org.testng.AssertJUnit.assertNotNull; import static org.testng.AssertJUnit.assertTrue; import java.io.IOException; import java.net.URISyntaxException; assertEquals(expected, actual); final ImportResource jsResource = somePageResources[1]; expectedIndex = 2; actualIndex = jsResource.index(); assertTrue(expectedIndex == actualIndex); expected = "TestPage.js"; actual = jsResource.resourceName(); assertEquals(expected, actual); expected = "js"; actual = jsResource.resourceType(); assertEquals(expected, actual); final ImportResource jsResource2 = somePageResources[2]; expectedIndex = 2; actualIndex = jsResource2.index(); assertTrue(expectedIndex == actualIndex); expected = "TestPanel.js"; actual = jsResource2.resourceName(); assertEquals(expected, actual); expected = "js"; actual = jsResource2.resourceType(); assertEquals(expected, actual);
final ImportResource[] otherPageResources = resources.get(OtherPage.class);
LMAX-Exchange/angler
src/main/java/com/lmax/angler/monitoring/network/monitor/socket/udp/UdpStatsEntry.java
// Path: src/main/java/com/lmax/angler/monitoring/network/monitor/socket/SocketIdentifier.java // public final class SocketIdentifier // { // private SocketIdentifier() {} // // /** // * Pack IPv4 address and socket into a long. // * @param socketAddress the socket address // * @return the encoded value // */ // public static long fromInet4SocketAddress(final InetSocketAddress socketAddress) // { // validateAddressType(socketAddress); // final long ipAddressOctets = Integer.toUnsignedLong(socketAddress.getAddress().hashCode()); // final long port = socketAddress.getPort(); // return port << 32 | ipAddressOctets; // } // // /** // * Pack IPv4 address and match-all socket flag into a long. // * @param inetAddress the host address // * @return the encoded value // */ // public static long fromInet4Address(final InetAddress inetAddress) // { // ensureIsInet4Address(inetAddress); // // return Integer.toUnsignedLong(inetAddress.hashCode()); // } // // /** // * Pack IPv4 address and socket into a long. // * @param socketAddress the socket address // * @param inode the socket inode // * @return the encoded value // */ // public static long fromInet4SocketAddressAndInode(final InetSocketAddress socketAddress, final int inode) // { // return overlayInode(fromInet4SocketAddress(socketAddress), inode); // } // // /** // * Pack IPv4 address and match-all socket flag into a long. // * @param inetAddress the host address // * @param inode the socket inode // * @return the encoded value // */ // public static long fromInet4AddressAndInode(final InetAddress inetAddress, final int inode) // { // return overlayInode(fromInet4Address(inetAddress), inode); // } // // /** // * Is this socketIdentifier a match for all ports on the encoded IP address. // * @param socketIdentifier the encoded value // * @return whether this socketIdentifier matches all ports // */ // public static boolean isMatchAllSocketFlagSet(final long socketIdentifier) // { // return extractPortNumber(socketIdentifier) == 0L; // } // // /** // * Mast the port number out of this socket identifier. // * @param socketIdentifier the encoded value // * @return the socketIdentifier with the port number masked out // */ // public static long asMatchAllSocketsSocketIdentifier(final long socketIdentifier) // { // return 0xFFFF0000FFFFFFFFL & socketIdentifier; // } // // /** // * Pack a hex-encoded IPv4:port socket address into a long. // * @param decodedAddress 32-bit IPv4 address decoded from hex // * @param port the port number // * @return the encoded value // */ // public static long fromLinuxKernelHexEncodedAddressAndPort(final long decodedAddress, final long port) // { // return port << 32 | Long.reverseBytes(decodedAddress) >>> 32; // } // // /** // * Pack inode value into socketIdentifier to differentiate between difference sockets listening to the same port. // * @param socketIdentifier the socketIdentifier // * @param inode the inode // * @return the encoded value // */ // public static long overlayInode(final long socketIdentifier, final long inode) // { // return inode << 48 | socketIdentifier; // } // // /** // * Extract port number from a socketIdentifier. // * @param socketIdentifier the socketIdentifier // * @return the port number // */ // public static int extractPortNumber(final long socketIdentifier) // { // return (int) ((socketIdentifier >> 32) & 0xFFFFL); // } // // /** // * Generates a vaguely human-readable format for a given socket identifier. // * @param socketIdentifier the encoded socket identifier // * @return human-readable form // */ // public static String toDebugString(final long socketIdentifier) // { // final int ipBits = (int) socketIdentifier; // final int port = extractPortNumber(socketIdentifier); // final int inode = (int) (socketIdentifier >> 48); // // return Integer.toHexString(ipBits) + ":" + port + "/" + inode; // } // // private static void validateAddressType(final InetSocketAddress socketAddress) // { // ensureIsInet4Address(socketAddress.getAddress()); // } // // private static void ensureIsInet4Address(final InetAddress address) // { // if(!(address instanceof Inet4Address)) // { // throw new IllegalArgumentException("Due to the nature of some awful hacks, " + // "I only work with Inet4Address-based sockets, not: " + address.getClass().getSimpleName()); // } // } // }
import com.lmax.angler.monitoring.network.monitor.socket.SocketIdentifier;
package com.lmax.angler.monitoring.network.monitor.socket.udp; /** * Value object. */ final class UdpStatsEntry { private long socketIdentifier; private long receiveQueueDepth; private long transmitQueueDepth; private long drops; private long inode; long getSocketIdentifier() { return socketIdentifier; } long getSocketInstanceIndentifier() {
// Path: src/main/java/com/lmax/angler/monitoring/network/monitor/socket/SocketIdentifier.java // public final class SocketIdentifier // { // private SocketIdentifier() {} // // /** // * Pack IPv4 address and socket into a long. // * @param socketAddress the socket address // * @return the encoded value // */ // public static long fromInet4SocketAddress(final InetSocketAddress socketAddress) // { // validateAddressType(socketAddress); // final long ipAddressOctets = Integer.toUnsignedLong(socketAddress.getAddress().hashCode()); // final long port = socketAddress.getPort(); // return port << 32 | ipAddressOctets; // } // // /** // * Pack IPv4 address and match-all socket flag into a long. // * @param inetAddress the host address // * @return the encoded value // */ // public static long fromInet4Address(final InetAddress inetAddress) // { // ensureIsInet4Address(inetAddress); // // return Integer.toUnsignedLong(inetAddress.hashCode()); // } // // /** // * Pack IPv4 address and socket into a long. // * @param socketAddress the socket address // * @param inode the socket inode // * @return the encoded value // */ // public static long fromInet4SocketAddressAndInode(final InetSocketAddress socketAddress, final int inode) // { // return overlayInode(fromInet4SocketAddress(socketAddress), inode); // } // // /** // * Pack IPv4 address and match-all socket flag into a long. // * @param inetAddress the host address // * @param inode the socket inode // * @return the encoded value // */ // public static long fromInet4AddressAndInode(final InetAddress inetAddress, final int inode) // { // return overlayInode(fromInet4Address(inetAddress), inode); // } // // /** // * Is this socketIdentifier a match for all ports on the encoded IP address. // * @param socketIdentifier the encoded value // * @return whether this socketIdentifier matches all ports // */ // public static boolean isMatchAllSocketFlagSet(final long socketIdentifier) // { // return extractPortNumber(socketIdentifier) == 0L; // } // // /** // * Mast the port number out of this socket identifier. // * @param socketIdentifier the encoded value // * @return the socketIdentifier with the port number masked out // */ // public static long asMatchAllSocketsSocketIdentifier(final long socketIdentifier) // { // return 0xFFFF0000FFFFFFFFL & socketIdentifier; // } // // /** // * Pack a hex-encoded IPv4:port socket address into a long. // * @param decodedAddress 32-bit IPv4 address decoded from hex // * @param port the port number // * @return the encoded value // */ // public static long fromLinuxKernelHexEncodedAddressAndPort(final long decodedAddress, final long port) // { // return port << 32 | Long.reverseBytes(decodedAddress) >>> 32; // } // // /** // * Pack inode value into socketIdentifier to differentiate between difference sockets listening to the same port. // * @param socketIdentifier the socketIdentifier // * @param inode the inode // * @return the encoded value // */ // public static long overlayInode(final long socketIdentifier, final long inode) // { // return inode << 48 | socketIdentifier; // } // // /** // * Extract port number from a socketIdentifier. // * @param socketIdentifier the socketIdentifier // * @return the port number // */ // public static int extractPortNumber(final long socketIdentifier) // { // return (int) ((socketIdentifier >> 32) & 0xFFFFL); // } // // /** // * Generates a vaguely human-readable format for a given socket identifier. // * @param socketIdentifier the encoded socket identifier // * @return human-readable form // */ // public static String toDebugString(final long socketIdentifier) // { // final int ipBits = (int) socketIdentifier; // final int port = extractPortNumber(socketIdentifier); // final int inode = (int) (socketIdentifier >> 48); // // return Integer.toHexString(ipBits) + ":" + port + "/" + inode; // } // // private static void validateAddressType(final InetSocketAddress socketAddress) // { // ensureIsInet4Address(socketAddress.getAddress()); // } // // private static void ensureIsInet4Address(final InetAddress address) // { // if(!(address instanceof Inet4Address)) // { // throw new IllegalArgumentException("Due to the nature of some awful hacks, " + // "I only work with Inet4Address-based sockets, not: " + address.getClass().getSimpleName()); // } // } // } // Path: src/main/java/com/lmax/angler/monitoring/network/monitor/socket/udp/UdpStatsEntry.java import com.lmax.angler.monitoring.network.monitor.socket.SocketIdentifier; package com.lmax.angler.monitoring.network.monitor.socket.udp; /** * Value object. */ final class UdpStatsEntry { private long socketIdentifier; private long receiveQueueDepth; private long transmitQueueDepth; private long drops; private long inode; long getSocketIdentifier() { return socketIdentifier; } long getSocketInstanceIndentifier() {
return SocketIdentifier.overlayInode(socketIdentifier, inode);
LMAX-Exchange/angler
src/test/java/com/lmax/angler/monitoring/network/monitor/system/snmp/SystemNetworkManagementMonitorTest.java
// Path: src/main/java/com/lmax/angler/monitoring/network/monitor/system/snmp/udp/SnmpUdpStatisticsHandler.java // @FunctionalInterface // public interface SnmpUdpStatisticsHandler // { // /** // * Callback method. // * @param inErrors InErrors count // * @param receiveBufferErrors RecvbufErrors count // * @param inChecksumErrors InCsumErrors count // */ // void onStatisticsUpdated(final long inErrors, final long receiveBufferErrors, final long inChecksumErrors); // } // // Path: src/test/java/com/lmax/angler/monitoring/network/monitor/ResourceUtil.java // public static void writeDataFile(final String resourceName, final Path sourcePath) throws IOException, URISyntaxException // { // copy(Paths.get(currentThread().getContextClassLoader().getResource(resourceName).toURI()), // new FileOutputStream(sourcePath.toFile(), false)); // }
import com.lmax.angler.monitoring.network.monitor.system.snmp.udp.SnmpUdpStatisticsHandler; import org.junit.After; import org.junit.Before; import org.junit.Test; import java.nio.file.Files; import java.nio.file.Path; import java.util.ArrayList; import java.util.List; import static com.lmax.angler.monitoring.network.monitor.ResourceUtil.writeDataFile; import static org.hamcrest.CoreMatchers.is; import static org.junit.Assert.assertThat;
package com.lmax.angler.monitoring.network.monitor.system.snmp; public class SystemNetworkManagementMonitorTest { private final RecordingSnmpUdpStatisticsHandler statsHandler = new RecordingSnmpUdpStatisticsHandler(); private Path inputPath; private SystemNetworkManagementMonitor monitor; @Before public void before() throws Exception { inputPath = Files.createTempFile("proc-net-snmp", "txt");
// Path: src/main/java/com/lmax/angler/monitoring/network/monitor/system/snmp/udp/SnmpUdpStatisticsHandler.java // @FunctionalInterface // public interface SnmpUdpStatisticsHandler // { // /** // * Callback method. // * @param inErrors InErrors count // * @param receiveBufferErrors RecvbufErrors count // * @param inChecksumErrors InCsumErrors count // */ // void onStatisticsUpdated(final long inErrors, final long receiveBufferErrors, final long inChecksumErrors); // } // // Path: src/test/java/com/lmax/angler/monitoring/network/monitor/ResourceUtil.java // public static void writeDataFile(final String resourceName, final Path sourcePath) throws IOException, URISyntaxException // { // copy(Paths.get(currentThread().getContextClassLoader().getResource(resourceName).toURI()), // new FileOutputStream(sourcePath.toFile(), false)); // } // Path: src/test/java/com/lmax/angler/monitoring/network/monitor/system/snmp/SystemNetworkManagementMonitorTest.java import com.lmax.angler.monitoring.network.monitor.system.snmp.udp.SnmpUdpStatisticsHandler; import org.junit.After; import org.junit.Before; import org.junit.Test; import java.nio.file.Files; import java.nio.file.Path; import java.util.ArrayList; import java.util.List; import static com.lmax.angler.monitoring.network.monitor.ResourceUtil.writeDataFile; import static org.hamcrest.CoreMatchers.is; import static org.junit.Assert.assertThat; package com.lmax.angler.monitoring.network.monitor.system.snmp; public class SystemNetworkManagementMonitorTest { private final RecordingSnmpUdpStatisticsHandler statsHandler = new RecordingSnmpUdpStatisticsHandler(); private Path inputPath; private SystemNetworkManagementMonitor monitor; @Before public void before() throws Exception { inputPath = Files.createTempFile("proc-net-snmp", "txt");
writeDataFile("proc_net_snmp_sample.txt", inputPath);
LMAX-Exchange/angler
src/test/java/com/lmax/angler/monitoring/network/monitor/system/snmp/SystemNetworkManagementMonitorTest.java
// Path: src/main/java/com/lmax/angler/monitoring/network/monitor/system/snmp/udp/SnmpUdpStatisticsHandler.java // @FunctionalInterface // public interface SnmpUdpStatisticsHandler // { // /** // * Callback method. // * @param inErrors InErrors count // * @param receiveBufferErrors RecvbufErrors count // * @param inChecksumErrors InCsumErrors count // */ // void onStatisticsUpdated(final long inErrors, final long receiveBufferErrors, final long inChecksumErrors); // } // // Path: src/test/java/com/lmax/angler/monitoring/network/monitor/ResourceUtil.java // public static void writeDataFile(final String resourceName, final Path sourcePath) throws IOException, URISyntaxException // { // copy(Paths.get(currentThread().getContextClassLoader().getResource(resourceName).toURI()), // new FileOutputStream(sourcePath.toFile(), false)); // }
import com.lmax.angler.monitoring.network.monitor.system.snmp.udp.SnmpUdpStatisticsHandler; import org.junit.After; import org.junit.Before; import org.junit.Test; import java.nio.file.Files; import java.nio.file.Path; import java.util.ArrayList; import java.util.List; import static com.lmax.angler.monitoring.network.monitor.ResourceUtil.writeDataFile; import static org.hamcrest.CoreMatchers.is; import static org.junit.Assert.assertThat;
writeDataFile("proc_net_snmp_sample.txt", inputPath); monitor = new SystemNetworkManagementMonitor(inputPath); } @After public void after() throws Exception { Files.deleteIfExists(inputPath); } @Test public void shouldParseDataAndNotifyListener() throws Exception { monitor.poll(statsHandler); assertThat(statsHandler.getRecorded().size(), is(1)); assertEntry(statsHandler.getRecorded().get(0), 78665L, 62374L, 37L); } private static void assertEntry( final SnmpUdpStatistic snmpUdpStatistic, final long inErrors, final long receiveBufferErrors, final long inChecksumErrors) { assertThat(snmpUdpStatistic.getInErrors(), is(inErrors)); assertThat(snmpUdpStatistic.getReceiveBufferErrors(), is(receiveBufferErrors)); assertThat(snmpUdpStatistic.getInChecksumErrors(), is(inChecksumErrors)); }
// Path: src/main/java/com/lmax/angler/monitoring/network/monitor/system/snmp/udp/SnmpUdpStatisticsHandler.java // @FunctionalInterface // public interface SnmpUdpStatisticsHandler // { // /** // * Callback method. // * @param inErrors InErrors count // * @param receiveBufferErrors RecvbufErrors count // * @param inChecksumErrors InCsumErrors count // */ // void onStatisticsUpdated(final long inErrors, final long receiveBufferErrors, final long inChecksumErrors); // } // // Path: src/test/java/com/lmax/angler/monitoring/network/monitor/ResourceUtil.java // public static void writeDataFile(final String resourceName, final Path sourcePath) throws IOException, URISyntaxException // { // copy(Paths.get(currentThread().getContextClassLoader().getResource(resourceName).toURI()), // new FileOutputStream(sourcePath.toFile(), false)); // } // Path: src/test/java/com/lmax/angler/monitoring/network/monitor/system/snmp/SystemNetworkManagementMonitorTest.java import com.lmax.angler.monitoring.network.monitor.system.snmp.udp.SnmpUdpStatisticsHandler; import org.junit.After; import org.junit.Before; import org.junit.Test; import java.nio.file.Files; import java.nio.file.Path; import java.util.ArrayList; import java.util.List; import static com.lmax.angler.monitoring.network.monitor.ResourceUtil.writeDataFile; import static org.hamcrest.CoreMatchers.is; import static org.junit.Assert.assertThat; writeDataFile("proc_net_snmp_sample.txt", inputPath); monitor = new SystemNetworkManagementMonitor(inputPath); } @After public void after() throws Exception { Files.deleteIfExists(inputPath); } @Test public void shouldParseDataAndNotifyListener() throws Exception { monitor.poll(statsHandler); assertThat(statsHandler.getRecorded().size(), is(1)); assertEntry(statsHandler.getRecorded().get(0), 78665L, 62374L, 37L); } private static void assertEntry( final SnmpUdpStatistic snmpUdpStatistic, final long inErrors, final long receiveBufferErrors, final long inChecksumErrors) { assertThat(snmpUdpStatistic.getInErrors(), is(inErrors)); assertThat(snmpUdpStatistic.getReceiveBufferErrors(), is(receiveBufferErrors)); assertThat(snmpUdpStatistic.getInChecksumErrors(), is(inChecksumErrors)); }
private static final class RecordingSnmpUdpStatisticsHandler implements SnmpUdpStatisticsHandler
LMAX-Exchange/angler
src/main/java/com/lmax/angler/monitoring/network/monitor/socket/tcp/TcpStatsEntry.java
// Path: src/main/java/com/lmax/angler/monitoring/network/monitor/socket/SocketIdentifier.java // public final class SocketIdentifier // { // private SocketIdentifier() {} // // /** // * Pack IPv4 address and socket into a long. // * @param socketAddress the socket address // * @return the encoded value // */ // public static long fromInet4SocketAddress(final InetSocketAddress socketAddress) // { // validateAddressType(socketAddress); // final long ipAddressOctets = Integer.toUnsignedLong(socketAddress.getAddress().hashCode()); // final long port = socketAddress.getPort(); // return port << 32 | ipAddressOctets; // } // // /** // * Pack IPv4 address and match-all socket flag into a long. // * @param inetAddress the host address // * @return the encoded value // */ // public static long fromInet4Address(final InetAddress inetAddress) // { // ensureIsInet4Address(inetAddress); // // return Integer.toUnsignedLong(inetAddress.hashCode()); // } // // /** // * Pack IPv4 address and socket into a long. // * @param socketAddress the socket address // * @param inode the socket inode // * @return the encoded value // */ // public static long fromInet4SocketAddressAndInode(final InetSocketAddress socketAddress, final int inode) // { // return overlayInode(fromInet4SocketAddress(socketAddress), inode); // } // // /** // * Pack IPv4 address and match-all socket flag into a long. // * @param inetAddress the host address // * @param inode the socket inode // * @return the encoded value // */ // public static long fromInet4AddressAndInode(final InetAddress inetAddress, final int inode) // { // return overlayInode(fromInet4Address(inetAddress), inode); // } // // /** // * Is this socketIdentifier a match for all ports on the encoded IP address. // * @param socketIdentifier the encoded value // * @return whether this socketIdentifier matches all ports // */ // public static boolean isMatchAllSocketFlagSet(final long socketIdentifier) // { // return extractPortNumber(socketIdentifier) == 0L; // } // // /** // * Mast the port number out of this socket identifier. // * @param socketIdentifier the encoded value // * @return the socketIdentifier with the port number masked out // */ // public static long asMatchAllSocketsSocketIdentifier(final long socketIdentifier) // { // return 0xFFFF0000FFFFFFFFL & socketIdentifier; // } // // /** // * Pack a hex-encoded IPv4:port socket address into a long. // * @param decodedAddress 32-bit IPv4 address decoded from hex // * @param port the port number // * @return the encoded value // */ // public static long fromLinuxKernelHexEncodedAddressAndPort(final long decodedAddress, final long port) // { // return port << 32 | Long.reverseBytes(decodedAddress) >>> 32; // } // // /** // * Pack inode value into socketIdentifier to differentiate between difference sockets listening to the same port. // * @param socketIdentifier the socketIdentifier // * @param inode the inode // * @return the encoded value // */ // public static long overlayInode(final long socketIdentifier, final long inode) // { // return inode << 48 | socketIdentifier; // } // // /** // * Extract port number from a socketIdentifier. // * @param socketIdentifier the socketIdentifier // * @return the port number // */ // public static int extractPortNumber(final long socketIdentifier) // { // return (int) ((socketIdentifier >> 32) & 0xFFFFL); // } // // /** // * Generates a vaguely human-readable format for a given socket identifier. // * @param socketIdentifier the encoded socket identifier // * @return human-readable form // */ // public static String toDebugString(final long socketIdentifier) // { // final int ipBits = (int) socketIdentifier; // final int port = extractPortNumber(socketIdentifier); // final int inode = (int) (socketIdentifier >> 48); // // return Integer.toHexString(ipBits) + ":" + port + "/" + inode; // } // // private static void validateAddressType(final InetSocketAddress socketAddress) // { // ensureIsInet4Address(socketAddress.getAddress()); // } // // private static void ensureIsInet4Address(final InetAddress address) // { // if(!(address instanceof Inet4Address)) // { // throw new IllegalArgumentException("Due to the nature of some awful hacks, " + // "I only work with Inet4Address-based sockets, not: " + address.getClass().getSimpleName()); // } // } // }
import com.lmax.angler.monitoring.network.monitor.socket.SocketIdentifier;
package com.lmax.angler.monitoring.network.monitor.socket.tcp; /** * Value object. */ final class TcpStatsEntry { private long socketIdentifier; private long receiveQueueDepth; private long transmitQueueDepth; private long inode; long getSocketIdentifier() { return socketIdentifier; } long getSocketInstanceIndentifier() {
// Path: src/main/java/com/lmax/angler/monitoring/network/monitor/socket/SocketIdentifier.java // public final class SocketIdentifier // { // private SocketIdentifier() {} // // /** // * Pack IPv4 address and socket into a long. // * @param socketAddress the socket address // * @return the encoded value // */ // public static long fromInet4SocketAddress(final InetSocketAddress socketAddress) // { // validateAddressType(socketAddress); // final long ipAddressOctets = Integer.toUnsignedLong(socketAddress.getAddress().hashCode()); // final long port = socketAddress.getPort(); // return port << 32 | ipAddressOctets; // } // // /** // * Pack IPv4 address and match-all socket flag into a long. // * @param inetAddress the host address // * @return the encoded value // */ // public static long fromInet4Address(final InetAddress inetAddress) // { // ensureIsInet4Address(inetAddress); // // return Integer.toUnsignedLong(inetAddress.hashCode()); // } // // /** // * Pack IPv4 address and socket into a long. // * @param socketAddress the socket address // * @param inode the socket inode // * @return the encoded value // */ // public static long fromInet4SocketAddressAndInode(final InetSocketAddress socketAddress, final int inode) // { // return overlayInode(fromInet4SocketAddress(socketAddress), inode); // } // // /** // * Pack IPv4 address and match-all socket flag into a long. // * @param inetAddress the host address // * @param inode the socket inode // * @return the encoded value // */ // public static long fromInet4AddressAndInode(final InetAddress inetAddress, final int inode) // { // return overlayInode(fromInet4Address(inetAddress), inode); // } // // /** // * Is this socketIdentifier a match for all ports on the encoded IP address. // * @param socketIdentifier the encoded value // * @return whether this socketIdentifier matches all ports // */ // public static boolean isMatchAllSocketFlagSet(final long socketIdentifier) // { // return extractPortNumber(socketIdentifier) == 0L; // } // // /** // * Mast the port number out of this socket identifier. // * @param socketIdentifier the encoded value // * @return the socketIdentifier with the port number masked out // */ // public static long asMatchAllSocketsSocketIdentifier(final long socketIdentifier) // { // return 0xFFFF0000FFFFFFFFL & socketIdentifier; // } // // /** // * Pack a hex-encoded IPv4:port socket address into a long. // * @param decodedAddress 32-bit IPv4 address decoded from hex // * @param port the port number // * @return the encoded value // */ // public static long fromLinuxKernelHexEncodedAddressAndPort(final long decodedAddress, final long port) // { // return port << 32 | Long.reverseBytes(decodedAddress) >>> 32; // } // // /** // * Pack inode value into socketIdentifier to differentiate between difference sockets listening to the same port. // * @param socketIdentifier the socketIdentifier // * @param inode the inode // * @return the encoded value // */ // public static long overlayInode(final long socketIdentifier, final long inode) // { // return inode << 48 | socketIdentifier; // } // // /** // * Extract port number from a socketIdentifier. // * @param socketIdentifier the socketIdentifier // * @return the port number // */ // public static int extractPortNumber(final long socketIdentifier) // { // return (int) ((socketIdentifier >> 32) & 0xFFFFL); // } // // /** // * Generates a vaguely human-readable format for a given socket identifier. // * @param socketIdentifier the encoded socket identifier // * @return human-readable form // */ // public static String toDebugString(final long socketIdentifier) // { // final int ipBits = (int) socketIdentifier; // final int port = extractPortNumber(socketIdentifier); // final int inode = (int) (socketIdentifier >> 48); // // return Integer.toHexString(ipBits) + ":" + port + "/" + inode; // } // // private static void validateAddressType(final InetSocketAddress socketAddress) // { // ensureIsInet4Address(socketAddress.getAddress()); // } // // private static void ensureIsInet4Address(final InetAddress address) // { // if(!(address instanceof Inet4Address)) // { // throw new IllegalArgumentException("Due to the nature of some awful hacks, " + // "I only work with Inet4Address-based sockets, not: " + address.getClass().getSimpleName()); // } // } // } // Path: src/main/java/com/lmax/angler/monitoring/network/monitor/socket/tcp/TcpStatsEntry.java import com.lmax.angler.monitoring.network.monitor.socket.SocketIdentifier; package com.lmax.angler.monitoring.network.monitor.socket.tcp; /** * Value object. */ final class TcpStatsEntry { private long socketIdentifier; private long receiveQueueDepth; private long transmitQueueDepth; private long inode; long getSocketIdentifier() { return socketIdentifier; } long getSocketInstanceIndentifier() {
return SocketIdentifier.overlayInode(socketIdentifier, inode);
LMAX-Exchange/angler
src/main/java/com/lmax/angler/monitoring/network/monitor/system/snmp/udp/SnmpUdpStatisticsColumnHandler.java
// Path: src/main/java/com/lmax/angler/monitoring/network/monitor/util/TokenHandler.java // public interface TokenHandler // { // /** // * Handle a single token. // * @param src data source // * @param startPosition the start position of the token // * @param endPosition the end position of the token // */ // void handleToken(final ByteBuffer src, final int startPosition, final int endPosition); // // /** // * Current token set is complete. // */ // void complete(); // // /** // * Reset state in preparation for handling a new data set. // */ // void reset(); // } // // Path: src/main/java/com/lmax/angler/monitoring/network/monitor/util/AsciiBytesToLongDecoder.java // public static long decodeAscii(final ByteBuffer src, final int startPosition, final int endPosition) // { // final int length = endPosition - startPosition; // if(length == 0) // { // throw new IllegalArgumentException("Cannot decode zero-length ascii string."); // } // long decoded = 0L; // for(int offset = 0; offset < length; offset++) // { // decoded *= 10; // // final byte digit = src.get(startPosition + offset); // // if(digit < '0' || digit > '9') // { // throw new IllegalArgumentException("Invalid digit: " + (char) digit); // } // // decoded += digit - '0'; // } // // return decoded; // }
import com.lmax.angler.monitoring.network.monitor.util.TokenHandler; import java.nio.ByteBuffer; import static com.lmax.angler.monitoring.network.monitor.util.AsciiBytesToLongDecoder.decodeAscii; import static java.nio.charset.StandardCharsets.UTF_8;
package com.lmax.angler.monitoring.network.monitor.system.snmp.udp; /** * TokenHandler for UDP-specific data in /proc/net/snmp. */ public final class SnmpUdpStatisticsColumnHandler implements TokenHandler { private static final long HEADER_ROW_FIRST_COLUMN_VALUE = ByteBuffer.wrap("Udp: InD".getBytes(UTF_8)).getLong(); private static final int UDP_ROW_FIRST_COLUMN_VALUE = ByteBuffer.wrap("Udp:".getBytes(UTF_8)).getInt(); private final SnmpUdpStatisticsHandler globalUdpStatisticsConsumer; private final GlobalUdpStatistics entry = new GlobalUdpStatistics(); private int currentColumn = 0; private boolean currentRowIsUdpDataRow; public SnmpUdpStatisticsColumnHandler(final SnmpUdpStatisticsHandler globalUdpStatisticsConsumer) { this.globalUdpStatisticsConsumer = globalUdpStatisticsConsumer; } /** * {@inheritDoc} */ @Override public void handleToken(final ByteBuffer src, final int startPosition, final int endPosition) { switch (currentColumn) { case 0: if(src.getInt(startPosition) == UDP_ROW_FIRST_COLUMN_VALUE && src.getLong(startPosition) != HEADER_ROW_FIRST_COLUMN_VALUE) { currentRowIsUdpDataRow = true; } break; case 3: // InErrors if(currentRowIsUdpDataRow) {
// Path: src/main/java/com/lmax/angler/monitoring/network/monitor/util/TokenHandler.java // public interface TokenHandler // { // /** // * Handle a single token. // * @param src data source // * @param startPosition the start position of the token // * @param endPosition the end position of the token // */ // void handleToken(final ByteBuffer src, final int startPosition, final int endPosition); // // /** // * Current token set is complete. // */ // void complete(); // // /** // * Reset state in preparation for handling a new data set. // */ // void reset(); // } // // Path: src/main/java/com/lmax/angler/monitoring/network/monitor/util/AsciiBytesToLongDecoder.java // public static long decodeAscii(final ByteBuffer src, final int startPosition, final int endPosition) // { // final int length = endPosition - startPosition; // if(length == 0) // { // throw new IllegalArgumentException("Cannot decode zero-length ascii string."); // } // long decoded = 0L; // for(int offset = 0; offset < length; offset++) // { // decoded *= 10; // // final byte digit = src.get(startPosition + offset); // // if(digit < '0' || digit > '9') // { // throw new IllegalArgumentException("Invalid digit: " + (char) digit); // } // // decoded += digit - '0'; // } // // return decoded; // } // Path: src/main/java/com/lmax/angler/monitoring/network/monitor/system/snmp/udp/SnmpUdpStatisticsColumnHandler.java import com.lmax.angler.monitoring.network.monitor.util.TokenHandler; import java.nio.ByteBuffer; import static com.lmax.angler.monitoring.network.monitor.util.AsciiBytesToLongDecoder.decodeAscii; import static java.nio.charset.StandardCharsets.UTF_8; package com.lmax.angler.monitoring.network.monitor.system.snmp.udp; /** * TokenHandler for UDP-specific data in /proc/net/snmp. */ public final class SnmpUdpStatisticsColumnHandler implements TokenHandler { private static final long HEADER_ROW_FIRST_COLUMN_VALUE = ByteBuffer.wrap("Udp: InD".getBytes(UTF_8)).getLong(); private static final int UDP_ROW_FIRST_COLUMN_VALUE = ByteBuffer.wrap("Udp:".getBytes(UTF_8)).getInt(); private final SnmpUdpStatisticsHandler globalUdpStatisticsConsumer; private final GlobalUdpStatistics entry = new GlobalUdpStatistics(); private int currentColumn = 0; private boolean currentRowIsUdpDataRow; public SnmpUdpStatisticsColumnHandler(final SnmpUdpStatisticsHandler globalUdpStatisticsConsumer) { this.globalUdpStatisticsConsumer = globalUdpStatisticsConsumer; } /** * {@inheritDoc} */ @Override public void handleToken(final ByteBuffer src, final int startPosition, final int endPosition) { switch (currentColumn) { case 0: if(src.getInt(startPosition) == UDP_ROW_FIRST_COLUMN_VALUE && src.getLong(startPosition) != HEADER_ROW_FIRST_COLUMN_VALUE) { currentRowIsUdpDataRow = true; } break; case 3: // InErrors if(currentRowIsUdpDataRow) {
entry.setInErrors(decodeAscii(src, startPosition, endPosition));
LMAX-Exchange/angler
src/main/java/com/lmax/angler/monitoring/network/monitor/socket/tcp/TcpBufferStats.java
// Path: src/main/java/com/lmax/angler/monitoring/network/monitor/socket/DescribableSocket.java // public interface DescribableSocket extends Updated // { // void describeTo(final SocketDescriptor descriptor); // } // // Path: src/main/java/com/lmax/angler/monitoring/network/monitor/socket/SocketDescriptor.java // public final class SocketDescriptor // { // private InetAddress address; // private int port; // private long inode; // // public void set(final InetAddress address, final int port, final long inode) // { // this.address = address; // this.port = port; // this.inode = inode; // } // // public InetAddress getAddress() // { // return address; // } // // public int getPort() // { // return port; // } // // public long getInode() // { // return inode; // } // }
import com.lmax.angler.monitoring.network.monitor.socket.DescribableSocket; import com.lmax.angler.monitoring.network.monitor.socket.SocketDescriptor; import java.net.InetAddress;
return changed; } void updateCount(final long updateCount) { this.updateCount = updateCount; } @Override public long getUpdateCount() { return updateCount; } long getInode() { return inode; } int getPort() { return port; } InetAddress getInetAddress() { return inetAddress; } @Override
// Path: src/main/java/com/lmax/angler/monitoring/network/monitor/socket/DescribableSocket.java // public interface DescribableSocket extends Updated // { // void describeTo(final SocketDescriptor descriptor); // } // // Path: src/main/java/com/lmax/angler/monitoring/network/monitor/socket/SocketDescriptor.java // public final class SocketDescriptor // { // private InetAddress address; // private int port; // private long inode; // // public void set(final InetAddress address, final int port, final long inode) // { // this.address = address; // this.port = port; // this.inode = inode; // } // // public InetAddress getAddress() // { // return address; // } // // public int getPort() // { // return port; // } // // public long getInode() // { // return inode; // } // } // Path: src/main/java/com/lmax/angler/monitoring/network/monitor/socket/tcp/TcpBufferStats.java import com.lmax.angler.monitoring.network.monitor.socket.DescribableSocket; import com.lmax.angler.monitoring.network.monitor.socket.SocketDescriptor; import java.net.InetAddress; return changed; } void updateCount(final long updateCount) { this.updateCount = updateCount; } @Override public long getUpdateCount() { return updateCount; } long getInode() { return inode; } int getPort() { return port; } InetAddress getInetAddress() { return inetAddress; } @Override
public void describeTo(final SocketDescriptor descriptor)
LMAX-Exchange/angler
src/main/java/com/lmax/angler/monitoring/network/monitor/socket/udp/UdpBufferStats.java
// Path: src/main/java/com/lmax/angler/monitoring/network/monitor/socket/DescribableSocket.java // public interface DescribableSocket extends Updated // { // void describeTo(final SocketDescriptor descriptor); // } // // Path: src/main/java/com/lmax/angler/monitoring/network/monitor/socket/SocketDescriptor.java // public final class SocketDescriptor // { // private InetAddress address; // private int port; // private long inode; // // public void set(final InetAddress address, final int port, final long inode) // { // this.address = address; // this.port = port; // this.inode = inode; // } // // public InetAddress getAddress() // { // return address; // } // // public int getPort() // { // return port; // } // // public long getInode() // { // return inode; // } // }
import com.lmax.angler.monitoring.network.monitor.socket.DescribableSocket; import com.lmax.angler.monitoring.network.monitor.socket.SocketDescriptor; import java.net.InetAddress;
return changed; } void updateCount(final long updateCount) { this.updateCount = updateCount; } @Override public long getUpdateCount() { return updateCount; } long getInode() { return inode; } int getPort() { return port; } InetAddress getInetAddress() { return inetAddress; } @Override
// Path: src/main/java/com/lmax/angler/monitoring/network/monitor/socket/DescribableSocket.java // public interface DescribableSocket extends Updated // { // void describeTo(final SocketDescriptor descriptor); // } // // Path: src/main/java/com/lmax/angler/monitoring/network/monitor/socket/SocketDescriptor.java // public final class SocketDescriptor // { // private InetAddress address; // private int port; // private long inode; // // public void set(final InetAddress address, final int port, final long inode) // { // this.address = address; // this.port = port; // this.inode = inode; // } // // public InetAddress getAddress() // { // return address; // } // // public int getPort() // { // return port; // } // // public long getInode() // { // return inode; // } // } // Path: src/main/java/com/lmax/angler/monitoring/network/monitor/socket/udp/UdpBufferStats.java import com.lmax.angler.monitoring.network.monitor.socket.DescribableSocket; import com.lmax.angler.monitoring.network.monitor.socket.SocketDescriptor; import java.net.InetAddress; return changed; } void updateCount(final long updateCount) { this.updateCount = updateCount; } @Override public long getUpdateCount() { return updateCount; } long getInode() { return inode; } int getPort() { return port; } InetAddress getInetAddress() { return inetAddress; } @Override
public void describeTo(final SocketDescriptor descriptor)
LMAX-Exchange/angler
src/test/java/com/lmax/angler/monitoring/network/monitor/system/softnet/SoftnetStatsMonitorTest.java
// Path: src/test/java/com/lmax/angler/monitoring/network/monitor/ResourceUtil.java // public final class ResourceUtil // { // private ResourceUtil() {} // // public static void writeDataFile(final String resourceName, final Path sourcePath) throws IOException, URISyntaxException // { // copy(Paths.get(currentThread().getContextClassLoader().getResource(resourceName).toURI()), // new FileOutputStream(sourcePath.toFile(), false)); // } // }
import com.lmax.angler.monitoring.network.monitor.ResourceUtil; import org.junit.After; import org.junit.Before; import org.junit.Test; import java.nio.file.Files; import java.nio.file.Path; import java.util.ArrayList; import java.util.List; import static org.hamcrest.CoreMatchers.is; import static org.junit.Assert.assertThat;
package com.lmax.angler.monitoring.network.monitor.system.softnet; public class SoftnetStatsMonitorTest { private final RecordingSoftnetStatsHandler softnetStatsHandler = new RecordingSoftnetStatsHandler(); private Path inputPath; private SoftnetStatsMonitor monitor; @Before public void before() throws Exception { inputPath = Files.createTempFile("proc-net-softnet_stat", "txt");
// Path: src/test/java/com/lmax/angler/monitoring/network/monitor/ResourceUtil.java // public final class ResourceUtil // { // private ResourceUtil() {} // // public static void writeDataFile(final String resourceName, final Path sourcePath) throws IOException, URISyntaxException // { // copy(Paths.get(currentThread().getContextClassLoader().getResource(resourceName).toURI()), // new FileOutputStream(sourcePath.toFile(), false)); // } // } // Path: src/test/java/com/lmax/angler/monitoring/network/monitor/system/softnet/SoftnetStatsMonitorTest.java import com.lmax.angler.monitoring.network.monitor.ResourceUtil; import org.junit.After; import org.junit.Before; import org.junit.Test; import java.nio.file.Files; import java.nio.file.Path; import java.util.ArrayList; import java.util.List; import static org.hamcrest.CoreMatchers.is; import static org.junit.Assert.assertThat; package com.lmax.angler.monitoring.network.monitor.system.softnet; public class SoftnetStatsMonitorTest { private final RecordingSoftnetStatsHandler softnetStatsHandler = new RecordingSoftnetStatsHandler(); private Path inputPath; private SoftnetStatsMonitor monitor; @Before public void before() throws Exception { inputPath = Files.createTempFile("proc-net-softnet_stat", "txt");
ResourceUtil.writeDataFile("proc_net_softnet_stat_sample.txt", inputPath);
LMAX-Exchange/angler
src/main/java/com/lmax/angler/monitoring/network/monitor/system/softnet/SoftnetStatsMonitor.java
// Path: src/main/java/com/lmax/angler/monitoring/network/monitor/util/FileLoader.java // public final class FileLoader // { // private final Path path; // private final ByteBuffer tmp = ByteBuffer.allocateDirect(4096); // private ByteBuffer buffer; // private FileChannel fileChannel; // // public FileLoader(final Path path, final int initialBufferCapacity) // { // this.path = path; // buffer = ByteBuffer.allocateDirect(initialBufferCapacity); // } // // /** // * Opens a channel to the specified path if it does not already exist. // * Allocates a larger ByteBuffer if file size &gt; current buffer size. // * Reads file data into ByteBuffer. // */ // public void load() // { // try // { // if (fileChannel == null) // { // fileChannel = FileChannel.open(path, StandardOpenOption.READ); // } // // fileChannel.position(0L); // buffer.clear(); // tmp.clear(); // while(fileChannel.read(tmp) > 0) // { // tmp.flip(); // if(tmp.remaining() > buffer.capacity() - buffer.position()) // { // final ByteBuffer next = ByteBuffer.allocateDirect(Math.max(buffer.capacity() * 2, tmp.remaining())); // buffer.flip(); // next.put(buffer); // buffer = next; // } // buffer.put(tmp); // tmp.clear(); // } // // buffer.flip(); // } // catch(final IOException e) // { // throw new UncheckedIOException(e); // } // } // // public ByteBuffer getBuffer() // { // return buffer; // } // } // // Path: src/main/java/com/lmax/angler/monitoring/network/monitor/util/TokenHandler.java // public interface TokenHandler // { // /** // * Handle a single token. // * @param src data source // * @param startPosition the start position of the token // * @param endPosition the end position of the token // */ // void handleToken(final ByteBuffer src, final int startPosition, final int endPosition); // // /** // * Current token set is complete. // */ // void complete(); // // /** // * Reset state in preparation for handling a new data set. // */ // void reset(); // } // // Path: src/main/java/com/lmax/angler/monitoring/network/monitor/util/Parsers.java // public static TokenHandler rowColumnParser( // TokenHandler tokenHandler) // { // return new DelimitedDataParser( // new DelimitedDataParser( // tokenHandler, // COLUMN_DELIMITER, // true), // ROW_DELIMITER, // true); // }
import com.lmax.angler.monitoring.network.monitor.util.FileLoader; import com.lmax.angler.monitoring.network.monitor.util.TokenHandler; import org.agrona.collections.Int2ObjectHashMap; import java.nio.ByteBuffer; import java.nio.file.Path; import java.nio.file.Paths; import static com.lmax.angler.monitoring.network.monitor.util.Parsers.rowColumnParser; import static java.lang.Runtime.getRuntime;
package com.lmax.angler.monitoring.network.monitor.system.softnet; /** * Monitor for reporting changes in /proc/net/softnet_stat, which can indicate that the kernel thread * responsible for processing incoming network softIRQs is unable to keep up with the ingress rate. */ public final class SoftnetStatsMonitor { private static final int ESTIMATED_LINE_LENGTH = 120; private final Int2ObjectHashMap<CpuSoftIrqData> cpuSoftIrqDataMap = new Int2ObjectHashMap<>();
// Path: src/main/java/com/lmax/angler/monitoring/network/monitor/util/FileLoader.java // public final class FileLoader // { // private final Path path; // private final ByteBuffer tmp = ByteBuffer.allocateDirect(4096); // private ByteBuffer buffer; // private FileChannel fileChannel; // // public FileLoader(final Path path, final int initialBufferCapacity) // { // this.path = path; // buffer = ByteBuffer.allocateDirect(initialBufferCapacity); // } // // /** // * Opens a channel to the specified path if it does not already exist. // * Allocates a larger ByteBuffer if file size &gt; current buffer size. // * Reads file data into ByteBuffer. // */ // public void load() // { // try // { // if (fileChannel == null) // { // fileChannel = FileChannel.open(path, StandardOpenOption.READ); // } // // fileChannel.position(0L); // buffer.clear(); // tmp.clear(); // while(fileChannel.read(tmp) > 0) // { // tmp.flip(); // if(tmp.remaining() > buffer.capacity() - buffer.position()) // { // final ByteBuffer next = ByteBuffer.allocateDirect(Math.max(buffer.capacity() * 2, tmp.remaining())); // buffer.flip(); // next.put(buffer); // buffer = next; // } // buffer.put(tmp); // tmp.clear(); // } // // buffer.flip(); // } // catch(final IOException e) // { // throw new UncheckedIOException(e); // } // } // // public ByteBuffer getBuffer() // { // return buffer; // } // } // // Path: src/main/java/com/lmax/angler/monitoring/network/monitor/util/TokenHandler.java // public interface TokenHandler // { // /** // * Handle a single token. // * @param src data source // * @param startPosition the start position of the token // * @param endPosition the end position of the token // */ // void handleToken(final ByteBuffer src, final int startPosition, final int endPosition); // // /** // * Current token set is complete. // */ // void complete(); // // /** // * Reset state in preparation for handling a new data set. // */ // void reset(); // } // // Path: src/main/java/com/lmax/angler/monitoring/network/monitor/util/Parsers.java // public static TokenHandler rowColumnParser( // TokenHandler tokenHandler) // { // return new DelimitedDataParser( // new DelimitedDataParser( // tokenHandler, // COLUMN_DELIMITER, // true), // ROW_DELIMITER, // true); // } // Path: src/main/java/com/lmax/angler/monitoring/network/monitor/system/softnet/SoftnetStatsMonitor.java import com.lmax.angler.monitoring.network.monitor.util.FileLoader; import com.lmax.angler.monitoring.network.monitor.util.TokenHandler; import org.agrona.collections.Int2ObjectHashMap; import java.nio.ByteBuffer; import java.nio.file.Path; import java.nio.file.Paths; import static com.lmax.angler.monitoring.network.monitor.util.Parsers.rowColumnParser; import static java.lang.Runtime.getRuntime; package com.lmax.angler.monitoring.network.monitor.system.softnet; /** * Monitor for reporting changes in /proc/net/softnet_stat, which can indicate that the kernel thread * responsible for processing incoming network softIRQs is unable to keep up with the ingress rate. */ public final class SoftnetStatsMonitor { private static final int ESTIMATED_LINE_LENGTH = 120; private final Int2ObjectHashMap<CpuSoftIrqData> cpuSoftIrqDataMap = new Int2ObjectHashMap<>();
private final TokenHandler lineParser = rowColumnParser(new SoftnetStatColumnHandler(this::handleEntry));
LMAX-Exchange/angler
src/main/java/com/lmax/angler/monitoring/network/monitor/system/softnet/SoftnetStatsMonitor.java
// Path: src/main/java/com/lmax/angler/monitoring/network/monitor/util/FileLoader.java // public final class FileLoader // { // private final Path path; // private final ByteBuffer tmp = ByteBuffer.allocateDirect(4096); // private ByteBuffer buffer; // private FileChannel fileChannel; // // public FileLoader(final Path path, final int initialBufferCapacity) // { // this.path = path; // buffer = ByteBuffer.allocateDirect(initialBufferCapacity); // } // // /** // * Opens a channel to the specified path if it does not already exist. // * Allocates a larger ByteBuffer if file size &gt; current buffer size. // * Reads file data into ByteBuffer. // */ // public void load() // { // try // { // if (fileChannel == null) // { // fileChannel = FileChannel.open(path, StandardOpenOption.READ); // } // // fileChannel.position(0L); // buffer.clear(); // tmp.clear(); // while(fileChannel.read(tmp) > 0) // { // tmp.flip(); // if(tmp.remaining() > buffer.capacity() - buffer.position()) // { // final ByteBuffer next = ByteBuffer.allocateDirect(Math.max(buffer.capacity() * 2, tmp.remaining())); // buffer.flip(); // next.put(buffer); // buffer = next; // } // buffer.put(tmp); // tmp.clear(); // } // // buffer.flip(); // } // catch(final IOException e) // { // throw new UncheckedIOException(e); // } // } // // public ByteBuffer getBuffer() // { // return buffer; // } // } // // Path: src/main/java/com/lmax/angler/monitoring/network/monitor/util/TokenHandler.java // public interface TokenHandler // { // /** // * Handle a single token. // * @param src data source // * @param startPosition the start position of the token // * @param endPosition the end position of the token // */ // void handleToken(final ByteBuffer src, final int startPosition, final int endPosition); // // /** // * Current token set is complete. // */ // void complete(); // // /** // * Reset state in preparation for handling a new data set. // */ // void reset(); // } // // Path: src/main/java/com/lmax/angler/monitoring/network/monitor/util/Parsers.java // public static TokenHandler rowColumnParser( // TokenHandler tokenHandler) // { // return new DelimitedDataParser( // new DelimitedDataParser( // tokenHandler, // COLUMN_DELIMITER, // true), // ROW_DELIMITER, // true); // }
import com.lmax.angler.monitoring.network.monitor.util.FileLoader; import com.lmax.angler.monitoring.network.monitor.util.TokenHandler; import org.agrona.collections.Int2ObjectHashMap; import java.nio.ByteBuffer; import java.nio.file.Path; import java.nio.file.Paths; import static com.lmax.angler.monitoring.network.monitor.util.Parsers.rowColumnParser; import static java.lang.Runtime.getRuntime;
package com.lmax.angler.monitoring.network.monitor.system.softnet; /** * Monitor for reporting changes in /proc/net/softnet_stat, which can indicate that the kernel thread * responsible for processing incoming network softIRQs is unable to keep up with the ingress rate. */ public final class SoftnetStatsMonitor { private static final int ESTIMATED_LINE_LENGTH = 120; private final Int2ObjectHashMap<CpuSoftIrqData> cpuSoftIrqDataMap = new Int2ObjectHashMap<>();
// Path: src/main/java/com/lmax/angler/monitoring/network/monitor/util/FileLoader.java // public final class FileLoader // { // private final Path path; // private final ByteBuffer tmp = ByteBuffer.allocateDirect(4096); // private ByteBuffer buffer; // private FileChannel fileChannel; // // public FileLoader(final Path path, final int initialBufferCapacity) // { // this.path = path; // buffer = ByteBuffer.allocateDirect(initialBufferCapacity); // } // // /** // * Opens a channel to the specified path if it does not already exist. // * Allocates a larger ByteBuffer if file size &gt; current buffer size. // * Reads file data into ByteBuffer. // */ // public void load() // { // try // { // if (fileChannel == null) // { // fileChannel = FileChannel.open(path, StandardOpenOption.READ); // } // // fileChannel.position(0L); // buffer.clear(); // tmp.clear(); // while(fileChannel.read(tmp) > 0) // { // tmp.flip(); // if(tmp.remaining() > buffer.capacity() - buffer.position()) // { // final ByteBuffer next = ByteBuffer.allocateDirect(Math.max(buffer.capacity() * 2, tmp.remaining())); // buffer.flip(); // next.put(buffer); // buffer = next; // } // buffer.put(tmp); // tmp.clear(); // } // // buffer.flip(); // } // catch(final IOException e) // { // throw new UncheckedIOException(e); // } // } // // public ByteBuffer getBuffer() // { // return buffer; // } // } // // Path: src/main/java/com/lmax/angler/monitoring/network/monitor/util/TokenHandler.java // public interface TokenHandler // { // /** // * Handle a single token. // * @param src data source // * @param startPosition the start position of the token // * @param endPosition the end position of the token // */ // void handleToken(final ByteBuffer src, final int startPosition, final int endPosition); // // /** // * Current token set is complete. // */ // void complete(); // // /** // * Reset state in preparation for handling a new data set. // */ // void reset(); // } // // Path: src/main/java/com/lmax/angler/monitoring/network/monitor/util/Parsers.java // public static TokenHandler rowColumnParser( // TokenHandler tokenHandler) // { // return new DelimitedDataParser( // new DelimitedDataParser( // tokenHandler, // COLUMN_DELIMITER, // true), // ROW_DELIMITER, // true); // } // Path: src/main/java/com/lmax/angler/monitoring/network/monitor/system/softnet/SoftnetStatsMonitor.java import com.lmax.angler.monitoring.network.monitor.util.FileLoader; import com.lmax.angler.monitoring.network.monitor.util.TokenHandler; import org.agrona.collections.Int2ObjectHashMap; import java.nio.ByteBuffer; import java.nio.file.Path; import java.nio.file.Paths; import static com.lmax.angler.monitoring.network.monitor.util.Parsers.rowColumnParser; import static java.lang.Runtime.getRuntime; package com.lmax.angler.monitoring.network.monitor.system.softnet; /** * Monitor for reporting changes in /proc/net/softnet_stat, which can indicate that the kernel thread * responsible for processing incoming network softIRQs is unable to keep up with the ingress rate. */ public final class SoftnetStatsMonitor { private static final int ESTIMATED_LINE_LENGTH = 120; private final Int2ObjectHashMap<CpuSoftIrqData> cpuSoftIrqDataMap = new Int2ObjectHashMap<>();
private final TokenHandler lineParser = rowColumnParser(new SoftnetStatColumnHandler(this::handleEntry));
LMAX-Exchange/angler
src/main/java/com/lmax/angler/monitoring/network/monitor/system/softnet/SoftnetStatsMonitor.java
// Path: src/main/java/com/lmax/angler/monitoring/network/monitor/util/FileLoader.java // public final class FileLoader // { // private final Path path; // private final ByteBuffer tmp = ByteBuffer.allocateDirect(4096); // private ByteBuffer buffer; // private FileChannel fileChannel; // // public FileLoader(final Path path, final int initialBufferCapacity) // { // this.path = path; // buffer = ByteBuffer.allocateDirect(initialBufferCapacity); // } // // /** // * Opens a channel to the specified path if it does not already exist. // * Allocates a larger ByteBuffer if file size &gt; current buffer size. // * Reads file data into ByteBuffer. // */ // public void load() // { // try // { // if (fileChannel == null) // { // fileChannel = FileChannel.open(path, StandardOpenOption.READ); // } // // fileChannel.position(0L); // buffer.clear(); // tmp.clear(); // while(fileChannel.read(tmp) > 0) // { // tmp.flip(); // if(tmp.remaining() > buffer.capacity() - buffer.position()) // { // final ByteBuffer next = ByteBuffer.allocateDirect(Math.max(buffer.capacity() * 2, tmp.remaining())); // buffer.flip(); // next.put(buffer); // buffer = next; // } // buffer.put(tmp); // tmp.clear(); // } // // buffer.flip(); // } // catch(final IOException e) // { // throw new UncheckedIOException(e); // } // } // // public ByteBuffer getBuffer() // { // return buffer; // } // } // // Path: src/main/java/com/lmax/angler/monitoring/network/monitor/util/TokenHandler.java // public interface TokenHandler // { // /** // * Handle a single token. // * @param src data source // * @param startPosition the start position of the token // * @param endPosition the end position of the token // */ // void handleToken(final ByteBuffer src, final int startPosition, final int endPosition); // // /** // * Current token set is complete. // */ // void complete(); // // /** // * Reset state in preparation for handling a new data set. // */ // void reset(); // } // // Path: src/main/java/com/lmax/angler/monitoring/network/monitor/util/Parsers.java // public static TokenHandler rowColumnParser( // TokenHandler tokenHandler) // { // return new DelimitedDataParser( // new DelimitedDataParser( // tokenHandler, // COLUMN_DELIMITER, // true), // ROW_DELIMITER, // true); // }
import com.lmax.angler.monitoring.network.monitor.util.FileLoader; import com.lmax.angler.monitoring.network.monitor.util.TokenHandler; import org.agrona.collections.Int2ObjectHashMap; import java.nio.ByteBuffer; import java.nio.file.Path; import java.nio.file.Paths; import static com.lmax.angler.monitoring.network.monitor.util.Parsers.rowColumnParser; import static java.lang.Runtime.getRuntime;
package com.lmax.angler.monitoring.network.monitor.system.softnet; /** * Monitor for reporting changes in /proc/net/softnet_stat, which can indicate that the kernel thread * responsible for processing incoming network softIRQs is unable to keep up with the ingress rate. */ public final class SoftnetStatsMonitor { private static final int ESTIMATED_LINE_LENGTH = 120; private final Int2ObjectHashMap<CpuSoftIrqData> cpuSoftIrqDataMap = new Int2ObjectHashMap<>(); private final TokenHandler lineParser = rowColumnParser(new SoftnetStatColumnHandler(this::handleEntry));
// Path: src/main/java/com/lmax/angler/monitoring/network/monitor/util/FileLoader.java // public final class FileLoader // { // private final Path path; // private final ByteBuffer tmp = ByteBuffer.allocateDirect(4096); // private ByteBuffer buffer; // private FileChannel fileChannel; // // public FileLoader(final Path path, final int initialBufferCapacity) // { // this.path = path; // buffer = ByteBuffer.allocateDirect(initialBufferCapacity); // } // // /** // * Opens a channel to the specified path if it does not already exist. // * Allocates a larger ByteBuffer if file size &gt; current buffer size. // * Reads file data into ByteBuffer. // */ // public void load() // { // try // { // if (fileChannel == null) // { // fileChannel = FileChannel.open(path, StandardOpenOption.READ); // } // // fileChannel.position(0L); // buffer.clear(); // tmp.clear(); // while(fileChannel.read(tmp) > 0) // { // tmp.flip(); // if(tmp.remaining() > buffer.capacity() - buffer.position()) // { // final ByteBuffer next = ByteBuffer.allocateDirect(Math.max(buffer.capacity() * 2, tmp.remaining())); // buffer.flip(); // next.put(buffer); // buffer = next; // } // buffer.put(tmp); // tmp.clear(); // } // // buffer.flip(); // } // catch(final IOException e) // { // throw new UncheckedIOException(e); // } // } // // public ByteBuffer getBuffer() // { // return buffer; // } // } // // Path: src/main/java/com/lmax/angler/monitoring/network/monitor/util/TokenHandler.java // public interface TokenHandler // { // /** // * Handle a single token. // * @param src data source // * @param startPosition the start position of the token // * @param endPosition the end position of the token // */ // void handleToken(final ByteBuffer src, final int startPosition, final int endPosition); // // /** // * Current token set is complete. // */ // void complete(); // // /** // * Reset state in preparation for handling a new data set. // */ // void reset(); // } // // Path: src/main/java/com/lmax/angler/monitoring/network/monitor/util/Parsers.java // public static TokenHandler rowColumnParser( // TokenHandler tokenHandler) // { // return new DelimitedDataParser( // new DelimitedDataParser( // tokenHandler, // COLUMN_DELIMITER, // true), // ROW_DELIMITER, // true); // } // Path: src/main/java/com/lmax/angler/monitoring/network/monitor/system/softnet/SoftnetStatsMonitor.java import com.lmax.angler.monitoring.network.monitor.util.FileLoader; import com.lmax.angler.monitoring.network.monitor.util.TokenHandler; import org.agrona.collections.Int2ObjectHashMap; import java.nio.ByteBuffer; import java.nio.file.Path; import java.nio.file.Paths; import static com.lmax.angler.monitoring.network.monitor.util.Parsers.rowColumnParser; import static java.lang.Runtime.getRuntime; package com.lmax.angler.monitoring.network.monitor.system.softnet; /** * Monitor for reporting changes in /proc/net/softnet_stat, which can indicate that the kernel thread * responsible for processing incoming network softIRQs is unable to keep up with the ingress rate. */ public final class SoftnetStatsMonitor { private static final int ESTIMATED_LINE_LENGTH = 120; private final Int2ObjectHashMap<CpuSoftIrqData> cpuSoftIrqDataMap = new Int2ObjectHashMap<>(); private final TokenHandler lineParser = rowColumnParser(new SoftnetStatColumnHandler(this::handleEntry));
private final FileLoader fileLoader;
mimacom/liferay-db-setup-core
db-setup-core/src/main/java/com/mimacom/liferay/portal/setup/core/SetupUsers.java
// Path: db-setup-core/src/main/java/com/mimacom/liferay/portal/setup/core/util/CustomFieldSettingUtil.java // public final class CustomFieldSettingUtil { // private static final Log LOG = LogFactoryUtil.getLog(CustomFieldSettingUtil.class); // // private CustomFieldSettingUtil() { // // } // // /** // * Auxiliary method that returns the expando value of a given expando field // * with a given key. // * // * @param user // * The user whose expando field will be retrieved. // * @param key // * The name of the expando field. // * @return Returns false, if the expando field or the value is not defined. // */ // // CHECKSTYLE:OFF // public static void setExpandoValue(final String resolverHint, final long runAsUserId, // final long groupId, final long company, final Class clazz, final long id, // final String key, final String value) { // String valueCopy = value; // try { // // ExpandoValue ev = ExpandoValueLocalServiceUtil.getValue(company, clazz.getName(), // "CUSTOM_FIELDS", key, id); // // resolve any values to be substituted // valueCopy = ResolverUtil.lookupAll(runAsUserId, groupId, company, valueCopy, // resolverHint); // if (ev == null) { // long classNameId = ClassNameLocalServiceUtil.getClassNameId(clazz.getName()); // // ExpandoTable expandoTable = ExpandoTableLocalServiceUtil.getTable(company, // classNameId, "CUSTOM_FIELDS"); // ExpandoColumn expandoColumn = ExpandoColumnLocalServiceUtil.getColumn(company, // classNameId, expandoTable.getName(), key); // // // In this we are adding MyUserColumnData for the column // // MyUserColumn. See the // // above line // ev = ExpandoValueLocalServiceUtil.addValue(classNameId, expandoTable.getTableId(), // expandoColumn.getColumnId(), id, valueCopy); // } else { // ev.setData(valueCopy); // ExpandoValueLocalServiceUtil.updateExpandoValue(ev); // } // } catch (Exception ex) { // LOG.error("Expando (custom field) not found or problem accessing it: " + key + " for " // + "class " + clazz.getName() + " with id " + id, ex); // } // // } // // CHECKSTYLE:ON // }
import java.util.Calendar; import java.util.HashMap; import java.util.List; import java.util.Locale; import java.util.Map; import com.liferay.portal.kernel.exception.NoSuchUserException; import com.liferay.portal.kernel.model.Group; import com.liferay.portal.kernel.model.Organization; import com.liferay.portal.kernel.model.Role; import com.liferay.portal.kernel.model.User; import com.liferay.portal.kernel.service.*; import com.liferay.portal.kernel.util.PortalUtil; import com.mimacom.liferay.portal.setup.core.util.CustomFieldSettingUtil; import com.mimacom.liferay.portal.setup.domain.CustomFieldSetting; import com.liferay.portal.kernel.exception.PortalException; import com.liferay.portal.kernel.exception.SystemException; import com.liferay.portal.kernel.log.Log; import com.liferay.portal.kernel.log.LogFactoryUtil; import com.liferay.portal.kernel.util.StringPool;
LOG.info("User " + liferayUser.getEmailAddress() + " already exist, not creating..."); } catch (NoSuchUserException e) { liferayUser = addUser(user); } catch (Exception e) { LOG.error("Error by retrieving user " + user.getEmailAddress()); } if( null != liferayUser ){ addUserToOrganizations(user, liferayUser); addRolesToUser(user, liferayUser); if (user.getCustomFieldSetting() != null && !user.getCustomFieldSetting().isEmpty()) { setCustomFields(runAsUser, groupId, COMPANY_ID, liferayUser, user); } } else { LOG.warn("Could not create user with screenName '" + user.getScreenName()+"'"); } } } private static void setCustomFields(final long runAsUser, final long groupId, final long company, final User liferayUser, final com.mimacom.liferay.portal.setup.domain.User user) { Class clazz = User.class; for (CustomFieldSetting cfs : user.getCustomFieldSetting()) { String resolverHint = "Custom value for user " + user.getScreenName() + ", " + user.getEmailAddress() + "" + " Key " + cfs.getKey() + ", value " + cfs.getValue();
// Path: db-setup-core/src/main/java/com/mimacom/liferay/portal/setup/core/util/CustomFieldSettingUtil.java // public final class CustomFieldSettingUtil { // private static final Log LOG = LogFactoryUtil.getLog(CustomFieldSettingUtil.class); // // private CustomFieldSettingUtil() { // // } // // /** // * Auxiliary method that returns the expando value of a given expando field // * with a given key. // * // * @param user // * The user whose expando field will be retrieved. // * @param key // * The name of the expando field. // * @return Returns false, if the expando field or the value is not defined. // */ // // CHECKSTYLE:OFF // public static void setExpandoValue(final String resolverHint, final long runAsUserId, // final long groupId, final long company, final Class clazz, final long id, // final String key, final String value) { // String valueCopy = value; // try { // // ExpandoValue ev = ExpandoValueLocalServiceUtil.getValue(company, clazz.getName(), // "CUSTOM_FIELDS", key, id); // // resolve any values to be substituted // valueCopy = ResolverUtil.lookupAll(runAsUserId, groupId, company, valueCopy, // resolverHint); // if (ev == null) { // long classNameId = ClassNameLocalServiceUtil.getClassNameId(clazz.getName()); // // ExpandoTable expandoTable = ExpandoTableLocalServiceUtil.getTable(company, // classNameId, "CUSTOM_FIELDS"); // ExpandoColumn expandoColumn = ExpandoColumnLocalServiceUtil.getColumn(company, // classNameId, expandoTable.getName(), key); // // // In this we are adding MyUserColumnData for the column // // MyUserColumn. See the // // above line // ev = ExpandoValueLocalServiceUtil.addValue(classNameId, expandoTable.getTableId(), // expandoColumn.getColumnId(), id, valueCopy); // } else { // ev.setData(valueCopy); // ExpandoValueLocalServiceUtil.updateExpandoValue(ev); // } // } catch (Exception ex) { // LOG.error("Expando (custom field) not found or problem accessing it: " + key + " for " // + "class " + clazz.getName() + " with id " + id, ex); // } // // } // // CHECKSTYLE:ON // } // Path: db-setup-core/src/main/java/com/mimacom/liferay/portal/setup/core/SetupUsers.java import java.util.Calendar; import java.util.HashMap; import java.util.List; import java.util.Locale; import java.util.Map; import com.liferay.portal.kernel.exception.NoSuchUserException; import com.liferay.portal.kernel.model.Group; import com.liferay.portal.kernel.model.Organization; import com.liferay.portal.kernel.model.Role; import com.liferay.portal.kernel.model.User; import com.liferay.portal.kernel.service.*; import com.liferay.portal.kernel.util.PortalUtil; import com.mimacom.liferay.portal.setup.core.util.CustomFieldSettingUtil; import com.mimacom.liferay.portal.setup.domain.CustomFieldSetting; import com.liferay.portal.kernel.exception.PortalException; import com.liferay.portal.kernel.exception.SystemException; import com.liferay.portal.kernel.log.Log; import com.liferay.portal.kernel.log.LogFactoryUtil; import com.liferay.portal.kernel.util.StringPool; LOG.info("User " + liferayUser.getEmailAddress() + " already exist, not creating..."); } catch (NoSuchUserException e) { liferayUser = addUser(user); } catch (Exception e) { LOG.error("Error by retrieving user " + user.getEmailAddress()); } if( null != liferayUser ){ addUserToOrganizations(user, liferayUser); addRolesToUser(user, liferayUser); if (user.getCustomFieldSetting() != null && !user.getCustomFieldSetting().isEmpty()) { setCustomFields(runAsUser, groupId, COMPANY_ID, liferayUser, user); } } else { LOG.warn("Could not create user with screenName '" + user.getScreenName()+"'"); } } } private static void setCustomFields(final long runAsUser, final long groupId, final long company, final User liferayUser, final com.mimacom.liferay.portal.setup.domain.User user) { Class clazz = User.class; for (CustomFieldSetting cfs : user.getCustomFieldSetting()) { String resolverHint = "Custom value for user " + user.getScreenName() + ", " + user.getEmailAddress() + "" + " Key " + cfs.getKey() + ", value " + cfs.getValue();
CustomFieldSettingUtil.setExpandoValue(resolverHint, runAsUser, groupId, company, clazz,
Amab/SWADroid
SWADroid/src/main/java/es/ugr/swad/swadroid/gui/AlertNotificationFactory.java
// Path: SWADroid/src/main/java/es/ugr/swad/swadroid/utils/NotificationUtils.java // @TargetApi(Build.VERSION_CODES.O) // public class NotificationUtils extends ContextWrapper { // // private NotificationManager mManager; // public static final String SWADROID_CHANNEL_ID = "es.ugr.swad.swadroid.SWADROID"; // public static final String SWADROID_CHANNEL_NAME = "SWADROID CHANNEL"; // // public NotificationUtils(Context base) { // super(base); // createChannels(); // } // // public void createChannels() { // // // create SWADroid channel // NotificationChannel androidChannel = new NotificationChannel(SWADROID_CHANNEL_ID, // SWADROID_CHANNEL_NAME, NotificationManager.IMPORTANCE_DEFAULT); // // Sets whether notifications posted to this channel should display notification lights // androidChannel.enableLights(true); // // Sets whether notification posted to this channel should vibrate. // androidChannel.enableVibration(true); // // Sets the notification light color for notifications posted to this channel // androidChannel.setLightColor(Color.GREEN); // // Sets whether notifications posted to this channel appear on the lockscreen or not // androidChannel.setLockscreenVisibility(Notification.VISIBILITY_PUBLIC); // // getManager().createNotificationChannel(androidChannel); // } // // public NotificationManager getManager() { // if (mManager == null) { // mManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE); // } // return mManager; // } // } // // Path: SWADroid/src/main/java/es/ugr/swad/swadroid/utils/NotificationUtils.java // public static final String SWADROID_CHANNEL_ID = "es.ugr.swad.swadroid.SWADROID";
import android.app.Notification; import android.app.NotificationManager; import android.app.PendingIntent; import android.content.Context; import android.graphics.BitmapFactory; import androidx.core.app.NotificationCompat; import es.ugr.swad.swadroid.utils.NotificationUtils; import static es.ugr.swad.swadroid.utils.NotificationUtils.SWADROID_CHANNEL_ID;
/* * This file is part of SWADroid. * * Copyright (C) 2010 Juan Miguel Boyero Corral <juanmi1982@gmail.com> * * SWADroid is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * SWADroid is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with SWADroid. If not, see <http://www.gnu.org/licenses/>. */ package es.ugr.swad.swadroid.gui; /** * Class for create notification alerts. * * @author Juan Miguel Boyero Corral <juanmi1982@gmail.com> */ public class AlertNotificationFactory { public static NotificationCompat.Builder createAlertNotificationBuilder(Context context, String contentTitle, String contentText, String ticker, PendingIntent pendingIntent, int smallIcon, int largeIcon, boolean autocancel, boolean ongoing, boolean onlyAlertOnce) { int flags = 0;
// Path: SWADroid/src/main/java/es/ugr/swad/swadroid/utils/NotificationUtils.java // @TargetApi(Build.VERSION_CODES.O) // public class NotificationUtils extends ContextWrapper { // // private NotificationManager mManager; // public static final String SWADROID_CHANNEL_ID = "es.ugr.swad.swadroid.SWADROID"; // public static final String SWADROID_CHANNEL_NAME = "SWADROID CHANNEL"; // // public NotificationUtils(Context base) { // super(base); // createChannels(); // } // // public void createChannels() { // // // create SWADroid channel // NotificationChannel androidChannel = new NotificationChannel(SWADROID_CHANNEL_ID, // SWADROID_CHANNEL_NAME, NotificationManager.IMPORTANCE_DEFAULT); // // Sets whether notifications posted to this channel should display notification lights // androidChannel.enableLights(true); // // Sets whether notification posted to this channel should vibrate. // androidChannel.enableVibration(true); // // Sets the notification light color for notifications posted to this channel // androidChannel.setLightColor(Color.GREEN); // // Sets whether notifications posted to this channel appear on the lockscreen or not // androidChannel.setLockscreenVisibility(Notification.VISIBILITY_PUBLIC); // // getManager().createNotificationChannel(androidChannel); // } // // public NotificationManager getManager() { // if (mManager == null) { // mManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE); // } // return mManager; // } // } // // Path: SWADroid/src/main/java/es/ugr/swad/swadroid/utils/NotificationUtils.java // public static final String SWADROID_CHANNEL_ID = "es.ugr.swad.swadroid.SWADROID"; // Path: SWADroid/src/main/java/es/ugr/swad/swadroid/gui/AlertNotificationFactory.java import android.app.Notification; import android.app.NotificationManager; import android.app.PendingIntent; import android.content.Context; import android.graphics.BitmapFactory; import androidx.core.app.NotificationCompat; import es.ugr.swad.swadroid.utils.NotificationUtils; import static es.ugr.swad.swadroid.utils.NotificationUtils.SWADROID_CHANNEL_ID; /* * This file is part of SWADroid. * * Copyright (C) 2010 Juan Miguel Boyero Corral <juanmi1982@gmail.com> * * SWADroid is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * SWADroid is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with SWADroid. If not, see <http://www.gnu.org/licenses/>. */ package es.ugr.swad.swadroid.gui; /** * Class for create notification alerts. * * @author Juan Miguel Boyero Corral <juanmi1982@gmail.com> */ public class AlertNotificationFactory { public static NotificationCompat.Builder createAlertNotificationBuilder(Context context, String contentTitle, String contentText, String ticker, PendingIntent pendingIntent, int smallIcon, int largeIcon, boolean autocancel, boolean ongoing, boolean onlyAlertOnce) { int flags = 0;
NotificationCompat.Builder notifBuilder = new NotificationCompat.Builder(context, SWADROID_CHANNEL_ID)
Amab/SWADroid
SWADroid/src/main/java/es/ugr/swad/swadroid/gui/AlertNotificationFactory.java
// Path: SWADroid/src/main/java/es/ugr/swad/swadroid/utils/NotificationUtils.java // @TargetApi(Build.VERSION_CODES.O) // public class NotificationUtils extends ContextWrapper { // // private NotificationManager mManager; // public static final String SWADROID_CHANNEL_ID = "es.ugr.swad.swadroid.SWADROID"; // public static final String SWADROID_CHANNEL_NAME = "SWADROID CHANNEL"; // // public NotificationUtils(Context base) { // super(base); // createChannels(); // } // // public void createChannels() { // // // create SWADroid channel // NotificationChannel androidChannel = new NotificationChannel(SWADROID_CHANNEL_ID, // SWADROID_CHANNEL_NAME, NotificationManager.IMPORTANCE_DEFAULT); // // Sets whether notifications posted to this channel should display notification lights // androidChannel.enableLights(true); // // Sets whether notification posted to this channel should vibrate. // androidChannel.enableVibration(true); // // Sets the notification light color for notifications posted to this channel // androidChannel.setLightColor(Color.GREEN); // // Sets whether notifications posted to this channel appear on the lockscreen or not // androidChannel.setLockscreenVisibility(Notification.VISIBILITY_PUBLIC); // // getManager().createNotificationChannel(androidChannel); // } // // public NotificationManager getManager() { // if (mManager == null) { // mManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE); // } // return mManager; // } // } // // Path: SWADroid/src/main/java/es/ugr/swad/swadroid/utils/NotificationUtils.java // public static final String SWADROID_CHANNEL_ID = "es.ugr.swad.swadroid.SWADROID";
import android.app.Notification; import android.app.NotificationManager; import android.app.PendingIntent; import android.content.Context; import android.graphics.BitmapFactory; import androidx.core.app.NotificationCompat; import es.ugr.swad.swadroid.utils.NotificationUtils; import static es.ugr.swad.swadroid.utils.NotificationUtils.SWADROID_CHANNEL_ID;
return notifBuilder.build(); } public static Notification createProgressNotification(Context context, String contentTitle, String contentText, String ticker, PendingIntent pendingIntent, int smallIcon, int largeIcon, boolean autocancel, boolean ongoing, boolean onlyAlertOnce, int maxProgress, int progress, boolean indeterminate) { NotificationCompat.Builder notifBuilder = createProgressNotificationBuilder(context, contentTitle, contentText, ticker, pendingIntent, smallIcon, largeIcon, autocancel, ongoing, onlyAlertOnce, maxProgress, progress, indeterminate); //Create alert return notifBuilder.build(); } public static void showAlertNotification(Context context, Notification notif, int notifId) { NotificationManager notifManager; //Obtain a reference to the notification service if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.O) {
// Path: SWADroid/src/main/java/es/ugr/swad/swadroid/utils/NotificationUtils.java // @TargetApi(Build.VERSION_CODES.O) // public class NotificationUtils extends ContextWrapper { // // private NotificationManager mManager; // public static final String SWADROID_CHANNEL_ID = "es.ugr.swad.swadroid.SWADROID"; // public static final String SWADROID_CHANNEL_NAME = "SWADROID CHANNEL"; // // public NotificationUtils(Context base) { // super(base); // createChannels(); // } // // public void createChannels() { // // // create SWADroid channel // NotificationChannel androidChannel = new NotificationChannel(SWADROID_CHANNEL_ID, // SWADROID_CHANNEL_NAME, NotificationManager.IMPORTANCE_DEFAULT); // // Sets whether notifications posted to this channel should display notification lights // androidChannel.enableLights(true); // // Sets whether notification posted to this channel should vibrate. // androidChannel.enableVibration(true); // // Sets the notification light color for notifications posted to this channel // androidChannel.setLightColor(Color.GREEN); // // Sets whether notifications posted to this channel appear on the lockscreen or not // androidChannel.setLockscreenVisibility(Notification.VISIBILITY_PUBLIC); // // getManager().createNotificationChannel(androidChannel); // } // // public NotificationManager getManager() { // if (mManager == null) { // mManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE); // } // return mManager; // } // } // // Path: SWADroid/src/main/java/es/ugr/swad/swadroid/utils/NotificationUtils.java // public static final String SWADROID_CHANNEL_ID = "es.ugr.swad.swadroid.SWADROID"; // Path: SWADroid/src/main/java/es/ugr/swad/swadroid/gui/AlertNotificationFactory.java import android.app.Notification; import android.app.NotificationManager; import android.app.PendingIntent; import android.content.Context; import android.graphics.BitmapFactory; import androidx.core.app.NotificationCompat; import es.ugr.swad.swadroid.utils.NotificationUtils; import static es.ugr.swad.swadroid.utils.NotificationUtils.SWADROID_CHANNEL_ID; return notifBuilder.build(); } public static Notification createProgressNotification(Context context, String contentTitle, String contentText, String ticker, PendingIntent pendingIntent, int smallIcon, int largeIcon, boolean autocancel, boolean ongoing, boolean onlyAlertOnce, int maxProgress, int progress, boolean indeterminate) { NotificationCompat.Builder notifBuilder = createProgressNotificationBuilder(context, contentTitle, contentText, ticker, pendingIntent, smallIcon, largeIcon, autocancel, ongoing, onlyAlertOnce, maxProgress, progress, indeterminate); //Create alert return notifBuilder.build(); } public static void showAlertNotification(Context context, Notification notif, int notifId) { NotificationManager notifManager; //Obtain a reference to the notification service if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.O) {
NotificationUtils mNotificationUtils = new NotificationUtils(context);
sammarshallou/ouaudioapplets
src/uk/ac/open/audio/streaming/StreamPlayerUI.java
// Path: src/uk/ac/open/audio/mp3/MP3Decoder.java // public class MP3Decoder implements StreamableDecoder // { // private Decoder d; // private Bitstream b; // private Header h; // // /** // * Initialises the decoder. // * @param input InputStream used for input data // * @throws AudioException If there is a problem reading the MP3 // */ // public void init(InputStream input) throws AudioException // { // try // { // d = new Decoder(); // if (!input.markSupported()) // { // input = new MarkResetStream(input); // } // b=new Bitstream(input,false); // h=b.readFrame(); // if(h==null) throw new AudioException("Cannot play empty MP3"); // SampleBuffer buffer=new SampleBuffer( // h.frequency(), // h.mode()==Header.SINGLE_CHANNEL ? 1 : 2); // d.setOutputBuffer(buffer); // } // catch(JavaLayerException e) // { // throw new AudioException(e); // } // } // // /** // * Decodes the next frame of the MP3 and returns audio data. This may cause // * the thread to block while waiting for data from the InputStream. // * @return Decoded data in 44.1kHz stereo 16-bit little-endian format; // * or null if MP3 has ended // * @throws AudioException // */ // public byte[] decode() throws AudioException // { // if(h==null) return null; // // try // { // SampleBuffer output=(SampleBuffer)d.decodeFrame(h, b); // short[] data=output.getBuffer(); // int length=output.getBufferLength(); // // // Upsample if required // boolean stereo=output.getChannelCount()==2; // int frequency=output.getSampleFrequency(); // if(frequency!=44100) // { // data=AudioUtil.resample(data,length,stereo,frequency,44100); // length=data.length; // } // // // Convert to bytes for audio output // byte[] byteData=AudioUtil.shortToByte(data, length, !stereo); // // b.closeFrame(); // h=b.readFrame(); // // return byteData; // } // catch(JavaLayerException e) // { // throw new AudioException(e); // } // } // // } // // Path: src/uk/ac/open/audio/streaming/StreamPlayer.java // public enum State // { // /** Downloading but not yet ready to play */ // WAITBEFOREPLAY, // /** Downloaded enough that you should be able to start playing */ // READYTOPLAY, // /** Completely downloaded */ // FULLYLOADED, // /** Fully loaded, but audio buffer is empty */ // BUFFEREMPTY, // /** Closed (no more playback possible) */ // CLOSED // }
import uk.ac.open.audio.mp3.MP3Decoder; import uk.ac.open.audio.streaming.StreamPlayer.State; import java.awt.*; import java.awt.event.*; import java.io.*; import java.net.*; import java.util.LinkedList; import javax.swing.*; import uk.ac.open.audio.*; import uk.ac.open.audio.adpcm.*;
{ if(JOptionPane.showConfirmDialog(this, "Recording again will overwrite your previous recording.", "Confirm record", JOptionPane.OK_CANCEL_OPTION, JOptionPane.WARNING_MESSAGE)!=JOptionPane.OK_OPTION) { return; } } try { doneBeep=false; reallyStop=false; if(playURL!=null) { playback=PlaybackDevice.construct(PlaybackDevice.Format.STEREO_44KHZ, forceCrossPlatform); if(stream==null) { if(connector == null) { progress.setIndeterminate(); boolean mp3=playURL.getPath().endsWith(".mp3"); if(!mp3 && !playURL.getPath().endsWith(".wav")) throw new Exception("Unsupported filetype: only MP3 or WAV permitted"); // Connect to the URL in a different thread. Sometimes, the URL connection // hangs, so this is not safe to do in the UI thread. connector = new Connector(playURL,
// Path: src/uk/ac/open/audio/mp3/MP3Decoder.java // public class MP3Decoder implements StreamableDecoder // { // private Decoder d; // private Bitstream b; // private Header h; // // /** // * Initialises the decoder. // * @param input InputStream used for input data // * @throws AudioException If there is a problem reading the MP3 // */ // public void init(InputStream input) throws AudioException // { // try // { // d = new Decoder(); // if (!input.markSupported()) // { // input = new MarkResetStream(input); // } // b=new Bitstream(input,false); // h=b.readFrame(); // if(h==null) throw new AudioException("Cannot play empty MP3"); // SampleBuffer buffer=new SampleBuffer( // h.frequency(), // h.mode()==Header.SINGLE_CHANNEL ? 1 : 2); // d.setOutputBuffer(buffer); // } // catch(JavaLayerException e) // { // throw new AudioException(e); // } // } // // /** // * Decodes the next frame of the MP3 and returns audio data. This may cause // * the thread to block while waiting for data from the InputStream. // * @return Decoded data in 44.1kHz stereo 16-bit little-endian format; // * or null if MP3 has ended // * @throws AudioException // */ // public byte[] decode() throws AudioException // { // if(h==null) return null; // // try // { // SampleBuffer output=(SampleBuffer)d.decodeFrame(h, b); // short[] data=output.getBuffer(); // int length=output.getBufferLength(); // // // Upsample if required // boolean stereo=output.getChannelCount()==2; // int frequency=output.getSampleFrequency(); // if(frequency!=44100) // { // data=AudioUtil.resample(data,length,stereo,frequency,44100); // length=data.length; // } // // // Convert to bytes for audio output // byte[] byteData=AudioUtil.shortToByte(data, length, !stereo); // // b.closeFrame(); // h=b.readFrame(); // // return byteData; // } // catch(JavaLayerException e) // { // throw new AudioException(e); // } // } // // } // // Path: src/uk/ac/open/audio/streaming/StreamPlayer.java // public enum State // { // /** Downloading but not yet ready to play */ // WAITBEFOREPLAY, // /** Downloaded enough that you should be able to start playing */ // READYTOPLAY, // /** Completely downloaded */ // FULLYLOADED, // /** Fully loaded, but audio buffer is empty */ // BUFFEREMPTY, // /** Closed (no more playback possible) */ // CLOSED // } // Path: src/uk/ac/open/audio/streaming/StreamPlayerUI.java import uk.ac.open.audio.mp3.MP3Decoder; import uk.ac.open.audio.streaming.StreamPlayer.State; import java.awt.*; import java.awt.event.*; import java.io.*; import java.net.*; import java.util.LinkedList; import javax.swing.*; import uk.ac.open.audio.*; import uk.ac.open.audio.adpcm.*; { if(JOptionPane.showConfirmDialog(this, "Recording again will overwrite your previous recording.", "Confirm record", JOptionPane.OK_CANCEL_OPTION, JOptionPane.WARNING_MESSAGE)!=JOptionPane.OK_OPTION) { return; } } try { doneBeep=false; reallyStop=false; if(playURL!=null) { playback=PlaybackDevice.construct(PlaybackDevice.Format.STEREO_44KHZ, forceCrossPlatform); if(stream==null) { if(connector == null) { progress.setIndeterminate(); boolean mp3=playURL.getPath().endsWith(".mp3"); if(!mp3 && !playURL.getPath().endsWith(".wav")) throw new Exception("Unsupported filetype: only MP3 or WAV permitted"); // Connect to the URL in a different thread. Sometimes, the URL connection // hangs, so this is not safe to do in the UI thread. connector = new Connector(playURL,
mp3 ? MP3Decoder.class : ADPCMDecoder.class);
sammarshallou/ouaudioapplets
src/uk/ac/open/audio/streaming/StreamPlayerUI.java
// Path: src/uk/ac/open/audio/mp3/MP3Decoder.java // public class MP3Decoder implements StreamableDecoder // { // private Decoder d; // private Bitstream b; // private Header h; // // /** // * Initialises the decoder. // * @param input InputStream used for input data // * @throws AudioException If there is a problem reading the MP3 // */ // public void init(InputStream input) throws AudioException // { // try // { // d = new Decoder(); // if (!input.markSupported()) // { // input = new MarkResetStream(input); // } // b=new Bitstream(input,false); // h=b.readFrame(); // if(h==null) throw new AudioException("Cannot play empty MP3"); // SampleBuffer buffer=new SampleBuffer( // h.frequency(), // h.mode()==Header.SINGLE_CHANNEL ? 1 : 2); // d.setOutputBuffer(buffer); // } // catch(JavaLayerException e) // { // throw new AudioException(e); // } // } // // /** // * Decodes the next frame of the MP3 and returns audio data. This may cause // * the thread to block while waiting for data from the InputStream. // * @return Decoded data in 44.1kHz stereo 16-bit little-endian format; // * or null if MP3 has ended // * @throws AudioException // */ // public byte[] decode() throws AudioException // { // if(h==null) return null; // // try // { // SampleBuffer output=(SampleBuffer)d.decodeFrame(h, b); // short[] data=output.getBuffer(); // int length=output.getBufferLength(); // // // Upsample if required // boolean stereo=output.getChannelCount()==2; // int frequency=output.getSampleFrequency(); // if(frequency!=44100) // { // data=AudioUtil.resample(data,length,stereo,frequency,44100); // length=data.length; // } // // // Convert to bytes for audio output // byte[] byteData=AudioUtil.shortToByte(data, length, !stereo); // // b.closeFrame(); // h=b.readFrame(); // // return byteData; // } // catch(JavaLayerException e) // { // throw new AudioException(e); // } // } // // } // // Path: src/uk/ac/open/audio/streaming/StreamPlayer.java // public enum State // { // /** Downloading but not yet ready to play */ // WAITBEFOREPLAY, // /** Downloaded enough that you should be able to start playing */ // READYTOPLAY, // /** Completely downloaded */ // FULLYLOADED, // /** Fully loaded, but audio buffer is empty */ // BUFFEREMPTY, // /** Closed (no more playback possible) */ // CLOSED // }
import uk.ac.open.audio.mp3.MP3Decoder; import uk.ac.open.audio.streaming.StreamPlayer.State; import java.awt.*; import java.awt.event.*; import java.io.*; import java.net.*; import java.util.LinkedList; import javax.swing.*; import uk.ac.open.audio.*; import uk.ac.open.audio.adpcm.*;
return; } } try { doneBeep=false; reallyStop=false; if(playURL!=null) { playback=PlaybackDevice.construct(PlaybackDevice.Format.STEREO_44KHZ, forceCrossPlatform); if(stream==null) { if(connector == null) { progress.setIndeterminate(); boolean mp3=playURL.getPath().endsWith(".mp3"); if(!mp3 && !playURL.getPath().endsWith(".wav")) throw new Exception("Unsupported filetype: only MP3 or WAV permitted"); // Connect to the URL in a different thread. Sometimes, the URL connection // hangs, so this is not safe to do in the UI thread. connector = new Connector(playURL, mp3 ? MP3Decoder.class : ADPCMDecoder.class); } } else { streamChangedState(stream.getState());
// Path: src/uk/ac/open/audio/mp3/MP3Decoder.java // public class MP3Decoder implements StreamableDecoder // { // private Decoder d; // private Bitstream b; // private Header h; // // /** // * Initialises the decoder. // * @param input InputStream used for input data // * @throws AudioException If there is a problem reading the MP3 // */ // public void init(InputStream input) throws AudioException // { // try // { // d = new Decoder(); // if (!input.markSupported()) // { // input = new MarkResetStream(input); // } // b=new Bitstream(input,false); // h=b.readFrame(); // if(h==null) throw new AudioException("Cannot play empty MP3"); // SampleBuffer buffer=new SampleBuffer( // h.frequency(), // h.mode()==Header.SINGLE_CHANNEL ? 1 : 2); // d.setOutputBuffer(buffer); // } // catch(JavaLayerException e) // { // throw new AudioException(e); // } // } // // /** // * Decodes the next frame of the MP3 and returns audio data. This may cause // * the thread to block while waiting for data from the InputStream. // * @return Decoded data in 44.1kHz stereo 16-bit little-endian format; // * or null if MP3 has ended // * @throws AudioException // */ // public byte[] decode() throws AudioException // { // if(h==null) return null; // // try // { // SampleBuffer output=(SampleBuffer)d.decodeFrame(h, b); // short[] data=output.getBuffer(); // int length=output.getBufferLength(); // // // Upsample if required // boolean stereo=output.getChannelCount()==2; // int frequency=output.getSampleFrequency(); // if(frequency!=44100) // { // data=AudioUtil.resample(data,length,stereo,frequency,44100); // length=data.length; // } // // // Convert to bytes for audio output // byte[] byteData=AudioUtil.shortToByte(data, length, !stereo); // // b.closeFrame(); // h=b.readFrame(); // // return byteData; // } // catch(JavaLayerException e) // { // throw new AudioException(e); // } // } // // } // // Path: src/uk/ac/open/audio/streaming/StreamPlayer.java // public enum State // { // /** Downloading but not yet ready to play */ // WAITBEFOREPLAY, // /** Downloaded enough that you should be able to start playing */ // READYTOPLAY, // /** Completely downloaded */ // FULLYLOADED, // /** Fully loaded, but audio buffer is empty */ // BUFFEREMPTY, // /** Closed (no more playback possible) */ // CLOSED // } // Path: src/uk/ac/open/audio/streaming/StreamPlayerUI.java import uk.ac.open.audio.mp3.MP3Decoder; import uk.ac.open.audio.streaming.StreamPlayer.State; import java.awt.*; import java.awt.event.*; import java.io.*; import java.net.*; import java.util.LinkedList; import javax.swing.*; import uk.ac.open.audio.*; import uk.ac.open.audio.adpcm.*; return; } } try { doneBeep=false; reallyStop=false; if(playURL!=null) { playback=PlaybackDevice.construct(PlaybackDevice.Format.STEREO_44KHZ, forceCrossPlatform); if(stream==null) { if(connector == null) { progress.setIndeterminate(); boolean mp3=playURL.getPath().endsWith(".mp3"); if(!mp3 && !playURL.getPath().endsWith(".wav")) throw new Exception("Unsupported filetype: only MP3 or WAV permitted"); // Connect to the URL in a different thread. Sometimes, the URL connection // hangs, so this is not safe to do in the UI thread. connector = new Connector(playURL, mp3 ? MP3Decoder.class : ADPCMDecoder.class); } } else { streamChangedState(stream.getState());
if(stream.getState()==State.WAITBEFOREPLAY)
sammarshallou/ouaudioapplets
src/uk/ac/open/audio/streaming/StreamableDecoder.java
// Path: src/uk/ac/open/audio/AudioException.java // public class AudioException extends Exception // { // /** // * @param cause Underlying exception // */ // public AudioException(Throwable cause) // { // super(cause); // } // // /** // * @param message Informational message // */ // public AudioException(String message) // { // super(message); // } // }
import uk.ac.open.audio.AudioException; import java.io.InputStream;
/* Copyright 2009 The Open University http://www.open.ac.uk/lts/projects/audioapplets/ This file is part of the "Open University audio applets" project. The "Open University audio applets" project is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. The "Open University audio applets" project is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with the "Open University audio applets" project. If not, see <http://www.gnu.org/licenses/>. */ package uk.ac.open.audio.streaming; /** * Interface implemented by anything that can stream data. */ public interface StreamableDecoder { /** * Initialises the decoder. This must be called precisely once per decoder. * You cannot reuse a decoder. * @param is Stream containing input data * @throws AudioException If there's any problem */
// Path: src/uk/ac/open/audio/AudioException.java // public class AudioException extends Exception // { // /** // * @param cause Underlying exception // */ // public AudioException(Throwable cause) // { // super(cause); // } // // /** // * @param message Informational message // */ // public AudioException(String message) // { // super(message); // } // } // Path: src/uk/ac/open/audio/streaming/StreamableDecoder.java import uk.ac.open.audio.AudioException; import java.io.InputStream; /* Copyright 2009 The Open University http://www.open.ac.uk/lts/projects/audioapplets/ This file is part of the "Open University audio applets" project. The "Open University audio applets" project is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. The "Open University audio applets" project is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with the "Open University audio applets" project. If not, see <http://www.gnu.org/licenses/>. */ package uk.ac.open.audio.streaming; /** * Interface implemented by anything that can stream data. */ public interface StreamableDecoder { /** * Initialises the decoder. This must be called precisely once per decoder. * You cannot reuse a decoder. * @param is Stream containing input data * @throws AudioException If there's any problem */
public void init(InputStream is) throws AudioException;
sammarshallou/ouaudioapplets
src/uk/ac/open/jlayertest/CompatibilityTest.java
// Path: src/uk/ac/open/audio/AudioException.java // public class AudioException extends Exception // { // /** // * @param cause Underlying exception // */ // public AudioException(Throwable cause) // { // super(cause); // } // // /** // * @param message Informational message // */ // public AudioException(String message) // { // super(message); // } // } // // Path: src/uk/ac/open/audio/mp3/MP3Decoder.java // public class MP3Decoder implements StreamableDecoder // { // private Decoder d; // private Bitstream b; // private Header h; // // /** // * Initialises the decoder. // * @param input InputStream used for input data // * @throws AudioException If there is a problem reading the MP3 // */ // public void init(InputStream input) throws AudioException // { // try // { // d = new Decoder(); // if (!input.markSupported()) // { // input = new MarkResetStream(input); // } // b=new Bitstream(input,false); // h=b.readFrame(); // if(h==null) throw new AudioException("Cannot play empty MP3"); // SampleBuffer buffer=new SampleBuffer( // h.frequency(), // h.mode()==Header.SINGLE_CHANNEL ? 1 : 2); // d.setOutputBuffer(buffer); // } // catch(JavaLayerException e) // { // throw new AudioException(e); // } // } // // /** // * Decodes the next frame of the MP3 and returns audio data. This may cause // * the thread to block while waiting for data from the InputStream. // * @return Decoded data in 44.1kHz stereo 16-bit little-endian format; // * or null if MP3 has ended // * @throws AudioException // */ // public byte[] decode() throws AudioException // { // if(h==null) return null; // // try // { // SampleBuffer output=(SampleBuffer)d.decodeFrame(h, b); // short[] data=output.getBuffer(); // int length=output.getBufferLength(); // // // Upsample if required // boolean stereo=output.getChannelCount()==2; // int frequency=output.getSampleFrequency(); // if(frequency!=44100) // { // data=AudioUtil.resample(data,length,stereo,frequency,44100); // length=data.length; // } // // // Convert to bytes for audio output // byte[] byteData=AudioUtil.shortToByte(data, length, !stereo); // // b.closeFrame(); // h=b.readFrame(); // // return byteData; // } // catch(JavaLayerException e) // { // throw new AudioException(e); // } // } // // }
import java.io.*; import uk.ac.open.audio.AudioException; import uk.ac.open.audio.mp3.MP3Decoder;
File[] files = folder.listFiles(); if(files == null) { return true; } // Loop through files boolean ok = true; for(File file : files) { if(file.isDirectory()) { ok = checkFolder(file) && ok; } else if(file.getName().toLowerCase().endsWith(".mp3")) { ok = checkFile(file) && ok; } } return ok; } private static boolean checkFile(File mp3) throws IOException { try { // Print file path System.out.print(mp3 + ": "); // Now test it...
// Path: src/uk/ac/open/audio/AudioException.java // public class AudioException extends Exception // { // /** // * @param cause Underlying exception // */ // public AudioException(Throwable cause) // { // super(cause); // } // // /** // * @param message Informational message // */ // public AudioException(String message) // { // super(message); // } // } // // Path: src/uk/ac/open/audio/mp3/MP3Decoder.java // public class MP3Decoder implements StreamableDecoder // { // private Decoder d; // private Bitstream b; // private Header h; // // /** // * Initialises the decoder. // * @param input InputStream used for input data // * @throws AudioException If there is a problem reading the MP3 // */ // public void init(InputStream input) throws AudioException // { // try // { // d = new Decoder(); // if (!input.markSupported()) // { // input = new MarkResetStream(input); // } // b=new Bitstream(input,false); // h=b.readFrame(); // if(h==null) throw new AudioException("Cannot play empty MP3"); // SampleBuffer buffer=new SampleBuffer( // h.frequency(), // h.mode()==Header.SINGLE_CHANNEL ? 1 : 2); // d.setOutputBuffer(buffer); // } // catch(JavaLayerException e) // { // throw new AudioException(e); // } // } // // /** // * Decodes the next frame of the MP3 and returns audio data. This may cause // * the thread to block while waiting for data from the InputStream. // * @return Decoded data in 44.1kHz stereo 16-bit little-endian format; // * or null if MP3 has ended // * @throws AudioException // */ // public byte[] decode() throws AudioException // { // if(h==null) return null; // // try // { // SampleBuffer output=(SampleBuffer)d.decodeFrame(h, b); // short[] data=output.getBuffer(); // int length=output.getBufferLength(); // // // Upsample if required // boolean stereo=output.getChannelCount()==2; // int frequency=output.getSampleFrequency(); // if(frequency!=44100) // { // data=AudioUtil.resample(data,length,stereo,frequency,44100); // length=data.length; // } // // // Convert to bytes for audio output // byte[] byteData=AudioUtil.shortToByte(data, length, !stereo); // // b.closeFrame(); // h=b.readFrame(); // // return byteData; // } // catch(JavaLayerException e) // { // throw new AudioException(e); // } // } // // } // Path: src/uk/ac/open/jlayertest/CompatibilityTest.java import java.io.*; import uk.ac.open.audio.AudioException; import uk.ac.open.audio.mp3.MP3Decoder; File[] files = folder.listFiles(); if(files == null) { return true; } // Loop through files boolean ok = true; for(File file : files) { if(file.isDirectory()) { ok = checkFolder(file) && ok; } else if(file.getName().toLowerCase().endsWith(".mp3")) { ok = checkFile(file) && ok; } } return ok; } private static boolean checkFile(File mp3) throws IOException { try { // Print file path System.out.print(mp3 + ": "); // Now test it...
MP3Decoder decoder = new MP3Decoder();
sammarshallou/ouaudioapplets
src/uk/ac/open/jlayertest/CompatibilityTest.java
// Path: src/uk/ac/open/audio/AudioException.java // public class AudioException extends Exception // { // /** // * @param cause Underlying exception // */ // public AudioException(Throwable cause) // { // super(cause); // } // // /** // * @param message Informational message // */ // public AudioException(String message) // { // super(message); // } // } // // Path: src/uk/ac/open/audio/mp3/MP3Decoder.java // public class MP3Decoder implements StreamableDecoder // { // private Decoder d; // private Bitstream b; // private Header h; // // /** // * Initialises the decoder. // * @param input InputStream used for input data // * @throws AudioException If there is a problem reading the MP3 // */ // public void init(InputStream input) throws AudioException // { // try // { // d = new Decoder(); // if (!input.markSupported()) // { // input = new MarkResetStream(input); // } // b=new Bitstream(input,false); // h=b.readFrame(); // if(h==null) throw new AudioException("Cannot play empty MP3"); // SampleBuffer buffer=new SampleBuffer( // h.frequency(), // h.mode()==Header.SINGLE_CHANNEL ? 1 : 2); // d.setOutputBuffer(buffer); // } // catch(JavaLayerException e) // { // throw new AudioException(e); // } // } // // /** // * Decodes the next frame of the MP3 and returns audio data. This may cause // * the thread to block while waiting for data from the InputStream. // * @return Decoded data in 44.1kHz stereo 16-bit little-endian format; // * or null if MP3 has ended // * @throws AudioException // */ // public byte[] decode() throws AudioException // { // if(h==null) return null; // // try // { // SampleBuffer output=(SampleBuffer)d.decodeFrame(h, b); // short[] data=output.getBuffer(); // int length=output.getBufferLength(); // // // Upsample if required // boolean stereo=output.getChannelCount()==2; // int frequency=output.getSampleFrequency(); // if(frequency!=44100) // { // data=AudioUtil.resample(data,length,stereo,frequency,44100); // length=data.length; // } // // // Convert to bytes for audio output // byte[] byteData=AudioUtil.shortToByte(data, length, !stereo); // // b.closeFrame(); // h=b.readFrame(); // // return byteData; // } // catch(JavaLayerException e) // { // throw new AudioException(e); // } // } // // }
import java.io.*; import uk.ac.open.audio.AudioException; import uk.ac.open.audio.mp3.MP3Decoder;
} else if(file.getName().toLowerCase().endsWith(".mp3")) { ok = checkFile(file) && ok; } } return ok; } private static boolean checkFile(File mp3) throws IOException { try { // Print file path System.out.print(mp3 + ": "); // Now test it... MP3Decoder decoder = new MP3Decoder(); decoder.init(new FileInputStream(mp3)); while(true) { byte[] data = decoder.decode(); if(data == null) { break; } } System.out.print("OK"); return true; }
// Path: src/uk/ac/open/audio/AudioException.java // public class AudioException extends Exception // { // /** // * @param cause Underlying exception // */ // public AudioException(Throwable cause) // { // super(cause); // } // // /** // * @param message Informational message // */ // public AudioException(String message) // { // super(message); // } // } // // Path: src/uk/ac/open/audio/mp3/MP3Decoder.java // public class MP3Decoder implements StreamableDecoder // { // private Decoder d; // private Bitstream b; // private Header h; // // /** // * Initialises the decoder. // * @param input InputStream used for input data // * @throws AudioException If there is a problem reading the MP3 // */ // public void init(InputStream input) throws AudioException // { // try // { // d = new Decoder(); // if (!input.markSupported()) // { // input = new MarkResetStream(input); // } // b=new Bitstream(input,false); // h=b.readFrame(); // if(h==null) throw new AudioException("Cannot play empty MP3"); // SampleBuffer buffer=new SampleBuffer( // h.frequency(), // h.mode()==Header.SINGLE_CHANNEL ? 1 : 2); // d.setOutputBuffer(buffer); // } // catch(JavaLayerException e) // { // throw new AudioException(e); // } // } // // /** // * Decodes the next frame of the MP3 and returns audio data. This may cause // * the thread to block while waiting for data from the InputStream. // * @return Decoded data in 44.1kHz stereo 16-bit little-endian format; // * or null if MP3 has ended // * @throws AudioException // */ // public byte[] decode() throws AudioException // { // if(h==null) return null; // // try // { // SampleBuffer output=(SampleBuffer)d.decodeFrame(h, b); // short[] data=output.getBuffer(); // int length=output.getBufferLength(); // // // Upsample if required // boolean stereo=output.getChannelCount()==2; // int frequency=output.getSampleFrequency(); // if(frequency!=44100) // { // data=AudioUtil.resample(data,length,stereo,frequency,44100); // length=data.length; // } // // // Convert to bytes for audio output // byte[] byteData=AudioUtil.shortToByte(data, length, !stereo); // // b.closeFrame(); // h=b.readFrame(); // // return byteData; // } // catch(JavaLayerException e) // { // throw new AudioException(e); // } // } // // } // Path: src/uk/ac/open/jlayertest/CompatibilityTest.java import java.io.*; import uk.ac.open.audio.AudioException; import uk.ac.open.audio.mp3.MP3Decoder; } else if(file.getName().toLowerCase().endsWith(".mp3")) { ok = checkFile(file) && ok; } } return ok; } private static boolean checkFile(File mp3) throws IOException { try { // Print file path System.out.print(mp3 + ": "); // Now test it... MP3Decoder decoder = new MP3Decoder(); decoder.init(new FileInputStream(mp3)); while(true) { byte[] data = decoder.decode(); if(data == null) { break; } } System.out.print("OK"); return true; }
catch(AudioException e)
sammarshallou/ouaudioapplets
src/uk/ac/open/audiorecorder/ErrorPage.java
// Path: src/uk/ac/open/audio/AudioException.java // public class AudioException extends Exception // { // /** // * @param cause Underlying exception // */ // public AudioException(Throwable cause) // { // super(cause); // } // // /** // * @param message Informational message // */ // public AudioException(String message) // { // super(message); // } // }
import java.awt.*; import java.awt.event.*; import java.io.*; import java.text.DateFormat; import java.util.Date; import javax.swing.*; import uk.ac.open.audio.AudioException;
/* Copyright 2009 The Open University http://www.open.ac.uk/lts/projects/audioapplets/ This file is part of the "Open University audio applets" project. The "Open University audio applets" project is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. The "Open University audio applets" project is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with the "Open University audio applets" project. If not, see <http://www.gnu.org/licenses/>. */ package uk.ac.open.audiorecorder; /** * Page displays applet errors. */ class ErrorPage extends JPanel { private static final long serialVersionUID=1L; /** * @param t Error that occurred */ ErrorPage(Throwable t) { super(new BorderLayout(0,8)); setBackground(Color.WHITE); JPanel upper=new JPanel(new BorderLayout(0,8)); upper.setOpaque(false); add(upper,BorderLayout.NORTH); JLabel headingLabel = new FLabel(FontType.HEADING, "An error has occurred"); upper.add(headingLabel,BorderLayout.NORTH);
// Path: src/uk/ac/open/audio/AudioException.java // public class AudioException extends Exception // { // /** // * @param cause Underlying exception // */ // public AudioException(Throwable cause) // { // super(cause); // } // // /** // * @param message Informational message // */ // public AudioException(String message) // { // super(message); // } // } // Path: src/uk/ac/open/audiorecorder/ErrorPage.java import java.awt.*; import java.awt.event.*; import java.io.*; import java.text.DateFormat; import java.util.Date; import javax.swing.*; import uk.ac.open.audio.AudioException; /* Copyright 2009 The Open University http://www.open.ac.uk/lts/projects/audioapplets/ This file is part of the "Open University audio applets" project. The "Open University audio applets" project is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. The "Open University audio applets" project is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with the "Open University audio applets" project. If not, see <http://www.gnu.org/licenses/>. */ package uk.ac.open.audiorecorder; /** * Page displays applet errors. */ class ErrorPage extends JPanel { private static final long serialVersionUID=1L; /** * @param t Error that occurred */ ErrorPage(Throwable t) { super(new BorderLayout(0,8)); setBackground(Color.WHITE); JPanel upper=new JPanel(new BorderLayout(0,8)); upper.setOpaque(false); add(upper,BorderLayout.NORTH); JLabel headingLabel = new FLabel(FontType.HEADING, "An error has occurred"); upper.add(headingLabel,BorderLayout.NORTH);
if((t instanceof AudioException) &&
sammarshallou/ouaudioapplets
src/uk/ac/open/audio/streaming/StreamPlayer.java
// Path: src/uk/ac/open/audio/streaming/StreamPlayer.java // public enum State // { // /** Downloading but not yet ready to play */ // WAITBEFOREPLAY, // /** Downloaded enough that you should be able to start playing */ // READYTOPLAY, // /** Completely downloaded */ // FULLYLOADED, // /** Fully loaded, but audio buffer is empty */ // BUFFEREMPTY, // /** Closed (no more playback possible) */ // CLOSED // }
import java.awt.*; import java.io.*; import java.util.*; import uk.ac.open.audio.*; import static uk.ac.open.audio.streaming.StreamPlayer.State.*;
* Displays an error message in standard format. * @param message Message * @param detail If true, only logs when detailed logging is on */ private static void log(String message, boolean detail) { if(detail && !DETAILED_LOG) { return; } System.err.println("[uk.ac.open.audio.streaming.StreamPlayer] " + message); } private final Class<? extends StreamableDecoder> decoderClass; private final LinkedList<DataBlock> data=new LinkedList<DataBlock>(); private boolean downloadFinished=false,playFinished=false; private long lastBlock; private final LinkedList<AudioBlock> nextAudio=new LinkedList<AudioBlock>(); private boolean isFromMemory; // Current statistics private final int length; private int totalSamplesDecoded,firstFrameBytes,firstFrameSamples; private double averageBytesPerSecondPlayback=0.0; private double recentBytesPerSecondDownload=0.0; private boolean close; /** States that the stream can be in. */
// Path: src/uk/ac/open/audio/streaming/StreamPlayer.java // public enum State // { // /** Downloading but not yet ready to play */ // WAITBEFOREPLAY, // /** Downloaded enough that you should be able to start playing */ // READYTOPLAY, // /** Completely downloaded */ // FULLYLOADED, // /** Fully loaded, but audio buffer is empty */ // BUFFEREMPTY, // /** Closed (no more playback possible) */ // CLOSED // } // Path: src/uk/ac/open/audio/streaming/StreamPlayer.java import java.awt.*; import java.io.*; import java.util.*; import uk.ac.open.audio.*; import static uk.ac.open.audio.streaming.StreamPlayer.State.*; * Displays an error message in standard format. * @param message Message * @param detail If true, only logs when detailed logging is on */ private static void log(String message, boolean detail) { if(detail && !DETAILED_LOG) { return; } System.err.println("[uk.ac.open.audio.streaming.StreamPlayer] " + message); } private final Class<? extends StreamableDecoder> decoderClass; private final LinkedList<DataBlock> data=new LinkedList<DataBlock>(); private boolean downloadFinished=false,playFinished=false; private long lastBlock; private final LinkedList<AudioBlock> nextAudio=new LinkedList<AudioBlock>(); private boolean isFromMemory; // Current statistics private final int length; private int totalSamplesDecoded,firstFrameBytes,firstFrameSamples; private double averageBytesPerSecondPlayback=0.0; private double recentBytesPerSecondDownload=0.0; private boolean close; /** States that the stream can be in. */
public enum State
sammarshallou/ouaudioapplets
src/uk/ac/open/audiorecorder/PageBase.java
// Path: src/uk/ac/open/audio/adpcm/ADPCMRecording.java // public class ADPCMRecording // { // private LinkedList<ADPCMEncoder.Block> blocks=new LinkedList<ADPCMEncoder.Block>(); // // /** // * Adds a block to the end of the recording. // * @param block Block data // */ // public synchronized void addBlock(ADPCMEncoder.Block block) // { // blocks.addLast(block); // } // // /** // * Clears the recording. // */ // public synchronized void clear() // { // blocks.clear(); // } // // /** // * @return Total recording time in milliseconds // */ // public synchronized int getTime() // { // return (ADPCMEncoder.BLOCKSAMPLES*blocks.size())/16; // } // // /** // * @param index Block that we want start time of // * @return Start time of that block in milliseconds since start of file // */ // public static int getBlockTime(int index) // { // return (ADPCMEncoder.BLOCKSAMPLES*index)/16; // } // // /** // * Obtains a range of blocks for display or output. // * @param start First block to retrieve // * @param count Number of blocks // * @return Requested blocks (or fewer if there weren't enough available) // */ // public synchronized ADPCMEncoder.Block[] getBlocks(int start,int count) // { // if(start+count>blocks.size()) count=blocks.size()-start; // ADPCMEncoder.Block[] result=new ADPCMEncoder.Block[count]; // // Iterator<ADPCMEncoder.Block> i=blocks.iterator(); // for(int skip=0;skip<start;skip++) i.next(); // for(int dest=0;dest<count;dest++) // { // result[dest]=i.next(); // } // return result; // } // // /** // * Obtains all blocks for display or output. // * @return Array of all blocks // */ // public synchronized ADPCMEncoder.Block[] getBlocks() // { // return blocks.toArray(new ADPCMEncoder.Block[blocks.size()]); // } // // /** // * Saves data as a .wav file. // * @param f Target for saving // * @throws IOException Any I/O errors // */ // public synchronized void save(File f) throws IOException // { // ADPCMEncoder.writeToWav(getBlocks(0,blocks.size()), f); // } // // } // // Path: src/uk/ac/open/tabapplet/TabAppletFocuser.java // public interface TabAppletFocuser // { // /** // * Called from JavaScript. Initialises focus for the applet. // * @param last True to focus the last thing, false for the first // */ // public void initFocus(boolean last); // }
import java.awt.BorderLayout; import java.awt.event.*; import javax.swing.*; import uk.ac.open.audio.adpcm.ADPCMRecording; import uk.ac.open.tabapplet.TabAppletFocuser;
case FOCUS_LEFT1: focusButton=left1Button; break; case FOCUS_LEFT2: focusButton=left2Button; break; default: focusButton=null; } SwingUtilities.invokeLater(new Runnable() { public void run() { if(focusButton!=null && focusButton.isShowing()) { getRootPane().setDefaultButton(focusButton); focusButton.requestFocus(); } } }); } /** Called when page is left. */ protected void leave() { } /** @return Owner panel */ protected MainPanel getOwner() { return owner; } /** @return Current recording */
// Path: src/uk/ac/open/audio/adpcm/ADPCMRecording.java // public class ADPCMRecording // { // private LinkedList<ADPCMEncoder.Block> blocks=new LinkedList<ADPCMEncoder.Block>(); // // /** // * Adds a block to the end of the recording. // * @param block Block data // */ // public synchronized void addBlock(ADPCMEncoder.Block block) // { // blocks.addLast(block); // } // // /** // * Clears the recording. // */ // public synchronized void clear() // { // blocks.clear(); // } // // /** // * @return Total recording time in milliseconds // */ // public synchronized int getTime() // { // return (ADPCMEncoder.BLOCKSAMPLES*blocks.size())/16; // } // // /** // * @param index Block that we want start time of // * @return Start time of that block in milliseconds since start of file // */ // public static int getBlockTime(int index) // { // return (ADPCMEncoder.BLOCKSAMPLES*index)/16; // } // // /** // * Obtains a range of blocks for display or output. // * @param start First block to retrieve // * @param count Number of blocks // * @return Requested blocks (or fewer if there weren't enough available) // */ // public synchronized ADPCMEncoder.Block[] getBlocks(int start,int count) // { // if(start+count>blocks.size()) count=blocks.size()-start; // ADPCMEncoder.Block[] result=new ADPCMEncoder.Block[count]; // // Iterator<ADPCMEncoder.Block> i=blocks.iterator(); // for(int skip=0;skip<start;skip++) i.next(); // for(int dest=0;dest<count;dest++) // { // result[dest]=i.next(); // } // return result; // } // // /** // * Obtains all blocks for display or output. // * @return Array of all blocks // */ // public synchronized ADPCMEncoder.Block[] getBlocks() // { // return blocks.toArray(new ADPCMEncoder.Block[blocks.size()]); // } // // /** // * Saves data as a .wav file. // * @param f Target for saving // * @throws IOException Any I/O errors // */ // public synchronized void save(File f) throws IOException // { // ADPCMEncoder.writeToWav(getBlocks(0,blocks.size()), f); // } // // } // // Path: src/uk/ac/open/tabapplet/TabAppletFocuser.java // public interface TabAppletFocuser // { // /** // * Called from JavaScript. Initialises focus for the applet. // * @param last True to focus the last thing, false for the first // */ // public void initFocus(boolean last); // } // Path: src/uk/ac/open/audiorecorder/PageBase.java import java.awt.BorderLayout; import java.awt.event.*; import javax.swing.*; import uk.ac.open.audio.adpcm.ADPCMRecording; import uk.ac.open.tabapplet.TabAppletFocuser; case FOCUS_LEFT1: focusButton=left1Button; break; case FOCUS_LEFT2: focusButton=left2Button; break; default: focusButton=null; } SwingUtilities.invokeLater(new Runnable() { public void run() { if(focusButton!=null && focusButton.isShowing()) { getRootPane().setDefaultButton(focusButton); focusButton.requestFocus(); } } }); } /** Called when page is left. */ protected void leave() { } /** @return Owner panel */ protected MainPanel getOwner() { return owner; } /** @return Current recording */
protected ADPCMRecording getRecording()
interdroid/interdroid-swan
src/interdroid/swan/sensors/AbstractConfigurationActivity.java
// Path: src/interdroid/swan/swansong/ExpressionFactory.java // public class ExpressionFactory { // // public static Expression parse(String parseString) // throws ExpressionParseException { // return SwanExpressionParser.parseExpression(parseString); // } // // } // // Path: src/interdroid/swan/swansong/SensorValueExpression.java // public class SensorValueExpression implements ValueExpression { // // private String mLocation; // private String mEntity; // private String mValuePath; // private Bundle mConfig; // private HistoryReductionMode mMode; // private long mHistoryLength; // // public SensorValueExpression(String location, String entity, // String valuePath, Bundle config, HistoryReductionMode mode, // long historyLength) { // mLocation = location; // mEntity = entity; // mValuePath = valuePath; // mConfig = config; // if (mConfig == null) { // mConfig = new Bundle(); // } // mMode = mode; // mHistoryLength = historyLength; // } // // @Override // public HistoryReductionMode getHistoryReductionMode() { // return mMode; // } // // public long getHistoryLength() { // return mHistoryLength; // } // // @Override // public String toParseString() { // String result = mLocation + "@" + mEntity + ":" + mValuePath; // if (mConfig != null && mConfig.size() > 0) { // boolean first = true; // for (String key : mConfig.keySet()) { // String value = "" + mConfig.get(key); // if (mConfig.get(key) instanceof String) { // value = "'" + value + "'"; // } // result += (first ? "?" : "&") + key + "=" + value; // first = false; // } // } // result += "{" + mMode.toParseString() + "," + mHistoryLength + "}"; // return result; // } // // public String getEntity() { // return mEntity; // } // // @Override // public void setInferredLocation(String location) { // throw new RuntimeException( // "Please don't use this method. For internal use only."); // } // // public String getValuePath() { // return mValuePath; // } // // public String getLocation() { // return mLocation; // } // // public Bundle getConfiguration() { // return mConfig; // } // // }
import interdroid.swan.swansong.ExpressionFactory; import interdroid.swan.swansong.ExpressionParseException; import interdroid.swan.swansong.HistoryReductionMode; import interdroid.swan.swansong.SensorValueExpression; import java.util.ArrayList; import java.util.List; import java.util.Map; import android.content.BroadcastReceiver; import android.content.Context; import android.content.Intent; import android.content.IntentFilter; import android.os.Bundle; import android.preference.EditTextPreference; import android.preference.ListPreference; import android.preference.Preference; import android.preference.Preference.OnPreferenceChangeListener; import android.preference.PreferenceActivity; import android.preference.PreferenceGroup; import android.preference.PreferenceManager; import android.util.Log;
package interdroid.swan.sensors; /** * Base for ConfigurationActivities for configuring sensors. * * @author nick &lt;palmer@cs.vu.nl&gt; * */ public abstract class AbstractConfigurationActivity extends PreferenceActivity implements OnPreferenceChangeListener { private static final String TAG = AbstractConfigurationActivity.class .getSimpleName(); private static final long SECOND = 1000; private static final long MINUTE = 60 * SECOND; private static final long HOUR = 60 * MINUTE; /** * Returns the id for the sensors preferences XML setup. * * @return the id for the preferences XML */ public abstract int getPreferencesXML(); private List<String> keys = new ArrayList<String>(); private BroadcastReceiver mNameReceiver = new BroadcastReceiver() { @SuppressWarnings("deprecation") @Override public void onReceive(Context context, Intent intent) { List<String> names = intent.getStringArrayListExtra("names"); names.add(0, "self"); ((ListPreference) findPreference("swan_location")).setEntries(names .toArray(new String[names.size()])); ((ListPreference) findPreference("swan_location")) .setEntryValues(names.toArray(new String[names.size()])); intentToPrefs(); } }; @Override protected void onCreate(final Bundle savedInstanceState) { super.onCreate(savedInstanceState); } private void intentToPrefs() { if (getIntent().hasExtra("expression")) { try {
// Path: src/interdroid/swan/swansong/ExpressionFactory.java // public class ExpressionFactory { // // public static Expression parse(String parseString) // throws ExpressionParseException { // return SwanExpressionParser.parseExpression(parseString); // } // // } // // Path: src/interdroid/swan/swansong/SensorValueExpression.java // public class SensorValueExpression implements ValueExpression { // // private String mLocation; // private String mEntity; // private String mValuePath; // private Bundle mConfig; // private HistoryReductionMode mMode; // private long mHistoryLength; // // public SensorValueExpression(String location, String entity, // String valuePath, Bundle config, HistoryReductionMode mode, // long historyLength) { // mLocation = location; // mEntity = entity; // mValuePath = valuePath; // mConfig = config; // if (mConfig == null) { // mConfig = new Bundle(); // } // mMode = mode; // mHistoryLength = historyLength; // } // // @Override // public HistoryReductionMode getHistoryReductionMode() { // return mMode; // } // // public long getHistoryLength() { // return mHistoryLength; // } // // @Override // public String toParseString() { // String result = mLocation + "@" + mEntity + ":" + mValuePath; // if (mConfig != null && mConfig.size() > 0) { // boolean first = true; // for (String key : mConfig.keySet()) { // String value = "" + mConfig.get(key); // if (mConfig.get(key) instanceof String) { // value = "'" + value + "'"; // } // result += (first ? "?" : "&") + key + "=" + value; // first = false; // } // } // result += "{" + mMode.toParseString() + "," + mHistoryLength + "}"; // return result; // } // // public String getEntity() { // return mEntity; // } // // @Override // public void setInferredLocation(String location) { // throw new RuntimeException( // "Please don't use this method. For internal use only."); // } // // public String getValuePath() { // return mValuePath; // } // // public String getLocation() { // return mLocation; // } // // public Bundle getConfiguration() { // return mConfig; // } // // } // Path: src/interdroid/swan/sensors/AbstractConfigurationActivity.java import interdroid.swan.swansong.ExpressionFactory; import interdroid.swan.swansong.ExpressionParseException; import interdroid.swan.swansong.HistoryReductionMode; import interdroid.swan.swansong.SensorValueExpression; import java.util.ArrayList; import java.util.List; import java.util.Map; import android.content.BroadcastReceiver; import android.content.Context; import android.content.Intent; import android.content.IntentFilter; import android.os.Bundle; import android.preference.EditTextPreference; import android.preference.ListPreference; import android.preference.Preference; import android.preference.Preference.OnPreferenceChangeListener; import android.preference.PreferenceActivity; import android.preference.PreferenceGroup; import android.preference.PreferenceManager; import android.util.Log; package interdroid.swan.sensors; /** * Base for ConfigurationActivities for configuring sensors. * * @author nick &lt;palmer@cs.vu.nl&gt; * */ public abstract class AbstractConfigurationActivity extends PreferenceActivity implements OnPreferenceChangeListener { private static final String TAG = AbstractConfigurationActivity.class .getSimpleName(); private static final long SECOND = 1000; private static final long MINUTE = 60 * SECOND; private static final long HOUR = 60 * MINUTE; /** * Returns the id for the sensors preferences XML setup. * * @return the id for the preferences XML */ public abstract int getPreferencesXML(); private List<String> keys = new ArrayList<String>(); private BroadcastReceiver mNameReceiver = new BroadcastReceiver() { @SuppressWarnings("deprecation") @Override public void onReceive(Context context, Intent intent) { List<String> names = intent.getStringArrayListExtra("names"); names.add(0, "self"); ((ListPreference) findPreference("swan_location")).setEntries(names .toArray(new String[names.size()])); ((ListPreference) findPreference("swan_location")) .setEntryValues(names.toArray(new String[names.size()])); intentToPrefs(); } }; @Override protected void onCreate(final Bundle savedInstanceState) { super.onCreate(savedInstanceState); } private void intentToPrefs() { if (getIntent().hasExtra("expression")) { try {
SensorValueExpression sensor = (SensorValueExpression) ExpressionFactory
interdroid/interdroid-swan
src/interdroid/swan/sensors/AbstractConfigurationActivity.java
// Path: src/interdroid/swan/swansong/ExpressionFactory.java // public class ExpressionFactory { // // public static Expression parse(String parseString) // throws ExpressionParseException { // return SwanExpressionParser.parseExpression(parseString); // } // // } // // Path: src/interdroid/swan/swansong/SensorValueExpression.java // public class SensorValueExpression implements ValueExpression { // // private String mLocation; // private String mEntity; // private String mValuePath; // private Bundle mConfig; // private HistoryReductionMode mMode; // private long mHistoryLength; // // public SensorValueExpression(String location, String entity, // String valuePath, Bundle config, HistoryReductionMode mode, // long historyLength) { // mLocation = location; // mEntity = entity; // mValuePath = valuePath; // mConfig = config; // if (mConfig == null) { // mConfig = new Bundle(); // } // mMode = mode; // mHistoryLength = historyLength; // } // // @Override // public HistoryReductionMode getHistoryReductionMode() { // return mMode; // } // // public long getHistoryLength() { // return mHistoryLength; // } // // @Override // public String toParseString() { // String result = mLocation + "@" + mEntity + ":" + mValuePath; // if (mConfig != null && mConfig.size() > 0) { // boolean first = true; // for (String key : mConfig.keySet()) { // String value = "" + mConfig.get(key); // if (mConfig.get(key) instanceof String) { // value = "'" + value + "'"; // } // result += (first ? "?" : "&") + key + "=" + value; // first = false; // } // } // result += "{" + mMode.toParseString() + "," + mHistoryLength + "}"; // return result; // } // // public String getEntity() { // return mEntity; // } // // @Override // public void setInferredLocation(String location) { // throw new RuntimeException( // "Please don't use this method. For internal use only."); // } // // public String getValuePath() { // return mValuePath; // } // // public String getLocation() { // return mLocation; // } // // public Bundle getConfiguration() { // return mConfig; // } // // }
import interdroid.swan.swansong.ExpressionFactory; import interdroid.swan.swansong.ExpressionParseException; import interdroid.swan.swansong.HistoryReductionMode; import interdroid.swan.swansong.SensorValueExpression; import java.util.ArrayList; import java.util.List; import java.util.Map; import android.content.BroadcastReceiver; import android.content.Context; import android.content.Intent; import android.content.IntentFilter; import android.os.Bundle; import android.preference.EditTextPreference; import android.preference.ListPreference; import android.preference.Preference; import android.preference.Preference.OnPreferenceChangeListener; import android.preference.PreferenceActivity; import android.preference.PreferenceGroup; import android.preference.PreferenceManager; import android.util.Log;
package interdroid.swan.sensors; /** * Base for ConfigurationActivities for configuring sensors. * * @author nick &lt;palmer@cs.vu.nl&gt; * */ public abstract class AbstractConfigurationActivity extends PreferenceActivity implements OnPreferenceChangeListener { private static final String TAG = AbstractConfigurationActivity.class .getSimpleName(); private static final long SECOND = 1000; private static final long MINUTE = 60 * SECOND; private static final long HOUR = 60 * MINUTE; /** * Returns the id for the sensors preferences XML setup. * * @return the id for the preferences XML */ public abstract int getPreferencesXML(); private List<String> keys = new ArrayList<String>(); private BroadcastReceiver mNameReceiver = new BroadcastReceiver() { @SuppressWarnings("deprecation") @Override public void onReceive(Context context, Intent intent) { List<String> names = intent.getStringArrayListExtra("names"); names.add(0, "self"); ((ListPreference) findPreference("swan_location")).setEntries(names .toArray(new String[names.size()])); ((ListPreference) findPreference("swan_location")) .setEntryValues(names.toArray(new String[names.size()])); intentToPrefs(); } }; @Override protected void onCreate(final Bundle savedInstanceState) { super.onCreate(savedInstanceState); } private void intentToPrefs() { if (getIntent().hasExtra("expression")) { try {
// Path: src/interdroid/swan/swansong/ExpressionFactory.java // public class ExpressionFactory { // // public static Expression parse(String parseString) // throws ExpressionParseException { // return SwanExpressionParser.parseExpression(parseString); // } // // } // // Path: src/interdroid/swan/swansong/SensorValueExpression.java // public class SensorValueExpression implements ValueExpression { // // private String mLocation; // private String mEntity; // private String mValuePath; // private Bundle mConfig; // private HistoryReductionMode mMode; // private long mHistoryLength; // // public SensorValueExpression(String location, String entity, // String valuePath, Bundle config, HistoryReductionMode mode, // long historyLength) { // mLocation = location; // mEntity = entity; // mValuePath = valuePath; // mConfig = config; // if (mConfig == null) { // mConfig = new Bundle(); // } // mMode = mode; // mHistoryLength = historyLength; // } // // @Override // public HistoryReductionMode getHistoryReductionMode() { // return mMode; // } // // public long getHistoryLength() { // return mHistoryLength; // } // // @Override // public String toParseString() { // String result = mLocation + "@" + mEntity + ":" + mValuePath; // if (mConfig != null && mConfig.size() > 0) { // boolean first = true; // for (String key : mConfig.keySet()) { // String value = "" + mConfig.get(key); // if (mConfig.get(key) instanceof String) { // value = "'" + value + "'"; // } // result += (first ? "?" : "&") + key + "=" + value; // first = false; // } // } // result += "{" + mMode.toParseString() + "," + mHistoryLength + "}"; // return result; // } // // public String getEntity() { // return mEntity; // } // // @Override // public void setInferredLocation(String location) { // throw new RuntimeException( // "Please don't use this method. For internal use only."); // } // // public String getValuePath() { // return mValuePath; // } // // public String getLocation() { // return mLocation; // } // // public Bundle getConfiguration() { // return mConfig; // } // // } // Path: src/interdroid/swan/sensors/AbstractConfigurationActivity.java import interdroid.swan.swansong.ExpressionFactory; import interdroid.swan.swansong.ExpressionParseException; import interdroid.swan.swansong.HistoryReductionMode; import interdroid.swan.swansong.SensorValueExpression; import java.util.ArrayList; import java.util.List; import java.util.Map; import android.content.BroadcastReceiver; import android.content.Context; import android.content.Intent; import android.content.IntentFilter; import android.os.Bundle; import android.preference.EditTextPreference; import android.preference.ListPreference; import android.preference.Preference; import android.preference.Preference.OnPreferenceChangeListener; import android.preference.PreferenceActivity; import android.preference.PreferenceGroup; import android.preference.PreferenceManager; import android.util.Log; package interdroid.swan.sensors; /** * Base for ConfigurationActivities for configuring sensors. * * @author nick &lt;palmer@cs.vu.nl&gt; * */ public abstract class AbstractConfigurationActivity extends PreferenceActivity implements OnPreferenceChangeListener { private static final String TAG = AbstractConfigurationActivity.class .getSimpleName(); private static final long SECOND = 1000; private static final long MINUTE = 60 * SECOND; private static final long HOUR = 60 * MINUTE; /** * Returns the id for the sensors preferences XML setup. * * @return the id for the preferences XML */ public abstract int getPreferencesXML(); private List<String> keys = new ArrayList<String>(); private BroadcastReceiver mNameReceiver = new BroadcastReceiver() { @SuppressWarnings("deprecation") @Override public void onReceive(Context context, Intent intent) { List<String> names = intent.getStringArrayListExtra("names"); names.add(0, "self"); ((ListPreference) findPreference("swan_location")).setEntries(names .toArray(new String[names.size()])); ((ListPreference) findPreference("swan_location")) .setEntryValues(names.toArray(new String[names.size()])); intentToPrefs(); } }; @Override protected void onCreate(final Bundle savedInstanceState) { super.onCreate(savedInstanceState); } private void intentToPrefs() { if (getIntent().hasExtra("expression")) { try {
SensorValueExpression sensor = (SensorValueExpression) ExpressionFactory
HarryXR/SimpleNews
app/src/main/java/com/lauren/simplenews/news/view/NewsView.java
// Path: app/src/main/java/com/lauren/simplenews/beans/NewsBean.java // public class NewsBean implements Serializable { // // /** // * docid // */ // public String docid; // /** // * 标题 // */ // public String title; // /** // * 小内容 // */ // public String digest; // /** // * 图片地址 // */ // public String imgsrc; // /** // * 来源 // */ // public String source; // /** // * 时间 // */ // public String ptime; // /** // * TAG // */ // private String tag; // // public String url; // // }
import com.lauren.simplenews.beans.NewsBean; import java.util.List;
package com.lauren.simplenews.news.view; /** * Description : * Author : lauren * Email : lauren.liuling@gmail.com * Blog : http://www.liuling123.com * Date : 15/12/18 */ public interface NewsView { void showProgress();
// Path: app/src/main/java/com/lauren/simplenews/beans/NewsBean.java // public class NewsBean implements Serializable { // // /** // * docid // */ // public String docid; // /** // * 标题 // */ // public String title; // /** // * 小内容 // */ // public String digest; // /** // * 图片地址 // */ // public String imgsrc; // /** // * 来源 // */ // public String source; // /** // * 时间 // */ // public String ptime; // /** // * TAG // */ // private String tag; // // public String url; // // } // Path: app/src/main/java/com/lauren/simplenews/news/view/NewsView.java import com.lauren.simplenews.beans.NewsBean; import java.util.List; package com.lauren.simplenews.news.view; /** * Description : * Author : lauren * Email : lauren.liuling@gmail.com * Blog : http://www.liuling123.com * Date : 15/12/18 */ public interface NewsView { void showProgress();
void addNews(List<NewsBean> newsList);
HarryXR/SimpleNews
app/src/main/java/com/lauren/simplenews/news/NewsJsonUtils.java
// Path: app/src/main/java/com/lauren/simplenews/beans/NewsBean.java // public class NewsBean implements Serializable { // // /** // * docid // */ // public String docid; // /** // * 标题 // */ // public String title; // /** // * 小内容 // */ // public String digest; // /** // * 图片地址 // */ // public String imgsrc; // /** // * 来源 // */ // public String source; // /** // * 时间 // */ // public String ptime; // /** // * TAG // */ // private String tag; // // public String url; // // } // // Path: app/src/main/java/com/lauren/simplenews/beans/NewsDetailBean.java // public class NewsDetailBean implements Serializable { // /** // * docid // */ // private String docid; // /** // * title // */ // private String title; // /** // * source // */ // private String source; // /** // * body // */ // private String body; // /** // * ptime // */ // private String ptime; // /** // * cover // */ // private String cover; // /** // * 图片列表 // */ // private List<String> imgList; // // // public String getDocid() { // return docid; // } // // public void setDocid(String docid) { // this.docid = docid; // } // // public String getTitle() { // return title; // } // // public void setTitle(String title) { // this.title = title; // } // // public String getSource() { // return source; // } // // public void setSource(String source) { // this.source = source; // } // // public String getBody() { // return body; // } // // public void setBody(String body) { // this.body = body; // } // // public String getPtime() { // return ptime; // } // // public void setPtime(String ptime) { // this.ptime = ptime; // } // // public String getCover() { // return cover; // } // // public void setCover(String cover) { // this.cover = cover; // } // // public List<String> getImgList() { // return imgList; // } // // public void setImgList(List<String> imgList) { // this.imgList = imgList; // } // } // // Path: app/src/main/java/com/lauren/simplenews/utils/LogUtils.java // public class LogUtils { // public static final boolean DEBUG = true; // // public static void v(String tag, String message) { // if(DEBUG) { // Log.v(tag, message); // } // } // // public static void d(String tag, String message) { // if(DEBUG) { // Log.d(tag, message); // } // } // // public static void i(String tag, String message) { // if(DEBUG) { // Log.i(tag, message); // } // } // // public static void w(String tag, String message) { // if(DEBUG) { // Log.w(tag, message); // } // } // // public static void e(String tag, String message) { // if(DEBUG) { // Log.e(tag, message); // } // } // // public static void e(String tag, String message, Exception e) { // if(DEBUG) { // Log.e(tag, message, e); // } // } // }
import com.google.gson.Gson; import com.google.gson.JsonElement; import com.google.gson.JsonObject; import com.google.gson.JsonParser; import com.lauren.simplenews.beans.NewsBean; import com.lauren.simplenews.beans.NewsDetailBean; import com.lauren.simplenews.utils.LogUtils; import java.lang.reflect.ParameterizedType; import java.lang.reflect.Type; import java.util.ArrayList; import java.util.List;
package com.lauren.simplenews.news; /** * Description : * Author : lauren * Email : lauren.liuling@gmail.com * Blog : http://www.liuling123.com * Date : 15/12/19 */ public class NewsJsonUtils { private final static String TAG = "NewsJsonUtils"; /** * 将获取到的json转换为新闻列表对象 * * @param res * @param value * * @return */
// Path: app/src/main/java/com/lauren/simplenews/beans/NewsBean.java // public class NewsBean implements Serializable { // // /** // * docid // */ // public String docid; // /** // * 标题 // */ // public String title; // /** // * 小内容 // */ // public String digest; // /** // * 图片地址 // */ // public String imgsrc; // /** // * 来源 // */ // public String source; // /** // * 时间 // */ // public String ptime; // /** // * TAG // */ // private String tag; // // public String url; // // } // // Path: app/src/main/java/com/lauren/simplenews/beans/NewsDetailBean.java // public class NewsDetailBean implements Serializable { // /** // * docid // */ // private String docid; // /** // * title // */ // private String title; // /** // * source // */ // private String source; // /** // * body // */ // private String body; // /** // * ptime // */ // private String ptime; // /** // * cover // */ // private String cover; // /** // * 图片列表 // */ // private List<String> imgList; // // // public String getDocid() { // return docid; // } // // public void setDocid(String docid) { // this.docid = docid; // } // // public String getTitle() { // return title; // } // // public void setTitle(String title) { // this.title = title; // } // // public String getSource() { // return source; // } // // public void setSource(String source) { // this.source = source; // } // // public String getBody() { // return body; // } // // public void setBody(String body) { // this.body = body; // } // // public String getPtime() { // return ptime; // } // // public void setPtime(String ptime) { // this.ptime = ptime; // } // // public String getCover() { // return cover; // } // // public void setCover(String cover) { // this.cover = cover; // } // // public List<String> getImgList() { // return imgList; // } // // public void setImgList(List<String> imgList) { // this.imgList = imgList; // } // } // // Path: app/src/main/java/com/lauren/simplenews/utils/LogUtils.java // public class LogUtils { // public static final boolean DEBUG = true; // // public static void v(String tag, String message) { // if(DEBUG) { // Log.v(tag, message); // } // } // // public static void d(String tag, String message) { // if(DEBUG) { // Log.d(tag, message); // } // } // // public static void i(String tag, String message) { // if(DEBUG) { // Log.i(tag, message); // } // } // // public static void w(String tag, String message) { // if(DEBUG) { // Log.w(tag, message); // } // } // // public static void e(String tag, String message) { // if(DEBUG) { // Log.e(tag, message); // } // } // // public static void e(String tag, String message, Exception e) { // if(DEBUG) { // Log.e(tag, message, e); // } // } // } // Path: app/src/main/java/com/lauren/simplenews/news/NewsJsonUtils.java import com.google.gson.Gson; import com.google.gson.JsonElement; import com.google.gson.JsonObject; import com.google.gson.JsonParser; import com.lauren.simplenews.beans.NewsBean; import com.lauren.simplenews.beans.NewsDetailBean; import com.lauren.simplenews.utils.LogUtils; import java.lang.reflect.ParameterizedType; import java.lang.reflect.Type; import java.util.ArrayList; import java.util.List; package com.lauren.simplenews.news; /** * Description : * Author : lauren * Email : lauren.liuling@gmail.com * Blog : http://www.liuling123.com * Date : 15/12/19 */ public class NewsJsonUtils { private final static String TAG = "NewsJsonUtils"; /** * 将获取到的json转换为新闻列表对象 * * @param res * @param value * * @return */
public static List<NewsBean> readJsonNewsBeans(String res, String value) {
HarryXR/SimpleNews
app/src/main/java/com/lauren/simplenews/news/NewsJsonUtils.java
// Path: app/src/main/java/com/lauren/simplenews/beans/NewsBean.java // public class NewsBean implements Serializable { // // /** // * docid // */ // public String docid; // /** // * 标题 // */ // public String title; // /** // * 小内容 // */ // public String digest; // /** // * 图片地址 // */ // public String imgsrc; // /** // * 来源 // */ // public String source; // /** // * 时间 // */ // public String ptime; // /** // * TAG // */ // private String tag; // // public String url; // // } // // Path: app/src/main/java/com/lauren/simplenews/beans/NewsDetailBean.java // public class NewsDetailBean implements Serializable { // /** // * docid // */ // private String docid; // /** // * title // */ // private String title; // /** // * source // */ // private String source; // /** // * body // */ // private String body; // /** // * ptime // */ // private String ptime; // /** // * cover // */ // private String cover; // /** // * 图片列表 // */ // private List<String> imgList; // // // public String getDocid() { // return docid; // } // // public void setDocid(String docid) { // this.docid = docid; // } // // public String getTitle() { // return title; // } // // public void setTitle(String title) { // this.title = title; // } // // public String getSource() { // return source; // } // // public void setSource(String source) { // this.source = source; // } // // public String getBody() { // return body; // } // // public void setBody(String body) { // this.body = body; // } // // public String getPtime() { // return ptime; // } // // public void setPtime(String ptime) { // this.ptime = ptime; // } // // public String getCover() { // return cover; // } // // public void setCover(String cover) { // this.cover = cover; // } // // public List<String> getImgList() { // return imgList; // } // // public void setImgList(List<String> imgList) { // this.imgList = imgList; // } // } // // Path: app/src/main/java/com/lauren/simplenews/utils/LogUtils.java // public class LogUtils { // public static final boolean DEBUG = true; // // public static void v(String tag, String message) { // if(DEBUG) { // Log.v(tag, message); // } // } // // public static void d(String tag, String message) { // if(DEBUG) { // Log.d(tag, message); // } // } // // public static void i(String tag, String message) { // if(DEBUG) { // Log.i(tag, message); // } // } // // public static void w(String tag, String message) { // if(DEBUG) { // Log.w(tag, message); // } // } // // public static void e(String tag, String message) { // if(DEBUG) { // Log.e(tag, message); // } // } // // public static void e(String tag, String message, Exception e) { // if(DEBUG) { // Log.e(tag, message, e); // } // } // }
import com.google.gson.Gson; import com.google.gson.JsonElement; import com.google.gson.JsonObject; import com.google.gson.JsonParser; import com.lauren.simplenews.beans.NewsBean; import com.lauren.simplenews.beans.NewsDetailBean; import com.lauren.simplenews.utils.LogUtils; import java.lang.reflect.ParameterizedType; import java.lang.reflect.Type; import java.util.ArrayList; import java.util.List;
package com.lauren.simplenews.news; /** * Description : * Author : lauren * Email : lauren.liuling@gmail.com * Blog : http://www.liuling123.com * Date : 15/12/19 */ public class NewsJsonUtils { private final static String TAG = "NewsJsonUtils"; /** * 将获取到的json转换为新闻列表对象 * * @param res * @param value * * @return */ public static List<NewsBean> readJsonNewsBeans(String res, String value) { List<NewsBean> beans = new ArrayList<NewsBean>(); try { JsonParser parser = new JsonParser(); JsonElement element = parser.parse(res); JsonObject jsonObject = element.getAsJsonObject(); JsonElement jsonElement = jsonObject.get(value); beans = new Gson().fromJson(jsonElement, type(List.class, NewsBean.class)); } catch (Exception e) {
// Path: app/src/main/java/com/lauren/simplenews/beans/NewsBean.java // public class NewsBean implements Serializable { // // /** // * docid // */ // public String docid; // /** // * 标题 // */ // public String title; // /** // * 小内容 // */ // public String digest; // /** // * 图片地址 // */ // public String imgsrc; // /** // * 来源 // */ // public String source; // /** // * 时间 // */ // public String ptime; // /** // * TAG // */ // private String tag; // // public String url; // // } // // Path: app/src/main/java/com/lauren/simplenews/beans/NewsDetailBean.java // public class NewsDetailBean implements Serializable { // /** // * docid // */ // private String docid; // /** // * title // */ // private String title; // /** // * source // */ // private String source; // /** // * body // */ // private String body; // /** // * ptime // */ // private String ptime; // /** // * cover // */ // private String cover; // /** // * 图片列表 // */ // private List<String> imgList; // // // public String getDocid() { // return docid; // } // // public void setDocid(String docid) { // this.docid = docid; // } // // public String getTitle() { // return title; // } // // public void setTitle(String title) { // this.title = title; // } // // public String getSource() { // return source; // } // // public void setSource(String source) { // this.source = source; // } // // public String getBody() { // return body; // } // // public void setBody(String body) { // this.body = body; // } // // public String getPtime() { // return ptime; // } // // public void setPtime(String ptime) { // this.ptime = ptime; // } // // public String getCover() { // return cover; // } // // public void setCover(String cover) { // this.cover = cover; // } // // public List<String> getImgList() { // return imgList; // } // // public void setImgList(List<String> imgList) { // this.imgList = imgList; // } // } // // Path: app/src/main/java/com/lauren/simplenews/utils/LogUtils.java // public class LogUtils { // public static final boolean DEBUG = true; // // public static void v(String tag, String message) { // if(DEBUG) { // Log.v(tag, message); // } // } // // public static void d(String tag, String message) { // if(DEBUG) { // Log.d(tag, message); // } // } // // public static void i(String tag, String message) { // if(DEBUG) { // Log.i(tag, message); // } // } // // public static void w(String tag, String message) { // if(DEBUG) { // Log.w(tag, message); // } // } // // public static void e(String tag, String message) { // if(DEBUG) { // Log.e(tag, message); // } // } // // public static void e(String tag, String message, Exception e) { // if(DEBUG) { // Log.e(tag, message, e); // } // } // } // Path: app/src/main/java/com/lauren/simplenews/news/NewsJsonUtils.java import com.google.gson.Gson; import com.google.gson.JsonElement; import com.google.gson.JsonObject; import com.google.gson.JsonParser; import com.lauren.simplenews.beans.NewsBean; import com.lauren.simplenews.beans.NewsDetailBean; import com.lauren.simplenews.utils.LogUtils; import java.lang.reflect.ParameterizedType; import java.lang.reflect.Type; import java.util.ArrayList; import java.util.List; package com.lauren.simplenews.news; /** * Description : * Author : lauren * Email : lauren.liuling@gmail.com * Blog : http://www.liuling123.com * Date : 15/12/19 */ public class NewsJsonUtils { private final static String TAG = "NewsJsonUtils"; /** * 将获取到的json转换为新闻列表对象 * * @param res * @param value * * @return */ public static List<NewsBean> readJsonNewsBeans(String res, String value) { List<NewsBean> beans = new ArrayList<NewsBean>(); try { JsonParser parser = new JsonParser(); JsonElement element = parser.parse(res); JsonObject jsonObject = element.getAsJsonObject(); JsonElement jsonElement = jsonObject.get(value); beans = new Gson().fromJson(jsonElement, type(List.class, NewsBean.class)); } catch (Exception e) {
LogUtils.e(TAG, "readJsonNewsBeans error", e);
HarryXR/SimpleNews
app/src/main/java/com/lauren/simplenews/news/NewsJsonUtils.java
// Path: app/src/main/java/com/lauren/simplenews/beans/NewsBean.java // public class NewsBean implements Serializable { // // /** // * docid // */ // public String docid; // /** // * 标题 // */ // public String title; // /** // * 小内容 // */ // public String digest; // /** // * 图片地址 // */ // public String imgsrc; // /** // * 来源 // */ // public String source; // /** // * 时间 // */ // public String ptime; // /** // * TAG // */ // private String tag; // // public String url; // // } // // Path: app/src/main/java/com/lauren/simplenews/beans/NewsDetailBean.java // public class NewsDetailBean implements Serializable { // /** // * docid // */ // private String docid; // /** // * title // */ // private String title; // /** // * source // */ // private String source; // /** // * body // */ // private String body; // /** // * ptime // */ // private String ptime; // /** // * cover // */ // private String cover; // /** // * 图片列表 // */ // private List<String> imgList; // // // public String getDocid() { // return docid; // } // // public void setDocid(String docid) { // this.docid = docid; // } // // public String getTitle() { // return title; // } // // public void setTitle(String title) { // this.title = title; // } // // public String getSource() { // return source; // } // // public void setSource(String source) { // this.source = source; // } // // public String getBody() { // return body; // } // // public void setBody(String body) { // this.body = body; // } // // public String getPtime() { // return ptime; // } // // public void setPtime(String ptime) { // this.ptime = ptime; // } // // public String getCover() { // return cover; // } // // public void setCover(String cover) { // this.cover = cover; // } // // public List<String> getImgList() { // return imgList; // } // // public void setImgList(List<String> imgList) { // this.imgList = imgList; // } // } // // Path: app/src/main/java/com/lauren/simplenews/utils/LogUtils.java // public class LogUtils { // public static final boolean DEBUG = true; // // public static void v(String tag, String message) { // if(DEBUG) { // Log.v(tag, message); // } // } // // public static void d(String tag, String message) { // if(DEBUG) { // Log.d(tag, message); // } // } // // public static void i(String tag, String message) { // if(DEBUG) { // Log.i(tag, message); // } // } // // public static void w(String tag, String message) { // if(DEBUG) { // Log.w(tag, message); // } // } // // public static void e(String tag, String message) { // if(DEBUG) { // Log.e(tag, message); // } // } // // public static void e(String tag, String message, Exception e) { // if(DEBUG) { // Log.e(tag, message, e); // } // } // }
import com.google.gson.Gson; import com.google.gson.JsonElement; import com.google.gson.JsonObject; import com.google.gson.JsonParser; import com.lauren.simplenews.beans.NewsBean; import com.lauren.simplenews.beans.NewsDetailBean; import com.lauren.simplenews.utils.LogUtils; import java.lang.reflect.ParameterizedType; import java.lang.reflect.Type; import java.util.ArrayList; import java.util.List;
package com.lauren.simplenews.news; /** * Description : * Author : lauren * Email : lauren.liuling@gmail.com * Blog : http://www.liuling123.com * Date : 15/12/19 */ public class NewsJsonUtils { private final static String TAG = "NewsJsonUtils"; /** * 将获取到的json转换为新闻列表对象 * * @param res * @param value * * @return */ public static List<NewsBean> readJsonNewsBeans(String res, String value) { List<NewsBean> beans = new ArrayList<NewsBean>(); try { JsonParser parser = new JsonParser(); JsonElement element = parser.parse(res); JsonObject jsonObject = element.getAsJsonObject(); JsonElement jsonElement = jsonObject.get(value); beans = new Gson().fromJson(jsonElement, type(List.class, NewsBean.class)); } catch (Exception e) { LogUtils.e(TAG, "readJsonNewsBeans error", e); } return beans; } public static ParameterizedType type(final Class raw, final Type... args) { return new ParameterizedType() { public Type getRawType() { return raw; } public Type[] getActualTypeArguments() { return args; } public Type getOwnerType() { return null; } }; }
// Path: app/src/main/java/com/lauren/simplenews/beans/NewsBean.java // public class NewsBean implements Serializable { // // /** // * docid // */ // public String docid; // /** // * 标题 // */ // public String title; // /** // * 小内容 // */ // public String digest; // /** // * 图片地址 // */ // public String imgsrc; // /** // * 来源 // */ // public String source; // /** // * 时间 // */ // public String ptime; // /** // * TAG // */ // private String tag; // // public String url; // // } // // Path: app/src/main/java/com/lauren/simplenews/beans/NewsDetailBean.java // public class NewsDetailBean implements Serializable { // /** // * docid // */ // private String docid; // /** // * title // */ // private String title; // /** // * source // */ // private String source; // /** // * body // */ // private String body; // /** // * ptime // */ // private String ptime; // /** // * cover // */ // private String cover; // /** // * 图片列表 // */ // private List<String> imgList; // // // public String getDocid() { // return docid; // } // // public void setDocid(String docid) { // this.docid = docid; // } // // public String getTitle() { // return title; // } // // public void setTitle(String title) { // this.title = title; // } // // public String getSource() { // return source; // } // // public void setSource(String source) { // this.source = source; // } // // public String getBody() { // return body; // } // // public void setBody(String body) { // this.body = body; // } // // public String getPtime() { // return ptime; // } // // public void setPtime(String ptime) { // this.ptime = ptime; // } // // public String getCover() { // return cover; // } // // public void setCover(String cover) { // this.cover = cover; // } // // public List<String> getImgList() { // return imgList; // } // // public void setImgList(List<String> imgList) { // this.imgList = imgList; // } // } // // Path: app/src/main/java/com/lauren/simplenews/utils/LogUtils.java // public class LogUtils { // public static final boolean DEBUG = true; // // public static void v(String tag, String message) { // if(DEBUG) { // Log.v(tag, message); // } // } // // public static void d(String tag, String message) { // if(DEBUG) { // Log.d(tag, message); // } // } // // public static void i(String tag, String message) { // if(DEBUG) { // Log.i(tag, message); // } // } // // public static void w(String tag, String message) { // if(DEBUG) { // Log.w(tag, message); // } // } // // public static void e(String tag, String message) { // if(DEBUG) { // Log.e(tag, message); // } // } // // public static void e(String tag, String message, Exception e) { // if(DEBUG) { // Log.e(tag, message, e); // } // } // } // Path: app/src/main/java/com/lauren/simplenews/news/NewsJsonUtils.java import com.google.gson.Gson; import com.google.gson.JsonElement; import com.google.gson.JsonObject; import com.google.gson.JsonParser; import com.lauren.simplenews.beans.NewsBean; import com.lauren.simplenews.beans.NewsDetailBean; import com.lauren.simplenews.utils.LogUtils; import java.lang.reflect.ParameterizedType; import java.lang.reflect.Type; import java.util.ArrayList; import java.util.List; package com.lauren.simplenews.news; /** * Description : * Author : lauren * Email : lauren.liuling@gmail.com * Blog : http://www.liuling123.com * Date : 15/12/19 */ public class NewsJsonUtils { private final static String TAG = "NewsJsonUtils"; /** * 将获取到的json转换为新闻列表对象 * * @param res * @param value * * @return */ public static List<NewsBean> readJsonNewsBeans(String res, String value) { List<NewsBean> beans = new ArrayList<NewsBean>(); try { JsonParser parser = new JsonParser(); JsonElement element = parser.parse(res); JsonObject jsonObject = element.getAsJsonObject(); JsonElement jsonElement = jsonObject.get(value); beans = new Gson().fromJson(jsonElement, type(List.class, NewsBean.class)); } catch (Exception e) { LogUtils.e(TAG, "readJsonNewsBeans error", e); } return beans; } public static ParameterizedType type(final Class raw, final Type... args) { return new ParameterizedType() { public Type getRawType() { return raw; } public Type[] getActualTypeArguments() { return args; } public Type getOwnerType() { return null; } }; }
public static NewsDetailBean readJsonNewsDetailBeans(String res, String docId) {
HarryXR/SimpleNews
app/src/main/java/com/lauren/simplenews/weather/widget/WeatherFragment.java
// Path: app/src/main/java/com/lauren/simplenews/beans/WeatherBean.java // public class WeatherBean { // // private static final long serialVersionUID = 1L; // /** // * temperature // */ // private String temperature; // /** // * weather // */ // private String weather; // /** // * wind // */ // private String wind; // /** // * week // */ // private String week; // /** // * date // */ // private String date; // // private int imageRes; // // public String getTemperature() { // return temperature; // } // // public void setTemperature(String temperature) { // this.temperature = temperature; // } // // public String getWeather() { // return weather; // } // // public void setWeather(String weather) { // this.weather = weather; // } // // public String getWind() { // return wind; // } // // public void setWind(String wind) { // this.wind = wind; // } // // public String getWeek() { // return week; // } // // public void setWeek(String week) { // this.week = week; // } // // public String getDate() { // return date; // } // // public void setDate(String date) { // this.date = date; // } // // public int getImageRes() { // return imageRes; // } // // public void setImageRes(int imageRes) { // this.imageRes = imageRes; // } // } // // Path: app/src/main/java/com/lauren/simplenews/weather/presenter/WeatherPresenter.java // public interface WeatherPresenter { // // void loadWeatherData(); // // } // // Path: app/src/main/java/com/lauren/simplenews/weather/presenter/WeatherPresenterImpl.java // public class WeatherPresenterImpl implements WeatherPresenter, WeatherModelImpl.LoadWeatherListener { // // private WeatherView mWeatherView; // private WeatherModel mWeatherModel; // private Context mContext; // // public WeatherPresenterImpl(Context context, WeatherView weatherView) { // this.mContext = context; // this.mWeatherView = weatherView; // mWeatherModel = new WeatherModelImpl(); // } // // @Override // public void loadWeatherData() { // mWeatherView.showProgress(); // if(!ToolsUtil.isNetworkAvailable(mContext)) { // mWeatherView.hideProgress(); // mWeatherView.showErrorToast("无网络连接"); // return; // } // // WeatherModelImpl.LoadLocationListener listener = new WeatherModelImpl.LoadLocationListener() { // @Override // public void onSuccess(String cityName) { // //定位成功,获取定位城市天气预报 // mWeatherView.setCity(cityName); // mWeatherModel.loadWeatherData(cityName, WeatherPresenterImpl.this); // } // // @Override // public void onFailure(String msg, Exception e) { // // mWeatherView.showErrorToast("定位失败"); // mWeatherView.setCity("南京"); // mWeatherModel.loadWeatherData("南京", WeatherPresenterImpl.this); // } // }; // //获取定位信息 // mWeatherModel.loadLocation(mContext, listener); // } // // @Override // public void onSuccess(List<WeatherBean> list) { // if(list != null && list.size() > 0) { // WeatherBean todayWeather = list.remove(0); // mWeatherView.setToday(todayWeather.getDate()); // mWeatherView.setTemperature(todayWeather.getTemperature()); // mWeatherView.setWeather(todayWeather.getWeather()); // mWeatherView.setWind(todayWeather.getWind()); // mWeatherView.setWeatherImage(todayWeather.getImageRes()); // } // mWeatherView.setWeatherData(list); // mWeatherView.hideProgress(); // mWeatherView.showWeatherLayout(); // } // // @Override // public void onFailure(String msg, Exception e) { // mWeatherView.hideProgress(); // mWeatherView.showErrorToast("获取天气数据失败"); // } // // } // // Path: app/src/main/java/com/lauren/simplenews/weather/view/WeatherView.java // public interface WeatherView { // // void showProgress(); // void hideProgress(); // void showWeatherLayout(); // // void setCity(String city); // void setToday(String data); // void setTemperature(String temperature); // void setWind(String wind); // void setWeather(String weather); // void setWeatherImage(int res); // void setWeatherData(List<WeatherBean> lists); // // void showErrorToast(String msg); // // // }
import android.os.Bundle; import android.support.design.widget.Snackbar; import android.app.Fragment; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.FrameLayout; import android.widget.ImageView; import android.widget.LinearLayout; import android.widget.ProgressBar; import android.widget.TextView; import com.lauren.simplenews.R; import com.lauren.simplenews.beans.WeatherBean; import com.lauren.simplenews.weather.presenter.WeatherPresenter; import com.lauren.simplenews.weather.presenter.WeatherPresenterImpl; import com.lauren.simplenews.weather.view.WeatherView; import java.util.ArrayList; import java.util.List;
package com.lauren.simplenews.weather.widget; /** * Description : * Author : lauren * Email : lauren.liuling@gmail.com * Blog : http://www.liuling123.com * Date : 15/12/21 */ public class WeatherFragment extends Fragment implements WeatherView { private WeatherPresenter mWeatherPresenter; private TextView mTodayTV; private ImageView mTodayWeatherImage; private TextView mTodayTemperatureTV; private TextView mTodayWindTV; private TextView mTodayWeatherTV; private TextView mCityTV; private ProgressBar mProgressBar; private LinearLayout mWeatherLayout; private LinearLayout mWeatherContentLayout; private FrameLayout mRootLayout; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState);
// Path: app/src/main/java/com/lauren/simplenews/beans/WeatherBean.java // public class WeatherBean { // // private static final long serialVersionUID = 1L; // /** // * temperature // */ // private String temperature; // /** // * weather // */ // private String weather; // /** // * wind // */ // private String wind; // /** // * week // */ // private String week; // /** // * date // */ // private String date; // // private int imageRes; // // public String getTemperature() { // return temperature; // } // // public void setTemperature(String temperature) { // this.temperature = temperature; // } // // public String getWeather() { // return weather; // } // // public void setWeather(String weather) { // this.weather = weather; // } // // public String getWind() { // return wind; // } // // public void setWind(String wind) { // this.wind = wind; // } // // public String getWeek() { // return week; // } // // public void setWeek(String week) { // this.week = week; // } // // public String getDate() { // return date; // } // // public void setDate(String date) { // this.date = date; // } // // public int getImageRes() { // return imageRes; // } // // public void setImageRes(int imageRes) { // this.imageRes = imageRes; // } // } // // Path: app/src/main/java/com/lauren/simplenews/weather/presenter/WeatherPresenter.java // public interface WeatherPresenter { // // void loadWeatherData(); // // } // // Path: app/src/main/java/com/lauren/simplenews/weather/presenter/WeatherPresenterImpl.java // public class WeatherPresenterImpl implements WeatherPresenter, WeatherModelImpl.LoadWeatherListener { // // private WeatherView mWeatherView; // private WeatherModel mWeatherModel; // private Context mContext; // // public WeatherPresenterImpl(Context context, WeatherView weatherView) { // this.mContext = context; // this.mWeatherView = weatherView; // mWeatherModel = new WeatherModelImpl(); // } // // @Override // public void loadWeatherData() { // mWeatherView.showProgress(); // if(!ToolsUtil.isNetworkAvailable(mContext)) { // mWeatherView.hideProgress(); // mWeatherView.showErrorToast("无网络连接"); // return; // } // // WeatherModelImpl.LoadLocationListener listener = new WeatherModelImpl.LoadLocationListener() { // @Override // public void onSuccess(String cityName) { // //定位成功,获取定位城市天气预报 // mWeatherView.setCity(cityName); // mWeatherModel.loadWeatherData(cityName, WeatherPresenterImpl.this); // } // // @Override // public void onFailure(String msg, Exception e) { // // mWeatherView.showErrorToast("定位失败"); // mWeatherView.setCity("南京"); // mWeatherModel.loadWeatherData("南京", WeatherPresenterImpl.this); // } // }; // //获取定位信息 // mWeatherModel.loadLocation(mContext, listener); // } // // @Override // public void onSuccess(List<WeatherBean> list) { // if(list != null && list.size() > 0) { // WeatherBean todayWeather = list.remove(0); // mWeatherView.setToday(todayWeather.getDate()); // mWeatherView.setTemperature(todayWeather.getTemperature()); // mWeatherView.setWeather(todayWeather.getWeather()); // mWeatherView.setWind(todayWeather.getWind()); // mWeatherView.setWeatherImage(todayWeather.getImageRes()); // } // mWeatherView.setWeatherData(list); // mWeatherView.hideProgress(); // mWeatherView.showWeatherLayout(); // } // // @Override // public void onFailure(String msg, Exception e) { // mWeatherView.hideProgress(); // mWeatherView.showErrorToast("获取天气数据失败"); // } // // } // // Path: app/src/main/java/com/lauren/simplenews/weather/view/WeatherView.java // public interface WeatherView { // // void showProgress(); // void hideProgress(); // void showWeatherLayout(); // // void setCity(String city); // void setToday(String data); // void setTemperature(String temperature); // void setWind(String wind); // void setWeather(String weather); // void setWeatherImage(int res); // void setWeatherData(List<WeatherBean> lists); // // void showErrorToast(String msg); // // // } // Path: app/src/main/java/com/lauren/simplenews/weather/widget/WeatherFragment.java import android.os.Bundle; import android.support.design.widget.Snackbar; import android.app.Fragment; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.FrameLayout; import android.widget.ImageView; import android.widget.LinearLayout; import android.widget.ProgressBar; import android.widget.TextView; import com.lauren.simplenews.R; import com.lauren.simplenews.beans.WeatherBean; import com.lauren.simplenews.weather.presenter.WeatherPresenter; import com.lauren.simplenews.weather.presenter.WeatherPresenterImpl; import com.lauren.simplenews.weather.view.WeatherView; import java.util.ArrayList; import java.util.List; package com.lauren.simplenews.weather.widget; /** * Description : * Author : lauren * Email : lauren.liuling@gmail.com * Blog : http://www.liuling123.com * Date : 15/12/21 */ public class WeatherFragment extends Fragment implements WeatherView { private WeatherPresenter mWeatherPresenter; private TextView mTodayTV; private ImageView mTodayWeatherImage; private TextView mTodayTemperatureTV; private TextView mTodayWindTV; private TextView mTodayWeatherTV; private TextView mCityTV; private ProgressBar mProgressBar; private LinearLayout mWeatherLayout; private LinearLayout mWeatherContentLayout; private FrameLayout mRootLayout; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState);
mWeatherPresenter = new WeatherPresenterImpl(getActivity().getApplication(), this);
HarryXR/SimpleNews
app/src/main/java/com/lauren/simplenews/weather/widget/WeatherFragment.java
// Path: app/src/main/java/com/lauren/simplenews/beans/WeatherBean.java // public class WeatherBean { // // private static final long serialVersionUID = 1L; // /** // * temperature // */ // private String temperature; // /** // * weather // */ // private String weather; // /** // * wind // */ // private String wind; // /** // * week // */ // private String week; // /** // * date // */ // private String date; // // private int imageRes; // // public String getTemperature() { // return temperature; // } // // public void setTemperature(String temperature) { // this.temperature = temperature; // } // // public String getWeather() { // return weather; // } // // public void setWeather(String weather) { // this.weather = weather; // } // // public String getWind() { // return wind; // } // // public void setWind(String wind) { // this.wind = wind; // } // // public String getWeek() { // return week; // } // // public void setWeek(String week) { // this.week = week; // } // // public String getDate() { // return date; // } // // public void setDate(String date) { // this.date = date; // } // // public int getImageRes() { // return imageRes; // } // // public void setImageRes(int imageRes) { // this.imageRes = imageRes; // } // } // // Path: app/src/main/java/com/lauren/simplenews/weather/presenter/WeatherPresenter.java // public interface WeatherPresenter { // // void loadWeatherData(); // // } // // Path: app/src/main/java/com/lauren/simplenews/weather/presenter/WeatherPresenterImpl.java // public class WeatherPresenterImpl implements WeatherPresenter, WeatherModelImpl.LoadWeatherListener { // // private WeatherView mWeatherView; // private WeatherModel mWeatherModel; // private Context mContext; // // public WeatherPresenterImpl(Context context, WeatherView weatherView) { // this.mContext = context; // this.mWeatherView = weatherView; // mWeatherModel = new WeatherModelImpl(); // } // // @Override // public void loadWeatherData() { // mWeatherView.showProgress(); // if(!ToolsUtil.isNetworkAvailable(mContext)) { // mWeatherView.hideProgress(); // mWeatherView.showErrorToast("无网络连接"); // return; // } // // WeatherModelImpl.LoadLocationListener listener = new WeatherModelImpl.LoadLocationListener() { // @Override // public void onSuccess(String cityName) { // //定位成功,获取定位城市天气预报 // mWeatherView.setCity(cityName); // mWeatherModel.loadWeatherData(cityName, WeatherPresenterImpl.this); // } // // @Override // public void onFailure(String msg, Exception e) { // // mWeatherView.showErrorToast("定位失败"); // mWeatherView.setCity("南京"); // mWeatherModel.loadWeatherData("南京", WeatherPresenterImpl.this); // } // }; // //获取定位信息 // mWeatherModel.loadLocation(mContext, listener); // } // // @Override // public void onSuccess(List<WeatherBean> list) { // if(list != null && list.size() > 0) { // WeatherBean todayWeather = list.remove(0); // mWeatherView.setToday(todayWeather.getDate()); // mWeatherView.setTemperature(todayWeather.getTemperature()); // mWeatherView.setWeather(todayWeather.getWeather()); // mWeatherView.setWind(todayWeather.getWind()); // mWeatherView.setWeatherImage(todayWeather.getImageRes()); // } // mWeatherView.setWeatherData(list); // mWeatherView.hideProgress(); // mWeatherView.showWeatherLayout(); // } // // @Override // public void onFailure(String msg, Exception e) { // mWeatherView.hideProgress(); // mWeatherView.showErrorToast("获取天气数据失败"); // } // // } // // Path: app/src/main/java/com/lauren/simplenews/weather/view/WeatherView.java // public interface WeatherView { // // void showProgress(); // void hideProgress(); // void showWeatherLayout(); // // void setCity(String city); // void setToday(String data); // void setTemperature(String temperature); // void setWind(String wind); // void setWeather(String weather); // void setWeatherImage(int res); // void setWeatherData(List<WeatherBean> lists); // // void showErrorToast(String msg); // // // }
import android.os.Bundle; import android.support.design.widget.Snackbar; import android.app.Fragment; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.FrameLayout; import android.widget.ImageView; import android.widget.LinearLayout; import android.widget.ProgressBar; import android.widget.TextView; import com.lauren.simplenews.R; import com.lauren.simplenews.beans.WeatherBean; import com.lauren.simplenews.weather.presenter.WeatherPresenter; import com.lauren.simplenews.weather.presenter.WeatherPresenterImpl; import com.lauren.simplenews.weather.view.WeatherView; import java.util.ArrayList; import java.util.List;
public void setCity(String city) { mCityTV.setText(city); } @Override public void setToday(String data) { mTodayTV.setText(data); } @Override public void setTemperature(String temperature) { mTodayTemperatureTV.setText(temperature); } @Override public void setWind(String wind) { mTodayWindTV.setText(wind); } @Override public void setWeather(String weather) { mTodayWeatherTV.setText(weather); } @Override public void setWeatherImage(int res) { mTodayWeatherImage.setImageResource(res); } @Override
// Path: app/src/main/java/com/lauren/simplenews/beans/WeatherBean.java // public class WeatherBean { // // private static final long serialVersionUID = 1L; // /** // * temperature // */ // private String temperature; // /** // * weather // */ // private String weather; // /** // * wind // */ // private String wind; // /** // * week // */ // private String week; // /** // * date // */ // private String date; // // private int imageRes; // // public String getTemperature() { // return temperature; // } // // public void setTemperature(String temperature) { // this.temperature = temperature; // } // // public String getWeather() { // return weather; // } // // public void setWeather(String weather) { // this.weather = weather; // } // // public String getWind() { // return wind; // } // // public void setWind(String wind) { // this.wind = wind; // } // // public String getWeek() { // return week; // } // // public void setWeek(String week) { // this.week = week; // } // // public String getDate() { // return date; // } // // public void setDate(String date) { // this.date = date; // } // // public int getImageRes() { // return imageRes; // } // // public void setImageRes(int imageRes) { // this.imageRes = imageRes; // } // } // // Path: app/src/main/java/com/lauren/simplenews/weather/presenter/WeatherPresenter.java // public interface WeatherPresenter { // // void loadWeatherData(); // // } // // Path: app/src/main/java/com/lauren/simplenews/weather/presenter/WeatherPresenterImpl.java // public class WeatherPresenterImpl implements WeatherPresenter, WeatherModelImpl.LoadWeatherListener { // // private WeatherView mWeatherView; // private WeatherModel mWeatherModel; // private Context mContext; // // public WeatherPresenterImpl(Context context, WeatherView weatherView) { // this.mContext = context; // this.mWeatherView = weatherView; // mWeatherModel = new WeatherModelImpl(); // } // // @Override // public void loadWeatherData() { // mWeatherView.showProgress(); // if(!ToolsUtil.isNetworkAvailable(mContext)) { // mWeatherView.hideProgress(); // mWeatherView.showErrorToast("无网络连接"); // return; // } // // WeatherModelImpl.LoadLocationListener listener = new WeatherModelImpl.LoadLocationListener() { // @Override // public void onSuccess(String cityName) { // //定位成功,获取定位城市天气预报 // mWeatherView.setCity(cityName); // mWeatherModel.loadWeatherData(cityName, WeatherPresenterImpl.this); // } // // @Override // public void onFailure(String msg, Exception e) { // // mWeatherView.showErrorToast("定位失败"); // mWeatherView.setCity("南京"); // mWeatherModel.loadWeatherData("南京", WeatherPresenterImpl.this); // } // }; // //获取定位信息 // mWeatherModel.loadLocation(mContext, listener); // } // // @Override // public void onSuccess(List<WeatherBean> list) { // if(list != null && list.size() > 0) { // WeatherBean todayWeather = list.remove(0); // mWeatherView.setToday(todayWeather.getDate()); // mWeatherView.setTemperature(todayWeather.getTemperature()); // mWeatherView.setWeather(todayWeather.getWeather()); // mWeatherView.setWind(todayWeather.getWind()); // mWeatherView.setWeatherImage(todayWeather.getImageRes()); // } // mWeatherView.setWeatherData(list); // mWeatherView.hideProgress(); // mWeatherView.showWeatherLayout(); // } // // @Override // public void onFailure(String msg, Exception e) { // mWeatherView.hideProgress(); // mWeatherView.showErrorToast("获取天气数据失败"); // } // // } // // Path: app/src/main/java/com/lauren/simplenews/weather/view/WeatherView.java // public interface WeatherView { // // void showProgress(); // void hideProgress(); // void showWeatherLayout(); // // void setCity(String city); // void setToday(String data); // void setTemperature(String temperature); // void setWind(String wind); // void setWeather(String weather); // void setWeatherImage(int res); // void setWeatherData(List<WeatherBean> lists); // // void showErrorToast(String msg); // // // } // Path: app/src/main/java/com/lauren/simplenews/weather/widget/WeatherFragment.java import android.os.Bundle; import android.support.design.widget.Snackbar; import android.app.Fragment; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.FrameLayout; import android.widget.ImageView; import android.widget.LinearLayout; import android.widget.ProgressBar; import android.widget.TextView; import com.lauren.simplenews.R; import com.lauren.simplenews.beans.WeatherBean; import com.lauren.simplenews.weather.presenter.WeatherPresenter; import com.lauren.simplenews.weather.presenter.WeatherPresenterImpl; import com.lauren.simplenews.weather.view.WeatherView; import java.util.ArrayList; import java.util.List; public void setCity(String city) { mCityTV.setText(city); } @Override public void setToday(String data) { mTodayTV.setText(data); } @Override public void setTemperature(String temperature) { mTodayTemperatureTV.setText(temperature); } @Override public void setWind(String wind) { mTodayWindTV.setText(wind); } @Override public void setWeather(String weather) { mTodayWeatherTV.setText(weather); } @Override public void setWeatherImage(int res) { mTodayWeatherImage.setImageResource(res); } @Override
public void setWeatherData(List<WeatherBean> lists) {
HarryXR/SimpleNews
app/src/main/java/com/lauren/simplenews/weather/WeatherJsonUtils.java
// Path: app/src/main/java/com/lauren/simplenews/beans/WeatherBean.java // public class WeatherBean { // // private static final long serialVersionUID = 1L; // /** // * temperature // */ // private String temperature; // /** // * weather // */ // private String weather; // /** // * wind // */ // private String wind; // /** // * week // */ // private String week; // /** // * date // */ // private String date; // // private int imageRes; // // public String getTemperature() { // return temperature; // } // // public void setTemperature(String temperature) { // this.temperature = temperature; // } // // public String getWeather() { // return weather; // } // // public void setWeather(String weather) { // this.weather = weather; // } // // public String getWind() { // return wind; // } // // public void setWind(String wind) { // this.wind = wind; // } // // public String getWeek() { // return week; // } // // public void setWeek(String week) { // this.week = week; // } // // public String getDate() { // return date; // } // // public void setDate(String date) { // this.date = date; // } // // public int getImageRes() { // return imageRes; // } // // public void setImageRes(int imageRes) { // this.imageRes = imageRes; // } // }
import android.text.TextUtils; import com.google.gson.JsonArray; import com.google.gson.JsonElement; import com.google.gson.JsonObject; import com.google.gson.JsonParser; import com.lauren.simplenews.R; import com.lauren.simplenews.beans.WeatherBean; import java.util.ArrayList; import java.util.List;
package com.lauren.simplenews.weather; /** * Description : * Author : lauren * Email : lauren.liuling@gmail.com * Blog : http://www.liuling123.com * Date : 2015/12/22 */ public class WeatherJsonUtils { /** * 从定位的json字串中获取城市 * @param json * @return */ public static String getCity(String json) { JsonParser parser = new JsonParser(); JsonObject jsonObj = parser.parse(json).getAsJsonObject(); JsonElement status = jsonObj.get("status"); if(status != null && "OK".equals(status.getAsString())) { JsonObject result = jsonObj.getAsJsonObject("result"); if(result != null) { JsonObject addressComponent = result.getAsJsonObject("addressComponent"); if(addressComponent != null) { JsonElement cityElement = addressComponent.get("city"); if(cityElement != null) { return cityElement.getAsString().replace("市", ""); } } } } return null; } /** * 获取天气信息 * @param json * @return */
// Path: app/src/main/java/com/lauren/simplenews/beans/WeatherBean.java // public class WeatherBean { // // private static final long serialVersionUID = 1L; // /** // * temperature // */ // private String temperature; // /** // * weather // */ // private String weather; // /** // * wind // */ // private String wind; // /** // * week // */ // private String week; // /** // * date // */ // private String date; // // private int imageRes; // // public String getTemperature() { // return temperature; // } // // public void setTemperature(String temperature) { // this.temperature = temperature; // } // // public String getWeather() { // return weather; // } // // public void setWeather(String weather) { // this.weather = weather; // } // // public String getWind() { // return wind; // } // // public void setWind(String wind) { // this.wind = wind; // } // // public String getWeek() { // return week; // } // // public void setWeek(String week) { // this.week = week; // } // // public String getDate() { // return date; // } // // public void setDate(String date) { // this.date = date; // } // // public int getImageRes() { // return imageRes; // } // // public void setImageRes(int imageRes) { // this.imageRes = imageRes; // } // } // Path: app/src/main/java/com/lauren/simplenews/weather/WeatherJsonUtils.java import android.text.TextUtils; import com.google.gson.JsonArray; import com.google.gson.JsonElement; import com.google.gson.JsonObject; import com.google.gson.JsonParser; import com.lauren.simplenews.R; import com.lauren.simplenews.beans.WeatherBean; import java.util.ArrayList; import java.util.List; package com.lauren.simplenews.weather; /** * Description : * Author : lauren * Email : lauren.liuling@gmail.com * Blog : http://www.liuling123.com * Date : 2015/12/22 */ public class WeatherJsonUtils { /** * 从定位的json字串中获取城市 * @param json * @return */ public static String getCity(String json) { JsonParser parser = new JsonParser(); JsonObject jsonObj = parser.parse(json).getAsJsonObject(); JsonElement status = jsonObj.get("status"); if(status != null && "OK".equals(status.getAsString())) { JsonObject result = jsonObj.getAsJsonObject("result"); if(result != null) { JsonObject addressComponent = result.getAsJsonObject("addressComponent"); if(addressComponent != null) { JsonElement cityElement = addressComponent.get("city"); if(cityElement != null) { return cityElement.getAsString().replace("市", ""); } } } } return null; } /** * 获取天气信息 * @param json * @return */
public static List<WeatherBean> getWeatherInfo(String json) {
HarryXR/SimpleNews
app/src/main/java/com/lauren/simplenews/weather/view/WeatherView.java
// Path: app/src/main/java/com/lauren/simplenews/beans/WeatherBean.java // public class WeatherBean { // // private static final long serialVersionUID = 1L; // /** // * temperature // */ // private String temperature; // /** // * weather // */ // private String weather; // /** // * wind // */ // private String wind; // /** // * week // */ // private String week; // /** // * date // */ // private String date; // // private int imageRes; // // public String getTemperature() { // return temperature; // } // // public void setTemperature(String temperature) { // this.temperature = temperature; // } // // public String getWeather() { // return weather; // } // // public void setWeather(String weather) { // this.weather = weather; // } // // public String getWind() { // return wind; // } // // public void setWind(String wind) { // this.wind = wind; // } // // public String getWeek() { // return week; // } // // public void setWeek(String week) { // this.week = week; // } // // public String getDate() { // return date; // } // // public void setDate(String date) { // this.date = date; // } // // public int getImageRes() { // return imageRes; // } // // public void setImageRes(int imageRes) { // this.imageRes = imageRes; // } // }
import com.lauren.simplenews.beans.WeatherBean; import java.util.List;
package com.lauren.simplenews.weather.view; /** * Description : * Author : lauren * Email : lauren.liuling@gmail.com * Blog : http://www.liuling123.com * Date : 2015/12/22 */ public interface WeatherView { void showProgress(); void hideProgress(); void showWeatherLayout(); void setCity(String city); void setToday(String data); void setTemperature(String temperature); void setWind(String wind); void setWeather(String weather); void setWeatherImage(int res);
// Path: app/src/main/java/com/lauren/simplenews/beans/WeatherBean.java // public class WeatherBean { // // private static final long serialVersionUID = 1L; // /** // * temperature // */ // private String temperature; // /** // * weather // */ // private String weather; // /** // * wind // */ // private String wind; // /** // * week // */ // private String week; // /** // * date // */ // private String date; // // private int imageRes; // // public String getTemperature() { // return temperature; // } // // public void setTemperature(String temperature) { // this.temperature = temperature; // } // // public String getWeather() { // return weather; // } // // public void setWeather(String weather) { // this.weather = weather; // } // // public String getWind() { // return wind; // } // // public void setWind(String wind) { // this.wind = wind; // } // // public String getWeek() { // return week; // } // // public void setWeek(String week) { // this.week = week; // } // // public String getDate() { // return date; // } // // public void setDate(String date) { // this.date = date; // } // // public int getImageRes() { // return imageRes; // } // // public void setImageRes(int imageRes) { // this.imageRes = imageRes; // } // } // Path: app/src/main/java/com/lauren/simplenews/weather/view/WeatherView.java import com.lauren.simplenews.beans.WeatherBean; import java.util.List; package com.lauren.simplenews.weather.view; /** * Description : * Author : lauren * Email : lauren.liuling@gmail.com * Blog : http://www.liuling123.com * Date : 2015/12/22 */ public interface WeatherView { void showProgress(); void hideProgress(); void showWeatherLayout(); void setCity(String city); void setToday(String data); void setTemperature(String temperature); void setWind(String wind); void setWeather(String weather); void setWeatherImage(int res);
void setWeatherData(List<WeatherBean> lists);
HarryXR/SimpleNews
app/src/main/java/com/lauren/simplenews/images/presenter/ImagePresenterImpl.java
// Path: app/src/main/java/com/lauren/simplenews/beans/ImageBean.java // public class ImageBean implements Serializable { // // private static final long serialVersionUID = 1L; // // private String title; // private String thumburl; // private String sourceurl; // private int height; // private int width; // // public String getTitle() { // return title; // } // // public void setTitle(String title) { // this.title = title; // } // // public String getThumburl() { // return thumburl; // } // // public void setThumburl(String thumburl) { // this.thumburl = thumburl; // } // // public String getSourceurl() { // return sourceurl; // } // // public void setSourceurl(String sourceurl) { // this.sourceurl = sourceurl; // } // // public int getHeight() { // return height; // } // // public void setHeight(int height) { // this.height = height; // } // // public int getWidth() { // return width; // } // // public void setWidth(int width) { // this.width = width; // } // } // // Path: app/src/main/java/com/lauren/simplenews/images/model/ImageModel.java // public interface ImageModel { // void loadImageList(ImageModelImpl.OnLoadImageListListener listener); // } // // Path: app/src/main/java/com/lauren/simplenews/images/model/ImageModelImpl.java // public class ImageModelImpl implements ImageModel { // // /** // * 获取图片列表 // * @param listener // */ // @Override // public void loadImageList(final OnLoadImageListListener listener) { // String url = Urls.IMAGES_URL; // OkHttpUtils.ResultCallback<String> loadNewsCallback = new OkHttpUtils.ResultCallback<String>() { // @Override // public void onSuccess(String response) { // List<ImageBean> iamgeBeanList = ImageJsonUtils.readJsonImageBeans(response); // listener.onSuccess(iamgeBeanList); // } // // @Override // public void onFailure(Exception e) { // listener.onFailure("load image list failure.", e); // } // }; // OkHttpUtils.get(url, loadNewsCallback); // } // // public interface OnLoadImageListListener { // void onSuccess(List<ImageBean> list); // void onFailure(String msg, Exception e); // } // } // // Path: app/src/main/java/com/lauren/simplenews/images/view/ImageView.java // public interface ImageView { // void addImages(List<ImageBean> list); // void showProgress(); // void hideProgress(); // void showLoadFailMsg(); // }
import com.lauren.simplenews.beans.ImageBean; import com.lauren.simplenews.images.model.ImageModel; import com.lauren.simplenews.images.model.ImageModelImpl; import com.lauren.simplenews.images.view.ImageView; import java.util.List;
package com.lauren.simplenews.images.presenter; /** * Description : * Author : lauren * Email : lauren.liuling@gmail.com * Blog : http://www.liuling123.com * Date : 15/12/22 */ public class ImagePresenterImpl implements ImagePresenter, ImageModelImpl.OnLoadImageListListener { private ImageModel mImageModel;
// Path: app/src/main/java/com/lauren/simplenews/beans/ImageBean.java // public class ImageBean implements Serializable { // // private static final long serialVersionUID = 1L; // // private String title; // private String thumburl; // private String sourceurl; // private int height; // private int width; // // public String getTitle() { // return title; // } // // public void setTitle(String title) { // this.title = title; // } // // public String getThumburl() { // return thumburl; // } // // public void setThumburl(String thumburl) { // this.thumburl = thumburl; // } // // public String getSourceurl() { // return sourceurl; // } // // public void setSourceurl(String sourceurl) { // this.sourceurl = sourceurl; // } // // public int getHeight() { // return height; // } // // public void setHeight(int height) { // this.height = height; // } // // public int getWidth() { // return width; // } // // public void setWidth(int width) { // this.width = width; // } // } // // Path: app/src/main/java/com/lauren/simplenews/images/model/ImageModel.java // public interface ImageModel { // void loadImageList(ImageModelImpl.OnLoadImageListListener listener); // } // // Path: app/src/main/java/com/lauren/simplenews/images/model/ImageModelImpl.java // public class ImageModelImpl implements ImageModel { // // /** // * 获取图片列表 // * @param listener // */ // @Override // public void loadImageList(final OnLoadImageListListener listener) { // String url = Urls.IMAGES_URL; // OkHttpUtils.ResultCallback<String> loadNewsCallback = new OkHttpUtils.ResultCallback<String>() { // @Override // public void onSuccess(String response) { // List<ImageBean> iamgeBeanList = ImageJsonUtils.readJsonImageBeans(response); // listener.onSuccess(iamgeBeanList); // } // // @Override // public void onFailure(Exception e) { // listener.onFailure("load image list failure.", e); // } // }; // OkHttpUtils.get(url, loadNewsCallback); // } // // public interface OnLoadImageListListener { // void onSuccess(List<ImageBean> list); // void onFailure(String msg, Exception e); // } // } // // Path: app/src/main/java/com/lauren/simplenews/images/view/ImageView.java // public interface ImageView { // void addImages(List<ImageBean> list); // void showProgress(); // void hideProgress(); // void showLoadFailMsg(); // } // Path: app/src/main/java/com/lauren/simplenews/images/presenter/ImagePresenterImpl.java import com.lauren.simplenews.beans.ImageBean; import com.lauren.simplenews.images.model.ImageModel; import com.lauren.simplenews.images.model.ImageModelImpl; import com.lauren.simplenews.images.view.ImageView; import java.util.List; package com.lauren.simplenews.images.presenter; /** * Description : * Author : lauren * Email : lauren.liuling@gmail.com * Blog : http://www.liuling123.com * Date : 15/12/22 */ public class ImagePresenterImpl implements ImagePresenter, ImageModelImpl.OnLoadImageListListener { private ImageModel mImageModel;
private ImageView mImageView;
HarryXR/SimpleNews
app/src/main/java/com/lauren/simplenews/images/presenter/ImagePresenterImpl.java
// Path: app/src/main/java/com/lauren/simplenews/beans/ImageBean.java // public class ImageBean implements Serializable { // // private static final long serialVersionUID = 1L; // // private String title; // private String thumburl; // private String sourceurl; // private int height; // private int width; // // public String getTitle() { // return title; // } // // public void setTitle(String title) { // this.title = title; // } // // public String getThumburl() { // return thumburl; // } // // public void setThumburl(String thumburl) { // this.thumburl = thumburl; // } // // public String getSourceurl() { // return sourceurl; // } // // public void setSourceurl(String sourceurl) { // this.sourceurl = sourceurl; // } // // public int getHeight() { // return height; // } // // public void setHeight(int height) { // this.height = height; // } // // public int getWidth() { // return width; // } // // public void setWidth(int width) { // this.width = width; // } // } // // Path: app/src/main/java/com/lauren/simplenews/images/model/ImageModel.java // public interface ImageModel { // void loadImageList(ImageModelImpl.OnLoadImageListListener listener); // } // // Path: app/src/main/java/com/lauren/simplenews/images/model/ImageModelImpl.java // public class ImageModelImpl implements ImageModel { // // /** // * 获取图片列表 // * @param listener // */ // @Override // public void loadImageList(final OnLoadImageListListener listener) { // String url = Urls.IMAGES_URL; // OkHttpUtils.ResultCallback<String> loadNewsCallback = new OkHttpUtils.ResultCallback<String>() { // @Override // public void onSuccess(String response) { // List<ImageBean> iamgeBeanList = ImageJsonUtils.readJsonImageBeans(response); // listener.onSuccess(iamgeBeanList); // } // // @Override // public void onFailure(Exception e) { // listener.onFailure("load image list failure.", e); // } // }; // OkHttpUtils.get(url, loadNewsCallback); // } // // public interface OnLoadImageListListener { // void onSuccess(List<ImageBean> list); // void onFailure(String msg, Exception e); // } // } // // Path: app/src/main/java/com/lauren/simplenews/images/view/ImageView.java // public interface ImageView { // void addImages(List<ImageBean> list); // void showProgress(); // void hideProgress(); // void showLoadFailMsg(); // }
import com.lauren.simplenews.beans.ImageBean; import com.lauren.simplenews.images.model.ImageModel; import com.lauren.simplenews.images.model.ImageModelImpl; import com.lauren.simplenews.images.view.ImageView; import java.util.List;
package com.lauren.simplenews.images.presenter; /** * Description : * Author : lauren * Email : lauren.liuling@gmail.com * Blog : http://www.liuling123.com * Date : 15/12/22 */ public class ImagePresenterImpl implements ImagePresenter, ImageModelImpl.OnLoadImageListListener { private ImageModel mImageModel; private ImageView mImageView; public ImagePresenterImpl(ImageView imageView) { this.mImageModel = new ImageModelImpl(); this.mImageView = imageView; } @Override public void loadImageList() { mImageView.showProgress(); mImageModel.loadImageList(this); } @Override
// Path: app/src/main/java/com/lauren/simplenews/beans/ImageBean.java // public class ImageBean implements Serializable { // // private static final long serialVersionUID = 1L; // // private String title; // private String thumburl; // private String sourceurl; // private int height; // private int width; // // public String getTitle() { // return title; // } // // public void setTitle(String title) { // this.title = title; // } // // public String getThumburl() { // return thumburl; // } // // public void setThumburl(String thumburl) { // this.thumburl = thumburl; // } // // public String getSourceurl() { // return sourceurl; // } // // public void setSourceurl(String sourceurl) { // this.sourceurl = sourceurl; // } // // public int getHeight() { // return height; // } // // public void setHeight(int height) { // this.height = height; // } // // public int getWidth() { // return width; // } // // public void setWidth(int width) { // this.width = width; // } // } // // Path: app/src/main/java/com/lauren/simplenews/images/model/ImageModel.java // public interface ImageModel { // void loadImageList(ImageModelImpl.OnLoadImageListListener listener); // } // // Path: app/src/main/java/com/lauren/simplenews/images/model/ImageModelImpl.java // public class ImageModelImpl implements ImageModel { // // /** // * 获取图片列表 // * @param listener // */ // @Override // public void loadImageList(final OnLoadImageListListener listener) { // String url = Urls.IMAGES_URL; // OkHttpUtils.ResultCallback<String> loadNewsCallback = new OkHttpUtils.ResultCallback<String>() { // @Override // public void onSuccess(String response) { // List<ImageBean> iamgeBeanList = ImageJsonUtils.readJsonImageBeans(response); // listener.onSuccess(iamgeBeanList); // } // // @Override // public void onFailure(Exception e) { // listener.onFailure("load image list failure.", e); // } // }; // OkHttpUtils.get(url, loadNewsCallback); // } // // public interface OnLoadImageListListener { // void onSuccess(List<ImageBean> list); // void onFailure(String msg, Exception e); // } // } // // Path: app/src/main/java/com/lauren/simplenews/images/view/ImageView.java // public interface ImageView { // void addImages(List<ImageBean> list); // void showProgress(); // void hideProgress(); // void showLoadFailMsg(); // } // Path: app/src/main/java/com/lauren/simplenews/images/presenter/ImagePresenterImpl.java import com.lauren.simplenews.beans.ImageBean; import com.lauren.simplenews.images.model.ImageModel; import com.lauren.simplenews.images.model.ImageModelImpl; import com.lauren.simplenews.images.view.ImageView; import java.util.List; package com.lauren.simplenews.images.presenter; /** * Description : * Author : lauren * Email : lauren.liuling@gmail.com * Blog : http://www.liuling123.com * Date : 15/12/22 */ public class ImagePresenterImpl implements ImagePresenter, ImageModelImpl.OnLoadImageListListener { private ImageModel mImageModel; private ImageView mImageView; public ImagePresenterImpl(ImageView imageView) { this.mImageModel = new ImageModelImpl(); this.mImageView = imageView; } @Override public void loadImageList() { mImageView.showProgress(); mImageModel.loadImageList(this); } @Override
public void onSuccess(List<ImageBean> list) {
HarryXR/SimpleNews
app/src/main/java/com/lauren/simplenews/images/ImageJsonUtils.java
// Path: app/src/main/java/com/lauren/simplenews/beans/ImageBean.java // public class ImageBean implements Serializable { // // private static final long serialVersionUID = 1L; // // private String title; // private String thumburl; // private String sourceurl; // private int height; // private int width; // // public String getTitle() { // return title; // } // // public void setTitle(String title) { // this.title = title; // } // // public String getThumburl() { // return thumburl; // } // // public void setThumburl(String thumburl) { // this.thumburl = thumburl; // } // // public String getSourceurl() { // return sourceurl; // } // // public void setSourceurl(String sourceurl) { // this.sourceurl = sourceurl; // } // // public int getHeight() { // return height; // } // // public void setHeight(int height) { // this.height = height; // } // // public int getWidth() { // return width; // } // // public void setWidth(int width) { // this.width = width; // } // } // // Path: app/src/main/java/com/lauren/simplenews/utils/JsonUtils.java // public class JsonUtils { // // private static Gson mGson = new Gson(); // // /** // * 将对象准换为json字符串 // * @param object // * @param <T> // * @return // */ // public static <T> String serialize(T object) { // return mGson.toJson(object); // } // // /** // * 将json字符串转换为对象 // * @param json // * @param clz // * @param <T> // * @return // */ // public static <T> T deserialize(String json, Class<T> clz) throws JsonSyntaxException { // return mGson.fromJson(json, clz); // } // // /** // * 将json对象转换为实体对象 // * @param json // * @param clz // * @param <T> // * @return // * @throws JsonSyntaxException // */ // public static <T> T deserialize(JsonObject json, Class<T> clz) throws JsonSyntaxException { // return mGson.fromJson(json, clz); // } // // /** // * 将json字符串转换为对象 // * @param json // * @param type // * @param <T> // * @return // */ // public static <T> T deserialize(String json, Type type) throws JsonSyntaxException { // return mGson.fromJson(json, type); // } // // // // // // // } // // Path: app/src/main/java/com/lauren/simplenews/utils/LogUtils.java // public class LogUtils { // public static final boolean DEBUG = true; // // public static void v(String tag, String message) { // if(DEBUG) { // Log.v(tag, message); // } // } // // public static void d(String tag, String message) { // if(DEBUG) { // Log.d(tag, message); // } // } // // public static void i(String tag, String message) { // if(DEBUG) { // Log.i(tag, message); // } // } // // public static void w(String tag, String message) { // if(DEBUG) { // Log.w(tag, message); // } // } // // public static void e(String tag, String message) { // if(DEBUG) { // Log.e(tag, message); // } // } // // public static void e(String tag, String message, Exception e) { // if(DEBUG) { // Log.e(tag, message, e); // } // } // }
import com.google.gson.JsonArray; import com.google.gson.JsonObject; import com.google.gson.JsonParser; import com.lauren.simplenews.beans.ImageBean; import com.lauren.simplenews.utils.JsonUtils; import com.lauren.simplenews.utils.LogUtils; import java.util.ArrayList; import java.util.List;
package com.lauren.simplenews.images; /** * Description : * Author : lauren * Email : lauren.liuling@gmail.com * Blog : http://www.liuling123.com * Date : 15/12/23 */ public class ImageJsonUtils { private final static String TAG = "ImageJsonUtils"; /** * 将获取到的json转换为图片列表对象 * @param res * @return */
// Path: app/src/main/java/com/lauren/simplenews/beans/ImageBean.java // public class ImageBean implements Serializable { // // private static final long serialVersionUID = 1L; // // private String title; // private String thumburl; // private String sourceurl; // private int height; // private int width; // // public String getTitle() { // return title; // } // // public void setTitle(String title) { // this.title = title; // } // // public String getThumburl() { // return thumburl; // } // // public void setThumburl(String thumburl) { // this.thumburl = thumburl; // } // // public String getSourceurl() { // return sourceurl; // } // // public void setSourceurl(String sourceurl) { // this.sourceurl = sourceurl; // } // // public int getHeight() { // return height; // } // // public void setHeight(int height) { // this.height = height; // } // // public int getWidth() { // return width; // } // // public void setWidth(int width) { // this.width = width; // } // } // // Path: app/src/main/java/com/lauren/simplenews/utils/JsonUtils.java // public class JsonUtils { // // private static Gson mGson = new Gson(); // // /** // * 将对象准换为json字符串 // * @param object // * @param <T> // * @return // */ // public static <T> String serialize(T object) { // return mGson.toJson(object); // } // // /** // * 将json字符串转换为对象 // * @param json // * @param clz // * @param <T> // * @return // */ // public static <T> T deserialize(String json, Class<T> clz) throws JsonSyntaxException { // return mGson.fromJson(json, clz); // } // // /** // * 将json对象转换为实体对象 // * @param json // * @param clz // * @param <T> // * @return // * @throws JsonSyntaxException // */ // public static <T> T deserialize(JsonObject json, Class<T> clz) throws JsonSyntaxException { // return mGson.fromJson(json, clz); // } // // /** // * 将json字符串转换为对象 // * @param json // * @param type // * @param <T> // * @return // */ // public static <T> T deserialize(String json, Type type) throws JsonSyntaxException { // return mGson.fromJson(json, type); // } // // // // // // // } // // Path: app/src/main/java/com/lauren/simplenews/utils/LogUtils.java // public class LogUtils { // public static final boolean DEBUG = true; // // public static void v(String tag, String message) { // if(DEBUG) { // Log.v(tag, message); // } // } // // public static void d(String tag, String message) { // if(DEBUG) { // Log.d(tag, message); // } // } // // public static void i(String tag, String message) { // if(DEBUG) { // Log.i(tag, message); // } // } // // public static void w(String tag, String message) { // if(DEBUG) { // Log.w(tag, message); // } // } // // public static void e(String tag, String message) { // if(DEBUG) { // Log.e(tag, message); // } // } // // public static void e(String tag, String message, Exception e) { // if(DEBUG) { // Log.e(tag, message, e); // } // } // } // Path: app/src/main/java/com/lauren/simplenews/images/ImageJsonUtils.java import com.google.gson.JsonArray; import com.google.gson.JsonObject; import com.google.gson.JsonParser; import com.lauren.simplenews.beans.ImageBean; import com.lauren.simplenews.utils.JsonUtils; import com.lauren.simplenews.utils.LogUtils; import java.util.ArrayList; import java.util.List; package com.lauren.simplenews.images; /** * Description : * Author : lauren * Email : lauren.liuling@gmail.com * Blog : http://www.liuling123.com * Date : 15/12/23 */ public class ImageJsonUtils { private final static String TAG = "ImageJsonUtils"; /** * 将获取到的json转换为图片列表对象 * @param res * @return */
public static List<ImageBean> readJsonImageBeans(String res) {
HarryXR/SimpleNews
app/src/main/java/com/lauren/simplenews/images/ImageJsonUtils.java
// Path: app/src/main/java/com/lauren/simplenews/beans/ImageBean.java // public class ImageBean implements Serializable { // // private static final long serialVersionUID = 1L; // // private String title; // private String thumburl; // private String sourceurl; // private int height; // private int width; // // public String getTitle() { // return title; // } // // public void setTitle(String title) { // this.title = title; // } // // public String getThumburl() { // return thumburl; // } // // public void setThumburl(String thumburl) { // this.thumburl = thumburl; // } // // public String getSourceurl() { // return sourceurl; // } // // public void setSourceurl(String sourceurl) { // this.sourceurl = sourceurl; // } // // public int getHeight() { // return height; // } // // public void setHeight(int height) { // this.height = height; // } // // public int getWidth() { // return width; // } // // public void setWidth(int width) { // this.width = width; // } // } // // Path: app/src/main/java/com/lauren/simplenews/utils/JsonUtils.java // public class JsonUtils { // // private static Gson mGson = new Gson(); // // /** // * 将对象准换为json字符串 // * @param object // * @param <T> // * @return // */ // public static <T> String serialize(T object) { // return mGson.toJson(object); // } // // /** // * 将json字符串转换为对象 // * @param json // * @param clz // * @param <T> // * @return // */ // public static <T> T deserialize(String json, Class<T> clz) throws JsonSyntaxException { // return mGson.fromJson(json, clz); // } // // /** // * 将json对象转换为实体对象 // * @param json // * @param clz // * @param <T> // * @return // * @throws JsonSyntaxException // */ // public static <T> T deserialize(JsonObject json, Class<T> clz) throws JsonSyntaxException { // return mGson.fromJson(json, clz); // } // // /** // * 将json字符串转换为对象 // * @param json // * @param type // * @param <T> // * @return // */ // public static <T> T deserialize(String json, Type type) throws JsonSyntaxException { // return mGson.fromJson(json, type); // } // // // // // // // } // // Path: app/src/main/java/com/lauren/simplenews/utils/LogUtils.java // public class LogUtils { // public static final boolean DEBUG = true; // // public static void v(String tag, String message) { // if(DEBUG) { // Log.v(tag, message); // } // } // // public static void d(String tag, String message) { // if(DEBUG) { // Log.d(tag, message); // } // } // // public static void i(String tag, String message) { // if(DEBUG) { // Log.i(tag, message); // } // } // // public static void w(String tag, String message) { // if(DEBUG) { // Log.w(tag, message); // } // } // // public static void e(String tag, String message) { // if(DEBUG) { // Log.e(tag, message); // } // } // // public static void e(String tag, String message, Exception e) { // if(DEBUG) { // Log.e(tag, message, e); // } // } // }
import com.google.gson.JsonArray; import com.google.gson.JsonObject; import com.google.gson.JsonParser; import com.lauren.simplenews.beans.ImageBean; import com.lauren.simplenews.utils.JsonUtils; import com.lauren.simplenews.utils.LogUtils; import java.util.ArrayList; import java.util.List;
package com.lauren.simplenews.images; /** * Description : * Author : lauren * Email : lauren.liuling@gmail.com * Blog : http://www.liuling123.com * Date : 15/12/23 */ public class ImageJsonUtils { private final static String TAG = "ImageJsonUtils"; /** * 将获取到的json转换为图片列表对象 * @param res * @return */ public static List<ImageBean> readJsonImageBeans(String res) { List<ImageBean> beans = new ArrayList<ImageBean>(); try { JsonParser parser = new JsonParser(); JsonArray jsonArray = parser.parse(res).getAsJsonArray(); for (int i = 1; i < jsonArray.size(); i++) { JsonObject jo = jsonArray.get(i).getAsJsonObject();
// Path: app/src/main/java/com/lauren/simplenews/beans/ImageBean.java // public class ImageBean implements Serializable { // // private static final long serialVersionUID = 1L; // // private String title; // private String thumburl; // private String sourceurl; // private int height; // private int width; // // public String getTitle() { // return title; // } // // public void setTitle(String title) { // this.title = title; // } // // public String getThumburl() { // return thumburl; // } // // public void setThumburl(String thumburl) { // this.thumburl = thumburl; // } // // public String getSourceurl() { // return sourceurl; // } // // public void setSourceurl(String sourceurl) { // this.sourceurl = sourceurl; // } // // public int getHeight() { // return height; // } // // public void setHeight(int height) { // this.height = height; // } // // public int getWidth() { // return width; // } // // public void setWidth(int width) { // this.width = width; // } // } // // Path: app/src/main/java/com/lauren/simplenews/utils/JsonUtils.java // public class JsonUtils { // // private static Gson mGson = new Gson(); // // /** // * 将对象准换为json字符串 // * @param object // * @param <T> // * @return // */ // public static <T> String serialize(T object) { // return mGson.toJson(object); // } // // /** // * 将json字符串转换为对象 // * @param json // * @param clz // * @param <T> // * @return // */ // public static <T> T deserialize(String json, Class<T> clz) throws JsonSyntaxException { // return mGson.fromJson(json, clz); // } // // /** // * 将json对象转换为实体对象 // * @param json // * @param clz // * @param <T> // * @return // * @throws JsonSyntaxException // */ // public static <T> T deserialize(JsonObject json, Class<T> clz) throws JsonSyntaxException { // return mGson.fromJson(json, clz); // } // // /** // * 将json字符串转换为对象 // * @param json // * @param type // * @param <T> // * @return // */ // public static <T> T deserialize(String json, Type type) throws JsonSyntaxException { // return mGson.fromJson(json, type); // } // // // // // // // } // // Path: app/src/main/java/com/lauren/simplenews/utils/LogUtils.java // public class LogUtils { // public static final boolean DEBUG = true; // // public static void v(String tag, String message) { // if(DEBUG) { // Log.v(tag, message); // } // } // // public static void d(String tag, String message) { // if(DEBUG) { // Log.d(tag, message); // } // } // // public static void i(String tag, String message) { // if(DEBUG) { // Log.i(tag, message); // } // } // // public static void w(String tag, String message) { // if(DEBUG) { // Log.w(tag, message); // } // } // // public static void e(String tag, String message) { // if(DEBUG) { // Log.e(tag, message); // } // } // // public static void e(String tag, String message, Exception e) { // if(DEBUG) { // Log.e(tag, message, e); // } // } // } // Path: app/src/main/java/com/lauren/simplenews/images/ImageJsonUtils.java import com.google.gson.JsonArray; import com.google.gson.JsonObject; import com.google.gson.JsonParser; import com.lauren.simplenews.beans.ImageBean; import com.lauren.simplenews.utils.JsonUtils; import com.lauren.simplenews.utils.LogUtils; import java.util.ArrayList; import java.util.List; package com.lauren.simplenews.images; /** * Description : * Author : lauren * Email : lauren.liuling@gmail.com * Blog : http://www.liuling123.com * Date : 15/12/23 */ public class ImageJsonUtils { private final static String TAG = "ImageJsonUtils"; /** * 将获取到的json转换为图片列表对象 * @param res * @return */ public static List<ImageBean> readJsonImageBeans(String res) { List<ImageBean> beans = new ArrayList<ImageBean>(); try { JsonParser parser = new JsonParser(); JsonArray jsonArray = parser.parse(res).getAsJsonArray(); for (int i = 1; i < jsonArray.size(); i++) { JsonObject jo = jsonArray.get(i).getAsJsonObject();
ImageBean news = JsonUtils.deserialize(jo, ImageBean.class);
HarryXR/SimpleNews
app/src/main/java/com/lauren/simplenews/images/ImageJsonUtils.java
// Path: app/src/main/java/com/lauren/simplenews/beans/ImageBean.java // public class ImageBean implements Serializable { // // private static final long serialVersionUID = 1L; // // private String title; // private String thumburl; // private String sourceurl; // private int height; // private int width; // // public String getTitle() { // return title; // } // // public void setTitle(String title) { // this.title = title; // } // // public String getThumburl() { // return thumburl; // } // // public void setThumburl(String thumburl) { // this.thumburl = thumburl; // } // // public String getSourceurl() { // return sourceurl; // } // // public void setSourceurl(String sourceurl) { // this.sourceurl = sourceurl; // } // // public int getHeight() { // return height; // } // // public void setHeight(int height) { // this.height = height; // } // // public int getWidth() { // return width; // } // // public void setWidth(int width) { // this.width = width; // } // } // // Path: app/src/main/java/com/lauren/simplenews/utils/JsonUtils.java // public class JsonUtils { // // private static Gson mGson = new Gson(); // // /** // * 将对象准换为json字符串 // * @param object // * @param <T> // * @return // */ // public static <T> String serialize(T object) { // return mGson.toJson(object); // } // // /** // * 将json字符串转换为对象 // * @param json // * @param clz // * @param <T> // * @return // */ // public static <T> T deserialize(String json, Class<T> clz) throws JsonSyntaxException { // return mGson.fromJson(json, clz); // } // // /** // * 将json对象转换为实体对象 // * @param json // * @param clz // * @param <T> // * @return // * @throws JsonSyntaxException // */ // public static <T> T deserialize(JsonObject json, Class<T> clz) throws JsonSyntaxException { // return mGson.fromJson(json, clz); // } // // /** // * 将json字符串转换为对象 // * @param json // * @param type // * @param <T> // * @return // */ // public static <T> T deserialize(String json, Type type) throws JsonSyntaxException { // return mGson.fromJson(json, type); // } // // // // // // // } // // Path: app/src/main/java/com/lauren/simplenews/utils/LogUtils.java // public class LogUtils { // public static final boolean DEBUG = true; // // public static void v(String tag, String message) { // if(DEBUG) { // Log.v(tag, message); // } // } // // public static void d(String tag, String message) { // if(DEBUG) { // Log.d(tag, message); // } // } // // public static void i(String tag, String message) { // if(DEBUG) { // Log.i(tag, message); // } // } // // public static void w(String tag, String message) { // if(DEBUG) { // Log.w(tag, message); // } // } // // public static void e(String tag, String message) { // if(DEBUG) { // Log.e(tag, message); // } // } // // public static void e(String tag, String message, Exception e) { // if(DEBUG) { // Log.e(tag, message, e); // } // } // }
import com.google.gson.JsonArray; import com.google.gson.JsonObject; import com.google.gson.JsonParser; import com.lauren.simplenews.beans.ImageBean; import com.lauren.simplenews.utils.JsonUtils; import com.lauren.simplenews.utils.LogUtils; import java.util.ArrayList; import java.util.List;
package com.lauren.simplenews.images; /** * Description : * Author : lauren * Email : lauren.liuling@gmail.com * Blog : http://www.liuling123.com * Date : 15/12/23 */ public class ImageJsonUtils { private final static String TAG = "ImageJsonUtils"; /** * 将获取到的json转换为图片列表对象 * @param res * @return */ public static List<ImageBean> readJsonImageBeans(String res) { List<ImageBean> beans = new ArrayList<ImageBean>(); try { JsonParser parser = new JsonParser(); JsonArray jsonArray = parser.parse(res).getAsJsonArray(); for (int i = 1; i < jsonArray.size(); i++) { JsonObject jo = jsonArray.get(i).getAsJsonObject(); ImageBean news = JsonUtils.deserialize(jo, ImageBean.class); beans.add(news); } } catch (Exception e) {
// Path: app/src/main/java/com/lauren/simplenews/beans/ImageBean.java // public class ImageBean implements Serializable { // // private static final long serialVersionUID = 1L; // // private String title; // private String thumburl; // private String sourceurl; // private int height; // private int width; // // public String getTitle() { // return title; // } // // public void setTitle(String title) { // this.title = title; // } // // public String getThumburl() { // return thumburl; // } // // public void setThumburl(String thumburl) { // this.thumburl = thumburl; // } // // public String getSourceurl() { // return sourceurl; // } // // public void setSourceurl(String sourceurl) { // this.sourceurl = sourceurl; // } // // public int getHeight() { // return height; // } // // public void setHeight(int height) { // this.height = height; // } // // public int getWidth() { // return width; // } // // public void setWidth(int width) { // this.width = width; // } // } // // Path: app/src/main/java/com/lauren/simplenews/utils/JsonUtils.java // public class JsonUtils { // // private static Gson mGson = new Gson(); // // /** // * 将对象准换为json字符串 // * @param object // * @param <T> // * @return // */ // public static <T> String serialize(T object) { // return mGson.toJson(object); // } // // /** // * 将json字符串转换为对象 // * @param json // * @param clz // * @param <T> // * @return // */ // public static <T> T deserialize(String json, Class<T> clz) throws JsonSyntaxException { // return mGson.fromJson(json, clz); // } // // /** // * 将json对象转换为实体对象 // * @param json // * @param clz // * @param <T> // * @return // * @throws JsonSyntaxException // */ // public static <T> T deserialize(JsonObject json, Class<T> clz) throws JsonSyntaxException { // return mGson.fromJson(json, clz); // } // // /** // * 将json字符串转换为对象 // * @param json // * @param type // * @param <T> // * @return // */ // public static <T> T deserialize(String json, Type type) throws JsonSyntaxException { // return mGson.fromJson(json, type); // } // // // // // // // } // // Path: app/src/main/java/com/lauren/simplenews/utils/LogUtils.java // public class LogUtils { // public static final boolean DEBUG = true; // // public static void v(String tag, String message) { // if(DEBUG) { // Log.v(tag, message); // } // } // // public static void d(String tag, String message) { // if(DEBUG) { // Log.d(tag, message); // } // } // // public static void i(String tag, String message) { // if(DEBUG) { // Log.i(tag, message); // } // } // // public static void w(String tag, String message) { // if(DEBUG) { // Log.w(tag, message); // } // } // // public static void e(String tag, String message) { // if(DEBUG) { // Log.e(tag, message); // } // } // // public static void e(String tag, String message, Exception e) { // if(DEBUG) { // Log.e(tag, message, e); // } // } // } // Path: app/src/main/java/com/lauren/simplenews/images/ImageJsonUtils.java import com.google.gson.JsonArray; import com.google.gson.JsonObject; import com.google.gson.JsonParser; import com.lauren.simplenews.beans.ImageBean; import com.lauren.simplenews.utils.JsonUtils; import com.lauren.simplenews.utils.LogUtils; import java.util.ArrayList; import java.util.List; package com.lauren.simplenews.images; /** * Description : * Author : lauren * Email : lauren.liuling@gmail.com * Blog : http://www.liuling123.com * Date : 15/12/23 */ public class ImageJsonUtils { private final static String TAG = "ImageJsonUtils"; /** * 将获取到的json转换为图片列表对象 * @param res * @return */ public static List<ImageBean> readJsonImageBeans(String res) { List<ImageBean> beans = new ArrayList<ImageBean>(); try { JsonParser parser = new JsonParser(); JsonArray jsonArray = parser.parse(res).getAsJsonArray(); for (int i = 1; i < jsonArray.size(); i++) { JsonObject jo = jsonArray.get(i).getAsJsonObject(); ImageBean news = JsonUtils.deserialize(jo, ImageBean.class); beans.add(news); } } catch (Exception e) {
LogUtils.e(TAG, "readJsonImageBeans error", e);
HarryXR/SimpleNews
app/src/main/java/com/lauren/simplenews/news/NewsAdapter.java
// Path: app/src/main/java/com/lauren/simplenews/beans/NewsBean.java // public class NewsBean implements Serializable { // // /** // * docid // */ // public String docid; // /** // * 标题 // */ // public String title; // /** // * 小内容 // */ // public String digest; // /** // * 图片地址 // */ // public String imgsrc; // /** // * 来源 // */ // public String source; // /** // * 时间 // */ // public String ptime; // /** // * TAG // */ // private String tag; // // public String url; // // } // // Path: app/src/main/java/com/lauren/simplenews/view/GlideImageView.java // public class GlideImageView extends ImageView { // int placeholderId = 0; // int failureImageId = 0; // boolean roundAsCircle = false; // int roundedCornerRadius = 0; // Context context; // // boolean failure = false; // RequestManager manager; // GenericRequestBuilder builder; // GlideRoundTransform mRoundTrans; // // public GlideImageView(Context context) { // super(context); // } // // public GlideImageView(Context context, AttributeSet attrs) { // this(context, attrs, 0); // } // // @TargetApi(Build.VERSION_CODES.HONEYCOMB) // public GlideImageView(Context context, AttributeSet attrs, int defStyle) { // super(context, attrs, defStyle); // init(context, attrs); // } // // private void init(Context context, AttributeSet attrs) { // manager = Glide.with(context); // this.context = context; // mRoundTrans = new GlideRoundTransform(context); // TypedArray a = context.obtainStyledAttributes(attrs, R.styleable.GlideImageView); // try { // placeholderId = a.getResourceId(R.styleable.GlideImageView_placeholderImage, placeholderId); // failureImageId = a.getResourceId(R.styleable.GlideImageView_placeholderImage, failureImageId); // roundAsCircle = a.getBoolean(R.styleable.GlideImageView_roundAsCircle, roundAsCircle); // roundedCornerRadius = a.getDimensionPixelSize(R.styleable.GlideImageView_roundedCornerRadius, // roundedCornerRadius); // } finally { // a.recycle(); // } // // if (failureImageId > 0) { // this.setFailureImage(failureImageId); // } // } // // /** // * Displays an fail image // */ // public void setFailureImage(int id) { // if (failure) { // this.setImageResource(id); // } // } // // /** // * Displays an image given by the url // * // * @param url url of the image // */ // public void setImageURL(String url) { // if (url == null) { // return; // } // builder = manager.load(url).centerCrop().placeholder(placeholderId).error(failureImageId); // if (roundAsCircle) { // builder.transform(mRoundTrans); // } // builder.into(this); // } // // public class GlideRoundTransform extends BitmapTransformation { // private float radius = 0f; // // public GlideRoundTransform(Context context) { // this(context, roundedCornerRadius); // } // // public GlideRoundTransform(Context context, int dp) { // super(context); // this.radius = Resources.getSystem().getDisplayMetrics().density * dp; // } // // @Override // protected Bitmap transform(BitmapPool pool, Bitmap toTransform, int outWidth, int outHeight) { // return roundCrop(pool, toTransform); // } // // private Bitmap roundCrop(BitmapPool pool, Bitmap source) { // if (source == null) { // return null; // } // Bitmap result = pool.get(source.getWidth(), source.getHeight(), Bitmap.Config.ARGB_8888); // if (result == null) { // result = Bitmap.createBitmap(source.getWidth(), source.getHeight(), Bitmap.Config.ARGB_8888); // } // Canvas canvas = new Canvas(result); // Paint paint = new Paint(); // paint.setShader(new BitmapShader(source, BitmapShader.TileMode.CLAMP, BitmapShader.TileMode.CLAMP)); // paint.setAntiAlias(true); // RectF rectF = new RectF(0f, 0f, source.getWidth(), source.getHeight()); // canvas.drawRoundRect(rectF, radius, radius, paint); // return result; // } // // @Override // public String getId() { // return getClass().getName() + Math.round(radius); // } // } // }
import android.content.Context; import android.support.v7.widget.RecyclerView; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.TextView; import com.lauren.simplenews.R; import com.lauren.simplenews.beans.NewsBean; import com.lauren.simplenews.view.GlideImageView; import java.util.List;
package com.lauren.simplenews.news; /** * Description : * Author : lauren * Email : lauren.liuling@gmail.com * Blog : http://www.liuling123.com * Date : 15/12/19 */ public class NewsAdapter extends RecyclerView.Adapter<RecyclerView.ViewHolder> { private static final int TYPE_ITEM = 0; private static final int TYPE_FOOTER = 1;
// Path: app/src/main/java/com/lauren/simplenews/beans/NewsBean.java // public class NewsBean implements Serializable { // // /** // * docid // */ // public String docid; // /** // * 标题 // */ // public String title; // /** // * 小内容 // */ // public String digest; // /** // * 图片地址 // */ // public String imgsrc; // /** // * 来源 // */ // public String source; // /** // * 时间 // */ // public String ptime; // /** // * TAG // */ // private String tag; // // public String url; // // } // // Path: app/src/main/java/com/lauren/simplenews/view/GlideImageView.java // public class GlideImageView extends ImageView { // int placeholderId = 0; // int failureImageId = 0; // boolean roundAsCircle = false; // int roundedCornerRadius = 0; // Context context; // // boolean failure = false; // RequestManager manager; // GenericRequestBuilder builder; // GlideRoundTransform mRoundTrans; // // public GlideImageView(Context context) { // super(context); // } // // public GlideImageView(Context context, AttributeSet attrs) { // this(context, attrs, 0); // } // // @TargetApi(Build.VERSION_CODES.HONEYCOMB) // public GlideImageView(Context context, AttributeSet attrs, int defStyle) { // super(context, attrs, defStyle); // init(context, attrs); // } // // private void init(Context context, AttributeSet attrs) { // manager = Glide.with(context); // this.context = context; // mRoundTrans = new GlideRoundTransform(context); // TypedArray a = context.obtainStyledAttributes(attrs, R.styleable.GlideImageView); // try { // placeholderId = a.getResourceId(R.styleable.GlideImageView_placeholderImage, placeholderId); // failureImageId = a.getResourceId(R.styleable.GlideImageView_placeholderImage, failureImageId); // roundAsCircle = a.getBoolean(R.styleable.GlideImageView_roundAsCircle, roundAsCircle); // roundedCornerRadius = a.getDimensionPixelSize(R.styleable.GlideImageView_roundedCornerRadius, // roundedCornerRadius); // } finally { // a.recycle(); // } // // if (failureImageId > 0) { // this.setFailureImage(failureImageId); // } // } // // /** // * Displays an fail image // */ // public void setFailureImage(int id) { // if (failure) { // this.setImageResource(id); // } // } // // /** // * Displays an image given by the url // * // * @param url url of the image // */ // public void setImageURL(String url) { // if (url == null) { // return; // } // builder = manager.load(url).centerCrop().placeholder(placeholderId).error(failureImageId); // if (roundAsCircle) { // builder.transform(mRoundTrans); // } // builder.into(this); // } // // public class GlideRoundTransform extends BitmapTransformation { // private float radius = 0f; // // public GlideRoundTransform(Context context) { // this(context, roundedCornerRadius); // } // // public GlideRoundTransform(Context context, int dp) { // super(context); // this.radius = Resources.getSystem().getDisplayMetrics().density * dp; // } // // @Override // protected Bitmap transform(BitmapPool pool, Bitmap toTransform, int outWidth, int outHeight) { // return roundCrop(pool, toTransform); // } // // private Bitmap roundCrop(BitmapPool pool, Bitmap source) { // if (source == null) { // return null; // } // Bitmap result = pool.get(source.getWidth(), source.getHeight(), Bitmap.Config.ARGB_8888); // if (result == null) { // result = Bitmap.createBitmap(source.getWidth(), source.getHeight(), Bitmap.Config.ARGB_8888); // } // Canvas canvas = new Canvas(result); // Paint paint = new Paint(); // paint.setShader(new BitmapShader(source, BitmapShader.TileMode.CLAMP, BitmapShader.TileMode.CLAMP)); // paint.setAntiAlias(true); // RectF rectF = new RectF(0f, 0f, source.getWidth(), source.getHeight()); // canvas.drawRoundRect(rectF, radius, radius, paint); // return result; // } // // @Override // public String getId() { // return getClass().getName() + Math.round(radius); // } // } // } // Path: app/src/main/java/com/lauren/simplenews/news/NewsAdapter.java import android.content.Context; import android.support.v7.widget.RecyclerView; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.TextView; import com.lauren.simplenews.R; import com.lauren.simplenews.beans.NewsBean; import com.lauren.simplenews.view.GlideImageView; import java.util.List; package com.lauren.simplenews.news; /** * Description : * Author : lauren * Email : lauren.liuling@gmail.com * Blog : http://www.liuling123.com * Date : 15/12/19 */ public class NewsAdapter extends RecyclerView.Adapter<RecyclerView.ViewHolder> { private static final int TYPE_ITEM = 0; private static final int TYPE_FOOTER = 1;
private List<NewsBean> mData;
HarryXR/SimpleNews
app/src/main/java/com/lauren/simplenews/news/NewsAdapter.java
// Path: app/src/main/java/com/lauren/simplenews/beans/NewsBean.java // public class NewsBean implements Serializable { // // /** // * docid // */ // public String docid; // /** // * 标题 // */ // public String title; // /** // * 小内容 // */ // public String digest; // /** // * 图片地址 // */ // public String imgsrc; // /** // * 来源 // */ // public String source; // /** // * 时间 // */ // public String ptime; // /** // * TAG // */ // private String tag; // // public String url; // // } // // Path: app/src/main/java/com/lauren/simplenews/view/GlideImageView.java // public class GlideImageView extends ImageView { // int placeholderId = 0; // int failureImageId = 0; // boolean roundAsCircle = false; // int roundedCornerRadius = 0; // Context context; // // boolean failure = false; // RequestManager manager; // GenericRequestBuilder builder; // GlideRoundTransform mRoundTrans; // // public GlideImageView(Context context) { // super(context); // } // // public GlideImageView(Context context, AttributeSet attrs) { // this(context, attrs, 0); // } // // @TargetApi(Build.VERSION_CODES.HONEYCOMB) // public GlideImageView(Context context, AttributeSet attrs, int defStyle) { // super(context, attrs, defStyle); // init(context, attrs); // } // // private void init(Context context, AttributeSet attrs) { // manager = Glide.with(context); // this.context = context; // mRoundTrans = new GlideRoundTransform(context); // TypedArray a = context.obtainStyledAttributes(attrs, R.styleable.GlideImageView); // try { // placeholderId = a.getResourceId(R.styleable.GlideImageView_placeholderImage, placeholderId); // failureImageId = a.getResourceId(R.styleable.GlideImageView_placeholderImage, failureImageId); // roundAsCircle = a.getBoolean(R.styleable.GlideImageView_roundAsCircle, roundAsCircle); // roundedCornerRadius = a.getDimensionPixelSize(R.styleable.GlideImageView_roundedCornerRadius, // roundedCornerRadius); // } finally { // a.recycle(); // } // // if (failureImageId > 0) { // this.setFailureImage(failureImageId); // } // } // // /** // * Displays an fail image // */ // public void setFailureImage(int id) { // if (failure) { // this.setImageResource(id); // } // } // // /** // * Displays an image given by the url // * // * @param url url of the image // */ // public void setImageURL(String url) { // if (url == null) { // return; // } // builder = manager.load(url).centerCrop().placeholder(placeholderId).error(failureImageId); // if (roundAsCircle) { // builder.transform(mRoundTrans); // } // builder.into(this); // } // // public class GlideRoundTransform extends BitmapTransformation { // private float radius = 0f; // // public GlideRoundTransform(Context context) { // this(context, roundedCornerRadius); // } // // public GlideRoundTransform(Context context, int dp) { // super(context); // this.radius = Resources.getSystem().getDisplayMetrics().density * dp; // } // // @Override // protected Bitmap transform(BitmapPool pool, Bitmap toTransform, int outWidth, int outHeight) { // return roundCrop(pool, toTransform); // } // // private Bitmap roundCrop(BitmapPool pool, Bitmap source) { // if (source == null) { // return null; // } // Bitmap result = pool.get(source.getWidth(), source.getHeight(), Bitmap.Config.ARGB_8888); // if (result == null) { // result = Bitmap.createBitmap(source.getWidth(), source.getHeight(), Bitmap.Config.ARGB_8888); // } // Canvas canvas = new Canvas(result); // Paint paint = new Paint(); // paint.setShader(new BitmapShader(source, BitmapShader.TileMode.CLAMP, BitmapShader.TileMode.CLAMP)); // paint.setAntiAlias(true); // RectF rectF = new RectF(0f, 0f, source.getWidth(), source.getHeight()); // canvas.drawRoundRect(rectF, radius, radius, paint); // return result; // } // // @Override // public String getId() { // return getClass().getName() + Math.round(radius); // } // } // }
import android.content.Context; import android.support.v7.widget.RecyclerView; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.TextView; import com.lauren.simplenews.R; import com.lauren.simplenews.beans.NewsBean; import com.lauren.simplenews.view.GlideImageView; import java.util.List;
return mData == null ? null : mData.get(position); } public void isShowFooter(boolean showFooter) { this.mShowFooter = showFooter; } public boolean isShowFooter() { return this.mShowFooter; } public void setOnItemClickListener(OnItemClickListener onItemClickListener) { this.mOnItemClickListener = onItemClickListener; } public class FooterViewHolder extends RecyclerView.ViewHolder { public FooterViewHolder(View view) { super(view); } } public interface OnItemClickListener { public void onItemClick(View view, int position); } public class ItemViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener { public TextView mTitle; public TextView mDesc;
// Path: app/src/main/java/com/lauren/simplenews/beans/NewsBean.java // public class NewsBean implements Serializable { // // /** // * docid // */ // public String docid; // /** // * 标题 // */ // public String title; // /** // * 小内容 // */ // public String digest; // /** // * 图片地址 // */ // public String imgsrc; // /** // * 来源 // */ // public String source; // /** // * 时间 // */ // public String ptime; // /** // * TAG // */ // private String tag; // // public String url; // // } // // Path: app/src/main/java/com/lauren/simplenews/view/GlideImageView.java // public class GlideImageView extends ImageView { // int placeholderId = 0; // int failureImageId = 0; // boolean roundAsCircle = false; // int roundedCornerRadius = 0; // Context context; // // boolean failure = false; // RequestManager manager; // GenericRequestBuilder builder; // GlideRoundTransform mRoundTrans; // // public GlideImageView(Context context) { // super(context); // } // // public GlideImageView(Context context, AttributeSet attrs) { // this(context, attrs, 0); // } // // @TargetApi(Build.VERSION_CODES.HONEYCOMB) // public GlideImageView(Context context, AttributeSet attrs, int defStyle) { // super(context, attrs, defStyle); // init(context, attrs); // } // // private void init(Context context, AttributeSet attrs) { // manager = Glide.with(context); // this.context = context; // mRoundTrans = new GlideRoundTransform(context); // TypedArray a = context.obtainStyledAttributes(attrs, R.styleable.GlideImageView); // try { // placeholderId = a.getResourceId(R.styleable.GlideImageView_placeholderImage, placeholderId); // failureImageId = a.getResourceId(R.styleable.GlideImageView_placeholderImage, failureImageId); // roundAsCircle = a.getBoolean(R.styleable.GlideImageView_roundAsCircle, roundAsCircle); // roundedCornerRadius = a.getDimensionPixelSize(R.styleable.GlideImageView_roundedCornerRadius, // roundedCornerRadius); // } finally { // a.recycle(); // } // // if (failureImageId > 0) { // this.setFailureImage(failureImageId); // } // } // // /** // * Displays an fail image // */ // public void setFailureImage(int id) { // if (failure) { // this.setImageResource(id); // } // } // // /** // * Displays an image given by the url // * // * @param url url of the image // */ // public void setImageURL(String url) { // if (url == null) { // return; // } // builder = manager.load(url).centerCrop().placeholder(placeholderId).error(failureImageId); // if (roundAsCircle) { // builder.transform(mRoundTrans); // } // builder.into(this); // } // // public class GlideRoundTransform extends BitmapTransformation { // private float radius = 0f; // // public GlideRoundTransform(Context context) { // this(context, roundedCornerRadius); // } // // public GlideRoundTransform(Context context, int dp) { // super(context); // this.radius = Resources.getSystem().getDisplayMetrics().density * dp; // } // // @Override // protected Bitmap transform(BitmapPool pool, Bitmap toTransform, int outWidth, int outHeight) { // return roundCrop(pool, toTransform); // } // // private Bitmap roundCrop(BitmapPool pool, Bitmap source) { // if (source == null) { // return null; // } // Bitmap result = pool.get(source.getWidth(), source.getHeight(), Bitmap.Config.ARGB_8888); // if (result == null) { // result = Bitmap.createBitmap(source.getWidth(), source.getHeight(), Bitmap.Config.ARGB_8888); // } // Canvas canvas = new Canvas(result); // Paint paint = new Paint(); // paint.setShader(new BitmapShader(source, BitmapShader.TileMode.CLAMP, BitmapShader.TileMode.CLAMP)); // paint.setAntiAlias(true); // RectF rectF = new RectF(0f, 0f, source.getWidth(), source.getHeight()); // canvas.drawRoundRect(rectF, radius, radius, paint); // return result; // } // // @Override // public String getId() { // return getClass().getName() + Math.round(radius); // } // } // } // Path: app/src/main/java/com/lauren/simplenews/news/NewsAdapter.java import android.content.Context; import android.support.v7.widget.RecyclerView; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.TextView; import com.lauren.simplenews.R; import com.lauren.simplenews.beans.NewsBean; import com.lauren.simplenews.view.GlideImageView; import java.util.List; return mData == null ? null : mData.get(position); } public void isShowFooter(boolean showFooter) { this.mShowFooter = showFooter; } public boolean isShowFooter() { return this.mShowFooter; } public void setOnItemClickListener(OnItemClickListener onItemClickListener) { this.mOnItemClickListener = onItemClickListener; } public class FooterViewHolder extends RecyclerView.ViewHolder { public FooterViewHolder(View view) { super(view); } } public interface OnItemClickListener { public void onItemClick(View view, int position); } public class ItemViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener { public TextView mTitle; public TextView mDesc;
public GlideImageView mNewsImg;
kollerlukas/Camera-Roll-Android-App
app/src/main/java/us/koller/cameraroll/data/fileOperations/Move.java
// Path: app/src/main/java/us/koller/cameraroll/data/models/File_POJO.java // public class File_POJO // implements Parcelable, SortUtil.Sortable { // // private String path; // private String name; // // private ArrayList<File_POJO> children; // public boolean isMedia; // public boolean excluded; // // public File_POJO(String path, boolean isMedia) { // this.path = path; // this.isMedia = isMedia; // // children = new ArrayList<>(); // // excluded = Provider.isDirExcluded(getPath(), // Provider.getExcludedPaths()); // } // // public void addChild(File_POJO file) { // children.add(file); // } // // public File_POJO setName(String name) { // this.name = name; // return this; // } // // @Override // public String getName() { // if (name != null) { // return name; // } // String[] s = getPath().split("/"); // return s[s.length - 1]; // } // // @Override // public long getDate() { // //not needed // return new File(getPath()).lastModified(); // } // // @Override // public String toString() { // return getPath(); // } // // public String getPath() { // return path; // } // // @Override // public boolean pinned() { // return false; // } // // public ArrayList<File_POJO> getChildren() { // return children; // } // // @Override // public int describeContents() { // return 0; // } // // @Override // public void writeToParcel(Parcel parcel, int i) { // parcel.writeString(path); // parcel.writeString(name); // parcel.writeString(String.valueOf(isMedia)); // File_POJO[] children = new File_POJO[this.children.size()]; // for (int k = 0; k < children.length; k++) { // children[k] = this.children.get(k); // } // parcel.writeTypedArray(children, 0); // parcel.writeString(String.valueOf(excluded)); // } // // @SuppressWarnings("unchecked") // public File_POJO(Parcel parcel) { // path = parcel.readString(); // name = parcel.readString(); // isMedia = Boolean.valueOf(parcel.readString()); // children = parcel.createTypedArrayList(CREATOR); // excluded = Boolean.valueOf(parcel.readString()); // } // // @SuppressWarnings("WeakerAccess") // public static final Parcelable.Creator CREATOR = new Parcelable.Creator() { // public File_POJO createFromParcel(Parcel parcel) { // return new File_POJO(parcel); // } // // @Override // public File_POJO[] newArray(int i) { // return new File_POJO[i]; // } // }; // // public static File_POJO[] generateArray(Parcelable[] parcelables) { // File_POJO[] files = new File_POJO[parcelables.length]; // for (int i = 0; i < parcelables.length; i++) { // files[i] = (File_POJO) parcelables[i]; // } // return files; // } // }
import android.content.Context; import android.content.Intent; import android.net.Uri; import android.os.Build; import android.os.Environment; import android.util.Log; import java.io.File; import java.util.ArrayList; import us.koller.cameraroll.R; import us.koller.cameraroll.data.models.File_POJO;
package us.koller.cameraroll.data.fileOperations; public class Move extends FileOperation { public static final String MOVED_FILES_PATHS = "MOVED_FILES_PATHS"; private ArrayList<String> movedFilePaths; @Override String getNotificationTitle() { return getString(R.string.move); } @Override public int getNotificationSmallIconRes() { return R.drawable.ic_folder_move_white; } @Override public void execute(Intent workIntent) {
// Path: app/src/main/java/us/koller/cameraroll/data/models/File_POJO.java // public class File_POJO // implements Parcelable, SortUtil.Sortable { // // private String path; // private String name; // // private ArrayList<File_POJO> children; // public boolean isMedia; // public boolean excluded; // // public File_POJO(String path, boolean isMedia) { // this.path = path; // this.isMedia = isMedia; // // children = new ArrayList<>(); // // excluded = Provider.isDirExcluded(getPath(), // Provider.getExcludedPaths()); // } // // public void addChild(File_POJO file) { // children.add(file); // } // // public File_POJO setName(String name) { // this.name = name; // return this; // } // // @Override // public String getName() { // if (name != null) { // return name; // } // String[] s = getPath().split("/"); // return s[s.length - 1]; // } // // @Override // public long getDate() { // //not needed // return new File(getPath()).lastModified(); // } // // @Override // public String toString() { // return getPath(); // } // // public String getPath() { // return path; // } // // @Override // public boolean pinned() { // return false; // } // // public ArrayList<File_POJO> getChildren() { // return children; // } // // @Override // public int describeContents() { // return 0; // } // // @Override // public void writeToParcel(Parcel parcel, int i) { // parcel.writeString(path); // parcel.writeString(name); // parcel.writeString(String.valueOf(isMedia)); // File_POJO[] children = new File_POJO[this.children.size()]; // for (int k = 0; k < children.length; k++) { // children[k] = this.children.get(k); // } // parcel.writeTypedArray(children, 0); // parcel.writeString(String.valueOf(excluded)); // } // // @SuppressWarnings("unchecked") // public File_POJO(Parcel parcel) { // path = parcel.readString(); // name = parcel.readString(); // isMedia = Boolean.valueOf(parcel.readString()); // children = parcel.createTypedArrayList(CREATOR); // excluded = Boolean.valueOf(parcel.readString()); // } // // @SuppressWarnings("WeakerAccess") // public static final Parcelable.Creator CREATOR = new Parcelable.Creator() { // public File_POJO createFromParcel(Parcel parcel) { // return new File_POJO(parcel); // } // // @Override // public File_POJO[] newArray(int i) { // return new File_POJO[i]; // } // }; // // public static File_POJO[] generateArray(Parcelable[] parcelables) { // File_POJO[] files = new File_POJO[parcelables.length]; // for (int i = 0; i < parcelables.length; i++) { // files[i] = (File_POJO) parcelables[i]; // } // return files; // } // } // Path: app/src/main/java/us/koller/cameraroll/data/fileOperations/Move.java import android.content.Context; import android.content.Intent; import android.net.Uri; import android.os.Build; import android.os.Environment; import android.util.Log; import java.io.File; import java.util.ArrayList; import us.koller.cameraroll.R; import us.koller.cameraroll.data.models.File_POJO; package us.koller.cameraroll.data.fileOperations; public class Move extends FileOperation { public static final String MOVED_FILES_PATHS = "MOVED_FILES_PATHS"; private ArrayList<String> movedFilePaths; @Override String getNotificationTitle() { return getString(R.string.move); } @Override public int getNotificationSmallIconRes() { return R.drawable.ic_folder_move_white; } @Override public void execute(Intent workIntent) {
File_POJO[] files = getFiles(workIntent);
xm-online/xm-lep
xm-lep-api-commons/src/main/java/com/icthh/xm/lep/api/commons/DefaultLepResourceDescriptor.java
// Path: xm-lep-api/src/main/java/com/icthh/xm/lep/api/LepResourceDescriptor.java // public interface LepResourceDescriptor { // // /** // * Composite class constant. // */ // Class<CompositeLepResourceDescriptor> COMPOSITE_CLASS = CompositeLepResourceDescriptor.class; // // LepResourceType getType(); // // LepResourceType getSubType(); // // LepResourceKey getKey(); // // Instant getCreationTime(); // // Instant getModificationTime(); // // Version getVersion(); // // default boolean isComposite() { // return COMPOSITE_CLASS.isInstance(this); // } // // /** // * Check is composite implementation and if so cast or throw exception otherwise. // * // * @return composite class representation of resource descriptor // */ // default CompositeLepResourceDescriptor asComposite() { // if (isComposite()) { // return COMPOSITE_CLASS.cast(this); // } else { // throw new IllegalStateException("Can't cast not composite: " // + this.getClass().getSimpleName() // + " object to composite: " // + COMPOSITE_CLASS.getSimpleName()); // } // } // // } // // Path: xm-lep-api/src/main/java/com/icthh/xm/lep/api/LepResourceKey.java // public interface LepResourceKey { // // String getId(); // // Version getVersion(); // // } // // Path: xm-lep-api/src/main/java/com/icthh/xm/lep/api/LepResourceType.java // public interface LepResourceType { // // String getName(); // // } // // Path: xm-lep-api/src/main/java/com/icthh/xm/lep/api/Version.java // public interface Version { // // /** // * Gets version identificator, for example: // * <br> // * 'b324', '1-alpha', '1.2.3', '1.0-RELEASE', '2.2-RC1', '2.2.3-M1', '12032017112331', etc. // * // * @return version id // */ // String getId(); // // }
import com.icthh.xm.lep.api.LepResourceDescriptor; import com.icthh.xm.lep.api.LepResourceKey; import com.icthh.xm.lep.api.LepResourceType; import com.icthh.xm.lep.api.Version; import java.time.Instant; import java.util.Objects;
package com.icthh.xm.lep.api.commons; /** * The {@link DefaultLepResourceDescriptor} class. */ public class DefaultLepResourceDescriptor implements LepResourceDescriptor { private LepResourceType type; private LepResourceType subType;
// Path: xm-lep-api/src/main/java/com/icthh/xm/lep/api/LepResourceDescriptor.java // public interface LepResourceDescriptor { // // /** // * Composite class constant. // */ // Class<CompositeLepResourceDescriptor> COMPOSITE_CLASS = CompositeLepResourceDescriptor.class; // // LepResourceType getType(); // // LepResourceType getSubType(); // // LepResourceKey getKey(); // // Instant getCreationTime(); // // Instant getModificationTime(); // // Version getVersion(); // // default boolean isComposite() { // return COMPOSITE_CLASS.isInstance(this); // } // // /** // * Check is composite implementation and if so cast or throw exception otherwise. // * // * @return composite class representation of resource descriptor // */ // default CompositeLepResourceDescriptor asComposite() { // if (isComposite()) { // return COMPOSITE_CLASS.cast(this); // } else { // throw new IllegalStateException("Can't cast not composite: " // + this.getClass().getSimpleName() // + " object to composite: " // + COMPOSITE_CLASS.getSimpleName()); // } // } // // } // // Path: xm-lep-api/src/main/java/com/icthh/xm/lep/api/LepResourceKey.java // public interface LepResourceKey { // // String getId(); // // Version getVersion(); // // } // // Path: xm-lep-api/src/main/java/com/icthh/xm/lep/api/LepResourceType.java // public interface LepResourceType { // // String getName(); // // } // // Path: xm-lep-api/src/main/java/com/icthh/xm/lep/api/Version.java // public interface Version { // // /** // * Gets version identificator, for example: // * <br> // * 'b324', '1-alpha', '1.2.3', '1.0-RELEASE', '2.2-RC1', '2.2.3-M1', '12032017112331', etc. // * // * @return version id // */ // String getId(); // // } // Path: xm-lep-api-commons/src/main/java/com/icthh/xm/lep/api/commons/DefaultLepResourceDescriptor.java import com.icthh.xm.lep.api.LepResourceDescriptor; import com.icthh.xm.lep.api.LepResourceKey; import com.icthh.xm.lep.api.LepResourceType; import com.icthh.xm.lep.api.Version; import java.time.Instant; import java.util.Objects; package com.icthh.xm.lep.api.commons; /** * The {@link DefaultLepResourceDescriptor} class. */ public class DefaultLepResourceDescriptor implements LepResourceDescriptor { private LepResourceType type; private LepResourceType subType;
private LepResourceKey key;
xm-online/xm-lep
xm-lep-api-commons/src/main/java/com/icthh/xm/lep/api/commons/DefaultLepResourceDescriptor.java
// Path: xm-lep-api/src/main/java/com/icthh/xm/lep/api/LepResourceDescriptor.java // public interface LepResourceDescriptor { // // /** // * Composite class constant. // */ // Class<CompositeLepResourceDescriptor> COMPOSITE_CLASS = CompositeLepResourceDescriptor.class; // // LepResourceType getType(); // // LepResourceType getSubType(); // // LepResourceKey getKey(); // // Instant getCreationTime(); // // Instant getModificationTime(); // // Version getVersion(); // // default boolean isComposite() { // return COMPOSITE_CLASS.isInstance(this); // } // // /** // * Check is composite implementation and if so cast or throw exception otherwise. // * // * @return composite class representation of resource descriptor // */ // default CompositeLepResourceDescriptor asComposite() { // if (isComposite()) { // return COMPOSITE_CLASS.cast(this); // } else { // throw new IllegalStateException("Can't cast not composite: " // + this.getClass().getSimpleName() // + " object to composite: " // + COMPOSITE_CLASS.getSimpleName()); // } // } // // } // // Path: xm-lep-api/src/main/java/com/icthh/xm/lep/api/LepResourceKey.java // public interface LepResourceKey { // // String getId(); // // Version getVersion(); // // } // // Path: xm-lep-api/src/main/java/com/icthh/xm/lep/api/LepResourceType.java // public interface LepResourceType { // // String getName(); // // } // // Path: xm-lep-api/src/main/java/com/icthh/xm/lep/api/Version.java // public interface Version { // // /** // * Gets version identificator, for example: // * <br> // * 'b324', '1-alpha', '1.2.3', '1.0-RELEASE', '2.2-RC1', '2.2.3-M1', '12032017112331', etc. // * // * @return version id // */ // String getId(); // // }
import com.icthh.xm.lep.api.LepResourceDescriptor; import com.icthh.xm.lep.api.LepResourceKey; import com.icthh.xm.lep.api.LepResourceType; import com.icthh.xm.lep.api.Version; import java.time.Instant; import java.util.Objects;
} /** * {@inheritDoc} */ @Override public LepResourceKey getKey() { return key; } /** * {@inheritDoc} */ @Override public Instant getCreationTime() { return creationTime; } /** * {@inheritDoc} */ @Override public Instant getModificationTime() { return modificationTime; } /** * {@inheritDoc} */ @Override
// Path: xm-lep-api/src/main/java/com/icthh/xm/lep/api/LepResourceDescriptor.java // public interface LepResourceDescriptor { // // /** // * Composite class constant. // */ // Class<CompositeLepResourceDescriptor> COMPOSITE_CLASS = CompositeLepResourceDescriptor.class; // // LepResourceType getType(); // // LepResourceType getSubType(); // // LepResourceKey getKey(); // // Instant getCreationTime(); // // Instant getModificationTime(); // // Version getVersion(); // // default boolean isComposite() { // return COMPOSITE_CLASS.isInstance(this); // } // // /** // * Check is composite implementation and if so cast or throw exception otherwise. // * // * @return composite class representation of resource descriptor // */ // default CompositeLepResourceDescriptor asComposite() { // if (isComposite()) { // return COMPOSITE_CLASS.cast(this); // } else { // throw new IllegalStateException("Can't cast not composite: " // + this.getClass().getSimpleName() // + " object to composite: " // + COMPOSITE_CLASS.getSimpleName()); // } // } // // } // // Path: xm-lep-api/src/main/java/com/icthh/xm/lep/api/LepResourceKey.java // public interface LepResourceKey { // // String getId(); // // Version getVersion(); // // } // // Path: xm-lep-api/src/main/java/com/icthh/xm/lep/api/LepResourceType.java // public interface LepResourceType { // // String getName(); // // } // // Path: xm-lep-api/src/main/java/com/icthh/xm/lep/api/Version.java // public interface Version { // // /** // * Gets version identificator, for example: // * <br> // * 'b324', '1-alpha', '1.2.3', '1.0-RELEASE', '2.2-RC1', '2.2.3-M1', '12032017112331', etc. // * // * @return version id // */ // String getId(); // // } // Path: xm-lep-api-commons/src/main/java/com/icthh/xm/lep/api/commons/DefaultLepResourceDescriptor.java import com.icthh.xm.lep.api.LepResourceDescriptor; import com.icthh.xm.lep.api.LepResourceKey; import com.icthh.xm.lep.api.LepResourceType; import com.icthh.xm.lep.api.Version; import java.time.Instant; import java.util.Objects; } /** * {@inheritDoc} */ @Override public LepResourceKey getKey() { return key; } /** * {@inheritDoc} */ @Override public Instant getCreationTime() { return creationTime; } /** * {@inheritDoc} */ @Override public Instant getModificationTime() { return modificationTime; } /** * {@inheritDoc} */ @Override
public Version getVersion() {
xm-online/xm-lep
xm-lep-api-commons/src/main/java/com/icthh/xm/lep/api/commons/StringLepResourceKey.java
// Path: xm-lep-api/src/main/java/com/icthh/xm/lep/api/LepResourceKey.java // public interface LepResourceKey { // // String getId(); // // Version getVersion(); // // } // // Path: xm-lep-api/src/main/java/com/icthh/xm/lep/api/Version.java // public interface Version { // // /** // * Gets version identificator, for example: // * <br> // * 'b324', '1-alpha', '1.2.3', '1.0-RELEASE', '2.2-RC1', '2.2.3-M1', '12032017112331', etc. // * // * @return version id // */ // String getId(); // // }
import com.icthh.xm.lep.api.LepResourceKey; import com.icthh.xm.lep.api.Version; import java.util.Objects;
package com.icthh.xm.lep.api.commons; /** * The {@link StringLepResourceKey} class. */ public class StringLepResourceKey implements LepResourceKey { private final String resourceKeyId;
// Path: xm-lep-api/src/main/java/com/icthh/xm/lep/api/LepResourceKey.java // public interface LepResourceKey { // // String getId(); // // Version getVersion(); // // } // // Path: xm-lep-api/src/main/java/com/icthh/xm/lep/api/Version.java // public interface Version { // // /** // * Gets version identificator, for example: // * <br> // * 'b324', '1-alpha', '1.2.3', '1.0-RELEASE', '2.2-RC1', '2.2.3-M1', '12032017112331', etc. // * // * @return version id // */ // String getId(); // // } // Path: xm-lep-api-commons/src/main/java/com/icthh/xm/lep/api/commons/StringLepResourceKey.java import com.icthh.xm.lep.api.LepResourceKey; import com.icthh.xm.lep.api.Version; import java.util.Objects; package com.icthh.xm.lep.api.commons; /** * The {@link StringLepResourceKey} class. */ public class StringLepResourceKey implements LepResourceKey { private final String resourceKeyId;
private final Version version;
xm-online/xm-lep
xm-lep-api-commons/src/main/java/com/icthh/xm/lep/api/commons/UrlLepResourceKey.java
// Path: xm-lep-api/src/main/java/com/icthh/xm/lep/api/LepResourceKey.java // public interface LepResourceKey { // // String getId(); // // Version getVersion(); // // } // // Path: xm-lep-api/src/main/java/com/icthh/xm/lep/api/Version.java // public interface Version { // // /** // * Gets version identificator, for example: // * <br> // * 'b324', '1-alpha', '1.2.3', '1.0-RELEASE', '2.2-RC1', '2.2.3-M1', '12032017112331', etc. // * // * @return version id // */ // String getId(); // // }
import static java.util.stream.Collectors.mapping; import static java.util.stream.Collectors.toList; import com.icthh.xm.lep.api.LepResourceKey; import com.icthh.xm.lep.api.Version; import java.io.IOException; import java.net.MalformedURLException; import java.net.URL; import java.net.URLConnection; import java.net.URLStreamHandler; import java.util.AbstractMap.SimpleImmutableEntry; import java.util.Arrays; import java.util.Collections; import java.util.LinkedHashMap; import java.util.List; import java.util.Map; import java.util.Objects; import java.util.stream.Collectors;
package com.icthh.xm.lep.api.commons; /** * The {@link UrlLepResourceKey} class. */ public class UrlLepResourceKey implements LepResourceKey { public static final String LEP_PROTOCOL = "lep"; public static final int DEFAULT_PORT = -1; public static final String PARAM_VERSION = "version"; private static final String URL_PARAM_VALUE_SPLITTER = "="; private static final String URL_PARAMS_SPLITTER = "&"; private static final int MAX_URL_PARARMS_VERSION = 1; private final URL url;
// Path: xm-lep-api/src/main/java/com/icthh/xm/lep/api/LepResourceKey.java // public interface LepResourceKey { // // String getId(); // // Version getVersion(); // // } // // Path: xm-lep-api/src/main/java/com/icthh/xm/lep/api/Version.java // public interface Version { // // /** // * Gets version identificator, for example: // * <br> // * 'b324', '1-alpha', '1.2.3', '1.0-RELEASE', '2.2-RC1', '2.2.3-M1', '12032017112331', etc. // * // * @return version id // */ // String getId(); // // } // Path: xm-lep-api-commons/src/main/java/com/icthh/xm/lep/api/commons/UrlLepResourceKey.java import static java.util.stream.Collectors.mapping; import static java.util.stream.Collectors.toList; import com.icthh.xm.lep.api.LepResourceKey; import com.icthh.xm.lep.api.Version; import java.io.IOException; import java.net.MalformedURLException; import java.net.URL; import java.net.URLConnection; import java.net.URLStreamHandler; import java.util.AbstractMap.SimpleImmutableEntry; import java.util.Arrays; import java.util.Collections; import java.util.LinkedHashMap; import java.util.List; import java.util.Map; import java.util.Objects; import java.util.stream.Collectors; package com.icthh.xm.lep.api.commons; /** * The {@link UrlLepResourceKey} class. */ public class UrlLepResourceKey implements LepResourceKey { public static final String LEP_PROTOCOL = "lep"; public static final int DEFAULT_PORT = -1; public static final String PARAM_VERSION = "version"; private static final String URL_PARAM_VALUE_SPLITTER = "="; private static final String URL_PARAMS_SPLITTER = "&"; private static final int MAX_URL_PARARMS_VERSION = 1; private final URL url;
private final Version version;
xm-online/xm-lep
xm-lep-script/src/main/java/com/icthh/xm/lep/script/CompositeScriptLepResource.java
// Path: xm-lep-api/src/main/java/com/icthh/xm/lep/api/CompositeLepResource.java // public interface CompositeLepResource extends LepResource { // // List<LepResource> getChildren(); // // } // // Path: xm-lep-api/src/main/java/com/icthh/xm/lep/api/LepResource.java // public interface LepResource { // // /** // * Composite class constant. // */ // Class<CompositeLepResource> COMPOSITE_CLASS = CompositeLepResource.class; // // LepResourceDescriptor getDescriptor(); // // <V> V getValue(Class<? extends V> valueClass); // // default boolean isComposite() { // return COMPOSITE_CLASS.isInstance(this); // } // // /** // * Check is composite implementation and if so cast or throw exception otherwise. // * // * @return composite class representation of resource // */ // default CompositeLepResource asComposite() { // if (isComposite()) { // return COMPOSITE_CLASS.cast(this); // } else { // throw new IllegalStateException("Can't cast not composite: " // + this.getClass().getSimpleName() // + " object to composite: " // + COMPOSITE_CLASS.getSimpleName()); // } // } // // } // // Path: xm-lep-api/src/main/java/com/icthh/xm/lep/api/LepResourceDescriptor.java // public interface LepResourceDescriptor { // // /** // * Composite class constant. // */ // Class<CompositeLepResourceDescriptor> COMPOSITE_CLASS = CompositeLepResourceDescriptor.class; // // LepResourceType getType(); // // LepResourceType getSubType(); // // LepResourceKey getKey(); // // Instant getCreationTime(); // // Instant getModificationTime(); // // Version getVersion(); // // default boolean isComposite() { // return COMPOSITE_CLASS.isInstance(this); // } // // /** // * Check is composite implementation and if so cast or throw exception otherwise. // * // * @return composite class representation of resource descriptor // */ // default CompositeLepResourceDescriptor asComposite() { // if (isComposite()) { // return COMPOSITE_CLASS.cast(this); // } else { // throw new IllegalStateException("Can't cast not composite: " // + this.getClass().getSimpleName() // + " object to composite: " // + COMPOSITE_CLASS.getSimpleName()); // } // } // // }
import com.icthh.xm.lep.api.CompositeLepResource; import com.icthh.xm.lep.api.LepResource; import com.icthh.xm.lep.api.LepResourceDescriptor; import java.util.Collections; import java.util.List;
package com.icthh.xm.lep.script; /** * The {@link CompositeScriptLepResource} class. */ public class CompositeScriptLepResource extends ScriptLepResource implements CompositeLepResource { private List<LepResource> children;
// Path: xm-lep-api/src/main/java/com/icthh/xm/lep/api/CompositeLepResource.java // public interface CompositeLepResource extends LepResource { // // List<LepResource> getChildren(); // // } // // Path: xm-lep-api/src/main/java/com/icthh/xm/lep/api/LepResource.java // public interface LepResource { // // /** // * Composite class constant. // */ // Class<CompositeLepResource> COMPOSITE_CLASS = CompositeLepResource.class; // // LepResourceDescriptor getDescriptor(); // // <V> V getValue(Class<? extends V> valueClass); // // default boolean isComposite() { // return COMPOSITE_CLASS.isInstance(this); // } // // /** // * Check is composite implementation and if so cast or throw exception otherwise. // * // * @return composite class representation of resource // */ // default CompositeLepResource asComposite() { // if (isComposite()) { // return COMPOSITE_CLASS.cast(this); // } else { // throw new IllegalStateException("Can't cast not composite: " // + this.getClass().getSimpleName() // + " object to composite: " // + COMPOSITE_CLASS.getSimpleName()); // } // } // // } // // Path: xm-lep-api/src/main/java/com/icthh/xm/lep/api/LepResourceDescriptor.java // public interface LepResourceDescriptor { // // /** // * Composite class constant. // */ // Class<CompositeLepResourceDescriptor> COMPOSITE_CLASS = CompositeLepResourceDescriptor.class; // // LepResourceType getType(); // // LepResourceType getSubType(); // // LepResourceKey getKey(); // // Instant getCreationTime(); // // Instant getModificationTime(); // // Version getVersion(); // // default boolean isComposite() { // return COMPOSITE_CLASS.isInstance(this); // } // // /** // * Check is composite implementation and if so cast or throw exception otherwise. // * // * @return composite class representation of resource descriptor // */ // default CompositeLepResourceDescriptor asComposite() { // if (isComposite()) { // return COMPOSITE_CLASS.cast(this); // } else { // throw new IllegalStateException("Can't cast not composite: " // + this.getClass().getSimpleName() // + " object to composite: " // + COMPOSITE_CLASS.getSimpleName()); // } // } // // } // Path: xm-lep-script/src/main/java/com/icthh/xm/lep/script/CompositeScriptLepResource.java import com.icthh.xm.lep.api.CompositeLepResource; import com.icthh.xm.lep.api.LepResource; import com.icthh.xm.lep.api.LepResourceDescriptor; import java.util.Collections; import java.util.List; package com.icthh.xm.lep.script; /** * The {@link CompositeScriptLepResource} class. */ public class CompositeScriptLepResource extends ScriptLepResource implements CompositeLepResource { private List<LepResource> children;
public CompositeScriptLepResource(LepResourceDescriptor descriptor,
xm-online/xm-lep
xm-lep-groovy/src/main/java/com/icthh/xm/lep/groovy/ExecutionStrategy.java
// Path: xm-lep-api/src/main/java/com/icthh/xm/lep/api/LepInvocationCauseException.java // public class LepInvocationCauseException extends Exception { // // /** // * Serial UID. // */ // private static final long serialVersionUID = -6216272704551111089L; // // /** // * This field holds the cause if the // * LepInvocationCauseException(Throwable lepCause) constructor was // * used to instantiate the object. // */ // private Exception lepCause; // // /** // * Constructs an {@code LepInvocationCauseException} with // * {@code null} as the target exception. // */ // private LepInvocationCauseException() { // super((Exception) null); // Disallow initCause // } // // /** // * Constructs a LepInvocationCauseException with a LEP exception. // * // * @param lepCause the LEP exception // */ // public LepInvocationCauseException(Exception lepCause) { // super((Exception) null); // Disallow initCause // this.lepCause = lepCause; // } // // /** // * Constructs a InvocationTargetException with a target exception // * and a detail message. // * // * @param lepCause the LEP exception // * @param msg the detail message // */ // public LepInvocationCauseException(Exception lepCause, String msg) { // super(msg, null); // Disallow initCause // this.lepCause = lepCause; // } // // /** // * Returns the cause of this exception (the LEP thrown cause exception, // * which may be {@code null}). // * // * @return the cause of this exception. // */ // @Override // public Exception getCause() { // return lepCause; // } // // } // // Path: xm-lep-api/src/main/java/com/icthh/xm/lep/api/LepManagerService.java // public interface LepManagerService extends ContextsHolder { // // ExtensionService getExtensionService(); // // LepResourceService getResourceService(); // // } // // Path: xm-lep-api/src/main/java/com/icthh/xm/lep/api/LepMethod.java // public interface LepMethod { // // Object getTarget(); // // MethodSignature getMethodSignature(); // // Object[] getMethodArgValues(); // // } // // Path: xm-lep-api/src/main/java/com/icthh/xm/lep/api/LepResourceKey.java // public interface LepResourceKey { // // String getId(); // // Version getVersion(); // // }
import com.icthh.xm.lep.api.LepInvocationCauseException; import com.icthh.xm.lep.api.LepManagerService; import com.icthh.xm.lep.api.LepMethod; import com.icthh.xm.lep.api.LepResourceKey; import java.util.function.Supplier;
package com.icthh.xm.lep.groovy; /** * The {@link ExecutionStrategy} interface. */ public interface ExecutionStrategy<E, K extends LepResourceKey> { /** * Executes LEP resource using some executor. * * @param resourceKey LEP resource key * @param method LEP method info data * @param managerService LEP manager service * @param resourceExecutorSupplier LEP resource executor supplier function * @return LEP method result * @throws LepInvocationCauseException when LEP invocation resource throws exception */ Object executeLepResource(K resourceKey,
// Path: xm-lep-api/src/main/java/com/icthh/xm/lep/api/LepInvocationCauseException.java // public class LepInvocationCauseException extends Exception { // // /** // * Serial UID. // */ // private static final long serialVersionUID = -6216272704551111089L; // // /** // * This field holds the cause if the // * LepInvocationCauseException(Throwable lepCause) constructor was // * used to instantiate the object. // */ // private Exception lepCause; // // /** // * Constructs an {@code LepInvocationCauseException} with // * {@code null} as the target exception. // */ // private LepInvocationCauseException() { // super((Exception) null); // Disallow initCause // } // // /** // * Constructs a LepInvocationCauseException with a LEP exception. // * // * @param lepCause the LEP exception // */ // public LepInvocationCauseException(Exception lepCause) { // super((Exception) null); // Disallow initCause // this.lepCause = lepCause; // } // // /** // * Constructs a InvocationTargetException with a target exception // * and a detail message. // * // * @param lepCause the LEP exception // * @param msg the detail message // */ // public LepInvocationCauseException(Exception lepCause, String msg) { // super(msg, null); // Disallow initCause // this.lepCause = lepCause; // } // // /** // * Returns the cause of this exception (the LEP thrown cause exception, // * which may be {@code null}). // * // * @return the cause of this exception. // */ // @Override // public Exception getCause() { // return lepCause; // } // // } // // Path: xm-lep-api/src/main/java/com/icthh/xm/lep/api/LepManagerService.java // public interface LepManagerService extends ContextsHolder { // // ExtensionService getExtensionService(); // // LepResourceService getResourceService(); // // } // // Path: xm-lep-api/src/main/java/com/icthh/xm/lep/api/LepMethod.java // public interface LepMethod { // // Object getTarget(); // // MethodSignature getMethodSignature(); // // Object[] getMethodArgValues(); // // } // // Path: xm-lep-api/src/main/java/com/icthh/xm/lep/api/LepResourceKey.java // public interface LepResourceKey { // // String getId(); // // Version getVersion(); // // } // Path: xm-lep-groovy/src/main/java/com/icthh/xm/lep/groovy/ExecutionStrategy.java import com.icthh.xm.lep.api.LepInvocationCauseException; import com.icthh.xm.lep.api.LepManagerService; import com.icthh.xm.lep.api.LepMethod; import com.icthh.xm.lep.api.LepResourceKey; import java.util.function.Supplier; package com.icthh.xm.lep.groovy; /** * The {@link ExecutionStrategy} interface. */ public interface ExecutionStrategy<E, K extends LepResourceKey> { /** * Executes LEP resource using some executor. * * @param resourceKey LEP resource key * @param method LEP method info data * @param managerService LEP manager service * @param resourceExecutorSupplier LEP resource executor supplier function * @return LEP method result * @throws LepInvocationCauseException when LEP invocation resource throws exception */ Object executeLepResource(K resourceKey,
LepMethod method,