lang
stringclasses
2 values
license
stringclasses
13 values
stderr
stringlengths
0
343
commit
stringlengths
40
40
returncode
int64
0
128
repos
stringlengths
6
87.7k
new_contents
stringlengths
0
6.23M
new_file
stringlengths
3
311
old_contents
stringlengths
0
6.23M
message
stringlengths
6
9.1k
old_file
stringlengths
3
311
subject
stringlengths
0
4k
git_diff
stringlengths
0
6.31M
Java
mit
41b356f649cb224c2243a921c27aee5c2435414b
0
CoursesPlus/CoursesPlusInstaller
package io.github.coursesplus.installer; import java.awt.Dimension; import java.awt.Font; import java.awt.GridLayout; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.io.File; import java.io.FileNotFoundException; import java.io.IOException; import java.io.PrintWriter; import java.io.UnsupportedEncodingException; import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.Paths; import java.nio.file.attribute.PosixFilePermission; import java.util.Set; import java.util.logging.Level; import java.util.logging.Logger; import javax.swing.ImageIcon; import javax.swing.JButton; import javax.swing.JFrame; import javax.swing.JLabel; import javax.swing.JOptionPane; import com.apple.eawt.Application; @SuppressWarnings("serial") public class CoursesPlusInstaller extends JFrame implements ActionListener { public static final String VERSION = "0.1"; public static Logger logger; public static Dimension screenSize; public static Font font; public static Font bigFont; public static Font titleFont; public static final String BASE_PATH = "/Users" + System.getProperty("user.name") + "Library/Application Support/Google/Chrome/"; public static final String FOLDER_NAME = "External Extensions"; public static final String EXT_ID = "pieincmodljnbihihjnapcmhdddhbpgi"; public static final String EXT_FILE = "{\"external_update_url\": \"https://clients2.google.com/service/update2/crx\"}"; public static final String LOAD_PAGE = "data:text/html,<h1>Loading, please wait...</h1><h2>Do not navigate away from this page while installation is in progress.</h2>"; public CoursesPlusInstaller() { super("CoursesPlus Installer v" + VERSION); logger = Logger.getLogger(CoursesPlusInstaller.class.getName()); screenSize = java.awt.Toolkit.getDefaultToolkit().getScreenSize(); Application.getApplication().setDockIconImage(new ImageIcon(getClass().getResource("Logo.png")).getImage()); public class Launcher { public static void main(String[] args) { System.setProperty("com.apple.mrj.application.apple.menu.about.name", "CoursesPlus Installer"); JFrame jframe = new MyJFrame(); jframe.setVisible(true); } } try { // try and load Lato font = Font.createFont(Font.TRUETYPE_FONT, getClass().getResourceAsStream("Lato-Regular.ttf")); font = font.deriveFont(14f); bigFont = font.deriveFont(32f); titleFont = font.deriveFont(64f); } catch (Exception e) { // if it failed, fallbacks // but first log failure logger.log(Level.WARNING, "Failed to load fonts - " + e.getMessage(), e); font = new Font("SansSerif", Font.PLAIN, 14); bigFont = new Font("SansSerif", Font.PLAIN, 32); titleFont = new Font("SansSerif", Font.PLAIN, 64); } setLayout(new GridLayout(3, 1)); JLabel title = new JLabel("CoursesPlus", JLabel.CENTER); title.setFont(titleFont); add(title); JButton install = new JButton("Install"); install.setFont(bigFont); install.addActionListener(this); add(install); JLabel info = new JLabel("<html><div width=\"400px\" style=\"text-align:center;\">Hi " + System.getProperty("user.name") + "! This installer will install CoursesPlus into Google Chrome. It will connect to the Internet to download the latest version of CoursesPlus, and then set up automatic updates. Anonymous analytics may be sent to us for statistical purposes. If an error occurs, you will be given the option to transmit information about the error to us so we can fix it.</div></html>", JLabel.CENTER); info.setFont(font); add(info); setBounds((screenSize.width - 600) / 2, (screenSize.height - 400) / 2, 600, 400); setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); setVisible(true); } public static void main(String[] args) { new CoursesPlusInstaller(); } @Override public void actionPerformed(ActionEvent e) { Object source = e.getSource(); String text = ((JButton)source).getText(); switch (text) { case "Install": JOptionPane.showMessageDialog(null, "Make sure you've closed open Chrome windows. Any windows remaining open will automatically be closed after pressing OK.", "Close Chrome windows", JOptionPane.WARNING_MESSAGE); try { Runtime.getRuntime().exec(new String[]{"killall", "Google Chrome"}); } catch (IOException e4) { // TODO Auto-generated catch block e4.printStackTrace(); } File destDir = new File(BASE_PATH + FOLDER_NAME); if (!destDir.exists()) { destDir.mkdir(); destDir = new File(BASE_PATH + FOLDER_NAME); } try { PrintWriter writer = new PrintWriter(BASE_PATH + FOLDER_NAME + "/" + EXT_ID + ".json", "UTF-8"); writer.write(EXT_FILE); writer.close(); } catch (FileNotFoundException e1) { // TODO Auto-generated catch block e1.printStackTrace(); } catch (UnsupportedEncodingException e1) { // TODO Auto-generated catch block e1.printStackTrace(); } // Clear out extension blacklist so user can reinstall extension if they removed it // should ask NLTL to put CoursesPlus on policy-set whitelist.... Path blDir = Paths.get("/Users/" + System.getProperty("user.name") + "/Library/Application Support/Google/Chrome/Safe Browsing Extension Blacklist"); try { Files.deleteIfExists(blDir); } catch (IOException e3) { // TODO Auto-generated catch block e3.printStackTrace(); } Path extensionDir = Paths.get("/Users/" + System.getProperty("user.name") + "/Library/Application Support/Google/Chrome/Default/Extensions"); Set<PosixFilePermission> orig = null; try { // save original Extensions dir permissions orig = Files.getPosixFilePermissions(extensionDir); // make Extensions dir writeable Set<PosixFilePermission> perms = Files.getPosixFilePermissions(extensionDir); perms.add(PosixFilePermission.OWNER_WRITE); Files.setPosixFilePermissions(extensionDir, perms); // open Chrome String[] cmd = {"/Applications/Google Chrome.app/Contents/MacOS/Google Chrome", LOAD_PAGE}; Process chrome = Runtime.getRuntime().exec(cmd); Thread.sleep(7500); Runtime.getRuntime().exec(new String[]{"killall", "Google Chrome"}); Thread.sleep(100); Runtime.getRuntime().exec(new String[]{"killall", "Google Chrome"}); // restore Extensions dir permissions Files.setPosixFilePermissions(extensionDir, orig); } catch (IOException e1) { // TODO Auto-generated catch block e1.printStackTrace(); } catch (InterruptedException e1) { // TODO Auto-generated catch block if (orig != null) { // restore the permissions try { Files.setPosixFilePermissions(extensionDir, orig); } catch (IOException e2) { // TODO Auto-generated catch block e2.printStackTrace(); } } e1.printStackTrace(); } JOptionPane.showMessageDialog(null, "The installation has been completed. See you later, " + System.getProperty("user.name")); break; default: logger.warning("Unknown button pressed - " + text); break; } } }
src/io/github/coursesplus/installer/CoursesPlusInstaller.java
package io.github.coursesplus.installer; import java.awt.Dimension; import java.awt.Font; import java.awt.GridLayout; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.io.File; import java.io.FileNotFoundException; import java.io.IOException; import java.io.PrintWriter; import java.io.UnsupportedEncodingException; import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.Paths; import java.nio.file.attribute.PosixFilePermission; import java.util.Set; import java.util.logging.Level; import java.util.logging.Logger; import javax.swing.ImageIcon; import javax.swing.JButton; import javax.swing.JFrame; import javax.swing.JLabel; import javax.swing.JOptionPane; import com.apple.eawt.Application; @SuppressWarnings("serial") public class CoursesPlusInstaller extends JFrame implements ActionListener { public static final String VERSION = "0.1"; public static Logger logger; public static Dimension screenSize; public static Font font; public static Font bigFont; public static Font titleFont; public static final String BASE_PATH = "/Users" + System.getProperty("user.name") + "Library/Application Support/Google/Chrome/"; public static final String FOLDER_NAME = "External Extensions"; public static final String EXT_ID = "pieincmodljnbihihjnapcmhdddhbpgi"; public static final String EXT_FILE = "{\"external_update_url\": \"https://clients2.google.com/service/update2/crx\"}"; public static final String LOAD_PAGE = "data:text/html,<h1>Loading, please wait...</h1><h2>Do not navigate away from this page while installation is in progress.</h2>"; public CoursesPlusInstaller() { super("CoursesPlus Installer v" + VERSION); logger = Logger.getLogger(CoursesPlusInstaller.class.getName()); screenSize = java.awt.Toolkit.getDefaultToolkit().getScreenSize(); Application.getApplication().setDockIconImage(new ImageIcon(getClass().getResource("Logo.png")).getImage()); java -Xdock:name="CoursesPlus Installer" -jar myapp.jar try { // try and load Lato font = Font.createFont(Font.TRUETYPE_FONT, getClass().getResourceAsStream("Lato-Regular.ttf")); font = font.deriveFont(14f); bigFont = font.deriveFont(32f); titleFont = font.deriveFont(64f); } catch (Exception e) { // if it failed, fallbacks // but first log failure logger.log(Level.WARNING, "Failed to load fonts - " + e.getMessage(), e); font = new Font("SansSerif", Font.PLAIN, 14); bigFont = new Font("SansSerif", Font.PLAIN, 32); titleFont = new Font("SansSerif", Font.PLAIN, 64); } setLayout(new GridLayout(3, 1)); JLabel title = new JLabel("CoursesPlus", JLabel.CENTER); title.setFont(titleFont); add(title); JButton install = new JButton("Install"); install.setFont(bigFont); install.addActionListener(this); add(install); JLabel info = new JLabel("<html><div width=\"400px\" style=\"text-align:center;\">Hi " + System.getProperty("user.name") + "! This installer will install CoursesPlus into Google Chrome. It will connect to the Internet to download the latest version of CoursesPlus, and then set up automatic updates. Anonymous analytics may be sent to us for statistical purposes. If an error occurs, you will be given the option to transmit information about the error to us so we can fix it.</div></html>", JLabel.CENTER); info.setFont(font); add(info); setBounds((screenSize.width - 600) / 2, (screenSize.height - 400) / 2, 600, 400); setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); setVisible(true); } public static void main(String[] args) { new CoursesPlusInstaller(); } @Override public void actionPerformed(ActionEvent e) { Object source = e.getSource(); String text = ((JButton)source).getText(); switch (text) { case "Install": JOptionPane.showMessageDialog(null, "Make sure you've closed open Chrome windows. Any windows remaining open will automatically be closed after pressing OK.", "Close Chrome windows", JOptionPane.WARNING_MESSAGE); try { Runtime.getRuntime().exec(new String[]{"killall", "Google Chrome"}); } catch (IOException e4) { // TODO Auto-generated catch block e4.printStackTrace(); } File destDir = new File(BASE_PATH + FOLDER_NAME); if (!destDir.exists()) { destDir.mkdir(); destDir = new File(BASE_PATH + FOLDER_NAME); } try { PrintWriter writer = new PrintWriter(BASE_PATH + FOLDER_NAME + "/" + EXT_ID + ".json", "UTF-8"); writer.write(EXT_FILE); writer.close(); } catch (FileNotFoundException e1) { // TODO Auto-generated catch block e1.printStackTrace(); } catch (UnsupportedEncodingException e1) { // TODO Auto-generated catch block e1.printStackTrace(); } // Clear out extension blacklist so user can reinstall extension if they removed it // should ask NLTL to put CoursesPlus on policy-set whitelist.... Path blDir = Paths.get("/Users/" + System.getProperty("user.name") + "/Library/Application Support/Google/Chrome/Safe Browsing Extension Blacklist"); try { Files.deleteIfExists(blDir); } catch (IOException e3) { // TODO Auto-generated catch block e3.printStackTrace(); } Path extensionDir = Paths.get("/Users/" + System.getProperty("user.name") + "/Library/Application Support/Google/Chrome/Default/Extensions"); Set<PosixFilePermission> orig = null; try { // save original Extensions dir permissions orig = Files.getPosixFilePermissions(extensionDir); // make Extensions dir writeable Set<PosixFilePermission> perms = Files.getPosixFilePermissions(extensionDir); perms.add(PosixFilePermission.OWNER_WRITE); Files.setPosixFilePermissions(extensionDir, perms); // open Chrome String[] cmd = {"/Applications/Google Chrome.app/Contents/MacOS/Google Chrome", LOAD_PAGE}; Process chrome = Runtime.getRuntime().exec(cmd); Thread.sleep(7500); Runtime.getRuntime().exec(new String[]{"killall", "Google Chrome"}); Thread.sleep(100); Runtime.getRuntime().exec(new String[]{"killall", "Google Chrome"}); // restore Extensions dir permissions Files.setPosixFilePermissions(extensionDir, orig); } catch (IOException e1) { // TODO Auto-generated catch block e1.printStackTrace(); } catch (InterruptedException e1) { // TODO Auto-generated catch block if (orig != null) { // restore the permissions try { Files.setPosixFilePermissions(extensionDir, orig); } catch (IOException e2) { // TODO Auto-generated catch block e2.printStackTrace(); } } e1.printStackTrace(); } JOptionPane.showMessageDialog(null, "The installation has been completed. See you later, " + System.getProperty("user.name")); break; default: logger.warning("Unknown button pressed - " + text); break; } } }
Fixed name
src/io/github/coursesplus/installer/CoursesPlusInstaller.java
Fixed name
<ide><path>rc/io/github/coursesplus/installer/CoursesPlusInstaller.java <ide> screenSize = java.awt.Toolkit.getDefaultToolkit().getScreenSize(); <ide> <ide> Application.getApplication().setDockIconImage(new ImageIcon(getClass().getResource("Logo.png")).getImage()); <del> java -Xdock:name="CoursesPlus Installer" -jar myapp.jar <add> public class Launcher { <add> public static void main(String[] args) { <add> System.setProperty("com.apple.mrj.application.apple.menu.about.name", "CoursesPlus Installer"); <add> JFrame jframe = new MyJFrame(); <add> jframe.setVisible(true); <add> } <add> } <ide> <ide> try { <ide> // try and load Lato
Java
mit
016ed27bcf208443512bff5ee1ef0fe68ecbf2a1
0
simonkro/do_mysql,simonkro/do_mysql,simonkro/do_mysql
package data_objects.util; import java.util.List; /** * * @author alexbcoles */ public final class StringUtil { public static String join(List<? extends Object> list, CharSequence delim) { StringBuilder sb = new StringBuilder(); return appendJoined(sb, list, delim).toString(); } public static StringBuilder appendJoined(StringBuilder sb, List<? extends Object> list) { return appendJoined(sb, list, ",", false); } public static StringBuilder appendJoined(StringBuilder sb, List<? extends Object> list, CharSequence delim) { return appendJoined(sb, list, delim, false); } public static StringBuilder appendJoinedAndQuoted(StringBuilder sb, List<? extends Object> list) { return appendJoined(sb, list, ",", true); } public static StringBuilder appendJoinedAndQuoted(StringBuilder sb, List<? extends Object> list, CharSequence delim) { return appendJoined(sb, list, delim, true); } public static StringBuilder appendQuoted(StringBuilder sb, Object toQuote) { sb.append("\"").append(toQuote).append("\""); return sb; } private static StringBuilder appendJoined(StringBuilder sb, List<? extends Object> list, CharSequence delim, boolean quote) { if (list.isEmpty()) { return sb.append(""); } if (quote) { appendQuoted(sb, list.get(0)); } else { sb.append(list.get(0)); } for (int i = 1; i < list.size(); i++) { sb.append(delim); if (quote) { appendQuoted(sb, list.get(i)); } else { sb.append(list.get(i)); } } return sb; } /** * Private constructor */ private StringUtil(){ } }
do_jdbc/src/main/java/data_objects/util/StringUtil.java
package data_objects.util; import java.util.List; /** * * @author alexbcoles */ public final class StringUtil { public static String join(List<? extends Object> list, CharSequence delim) { StringBuilder sb = new StringBuilder(); return appendJoined(sb, list, delim).toString(); } public static StringBuilder appendJoined(StringBuilder sb, List<? extends Object> list) { return appendJoined(sb, list, ",", false); } public static StringBuilder appendJoined(StringBuilder sb, List<? extends Object> list, CharSequence delim) { return appendJoined(sb, list, delim, false); } public static StringBuilder appendJoinedAndQuoted(StringBuilder sb, List<? extends Object> list) { return appendJoined(sb, list, ",", true); } public static StringBuilder appendJoinedAndQuoted(StringBuilder sb, List<? extends Object> list, CharSequence delim) { return appendJoined(sb, list, delim, true); } public static StringBuilder appendQuoted(StringBuilder sb, Object toQuote) { sb.append("\"").append(toQuote).append("\""); return sb; } private static StringBuilder appendJoined(StringBuilder sb, List<? extends Object> list, CharSequence delim, boolean quote) { if (list.isEmpty()) { return sb.append(""); } if (quote) { appendQuoted(sb, list.get(0)); } else { sb.append(list.get(0)); } for (int i = 1; i < list.size(); i++) { sb.append(delim); if (quote) { appendQuoted(sb, list.get(i)); } else { sb.append(list.get(i)); } } return sb; } }
[do_jdbc] StringUtil prevented from instantiating
do_jdbc/src/main/java/data_objects/util/StringUtil.java
[do_jdbc] StringUtil prevented from instantiating
<ide><path>o_jdbc/src/main/java/data_objects/util/StringUtil.java <ide> return sb; <ide> } <ide> <add> /** <add> * Private constructor <add> */ <add> private StringUtil(){ <add> <add> } <add> <ide> }
Java
apache-2.0
c38665900534c04bb4a109bbae61ae87ead3a624
0
jior/glaf,jior/glaf,jior/glaf,jior/glaf,jior/glaf,jior/glaf
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.glaf.core.web.servlet; import java.io.ByteArrayOutputStream; import java.io.File; import java.io.IOException; import java.io.InputStream; import java.util.Map; import java.util.Map.Entry; import java.util.Set; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.ConcurrentMap; import java.util.zip.GZIPOutputStream; import javax.servlet.ServletConfig; import javax.servlet.ServletException; import javax.servlet.ServletOutputStream; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.apache.commons.lang.StringUtils; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import com.glaf.core.config.BaseConfiguration; import com.glaf.core.config.Configuration; import com.glaf.core.config.SystemProperties; import com.glaf.core.util.FileUtils; import com.glaf.core.util.IOUtils; import com.glaf.core.web.resource.WebResource; import com.glaf.core.xml.MimeMappingReader; public class WebResourceServlet extends HttpServlet { private static final long serialVersionUID = 1L; protected static final Log logger = LogFactory .getLog(WebResourceServlet.class); protected static Configuration conf = BaseConfiguration.create(); protected static ConcurrentMap<String, String> mimeMapping = new ConcurrentHashMap<String, String>(); protected static boolean debugMode = false; protected boolean isGZIPSupported(HttpServletRequest req) { String browserEncodings = req.getHeader("accept-encoding"); boolean supported = ((browserEncodings != null) && (browserEncodings .indexOf("gzip") != -1)); String userAgent = req.getHeader("user-agent"); if ((userAgent != null) && userAgent.startsWith("httpunit")) { logger.debug("httpunit detected, disabling filter..."); return false; } else { return supported; } } @Override protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { String contextPath = request.getContextPath(); String requestURI = request.getRequestURI(); String resPath = requestURI.substring(contextPath.length(), requestURI.length()); // logger.debug("contextPath:" + contextPath); // logger.debug("requestURI:" + requestURI); // logger.debug("resPath:" + resPath); int slash = request.getRequestURI().lastIndexOf("/"); String file = request.getRequestURI().substring(slash + 1); if (StringUtils.endsWithIgnoreCase(file, ".class")) { return; } if (StringUtils.endsWithIgnoreCase(file, ".jsp")) { return; } if (StringUtils.endsWithIgnoreCase(file, ".conf")) { return; } if (StringUtils.endsWithIgnoreCase(file, "-config.properties")) { return; } if (StringUtils.endsWithIgnoreCase(file, "-spring-context.xml")) { return; } if (StringUtils.endsWithIgnoreCase(file, "Mapper.xml")) { return; } int dot = file.lastIndexOf("."); String ext = file.substring(dot + 1); String contentType = ""; boolean requiredZip = false; if (StringUtils.equalsIgnoreCase(ext, "jpg") || StringUtils.equalsIgnoreCase(ext, "jpeg") || StringUtils.equalsIgnoreCase(ext, "gif") || StringUtils.equalsIgnoreCase(ext, "png") || StringUtils.equalsIgnoreCase(ext, "bmp")) { contentType = "image/" + ext; } else if (StringUtils.equalsIgnoreCase(ext, "svg")) { contentType = "image/svg+xml"; requiredZip = true; } else if (StringUtils.equalsIgnoreCase(ext, "css")) { contentType = "text/css"; requiredZip = true; } else if (StringUtils.equalsIgnoreCase(ext, "txt")) { contentType = "text/plain"; requiredZip = true; } else if (StringUtils.equalsIgnoreCase(ext, "htm") || StringUtils.equalsIgnoreCase(ext, "html")) { contentType = "text/html"; requiredZip = true; } else if (StringUtils.equalsIgnoreCase(ext, "js")) { contentType = "application/javascript"; requiredZip = true; } else if (StringUtils.equalsIgnoreCase(ext, "ttf")) { contentType = "application/x-font-ttf"; requiredZip = true; } else if (StringUtils.equalsIgnoreCase(ext, "eot")) { contentType = "application/vnd.ms-fontobject"; } else if (StringUtils.equalsIgnoreCase(ext, "woff")) { contentType = "application/x-font-woff"; } else if (StringUtils.equalsIgnoreCase(ext, "swf")) { contentType = "application/x-shockwave-flash"; } else { contentType = mimeMapping.get(ext.trim().toLowerCase()); } if (requiredZip && isGZIPSupported(request) && conf.getBoolean("gzipEnabled", true)) { requiredZip = true; } else { requiredZip = false; } InputStream inputStream = null; ServletOutputStream output = null; boolean zipFlag = false; byte[] raw = null; try { output = response.getOutputStream(); if (!debugMode) { raw = WebResource.getData(resPath); if (requiredZip) { raw = WebResource.getData(resPath + ".gz"); if (raw != null) { zipFlag = true; } } } if (raw == null) { zipFlag = false; String filename = SystemProperties.getAppPath() + resPath; File filex = new File(filename); if (filex.exists() && filex.isFile()) { inputStream = FileUtils.getInputStream(filename); } if (inputStream == null) { inputStream = WebResourceServlet.class .getResourceAsStream(resPath); } logger.debug("load resource:" + resPath); raw = FileUtils.getBytes(inputStream); WebResource.setBytes(resPath, raw); GZIPOutputStream gzipStream = null; ByteArrayOutputStream compressedContent = null; try { // prepare a gzip stream compressedContent = new ByteArrayOutputStream(); gzipStream = new GZIPOutputStream(compressedContent); gzipStream.write(raw); gzipStream.finish(); // get the compressed content byte[] compressedBytes = compressedContent.toByteArray(); WebResource.setBytes(resPath + ".gz", compressedBytes); logger.debug(resPath + " raw size:[" + raw.length + "] gzip compressed size:[" + compressedBytes.length + "]"); if (requiredZip) { raw = compressedBytes; zipFlag = true; } } catch (Exception ex) { zipFlag = false; } finally { IOUtils.closeStream(compressedContent); IOUtils.closeStream(gzipStream); } } if (zipFlag) { response.addHeader("Content-Encoding", "gzip"); } response.setStatus(HttpServletResponse.SC_OK); response.setContentType(contentType); response.setContentLength(raw.length); output.write(raw); output.flush(); IOUtils.closeStream(output); } catch (IOException ex) { // ex.printStackTrace(); } finally { raw = null; IOUtils.closeStream(inputStream); IOUtils.closeStream(output); } response.flushBuffer(); } @Override protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { doGet(request, response); } @Override public void init(ServletConfig config) { logger.info("--------------WebResourceServlet init----------------"); try { if (System.getProperty("debugMode") != null) { debugMode = true; logger.info("---------------WebResource开启调试模式---------------"); } MimeMappingReader reader = new MimeMappingReader(); Map<String, String> mapping = reader.read(); Set<Entry<String, String>> entrySet = mapping.entrySet(); for (Entry<String, String> entry : entrySet) { String key = entry.getKey(); String value = entry.getValue(); mimeMapping.put(key, value); } } catch (Exception ex) { ex.printStackTrace(); } } }
workspace/glaf-core/src/main/java/com/glaf/core/web/servlet/WebResourceServlet.java
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.glaf.core.web.servlet; import java.io.ByteArrayOutputStream; import java.io.File; import java.io.IOException; import java.io.InputStream; import java.util.Map; import java.util.Map.Entry; import java.util.Set; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.ConcurrentMap; import java.util.zip.GZIPOutputStream; import javax.servlet.ServletConfig; import javax.servlet.ServletException; import javax.servlet.ServletOutputStream; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.apache.commons.lang.StringUtils; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import com.glaf.core.config.BaseConfiguration; import com.glaf.core.config.Configuration; import com.glaf.core.config.SystemProperties; import com.glaf.core.util.FileUtils; import com.glaf.core.util.IOUtils; import com.glaf.core.web.resource.WebResource; import com.glaf.core.xml.MimeMappingReader; public class WebResourceServlet extends HttpServlet { private static final long serialVersionUID = 1L; protected static final Log logger = LogFactory .getLog(WebResourceServlet.class); protected static Configuration conf = BaseConfiguration.create(); protected static ConcurrentMap<String, String> mimeMapping = new ConcurrentHashMap<String, String>(); protected boolean isGZIPSupported(HttpServletRequest req) { String browserEncodings = req.getHeader("accept-encoding"); boolean supported = ((browserEncodings != null) && (browserEncodings .indexOf("gzip") != -1)); String userAgent = req.getHeader("user-agent"); if ((userAgent != null) && userAgent.startsWith("httpunit")) { logger.debug("httpunit detected, disabling filter..."); return false; } else { return supported; } } @Override protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { String contextPath = request.getContextPath(); String requestURI = request.getRequestURI(); String resPath = requestURI.substring(contextPath.length(), requestURI.length()); // logger.debug("contextPath:" + contextPath); // logger.debug("requestURI:" + requestURI); // logger.debug("resPath:" + resPath); int slash = request.getRequestURI().lastIndexOf("/"); String file = request.getRequestURI().substring(slash + 1); if (StringUtils.endsWithIgnoreCase(file, ".class")) { return; } if (StringUtils.endsWithIgnoreCase(file, ".jsp")) { return; } if (StringUtils.endsWithIgnoreCase(file, ".conf")) { return; } if (StringUtils.endsWithIgnoreCase(file, "-config.properties")) { return; } if (StringUtils.endsWithIgnoreCase(file, "-spring-context.xml")) { return; } if (StringUtils.endsWithIgnoreCase(file, "Mapper.xml")) { return; } int dot = file.lastIndexOf("."); String ext = file.substring(dot + 1); String contentType = ""; boolean requiredZip = false; if (StringUtils.equalsIgnoreCase(ext, "jpg") || StringUtils.equalsIgnoreCase(ext, "jpeg") || StringUtils.equalsIgnoreCase(ext, "gif") || StringUtils.equalsIgnoreCase(ext, "png") || StringUtils.equalsIgnoreCase(ext, "bmp")) { contentType = "image/" + ext; } else if (StringUtils.equalsIgnoreCase(ext, "svg")) { contentType = "image/svg+xml"; requiredZip = true; } else if (StringUtils.equalsIgnoreCase(ext, "css")) { contentType = "text/css"; requiredZip = true; } else if (StringUtils.equalsIgnoreCase(ext, "txt")) { contentType = "text/plain"; requiredZip = true; } else if (StringUtils.equalsIgnoreCase(ext, "htm") || StringUtils.equalsIgnoreCase(ext, "html")) { contentType = "text/html"; requiredZip = true; } else if (StringUtils.equalsIgnoreCase(ext, "js")) { contentType = "application/javascript"; requiredZip = true; } else if (StringUtils.equalsIgnoreCase(ext, "ttf")) { contentType = "application/x-font-ttf"; requiredZip = true; } else if (StringUtils.equalsIgnoreCase(ext, "eot")) { contentType = "application/vnd.ms-fontobject"; } else if (StringUtils.equalsIgnoreCase(ext, "woff")) { contentType = "application/x-font-woff"; } else if (StringUtils.equalsIgnoreCase(ext, "swf")) { contentType = "application/x-shockwave-flash"; } else { contentType = mimeMapping.get(ext.trim().toLowerCase()); } if (requiredZip && isGZIPSupported(request) && conf.getBoolean("gzipEnabled", true)) { requiredZip = true; } else { requiredZip = false; } InputStream inputStream = null; ServletOutputStream output = null; boolean zipFlag = false; byte[] raw = null; try { output = response.getOutputStream(); raw = WebResource.getData(resPath); if (requiredZip) { raw = WebResource.getData(resPath + ".gz"); if (raw != null) { zipFlag = true; } } if (raw == null) { zipFlag = false; String filename = SystemProperties.getAppPath() + resPath; File filex = new File(filename); if (filex.exists() && filex.isFile()) { inputStream = FileUtils.getInputStream(filename); } if (inputStream == null) { inputStream = WebResourceServlet.class .getResourceAsStream(resPath); } logger.debug("load resource:" + resPath); raw = FileUtils.getBytes(inputStream); WebResource.setBytes(resPath, raw); GZIPOutputStream gzipStream = null; ByteArrayOutputStream compressedContent = null; try { // prepare a gzip stream compressedContent = new ByteArrayOutputStream(); gzipStream = new GZIPOutputStream(compressedContent); gzipStream.write(raw); gzipStream.finish(); // get the compressed content byte[] compressedBytes = compressedContent.toByteArray(); WebResource.setBytes(resPath + ".gz", compressedBytes); logger.debug(resPath + " raw size:[" + raw.length + "] gzip compressed size:[" + compressedBytes.length + "]"); if (requiredZip) { raw = compressedBytes; zipFlag = true; } } catch (Exception ex) { zipFlag = false; } finally { IOUtils.closeStream(compressedContent); IOUtils.closeStream(gzipStream); } } if (zipFlag) { response.addHeader("Content-Encoding", "gzip"); } response.setStatus(HttpServletResponse.SC_OK); response.setContentType(contentType); response.setContentLength(raw.length); output.write(raw); output.flush(); IOUtils.closeStream(output); } catch (IOException ex) { // ex.printStackTrace(); } finally { raw = null; IOUtils.closeStream(inputStream); IOUtils.closeStream(output); } response.flushBuffer(); } @Override protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { doGet(request, response); } @Override public void init(ServletConfig config) { logger.info("--------------WebResourceServlet init----------------"); try { MimeMappingReader reader = new MimeMappingReader(); Map<String, String> mapping = reader.read(); Set<Entry<String, String>> entrySet = mapping.entrySet(); for (Entry<String, String> entry : entrySet) { String key = entry.getKey(); String value = entry.getValue(); mimeMapping.put(key, value); } } catch (Exception ex) { ex.printStackTrace(); } } }
update WebResourceServlet
workspace/glaf-core/src/main/java/com/glaf/core/web/servlet/WebResourceServlet.java
update WebResourceServlet
<ide><path>orkspace/glaf-core/src/main/java/com/glaf/core/web/servlet/WebResourceServlet.java <ide> <ide> protected static ConcurrentMap<String, String> mimeMapping = new ConcurrentHashMap<String, String>(); <ide> <add> protected static boolean debugMode = false; <add> <ide> protected boolean isGZIPSupported(HttpServletRequest req) { <ide> String browserEncodings = req.getHeader("accept-encoding"); <ide> boolean supported = ((browserEncodings != null) && (browserEncodings <ide> byte[] raw = null; <ide> try { <ide> output = response.getOutputStream(); <del> raw = WebResource.getData(resPath); <del> if (requiredZip) { <del> raw = WebResource.getData(resPath + ".gz"); <del> if (raw != null) { <del> zipFlag = true; <add> if (!debugMode) { <add> raw = WebResource.getData(resPath); <add> if (requiredZip) { <add> raw = WebResource.getData(resPath + ".gz"); <add> if (raw != null) { <add> zipFlag = true; <add> } <ide> } <ide> } <ide> if (raw == null) { <ide> public void init(ServletConfig config) { <ide> logger.info("--------------WebResourceServlet init----------------"); <ide> try { <add> if (System.getProperty("debugMode") != null) { <add> debugMode = true; <add> logger.info("---------------WebResource开启调试模式---------------"); <add> } <ide> MimeMappingReader reader = new MimeMappingReader(); <ide> Map<String, String> mapping = reader.read(); <ide> Set<Entry<String, String>> entrySet = mapping.entrySet();
Java
epl-1.0
61650b01dfdd1eaafee7bbc2789216f37ff01b05
0
ivannov/core,D9110/core,D9110/core,D9110/core,jerr/jbossforge-core,jerr/jbossforge-core,oscerd/core,pplatek/core,forge/core,oscerd/core,pplatek/core,agoncal/core,D9110/core,ivannov/core,pplatek/core,stalep/forge-core,ivannov/core,jerr/jbossforge-core,forge/core,jerr/jbossforge-core,oscerd/core,oscerd/core,ivannov/core,forge/core,agoncal/core,jerr/jbossforge-core,ivannov/core,forge/core,agoncal/core,D9110/core,jerr/jbossforge-core,agoncal/core,forge/core,agoncal/core,agoncal/core,D9110/core,oscerd/core,pplatek/core,oscerd/core,ivannov/core,forge/core,D9110/core,ivannov/core,jerr/jbossforge-core,oscerd/core,stalep/forge-core,agoncal/core,pplatek/core,agoncal/core,pplatek/core,ivannov/core,forge/core,oscerd/core,D9110/core,D9110/core,jerr/jbossforge-core,jerr/jbossforge-core,pplatek/core,pplatek/core,ivannov/core,pplatek/core,oscerd/core,agoncal/core,forge/core,forge/core,pplatek/core,ivannov/core,jerr/jbossforge-core,agoncal/core,D9110/core,forge/core,oscerd/core
/* * JBoss, by Red Hat. * Copyright 2010, Red Hat, Inc., and individual contributors * by the @authors tag. See the copyright.txt in the distribution for a * full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.jboss.seam.forge.shell.plugins.builtin; import org.jboss.seam.forge.project.Resource; import org.jboss.seam.forge.project.resources.FileResource; import org.jboss.seam.forge.project.resources.builtin.DirectoryResource; import org.jboss.seam.forge.project.services.ResourceFactory; import org.jboss.seam.forge.shell.Shell; import org.jboss.seam.forge.shell.plugins.*; import javax.inject.Inject; import javax.inject.Named; /** * @author Mike Brock */ @Named("rm") @Topic("File & Resources") @ResourceScope(DirectoryResource.class) @Help("Removes a file or directory") public class RmPlugin implements Plugin { private final Shell shell; private final ResourceFactory factory; @Inject public RmPlugin(Shell shell, ResourceFactory factory) { this.shell = shell; this.factory = factory; } @DefaultCommand public void rm(@Option(name = "recursive", shortName = "r", help = "recursively delete files and directories", flagOnly = true) boolean recursive, @Option(name = "force", shortName = "f", help = "do not prompt to confirm operations", flagOnly = true) boolean force, @Option(description = "path", required = true) Resource<?>[] paths) { for (Resource<?> resource : paths) { if (resource instanceof FileResource) { FileResource fResource = (FileResource) resource; if (force || shell.promptBoolean("delete: " + resource.toString() + ": are you sure?")) { if (!fResource.delete(recursive)) { throw new RuntimeException("error deleting files."); } } } } } }
shell/src/main/java/org/jboss/seam/forge/shell/plugins/builtin/RmPlugin.java
/* * JBoss, by Red Hat. * Copyright 2010, Red Hat, Inc., and individual contributors * by the @authors tag. See the copyright.txt in the distribution for a * full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.jboss.seam.forge.shell.plugins.builtin; import org.jboss.seam.forge.project.Resource; import org.jboss.seam.forge.project.resources.FileResource; import org.jboss.seam.forge.project.resources.builtin.DirectoryResource; import org.jboss.seam.forge.project.services.ResourceFactory; import org.jboss.seam.forge.shell.Shell; import org.jboss.seam.forge.shell.plugins.*; import javax.inject.Inject; import javax.inject.Named; /** * @author Mike Brock */ @Named("rm") @Topic("File & Resources") @ResourceScope(DirectoryResource.class) @Help("Removes a file or directory") public class RmPlugin implements Plugin { private final Shell shell; private final ResourceFactory factory; @Inject public RmPlugin(Shell shell, ResourceFactory factory) { this.shell = shell; this.factory = factory; } @DefaultCommand public void rm(@Option(name = "recursive", shortName = "r", help = "recursively delete files and directories", flagOnly = true) boolean recursive, @Option(name = "force", shortName = "f", help = "do not prompt to confirm operations") boolean force, @Option(description = "path", required = true) Resource<?>[] paths) { for (Resource<?> resource : paths) { if (resource instanceof FileResource) { FileResource fResource = (FileResource) resource; if (force || shell.promptBoolean("delete: " + resource.toString() + ": are you sure?")) { if (!fResource.delete(recursive)) { throw new RuntimeException("error deleting files."); } } } } } }
fix to rm command
shell/src/main/java/org/jboss/seam/forge/shell/plugins/builtin/RmPlugin.java
fix to rm command
<ide><path>hell/src/main/java/org/jboss/seam/forge/shell/plugins/builtin/RmPlugin.java <ide> <ide> @DefaultCommand <ide> public void rm(@Option(name = "recursive", shortName = "r", help = "recursively delete files and directories", flagOnly = true) boolean recursive, <del> @Option(name = "force", shortName = "f", help = "do not prompt to confirm operations") boolean force, <add> @Option(name = "force", shortName = "f", help = "do not prompt to confirm operations", flagOnly = true) boolean force, <ide> @Option(description = "path", required = true) Resource<?>[] paths) <ide> { <del> <del> <ide> for (Resource<?> resource : paths) <ide> { <ide> if (resource instanceof FileResource)
Java
apache-2.0
error: pathspec 'server/src/main/java/net/oneandone/stool/server/logging/DetailsLogEntry.java' did not match any file(s) known to git
80f50bbb27b04aab4ddaa436d5d06feedaf024fa
1
mlhartme/stool,mlhartme/stool,mlhartme/stool,mlhartme/stool,mlhartme/stool
/* * Copyright 1&1 Internet AG, https://github.com/1and1/ * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package net.oneandone.stool.server.logging; import ch.qos.logback.classic.spi.ILoggingEvent; import java.time.Instant; import java.time.LocalDateTime; import java.time.ZoneId; import java.time.format.DateTimeFormatter; import java.util.Map; public class DetailsLogEntry { public static DetailsLogEntry forEvent(ILoggingEvent event) { Instant instant; LocalDateTime date; Map<String, String> mdc; instant = Instant.ofEpochMilli(event.getTimeStamp()); date = instant.atZone(ZoneId.systemDefault()).toLocalDateTime(); mdc = event.getMDCPropertyMap(); return new DetailsLogEntry(date, mdc.get("client-invocation"), mdc.get("client-command"), mdc.get("user"), mdc.get("stage"), event.getMessage()); } public static final DateTimeFormatter DATE_FMT = DateTimeFormatter.ofPattern("yy-MM-dd HH:mm:ss,SSS"); /** Count-part of the Logging.log method. */ public static DetailsLogEntry parse(String line) { int len; int date; int invocation; int command; int user; int stage; len = line.length(); // CAUTION: do not use split, because messages may contain separators date = line.indexOf('|'); invocation = line.indexOf('|', date + 1); // invocation id command = line.indexOf('|', invocation + 1); user = line.indexOf('|', command + 1); stage = line.indexOf('|', user + 1); if (line.charAt(len - 1) != '\n') { throw new IllegalArgumentException(line); } return new DetailsLogEntry( LocalDateTime.parse(line.substring(0, date), DetailsLogEntry.DATE_FMT), line.substring(date + 1, invocation), line.substring(invocation + 1, command), line.substring(command + 1, user), line.substring(user + 1, stage), unescape(line.substring(stage + 1, len -1))); } private static String unescape(String message) { StringBuilder builder; char c; int max; if (message.indexOf('\\') == -1) { return message; } else { max = message.length(); builder = new StringBuilder(max); for (int i = 0; i < max; i++) { c = message.charAt(i); if (c != '\\') { builder.append(c); } else { i++; c = message.charAt(i); switch (c) { case 'n': builder.append('\n'); break; case 'r': builder.append('\r'); break; default: builder.append(c); break; } } } return builder.toString(); } } //-- public final LocalDateTime dateTime; public final String clientInvocation; public final String clientCommand; public final String user; public final String stageName; public final String message; public DetailsLogEntry(LocalDateTime dateTime, String clientInvocation, String clientCommand, String user, String stageName, String message) { this.dateTime = dateTime; this.clientInvocation = clientInvocation; this.clientCommand = clientCommand; this.user = user; this.stageName = stageName; this.message = message; } public String toString() { StringBuilder result; result = new StringBuilder(); char c; result.append(DetailsLogEntry.DATE_FMT.format(LocalDateTime.now())).append('|'); result.append(clientInvocation).append('|'); result.append(clientCommand).append('|'); result.append(user).append('|'); result.append(stageName).append('|'); for (int i = 0, max = message.length(); i < max; i++) { c = message.charAt(i); switch (c) { case '\r': result.append("\\r"); break; case '\n': result.append("\\n"); break; case '\\': result.append("\\\\"); break; default: result.append(c); break; } } result.append('\n'); return result.toString(); } }
server/src/main/java/net/oneandone/stool/server/logging/DetailsLogEntry.java
DetailsLogEntry
server/src/main/java/net/oneandone/stool/server/logging/DetailsLogEntry.java
DetailsLogEntry
<ide><path>erver/src/main/java/net/oneandone/stool/server/logging/DetailsLogEntry.java <add>/* <add> * Copyright 1&1 Internet AG, https://github.com/1and1/ <add> * <add> * Licensed under the Apache License, Version 2.0 (the "License"); <add> * you may not use this file except in compliance with the License. <add> * You may obtain a copy of the License at <add> * <add> * http://www.apache.org/licenses/LICENSE-2.0 <add> * <add> * Unless required by applicable law or agreed to in writing, software <add> * distributed under the License is distributed on an "AS IS" BASIS, <add> * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. <add> * See the License for the specific language governing permissions and <add> * limitations under the License. <add> */ <add>package net.oneandone.stool.server.logging; <add> <add>import ch.qos.logback.classic.spi.ILoggingEvent; <add> <add>import java.time.Instant; <add>import java.time.LocalDateTime; <add>import java.time.ZoneId; <add>import java.time.format.DateTimeFormatter; <add>import java.util.Map; <add> <add>public class DetailsLogEntry { <add> public static DetailsLogEntry forEvent(ILoggingEvent event) { <add> Instant instant; <add> LocalDateTime date; <add> Map<String, String> mdc; <add> <add> instant = Instant.ofEpochMilli(event.getTimeStamp()); <add> date = instant.atZone(ZoneId.systemDefault()).toLocalDateTime(); <add> mdc = event.getMDCPropertyMap(); <add> return new DetailsLogEntry(date, mdc.get("client-invocation"), mdc.get("client-command"), mdc.get("user"), mdc.get("stage"), event.getMessage()); <add> } <add> <add> public static final DateTimeFormatter DATE_FMT = DateTimeFormatter.ofPattern("yy-MM-dd HH:mm:ss,SSS"); <add> <add> /** Count-part of the Logging.log method. */ <add> public static DetailsLogEntry parse(String line) { <add> int len; <add> <add> int date; <add> int invocation; <add> int command; <add> int user; <add> int stage; <add> <add> len = line.length(); <add> <add> // CAUTION: do not use split, because messages may contain separators <add> date = line.indexOf('|'); <add> invocation = line.indexOf('|', date + 1); // invocation id <add> command = line.indexOf('|', invocation + 1); <add> user = line.indexOf('|', command + 1); <add> stage = line.indexOf('|', user + 1); <add> if (line.charAt(len - 1) != '\n') { <add> throw new IllegalArgumentException(line); <add> } <add> <add> return new DetailsLogEntry( <add> LocalDateTime.parse(line.substring(0, date), DetailsLogEntry.DATE_FMT), <add> line.substring(date + 1, invocation), <add> line.substring(invocation + 1, command), <add> line.substring(command + 1, user), <add> line.substring(user + 1, stage), <add> unescape(line.substring(stage + 1, len -1))); <add> } <add> <add> private static String unescape(String message) { <add> StringBuilder builder; <add> char c; <add> int max; <add> <add> if (message.indexOf('\\') == -1) { <add> return message; <add> } else { <add> max = message.length(); <add> builder = new StringBuilder(max); <add> for (int i = 0; i < max; i++) { <add> c = message.charAt(i); <add> if (c != '\\') { <add> builder.append(c); <add> } else { <add> i++; <add> c = message.charAt(i); <add> switch (c) { <add> case 'n': <add> builder.append('\n'); <add> break; <add> case 'r': <add> builder.append('\r'); <add> break; <add> default: <add> builder.append(c); <add> break; <add> } <add> } <add> } <add> return builder.toString(); <add> } <add> } <add> <add> //-- <add> <add> public final LocalDateTime dateTime; <add> public final String clientInvocation; <add> public final String clientCommand; <add> public final String user; <add> public final String stageName; <add> public final String message; <add> <add> public DetailsLogEntry(LocalDateTime dateTime, String clientInvocation, String clientCommand, String user, String stageName, String message) { <add> this.dateTime = dateTime; <add> this.clientInvocation = clientInvocation; <add> this.clientCommand = clientCommand; <add> this.user = user; <add> this.stageName = stageName; <add> this.message = message; <add> } <add> <add> public String toString() { <add> StringBuilder result; <add> <add> result = new StringBuilder(); <add> char c; <add> <add> result.append(DetailsLogEntry.DATE_FMT.format(LocalDateTime.now())).append('|'); <add> result.append(clientInvocation).append('|'); <add> result.append(clientCommand).append('|'); <add> result.append(user).append('|'); <add> result.append(stageName).append('|'); <add> for (int i = 0, max = message.length(); i < max; i++) { <add> c = message.charAt(i); <add> switch (c) { <add> case '\r': <add> result.append("\\r"); <add> break; <add> case '\n': <add> result.append("\\n"); <add> break; <add> case '\\': <add> result.append("\\\\"); <add> break; <add> default: <add> result.append(c); <add> break; <add> } <add> } <add> result.append('\n'); <add> return result.toString(); <add> } <add>}
JavaScript
mit
1ccf39094ee035cb95cdb05efbb17bb7c83334af
0
u9520107/locale-loader,u9520107/locale-loader
import fs from 'fs-promise'; import path from 'path'; import glob from 'glob'; import { parse, tokTypes } from 'babylon'; import isLocaleFile from './isLocaleFile'; // import generateLoader from './generateLoader'; import loaderRegExp from './loaderRegExp'; // import noChunkRegExp from './noChunkRegExp'; import formatLocale from './formatLocale'; async function getLoaderFiles(fileList) { const loaderFiles = new Set(); await Promise.all(fileList.map(async (file) => { if ((await fs.stat(file)).isFile()) { const content = await fs.readFile(file, 'utf8'); if (loaderRegExp.test(content)) { loaderFiles.add(file); } } })); return [...loaderFiles]; } function parseLine(tokens, startingIdx) { let idx = startingIdx; let token = tokens[idx]; const keyArray = []; do { keyArray.push(token.value || token.type.label); idx += 1; token = tokens[idx]; } while (token.type !== tokTypes.colon); return [{ key: keyArray.join(''), value: tokens[idx + 1].value, }, idx + 3]; } async function extractData(localeFile) { const content = await fs.readFile(localeFile, 'utf8'); const parsed = parse(content, { sourceType: 'module' }); let idx = 0; const len = parsed.tokens.length; let capturing = false; const data = {}; while (idx < len) { const token = parsed.tokens[idx]; if ( token.type === tokTypes._export && parsed.tokens[idx + 1].type === tokTypes._default && parsed.tokens[idx + 2].type === tokTypes.braceL ) { capturing = true; idx += 3; } else if (capturing) { if (token.type === tokTypes.braceR) { break; } else { const [item, newIdx] = parseLine(parsed.tokens, idx); data[item.key] = item.value; idx = newIdx; } } else { idx += 1; } } return { content, data, }; } async function getLocaleData({ folderPath, sourceLocale, supportedLocales }) { const localeFiles = (await fs.readdir(folderPath)).filter(isLocaleFile); const localeData = { path: folderPath, data: {}, }; await Promise.all(localeFiles.map(async (file) => { const locale = formatLocale(file.replace(/\.(js|json)$/i, '')); if (locale === sourceLocale || supportedLocales.indexOf(locale) > -1) { localeData.data[locale] = { file, locale, data: await extractData(path.resolve(folderPath, file)), }; } })); return localeData; } async function getRawData({ src, sourceLocale, supportedLocales, }) { const fileList = await new Promise((resolve, reject) => { const g = new glob.Glob(src, (err, m) => { if (err) { return reject(err); } return resolve(m); }); }); const loaderFiles = await getLoaderFiles(fileList); const rawData = {}; await Promise.all(loaderFiles.map(async (f) => { const folderPath = path.dirname(f); rawData[folderPath] = await getLocaleData({ folderPath, sourceLocale, supportedLocales }); })); console.log(JSON.stringify(rawData, null, 2)); } export default async function exportLocale({ src = './src/**/*', dest = './build', cwd = process.cwd(), sourceLocale = 'en-US', supportedLocales = ['en-GB', 'en-CA', 'fr-FR', 'fr-CA', 'de-DE'], } = {}) { const rawData = getRawData({ src, sourceLocale, supportedLocales, }); console.log(JSON.stringify(rawData, null, 2)); // const folderPath = path.dirname(file); // const files = (await fs.readdir(folderPath)).filter(isLocaleFile); // localeFiles.add(...files.map(f => path.resolve(folderPath, f))); // const localeData = {}}; // await Promise.all([...localeFiles].map(async (file) => { // const content = await fs.readFile(file, 'utf8'); // const parsed = parse(content, { sourceType: 'module' }); // let idx = 0; // const len = parsed.tokens.length; // let capturing = false; // const data = {}; // while (idx < len) { // const token = parsed.tokens[idx]; // if ( // token.type === tokTypes._export && // parsed.tokens[idx + 1].type === tokTypes._default && // parsed.tokens[idx + 2].type === tokTypes.braceL // ) { // capturing = true; // idx += 3; // } else if (capturing) { // if (token.type === tokTypes.braceR) { // break; // } else { // const [item, newIdx] = parseLine(parsed.tokens, idx); // data[item.key] = item.value; // idx = newIdx; // } // } else { // idx += 1; // } // } // localeData[file] = data; // })); }
src/exportLocale.js
// import through from 'through2'; import fs from 'fs-promise'; import path from 'path'; import glob from 'glob'; const babylon = require('babylon'); // for some reason, import syntax result in undefined import isLocaleFile from './isLocaleFile'; // import generateLoader from './generateLoader'; import loaderRegExp from './loaderRegExp'; // import noChunkRegExp from './noChunkRegExp'; import formatLocale from './formatLocale'; async function getLoaderFiles(fileList) { const loaderFiles = new Set(); await Promise.all(fileList.map(async (file) => { if ((await fs.stat(file)).isFile()) { const content = await fs.readFile(file, 'utf8'); if (loaderRegExp.test(content)) { loaderFiles.add(file); } } })); return [...loaderFiles]; } function parseLine(tokens, startingIdx) { let idx = startingIdx; let token = tokens[idx]; const keyArray = []; do { keyArray.push(token.value || token.type.label); idx += 1; token = tokens[idx]; } while (token.type !== babylon.tokTypes.colon); return [{ key: keyArray.join(''), value: tokens[idx + 1].value, }, idx + 3]; } async function extractData(localeFile) { const content = await fs.readFile(localeFile, 'utf8'); const parsed = babylon.parse(content, { sourceType: 'module' }); let idx = 0; const len = parsed.tokens.length; let capturing = false; const data = {}; while (idx < len) { const token = parsed.tokens[idx]; if ( token.type === babylon.tokTypes._export && parsed.tokens[idx + 1].type === babylon.tokTypes._default && parsed.tokens[idx + 2].type === babylon.tokTypes.braceL ) { capturing = true; idx += 3; } else if (capturing) { if (token.type === babylon.tokTypes.braceR) { break; } else { const [item, newIdx] = parseLine(parsed.tokens, idx); data[item.key] = item.value; idx = newIdx; } } else { idx += 1; } } return { content, data, }; } async function getLocaleData({ folderPath, sourceLocale, supportedLocales }) { const localeFiles = (await fs.readdir(folderPath)).filter(isLocaleFile); const localeData = { path: folderPath, data: {}, }; await Promise.all(localeFiles.map(async (file) => { const locale = formatLocale(file.replace(/\.(js|json)$/i, '')); if (locale === sourceLocale || supportedLocales.indexOf(locale) > -1) { localeData.data[locale] = { file, locale, data: await extractData(path.resolve(folderPath, file)), }; } })); return localeData; } async function getRawData({ src, sourceLocale, supportedLocales, }) { const fileList = await new Promise((resolve, reject) => { const g = new glob.Glob(src, (err, m) => { if (err) { return reject(err); } return resolve(m); }); }); const loaderFiles = await getLoaderFiles(fileList); const rawData = {}; await Promise.all(loaderFiles.map(async (f) => { const folderPath = path.dirname(f); rawData[folderPath] = await getLocaleData({ folderPath, sourceLocale, supportedLocales }); })); console.log(JSON.stringify(rawData, null, 2)); } export default async function exportLocale({ src = './src/**/*', dest = './build', cwd = process.cwd(), sourceLocale = 'en-US', supportedLocales = ['en-GB', 'en-CA', 'fr-FR', 'fr-CA', 'de-DE'], } = {}) { const rawData = getRawData({ src, sourceLocale, supportedLocales, }); console.log(JSON.stringify(rawData, null, 2)); // const folderPath = path.dirname(file); // const files = (await fs.readdir(folderPath)).filter(isLocaleFile); // localeFiles.add(...files.map(f => path.resolve(folderPath, f))); // const localeData = {}}; // await Promise.all([...localeFiles].map(async (file) => { // const content = await fs.readFile(file, 'utf8'); // const parsed = babylon.parse(content, { sourceType: 'module' }); // let idx = 0; // const len = parsed.tokens.length; // let capturing = false; // const data = {}; // while (idx < len) { // const token = parsed.tokens[idx]; // if ( // token.type === babylon.tokTypes._export && // parsed.tokens[idx + 1].type === babylon.tokTypes._default && // parsed.tokens[idx + 2].type === babylon.tokTypes.braceL // ) { // capturing = true; // idx += 3; // } else if (capturing) { // if (token.type === babylon.tokTypes.braceR) { // break; // } else { // const [item, newIdx] = parseLine(parsed.tokens, idx); // data[item.key] = item.value; // idx = newIdx; // } // } else { // idx += 1; // } // } // localeData[file] = data; // })); }
progress
src/exportLocale.js
progress
<ide><path>rc/exportLocale.js <del>// import through from 'through2'; <ide> import fs from 'fs-promise'; <ide> import path from 'path'; <ide> import glob from 'glob'; <del>const babylon = require('babylon'); // for some reason, import syntax result in undefined <del> <add>import { parse, tokTypes } from 'babylon'; <ide> import isLocaleFile from './isLocaleFile'; <ide> // import generateLoader from './generateLoader'; <ide> import loaderRegExp from './loaderRegExp'; <ide> keyArray.push(token.value || token.type.label); <ide> idx += 1; <ide> token = tokens[idx]; <del> } while (token.type !== babylon.tokTypes.colon); <add> } while (token.type !== tokTypes.colon); <ide> return [{ <ide> key: keyArray.join(''), <ide> value: tokens[idx + 1].value, <ide> <ide> async function extractData(localeFile) { <ide> const content = await fs.readFile(localeFile, 'utf8'); <del> const parsed = babylon.parse(content, { sourceType: 'module' }); <add> const parsed = parse(content, { sourceType: 'module' }); <ide> let idx = 0; <ide> const len = parsed.tokens.length; <ide> let capturing = false; <ide> while (idx < len) { <ide> const token = parsed.tokens[idx]; <ide> if ( <del> token.type === babylon.tokTypes._export && <del> parsed.tokens[idx + 1].type === babylon.tokTypes._default && <del> parsed.tokens[idx + 2].type === babylon.tokTypes.braceL <add> token.type === tokTypes._export && <add> parsed.tokens[idx + 1].type === tokTypes._default && <add> parsed.tokens[idx + 2].type === tokTypes.braceL <ide> ) { <ide> capturing = true; <ide> idx += 3; <ide> } else if (capturing) { <del> if (token.type === babylon.tokTypes.braceR) { <add> if (token.type === tokTypes.braceR) { <ide> break; <ide> } else { <ide> const [item, newIdx] = parseLine(parsed.tokens, idx); <ide> // const localeData = {}}; <ide> // await Promise.all([...localeFiles].map(async (file) => { <ide> // const content = await fs.readFile(file, 'utf8'); <del> // const parsed = babylon.parse(content, { sourceType: 'module' }); <add> // const parsed = parse(content, { sourceType: 'module' }); <ide> // let idx = 0; <ide> // const len = parsed.tokens.length; <ide> // let capturing = false; <ide> // while (idx < len) { <ide> // const token = parsed.tokens[idx]; <ide> // if ( <del> // token.type === babylon.tokTypes._export && <del> // parsed.tokens[idx + 1].type === babylon.tokTypes._default && <del> // parsed.tokens[idx + 2].type === babylon.tokTypes.braceL <add> // token.type === tokTypes._export && <add> // parsed.tokens[idx + 1].type === tokTypes._default && <add> // parsed.tokens[idx + 2].type === tokTypes.braceL <ide> // ) { <ide> // capturing = true; <ide> // idx += 3; <ide> // } else if (capturing) { <del> // if (token.type === babylon.tokTypes.braceR) { <add> // if (token.type === tokTypes.braceR) { <ide> // break; <ide> // } else { <ide> // const [item, newIdx] = parseLine(parsed.tokens, idx);
JavaScript
apache-2.0
aefacd41770a3ee24355e353a8c3cd2d0b529735
0
atomjump/medimage,atomjump/medimage
/* * 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. */ //Source code Copyright (c) 2018 AtomJump Ltd. (New Zealand) var deleteThisFile = {}; //Global object for image taken, to be deleted var centralPairingUrl = "https://atomjump.com/med-genid.php"; //Redirects to an https connection. In future try setting to http://atomjump.org/med-genid.php var glbThis = {}; //Used as a global error handler var retryIfNeeded = []; //A global pushable list with the repeat attempts var checkComplete = []; //A global pushable list with the repeat checks to see if image is on PC var retryNum = 0; //See: https://stackoverflow.com/questions/14787705/phonegap-cordova-filetransfer-abort-not-working-as-expected // basic implementation of hash map of FileTransfer objects // so that given a key, an abort function can find the right FileTransfer to abort function SimpleHashMap() { this.items = {}; this.setItem = function(key, value) { this.items[key] = value; } this.getItem = function(key) { if (this.hasItem(key)) { return this.items[key]; } return undefined; } this.hasItem = function(key) { return this.items.hasOwnProperty(key); } this.removeItem = function(key) { if (this.hasItem(key)) { delete this.items[key]; } } } var fileTransferMap = new SimpleHashMap(); var app = { // Application Constructor initialize: function() { glbThis = this; this.bindEvents(); //Set display name this.displayServerName(); //Initialise the id field this.displayIdInput(); //Check if there are any residual photos that need to be sent again glbThis.loopLocalPhotos(); }, // Bind Event Listeners // // Bind any events that are required on startup. Common events are: // 'load', 'deviceready', 'offline', and 'online'. bindEvents: function() { document.addEventListener('deviceready', this.onDeviceReady, false); }, // deviceready Event Handler // // The scope of 'this' is the event. In order to call the 'receivedEvent' // function, we must explicity call 'app.receivedEvent(...);' onDeviceReady: function() { app.receivedEvent('deviceready'); }, // Update DOM on a Received Event receivedEvent: function(id) { var parentElement = document.getElementById(id); if(parentElement) { var listeningElement = parentElement.querySelector('.listening'); var receivedElement = parentElement.querySelector('.received'); listeningElement.setAttribute('style', 'display:none;'); receivedElement.setAttribute('style', 'display:block;'); console.log('Received Event: ' + id); } else { console.log('Failed Received Event: ' + id); } }, processPicture: function(imageURI) { var _this = this; glbThis = this; //Called from takePicture(), after the image file URI has been shifted into a persistent file //Reconnect once localStorage.removeItem("usingServer"); //This will force a reconnection localStorage.removeItem("defaultDir"); var thisImageURI = imageURI; var idEntered = document.getElementById("id-entered").value; //Store in case the app quits unexpectably _this.determineFilename(imageURI, idEntered, function(err, newFilename) { if(err) { //There was a problem getting the filename from the disk file glbThis.notify("Sorry, we cannot process the filename of the photo " + idEntered + ". If this happens consistently, please report the problem to medimage.co.nz"); } else { _this.recordLocalPhoto( imageURI, idEntered, newFilename); _this.findServer(function(err) { if(err) { glbThis.notify("Sorry, we cannot connect to the server. Trying again in 10 seconds."); //Search again in 10 seconds: var passedImageURI = thisImageURI; var idEnteredB = idEntered; setTimeout(function() { localStorage.removeItem("usingServer"); //This will force a reconnection localStorage.removeItem("defaultDir"); glbThis.uploadPhoto(passedImageURI, idEnteredB, newFilename); }, 10000); } else { //Now we are connected, upload the photo again glbThis.uploadPhoto(thisImageURI, idEntered, newFilename); } }); } }); }, takePicture: function() { var _this = this; glbThis = this; navigator.camera.getPicture( function( imageURI ) { //Move picture into persistent storage //Grab the file name of the photo in the temporary directory var currentName = imageURI.replace(/^.*[\\\/]/, ''); //Create a new name for the photo var d = new Date(), n = d.getTime(), newFileName = n + ".jpg"; window.resolveLocalFileSystemURI( imageURI, function(fileEntry) { var myFile = fileEntry; try { //Try moving the file to permanent storage window.resolveLocalFileSystemURL( cordova.file.dataDirectory, function(directory) { try { myFile.moveTo(directory, newFileName, function(success){ //Moved it to permanent storage successfully //success.fullPath contains the path to the photo in permanent storage if(success.nativeURL) { glbThis.processPicture(success.nativeURL); } else { glbThis.notify("Sorry we could not find the moved photo on the phone. Please let medimage.co.nz know that a moveFile() has not worked correctly."); } }, function(err){ //an error occured moving file - send anyway, even if it is in the temporary folder glbThis.processPicture(imageURI); }); } catch(err) { //A problem moving the file but send the temp file anyway glbThis.processPicture(imageURI); } }, function(err) { //an error occured moving file - send anyway, even if it is in the temporary folder glbThis.processPicture(imageURI); }); } catch(err) { //A proble occured determining if the persistent folder existed glbThis.processPicture(imageURI); } }, function(err) { //Could not resolve local file glbThis.notify("Sorry we could not find the photo on the phone."); }); }, function( message ) { //An error or cancellation glbThis.notify( message ); }, { quality: 100, destinationType: Camera.DestinationType.FILE_URI }); }, recordLocalPhoto: function(imageURI, idEntered, fileName) { //Save into our localPhotos array, in case the app quits var localPhotos = glbThis.getArrayLocalStorage("localPhotos"); if(!localPhotos) { localPhotos = []; } var newPhoto = { "imageURI" : imageURI, "idEntered" : idEntered, "fileName" : fileName, "status" : "send" }; //Status can be 'send', 'onserver', 'sent' (usually deleted from the array), or 'cancel' localPhotos.push(newPhoto); glbThis.setArrayLocalStorage("localPhotos", localPhotos); return true; }, changeLocalPhotoStatus: function(imageURI, newStatus, fullData) { //Input: //imageURI - unique image address on phone filesystem //newStatus can be 'send', 'onserver', 'sent' (usually deleted from the array), or 'cancel' //If onserver, the optional parameter 'fullGet', is the URL to call to check if the file is back on the server var localPhotos = glbThis.getArrayLocalStorage("localPhotos"); if(!localPhotos) { localPhotos = []; } for(var cnt = 0; cnt< localPhotos.length; cnt++) { if(localPhotos[cnt].imageURI === imageURI) { if(newStatus === "cancel") { //Delete the photo window.resolveLocalFileSystemURI(imageURI, function(fileEntry) { //Remove the file from the phone fileEntry.remove(); //Remove entry from the array var splicing = cnt - 1; localPhotos.splice(splicing,1); //Set back the storage of the array glbThis.setArrayLocalStorage("localPhotos", localPhotos); }, function(evt) { //Some form of error case. We likely couldn't find the file, but we still want to remove the entry from the array //in this case var errorCode = null; if(evt.code) { errorCode = evt.code; } if(evt.target && evt.target.error.code) { errorCode = evt.target.error.code; } if(errorCode === 1) { //The photo is not there. Remove anyway //Remove entry from the array var splicing = cnt - 1; localPhotos.splice(splicing,1); //Set back the storage of the array glbThis.setArrayLocalStorage("localPhotos", localPhotos); } else { glbThis.notify("Sorry, there was a problem removing the photo on the phone. Error code: " + evt.target.error.code); //Remove entry from the array var splicing = cnt - 1; localPhotos.splice(splicing,1); //Set back the storage of the array glbThis.setArrayLocalStorage("localPhotos", localPhotos); } }); } else { localPhotos[cnt].status = newStatus; if((newStatus == "onserver")&&(fullData)) { localPhotos[cnt].fullData = JSON.stringify(fullData); //Create a copy of the JSON data array in string format } //Set back the storage of the array glbThis.setArrayLocalStorage("localPhotos", localPhotos); } } } }, loopLocalPhotos: function() { //Get a photo, one at a time, in the array format: /* { "imageURI" : imageURI, "idEntered" : idEntered, "fileName" : fileName, "fullData" : fullDataObject stringified - optional "status" : "send" }; //Status can be 'send', 'onserver', 'sent' (usually deleted from the array), or 'cancel' and attempt to upload them. */ var photoDetails = null; var localPhotos = glbThis.getArrayLocalStorage("localPhotos"); if(!localPhotos) { localPhotos = []; } for(var cnt = 0; cnt< localPhotos.length; cnt++) { var newPhoto = localPhotos[cnt]; if(newPhoto) { if(newPhoto.status == 'onserver') { //OK - so it was successfully put onto the server. Recheck to see if it needs to be uploaded again if(newPhoto.fullData) { try { var fullData = JSON.parse(newPhoto); checkComplete.push(nowChecking); glbThis.check(); //This will only upload again if it finds it hasn't been transferred off the //server } catch(err) { //There was a problem parsing the data. Resends the whole photo, just in case glbThis.uploadPhoto(newPhoto.imageURI, newPhoto.idEntered, newPhoto.fileName); } } else { //No fullData was added - resend anyway glbThis.uploadPhoto(newPhoto.imageURI, newPhoto.idEntered, newPhoto.fileName); } } else { //Needs to be resent glbThis.uploadPhoto(newPhoto.imageURI, newPhoto.idEntered, newPhoto.fileName); } } } return; }, get: function(url, cb) { var request = new XMLHttpRequest(); request.open("GET", url, true); var getTimeout = setTimeout(function() { cb(url, null); // Assume it hasn't gone through - we have a 404 error checking the server }, 5000); request.onreadystatechange = function() { if (request.readyState == 4) { if (request.status == 200 || request.status == 0) { clearTimeout(getTimeout); cb(url, request.responseText); // -> request.responseText <- is a result } } } request.onerror = function() { clearTimeout(getTimeout); cb(url, null); } request.send(); }, scanlan: function(port, cb) { var _this = this; if(this.lan) { var lan = this.lan; for(var cnt=0; cnt< 255; cnt++){ var machine = cnt.toString(); var url = 'http://' + lan + machine + ':' + port; this.get(url, function(goodurl, resp) { if(resp) { //Save the first TODO: if more than one, open another screen here localStorage.setItem("currentWifiServer", goodurl); clearTimeout(scanning); cb(goodurl, null); } }); } //timeout after 5 secs var scanning = setTimeout(function() { _this.notify('Timeout finding your Wifi server.'); }, 4000); } else { //No lan detected cb(null,'Local Wifi server not detected.'); } }, notify: function(msg) { //Set the user message document.getElementById("notify").innerHTML = msg; }, cancelNotify: function(msg) { //Set the user message document.getElementById("cancel-trans").innerHTML = msg; }, cancelUpload: function(cancelURI) { var ft = fileTransferMap.getItem(cancelURI); if (ft) { ft.abort(glbThis.win, glbThis.fail); //remove the photo glbThis.changeLocalPhotoStatus(cancelURI, "cancel"); } }, determineFilename: function(imageURIin, idEntered, cb) { //Determines the filename to use based on the imageURI of the photo, //and the id entered into the text field. //Calls back with: cb(err, newFilename) // where err is null for no error, or text of the error, // and the newFilename as a text string which includes the .jpg at the end. //It will use the current date / time from the phone, thought this format varies slightly //phone to phone. //Have connected OK to a server var idEnteredB = idEntered; window.resolveLocalFileSystemURI(imageURIin, function(fileEntry) { deleteThisFile = fileEntry; //Store globally var imageURI = fileEntry.toURL(); var tempName = idEnteredB; if((tempName == '')||(tempName == null)) { tempName = 'image'; } var initialHash = localStorage.getItem("initialHash"); if((initialHash)&&(initialHash != null)) { if(initialHash == 'true') { //Prepend the initial hash tempName = "#" + tempName; } } else { //Not set, so prepend the initial hash by default tempName = "#" + tempName; } var defaultDir = localStorage.getItem("defaultDir"); if((defaultDir)&&(defaultDir != null)) { //A hash code signifies a directory to write to tempName = "#" + defaultDir + " " + tempName; } var myoutFile = tempName.replace(/ /g,'-'); var idEnteredC = idEnteredB; //Get a 2nd tier of variable navigator.globalization.dateToString( new Date(), function (date) { var mydt = date.value.replace(/:/g,'-'); mydt = mydt.replace(/ /g,'-'); mydt = mydt.replace(/\//g,'-'); var aDate = new Date(); var seconds = aDate.getSeconds(); mydt = mydt + "-" + seconds; mydt = mydt.replace(/,/g,''); //remove any commas from iphone mydt = mydt.replace(/\./g,'-'); //remove any fullstops var myNewFileName = myoutFile + '-' + mydt + '.jpg'; cb(null, myNewFileName); }, function () { navigator.notification.alert('Sorry, there was an error getting the current date\n'); cb("Sorry, there was an error getting the current date"); }, { formatLength:'medium', selector:'date and time'} ); //End of function in globalization date to string }, function(evt) { //An error accessing the file //and potentially delete phone version glbThis.changeLocalPhotoStatus(myImageURIin, 'cancel'); cb("Sorry, we could not access the photo file"); }); //End of resolveLocalFileSystemURI }, uploadPhoto: function(imageURIin, idEntered, newFilename) { var _this = this; var usingServer = localStorage.getItem("usingServer"); var idEnteredB = idEntered; if((!usingServer)||(usingServer == null)) { //No remove server already connected to, find the server now. And then call upload again _this.findServer(function(err) { if(err) { window.plugins.insomnia.allowSleepAgain(); //Allow sleeping again glbThis.notify("Sorry, we cannot connect to the server. Trying again in 10 seconds."); //Search again in 10 seconds: setTimeout(function() { glbThis.uploadPhoto(imageURIin, idEnteredB, newFilename) }, 10000); } else { //Now we are connected, upload the photo again glbThis.uploadPhoto(imageURIin, idEnteredB, newFilename); } }); return; } else { //Have connected OK to a server var myImageURIin = imageURIin; var options = new FileUploadOptions(); options.fileKey="file1"; options.mimeType="image/jpeg"; var params = new Object(); params.title = idEntered; if((params.title == '')||(params.title == null)) { if((idEnteredB == '')||(idEnteredB == null)) { params.title = 'image'; } else { params.title = idEnteredB; } } options.fileName = newFilename; options.params = params; options.chunkedMode = false; //chunkedMode = false does work, but still having some issues. =true may only work on newer systems? options.headers = { Connection: "close" } options.idEntered = idEnteredB; var ft = new FileTransfer(); _this.notify("Uploading " + params.title); _this.cancelNotify("<ons-icon style=\"vertical-align: middle; color:#f7afbb;\" size=\"30px\" icon=\"fa-close\" href=\"#javascript\" onclick=\"app.cancelUpload('" + imageURI + "');\"></ons-icon><br/>Cancel"); ft.onprogress = _this.progress; var serverReq = usingServer + '/api/photo'; var repeatIfNeeded = { "imageURI" : imageURI, "serverReq" : serverReq, "options" :options, "failureCount": 0, "nextAttemptSec": 15 }; retryIfNeeded.push(repeatIfNeeded); fileTransferMap.setItem(imageURI, ft); //Make sure we can abort this photo later //Keep the screen awake as we upload window.plugins.insomnia.keepAwake(); ft.upload(imageURI, serverReq, _this.win, _this.fail, options); } //End of connected to a server OK }, progress: function(progressEvent) { var statusDom = document.querySelector('#status'); if (progressEvent.lengthComputable) { var perc = Math.floor(progressEvent.loaded / progressEvent.total * 100); statusDom.innerHTML = perc + "% uploaded..."; } else { if(statusDom.innerHTML == "") { statusDom.innerHTML = "Uploading"; } else { statusDom.innerHTML += "."; } } }, retry: function(existingText) { window.plugins.insomnia.allowSleepAgain(); //Allow sleeping again var repeatIfNeeded = retryIfNeeded.pop(); if(repeatIfNeeded) { //Resend within a minute here var t = new Date(); t.setSeconds(t.getSeconds() + repeatIfNeeded.nextAttemptSec); var timein = (repeatIfNeeded.nextAttemptSec*1000); //In microseconds repeatIfNeeded.nextAttemptSec *= 3; //Increase the delay between attempts each time to save battery if(repeatIfNeeded.nextAttemptSec > 21600) repeatIfNeeded.nextAttemptSec = 21600; //If longer than 6 hours gap, make 6 hours (that is 60x60x6) var hrMin = t.getHours() + ":" + t.getMinutes(); glbThis.notify(existingText + " Retrying " + repeatIfNeeded.options.params.title + " at " + hrMin); repeatIfNeeded.failureCount += 1; //Increase this if(repeatIfNeeded.failureCount > 2) { //Have tried too many attempts - try to reconnect completely (i.e. go //from wifi to network and vica versa localStorage.removeItem("usingServer"); //This will force a reconnection localStorage.removeItem("defaultDir"); localStorage.removeItem("serverRemote"); glbThis.uploadPhoto(repeatIfNeeded.imageURI, repeatIfNeeded.options.idEntered, repeatIfNeeded.options.idEntered, repeatIfNeeded.options.fileName); //Clear any existing timeouts if(repeatIfNeeded.retryTimeout) { clearTimeout(repeatIfNeeded.retryTimeout); } //Clear the current transfer too repeatIfNeeded.ft.abort(); return; } else { //OK in the first few attempts - keep the current connection and try again //Wait 10 seconds+ here before trying the next upload repeatIfNeeded.retryTimeout = setTimeout(function() { repeatIfNeeded.ft = new FileTransfer(); repeatIfNeeded.ft.onprogress = glbThis.progress; glbThis.notify("Trying to upload " + repeatIfNeeded.options.params.title); glbThis.cancelNotify("<ons-icon size=\"30px\" style=\"vertical-align: middle; color:#f7afbb;\" icon=\"fa-close\" href=\"#javascript\" onclick=\"app.cancelUpload('" + repeatIfNeeded.imageURI + "');\"></ons-icon><br/>Cancel"); retryIfNeeded.push(repeatIfNeeded); //Keep the screen awake as we upload window.plugins.insomnia.keepAwake(); repeatIfNeeded.ft.upload(repeatIfNeeded.imageURI, repeatIfNeeded.serverReq, glbThis.win, glbThis.fail, repeatIfNeeded.options); }, timein); //Wait 10 seconds before trying again } } }, check: function(){ //Checks to see if the next photo on the server (in the checkComplete stack) has been sent on to the PC successfully. If not it will keep pinging until is has been dealt with, or it times out. var nowChecking = checkComplete.pop(); nowChecking.loopCnt --; if(nowChecking.loopCnt <= 0) { //Have finished - remove interval and report back if(!nowChecking.slowLoopCnt) { document.getElementById("notify").innerHTML = "You are experiencing a slightly longer transfer time than normal, likely due to a slow network. Your image should be delivered shortly."; window.plugins.insomnia.allowSleepAgain(); //Allow the screen to sleep, we could be here for a while. //Now continue to check with this photo, but only once every 30 seconds, 90 times (i.e. for 45 minutes). nowChecking.slowLoopCnt = 90; checkComplete.push(nowChecking); //The file exists on the server still - try again in 30 seconds setTimeout(glbThis.check, 30000); } else { //Count down nowChecking.slowLoopCnt --; if(nowChecking.slowLoopCnt <= 0) { //Have finished the long count down, and given up document.getElementById("notify").innerHTML = "Sorry, the image is on the remote server, but has not been delivered to your local PC. We will try again once your app restarts."; glbThis.cancelNotify(""); //Remove any cancel icons } else { //Otherwise in the long count down checkComplete.push(nowChecking); var myNowChecking = nowChecking; glbThis.get(nowChecking.fullGet, function(url, resp) { if((resp === "false")||(resp === false)) { //File no longer exists, success! var myTitle = "Image"; if(myNowChecking.details && myNowChecking.details.options && myNowChecking.details.options.params && myNowChecking.details.options.params.title && myNowChecking.details.options.params.title != "") { myTitle = myNowChecking.details.options.params.title; } checkComplete.pop(); var more = " " + checkComplete.length + " more."; //Some more yet if(checkComplete.length == 0) { document.getElementById("notify").innerHTML = myTitle + ' transferred. Success! '; } else { if(myTitle != "") { document.getElementById("notify").innerHTML = myTitle + ' transferred. Success!' + more; } else { document.getElementById("notify").innerHTML = 'Image transferred. Success!' + more; } } //and delete phone version if(myNowChecking.details) { glbThis.changeLocalPhotoStatus(myNowChecking.details.imageURI, 'cancel'); } else { document.getElementById("notify").innerHTML = 'Image transferred. Success! ' + more + ' Note: The image will be resent on a restart to verify.'; } } else { //The file exists on the server still - try again in 30 seconds setTimeout(glbThis.check, 30000); } }); } } } else { //Try a get request to the check //Get the current file data checkComplete.push(nowChecking); glbThis.cancelNotify(""); //Remove any cancel icons var myNowChecking = nowChecking; document.getElementById("notify").innerHTML = "Image on server. Transferring to PC.. " + nowChecking.loopCnt; glbThis.cancelNotify(""); //Remove any cancel icons var myNowChecking = nowChecking; glbThis.get(nowChecking.fullGet, function(url, resp) { if((resp === "false")||(resp === false)) { //File no longer exists, success! checkComplete.pop(); var myTitle = "Image"; if(myNowChecking.details && myNowChecking.details.options && myNowChecking.details.options.params && myNowChecking.details.options.params.title && myNowChecking.details.options.params.title != "") { myTitle = myNowChecking.details.options.params.title; } var more = " " + checkComplete.length + " more."; //Some more yet if(checkComplete.length == 0) { document.getElementById("notify").innerHTML = myTitle + ' transferred. Success! '; } else { if(myTitle != "") { document.getElementById("notify").innerHTML = myTitle + ' transferred. Success!' + more; } else { document.getElementById("notify").innerHTML = 'Image transferred. Success!' + more; } } //and delete phone version if(myNowChecking.details) { glbThis.changeLocalPhotoStatus(myNowChecking.details.imageURI, 'cancel'); } else { document.getElementById("notify").innerHTML = 'Image transferred. Success! ' + more + ' Note: The image will be resent on a restart to verify.'; } } else { //The file exists on the server still - try again in a few moments setTimeout(glbThis.check, 2000); } }); } }, win: function(r) { //Have finished transferring the file to the server window.plugins.insomnia.allowSleepAgain(); //Allow sleeping again document.querySelector('#status').innerHTML = ""; //Clear progress status glbThis.cancelNotify(""); //Remove any cancel icons //Check if this was a transfer to the remote server console.log("Code = " + r.responseCode); console.log("Response = " + r.response); console.log("Sent = " + r.bytesSent); if((r.responseCode == 200)||(r.response.indexOf("200") != -1)) { var remoteServer = localStorage.getItem("serverRemote"); if(remoteServer == 'false') { //i.e. Wifi case //and delete phone version of file var repeatIfNeeded = retryIfNeeded.pop(); var more = " " + retryIfNeeded.length + " more."; //Some more yet var myTitle = "Image"; if(repeatIfNeeded) { if(repeatIfNeeded.detail && repeatIfNeeded.detail.options && repeatIfNeeded.detail.options.params && repeatIfNeeded.detail.options.params.title && repeatIfNeeded.detail.options.params.title != "") { document.getElementById("notify").innerHTML = myTitle + ' transferred. Success! ' + more; myTitle = repeatIfNeeded.detail.options.params.title; } else { document.getElementById("notify").innerHTML = 'Image transferred. Success!' + more; } glbThis.changeLocalPhotoStatus(repeatIfNeeded.imageURI, 'cancel'); } else { //Trying to check, but no file on stack document.getElementById("notify").innerHTML = 'Image transferred. Success! ' + more + ' Note: The image will be resent on a restart to verify.'; } } else { //Onto remote server - now do some pings to check we have got to the PC document.getElementById("notify").innerHTML = 'Image on server. Transferring to PC..'; var repeatIfNeeded = retryIfNeeded.pop(); if(repeatIfNeeded) { var thisFile = repeatIfNeeded.options.fileName; var usingServer = localStorage.getItem("usingServer"); var fullGet = usingServer + '/check=' + encodeURIComponent(thisFile); var nowChecking = {}; nowChecking.loopCnt = 11; //Max timeout = 11*2 = 22 secs but also a timeout of 5 seconds on the request. nowChecking.fullGet = fullGet; nowChecking.details = repeatIfNeeded; checkComplete.push(nowChecking); //Set an 'onserver' status glbThis.changeLocalPhotoStatus(repeatIfNeeded.imageURI, 'onserver', nowChecking); setTimeout(function() { //Wait two seconds and then do a check glbThis.check(); }, 2000); } else { //Trying to check, but no file on stack } } //Save the current server settings for future reuse glbThis.saveServer(); } else { //Retry sending glbThis.retry(""); } }, fail: function(error) { window.plugins.insomnia.allowSleepAgain(); //Allow the screen to sleep document.querySelector('#status').innerHTML = ""; //Clear progress status glbThis.cancelNotify(""); //Remove any cancel icons switch(error.code) { case 1: glbThis.notify("The photo was uploaded."); break; case 2: glbThis.notify("Sorry you have tried to send it to an invalid URL."); break; case 3: glbThis.notify("Waiting for better reception.."); glbThis.retry("Waiting for better reception...</br>"); break; case 4: glbThis.notify("Your image transfer was aborted."); //No need to retry here: glbThis.retry("Sorry, your image transfer was aborted.</br>"); break; default: glbThis.notify("An error has occurred: Code = " + error.code); break; } }, getip: function(cb) { var _this = this; //timeout after 3 secs -rerun this.findServer() var iptime = setTimeout(function() { var err = "You don't appear to be connected to your wifi. Please connect and try again."; cb(err); }, 5000); networkinterface.getWiFiIPAddress(function(ipInfo) { _this.ip = ipInfo.ip; //note: we could use ipInfo.subnet here but, this could be a 16-bit subnet rather than 24-bit? var len = ipInfo.ip.lastIndexOf('\.') + 1; _this.lan = ipInfo.ip.substr(0,len); clearTimeout(iptime); cb(null); }); }, factoryReset: function() { //We have connected to a server OK var _this = this; navigator.notification.confirm( 'Are you sure? All your saved PCs and other settings will be cleared.', // message function(buttonIndex) { if(buttonIndex == 1) { localStorage.clear(); localStorage.removeItem("usingServer"); //Init it localStorage.removeItem("defaultDir"); //Init it localStorage.removeItem("currentRemoteServer"); localStorage.removeItem("currentWifiServer"); localStorage.setItem("initialHash", 'true'); //Default to write a folder document.getElementById("always-create-folder").checked = true; //Now refresh the current server display document.getElementById("currentPC").innerHTML = ""; alert("Cleared all saved PCs."); glbThis.openSettings(); } }, // callback to invoke 'Clear Settings', // title ['Ok','Cancel'] // buttonLabels ); return false; }, checkDefaultDir: function(server) { //Check if the default server has a default dir eg. input: // http://123.123.123.123:5566/write/fshoreihtskhfv //Where the defaultDir would be 'fshoreihtskhfv' //Returns '{ server: "http://123.123.123.123:5566", dir: "fshoreihtskhfv"' var requiredStr = "/write/"; var startsAt = server.indexOf(requiredStr); if(startsAt >= 0) { //Get the default dir after the /write/ string var startFrom = startsAt + requiredStr.length; var defaultDir = server.substr(startFrom); var properServer = server.substr(0, startsAt); return { server: properServer, dir: defaultDir }; } else { return { server: server, dir: "" }; } }, connect: function(results) { //Save the server with a name //Get existing settings array switch(results.buttonIndex) { case 1: //Clicked on 'Ok' //Start the pairing process var pairUrl = centralPairingUrl + '?compare=' + results.input1; glbThis.notify("Pairing.."); glbThis.get(pairUrl, function(url, resp) { if(resp) { resp = resp.replace('\n', '') if(resp == 'nomatch') { glbThis.notify("Sorry, there was no match for that code."); return; } else { var server = resp; glbThis.notify("Pairing success."); //And save this server localStorage.setItem("currentRemoteServer",server); localStorage.removeItem("currentWifiServer"); //Clear the wifi localStorage.removeItem("usingServer"); //Init it localStorage.removeItem("defaultDir"); //Init it navigator.notification.confirm( 'Do you want to connect via WiFi, if it is available, also?', // message function(buttonIndex) { if(buttonIndex == 1) { //yes, we also want to connect via wifi glbThis.checkWifi(function(err) { if(err) { //An error finding wifi glbThis.notify(err); glbThis.bigButton(); } else { //Ready to take a picture, rerun with this //wifi server glbThis.notify("WiFi paired successfully."); glbThis.bigButton(); } }); } else { glbThis.notify("Pairing success, without WiFi."); glbThis.bigButton(); } }, // callback to invoke 'Pairing Success!', // title ['Yes','No'] // buttonLabels ); return; } } else { //A 404 response glbThis.notify("Sorry, we could not connect to the pairing server. Please try again."); } }); //end of get return; break; case 2: //Clicked on 'Wifi only' //Otherwise, first time we are running the app this session localStorage.removeItem("currentWifiServer"); //Clear the wifi localStorage.removeItem("currentRemoteServer"); //Clear the wifi localStorage.removeItem("usingServer"); //Init it localStorage.removeItem("defaultDir"); //Init it glbThis.checkWifi(function(err) { if(err) { //An error finding server - likely need to enter a pairing code. Warn the user glbThis.notify(err); } else { //Ready to take a picture, rerun glbThis.notify("Wifi paired successfully."); glbThis.bigButton(); } }); return; break; default: //Clicked on 'Cancel' break; } }, bigButton: function() { //Called when pushing the big button var _this = this; var foundRemoteServer = null; var foundWifiServer = null; foundRemoteServer = localStorage.getItem("currentRemoteServer"); foundWifiServer = localStorage.getItem("currentWifiServer"); if(((foundRemoteServer == null)||(foundRemoteServer == ""))&& ((foundWifiServer == null)||(foundWifiServer == ""))) { //Likely need to enter a pairing code. Warn the user //No current server - first time with this new connection //We have connected to a server OK navigator.notification.prompt( 'Please enter the 4 letter pairing code from your PC.', // message glbThis.connect, // callback to invoke 'New Connection', // title ['Ok','Use Wifi Only','Cancel'], // buttonLabels '' // defaultText ); } else { //Ready to take a picture _this.takePicture(); } }, checkWifi: function(cb) { glbThis.notify("Checking Wifi connection"); this.getip(function(ip, err) { if(err) { cb(err); return; } glbThis.notify("Scanning Wifi"); glbThis.scanlan('5566', function(url, err) { if(err) { cb(err); } else { cb(null); } }); }); }, getOptions: function(guid, cb) { //Input a server dir e.g. uPSE4UWHmJ8XqFUqvf // where the last part is the guid. //Get a URL like this: https://atomjump.com/med-settings.php?type=get&guid=uPSE4UWHmJ8XqFUqvf //to get a .json array of options. var settingsUrl = "https://atomjump.com/med-settings.php?type=get&guid=" + guid; glbThis.get(settingsUrl, function(url, resp) { if(resp != "") { var options = JSON.stringify(resp); //Or is it without the json parsing? if(options) { //Set local storage //localStorage.removeItem("serverOptions"); localStorage.setItem("serverOptions", options); cb(null); } else { cb("No options"); } } else { cb("No options"); } }); }, clearOptions: function() { localStorage.removeItem("serverOptions"); }, findServer: function(cb) { //Check storage for any saved current servers, and set the remote and wifi servers //along with splitting any subdirectories, ready for use by the the uploader. //Then actually try to connect - if wifi is an option, use that first var _this = this; var alreadyReturned = false; var found = false; //Clear off var foundRemoteServer = null; var foundWifiServer = null; var foundRemoteDir = null; var foundWifiDir = null; var usingServer = null; this.clearOptions(); //Early out usingServer = localStorage.getItem("usingServer"); if((usingServer)&&(usingServer != null)) { cb(null); return; } foundRemoteServer = localStorage.getItem("currentRemoteServer"); foundWifiServer = localStorage.getItem("currentWifiServer"); if((foundRemoteServer)&&(foundRemoteServer != null)&&(foundRemoteServer != "")) { //Already found a remote server //Generate the directory split, if any. Setting RAM foundServer and defaultDir var split = this.checkDefaultDir(foundRemoteServer); foundRemoteServer = split.server; foundRemoteDir = split.dir; } else { foundRemoteServer = null; foundRemoteDir = null; } //Check if we have a Wifi option if((foundWifiServer)&&(foundWifiServer != null)&&(foundWifiServer != "")) { //Already found wifi //Generate the directory split, if any. Setting RAM foundServer and defaultDir var split = this.checkDefaultDir(foundWifiServer); foundWifiServer = split.server; foundWifiDir = split.dir; } else { foundWifiServer = null; foundWifiDir = null; } //Early out: if((foundWifiServer == null)&&(foundRemoteServer == null)) { cb('No known server.'); return; } //Now try the wifi server as the first option to use if it exists: if((foundWifiServer)&&(foundWifiServer != null)&&(foundWifiServer != "null")) { //Ping the wifi server glbThis.notify('Trying to connect to the wifi server..'); //Timeout after 5 secs for the following ping var scanning = setTimeout(function() { glbThis.notify('Timeout finding your wifi server.</br>Trying remote server..'); //Else can't communicate with the wifi server at this time. //Try the remote server if((foundRemoteServer)&&(foundRemoteServer != null)&&(foundRemoteServer != "null")) { var scanningB = setTimeout(function() { //Timed out connecting to the remote server - that was the //last option. localStorage.removeItem("usingServer"); localStorage.removeItem("defaultDir"); localStorage.removeItem("serverRemote"); if(alreadyReturned == false) { alreadyReturned = true; cb('No server found'); } }, 6000); glbThis.get(foundRemoteServer, function(url, resp) { if(resp != "") { //Success, got a connection to the remote server clearTimeout(scanningB); //Ensure we don't error out localStorage.setItem("usingServer", foundRemoteServer); localStorage.setItem("serverRemote", 'true'); localStorage.setItem("defaultDir", foundRemoteDir); if(alreadyReturned == false) { alreadyReturned = true; //Get any global options glbThis.getOptions(foundRemoteDir); cb(null); } clearTimeout(scanning); //Ensure we don't error out } }); } else { //Only wifi existed localStorage.removeItem("usingServer"); localStorage.removeItem("defaultDir"); localStorage.removeItem("serverRemote"); if(alreadyReturned == false) { alreadyReturned = true; cb('No server found'); } } }, 2000); //Ping the wifi server glbThis.get(foundWifiServer, function(url, resp) { if(resp != "") { //Success, got a connection to the wifi clearTimeout(scanning); //Ensure we don't error out localStorage.setItem("usingServer", foundWifiServer); localStorage.setItem("defaultDir", foundWifiDir); localStorage.setItem("serverRemote", 'false'); if(alreadyReturned == false) { alreadyReturned = true; cb(null); //Success found server } } }); } else { //OK - no wifi option - go straight to the remote server //Try the remote server glbThis.notify('Trying to connect to the remote server....'); var scanning = setTimeout(function() { //Timed out connecting to the remote server - that was the //last option. localStorage.removeItem("usingServer"); localStorage.removeItem("defaultDir"); localStorage.removeItem("serverRemote"); if(alreadyReturned == false) { alreadyReturned = true; cb('No server found'); } }, 6000); _this.get(foundRemoteServer, function(url, resp) { if(resp != "") { //Success, got a connection to the remote server localStorage.setItem("usingServer", foundRemoteServer); localStorage.setItem("defaultDir", foundRemoteDir); localStorage.setItem("serverRemote", 'true'); if(alreadyReturned == false) { alreadyReturned = true; //Get any global options glbThis.getOptions(foundRemoteDir); cb(null); } clearTimeout(scanning); //Ensure we don't error out } }); } }, /* Settings Functions */ openSettings: function() { //Open the settings screen var html = this.listServers(); document.getElementById("settings").innerHTML = html; document.getElementById("settings-popup").style.display = "block"; }, closeSettings: function() { //Close the settings screen document.getElementById("settings-popup").style.display = "none"; }, listServers: function() { //List the available servers var settings = this.getArrayLocalStorage("settings"); if(settings) { var html = "<ons-list><ons-list-header>Select a PC to use now:</ons-list-header>"; //Convert the array into html for(var cnt=0; cnt< settings.length; cnt++) { html = html + "<ons-list-item><ons-list-item onclick='app.setServer(" + cnt + ");'>" + settings[cnt].name + "</ons-list-item><div class='right'><ons-icon icon='md-delete' onclick='app.deleteServer(" + cnt + ");'></ons-icon></div></ons-list-item>"; } html = html + "</ons-list>"; } else { var html = "<ons-list><ons-list-header>PCs Stored</ons-list-header>"; var html = html + "<ons-list-item><ons-list-item>Default</ons-list-item><div class='right'><ons-icon icon='md-delete'style='color:#AAA></ons-icon></div></ons-list-item>"; html = html + "</ons-list>"; } return html; }, setServer: function(serverId) { //Set the server to the input server id var settings = this.getArrayLocalStorage("settings"); var currentRemoteServer = settings[serverId].currentRemoteServer; var currentWifiServer = settings[serverId].currentWifiServer; localStorage.removeItem("usingServer"); //reset the currently used server //Save the current server localStorage.removeItem("defaultDir"); //Remove if one of these doesn't exist, and use the other. if((!currentWifiServer)||(currentWifiServer == null)||(currentWifiServer =="")) { localStorage.removeItem("currentWifiServer"); } else { localStorage.setItem("currentWifiServer", currentWifiServer); } if((!currentRemoteServer)||(currentRemoteServer == null)||(currentRemoteServer == "")) { localStorage.removeItem("currentRemoteServer"); } else { localStorage.setItem("currentRemoteServer", currentRemoteServer); } //Set the localstorage localStorage.setItem("currentServerName", settings[serverId].name); navigator.notification.alert("Switched to: " + settings[serverId].name, function() {}, "Changing PC"); //Now refresh the current server display document.getElementById("currentPC").innerHTML = settings[serverId].name; this.closeSettings(); return false; }, newServer: function() { //Create a new server. //This is actually effectively resetting, and we will allow the normal functions to input a new one localStorage.removeItem("usingServer"); //Remove the current one localStorage.removeItem("currentRemoteServer"); localStorage.removeItem("currentWifiServer"); this.notify("Tap above to activate."); //Clear off old notifications //Ask for a name of the current Server: navigator.notification.prompt( 'Please enter a name for this PC', // message this.saveServerName, // callback to invoke 'PC Name', // title ['Ok','Cancel'], // buttonLabels 'Main' // defaultText ); }, deleteServer: function(serverId) { //Delete an existing server this.myServerId = serverId; navigator.notification.confirm( 'Are you sure? This PC will be removed from memory.', // message function(buttonIndex) { if(buttonIndex == 1) { var settings = glbThis.getArrayLocalStorage("settings"); if((settings == null)|| (settings == '')) { //Nothing to delete } else { //Check if it is deleting the current entry var deleteName = settings[glbThis.myServerId].name; var currentServerName = localStorage.getItem("currentServerName"); if((currentServerName) && (deleteName) && (currentServerName == deleteName)) { //Now refresh the current server display document.getElementById("currentPC").innerHTML = ""; localStorage.removeItem("currentRemoteServer"); localStorage.removeItem("currentWifiServer"); localStorage.removeItem("currentServerName"); } settings.splice(glbThis.myServerId, 1); //Remove the entry entirely from array glbThis.setArrayLocalStorage("settings", settings); } glbThis.openSettings(); //refresh } }, // callback to invoke 'Remove PC', // title ['Ok','Cancel'] // buttonLabels ); }, saveServerName: function(results) { //Save the server with a name - but since this is new, //Get existing settings array if(results.buttonIndex == 1) { //Clicked on 'Ok' localStorage.setItem("currentServerName", results.input1); //Now refresh the current server display document.getElementById("currentPC").innerHTML = results.input1; glbThis.closeSettings(); return; } else { //Clicked on 'Exit'. Do nothing. return; } }, displayServerName: function() { //Call this during initialisation on app startup var currentServerName = localStorage.getItem("currentServerName"); if((currentServerName) && (currentServerName != null)) { //Now refresh the current server display document.getElementById("currentPC").innerHTML = currentServerName; } else { document.getElementById("currentPC").innerHTML = ""; } }, saveIdInput: function(status) { //Save the idInput. input true/false true = 'start with a hash' // false = 'start with blank' //Get existing settings array if(status == true) { //Show a hash by default localStorage.setItem("initialHash", "true"); } else { //Remove the hash by default localStorage.setItem("initialHash", "false"); } }, displayIdInput: function() { //Call this during initialisation on app startup var initialHash = localStorage.getItem("initialHash"); if((initialHash) && (initialHash != null)) { //Now refresh the current ID field if(initialHash == "true") { document.getElementById("always-create-folder").checked = true; } else { document.getElementById("always-create-folder").checked = false; } } }, saveServer: function() { //Run this after a successful upload var currentServerName = localStorage.getItem("currentServerName"); var currentRemoteServer = localStorage.getItem("currentRemoteServer"); var currentWifiServer = localStorage.getItem("currentWifiServer"); if((!currentServerName) ||(currentServerName == null)) currentServerName = "Default"; if((!currentRemoteServer) ||(currentRemoteServer == null)) currentRemoteServer = ""; if((!currentWifiServer) ||(currentWifiServer == null)) currentWifiServer = ""; var settings = glbThis.getArrayLocalStorage("settings"); //Create a new entry - which will be blank to being with var newSetting = { "name": currentServerName, //As input by the user "currentRemoteServer": currentRemoteServer, "currentWifiServer": currentWifiServer }; if((settings == null)|| (settings == '')) { //Creating an array for the first time var settings = []; settings.push(newSetting); //Save back to the array } else { //Check if we are writing over the existing entries var writeOver = false; for(cnt = 0; cnt< settings.length; cnt++) { if(settings[cnt].name == currentServerName) { writeOver = true; settings[cnt] = newSetting; } } if(writeOver == false) { settings.push(newSetting); //Save back to the array } } //Save back to the persistent settings glbThis.setArrayLocalStorage("settings", settings); return; }, //Array storage for app permanent settings (see http://inflagrantedelicto.memoryspiral.com/2013/05/phonegap-saving-arrays-in-local-storage/) setArrayLocalStorage: function(mykey, myobj) { return localStorage.setItem(mykey, JSON.stringify(myobj)); }, getArrayLocalStorage: function(mykey) { return JSON.parse(localStorage.getItem(mykey)); } };
www/js/index.js
/* * 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. */ //Source code Copyright (c) 2018 AtomJump Ltd. (New Zealand) var deleteThisFile = {}; //Global object for image taken, to be deleted var centralPairingUrl = "https://atomjump.com/med-genid.php"; //Redirects to an https connection. In future try setting to http://atomjump.org/med-genid.php var glbThis = {}; //Used as a global error handler var retryIfNeeded = []; //A global pushable list with the repeat attempts var checkComplete = []; //A global pushable list with the repeat checks to see if image is on PC var retryNum = 0; //See: https://stackoverflow.com/questions/14787705/phonegap-cordova-filetransfer-abort-not-working-as-expected // basic implementation of hash map of FileTransfer objects // so that given a key, an abort function can find the right FileTransfer to abort function SimpleHashMap() { this.items = {}; this.setItem = function(key, value) { this.items[key] = value; } this.getItem = function(key) { if (this.hasItem(key)) { return this.items[key]; } return undefined; } this.hasItem = function(key) { return this.items.hasOwnProperty(key); } this.removeItem = function(key) { if (this.hasItem(key)) { delete this.items[key]; } } } var fileTransferMap = new SimpleHashMap(); var app = { // Application Constructor initialize: function() { glbThis = this; this.bindEvents(); //Set display name this.displayServerName(); //Initialise the id field this.displayIdInput(); //Check if there are any residual photos that need to be sent again glbThis.loopLocalPhotos(); }, // Bind Event Listeners // // Bind any events that are required on startup. Common events are: // 'load', 'deviceready', 'offline', and 'online'. bindEvents: function() { document.addEventListener('deviceready', this.onDeviceReady, false); }, // deviceready Event Handler // // The scope of 'this' is the event. In order to call the 'receivedEvent' // function, we must explicity call 'app.receivedEvent(...);' onDeviceReady: function() { app.receivedEvent('deviceready'); }, // Update DOM on a Received Event receivedEvent: function(id) { var parentElement = document.getElementById(id); if(parentElement) { var listeningElement = parentElement.querySelector('.listening'); var receivedElement = parentElement.querySelector('.received'); listeningElement.setAttribute('style', 'display:none;'); receivedElement.setAttribute('style', 'display:block;'); console.log('Received Event: ' + id); } else { console.log('Failed Received Event: ' + id); } }, processPicture: function(imageURI) { var _this = this; glbThis = this; //Called from takePicture(), after the image file URI has been shifted into a persistent file //Reconnect once localStorage.removeItem("usingServer"); //This will force a reconnection localStorage.removeItem("defaultDir"); var thisImageURI = imageURI; var idEntered = document.getElementById("id-entered").value; //Store in case the app quits unexpectably _this.determineFilename(imageURI, idEntered, function(err, newFilename) { if(err) { //There was a problem getting the filename from the disk file glbThis.notify("Sorry, we cannot process the filename of the photo " + idEntered + ". If this happens consistently, please report the problem to medimage.co.nz"); } else { _this.recordLocalPhoto( imageURI, idEntered, newFilename); _this.findServer(function(err) { if(err) { glbThis.notify("Sorry, we cannot connect to the server. Trying again in 10 seconds."); //Search again in 10 seconds: var passedImageURI = thisImageURI; var idEnteredB = idEntered; setTimeout(function() { localStorage.removeItem("usingServer"); //This will force a reconnection localStorage.removeItem("defaultDir"); glbThis.uploadPhoto(passedImageURI, idEnteredB, newFilename); }, 10000); } else { //Now we are connected, upload the photo again glbThis.uploadPhoto(thisImageURI, idEntered, newFilename); } }); } }); }, takePicture: function() { var _this = this; glbThis = this; navigator.camera.getPicture( function( imageURI ) { //Move picture into persistent storage //Grab the file name of the photo in the temporary directory var currentName = imageURI.replace(/^.*[\\\/]/, ''); //Create a new name for the photo var d = new Date(), n = d.getTime(), newFileName = n + ".jpg"; window.resolveLocalFileSystemURI( imageURI, function(fileEntry) { var myFile = fileEntry; try { //Try moving the file to permanent storage window.resolveLocalFileSystemURL( cordova.file.dataDirectory, function(directory) { try { myFile.moveTo(directory, newFileName, function(success){ //Moved it to permanent storage successfully //success.fullPath contains the path to the photo in permanent storage if(success.nativeURL) { glbThis.processPicture(success.nativeURL); } else { glbThis.notify("Sorry we could not find the moved photo on the phone. Please let medimage.co.nz know that a moveFile() has not worked correctly."); } }, function(err){ //an error occured moving file - send anyway, even if it is in the temporary folder glbThis.processPicture(imageURI); }); } catch(err) { //A problem moving the file but send the temp file anyway glbThis.processPicture(imageURI); } }, function(err) { //an error occured moving file - send anyway, even if it is in the temporary folder glbThis.processPicture(imageURI); }); } catch(err) { //A proble occured determining if the persistent folder existed glbThis.processPicture(imageURI); } }, function(err) { //Could not resolve local file glbThis.notify("Sorry we could not find the photo on the phone."); }); }, function( message ) { //An error or cancellation glbThis.notify( message ); }, { quality: 100, destinationType: Camera.DestinationType.FILE_URI }); }, recordLocalPhoto: function(imageURI, idEntered, fileName) { //Save into our localPhotos array, in case the app quits var localPhotos = glbThis.getArrayLocalStorage("localPhotos"); if(!localPhotos) { localPhotos = []; } var newPhoto = { "imageURI" : imageURI, "idEntered" : idEntered, "fileName" : fileName, "status" : "send" }; //Status can be 'send', 'sent' (usually deleted from the array), or 'cancel' localPhotos.push(newPhoto); glbThis.setArrayLocalStorage("localPhotos", localPhotos); return true; }, changeLocalPhotoStatus: function(imageURI, newStatus) { var localPhotos = glbThis.getArrayLocalStorage("localPhotos"); if(!localPhotos) { localPhotos = []; } for(var cnt = 0; cnt< localPhotos.length; cnt++) { if(localPhotos[cnt].imageURI === imageURI) { if(newStatus === "cancel") { //Delete the photo window.resolveLocalFileSystemURI(imageURI, function(fileEntry) { //Remove the file from the phone fileEntry.remove(); //Remove entry from the array var splicing = cnt - 1; localPhotos.splice(splicing,1); //Set back the storage of the array glbThis.setArrayLocalStorage("localPhotos", localPhotos); }, function(evt) { //Some form of error case. We likely couldn't find the file, but we still want to remove the entry from the array //in this case var errorCode = null; if(evt.code) { errorCode = evt.code; } if(evt.target && evt.target.error.code) { errorCode = evt.target.error.code; } if(errorCode === 1) { //The photo is not there. Remove anyway //Remove entry from the array var splicing = cnt - 1; localPhotos.splice(splicing,1); //Set back the storage of the array glbThis.setArrayLocalStorage("localPhotos", localPhotos); } else { glbThis.notify("Sorry, there was a problem removing the photo on the phone. Error code: " + evt.target.error.code); //Remove entry from the array var splicing = cnt - 1; localPhotos.splice(splicing,1); //Set back the storage of the array glbThis.setArrayLocalStorage("localPhotos", localPhotos); } }); } else { localPhotos[cnt].status = newStatus; //Set back the storage of the array glbThis.setArrayLocalStorage("localPhotos", localPhotos); } } } }, loopLocalPhotos: function() { //Get a photo, one at a time, in the array format: /* { "imageURI" : imageURI, "idEntered" : idEntered "fileName" : fileName "status" : "send" }; //Status can be 'send', 'sent' (usually deleted from the array), or 'cancel' and attempt to upload them. */ var photoDetails = null; var localPhotos = glbThis.getArrayLocalStorage("localPhotos"); if(!localPhotos) { localPhotos = []; } for(var cnt = 0; cnt< localPhotos.length; cnt++) { var newPhoto = localPhotos[cnt]; if(newPhoto) { glbThis.uploadPhoto(newPhoto.imageURI, newPhoto.idEntered, newPhoto.fileName); } } return; }, get: function(url, cb) { var request = new XMLHttpRequest(); request.open("GET", url, true); var getTimeout = setTimeout(function() { cb(url, null); // Assume it hasn't gone through - we have a 404 error checking the server }, 5000); request.onreadystatechange = function() { if (request.readyState == 4) { if (request.status == 200 || request.status == 0) { clearTimeout(getTimeout); cb(url, request.responseText); // -> request.responseText <- is a result } } } request.onerror = function() { clearTimeout(getTimeout); cb(url, null); } request.send(); }, scanlan: function(port, cb) { var _this = this; if(this.lan) { var lan = this.lan; for(var cnt=0; cnt< 255; cnt++){ var machine = cnt.toString(); var url = 'http://' + lan + machine + ':' + port; this.get(url, function(goodurl, resp) { if(resp) { //Save the first TODO: if more than one, open another screen here localStorage.setItem("currentWifiServer", goodurl); clearTimeout(scanning); cb(goodurl, null); } }); } //timeout after 5 secs var scanning = setTimeout(function() { _this.notify('Timeout finding your Wifi server.'); }, 4000); } else { //No lan detected cb(null,'Local Wifi server not detected.'); } }, notify: function(msg) { //Set the user message document.getElementById("notify").innerHTML = msg; }, cancelNotify: function(msg) { //Set the user message document.getElementById("cancel-trans").innerHTML = msg; }, cancelUpload: function(cancelURI) { var ft = fileTransferMap.getItem(cancelURI); if (ft) { ft.abort(glbThis.win, glbThis.fail); //remove the photo glbThis.changeLocalPhotoStatus(cancelURI, "cancel"); } }, determineFilename: function(imageURIin, idEntered, cb) { //Determines the filename to use based on the imageURI of the photo, //and the id entered into the text field. //Calls back with: cb(err, newFilename) // where err is null for no error, or text of the error, // and the newFilename as a text string which includes the .jpg at the end. //It will use the current date / time from the phone, thought this format varies slightly //phone to phone. //Have connected OK to a server var idEnteredB = idEntered; window.resolveLocalFileSystemURI(imageURIin, function(fileEntry) { deleteThisFile = fileEntry; //Store globally var imageURI = fileEntry.toURL(); var tempName = idEnteredB; if((tempName == '')||(tempName == null)) { tempName = 'image'; } var initialHash = localStorage.getItem("initialHash"); if((initialHash)&&(initialHash != null)) { if(initialHash == 'true') { //Prepend the initial hash tempName = "#" + tempName; } } else { //Not set, so prepend the initial hash by default tempName = "#" + tempName; } var defaultDir = localStorage.getItem("defaultDir"); if((defaultDir)&&(defaultDir != null)) { //A hash code signifies a directory to write to tempName = "#" + defaultDir + " " + tempName; } var myoutFile = tempName.replace(/ /g,'-'); var idEnteredC = idEnteredB; //Get a 2nd tier of variable navigator.globalization.dateToString( new Date(), function (date) { var mydt = date.value.replace(/:/g,'-'); mydt = mydt.replace(/ /g,'-'); mydt = mydt.replace(/\//g,'-'); var aDate = new Date(); var seconds = aDate.getSeconds(); mydt = mydt + "-" + seconds; mydt = mydt.replace(/,/g,''); //remove any commas from iphone mydt = mydt.replace(/\./g,'-'); //remove any fullstops var myNewFileName = myoutFile + '-' + mydt + '.jpg'; cb(null, myNewFileName); }, function () { navigator.notification.alert('Sorry, there was an error getting the current date\n'); cb("Sorry, there was an error getting the current date"); }, { formatLength:'medium', selector:'date and time'} ); //End of function in globalization date to string }, function(evt) { //An error accessing the file //and potentially delete phone version glbThis.changeLocalPhotoStatus(myImageURIin, 'cancel'); cb("Sorry, we could not access the photo file"); }); //End of resolveLocalFileSystemURI }, uploadPhoto: function(imageURIin, idEntered, newFilename) { var _this = this; var usingServer = localStorage.getItem("usingServer"); var idEnteredB = idEntered; if((!usingServer)||(usingServer == null)) { //No remove server already connected to, find the server now. And then call upload again _this.findServer(function(err) { if(err) { window.plugins.insomnia.allowSleepAgain(); //Allow sleeping again glbThis.notify("Sorry, we cannot connect to the server. Trying again in 10 seconds."); //Search again in 10 seconds: setTimeout(function() { glbThis.uploadPhoto(imageURIin, idEnteredB, newFilename) }, 10000); } else { //Now we are connected, upload the photo again glbThis.uploadPhoto(imageURIin, idEnteredB, newFilename); } }); return; } else { //Have connected OK to a server var myImageURIin = imageURIin; var options = new FileUploadOptions(); options.fileKey="file1"; options.mimeType="image/jpeg"; var params = new Object(); params.title = idEntered; //OLD: document.getElementById("id-entered").value; if((params.title == '')||(params.title == null)) { if((idEnteredB == '')||(idEnteredB == null)) { params.title = 'image'; } else { params.title = idEnteredB; } } options.fileName = newFilename; options.params = params; options.chunkedMode = false; //chunkedMode = false does work, but still having some issues. =true may only work on newer systems? options.headers = { Connection: "close" } options.idEntered = idEnteredB; var ft = new FileTransfer(); _this.notify("Uploading " + params.title); _this.cancelNotify("<ons-icon style=\"vertical-align: middle; color:#f7afbb;\" size=\"30px\" icon=\"fa-close\" href=\"#javascript\" onclick=\"app.cancelUpload('" + imageURI + "');\"></ons-icon><br/>Cancel"); ft.onprogress = _this.progress; var serverReq = usingServer + '/api/photo'; var repeatIfNeeded = { "imageURI" : imageURI, "serverReq" : serverReq, "options" :options, "failureCount": 0, "nextAttemptSec": 15 }; retryIfNeeded.push(repeatIfNeeded); fileTransferMap.setItem(imageURI, ft); //Make sure we can abort this photo later //Keep the screen awake as we upload window.plugins.insomnia.keepAwake(); ft.upload(imageURI, serverReq, _this.win, _this.fail, options); } //End of connected to a server OK }, progress: function(progressEvent) { var statusDom = document.querySelector('#status'); if (progressEvent.lengthComputable) { var perc = Math.floor(progressEvent.loaded / progressEvent.total * 100); statusDom.innerHTML = perc + "% uploaded..."; } else { if(statusDom.innerHTML == "") { statusDom.innerHTML = "Uploading"; } else { statusDom.innerHTML += "."; } } }, retry: function(existingText) { window.plugins.insomnia.allowSleepAgain(); //Allow sleeping again var repeatIfNeeded = retryIfNeeded.pop(); if(repeatIfNeeded) { //Resend within a minute here var t = new Date(); t.setSeconds(t.getSeconds() + repeatIfNeeded.nextAttemptSec); var timein = (repeatIfNeeded.nextAttemptSec*1000); //In microseconds repeatIfNeeded.nextAttemptSec *= 3; //Increase the delay between attempts each time to save battery if(repeatIfNeeded.nextAttemptSec > 21600) repeatIfNeeded.nextAttemptSec = 21600; //If longer than 6 hours gap, make 6 hours (that is 60x60x6) var hrMin = t.getHours() + ":" + t.getMinutes(); glbThis.notify(existingText + " Retrying " + repeatIfNeeded.options.params.title + " at " + hrMin); repeatIfNeeded.failureCount += 1; //Increase this if(repeatIfNeeded.failureCount > 2) { //Have tried too many attempts - try to reconnect completely (i.e. go //from wifi to network and vica versa localStorage.removeItem("usingServer"); //This will force a reconnection localStorage.removeItem("defaultDir"); localStorage.removeItem("serverRemote"); glbThis.uploadPhoto(repeatIfNeeded.imageURI, repeatIfNeeded.options.idEntered, repeatIfNeeded.options.idEntered, repeatIfNeeded.options.fileName); //Clear any existing timeouts if(repeatIfNeeded.retryTimeout) { clearTimeout(repeatIfNeeded.retryTimeout); } //Clear the current transfer too repeatIfNeeded.ft.abort(); return; } else { //OK in the first few attempts - keep the current connection and try again //Wait 10 seconds+ here before trying the next upload repeatIfNeeded.retryTimeout = setTimeout(function() { repeatIfNeeded.ft = new FileTransfer(); repeatIfNeeded.ft.onprogress = glbThis.progress; glbThis.notify("Trying to upload " + repeatIfNeeded.options.params.title); glbThis.cancelNotify("<ons-icon size=\"30px\" style=\"vertical-align: middle; color:#f7afbb;\" icon=\"fa-close\" href=\"#javascript\" onclick=\"app.cancelUpload('" + repeatIfNeeded.imageURI + "');\"></ons-icon><br/>Cancel"); retryIfNeeded.push(repeatIfNeeded); //Keep the screen awake as we upload window.plugins.insomnia.keepAwake(); repeatIfNeeded.ft.upload(repeatIfNeeded.imageURI, repeatIfNeeded.serverReq, glbThis.win, glbThis.fail, repeatIfNeeded.options); }, timein); //Wait 10 seconds before trying again } } }, check: function(){ var nowChecking = checkComplete.pop(); nowChecking.loopCnt --; if(nowChecking.loopCnt <= 0) { //Have finished - remove interval and report back if(!nowChecking.slowLoopCnt) { document.getElementById("notify").innerHTML = "You are experiencing a slightly longer transfer time than normal, likely due to a slow network. Your image should be delivered shortly."; window.plugins.insomnia.allowSleepAgain(); //Allow the screen to sleep, we could be here for a while. //Now continue to check with this photo, but only once every 30 seconds, 90 times (i.e. for 45 minutes). nowChecking.slowLoopCnt = 90; checkComplete.push(nowChecking); //The file exists on the server still - try again in 30 seconds setTimeout(glbThis.check, 30000); } else { //Count down nowChecking.slowLoopCnt --; if(nowChecking.slowLoopCnt <= 0) { //Have finished the long count down, and given up document.getElementById("notify").innerHTML = "Sorry, the image is on the remote server, but has not been delivered to your local PC. We will try again once your app restarts."; glbThis.cancelNotify(""); //Remove any cancel icons } else { //Otherwise in the long count down checkComplete.push(nowChecking); var myNowChecking = nowChecking; glbThis.get(nowChecking.fullGet, function(url, resp) { if((resp === "false")||(resp === false)) { //File no longer exists, success! var myTitle = "Image"; if(myNowChecking.details && myNowChecking.details.options && myNowChecking.details.options.params && myNowChecking.details.options.params.title && myNowChecking.details.options.params.title != "") { myTitle = myNowChecking.details.options.params.title; } checkComplete.pop(); var more = " " + checkComplete.length + " more."; //Some more yet if(checkComplete.length == 0) { document.getElementById("notify").innerHTML = myTitle + ' transferred. Success! '; } else { if(myTitle != "") { document.getElementById("notify").innerHTML = myTitle + ' transferred. Success!' + more; } else { document.getElementById("notify").innerHTML = 'Image transferred. Success!' + more; } } //and delete phone version if(myNowChecking.details) { glbThis.changeLocalPhotoStatus(myNowChecking.details.imageURI, 'cancel'); } else { document.getElementById("notify").innerHTML = 'Image transferred. Success! ' + more + ' Note: The image will be resent on a restart to verify.'; } } else { //The file exists on the server still - try again in 30 seconds setTimeout(glbThis.check, 30000); } }); } } } else { //Try a get request to the check //Get the current file data checkComplete.push(nowChecking); glbThis.cancelNotify(""); //Remove any cancel icons var myNowChecking = nowChecking; document.getElementById("notify").innerHTML = "Image on server. Transferring to PC.. " + nowChecking.loopCnt; glbThis.cancelNotify(""); //Remove any cancel icons var myNowChecking = nowChecking; glbThis.get(nowChecking.fullGet, function(url, resp) { if((resp === "false")||(resp === false)) { //File no longer exists, success! checkComplete.pop(); var myTitle = "Image"; if(myNowChecking.details && myNowChecking.details.options && myNowChecking.details.options.params && myNowChecking.details.options.params.title && myNowChecking.details.options.params.title != "") { myTitle = myNowChecking.details.options.params.title; } var more = " " + checkComplete.length + " more."; //Some more yet if(checkComplete.length == 0) { document.getElementById("notify").innerHTML = myTitle + ' transferred. Success! '; } else { if(myTitle != "") { document.getElementById("notify").innerHTML = myTitle + ' transferred. Success!' + more; } else { document.getElementById("notify").innerHTML = 'Image transferred. Success!' + more; } } //and delete phone version if(myNowChecking.details) { glbThis.changeLocalPhotoStatus(myNowChecking.details.imageURI, 'cancel'); } else { document.getElementById("notify").innerHTML = 'Image transferred. Success! ' + more + ' Note: The image will be resent on a restart to verify.'; } } else { //The file exists on the server still - try again in a few moments setTimeout(glbThis.check, 2000); } }); } }, win: function(r) { window.plugins.insomnia.allowSleepAgain(); //Allow sleeping again document.querySelector('#status').innerHTML = ""; //Clear progress status glbThis.cancelNotify(""); //Remove any cancel icons //Check if this was a transfer to the remote server console.log("Code = " + r.responseCode); console.log("Response = " + r.response); console.log("Sent = " + r.bytesSent); if((r.responseCode == 200)||(r.response.indexOf("200") != -1)) { var remoteServer = localStorage.getItem("serverRemote"); if(remoteServer == 'false') { //i.e. Wifi case //and delete phone version of file var repeatIfNeeded = retryIfNeeded.pop(); var more = " " + retryIfNeeded.length + " more."; //Some more yet var myTitle = "Image"; if(repeatIfNeeded) { if(repeatIfNeeded.detail && repeatIfNeeded.detail.options && repeatIfNeeded.detail.options.params && repeatIfNeeded.detail.options.params.title && repeatIfNeeded.detail.options.params.title != "") { document.getElementById("notify").innerHTML = myTitle + ' transferred. Success! ' + more; myTitle = repeatIfNeeded.detail.options.params.title; } else { document.getElementById("notify").innerHTML = 'Image transferred. Success!' + more; } glbThis.changeLocalPhotoStatus(repeatIfNeeded.imageURI, 'cancel'); } else { //Trying to check, but no file on stack document.getElementById("notify").innerHTML = 'Image transferred. Success! ' + more + ' Note: The image will be resent on a restart to verify.'; } } else { //Onto remote server - now do some pings to check we have got to the PC document.getElementById("notify").innerHTML = 'Image on server. Transferring to PC..'; var repeatIfNeeded = retryIfNeeded.pop(); if(repeatIfNeeded) { var thisFile = repeatIfNeeded.options.fileName; var usingServer = localStorage.getItem("usingServer"); var fullGet = usingServer + '/check=' + encodeURIComponent(thisFile); var nowChecking = {}; nowChecking.loopCnt = 11; //Max timeout = 11*2 = 22 secs but also a timeout of 5 seconds on the request. nowChecking.fullGet = fullGet; nowChecking.details = repeatIfNeeded; checkComplete.push(nowChecking); setTimeout(function() { //Wait two seconds and then do a check glbThis.check(); }, 2000); } else { //Trying to check, but no file on stack } } //Save the current server settings for future reuse glbThis.saveServer(); } else { //Retry sending glbThis.retry(""); } }, fail: function(error) { window.plugins.insomnia.allowSleepAgain(); //Allow the screen to sleep document.querySelector('#status').innerHTML = ""; //Clear progress status glbThis.cancelNotify(""); //Remove any cancel icons switch(error.code) { case 1: glbThis.notify("The photo was uploaded."); break; case 2: glbThis.notify("Sorry you have tried to send it to an invalid URL."); break; case 3: glbThis.notify("Waiting for better reception.."); glbThis.retry("Waiting for better reception...</br>"); break; case 4: glbThis.notify("Your image transfer was aborted."); //No need to retry here: glbThis.retry("Sorry, your image transfer was aborted.</br>"); break; default: glbThis.notify("An error has occurred: Code = " + error.code); break; } }, getip: function(cb) { var _this = this; //timeout after 3 secs -rerun this.findServer() var iptime = setTimeout(function() { var err = "You don't appear to be connected to your wifi. Please connect and try again."; cb(err); }, 5000); networkinterface.getWiFiIPAddress(function(ipInfo) { _this.ip = ipInfo.ip; //note: we could use ipInfo.subnet here but, this could be a 16-bit subnet rather than 24-bit? var len = ipInfo.ip.lastIndexOf('\.') + 1; _this.lan = ipInfo.ip.substr(0,len); clearTimeout(iptime); cb(null); }); }, factoryReset: function() { //We have connected to a server OK var _this = this; navigator.notification.confirm( 'Are you sure? All your saved PCs and other settings will be cleared.', // message function(buttonIndex) { if(buttonIndex == 1) { localStorage.clear(); localStorage.removeItem("usingServer"); //Init it localStorage.removeItem("defaultDir"); //Init it localStorage.removeItem("currentRemoteServer"); localStorage.removeItem("currentWifiServer"); localStorage.setItem("initialHash", 'true'); //Default to write a folder document.getElementById("always-create-folder").checked = true; //Now refresh the current server display document.getElementById("currentPC").innerHTML = ""; alert("Cleared all saved PCs."); glbThis.openSettings(); } }, // callback to invoke 'Clear Settings', // title ['Ok','Cancel'] // buttonLabels ); return false; }, checkDefaultDir: function(server) { //Check if the default server has a default dir eg. input: // http://123.123.123.123:5566/write/fshoreihtskhfv //Where the defaultDir would be 'fshoreihtskhfv' //Returns '{ server: "http://123.123.123.123:5566", dir: "fshoreihtskhfv"' var requiredStr = "/write/"; var startsAt = server.indexOf(requiredStr); if(startsAt >= 0) { //Get the default dir after the /write/ string var startFrom = startsAt + requiredStr.length; var defaultDir = server.substr(startFrom); var properServer = server.substr(0, startsAt); return { server: properServer, dir: defaultDir }; } else { return { server: server, dir: "" }; } }, connect: function(results) { //Save the server with a name //Get existing settings array switch(results.buttonIndex) { case 1: //Clicked on 'Ok' //Start the pairing process var pairUrl = centralPairingUrl + '?compare=' + results.input1; glbThis.notify("Pairing.."); glbThis.get(pairUrl, function(url, resp) { if(resp) { resp = resp.replace('\n', '') if(resp == 'nomatch') { glbThis.notify("Sorry, there was no match for that code."); return; } else { var server = resp; glbThis.notify("Pairing success."); //And save this server localStorage.setItem("currentRemoteServer",server); localStorage.removeItem("currentWifiServer"); //Clear the wifi localStorage.removeItem("usingServer"); //Init it localStorage.removeItem("defaultDir"); //Init it navigator.notification.confirm( 'Do you want to connect via WiFi, if it is available, also?', // message function(buttonIndex) { if(buttonIndex == 1) { //yes, we also want to connect via wifi glbThis.checkWifi(function(err) { if(err) { //An error finding wifi glbThis.notify(err); glbThis.bigButton(); } else { //Ready to take a picture, rerun with this //wifi server glbThis.notify("WiFi paired successfully."); glbThis.bigButton(); } }); } else { glbThis.notify("Pairing success, without WiFi."); glbThis.bigButton(); } }, // callback to invoke 'Pairing Success!', // title ['Yes','No'] // buttonLabels ); return; } } else { //A 404 response glbThis.notify("Sorry, we could not connect to the pairing server. Please try again."); } }); //end of get return; break; case 2: //Clicked on 'Wifi only' //Otherwise, first time we are running the app this session localStorage.removeItem("currentWifiServer"); //Clear the wifi localStorage.removeItem("currentRemoteServer"); //Clear the wifi localStorage.removeItem("usingServer"); //Init it localStorage.removeItem("defaultDir"); //Init it glbThis.checkWifi(function(err) { if(err) { //An error finding server - likely need to enter a pairing code. Warn the user glbThis.notify(err); } else { //Ready to take a picture, rerun glbThis.notify("Wifi paired successfully."); glbThis.bigButton(); } }); return; break; default: //Clicked on 'Cancel' break; } }, bigButton: function() { //Called when pushing the big button var _this = this; var foundRemoteServer = null; var foundWifiServer = null; foundRemoteServer = localStorage.getItem("currentRemoteServer"); foundWifiServer = localStorage.getItem("currentWifiServer"); if(((foundRemoteServer == null)||(foundRemoteServer == ""))&& ((foundWifiServer == null)||(foundWifiServer == ""))) { //Likely need to enter a pairing code. Warn the user //No current server - first time with this new connection //We have connected to a server OK navigator.notification.prompt( 'Please enter the 4 letter pairing code from your PC.', // message glbThis.connect, // callback to invoke 'New Connection', // title ['Ok','Use Wifi Only','Cancel'], // buttonLabels '' // defaultText ); } else { //Ready to take a picture _this.takePicture(); } }, checkWifi: function(cb) { glbThis.notify("Checking Wifi connection"); this.getip(function(ip, err) { if(err) { cb(err); return; } glbThis.notify("Scanning Wifi"); glbThis.scanlan('5566', function(url, err) { if(err) { cb(err); } else { cb(null); } }); }); }, getOptions: function(guid, cb) { //Input a server dir e.g. uPSE4UWHmJ8XqFUqvf // where the last part is the guid. //Get a URL like this: https://atomjump.com/med-settings.php?type=get&guid=uPSE4UWHmJ8XqFUqvf //to get a .json array of options. var settingsUrl = "https://atomjump.com/med-settings.php?type=get&guid=" + guid; glbThis.get(settingsUrl, function(url, resp) { if(resp != "") { var options = JSON.stringify(resp); //Or is it without the json parsing? if(options) { //Set local storage //localStorage.removeItem("serverOptions"); localStorage.setItem("serverOptions", options); cb(null); } else { cb("No options"); } } else { cb("No options"); } }); }, clearOptions: function() { localStorage.removeItem("serverOptions"); }, findServer: function(cb) { //Check storage for any saved current servers, and set the remote and wifi servers //along with splitting any subdirectories, ready for use by the the uploader. //Then actually try to connect - if wifi is an option, use that first var _this = this; var alreadyReturned = false; var found = false; //Clear off var foundRemoteServer = null; var foundWifiServer = null; var foundRemoteDir = null; var foundWifiDir = null; var usingServer = null; this.clearOptions(); //Early out usingServer = localStorage.getItem("usingServer"); if((usingServer)&&(usingServer != null)) { cb(null); return; } foundRemoteServer = localStorage.getItem("currentRemoteServer"); foundWifiServer = localStorage.getItem("currentWifiServer"); if((foundRemoteServer)&&(foundRemoteServer != null)&&(foundRemoteServer != "")) { //Already found a remote server //Generate the directory split, if any. Setting RAM foundServer and defaultDir var split = this.checkDefaultDir(foundRemoteServer); foundRemoteServer = split.server; foundRemoteDir = split.dir; } else { foundRemoteServer = null; foundRemoteDir = null; } //Check if we have a Wifi option if((foundWifiServer)&&(foundWifiServer != null)&&(foundWifiServer != "")) { //Already found wifi //Generate the directory split, if any. Setting RAM foundServer and defaultDir var split = this.checkDefaultDir(foundWifiServer); foundWifiServer = split.server; foundWifiDir = split.dir; } else { foundWifiServer = null; foundWifiDir = null; } //Early out: if((foundWifiServer == null)&&(foundRemoteServer == null)) { cb('No known server.'); return; } //Now try the wifi server as the first option to use if it exists: if((foundWifiServer)&&(foundWifiServer != null)&&(foundWifiServer != "null")) { //Ping the wifi server glbThis.notify('Trying to connect to the wifi server..'); //Timeout after 5 secs for the following ping var scanning = setTimeout(function() { glbThis.notify('Timeout finding your wifi server.</br>Trying remote server..'); //Else can't communicate with the wifi server at this time. //Try the remote server if((foundRemoteServer)&&(foundRemoteServer != null)&&(foundRemoteServer != "null")) { var scanningB = setTimeout(function() { //Timed out connecting to the remote server - that was the //last option. localStorage.removeItem("usingServer"); localStorage.removeItem("defaultDir"); localStorage.removeItem("serverRemote"); if(alreadyReturned == false) { alreadyReturned = true; cb('No server found'); } }, 6000); glbThis.get(foundRemoteServer, function(url, resp) { if(resp != "") { //Success, got a connection to the remote server clearTimeout(scanningB); //Ensure we don't error out localStorage.setItem("usingServer", foundRemoteServer); localStorage.setItem("serverRemote", 'true'); localStorage.setItem("defaultDir", foundRemoteDir); if(alreadyReturned == false) { alreadyReturned = true; //Get any global options glbThis.getOptions(foundRemoteDir); cb(null); } clearTimeout(scanning); //Ensure we don't error out } }); } else { //Only wifi existed localStorage.removeItem("usingServer"); localStorage.removeItem("defaultDir"); localStorage.removeItem("serverRemote"); if(alreadyReturned == false) { alreadyReturned = true; cb('No server found'); } } }, 2000); //Ping the wifi server glbThis.get(foundWifiServer, function(url, resp) { if(resp != "") { //Success, got a connection to the wifi clearTimeout(scanning); //Ensure we don't error out localStorage.setItem("usingServer", foundWifiServer); localStorage.setItem("defaultDir", foundWifiDir); localStorage.setItem("serverRemote", 'false'); if(alreadyReturned == false) { alreadyReturned = true; cb(null); //Success found server } } }); } else { //OK - no wifi option - go straight to the remote server //Try the remote server glbThis.notify('Trying to connect to the remote server....'); var scanning = setTimeout(function() { //Timed out connecting to the remote server - that was the //last option. localStorage.removeItem("usingServer"); localStorage.removeItem("defaultDir"); localStorage.removeItem("serverRemote"); if(alreadyReturned == false) { alreadyReturned = true; cb('No server found'); } }, 6000); _this.get(foundRemoteServer, function(url, resp) { if(resp != "") { //Success, got a connection to the remote server localStorage.setItem("usingServer", foundRemoteServer); localStorage.setItem("defaultDir", foundRemoteDir); localStorage.setItem("serverRemote", 'true'); if(alreadyReturned == false) { alreadyReturned = true; //Get any global options glbThis.getOptions(foundRemoteDir); cb(null); } clearTimeout(scanning); //Ensure we don't error out } }); } }, /* Settings Functions */ openSettings: function() { //Open the settings screen var html = this.listServers(); document.getElementById("settings").innerHTML = html; document.getElementById("settings-popup").style.display = "block"; }, closeSettings: function() { //Close the settings screen document.getElementById("settings-popup").style.display = "none"; }, listServers: function() { //List the available servers var settings = this.getArrayLocalStorage("settings"); if(settings) { var html = "<ons-list><ons-list-header>Select a PC to use now:</ons-list-header>"; //Convert the array into html for(var cnt=0; cnt< settings.length; cnt++) { html = html + "<ons-list-item><ons-list-item onclick='app.setServer(" + cnt + ");'>" + settings[cnt].name + "</ons-list-item><div class='right'><ons-icon icon='md-delete' onclick='app.deleteServer(" + cnt + ");'></ons-icon></div></ons-list-item>"; } html = html + "</ons-list>"; } else { var html = "<ons-list><ons-list-header>PCs Stored</ons-list-header>"; var html = html + "<ons-list-item><ons-list-item>Default</ons-list-item><div class='right'><ons-icon icon='md-delete'style='color:#AAA></ons-icon></div></ons-list-item>"; html = html + "</ons-list>"; } return html; }, setServer: function(serverId) { //Set the server to the input server id var settings = this.getArrayLocalStorage("settings"); var currentRemoteServer = settings[serverId].currentRemoteServer; var currentWifiServer = settings[serverId].currentWifiServer; localStorage.removeItem("usingServer"); //reset the currently used server //Save the current server localStorage.removeItem("defaultDir"); //Remove if one of these doesn't exist, and use the other. if((!currentWifiServer)||(currentWifiServer == null)||(currentWifiServer =="")) { localStorage.removeItem("currentWifiServer"); } else { localStorage.setItem("currentWifiServer", currentWifiServer); } if((!currentRemoteServer)||(currentRemoteServer == null)||(currentRemoteServer == "")) { localStorage.removeItem("currentRemoteServer"); } else { localStorage.setItem("currentRemoteServer", currentRemoteServer); } //Set the localstorage localStorage.setItem("currentServerName", settings[serverId].name); navigator.notification.alert("Switched to: " + settings[serverId].name, function() {}, "Changing PC"); //Now refresh the current server display document.getElementById("currentPC").innerHTML = settings[serverId].name; this.closeSettings(); return false; }, newServer: function() { //Create a new server. //This is actually effectively resetting, and we will allow the normal functions to input a new one localStorage.removeItem("usingServer"); //Remove the current one localStorage.removeItem("currentRemoteServer"); localStorage.removeItem("currentWifiServer"); this.notify("Tap above to activate."); //Clear off old notifications //Ask for a name of the current Server: navigator.notification.prompt( 'Please enter a name for this PC', // message this.saveServerName, // callback to invoke 'PC Name', // title ['Ok','Cancel'], // buttonLabels 'Main' // defaultText ); }, deleteServer: function(serverId) { //Delete an existing server this.myServerId = serverId; navigator.notification.confirm( 'Are you sure? This PC will be removed from memory.', // message function(buttonIndex) { if(buttonIndex == 1) { var settings = glbThis.getArrayLocalStorage("settings"); if((settings == null)|| (settings == '')) { //Nothing to delete } else { //Check if it is deleting the current entry var deleteName = settings[glbThis.myServerId].name; var currentServerName = localStorage.getItem("currentServerName"); if((currentServerName) && (deleteName) && (currentServerName == deleteName)) { //Now refresh the current server display document.getElementById("currentPC").innerHTML = ""; localStorage.removeItem("currentRemoteServer"); localStorage.removeItem("currentWifiServer"); localStorage.removeItem("currentServerName"); } settings.splice(glbThis.myServerId, 1); //Remove the entry entirely from array glbThis.setArrayLocalStorage("settings", settings); } glbThis.openSettings(); //refresh } }, // callback to invoke 'Remove PC', // title ['Ok','Cancel'] // buttonLabels ); }, saveServerName: function(results) { //Save the server with a name - but since this is new, //Get existing settings array if(results.buttonIndex == 1) { //Clicked on 'Ok' localStorage.setItem("currentServerName", results.input1); //Now refresh the current server display document.getElementById("currentPC").innerHTML = results.input1; glbThis.closeSettings(); return; } else { //Clicked on 'Exit'. Do nothing. return; } }, displayServerName: function() { //Call this during initialisation on app startup var currentServerName = localStorage.getItem("currentServerName"); if((currentServerName) && (currentServerName != null)) { //Now refresh the current server display document.getElementById("currentPC").innerHTML = currentServerName; } else { document.getElementById("currentPC").innerHTML = ""; } }, saveIdInput: function(status) { //Save the idInput. input true/false true = 'start with a hash' // false = 'start with blank' //Get existing settings array if(status == true) { //Show a hash by default localStorage.setItem("initialHash", "true"); } else { //Remove the hash by default localStorage.setItem("initialHash", "false"); } }, displayIdInput: function() { //Call this during initialisation on app startup var initialHash = localStorage.getItem("initialHash"); if((initialHash) && (initialHash != null)) { //Now refresh the current ID field if(initialHash == "true") { document.getElementById("always-create-folder").checked = true; } else { document.getElementById("always-create-folder").checked = false; } } }, saveServer: function() { //Run this after a successful upload var currentServerName = localStorage.getItem("currentServerName"); var currentRemoteServer = localStorage.getItem("currentRemoteServer"); var currentWifiServer = localStorage.getItem("currentWifiServer"); if((!currentServerName) ||(currentServerName == null)) currentServerName = "Default"; if((!currentRemoteServer) ||(currentRemoteServer == null)) currentRemoteServer = ""; if((!currentWifiServer) ||(currentWifiServer == null)) currentWifiServer = ""; var settings = glbThis.getArrayLocalStorage("settings"); //Create a new entry - which will be blank to being with var newSetting = { "name": currentServerName, //As input by the user "currentRemoteServer": currentRemoteServer, "currentWifiServer": currentWifiServer }; if((settings == null)|| (settings == '')) { //Creating an array for the first time var settings = []; settings.push(newSetting); //Save back to the array } else { //Check if we are writing over the existing entries var writeOver = false; for(cnt = 0; cnt< settings.length; cnt++) { if(settings[cnt].name == currentServerName) { writeOver = true; settings[cnt] = newSetting; } } if(writeOver == false) { settings.push(newSetting); //Save back to the array } } //Save back to the persistent settings glbThis.setArrayLocalStorage("settings", settings); return; }, //Array storage for app permanent settings (see http://inflagrantedelicto.memoryspiral.com/2013/05/phonegap-saving-arrays-in-local-storage/) setArrayLocalStorage: function(mykey, myobj) { return localStorage.setItem(mykey, JSON.stringify(myobj)); }, getArrayLocalStorage: function(mykey) { return JSON.parse(localStorage.getItem(mykey)); } };
handle already onserver case
www/js/index.js
handle already onserver case
<ide><path>ww/js/index.js <ide> "idEntered" : idEntered, <ide> "fileName" : fileName, <ide> "status" : "send" <del> }; //Status can be 'send', 'sent' (usually deleted from the array), or 'cancel' <add> }; //Status can be 'send', 'onserver', 'sent' (usually deleted from the array), or 'cancel' <ide> localPhotos.push(newPhoto); <ide> glbThis.setArrayLocalStorage("localPhotos", localPhotos); <ide> return true; <ide> }, <ide> <del> changeLocalPhotoStatus: function(imageURI, newStatus) { <add> changeLocalPhotoStatus: function(imageURI, newStatus, fullData) { <add> //Input: <add> //imageURI - unique image address on phone filesystem <add> //newStatus can be 'send', 'onserver', 'sent' (usually deleted from the array), or 'cancel' <add> //If onserver, the optional parameter 'fullGet', is the URL to call to check if the file is back on the server <add> <add> <ide> var localPhotos = glbThis.getArrayLocalStorage("localPhotos"); <ide> if(!localPhotos) { <ide> localPhotos = []; <ide> } else { <ide> localPhotos[cnt].status = newStatus; <ide> <add> if((newStatus == "onserver")&&(fullData)) { <add> localPhotos[cnt].fullData = JSON.stringify(fullData); //Create a copy of the JSON data array in string format <add> <add> } <add> <ide> //Set back the storage of the array <ide> glbThis.setArrayLocalStorage("localPhotos", localPhotos); <ide> } <ide> //Get a photo, one at a time, in the array format: <ide> /* { <ide> "imageURI" : imageURI, <del> "idEntered" : idEntered <del> "fileName" : fileName <add> "idEntered" : idEntered, <add> "fileName" : fileName, <add> "fullData" : fullDataObject stringified - optional <ide> "status" : "send" <del> }; //Status can be 'send', 'sent' (usually deleted from the array), or 'cancel' <add> }; //Status can be 'send', 'onserver', 'sent' (usually deleted from the array), or 'cancel' <ide> <ide> and attempt to upload them. <ide> */ <ide> for(var cnt = 0; cnt< localPhotos.length; cnt++) { <ide> var newPhoto = localPhotos[cnt]; <ide> if(newPhoto) { <del> glbThis.uploadPhoto(newPhoto.imageURI, newPhoto.idEntered, newPhoto.fileName); <add> <add> if(newPhoto.status == 'onserver') { <add> //OK - so it was successfully put onto the server. Recheck to see if it needs to be uploaded again <add> if(newPhoto.fullData) { <add> <add> try { <add> var fullData = JSON.parse(newPhoto); <add> <add> checkComplete.push(nowChecking); <add> glbThis.check(); //This will only upload again if it finds it hasn't been transferred off the <add> //server <add> } catch(err) { <add> //There was a problem parsing the data. Resends the whole photo, just in case <add> glbThis.uploadPhoto(newPhoto.imageURI, newPhoto.idEntered, newPhoto.fileName); <add> <add> } <add> } else { <add> //No fullData was added - resend anyway <add> glbThis.uploadPhoto(newPhoto.imageURI, newPhoto.idEntered, newPhoto.fileName); <add> <add> } <add> <add> <add> } else { <add> //Needs to be resent <add> glbThis.uploadPhoto(newPhoto.imageURI, newPhoto.idEntered, newPhoto.fileName); <add> } <ide> } <ide> } <ide> <ide> options.mimeType="image/jpeg"; <ide> <ide> var params = new Object(); <del> params.title = idEntered; //OLD: document.getElementById("id-entered").value; <add> params.title = idEntered; <ide> if((params.title == '')||(params.title == null)) { <ide> if((idEnteredB == '')||(idEnteredB == null)) { <ide> params.title = 'image'; <ide> <ide> <ide> check: function(){ <add> //Checks to see if the next photo on the server (in the checkComplete stack) has been sent on to the PC successfully. If not it will keep pinging until is has been dealt with, or it times out. <add> <ide> var nowChecking = checkComplete.pop(); <ide> nowChecking.loopCnt --; <ide> <ide> <ide> win: function(r) { <ide> <add> //Have finished transferring the file to the server <ide> window.plugins.insomnia.allowSleepAgain(); //Allow sleeping again <ide> <ide> document.querySelector('#status').innerHTML = ""; //Clear progress status <ide> //Onto remote server - now do some pings to check we have got to the PC <ide> document.getElementById("notify").innerHTML = 'Image on server. Transferring to PC..'; <ide> <add> <ide> var repeatIfNeeded = retryIfNeeded.pop(); <add> <add> <ide> <ide> <ide> if(repeatIfNeeded) { <ide> nowChecking.fullGet = fullGet; <ide> nowChecking.details = repeatIfNeeded; <ide> checkComplete.push(nowChecking); <add> <add> //Set an 'onserver' status <add> glbThis.changeLocalPhotoStatus(repeatIfNeeded.imageURI, 'onserver', nowChecking); <ide> <ide> setTimeout(function() { //Wait two seconds and then do a check <ide> glbThis.check();
Java
apache-2.0
7573f045e855d7932aeb1118118162cb01e7c3e8
0
McLeodMoores/starling,ChinaQuants/OG-Platform,codeaudit/OG-Platform,jerome79/OG-Platform,nssales/OG-Platform,codeaudit/OG-Platform,jerome79/OG-Platform,DevStreet/FinanceAnalytics,jerome79/OG-Platform,jeorme/OG-Platform,jeorme/OG-Platform,jeorme/OG-Platform,jeorme/OG-Platform,codeaudit/OG-Platform,McLeodMoores/starling,ChinaQuants/OG-Platform,jerome79/OG-Platform,ChinaQuants/OG-Platform,nssales/OG-Platform,DevStreet/FinanceAnalytics,DevStreet/FinanceAnalytics,nssales/OG-Platform,DevStreet/FinanceAnalytics,codeaudit/OG-Platform,ChinaQuants/OG-Platform,nssales/OG-Platform,McLeodMoores/starling,McLeodMoores/starling
/** * Copyright (C) 2012 - present by OpenGamma Inc. and the OpenGamma group of companies * * Please see distribution for license. */ package com.opengamma.master.cache; import java.util.Collections; import java.util.LinkedList; import java.util.List; import java.util.Map; import java.util.concurrent.ConcurrentNavigableMap; import java.util.concurrent.ConcurrentSkipListMap; import java.util.concurrent.ExecutorService; import org.joda.beans.Bean; import org.joda.beans.JodaBeanUtils; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import com.opengamma.OpenGammaRuntimeException; import com.opengamma.id.UniqueId; import com.opengamma.id.UniqueIdentifiable; import com.opengamma.master.AbstractDocument; import com.opengamma.util.ArgumentChecker; import com.opengamma.util.ExecutorServiceFactoryBean; import com.opengamma.util.paging.PagingRequest; import com.opengamma.util.tuple.ObjectsPair; import net.sf.ehcache.Cache; import net.sf.ehcache.CacheManager; import net.sf.ehcache.Ehcache; import net.sf.ehcache.Element; import net.sf.ehcache.config.CacheConfiguration; /** * A cache for search results, providing common search caching logic across caching masters and across search types. * * <p> * The cache is implemented using {@code EHCache}. * * TODO externalise configuration in xml file * TODO set aggressive expiry for cached searches * TODO investigate possibility of using SelfPopulatingCache for the search cache too * TODO eliminate/minimise duplicate caching of similar searches (e.g. history searches with different date ranges) * TODO OPTIMIZE finer grain range locking * TODO OPTIMIZE cache replacement policy/handling huge requests that would flush out entire content * TODO OPTIMIZE underlying search request coalescing */ public class EHCachingSearchCache { /** Logger. */ private static final Logger s_logger = LoggerFactory.getLogger(EHCachingSearchCache.class); /** The number of units to prefetch on either side of the current paging request */ protected static final int PREFETCH_RADIUS = 2; /** The size of a prefetch unit */ protected static final int PREFETCH_GRANULARITY = 100; /** The maximum number of concurrent prefetch operations */ protected static final int MAX_PREFETCH_CONCURRENCY = 4; /** Cache name. */ private static final String CACHE_NAME_SUFFIX = "PagedSearchCache"; /** Check cached results against results from underlying */ public static final boolean TEST_AGAINST_UNDERLYING = false; //s_logger.isDebugEnabled(); /** The cache manager */ private final CacheManager _cacheManager; /** * The UniqueId cache indexed by search requests. * A cache entry contains unpaged (total) result size and a map from start indices to ranges of cached result UniqueIds */ private final Cache _searchRequestCache; /** The prefetch thread executor service */ private final ExecutorService _executorService; /** The searcher provides access to a master-specific search operation */ private final Searcher _searcher; /** * A cache searcher, used by the search cache to pass search requests to an underlying master without * knowing its type and retrieve the result unique Ids without knowing the document type. */ public interface Searcher { /** Searches an underlying master, casting search requests/results as required for a specific master * @param request The search request, without paging (will be cast to a search request for a specific master) * @param pagingRequest the paging request * @return The search result */ ObjectsPair<Integer, List<UniqueId>> search(Bean request, PagingRequest pagingRequest); } /** * Create a new search cache. * * @param name A unique name for this cache, not empty * @param cacheManager The cache manager to use, not null * @param searcher The CacheSearcher to use for passing search requests to an underlying master, not null */ public EHCachingSearchCache(String name, CacheManager cacheManager, Searcher searcher) { ArgumentChecker.notNull(cacheManager, "cacheManager"); ArgumentChecker.notEmpty(name, "name"); ArgumentChecker.notNull(searcher, "searcher"); _cacheManager = cacheManager; _searcher = searcher; // Configure cache - this should probably be in an xml config CacheConfiguration cacheConfiguration = new CacheConfiguration(name + CACHE_NAME_SUFFIX, 1000); // Make copies of cached objects (use default Serializable copy) cacheConfiguration.setCopyOnRead(true); cacheConfiguration.setCopyOnWrite(true); // Set short expiry time, since search result change management is not yet available cacheConfiguration.setTimeToLiveSeconds(5 * 60); // Generate statistics cacheConfiguration.setStatistics(true); _searchRequestCache = new Cache(cacheConfiguration); cacheManager.addCache(_searchRequestCache); // Async prefetch executor service ExecutorServiceFactoryBean execBean = new ExecutorServiceFactoryBean(); execBean.setNumberOfThreads(MAX_PREFETCH_CONCURRENCY); execBean.setStyle(ExecutorServiceFactoryBean.Style.CACHED); _executorService = execBean.getObjectCreating(); } /** * If result is entirely cached return it immediately; otherwise, fetch any missing ranges from the underlying * master in the foreground, cache and return it. * * @param requestBean the search request, without paging * @param pagingRequest the paging request * @param blockUntilCached if true, block the request until all caching, including related prefetching, is done * @return the total number of results (ignoring paging), and the unique IDs of the requested result page */ public ObjectsPair<Integer, List<UniqueId>> search(final Bean requestBean, PagingRequest pagingRequest, boolean blockUntilCached) { ArgumentChecker.notNull(requestBean, "requestBean"); ArgumentChecker.notNull(pagingRequest, "pagingRequest"); // Fetch the total #results and cached ranges for the search request (without paging) final ObjectsPair<Integer, ConcurrentNavigableMap<Integer, List<UniqueId>>> info = getCachedRequestInfo(requestBean, pagingRequest); final int totalResults = info.getFirst(); final ConcurrentNavigableMap<Integer, List<UniqueId>> rangeMap = info.getSecond(); // Fix indexes larger than the total doc count if (pagingRequest.getFirstItem() >= totalResults) { pagingRequest = PagingRequest.ofIndex(totalResults, 0); } else if (pagingRequest.getLastItem() >= totalResults) { pagingRequest = PagingRequest.ofIndex(pagingRequest.getFirstItem(), totalResults - pagingRequest.getFirstItem()); } // Ensure that the required range is cached in its entirety ObjectsPair<Integer, List<UniqueId>> pair = cacheSuperRange(requestBean, pagingRequest, rangeMap, totalResults, blockUntilCached); final int superIndex = pair.getFirst(); final List<UniqueId> superRange = pair.getSecond(); // Create and return the search result final List<UniqueId> resultUniqueIds = superRange.subList( pagingRequest.getFirstItem() - superIndex, Math.min(pagingRequest.getLastItem() - superIndex, superRange.size())); return new ObjectsPair<>(totalResults, resultUniqueIds); } /** * Calculate the range that should be prefetched for the supplied request and initiate the fetching of any uncached * ranges from the underlying master in the background, without blocking. * * @param requestBean the search request, without paging * @param pagingRequest the paging request */ public void prefetch(final Bean requestBean, PagingRequest pagingRequest) { // Build larger range to prefetch final int start = (pagingRequest.getFirstItem() / PREFETCH_GRANULARITY >= PREFETCH_RADIUS) ? ((pagingRequest.getFirstItem() / PREFETCH_GRANULARITY) * PREFETCH_GRANULARITY) - (PREFETCH_RADIUS * PREFETCH_GRANULARITY) : 0; final int end = (pagingRequest.getLastItem() < Integer.MAX_VALUE - (PREFETCH_RADIUS * PREFETCH_GRANULARITY)) ? ((pagingRequest.getLastItem() / PREFETCH_GRANULARITY) * PREFETCH_GRANULARITY) + (PREFETCH_RADIUS * PREFETCH_GRANULARITY) : Integer.MAX_VALUE; final PagingRequest superPagingRequest = PagingRequest.ofIndex(start, end - start); // Submit search task to background executor getExecutorService().submit(new Runnable() { @Override public void run() { search(requestBean, superPagingRequest, true); // block until cached } }); } //------------------------------------------------------------------------- /** * Retrieve from cache the total #results and the cached ranges for the supplied search request (without * taking into account its paging request). If an cached entry is not found for the unpaged search request, then * create one, populate it with the results of the supplied paged search request, and return it. * * @param requestBean the search request, without paging * @param pagingRequest the paging request * @return the total result count and a range map of cached UniqueIds for the supplied search request without * paging */ private ObjectsPair<Integer, ConcurrentNavigableMap<Integer, List<UniqueId>>> getCachedRequestInfo(final Bean requestBean, PagingRequest pagingRequest) { // Get cache entry for current request (or create and get a primed cache entry if not found) // TODO investigate atomicity final Element element = getCache().get(withPagingRequest(requestBean, null)); if (element != null) { return (ObjectsPair<Integer, ConcurrentNavigableMap<Integer, List<UniqueId>>>) element.getObjectValue(); } else { // Build a new cached map entry and pre-fill it with the results of the supplied search request final ObjectsPair<Integer, List<UniqueId>> resultToCache = getSearcher().search(requestBean, pagingRequest); final ConcurrentNavigableMap<Integer, List<UniqueId>> rangeMapToCache = new ConcurrentSkipListMap<>(); // Cache UniqueIds in search cache rangeMapToCache.put(pagingRequest.getFirstItem(), resultToCache.getSecond()); final ObjectsPair<Integer, ConcurrentNavigableMap<Integer, List<UniqueId>>> newResult = new ObjectsPair<>(resultToCache.getFirst(), rangeMapToCache); getCache().put(new Element(withPagingRequest(requestBean, null), newResult)); return newResult; } } /** * Fill in any uncached gaps for the requested range from the underlying, creating a single cached 'super range' from * which the entire current search request can be satisfied. This method may be called concurrently in multiple * threads. * * @param requestBean the search request, without paging * @param pagingRequest the paging request * @param rangeMap the range map of cached UniqueIds for the supplied search request without paging * @param totalResults the total number of results without paging * @return a super-range of cached UniqueIds that contains at least the requested UniqueIds */ private ObjectsPair<Integer, List<UniqueId>> cacheSuperRange(final Bean requestBean, PagingRequest pagingRequest, final ConcurrentNavigableMap<Integer, List<UniqueId>> rangeMap, int totalResults, boolean blockUntilCached) { final int startIndex = pagingRequest.getFirstItem(); final int endIndex = pagingRequest.getLastItem(); final List<UniqueId> superRange; final int superIndex; if (blockUntilCached) { synchronized (rangeMap) { // Determine the super range's start index if (rangeMap.floorKey(startIndex) != null && rangeMap.floorKey(startIndex) + rangeMap.floorEntry(startIndex).getValue().size() >= startIndex) { superRange = rangeMap.floorEntry(startIndex).getValue(); superIndex = rangeMap.floorKey(startIndex); } else { superRange = Collections.synchronizedList(new LinkedList<UniqueId>()); superIndex = startIndex; rangeMap.put(superIndex, superRange); } // Get map subset from closest start index above requested start index, to closest start index below requested // end index final Integer start = rangeMap.ceilingKey(startIndex + 1); final Integer end = rangeMap.floorKey(endIndex); final ConcurrentNavigableMap<Integer, List<UniqueId>> subMap = (ConcurrentNavigableMap<Integer, List<UniqueId>>) ( ((start != null) && (end != null) && (start <= end)) ? rangeMap.subMap(start, true, end, true) : new ConcurrentSkipListMap<>() ); // Iterate through ranges within the paging request range, concatenating them into the super range while // filling in any gaps from the underlying master int currentIndex = superIndex + superRange.size(); final List<Integer> toRemove = new LinkedList<>(); for (Map.Entry<Integer, List<UniqueId>> entry : subMap.entrySet()) { // If required, fill gap from underlying if (entry.getKey() > currentIndex) { List<UniqueId> missingResult = getSearcher().search(requestBean, PagingRequest.ofIndex(currentIndex, entry.getKey() - currentIndex)).getSecond(); // Cache UniqueIds in search cache superRange.addAll(missingResult); currentIndex += missingResult.size(); } // Add next cached range superRange.addAll(entry.getValue()); currentIndex += entry.getValue().size(); toRemove.add(entry.getKey()); } // Remove original cached ranges (now part of the super range) for (Integer i : toRemove) { rangeMap.remove(i); } // If required, fill in the final range from underlying if (currentIndex < endIndex) { final List<UniqueId> missingResult = getSearcher().search(requestBean, PagingRequest.ofIndex(currentIndex,endIndex - currentIndex)).getSecond(); // Cache UniqueIds in search cache superRange.addAll(missingResult); currentIndex += missingResult.size(); } // put expanded super range into range map rangeMap.put(superIndex, superRange); final ObjectsPair<Integer, ConcurrentNavigableMap<Integer, List<UniqueId>>> newValue = new ObjectsPair<>(totalResults, rangeMap); getCache().put(new Element(withPagingRequest(requestBean, null), newValue)); } } else { // If entirely cached then return cached values if (rangeMap.floorKey(startIndex) != null && rangeMap.floorKey(startIndex) + rangeMap.floorEntry(startIndex).getValue().size() >= endIndex) { superRange = rangeMap.floorEntry(startIndex).getValue(); superIndex = rangeMap.floorKey(startIndex); // If not entirely cached then just fetch from underlying without caching } else { final List<UniqueId> missingResult = getSearcher().search(requestBean, pagingRequest).getSecond(); superRange = Collections.synchronizedList(new LinkedList<UniqueId>()); // Cache UniqueIds in search cache superRange.addAll(missingResult); superIndex = startIndex; } } return new ObjectsPair<>(superIndex, superRange); } //------------------------------------------------------------------------- /** * Extract a list of unique Ids from a list of uniqueIdentifiable objects * * @param uniqueIdentifiables The uniquely identifiable objects * @return a list of unique Ids */ public static List<UniqueId> extractUniqueIds(List<? extends UniqueIdentifiable> uniqueIdentifiables) { List<UniqueId> result = new LinkedList<>(); for (UniqueIdentifiable uniqueIdentifiable : uniqueIdentifiables) { result.add(uniqueIdentifiable.getUniqueId()); } return result; } /** * Insert documents in the specified document cache * * @param documents The list of documents to be inserted * @param documentCache The document cache in which to insert the documents */ public static void cacheDocuments(List<? extends AbstractDocument> documents, Ehcache documentCache) { for (AbstractDocument document : documents) { documentCache.put(new Element(document.getUniqueId(), document)); } } /** * Return a clone of the supplied search request, but with its paging request replaced * * @param requestBean the search request whose paging request to replace (currently a doc or history search request) * @param pagingRequest the paging request, null allowed * @return a clone of the supplied search request, with its paging request replaced */ public static Bean withPagingRequest(final Bean requestBean, final PagingRequest pagingRequest) { if (requestBean.propertyNames().contains("pagingRequest")) { final Bean newRequest = JodaBeanUtils.clone(requestBean); if (pagingRequest != null) { newRequest.property("pagingRequest").set( PagingRequest.ofIndex(pagingRequest.getFirstItem(), pagingRequest.getPagingSize())); } else { newRequest.property("pagingRequest").set(null); } return newRequest; } else { throw new OpenGammaRuntimeException( "Could not invoke setPagingRequest() on request object of type " + requestBean.getClass()); } } /** * Call this at the end of a unit test run to clear the state of EHCache. * It should not be part of a generic lifecycle method. */ public void shutdown() { // No change management for searches... yet //getUnderlying().changeManager().removeChangeListener(_changeListener); getCacheManager().removeCache(getCache().getName()); } /** * Gets the cache searcher * * @return the cache searcher instance */ public Searcher getSearcher() { return _searcher; } /** * Gets the cache * * @return the cache instance */ public Ehcache getCache() { return _searchRequestCache; } /** * Gets the cache manager * * @return the cache manager instance */ public CacheManager getCacheManager() { return _cacheManager; } /** * Gets the executor service used for prefetching * * @return the executor service instance */ public ExecutorService getExecutorService() { return _executorService; } }
projects/OG-Master/src/main/java/com/opengamma/master/cache/EHCachingSearchCache.java
/** * Copyright (C) 2012 - present by OpenGamma Inc. and the OpenGamma group of companies * * Please see distribution for license. */ package com.opengamma.master.cache; import java.util.Collections; import java.util.LinkedList; import java.util.List; import java.util.Map; import java.util.concurrent.ConcurrentNavigableMap; import java.util.concurrent.ConcurrentSkipListMap; import java.util.concurrent.ExecutorService; import org.joda.beans.Bean; import org.joda.beans.JodaBeanUtils; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import com.opengamma.OpenGammaRuntimeException; import com.opengamma.id.UniqueId; import com.opengamma.id.UniqueIdentifiable; import com.opengamma.master.AbstractDocument; import com.opengamma.util.ArgumentChecker; import com.opengamma.util.ExecutorServiceFactoryBean; import com.opengamma.util.paging.PagingRequest; import com.opengamma.util.tuple.ObjectsPair; import net.sf.ehcache.Cache; import net.sf.ehcache.CacheManager; import net.sf.ehcache.Ehcache; import net.sf.ehcache.Element; import net.sf.ehcache.config.CacheConfiguration; /** * A cache for search results, providing common search caching logic across caching masters and across search types. * * <p> * The cache is implemented using {@code EHCache}. * * TODO externalise configuration in xml file * TODO set aggressive expiry for cached searches * TODO investigate possibility of using SelfPopulatingCache for the search cache too * TODO eliminate/minimise duplicate caching of similar searches (e.g. history searches with different date ranges) * TODO OPTIMIZE finer grain range locking * TODO OPTIMIZE cache replacement policy/handling huge requests that would flush out entire content * TODO OPTIMIZE underlying search request coalescing */ public class EHCachingSearchCache { /** Logger. */ private static final Logger s_logger = LoggerFactory.getLogger(EHCachingSearchCache.class); /** The number of units to prefetch on either side of the current paging request */ protected static final int PREFETCH_RADIUS = 2; /** The size of a prefetch unit */ protected static final int PREFETCH_GRANULARITY = 100; /** The maximum number of concurrent prefetch operations */ protected static final int MAX_PREFETCH_CONCURRENCY = 4; /** Cache name. */ private static final String CACHE_NAME_SUFFIX = "PagedSearchCache"; /** Check cached results against results from underlying */ public static final boolean TEST_AGAINST_UNDERLYING = false; //s_logger.isDebugEnabled(); /** The cache manager */ private final CacheManager _cacheManager; /** * The UniqueId cache indexed by search requests. * A cache entry contains unpaged (total) result size and a map from start indices to ranges of cached result UniqueIds */ private final Cache _searchRequestCache; /** The prefetch thread executor service */ private final ExecutorService _executorService; /** The searcher provides access to a master-specific search operation */ private final Searcher _searcher; /** * A cache searcher, used by the search cache to pass search requests to an underlying master without * knowing its type and retrieve the result unique Ids without knowing the document type. */ public interface Searcher { /** Searches an underlying master, casting search requests/results as required for a specific master * @param request The search request, without paging (will be cast to a search request for a specific master) * @param pagingRequest the paging request * @return The search result */ ObjectsPair<Integer, List<UniqueId>> search(Bean request, PagingRequest pagingRequest); } /** * Create a new search cache. * * @param name A unique name for this cache, not empty * @param cacheManager The cache manager to use, not null * @param searcher The CacheSearcher to use for passing search requests to an underlying master, not null */ public EHCachingSearchCache(String name, CacheManager cacheManager, Searcher searcher) { ArgumentChecker.notNull(cacheManager, "cacheManager"); ArgumentChecker.notEmpty(name, "name"); ArgumentChecker.notNull(searcher, "searcher"); _cacheManager = cacheManager; _searcher = searcher; // Configure cache - this should probably be in an xml config CacheConfiguration cacheConfiguration = new CacheConfiguration(name + CACHE_NAME_SUFFIX, 1000); // Make copies of cached objects (use default Serializable copy) cacheConfiguration.setCopyOnRead(true); cacheConfiguration.setCopyOnWrite(true); // Set short expiry time, since search result change management is not yet available cacheConfiguration.setTimeToLiveSeconds(5 * 60); // Generate statistics cacheConfiguration.setStatistics(true); _searchRequestCache = new Cache(cacheConfiguration); cacheManager.addCache(_searchRequestCache); // Async prefetch executor service ExecutorServiceFactoryBean execBean = new ExecutorServiceFactoryBean(); execBean.setNumberOfThreads(MAX_PREFETCH_CONCURRENCY); execBean.setStyle(ExecutorServiceFactoryBean.Style.CACHED); _executorService = execBean.getObjectCreating(); } /** * If result is entirely cached return it immediately; otherwise, fetch any missing ranges from the underlying * master in the foreground, cache and return it. * * @param requestBean the search request, without paging * @param pagingRequest the paging request * @param blockUntilCached if true, block the request until all caching, including related prefetching, is done * @return the total number of results (ignoring paging), and the unique IDs of the requested result page */ public ObjectsPair<Integer, List<UniqueId>> search(final Bean requestBean, PagingRequest pagingRequest, boolean blockUntilCached) { ArgumentChecker.notNull(requestBean, "requestBean"); ArgumentChecker.notNull(pagingRequest, "pagingRequest"); // Fetch the total #results and cached ranges for the search request (without paging) final ObjectsPair<Integer, ConcurrentNavigableMap<Integer, List<UniqueId>>> info = getCachedRequestInfo(requestBean, pagingRequest); final int totalResults = info.getFirst(); final ConcurrentNavigableMap<Integer, List<UniqueId>> rangeMap = info.getSecond(); // Fix unpaged requests and end indexes larger than the total doc count if (pagingRequest.getLastItem() >= totalResults) { pagingRequest = PagingRequest.ofIndex(pagingRequest.getFirstItem(), totalResults - pagingRequest.getFirstItem()); } // Ensure that the required range is cached in its entirety ObjectsPair<Integer, List<UniqueId>> pair = cacheSuperRange(requestBean, pagingRequest, rangeMap, totalResults, blockUntilCached); final int superIndex = pair.getFirst(); final List<UniqueId> superRange = pair.getSecond(); // Create and return the search result final List<UniqueId> resultUniqueIds = superRange.subList( pagingRequest.getFirstItem() - superIndex, Math.min(pagingRequest.getLastItem() - superIndex, superRange.size())); return new ObjectsPair<>(totalResults, resultUniqueIds); } /** * Calculate the range that should be prefetched for the supplied request and initiate the fetching of any uncached * ranges from the underlying master in the background, without blocking. * * @param requestBean the search request, without paging * @param pagingRequest the paging request */ public void prefetch(final Bean requestBean, PagingRequest pagingRequest) { // Build larger range to prefetch final int start = (pagingRequest.getFirstItem() / PREFETCH_GRANULARITY >= PREFETCH_RADIUS) ? ((pagingRequest.getFirstItem() / PREFETCH_GRANULARITY) * PREFETCH_GRANULARITY) - (PREFETCH_RADIUS * PREFETCH_GRANULARITY) : 0; final int end = (pagingRequest.getLastItem() < Integer.MAX_VALUE - (PREFETCH_RADIUS * PREFETCH_GRANULARITY)) ? ((pagingRequest.getLastItem() / PREFETCH_GRANULARITY) * PREFETCH_GRANULARITY) + (PREFETCH_RADIUS * PREFETCH_GRANULARITY) : Integer.MAX_VALUE; final PagingRequest superPagingRequest = PagingRequest.ofIndex(start, end - start); // Submit search task to background executor getExecutorService().submit(new Runnable() { @Override public void run() { search(requestBean, superPagingRequest, true); // block until cached } }); } //------------------------------------------------------------------------- /** * Retrieve from cache the total #results and the cached ranges for the supplied search request (without * taking into account its paging request). If an cached entry is not found for the unpaged search request, then * create one, populate it with the results of the supplied paged search request, and return it. * * @param requestBean the search request, without paging * @param pagingRequest the paging request * @return the total result count and a range map of cached UniqueIds for the supplied search request without * paging */ private ObjectsPair<Integer, ConcurrentNavigableMap<Integer, List<UniqueId>>> getCachedRequestInfo(final Bean requestBean, PagingRequest pagingRequest) { // Get cache entry for current request (or create and get a primed cache entry if not found) // TODO investigate atomicity final Element element = getCache().get(withPagingRequest(requestBean, null)); if (element != null) { return (ObjectsPair<Integer, ConcurrentNavigableMap<Integer, List<UniqueId>>>) element.getObjectValue(); } else { // Build a new cached map entry and pre-fill it with the results of the supplied search request final ObjectsPair<Integer, List<UniqueId>> resultToCache = getSearcher().search(requestBean, pagingRequest); final ConcurrentNavigableMap<Integer, List<UniqueId>> rangeMapToCache = new ConcurrentSkipListMap<>(); // Cache UniqueIds in search cache rangeMapToCache.put(pagingRequest.getFirstItem(), resultToCache.getSecond()); final ObjectsPair<Integer, ConcurrentNavigableMap<Integer, List<UniqueId>>> newResult = new ObjectsPair<>(resultToCache.getFirst(), rangeMapToCache); getCache().put(new Element(withPagingRequest(requestBean, null), newResult)); return newResult; } } /** * Fill in any uncached gaps for the requested range from the underlying, creating a single cached 'super range' from * which the entire current search request can be satisfied. This method may be called concurrently in multiple * threads. * * @param requestBean the search request, without paging * @param pagingRequest the paging request * @param rangeMap the range map of cached UniqueIds for the supplied search request without paging * @param totalResults the total number of results without paging * @return a super-range of cached UniqueIds that contains at least the requested UniqueIds */ private ObjectsPair<Integer, List<UniqueId>> cacheSuperRange(final Bean requestBean, PagingRequest pagingRequest, final ConcurrentNavigableMap<Integer, List<UniqueId>> rangeMap, int totalResults, boolean blockUntilCached) { final int startIndex = pagingRequest.getFirstItem(); final int endIndex = pagingRequest.getLastItem(); final List<UniqueId> superRange; final int superIndex; if (blockUntilCached) { synchronized (rangeMap) { // Determine the super range's start index if (rangeMap.floorKey(startIndex) != null && rangeMap.floorKey(startIndex) + rangeMap.floorEntry(startIndex).getValue().size() >= startIndex) { superRange = rangeMap.floorEntry(startIndex).getValue(); superIndex = rangeMap.floorKey(startIndex); } else { superRange = Collections.synchronizedList(new LinkedList<UniqueId>()); superIndex = startIndex; rangeMap.put(superIndex, superRange); } // Get map subset from closest start index above requested start index, to closest start index below requested // end index final Integer start = rangeMap.ceilingKey(startIndex + 1); final Integer end = rangeMap.floorKey(endIndex); final ConcurrentNavigableMap<Integer, List<UniqueId>> subMap = (ConcurrentNavigableMap<Integer, List<UniqueId>>) ( ((start != null) && (end != null) && (start <= end)) ? rangeMap.subMap(start, true, end, true) : new ConcurrentSkipListMap<>() ); // Iterate through ranges within the paging request range, concatenating them into the super range while // filling in any gaps from the underlying master int currentIndex = superIndex + superRange.size(); final List<Integer> toRemove = new LinkedList<>(); for (Map.Entry<Integer, List<UniqueId>> entry : subMap.entrySet()) { // If required, fill gap from underlying if (entry.getKey() > currentIndex) { List<UniqueId> missingResult = getSearcher().search(requestBean, PagingRequest.ofIndex(currentIndex, entry.getKey() - currentIndex)).getSecond(); // Cache UniqueIds in search cache superRange.addAll(missingResult); currentIndex += missingResult.size(); } // Add next cached range superRange.addAll(entry.getValue()); currentIndex += entry.getValue().size(); toRemove.add(entry.getKey()); } // Remove original cached ranges (now part of the super range) for (Integer i : toRemove) { rangeMap.remove(i); } // If required, fill in the final range from underlying if (currentIndex < endIndex) { final List<UniqueId> missingResult = getSearcher().search(requestBean, PagingRequest.ofIndex(currentIndex,endIndex - currentIndex)).getSecond(); // Cache UniqueIds in search cache superRange.addAll(missingResult); currentIndex += missingResult.size(); } // put expanded super range into range map rangeMap.put(superIndex, superRange); final ObjectsPair<Integer, ConcurrentNavigableMap<Integer, List<UniqueId>>> newValue = new ObjectsPair<>(totalResults, rangeMap); getCache().put(new Element(withPagingRequest(requestBean, null), newValue)); } } else { // If entirely cached then return cached values if (rangeMap.floorKey(startIndex) != null && rangeMap.floorKey(startIndex) + rangeMap.floorEntry(startIndex).getValue().size() >= endIndex) { superRange = rangeMap.floorEntry(startIndex).getValue(); superIndex = rangeMap.floorKey(startIndex); // If not entirely cached then just fetch from underlying without caching } else { final List<UniqueId> missingResult = getSearcher().search(requestBean, pagingRequest).getSecond(); superRange = Collections.synchronizedList(new LinkedList<UniqueId>()); // Cache UniqueIds in search cache superRange.addAll(missingResult); superIndex = startIndex; } } return new ObjectsPair<>(superIndex, superRange); } //------------------------------------------------------------------------- /** * Extract a list of unique Ids from a list of uniqueIdentifiable objects * * @param uniqueIdentifiables The uniquely identifiable objects * @return a list of unique Ids */ public static List<UniqueId> extractUniqueIds(List<? extends UniqueIdentifiable> uniqueIdentifiables) { List<UniqueId> result = new LinkedList<>(); for (UniqueIdentifiable uniqueIdentifiable : uniqueIdentifiables) { result.add(uniqueIdentifiable.getUniqueId()); } return result; } /** * Insert documents in the specified document cache * * @param documents The list of documents to be inserted * @param documentCache The document cache in which to insert the documents */ public static void cacheDocuments(List<? extends AbstractDocument> documents, Ehcache documentCache) { for (AbstractDocument document : documents) { documentCache.put(new Element(document.getUniqueId(), document)); } } /** * Return a clone of the supplied search request, but with its paging request replaced * * @param requestBean the search request whose paging request to replace (currently a doc or history search request) * @param pagingRequest the paging request, null allowed * @return a clone of the supplied search request, with its paging request replaced */ public static Bean withPagingRequest(final Bean requestBean, final PagingRequest pagingRequest) { if (requestBean.propertyNames().contains("pagingRequest")) { final Bean newRequest = JodaBeanUtils.clone(requestBean); if (pagingRequest != null) { newRequest.property("pagingRequest").set( PagingRequest.ofIndex(pagingRequest.getFirstItem(), pagingRequest.getPagingSize())); } else { newRequest.property("pagingRequest").set(null); } return newRequest; } else { throw new OpenGammaRuntimeException( "Could not invoke setPagingRequest() on request object of type " + requestBean.getClass()); } } /** * Call this at the end of a unit test run to clear the state of EHCache. * It should not be part of a generic lifecycle method. */ public void shutdown() { // No change management for searches... yet //getUnderlying().changeManager().removeChangeListener(_changeListener); getCacheManager().removeCache(getCache().getName()); } /** * Gets the cache searcher * * @return the cache searcher instance */ public Searcher getSearcher() { return _searcher; } /** * Gets the cache * * @return the cache instance */ public Ehcache getCache() { return _searchRequestCache; } /** * Gets the cache manager * * @return the cache manager instance */ public CacheManager getCacheManager() { return _cacheManager; } /** * Gets the executor service used for prefetching * * @return the executor service instance */ public ExecutorService getExecutorService() { return _executorService; } }
Fix PagingRequest range problem
projects/OG-Master/src/main/java/com/opengamma/master/cache/EHCachingSearchCache.java
Fix PagingRequest range problem
<ide><path>rojects/OG-Master/src/main/java/com/opengamma/master/cache/EHCachingSearchCache.java <ide> final int totalResults = info.getFirst(); <ide> final ConcurrentNavigableMap<Integer, List<UniqueId>> rangeMap = info.getSecond(); <ide> <del> // Fix unpaged requests and end indexes larger than the total doc count <del> if (pagingRequest.getLastItem() >= totalResults) { <add> // Fix indexes larger than the total doc count <add> if (pagingRequest.getFirstItem() >= totalResults) { <add> pagingRequest = PagingRequest.ofIndex(totalResults, 0); <add> } else if (pagingRequest.getLastItem() >= totalResults) { <ide> pagingRequest = PagingRequest.ofIndex(pagingRequest.getFirstItem(), totalResults - pagingRequest.getFirstItem()); <ide> } <ide>
Java
apache-2.0
9e46997159100e5e3d4c39145d5903da39da8d9c
0
bitcoinj/bitcoinj,natzei/bitcoinj,peterdettman/bitcoinj,kmels/bitcoinj,GroestlCoin/groestlcoinj,GroestlCoin/groestlcoinj,kmels/bitcoinj,yenliangl/bitcoinj,GroestlCoin/groestlcoinj,natzei/bitcoinj,schildbach/bitcoinj,peterdettman/bitcoinj,yenliangl/bitcoinj,bitcoinj/bitcoinj,schildbach/bitcoinj
/* * Copyright 2011 Google Inc. * Copyright 2014 Andreas Schildbach * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.bitcoinj.core; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.io.*; import java.math.BigInteger; import java.nio.charset.StandardCharsets; import java.util.Arrays; import static com.google.common.base.Preconditions.checkState; /** * <p>A Message is a data structure that can be serialized/deserialized using the Bitcoin serialization format. * Specific types of messages that are used both in the block chain, and on the wire, are derived from this * class.</p> * * <p>Instances of this class are not safe for use by multiple threads.</p> */ public abstract class Message { private static final Logger log = LoggerFactory.getLogger(Message.class); public static final int MAX_SIZE = 0x02000000; // 32MB public static final int UNKNOWN_LENGTH = Integer.MIN_VALUE; // Useful to ensure serialize/deserialize are consistent with each other. private static final boolean SELF_CHECK = false; // The offset is how many bytes into the provided byte array this message payload starts at. protected int offset; // The cursor keeps track of where we are in the byte array as we parse it. // Note that it's relative to the start of the array NOT the start of the message payload. protected int cursor; protected int length = UNKNOWN_LENGTH; // The raw message payload bytes themselves. protected byte[] payload; protected boolean recached = false; protected MessageSerializer serializer; protected int protocolVersion; protected NetworkParameters params; protected Message() { serializer = DummySerializer.DEFAULT; } protected Message(NetworkParameters params) { this.params = params; this.protocolVersion = params.getProtocolVersionNum(NetworkParameters.ProtocolVersion.CURRENT); this.serializer = params.getDefaultSerializer(); } protected Message(NetworkParameters params, byte[] payload, int offset, int protocolVersion) throws ProtocolException { this(params, payload, offset, protocolVersion, params.getDefaultSerializer(), UNKNOWN_LENGTH); } /** * * @param params NetworkParameters object. * @param payload Bitcoin protocol formatted byte array containing message content. * @param offset The location of the first payload byte within the array. * @param protocolVersion Bitcoin protocol version. * @param serializer the serializer to use for this message. * @param length The length of message payload if known. Usually this is provided when deserializing of the wire * as the length will be provided as part of the header. If unknown then set to Message.UNKNOWN_LENGTH * @throws ProtocolException */ protected Message(NetworkParameters params, byte[] payload, int offset, int protocolVersion, MessageSerializer serializer, int length) throws ProtocolException { this.serializer = serializer; this.protocolVersion = protocolVersion; this.params = params; this.payload = payload; this.cursor = this.offset = offset; this.length = length; parse(); if (this.length == UNKNOWN_LENGTH) checkState(false, "Length field has not been set in constructor for %s after parse.", getClass().getSimpleName()); if (SELF_CHECK) { selfCheck(payload, offset); } if (!serializer.isParseRetainMode()) this.payload = null; } private void selfCheck(byte[] payload, int offset) { if (!(this instanceof VersionMessage)) { byte[] payloadBytes = new byte[cursor - offset]; System.arraycopy(payload, offset, payloadBytes, 0, cursor - offset); byte[] reserialized = bitcoinSerialize(); if (!Arrays.equals(reserialized, payloadBytes)) throw new RuntimeException("Serialization is wrong: \n" + Utils.HEX.encode(reserialized) + " vs \n" + Utils.HEX.encode(payloadBytes)); } } protected Message(NetworkParameters params, byte[] payload, int offset) throws ProtocolException { this(params, payload, offset, params.getProtocolVersionNum(NetworkParameters.ProtocolVersion.CURRENT), params.getDefaultSerializer(), UNKNOWN_LENGTH); } protected Message(NetworkParameters params, byte[] payload, int offset, MessageSerializer serializer, int length) throws ProtocolException { this(params, payload, offset, params.getProtocolVersionNum(NetworkParameters.ProtocolVersion.CURRENT), serializer, length); } // These methods handle the serialization/deserialization using the custom Bitcoin protocol. protected abstract void parse() throws ProtocolException; /** * <p>To be called before any change of internal values including any setters. This ensures any cached byte array is * removed.</p> * <p>Child messages of this object(e.g. Transactions belonging to a Block) will not have their internal byte caches * invalidated unless they are also modified internally.</p> */ protected void unCache() { payload = null; recached = false; } protected void adjustLength(int newArraySize, int adjustment) { if (length == UNKNOWN_LENGTH) return; // Our own length is now unknown if we have an unknown length adjustment. if (adjustment == UNKNOWN_LENGTH) { length = UNKNOWN_LENGTH; return; } length += adjustment; // Check if we will need more bytes to encode the length prefix. if (newArraySize == 1) length++; // The assumption here is we never call adjustLength with the same arraySize as before. else if (newArraySize != 0) length += VarInt.sizeOf(newArraySize) - VarInt.sizeOf(newArraySize - 1); } /** * used for unit testing */ public boolean isCached() { return payload != null; } public boolean isRecached() { return recached; } /** * Returns a copy of the array returned by {@link Message#unsafeBitcoinSerialize()}, which is safe to mutate. * If you need extra performance and can guarantee you won't write to the array, you can use the unsafe version. * * @return a freshly allocated serialized byte array */ public byte[] bitcoinSerialize() { byte[] bytes = unsafeBitcoinSerialize(); byte[] copy = new byte[bytes.length]; System.arraycopy(bytes, 0, copy, 0, bytes.length); return copy; } /** * <p>Serialize this message to a byte array that conforms to the bitcoin wire protocol.</p> * * <p>This method may return the original byte array used to construct this message if the * following conditions are met:</p> * * <ol> * <li>1) The message was parsed from a byte array with parseRetain = true</li> * <li>2) The message has not been modified</li> * <li>3) The array had an offset of 0 and no surplus bytes</li> * </ol> * * <p>If condition 3 is not met then an copy of the relevant portion of the array will be returned. * Otherwise a full serialize will occur. For this reason you should only use this API if you can guarantee you * will treat the resulting array as read only.</p> * * @return a byte array owned by this object, do NOT mutate it. */ public byte[] unsafeBitcoinSerialize() { // 1st attempt to use a cached array. if (payload != null) { if (offset == 0 && length == payload.length) { // Cached byte array is the entire message with no extras so we can return as is and avoid an array // copy. return payload; } byte[] buf = new byte[length]; System.arraycopy(payload, offset, buf, 0, length); return buf; } // No cached array available so serialize parts by stream. ByteArrayOutputStream stream = new UnsafeByteArrayOutputStream(length < 32 ? 32 : length + 32); try { bitcoinSerializeToStream(stream); } catch (IOException e) { // Cannot happen, we are serializing to a memory stream. } if (serializer.isParseRetainMode()) { // A free set of steak knives! // If there happens to be a call to this method we gain an opportunity to recache // the byte array and in this case it contains no bytes from parent messages. // This give a dual benefit. Releasing references to the larger byte array so that it // it is more likely to be GC'd. And preventing double serializations. E.g. calculating // merkle root calls this method. It is will frequently happen prior to serializing the block // which means another call to bitcoinSerialize is coming. If we didn't recache then internal // serialization would occur a 2nd time and every subsequent time the message is serialized. payload = stream.toByteArray(); cursor = cursor - offset; offset = 0; recached = true; length = payload.length; return payload; } // Record length. If this Message wasn't parsed from a byte stream it won't have length field // set (except for static length message types). Setting it makes future streaming more efficient // because we can preallocate the ByteArrayOutputStream buffer and avoid resizing. byte[] buf = stream.toByteArray(); length = buf.length; return buf; } /** * Serialize this message to the provided OutputStream using the bitcoin wire format. * * @param stream * @throws IOException */ public final void bitcoinSerialize(OutputStream stream) throws IOException { // 1st check for cached bytes. if (payload != null && length != UNKNOWN_LENGTH) { stream.write(payload, offset, length); return; } bitcoinSerializeToStream(stream); } /** * Serializes this message to the provided stream. If you just want the raw bytes use bitcoinSerialize(). */ protected void bitcoinSerializeToStream(OutputStream stream) throws IOException { log.error("Error: {} class has not implemented bitcoinSerializeToStream method. Generating message with no payload", getClass()); } /** * This method is a NOP for all classes except Block and Transaction. It is only declared in Message * so BitcoinSerializer can avoid 2 instanceof checks + a casting. */ public Sha256Hash getHash() { throw new UnsupportedOperationException(); } /** * This returns a correct value by parsing the message. */ public final int getMessageSize() { if (length == UNKNOWN_LENGTH) checkState(false, "Length field has not been set in %s.", getClass().getSimpleName()); return length; } protected long readUint32() throws ProtocolException { try { long u = Utils.readUint32(payload, cursor); cursor += 4; return u; } catch (ArrayIndexOutOfBoundsException e) { throw new ProtocolException(e); } } protected long readInt64() throws ProtocolException { try { long u = Utils.readInt64(payload, cursor); cursor += 8; return u; } catch (ArrayIndexOutOfBoundsException e) { throw new ProtocolException(e); } } protected BigInteger readUint64() throws ProtocolException { // Java does not have an unsigned 64 bit type. So scrape it off the wire then flip. return new BigInteger(Utils.reverseBytes(readBytes(8))); } protected long readVarInt() throws ProtocolException { return readVarInt(0); } protected long readVarInt(int offset) throws ProtocolException { try { VarInt varint = new VarInt(payload, cursor + offset); cursor += offset + varint.getOriginalSizeInBytes(); return varint.value; } catch (ArrayIndexOutOfBoundsException e) { throw new ProtocolException(e); } } protected byte[] readBytes(int length) throws ProtocolException { if ((length > MAX_SIZE) || (cursor + length > payload.length)) { throw new ProtocolException("Claimed value length too large: " + length); } try { byte[] b = new byte[length]; System.arraycopy(payload, cursor, b, 0, length); cursor += length; return b; } catch (IndexOutOfBoundsException e) { throw new ProtocolException(e); } } protected byte[] readByteArray() throws ProtocolException { long len = readVarInt(); return readBytes((int)len); } protected String readStr() throws ProtocolException { long length = readVarInt(); return length == 0 ? "" : new String(readBytes((int) length), StandardCharsets.UTF_8); // optimization for empty strings } protected Sha256Hash readHash() throws ProtocolException { // We have to flip it around, as it's been read off the wire in little endian. // Not the most efficient way to do this but the clearest. return Sha256Hash.wrapReversed(readBytes(32)); } protected boolean hasMoreBytes() { return cursor < payload.length; } /** Network parameters this message was created with. */ public NetworkParameters getParams() { return params; } /** * Set the serializer for this message when deserialized by Java. */ private void readObject(ObjectInputStream in) throws IOException, ClassNotFoundException { in.defaultReadObject(); if (null != params) { this.serializer = params.getDefaultSerializer(); } } }
core/src/main/java/org/bitcoinj/core/Message.java
/* * Copyright 2011 Google Inc. * Copyright 2014 Andreas Schildbach * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.bitcoinj.core; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.io.*; import java.math.BigInteger; import java.nio.charset.StandardCharsets; import java.util.Arrays; import static com.google.common.base.Preconditions.checkState; /** * <p>A Message is a data structure that can be serialized/deserialized using the Bitcoin serialization format. * Specific types of messages that are used both in the block chain, and on the wire, are derived from this * class.</p> * * <p>Instances of this class are not safe for use by multiple threads.</p> */ public abstract class Message { private static final Logger log = LoggerFactory.getLogger(Message.class); public static final int MAX_SIZE = 0x02000000; // 32MB public static final int UNKNOWN_LENGTH = Integer.MIN_VALUE; // Useful to ensure serialize/deserialize are consistent with each other. private static final boolean SELF_CHECK = false; // The offset is how many bytes into the provided byte array this message payload starts at. protected int offset; // The cursor keeps track of where we are in the byte array as we parse it. // Note that it's relative to the start of the array NOT the start of the message payload. protected int cursor; protected int length = UNKNOWN_LENGTH; // The raw message payload bytes themselves. protected byte[] payload; protected boolean recached = false; protected MessageSerializer serializer; protected int protocolVersion; protected NetworkParameters params; protected Message() { serializer = DummySerializer.DEFAULT; } protected Message(NetworkParameters params) { this.params = params; serializer = params.getDefaultSerializer(); } protected Message(NetworkParameters params, byte[] payload, int offset, int protocolVersion) throws ProtocolException { this(params, payload, offset, protocolVersion, params.getDefaultSerializer(), UNKNOWN_LENGTH); } /** * * @param params NetworkParameters object. * @param payload Bitcoin protocol formatted byte array containing message content. * @param offset The location of the first payload byte within the array. * @param protocolVersion Bitcoin protocol version. * @param serializer the serializer to use for this message. * @param length The length of message payload if known. Usually this is provided when deserializing of the wire * as the length will be provided as part of the header. If unknown then set to Message.UNKNOWN_LENGTH * @throws ProtocolException */ protected Message(NetworkParameters params, byte[] payload, int offset, int protocolVersion, MessageSerializer serializer, int length) throws ProtocolException { this.serializer = serializer; this.protocolVersion = protocolVersion; this.params = params; this.payload = payload; this.cursor = this.offset = offset; this.length = length; parse(); if (this.length == UNKNOWN_LENGTH) checkState(false, "Length field has not been set in constructor for %s after parse.", getClass().getSimpleName()); if (SELF_CHECK) { selfCheck(payload, offset); } if (!serializer.isParseRetainMode()) this.payload = null; } private void selfCheck(byte[] payload, int offset) { if (!(this instanceof VersionMessage)) { byte[] payloadBytes = new byte[cursor - offset]; System.arraycopy(payload, offset, payloadBytes, 0, cursor - offset); byte[] reserialized = bitcoinSerialize(); if (!Arrays.equals(reserialized, payloadBytes)) throw new RuntimeException("Serialization is wrong: \n" + Utils.HEX.encode(reserialized) + " vs \n" + Utils.HEX.encode(payloadBytes)); } } protected Message(NetworkParameters params, byte[] payload, int offset) throws ProtocolException { this(params, payload, offset, params.getProtocolVersionNum(NetworkParameters.ProtocolVersion.CURRENT), params.getDefaultSerializer(), UNKNOWN_LENGTH); } protected Message(NetworkParameters params, byte[] payload, int offset, MessageSerializer serializer, int length) throws ProtocolException { this(params, payload, offset, params.getProtocolVersionNum(NetworkParameters.ProtocolVersion.CURRENT), serializer, length); } // These methods handle the serialization/deserialization using the custom Bitcoin protocol. protected abstract void parse() throws ProtocolException; /** * <p>To be called before any change of internal values including any setters. This ensures any cached byte array is * removed.</p> * <p>Child messages of this object(e.g. Transactions belonging to a Block) will not have their internal byte caches * invalidated unless they are also modified internally.</p> */ protected void unCache() { payload = null; recached = false; } protected void adjustLength(int newArraySize, int adjustment) { if (length == UNKNOWN_LENGTH) return; // Our own length is now unknown if we have an unknown length adjustment. if (adjustment == UNKNOWN_LENGTH) { length = UNKNOWN_LENGTH; return; } length += adjustment; // Check if we will need more bytes to encode the length prefix. if (newArraySize == 1) length++; // The assumption here is we never call adjustLength with the same arraySize as before. else if (newArraySize != 0) length += VarInt.sizeOf(newArraySize) - VarInt.sizeOf(newArraySize - 1); } /** * used for unit testing */ public boolean isCached() { return payload != null; } public boolean isRecached() { return recached; } /** * Returns a copy of the array returned by {@link Message#unsafeBitcoinSerialize()}, which is safe to mutate. * If you need extra performance and can guarantee you won't write to the array, you can use the unsafe version. * * @return a freshly allocated serialized byte array */ public byte[] bitcoinSerialize() { byte[] bytes = unsafeBitcoinSerialize(); byte[] copy = new byte[bytes.length]; System.arraycopy(bytes, 0, copy, 0, bytes.length); return copy; } /** * <p>Serialize this message to a byte array that conforms to the bitcoin wire protocol.</p> * * <p>This method may return the original byte array used to construct this message if the * following conditions are met:</p> * * <ol> * <li>1) The message was parsed from a byte array with parseRetain = true</li> * <li>2) The message has not been modified</li> * <li>3) The array had an offset of 0 and no surplus bytes</li> * </ol> * * <p>If condition 3 is not met then an copy of the relevant portion of the array will be returned. * Otherwise a full serialize will occur. For this reason you should only use this API if you can guarantee you * will treat the resulting array as read only.</p> * * @return a byte array owned by this object, do NOT mutate it. */ public byte[] unsafeBitcoinSerialize() { // 1st attempt to use a cached array. if (payload != null) { if (offset == 0 && length == payload.length) { // Cached byte array is the entire message with no extras so we can return as is and avoid an array // copy. return payload; } byte[] buf = new byte[length]; System.arraycopy(payload, offset, buf, 0, length); return buf; } // No cached array available so serialize parts by stream. ByteArrayOutputStream stream = new UnsafeByteArrayOutputStream(length < 32 ? 32 : length + 32); try { bitcoinSerializeToStream(stream); } catch (IOException e) { // Cannot happen, we are serializing to a memory stream. } if (serializer.isParseRetainMode()) { // A free set of steak knives! // If there happens to be a call to this method we gain an opportunity to recache // the byte array and in this case it contains no bytes from parent messages. // This give a dual benefit. Releasing references to the larger byte array so that it // it is more likely to be GC'd. And preventing double serializations. E.g. calculating // merkle root calls this method. It is will frequently happen prior to serializing the block // which means another call to bitcoinSerialize is coming. If we didn't recache then internal // serialization would occur a 2nd time and every subsequent time the message is serialized. payload = stream.toByteArray(); cursor = cursor - offset; offset = 0; recached = true; length = payload.length; return payload; } // Record length. If this Message wasn't parsed from a byte stream it won't have length field // set (except for static length message types). Setting it makes future streaming more efficient // because we can preallocate the ByteArrayOutputStream buffer and avoid resizing. byte[] buf = stream.toByteArray(); length = buf.length; return buf; } /** * Serialize this message to the provided OutputStream using the bitcoin wire format. * * @param stream * @throws IOException */ public final void bitcoinSerialize(OutputStream stream) throws IOException { // 1st check for cached bytes. if (payload != null && length != UNKNOWN_LENGTH) { stream.write(payload, offset, length); return; } bitcoinSerializeToStream(stream); } /** * Serializes this message to the provided stream. If you just want the raw bytes use bitcoinSerialize(). */ protected void bitcoinSerializeToStream(OutputStream stream) throws IOException { log.error("Error: {} class has not implemented bitcoinSerializeToStream method. Generating message with no payload", getClass()); } /** * This method is a NOP for all classes except Block and Transaction. It is only declared in Message * so BitcoinSerializer can avoid 2 instanceof checks + a casting. */ public Sha256Hash getHash() { throw new UnsupportedOperationException(); } /** * This returns a correct value by parsing the message. */ public final int getMessageSize() { if (length == UNKNOWN_LENGTH) checkState(false, "Length field has not been set in %s.", getClass().getSimpleName()); return length; } protected long readUint32() throws ProtocolException { try { long u = Utils.readUint32(payload, cursor); cursor += 4; return u; } catch (ArrayIndexOutOfBoundsException e) { throw new ProtocolException(e); } } protected long readInt64() throws ProtocolException { try { long u = Utils.readInt64(payload, cursor); cursor += 8; return u; } catch (ArrayIndexOutOfBoundsException e) { throw new ProtocolException(e); } } protected BigInteger readUint64() throws ProtocolException { // Java does not have an unsigned 64 bit type. So scrape it off the wire then flip. return new BigInteger(Utils.reverseBytes(readBytes(8))); } protected long readVarInt() throws ProtocolException { return readVarInt(0); } protected long readVarInt(int offset) throws ProtocolException { try { VarInt varint = new VarInt(payload, cursor + offset); cursor += offset + varint.getOriginalSizeInBytes(); return varint.value; } catch (ArrayIndexOutOfBoundsException e) { throw new ProtocolException(e); } } protected byte[] readBytes(int length) throws ProtocolException { if ((length > MAX_SIZE) || (cursor + length > payload.length)) { throw new ProtocolException("Claimed value length too large: " + length); } try { byte[] b = new byte[length]; System.arraycopy(payload, cursor, b, 0, length); cursor += length; return b; } catch (IndexOutOfBoundsException e) { throw new ProtocolException(e); } } protected byte[] readByteArray() throws ProtocolException { long len = readVarInt(); return readBytes((int)len); } protected String readStr() throws ProtocolException { long length = readVarInt(); return length == 0 ? "" : new String(readBytes((int) length), StandardCharsets.UTF_8); // optimization for empty strings } protected Sha256Hash readHash() throws ProtocolException { // We have to flip it around, as it's been read off the wire in little endian. // Not the most efficient way to do this but the clearest. return Sha256Hash.wrapReversed(readBytes(32)); } protected boolean hasMoreBytes() { return cursor < payload.length; } /** Network parameters this message was created with. */ public NetworkParameters getParams() { return params; } /** * Set the serializer for this message when deserialized by Java. */ private void readObject(ObjectInputStream in) throws IOException, ClassNotFoundException { in.defaultReadObject(); if (null != params) { this.serializer = params.getDefaultSerializer(); } } }
Message: Fix one constructor doesn't set the protocol version.
core/src/main/java/org/bitcoinj/core/Message.java
Message: Fix one constructor doesn't set the protocol version.
<ide><path>ore/src/main/java/org/bitcoinj/core/Message.java <ide> <ide> protected Message(NetworkParameters params) { <ide> this.params = params; <del> serializer = params.getDefaultSerializer(); <add> this.protocolVersion = params.getProtocolVersionNum(NetworkParameters.ProtocolVersion.CURRENT); <add> this.serializer = params.getDefaultSerializer(); <ide> } <ide> <ide> protected Message(NetworkParameters params, byte[] payload, int offset, int protocolVersion) throws ProtocolException {
Java
apache-2.0
8c1c476815fc1c70c1e5609f98eea83a7506245f
0
InnoFang/Android-Code-Demos,InnoFang/Android-Code-Demos,InnoFang/Android-Code-Demos,InnoFang/Android-Code-Demos
package io.innofang.eventbusdemo; import android.content.Intent; import android.os.Bundle; import android.support.v7.app.AppCompatActivity; import android.view.View; import android.widget.Toast; import org.greenrobot.eventbus.EventBus; import org.greenrobot.eventbus.Subscribe; import org.greenrobot.eventbus.ThreadMode; public class MainActivity extends AppCompatActivity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); // If you want to handle sticky message, please comment out the following code EventBus.getDefault().register(this); } @Override protected void onDestroy() { super.onDestroy(); EventBus.getDefault().unregister(this); } public void onClick(View view) { switch (view.getId()) { case R.id.intent_to_second_button: startActivity(new Intent(MainActivity.this, SecondActivity.class)); break; case R.id.handle_sticky_button: EventBus.getDefault().register(this); break; } startActivity(new Intent(MainActivity.this, SecondActivity.class)); } @Subscribe(threadMode = ThreadMode.MAIN) public void onHandleMessage(MessageEvent messageEvent) { Toast.makeText(this, "Message: " + messageEvent.getMessage(), Toast.LENGTH_SHORT).show(); } @Subscribe(sticky = true) public void onHandleStickyMessage(MessageEvent messageEvent) { Toast.makeText(this, "Sticky Message: " + messageEvent.getMessage(), Toast.LENGTH_SHORT).show(); } }
EventBusDemo/app/src/main/java/io/innofang/eventbusdemo/MainActivity.java
package io.innofang.eventbusdemo; import android.content.Intent; import android.os.Bundle; import android.support.v7.app.AppCompatActivity; import android.view.View; import android.widget.Toast; import org.greenrobot.eventbus.EventBus; import org.greenrobot.eventbus.Subscribe; import org.greenrobot.eventbus.ThreadMode; public class MainActivity extends AppCompatActivity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); // If you want to handle sticky message, please comment out the following code EventBus.getDefault().register(this); } @Override protected void onDestroy() { super.onDestroy(); EventBus.getDefault().register(this); } public void onClick(View view) { switch (view.getId()) { case R.id.intent_to_second_button: startActivity(new Intent(MainActivity.this, SecondActivity.class)); break; case R.id.handle_sticky_button: EventBus.getDefault().register(this); break; } startActivity(new Intent(MainActivity.this, SecondActivity.class)); } @Subscribe(threadMode = ThreadMode.MAIN) public void onHandleMessage(MessageEvent messageEvent) { Toast.makeText(this, "Message: " + messageEvent.getMessage(), Toast.LENGTH_SHORT).show(); } @Subscribe(sticky = true) public void onHandleStickyMessage(MessageEvent messageEvent) { Toast.makeText(this, "Sticky Message: " + messageEvent.getMessage(), Toast.LENGTH_SHORT).show(); } }
:bug: fix some bugs
EventBusDemo/app/src/main/java/io/innofang/eventbusdemo/MainActivity.java
:bug: fix some bugs
<ide><path>ventBusDemo/app/src/main/java/io/innofang/eventbusdemo/MainActivity.java <ide> @Override <ide> protected void onDestroy() { <ide> super.onDestroy(); <del> EventBus.getDefault().register(this); <add> EventBus.getDefault().unregister(this); <ide> } <ide> <ide> public void onClick(View view) {
Java
mit
e0dd003039e86ce717e65e5775eb1302f0a6012a
0
jvasileff/aos-xp
package org.anodyneos.xpImpl.runtime; import java.lang.reflect.Method; import java.util.Collections; import java.util.HashMap; import java.util.List; import java.util.Map; import org.anodyneos.commons.net.URI; import org.anodyneos.commons.xml.UnifiedResolver; import org.anodyneos.xp.XpPage; import org.anodyneos.xpImpl.compiler.JavaCompiler; import org.anodyneos.xpImpl.compiler.SunJavaCompiler; import org.anodyneos.xpImpl.translater.Translater; import org.anodyneos.xpImpl.translater.TranslaterResult; public class XpCachingLoader{ public static final long NEVER_LOADED = -1; private ClassLoader parentLoader; private String classPath; private String classRoot; private String javaRoot; private String xpRegistry; private UnifiedResolver resolver; private final Map xpCache = Collections.synchronizedMap(new HashMap()); private static XpCachingLoader me = new XpCachingLoader(); private XpCachingLoader(){} public static XpCachingLoader getLoader(){ return me; } public XpPage getXpPage(URI xpURI){ try{ XpPage xpPage = (XpPage)xpCache.get(xpURI.toString()); long loadTime = NEVER_LOADED; if (xpPage != null ){ loadTime = xpPage.getLoadTime(); } if ((xpPage == null ) || (xpPage != null && xpNeedsReloading(xpURI, loadTime, xpPage.getClass().getClassLoader()))){ translateXp(xpURI); compileXp(xpURI); xpCache.remove(xpURI.toString()); xpPage = loadPage(xpURI); xpCache.put(xpURI.toString(),xpPage); } return xpPage; }catch(Exception e){ e.printStackTrace(); return null; } } private XpPage loadPage(URI xpURI) throws Exception { XpClassLoader loader = new XpClassLoader(parentLoader); loader.setRoot(getClassRoot()); Class cls = loader.loadClass(Translater.getClassName(xpURI)); return (XpPage)cls.newInstance(); } private boolean xpNeedsReloading(URI xpURI, long loadTime, ClassLoader loader){ if (Translater.xpIsOutOfDate(xpURI,getClassRoot(),getResolver(),loadTime)) { return true; } else { try{ Class xpClass = Class.forName(Translater.getClassName(xpURI),true,loader); Method getDependents = xpClass.getDeclaredMethod("getDependents",(Class[])null); List dependents = (List)getDependents.invoke((Object)null,(Object[])null); for (int i=0; i<dependents.size();i++){ String dependent = (String)dependents.get(i); URI uriDep = new URI(dependent); if (xpNeedsReloading(uriDep,loadTime,loader)){ return true; } } }catch (Exception e){ // something happened System.out.println("Unable to inspect children of " + xpURI.toString() + " to see if they would cause a reload."); e.printStackTrace(); return true; } } // neither the file itself nor any dependents are out of date return false; } private void compileXp(URI xpURI) throws Exception { System.out.println("Compiling " + xpURI.toString()); JavaCompiler compiler = new SunJavaCompiler(getClassPath(),getClassRoot()); compiler.setSourcePath(getJavaRoot()); compiler.compile(Translater.getJavaFile(getJavaRoot(),xpURI),System.err); } private void translateXp(URI xpURI) throws Exception{ System.out.println("Translating " + xpURI.toString()); if (getResolver() == null){ throw new IllegalStateException("XpCachingLoader requires resolver to be set."); } TranslaterResult result = Translater.translate(getJavaRoot(), xpURI, getXpRegistry(),resolver); } public String getClassRoot() { return classRoot; } public void setClassRoot(String classRoot) { this.classRoot = classRoot; } public String getJavaRoot() { return javaRoot; } public void setJavaRoot(String javaRoot) { this.javaRoot = javaRoot; } public String getXpRegistry() { return xpRegistry; } public void setXpRegistry(String xpRegistry) { this.xpRegistry = xpRegistry; } public String getClassPath() { return classPath; } public void setClassPath(String classPath) { this.classPath = classPath; } public ClassLoader getParentLoader() { return parentLoader; } public void setParentLoader(ClassLoader parentLoader) { this.parentLoader = parentLoader; } /** * @return Returns the resolver. */ public UnifiedResolver getResolver() { return resolver; } /** * @param resolver The resolver to set. */ public void setResolver(UnifiedResolver resolver) { this.resolver = resolver; } }
src.java/org/anodyneos/xpImpl/runtime/XpCachingLoader.java
package org.anodyneos.xpImpl.runtime; import java.io.File; import java.lang.reflect.Method; import java.util.Collections; import java.util.HashMap; import java.util.List; import java.util.Map; import org.anodyneos.commons.net.URI; import org.anodyneos.commons.xml.UnifiedResolver; import org.anodyneos.xp.XpPage; import org.anodyneos.xpImpl.compiler.JavaCompiler; import org.anodyneos.xpImpl.compiler.SunJavaCompiler; import org.anodyneos.xpImpl.translater.Translater; import org.anodyneos.xpImpl.translater.TranslaterResult; public class XpCachingLoader{ public static final long NEVER_LOADED = -1; private ClassLoader parentLoader; private String classPath; private String classRoot; private String javaRoot; private String xpRegistry; private UnifiedResolver resolver; private final Map xpCache = Collections.synchronizedMap(new HashMap()); private static XpCachingLoader me = new XpCachingLoader(); private XpCachingLoader(){} public static XpCachingLoader getLoader(){ return me; } public XpPage getXpPage(URI xpURI){ try{ XpPage xpPage = (XpPage)xpCache.get(xpURI.toString()); long loadTime = NEVER_LOADED; if (xpPage != null ){ loadTime = xpPage.getLoadTime(); } if ((xpPage == null ) || (xpPage != null && xpNeedsReloading(xpURI, loadTime, xpPage.getClass().getClassLoader()))){ translateXp(xpURI); compileXp(xpURI); xpCache.remove(xpURI.toString()); xpPage = loadPage(xpURI); xpCache.put(xpURI.toString(),xpPage); } return xpPage; }catch(Exception e){ e.printStackTrace(); return null; } } private XpPage loadPage(URI xpURI) throws Exception { XpClassLoader loader = new XpClassLoader(parentLoader); loader.setRoot(getClassRoot()); Class cls = loader.loadClass(Translater.getClassName(xpURI)); return (XpPage)cls.newInstance(); } private boolean xpNeedsReloading(URI xpURI, long loadTime, ClassLoader loader){ if (Translater.xpIsOutOfDate(xpURI,getClassRoot(),getResolver(),loadTime)) { return true; } else { try{ Class xpClass = Class.forName(Translater.getClassName(xpURI),true,loader); Method getDependents = xpClass.getDeclaredMethod("getDependents",(Class[])null); List dependents = (List)getDependents.invoke((Object)null,(Object[])null); for (int i=0; i<dependents.size();i++){ String dependent = (String)dependents.get(i); URI uriDep = new URI(dependent); if (xpNeedsReloading(uriDep,loadTime,loader)){ return true; } } }catch (Exception e){ // something happened System.out.println("Unable to inspect children of " + xpURI.toString() + " to see if they would cause a reload."); e.printStackTrace(); return true; } } // neither the file itself nor any dependents are out of date return false; } private void compileXp(URI xpURI) throws Exception { System.out.println("Compiling " + xpURI.toString()); String cPath = System.getProperty("java.class.path"); cPath += File.pathSeparator + getClassPath(); System.out.println("classpath = " + cPath); JavaCompiler compiler = new SunJavaCompiler(cPath,getClassRoot()); compiler.setSourcePath(getJavaRoot()); compiler.compile(Translater.getJavaFile(getJavaRoot(),xpURI),System.err); } private void translateXp(URI xpURI) throws Exception{ System.out.println("Translating " + xpURI.toString()); if (getResolver() == null){ throw new IllegalStateException("XpCachingLoader requires resolver to be set."); } TranslaterResult result = Translater.translate(getJavaRoot(), xpURI, getXpRegistry(),resolver); } public String getClassRoot() { return classRoot; } public void setClassRoot(String classRoot) { this.classRoot = classRoot; } public String getJavaRoot() { return javaRoot; } public void setJavaRoot(String javaRoot) { this.javaRoot = javaRoot; } public String getXpRegistry() { return xpRegistry; } public void setXpRegistry(String xpRegistry) { this.xpRegistry = xpRegistry; } public String getClassPath() { return classPath; } public void setClassPath(String classPath) { this.classPath = classPath; } public ClassLoader getParentLoader() { return parentLoader; } public void setParentLoader(ClassLoader parentLoader) { this.parentLoader = parentLoader; } /** * @return Returns the resolver. */ public UnifiedResolver getResolver() { return resolver; } /** * @param resolver The resolver to set. */ public void setResolver(UnifiedResolver resolver) { this.resolver = resolver; } }
Removed unnecessary code because classpath is expected to be complete by calling client
src.java/org/anodyneos/xpImpl/runtime/XpCachingLoader.java
Removed unnecessary code because classpath is expected to be complete by calling client
<ide><path>rc.java/org/anodyneos/xpImpl/runtime/XpCachingLoader.java <ide> package org.anodyneos.xpImpl.runtime; <ide> <del>import java.io.File; <ide> import java.lang.reflect.Method; <ide> import java.util.Collections; <ide> import java.util.HashMap; <ide> private void compileXp(URI xpURI) throws Exception { <ide> System.out.println("Compiling " + xpURI.toString()); <ide> <del> String cPath = System.getProperty("java.class.path"); <del> <del> cPath += File.pathSeparator + getClassPath(); <del> <del> System.out.println("classpath = " + cPath); <del> <del> JavaCompiler compiler = new SunJavaCompiler(cPath,getClassRoot()); <add> JavaCompiler compiler = new SunJavaCompiler(getClassPath(),getClassRoot()); <ide> <ide> compiler.setSourcePath(getJavaRoot()); <ide> compiler.compile(Translater.getJavaFile(getJavaRoot(),xpURI),System.err);
Java
lgpl-2.1
c0a57d3086870764aa48e1fa091cb579709d6226
0
JoeCarlson/intermine,joshkh/intermine,joshkh/intermine,Arabidopsis-Information-Portal/intermine,elsiklab/intermine,tomck/intermine,zebrafishmine/intermine,justincc/intermine,justincc/intermine,elsiklab/intermine,justincc/intermine,zebrafishmine/intermine,JoeCarlson/intermine,drhee/toxoMine,joshkh/intermine,zebrafishmine/intermine,kimrutherford/intermine,joshkh/intermine,tomck/intermine,JoeCarlson/intermine,kimrutherford/intermine,Arabidopsis-Information-Portal/intermine,drhee/toxoMine,justincc/intermine,Arabidopsis-Information-Portal/intermine,elsiklab/intermine,kimrutherford/intermine,kimrutherford/intermine,JoeCarlson/intermine,drhee/toxoMine,JoeCarlson/intermine,Arabidopsis-Information-Portal/intermine,elsiklab/intermine,kimrutherford/intermine,drhee/toxoMine,JoeCarlson/intermine,Arabidopsis-Information-Portal/intermine,drhee/toxoMine,drhee/toxoMine,zebrafishmine/intermine,tomck/intermine,zebrafishmine/intermine,elsiklab/intermine,tomck/intermine,Arabidopsis-Information-Portal/intermine,justincc/intermine,kimrutherford/intermine,joshkh/intermine,elsiklab/intermine,tomck/intermine,JoeCarlson/intermine,joshkh/intermine,JoeCarlson/intermine,drhee/toxoMine,tomck/intermine,zebrafishmine/intermine,kimrutherford/intermine,elsiklab/intermine,zebrafishmine/intermine,kimrutherford/intermine,joshkh/intermine,elsiklab/intermine,justincc/intermine,justincc/intermine,tomck/intermine,Arabidopsis-Information-Portal/intermine,JoeCarlson/intermine,zebrafishmine/intermine,kimrutherford/intermine,joshkh/intermine,tomck/intermine,drhee/toxoMine,tomck/intermine,justincc/intermine,justincc/intermine,joshkh/intermine,Arabidopsis-Information-Portal/intermine,zebrafishmine/intermine,elsiklab/intermine,Arabidopsis-Information-Portal/intermine,drhee/toxoMine
package org.flymine.dataconversion; /* * Copyright (C) 2002-2005 FlyMine * * This code may be freely distributed and modified under the * terms of the GNU Lesser General Public Licence. This should * be distributed with the code. See the LICENSE file for more * information or http://www.gnu.org/copyleft/lesser.html. * */ import junit.framework.TestCase; import java.util.Map; import java.util.HashMap; import java.util.Set; import java.util.HashSet; import java.util.List; import java.util.ArrayList; import java.util.LinkedHashSet; import java.util.LinkedHashMap; import java.util.Collection; import java.util.Arrays; import java.io.InputStreamReader; import java.io.FileWriter; import java.io.File; import java.io.BufferedReader; import org.intermine.xml.full.FullParser; import org.intermine.xml.full.FullRenderer; import org.intermine.xml.full.Attribute; import org.intermine.xml.full.Item; import org.intermine.xml.full.Reference; import org.intermine.xml.full.ReferenceList; import org.intermine.dataconversion.DataTranslator; import org.intermine.dataconversion.DataTranslatorTestCase; import org.intermine.dataconversion.MockItemReader; import org.intermine.dataconversion.MockItemWriter; /** * Test for translating MAGE data in fulldata Item format conforming to a source OWL definition * to fulldata Item format conforming to InterMine OWL definition. * * @author Wenyan Ji * @author Richard Smith */ public class MageDataTranslatorTest extends DataTranslatorTestCase { private String tgtNs = "http://www.flymine.org/model/genomic#"; private String ns = "http://www.flymine.org/model/mage#"; public MageDataTranslatorTest(String arg) { super(arg); } public void setUp() throws Exception { super.setUp(); } public void testTranslate() throws Exception { Collection srcItems = getSrcItems(); //FileWriter writerSrc = new FileWriter(new File("src_items.xml")); //writerSrc.write(FullRenderer.render(srcItems)); //writerSrc.close(); Map itemMap = writeItems(srcItems); DataTranslator translator = new MageDataTranslator(new MockItemReader(itemMap), mapping, srcModel, getTargetModel(tgtNs)); MockItemWriter tgtIw = new MockItemWriter(new LinkedHashMap()); translator.translate(tgtIw); //FileWriter writer = new FileWriter(new File("exptmp")); //writer.write(FullRenderer.render(tgtIw.getItems())); //writer.close(); //assertEquals(new HashSet(expectedItems), tgtIw.getItems()); } public void testCreateAuthors() throws Exception { Item srcItem = createItem(ns + "BibliographicReference", "0_0", ""); srcItem.addAttribute(new Attribute("authors", " William Whitfield; FlyChip Facility")); Item exp1 = createItem(tgtNs + "Author", "-1_1", ""); exp1.addAttribute(new Attribute("name", "William Whitfield")); Item exp2 = createItem(tgtNs + "Author", "-1_2", ""); exp2.addAttribute(new Attribute("name", "FlyChip Facility")); Set expected = new HashSet(Arrays.asList(new Object[] {exp1, exp2})); MageDataTranslator translator = new MageDataTranslator(new MockItemReader(new HashMap()), mapping, srcModel, getTargetModel(tgtNs)); assertEquals(expected, translator.createAuthors(srcItem)); } public void testSetReporterLocationCoords() throws Exception{ Item srcItem = createItem(ns + "FeatureReporterMap", "6_28", ""); srcItem.addCollection(new ReferenceList("featureInformationSources", new ArrayList(Arrays.asList(new Object[]{"7_29"})))); Item srcItem2=createItem(ns + "FeatureInformation", "7_29", ""); srcItem2. addReference(new Reference("feature", "8_30")); Item srcItem3=createItem(ns + "Feature", "8_30", ""); srcItem3.addReference(new Reference("featureLocation", "9_31")); srcItem3.addReference(new Reference("zone", "10_17")); Item srcItem4 = createItem(ns + "FeatureLocation", "9_31", ""); srcItem4.addAttribute(new Attribute("column", "1")); srcItem4.addAttribute(new Attribute("row", "2")); Item srcItem5 = createItem(ns + "Zone", "10_17", ""); srcItem5.addAttribute(new Attribute("column", "1")); srcItem5.addAttribute(new Attribute("row", "1")); Set srcItems = new HashSet(Arrays.asList(new Object[]{srcItem, srcItem2, srcItem3, srcItem4, srcItem5})); Map itemMap = writeItems(srcItems); MageDataTranslator translator = new MageDataTranslator(new MockItemReader(itemMap), mapping, srcModel, getTargetModel(tgtNs)); //MockItemWriter tgtIw = new MockItemWriter(new LinkedHashMap()); //translator.translate(tgtIw); Item tgtItem = createItem(tgtNs + "ReporterLocation", "6_28", ""); tgtItem.addAttribute(new Attribute("localX", "1")); tgtItem.addAttribute(new Attribute("localY", "2")); tgtItem.addAttribute(new Attribute("zoneX", "1")); tgtItem.addAttribute(new Attribute("zoneY", "1")); HashSet expected = new HashSet(Arrays.asList(new Object[]{tgtItem})); //assertEquals(expected, tgtIw.getItems()); Item destItem = createItem(tgtNs + "ReporterLocation", "6_28", ""); translator.setReporterLocationCoords(srcItem, destItem); assertEquals(tgtItem, destItem); } public void testCreateFeatureMap() throws Exception { Item srcItem1=createItem(ns + "PhysicalArrayDesign", "0_0", ""); ReferenceList rl1=new ReferenceList("featureGroups", new ArrayList(Arrays.asList(new Object[] {"1_1"}))); srcItem1.addCollection(rl1); Item srcItem2=createItem(ns + "FeatureGroup", "1_1", ""); ReferenceList rl2=new ReferenceList("features", new ArrayList(Arrays.asList(new Object[] {"1_2"}))); srcItem2.addCollection(rl2); Set srcItems = new HashSet(Arrays.asList(new Object[] {srcItem1, srcItem2})); Map itemMap = writeItems(srcItems); MageDataTranslator translator = new MageDataTranslator(new MockItemReader(itemMap), mapping, srcModel, getTargetModel(tgtNs)); Item tgtItem = createItem(tgtNs+"MicroArraySlideDesign", "0_0", ""); Map expected = new HashMap(); expected.put("1_2", "0_0"); translator.createFeatureMap(srcItem1); assertEquals(expected, translator.featureToDesign); } //test translate from PhysicalArrayDesign to MicroArraySlideDesign //which includes 3 methods, createFeatureMap, padDescriptions, and changeRefToAttr public void testTranslateMASD() throws Exception { Item srcItem1=createItem(ns + "PhysicalArrayDesign", "1_1", ""); srcItem1.addCollection(new ReferenceList("descriptions", new ArrayList(Arrays.asList(new Object[] {"1_2", "2_2"} )))); srcItem1.addReference(new Reference("surfaceType","1_11")); srcItem1.addCollection(new ReferenceList("featureGroups", new ArrayList(Arrays.asList(new Object[] {"1_12"})))); Item srcItem2=createItem(ns + "Description", "1_2", ""); srcItem2.addCollection(new ReferenceList("annotations", new ArrayList(Arrays.asList(new Object[] {"1_3", "1_4"})))); Item srcItem2a=createItem(ns + "Description", "2_2", ""); srcItem2a.addCollection(new ReferenceList("annotations", new ArrayList(Arrays.asList(new Object[] {"2_3", "2_4"})))); Item srcItem3=createItem(ns + "OntologyEntry", "1_3", ""); srcItem3.addAttribute(new Attribute("value", "double")); Item srcItem4=createItem(ns + "SurfaceType", "1_11", ""); srcItem4.addAttribute(new Attribute("value", "polylysine")); Item srcItem5=createItem(ns + "FeatureGroup", "1_12", ""); srcItem5.addCollection(new ReferenceList("features", new ArrayList(Arrays.asList(new Object[] {"1_13"})))); Set srcItems = new HashSet(Arrays.asList(new Object[] {srcItem1, srcItem2, srcItem2a, srcItem3, srcItem4, srcItem5})); Map itemMap = writeItems(srcItems); MageDataTranslator translator = new MageDataTranslator(new MockItemReader(itemMap), mapping, srcModel, getTargetModel(tgtNs)); //MockItemWriter tgtIw = new MockItemWriter(new LinkedHashMap()); //translator.translate(tgtIw); // expected items // MicroArraySlideDesign 1_1 Item expectedItem=createItem(tgtNs + "MicroArraySlideDesign", "1_1", ""); expectedItem.addCollection(new ReferenceList("descriptions", new ArrayList(Arrays.asList(new Object[] {"1_3", "1_4", "2_3", "2_4"})))); expectedItem.addAttribute(new Attribute("surfaceType", "polylysine")); HashSet expected = new HashSet(Arrays.asList(new Object[]{expectedItem})); assertEquals(expected, translator.translateItem(srcItem1)); } public void testMicroArrayExperiment()throws Exception { Item srcItem = createItem(ns+"Experiment", "61_748", ""); srcItem.addAttribute(new Attribute("name", "P10005")); srcItem.addCollection(new ReferenceList("bioAssays", new ArrayList(Arrays.asList(new Object[]{"33_603", "57_709", "43_654"})))); srcItem.addCollection(new ReferenceList("descriptions", new ArrayList(Arrays.asList(new Object[]{"12_749", "12_750"})))); Item srcItem1= createItem(ns+"MeasuredBioAssay", "33_603", ""); srcItem1.addReference(new Reference("featureExtraction", "4_2")); Item srcItem2= createItem(ns+"DerivedBioAssay", "57_709", ""); srcItem2.addReference(new Reference("featureExtraction", "4_2")); Item srcItem3= createItem(ns+"PhysicalBioAssay", "43_654", ""); srcItem3.addReference(new Reference("featureExtraction", "4_2")); Item srcItem4= createItem(ns+"Description", "12_749", ""); srcItem4.addAttribute(new Attribute("text", "experiment description")); Item srcItem5= createItem(ns+"Description", "12_750", ""); srcItem5.addCollection(new ReferenceList("bibliographicReferences", new ArrayList(Arrays.asList(new Object[]{"62_751"})))); Set src = new HashSet(Arrays.asList(new Object[]{srcItem, srcItem1, srcItem2, srcItem3, srcItem4, srcItem5})); Map srcMap = writeItems(src); MageDataTranslator translator = new MageDataTranslator(new MockItemReader(srcMap), mapping, srcModel, getTargetModel(tgtNs)); Item expectedItem =createItem(tgtNs+"MicroArrayExperiment", "61_748", ""); expectedItem.addAttribute(new Attribute("name", "P10005")); expectedItem.addAttribute(new Attribute("description", "experiment description")); expectedItem.addReference(new Reference("publication", "62_751")); //expectedItem.addCollection(new ReferenceList("assays", new ArrayList(Arrays.asList(new Object[]{"57_709"})))); HashSet expected=new HashSet(Arrays.asList(new Object[]{expectedItem})); assertEquals(expected, translator.translateItem(srcItem)); } public void testMicroArrayAssay() throws Exception{ Item srcItem= createItem(ns+"DerivedBioAssay", "57_709", ""); srcItem.addCollection(new ReferenceList("derivedBioAssayData", new ArrayList(Arrays.asList(new Object[]{"58_710"})))); Item srcItem1= createItem(ns+"DerivedBioAssayData", "58_710", ""); srcItem1.addReference(new Reference("bioDataValues", "58_739")); Item srcItem2= createItem(ns+"BioDataTuples", "58_739", ""); srcItem2.addCollection(new ReferenceList("bioAssayTupleData", new ArrayList(Arrays.asList(new Object[]{"58_740", "58_744", "58_755"})))); Item srcItem10 = createItem(ns+"Experiment", "61_748", ""); srcItem10.addCollection(new ReferenceList("bioAssays", new ArrayList(Arrays.asList(new Object[]{"33_603", "57_709", "43_654"})))); Item srcItem11= createItem(ns+"MeasuredBioAssay", "33_603", ""); srcItem11.addReference(new Reference("featureExtraction", "4_2")); Item srcItem13= createItem(ns+"PhysicalBioAssay", "43_654", ""); srcItem13.addReference(new Reference("bioAssayCreation", "50_735")); Item srcItem14= createItem(ns+"Hybridization", "50_735", ""); srcItem14.addCollection(new ReferenceList("sourceBioMaterialMeasurements", new ArrayList(Arrays.asList(new Object[]{"26_736", "26_737"})))); Item srcItem15= createItem(ns+"BioMaterialMeasurement", "26_736", ""); srcItem15.addReference(new Reference("bioMaterial", "23_78")); Item srcItem16= createItem(ns+"BioMaterialMeasurement", "26_737", ""); srcItem16.addReference(new Reference("bioMaterial", "23_146")); Set src = new HashSet(Arrays.asList(new Object[]{srcItem, srcItem1, srcItem2,srcItem10, srcItem11, srcItem13, srcItem14, srcItem15, srcItem16 })); Map srcMap = writeItems(src); MageDataTranslator translator = new MageDataTranslator(new MockItemReader(srcMap), mapping, srcModel, getTargetModel(tgtNs)); Item expectedItem = createItem(tgtNs+"MicroArrayAssay", "57_709", ""); //expectedItem.addCollection(new ReferenceList("results", new ArrayList(Arrays.asList(new Object[]{"58_740", "58_744", "58_755"})))); //expectedItem.addCollection(new ReferenceList("tissues", new ArrayList(Arrays.asList(new Object[]{"23_78", "23_146"})))); expectedItem.addReference(new Reference("experiment", "61_748")); Item expectedItem2 =createItem(tgtNs+"MicroArrayExperiment", "61_748", ""); //expectedItem2.addCollection(new ReferenceList("assays", new ArrayList(Arrays.asList(new Object[]{"57_709"})))); HashSet expected=new HashSet(Arrays.asList(new Object[]{expectedItem, expectedItem2})); MockItemWriter tgtIw = new MockItemWriter(new LinkedHashMap()); translator.translate(tgtIw); assertEquals(expected, tgtIw.getItems()); } public void testMicroArrayExperimentalResult() throws Exception { Item srcItem= createItem(ns+"BioAssayDatum", "58_762", ""); srcItem.addReference(new Reference("quantitationType","40_620")); srcItem.addAttribute(new Attribute("normalised","true")); Item srcItem1= createItem(ns+"Error", "40_620", ""); srcItem1.addAttribute(new Attribute("name", "Signal st dev Cy3")); srcItem1.addReference(new Reference("targetQuantitationType", "38_608")); Item srcItem2= createItem(ns+"MeasuredSignal", "38_608", ""); srcItem2.addAttribute(new Attribute("isBackground", "false")); srcItem2.addReference(new Reference("scale", "1_611")); Item srcItem3= createItem(ns+"OntologyEntry", "1_611", ""); srcItem3.addAttribute(new Attribute("value", "linear_scale")); Set src = new HashSet(Arrays.asList(new Object[]{srcItem, srcItem1, srcItem2, srcItem3})); Map srcMap = writeItems(src); MageDataTranslator translator = new MageDataTranslator(new MockItemReader(srcMap), mapping, srcModel, getTargetModel(tgtNs)); Item expectedItem = createItem(tgtNs+"MicroArrayExperimentalResult", "58_762", ""); expectedItem.addAttribute(new Attribute("normalised","true")); expectedItem.addAttribute(new Attribute("type","Signal st dev Cy3")); expectedItem.addAttribute(new Attribute("scale","linear_scale")); expectedItem.addAttribute(new Attribute("isBackground","false")); expectedItem.addReference(new Reference("analysis","-1_1")); Item expectedItem2 = createItem(tgtNs+"OntologyTerm", "1_611", ""); expectedItem2.addAttribute(new Attribute("name","linear_scale")); HashSet expected=new HashSet(Arrays.asList(new Object[]{expectedItem, expectedItem2})); MockItemWriter tgtIw = new MockItemWriter(new LinkedHashMap()); translator.translate(tgtIw); assertEquals(expected, tgtIw.getItems()); } public void testBioEntity() throws Exception { Item srcItem= createItem(ns+"BioSequence", "0_11", ""); srcItem.addReference(new Reference("type","1_13")); srcItem.addCollection(new ReferenceList("sequenceDatabases", new ArrayList(Arrays.asList(new Object[]{"2_14", "2_15", "2_16", "2_17"})))); Item srcItem1= createItem(ns+"OntologyEntry", "1_13", ""); srcItem1.addAttribute(new Attribute("value", "cDNA_clone")); Item srcItem2= createItem(ns+"DatabaseEntry", "2_14", ""); srcItem2.addAttribute(new Attribute("accession", "FBgn0010173")); srcItem2.addReference(new Reference("database", "3_7")); Item srcItem3= createItem(ns+"DatabaseEntry", "2_15", ""); srcItem3.addAttribute(new Attribute("accession", "AY069331")); srcItem3.addReference(new Reference("database", "3_9")); Item srcItem4= createItem(ns+"DatabaseEntry", "2_16", ""); srcItem4.addAttribute(new Attribute("accession", "AA201663")); srcItem4.addReference(new Reference("database", "3_9")); Item srcItem5= createItem(ns+"DatabaseEntry", "2_17", ""); srcItem5.addAttribute(new Attribute("accession", "AW941561")); srcItem5.addReference(new Reference("database", "3_9")); Item srcItem6= createItem(ns+"Database", "3_7", ""); srcItem6.addAttribute(new Attribute("name", "flybase")); Item srcItem7= createItem(ns+"Database", "3_9", ""); srcItem7.addAttribute(new Attribute("name", "embl")); Item srcItem10=createItem(ns+"Reporter", "12_50", ""); srcItem10.addAttribute(new Attribute("name","LD04815")); srcItem10.addCollection(new ReferenceList("featureReporterMaps", new ArrayList(Arrays.asList(new Object[]{"7_46"})))); srcItem10.addCollection(new ReferenceList("immobilizedCharacteristics", new ArrayList(Arrays.asList(new Object[]{"0_11"})))); Item srcItem11 = createItem(ns+"FeatureReporterMap", "7_46", ""); srcItem11.addReference(new Reference("reporter", "12_50")); srcItem11.addCollection(new ReferenceList("featureInformationSources", new ArrayList(Arrays.asList(new Object[]{"8_47"})))); Item srcItem12= createItem(ns+"FeatureInformation", "8_47", ""); srcItem12.addReference(new Reference("feature", "11_49")); Item srcItem13= createItem(ns+"Feature", "11_49", ""); srcItem13.addReference(new Reference("featureLocation", "9_480")); srcItem13.addReference(new Reference("zone", "10_290")); Item srcItem14= createItem(ns+"FeatureLocation", "9_480", ""); srcItem14.addAttribute(new Attribute("column", "1")); srcItem14.addAttribute(new Attribute("row", "3")); Item srcItem15= createItem(ns+"FeatureLocation", "10_290", ""); srcItem15.addAttribute(new Attribute("column", "2")); srcItem15.addAttribute(new Attribute("row", "5")); Item srcItem20= createItem(ns+"BioAssayDatum", "58_828", ""); srcItem20.addAttribute(new Attribute("normalised", "false")); srcItem20.addReference(new Reference("designElement", "11_49")); Item srcItem21= createItem(ns+"BioAssayDatum", "58_821", ""); srcItem21.addAttribute(new Attribute("normalised", "false")); srcItem21.addReference(new Reference("designElement", "11_49")); Item srcItem22= createItem(ns+"BioAssayDatum", "58_823", ""); srcItem22.addAttribute(new Attribute("normalised", "false")); srcItem22.addReference(new Reference("designElement", "11_49")); Item srcItem30=createItem(ns+"PhysicalArrayDesign", "20_69", ""); srcItem30.addCollection(new ReferenceList("featureGroups", new ArrayList(Arrays.asList(new Object[]{ "17_63"})))); Item srcItem31=createItem(ns+"FeatureGroup", "17_63", ""); srcItem31.addCollection(new ReferenceList("features", new ArrayList(Arrays.asList(new Object[]{"11_49"})))); Set src = new HashSet(Arrays.asList(new Object[]{srcItem, srcItem1, srcItem2, srcItem3, srcItem4, srcItem5, srcItem6, srcItem7, srcItem10, srcItem11, srcItem12, srcItem13, srcItem14, srcItem15, srcItem20, srcItem21, srcItem22, srcItem30, srcItem31 })); Map srcMap = writeItems(src); MageDataTranslator translator = new MageDataTranslator(new MockItemReader(srcMap), mapping, srcModel, getTargetModel(tgtNs)); Item expectedItem = createItem(tgtNs+"CDNAClone", "0_11", ""); expectedItem.addAttribute(new Attribute("identifier","LD04815")); expectedItem.addCollection(new ReferenceList("synonyms", new ArrayList(Arrays.asList(new Object[]{"2_15", "2_16", "2_17"})))); Item expectedItem1 = createItem(tgtNs+"Gene", "2_14", ""); expectedItem1.addAttribute(new Attribute("organismDbId", "FBgn0010173")); Item expectedItem2 = createItem(tgtNs+"Synonym", "2_15", ""); expectedItem2.addAttribute(new Attribute("type", "accession")); expectedItem2.addAttribute(new Attribute("value", "AY069331")); expectedItem2.addReference(new Reference("source", "-1_3")); expectedItem2.addReference(new Reference("subject", "0_11")); Item expectedItem3 = createItem(tgtNs+"Synonym", "2_16", ""); expectedItem3.addAttribute(new Attribute("type", "accession")); expectedItem3.addAttribute(new Attribute("value", "AA201663")); expectedItem3.addReference(new Reference("source", "-1_3")); expectedItem3.addReference(new Reference("subject", "0_11")); Item expectedItem4 = createItem(tgtNs+"Synonym", "2_17", ""); expectedItem4.addAttribute(new Attribute("type", "accession")); expectedItem4.addAttribute(new Attribute("value", "AW941561")); expectedItem4.addReference(new Reference("source", "-1_3")); expectedItem4.addReference(new Reference("subject", "0_11")); Item expectedItem5 = createItem(tgtNs+"OntologyTerm", "1_13", ""); expectedItem5.addAttribute(new Attribute("name", "cDNA_clone")); Item expectedItem7 = createItem(tgtNs+"Database", "-1_3", ""); expectedItem7.addAttribute(new Attribute("title", "embl")); Item expectedItem10 = createItem(tgtNs+"MicroArrayExperimentalResult", "58_821", ""); expectedItem10.addAttribute(new Attribute("normalised", "false")); expectedItem10.addReference(new Reference("analysis","-1_1")); expectedItem10.addReference(new Reference("material","0_11")); expectedItem10.addReference(new Reference("reporter","12_50")); expectedItem10.addCollection(new ReferenceList("genes", new ArrayList(Arrays.asList(new Object[]{"2_14"})))); Item expectedItem11 = createItem(tgtNs+"MicroArrayExperimentalResult", "58_823", ""); expectedItem11.addAttribute(new Attribute("normalised", "false")); expectedItem11.addReference(new Reference("analysis","-1_1")); expectedItem11.addReference(new Reference("material","0_11")); expectedItem11.addReference(new Reference("reporter","12_50")); expectedItem11.addCollection(new ReferenceList("genes", new ArrayList(Arrays.asList(new Object[]{"2_14"})))); Item expectedItem12 = createItem(tgtNs+"MicroArrayExperimentalResult", "58_828", ""); expectedItem12.addAttribute(new Attribute("normalised", "false")); expectedItem12.addReference(new Reference("analysis","-1_1")); expectedItem12.addReference(new Reference("material","0_11")); expectedItem12.addReference(new Reference("reporter","12_50")); expectedItem12.addCollection(new ReferenceList("genes", new ArrayList(Arrays.asList(new Object[]{"2_14"})))); Item expectedItem13 = createItem(tgtNs+"Reporter", "12_50", ""); expectedItem13.addReference(new Reference("material", "0_11")); expectedItem13.addReference(new Reference("location", "7_46")); Item expectedItem14 = createItem(tgtNs+"MicroArraySlideDesign", "20_69", ""); Item expectedItem15 = createItem(tgtNs + "ReporterLocation", "7_46", ""); expectedItem15.addAttribute(new Attribute("localX", "1")); expectedItem15.addAttribute(new Attribute("localY", "3")); expectedItem15.addAttribute(new Attribute("zoneX", "2")); expectedItem15.addAttribute(new Attribute("zoneY", "5")); expectedItem15.addReference(new Reference("design", "20_69")); expectedItem15.addReference(new Reference("reporter", "12_50")); HashSet expected=new HashSet(Arrays.asList(new Object[]{expectedItem, expectedItem1, expectedItem2,expectedItem3, expectedItem4, expectedItem5, expectedItem7,expectedItem10, expectedItem11, expectedItem12, expectedItem13, expectedItem14, expectedItem15 })); MockItemWriter tgtIw = new MockItemWriter(new LinkedHashMap()); translator.translate(tgtIw); assertEquals(expected, tgtIw.getItems()); } public void testBioEntity2MAER() throws Exception { Item srcItem= createItem(ns+"Reporter", "12_45", ""); srcItem.addCollection(new ReferenceList("featureReporterMaps", new ArrayList(Arrays.asList(new Object[]{"7_41"})))); srcItem.addCollection(new ReferenceList("immobilizedCharacteristics", new ArrayList(Arrays.asList(new Object[]{"0_3"})))); Item srcItem1= createItem(ns+"FeatureReporterMap", "7_41", ""); srcItem1.addCollection(new ReferenceList("featureInformationSources", new ArrayList(Arrays.asList(new Object[]{"8_42"})))); Item srcItem2= createItem(ns+"FeatureInformation", "8_42", ""); srcItem2.addReference(new Reference("feature", "9_43")); Item srcItem3= createItem(ns+"BioSequence", "0_3", ""); srcItem3.addReference(new Reference("type", "1_5")); Item srcItem4 =createItem(ns+"OntologyEntry", "1_5", ""); srcItem4.addAttribute(new Attribute("value", "cDNA_clone")); Set srcItems = new HashSet(Arrays.asList(new Object[] {srcItem, srcItem1, srcItem2, srcItem3, srcItem4})); Map itemMap = writeItems(srcItems); MageDataTranslator translator = new MageDataTranslator(new MockItemReader(itemMap), mapping, srcModel, getTargetModel(tgtNs)); Item tgtItem = createItem(tgtNs+"cDNAClone", "0_3", ""); Map expected = new HashMap(); expected.put("0_3", "9_43"); translator.setBioEntityMap(srcItem,tgtItem); assertEquals(expected, translator.bioEntity2Feature); } public void testBioEntity2Identifier() throws Exception { Item srcItem= createItem(ns+"Reporter", "12_45", ""); srcItem.addAttribute(new Attribute("name", "LD14383")); srcItem.addCollection(new ReferenceList("immobilizedCharacteristics", new ArrayList(Arrays.asList(new Object[]{"0_3"})))); srcItem.addCollection(new ReferenceList("featureReporterMaps", new ArrayList(Arrays.asList(new Object[]{"7_41"})))); Item srcItem1= createItem(ns+"FeatureReporterMap", "7_41", ""); srcItem1.addCollection(new ReferenceList("featureInformationSources", new ArrayList(Arrays.asList(new Object[]{"8_42"})))); Item srcItem2= createItem(ns+"FeatureInformation", "8_42", ""); srcItem2.addReference(new Reference("feature","11_44")); Item srcItem3= createItem(ns+"BioSequence", "0_3", ""); srcItem3.addReference(new Reference("type", "1_5")); Item srcItem4 =createItem(ns+"OntologyEntry", "1_5", ""); srcItem4.addAttribute(new Attribute("value", "cDNA_clone")); Set srcItems = new HashSet(Arrays.asList(new Object[] {srcItem, srcItem1,srcItem2, srcItem3, srcItem4})); Map itemMap = writeItems(srcItems); MageDataTranslator translator = new MageDataTranslator(new MockItemReader(itemMap), mapping, srcModel, getTargetModel(tgtNs)); Item tgtItem = createItem(tgtNs+"cDNAClone", "0_3", ""); Map expected = new HashMap(); expected.put("0_3", "LD14383"); translator.setBioEntityMap(srcItem,tgtItem); assertEquals(expected, translator.bioEntity2IdentifierMap); } protected Collection getSrcItems() throws Exception { BufferedReader srcReader = new BufferedReader(new InputStreamReader(getClass().getClassLoader().getResourceAsStream("test/MageTestData_adf.xml"))); MockItemWriter mockIw = new MockItemWriter(new LinkedHashMap()); MageConverter converter = new MageConverter(mockIw); converter.process(srcReader); //BufferedReader srcReader = new BufferedReader(new InputStreamReader(getClass().getClassLoader().getResourceAsStream("test/MageTestData_exp.xml"))); //converter = new MageConverter( mockIw); converter.process(srcReader); converter.close(); return mockIw.getItems(); } protected Collection getExpectedItems() throws Exception { Collection srcItems = getSrcItems(); Map itemMap = writeItems(srcItems); MageDataTranslator translator = new MageDataTranslator(new MockItemReader(itemMap), mapping, srcModel, getTargetModel(tgtNs)); MockItemWriter tgtIw = new MockItemWriter(new LinkedHashMap()); translator.translate(tgtIw); return tgtIw.getItems(); } protected String getModelName() { return "genomic"; } protected String getSrcModelName() { return "mage"; } private Item createItem(String className, String itemId, String implementation){ Item item=new Item(); item.setIdentifier(itemId); item.setClassName(className); item.setImplementations(implementation); return item; } }
flymine/model/mage/src/test/org/flymine/dataconversion/MageDataTranslatorTest.java
package org.flymine.dataconversion; /* * Copyright (C) 2002-2005 FlyMine * * This code may be freely distributed and modified under the * terms of the GNU Lesser General Public Licence. This should * be distributed with the code. See the LICENSE file for more * information or http://www.gnu.org/copyleft/lesser.html. * */ import junit.framework.TestCase; import java.util.Map; import java.util.HashMap; import java.util.Set; import java.util.HashSet; import java.util.List; import java.util.ArrayList; import java.util.LinkedHashSet; import java.util.LinkedHashMap; import java.util.Collection; import java.util.Arrays; import java.io.InputStreamReader; import java.io.FileWriter; import java.io.File; import java.io.BufferedReader; import org.intermine.xml.full.FullParser; import org.intermine.xml.full.FullRenderer; import org.intermine.xml.full.Attribute; import org.intermine.xml.full.Item; import org.intermine.xml.full.Reference; import org.intermine.xml.full.ReferenceList; import org.intermine.dataconversion.DataTranslator; import org.intermine.dataconversion.DataTranslatorTestCase; import org.intermine.dataconversion.MockItemReader; import org.intermine.dataconversion.MockItemWriter; /** * Test for translating MAGE data in fulldata Item format conforming to a source OWL definition * to fulldata Item format conforming to InterMine OWL definition. * * @author Wenyan Ji * @author Richard Smith */ public class MageDataTranslatorTest extends DataTranslatorTestCase { private String tgtNs = "http://www.flymine.org/model/genomic#"; private String ns = "http://www.flymine.org/model/mage#"; public MageDataTranslatorTest(String arg) { super(arg); } public void setUp() throws Exception { super.setUp(); } public void testTranslate() throws Exception { Collection srcItems = getSrcItems(); //FileWriter writerSrc = new FileWriter(new File("src_items.xml")); //writerSrc.write(FullRenderer.render(srcItems)); //writerSrc.close(); Map itemMap = writeItems(srcItems); DataTranslator translator = new MageDataTranslator(new MockItemReader(itemMap), mapping, srcModel, getTargetModel(tgtNs)); MockItemWriter tgtIw = new MockItemWriter(new LinkedHashMap()); translator.translate(tgtIw); //FileWriter writer = new FileWriter(new File("exptmp")); //writer.write(FullRenderer.render(tgtIw.getItems())); //writer.close(); //assertEquals(new HashSet(expectedItems), tgtIw.getItems()); } public void testCreateAuthors() throws Exception { Item srcItem = createItem(ns + "BibliographicReference", "0_0", ""); srcItem.addAttribute(new Attribute("authors", " William Whitfield; FlyChip Facility")); Item exp1 = createItem(tgtNs + "Author", "-1_1", ""); exp1.addAttribute(new Attribute("name", "William Whitfield")); Item exp2 = createItem(tgtNs + "Author", "-1_2", ""); exp2.addAttribute(new Attribute("name", "FlyChip Facility")); Set expected = new HashSet(Arrays.asList(new Object[] {exp1, exp2})); MageDataTranslator translator = new MageDataTranslator(new MockItemReader(new HashMap()), mapping, srcModel, getTargetModel(tgtNs)); assertEquals(expected, translator.createAuthors(srcItem)); } public void testSetReporterLocationCoords() throws Exception{ Item srcItem = createItem(ns + "FeatureReporterMap", "6_28", ""); srcItem.addCollection(new ReferenceList("featureInformationSources", new ArrayList(Arrays.asList(new Object[]{"7_29"})))); Item srcItem2=createItem(ns + "FeatureInformation", "7_29", ""); srcItem2. addReference(new Reference("feature", "8_30")); Item srcItem3=createItem(ns + "Feature", "8_30", ""); srcItem3.addReference(new Reference("featureLocation", "9_31")); srcItem3.addReference(new Reference("zone", "10_17")); Item srcItem4 = createItem(ns + "FeatureLocation", "9_31", ""); srcItem4.addAttribute(new Attribute("column", "1")); srcItem4.addAttribute(new Attribute("row", "2")); Item srcItem5 = createItem(ns + "Zone", "10_17", ""); srcItem5.addAttribute(new Attribute("column", "1")); srcItem5.addAttribute(new Attribute("row", "1")); Set srcItems = new HashSet(Arrays.asList(new Object[]{srcItem, srcItem2, srcItem3, srcItem4, srcItem5})); Map itemMap = writeItems(srcItems); MageDataTranslator translator = new MageDataTranslator(new MockItemReader(itemMap), mapping, srcModel, getTargetModel(tgtNs)); //MockItemWriter tgtIw = new MockItemWriter(new LinkedHashMap()); //translator.translate(tgtIw); Item tgtItem = createItem(tgtNs + "ReporterLocation", "6_28", ""); tgtItem.addAttribute(new Attribute("localX", "1")); tgtItem.addAttribute(new Attribute("localY", "2")); tgtItem.addAttribute(new Attribute("zoneX", "1")); tgtItem.addAttribute(new Attribute("zoneY", "1")); HashSet expected = new HashSet(Arrays.asList(new Object[]{tgtItem})); //assertEquals(expected, tgtIw.getItems()); Item destItem = createItem(tgtNs + "ReporterLocation", "6_28", ""); translator.setReporterLocationCoords(srcItem, destItem); assertEquals(tgtItem, destItem); } public void testCreateFeatureMap() throws Exception { Item srcItem1=createItem(ns + "PhysicalArrayDesign", "0_0", ""); ReferenceList rl1=new ReferenceList("featureGroups", new ArrayList(Arrays.asList(new Object[] {"1_1"}))); srcItem1.addCollection(rl1); Item srcItem2=createItem(ns + "FeatureGroup", "1_1", ""); ReferenceList rl2=new ReferenceList("features", new ArrayList(Arrays.asList(new Object[] {"1_2"}))); srcItem2.addCollection(rl2); Set srcItems = new HashSet(Arrays.asList(new Object[] {srcItem1, srcItem2})); Map itemMap = writeItems(srcItems); MageDataTranslator translator = new MageDataTranslator(new MockItemReader(itemMap), mapping, srcModel, getTargetModel(tgtNs)); Item tgtItem = createItem(tgtNs+"MicroArraySlideDesign", "0_0", ""); Map expected = new HashMap(); expected.put("1_2", "0_0"); translator.createFeatureMap(srcItem1); assertEquals(expected, translator.featureToDesign); } //test translate from PhysicalArrayDesign to MicroArraySlideDesign //which includes 3 methods, createFeatureMap, padDescriptions, and changeRefToAttr public void testTranslateMASD() throws Exception { Item srcItem1=createItem(ns + "PhysicalArrayDesign", "1_1", ""); srcItem1.addCollection(new ReferenceList("descriptions", new ArrayList(Arrays.asList(new Object[] {"1_2", "2_2"} )))); srcItem1.addReference(new Reference("surfaceType","1_11")); srcItem1.addCollection(new ReferenceList("featureGroups", new ArrayList(Arrays.asList(new Object[] {"1_12"})))); Item srcItem2=createItem(ns + "Description", "1_2", ""); srcItem2.addCollection(new ReferenceList("annotations", new ArrayList(Arrays.asList(new Object[] {"1_3", "1_4"})))); Item srcItem2a=createItem(ns + "Description", "2_2", ""); srcItem2a.addCollection(new ReferenceList("annotations", new ArrayList(Arrays.asList(new Object[] {"2_3", "2_4"})))); Item srcItem3=createItem(ns + "OntologyEntry", "1_3", ""); srcItem3.addAttribute(new Attribute("value", "double")); Item srcItem4=createItem(ns + "SurfaceType", "1_11", ""); srcItem4.addAttribute(new Attribute("value", "polylysine")); Item srcItem5=createItem(ns + "FeatureGroup", "1_12", ""); srcItem5.addCollection(new ReferenceList("features", new ArrayList(Arrays.asList(new Object[] {"1_13"})))); Set srcItems = new HashSet(Arrays.asList(new Object[] {srcItem1, srcItem2, srcItem2a, srcItem3, srcItem4, srcItem5})); Map itemMap = writeItems(srcItems); MageDataTranslator translator = new MageDataTranslator(new MockItemReader(itemMap), mapping, srcModel, getTargetModel(tgtNs)); //MockItemWriter tgtIw = new MockItemWriter(new LinkedHashMap()); //translator.translate(tgtIw); // expected items // MicroArraySlideDesign 1_1 Item expectedItem=createItem(tgtNs + "MicroArraySlideDesign", "1_1", ""); expectedItem.addCollection(new ReferenceList("descriptions", new ArrayList(Arrays.asList(new Object[] {"1_3", "1_4", "2_3", "2_4"})))); expectedItem.addAttribute(new Attribute("surfaceType", "polylysine")); HashSet expected = new HashSet(Arrays.asList(new Object[]{expectedItem})); assertEquals(expected, translator.translateItem(srcItem1)); } public void testMicroArrayExperiment()throws Exception { Item srcItem = createItem(ns+"Experiment", "61_748", ""); srcItem.addAttribute(new Attribute("name", "P10005")); srcItem.addCollection(new ReferenceList("bioAssays", new ArrayList(Arrays.asList(new Object[]{"33_603", "57_709", "43_654"})))); srcItem.addCollection(new ReferenceList("descriptions", new ArrayList(Arrays.asList(new Object[]{"12_749", "12_750"})))); Item srcItem1= createItem(ns+"MeasuredBioAssay", "33_603", ""); srcItem1.addReference(new Reference("featureExtraction", "4_2")); Item srcItem2= createItem(ns+"DerivedBioAssay", "57_709", ""); srcItem2.addReference(new Reference("featureExtraction", "4_2")); Item srcItem3= createItem(ns+"PhysicalBioAssay", "43_654", ""); srcItem3.addReference(new Reference("featureExtraction", "4_2")); Item srcItem4= createItem(ns+"Description", "12_749", ""); srcItem4.addAttribute(new Attribute("text", "experiment description")); Item srcItem5= createItem(ns+"Description", "12_750", ""); srcItem5.addCollection(new ReferenceList("bibliographicReferences", new ArrayList(Arrays.asList(new Object[]{"62_751"})))); Set src = new HashSet(Arrays.asList(new Object[]{srcItem, srcItem1, srcItem2, srcItem3, srcItem4, srcItem5})); Map srcMap = writeItems(src); MageDataTranslator translator = new MageDataTranslator(new MockItemReader(srcMap), mapping, srcModel, getTargetModel(tgtNs)); Item expectedItem =createItem(tgtNs+"MicroArrayExperiment", "61_748", ""); expectedItem.addAttribute(new Attribute("name", "P10005")); expectedItem.addAttribute(new Attribute("description", "experiment description")); expectedItem.addReference(new Reference("publication", "62_751")); //expectedItem.addCollection(new ReferenceList("assays", new ArrayList(Arrays.asList(new Object[]{"57_709"})))); HashSet expected=new HashSet(Arrays.asList(new Object[]{expectedItem})); assertEquals(expected, translator.translateItem(srcItem)); } public void testMicroArrayAssay() throws Exception{ Item srcItem= createItem(ns+"DerivedBioAssay", "57_709", ""); srcItem.addCollection(new ReferenceList("derivedBioAssayData", new ArrayList(Arrays.asList(new Object[]{"58_710"})))); Item srcItem1= createItem(ns+"DerivedBioAssayData", "58_710", ""); srcItem1.addReference(new Reference("bioDataValues", "58_739")); Item srcItem2= createItem(ns+"BioDataTuples", "58_739", ""); srcItem2.addCollection(new ReferenceList("bioAssayTupleData", new ArrayList(Arrays.asList(new Object[]{"58_740", "58_744", "58_755"})))); Item srcItem10 = createItem(ns+"Experiment", "61_748", ""); srcItem10.addCollection(new ReferenceList("bioAssays", new ArrayList(Arrays.asList(new Object[]{"33_603", "57_709", "43_654"})))); Item srcItem11= createItem(ns+"MeasuredBioAssay", "33_603", ""); srcItem11.addReference(new Reference("featureExtraction", "4_2")); Item srcItem13= createItem(ns+"PhysicalBioAssay", "43_654", ""); srcItem13.addReference(new Reference("bioAssayCreation", "50_735")); Item srcItem14= createItem(ns+"Hybridization", "50_735", ""); srcItem14.addCollection(new ReferenceList("sourceBioMaterialMeasurements", new ArrayList(Arrays.asList(new Object[]{"26_736", "26_737"})))); Item srcItem15= createItem(ns+"BioMaterialMeasurement", "26_736", ""); srcItem15.addReference(new Reference("bioMaterial", "23_78")); Item srcItem16= createItem(ns+"BioMaterialMeasurement", "26_737", ""); srcItem16.addReference(new Reference("bioMaterial", "23_146")); Set src = new HashSet(Arrays.asList(new Object[]{srcItem, srcItem1, srcItem2,srcItem10, srcItem11, srcItem13, srcItem14, srcItem15, srcItem16 })); Map srcMap = writeItems(src); MageDataTranslator translator = new MageDataTranslator(new MockItemReader(srcMap), mapping, srcModel, getTargetModel(tgtNs)); Item expectedItem = createItem(tgtNs+"MicroArrayAssay", "57_709", ""); //expectedItem.addCollection(new ReferenceList("results", new ArrayList(Arrays.asList(new Object[]{"58_740", "58_744", "58_755"})))); //expectedItem.addCollection(new ReferenceList("tissues", new ArrayList(Arrays.asList(new Object[]{"23_78", "23_146"})))); expectedItem.addReference(new Reference("experiment", "61_748")); Item expectedItem2 =createItem(tgtNs+"MicroArrayExperiment", "61_748", ""); //expectedItem2.addCollection(new ReferenceList("assays", new ArrayList(Arrays.asList(new Object[]{"57_709"})))); HashSet expected=new HashSet(Arrays.asList(new Object[]{expectedItem, expectedItem2})); MockItemWriter tgtIw = new MockItemWriter(new LinkedHashMap()); translator.translate(tgtIw); assertEquals(expected, tgtIw.getItems()); } public void testMicroArrayExperimentalResult() throws Exception { Item srcItem= createItem(ns+"BioAssayDatum", "58_762", ""); srcItem.addReference(new Reference("quantitationType","40_620")); srcItem.addAttribute(new Attribute("normalised","true")); Item srcItem1= createItem(ns+"Error", "40_620", ""); srcItem1.addAttribute(new Attribute("name", "Signal st dev Cy3")); srcItem1.addReference(new Reference("targetQuantitationType", "38_608")); Item srcItem2= createItem(ns+"MeasuredSignal", "38_608", ""); srcItem2.addAttribute(new Attribute("isBackground", "false")); srcItem2.addReference(new Reference("scale", "1_611")); Item srcItem3= createItem(ns+"OntologyEntry", "1_611", ""); srcItem3.addAttribute(new Attribute("value", "linear_scale")); Set src = new HashSet(Arrays.asList(new Object[]{srcItem, srcItem1, srcItem2, srcItem3})); Map srcMap = writeItems(src); MageDataTranslator translator = new MageDataTranslator(new MockItemReader(srcMap), mapping, srcModel, getTargetModel(tgtNs)); Item expectedItem = createItem(tgtNs+"MicroArrayExperimentalResult", "58_762", ""); expectedItem.addAttribute(new Attribute("normalised","true")); expectedItem.addAttribute(new Attribute("type","Signal st dev Cy3")); expectedItem.addAttribute(new Attribute("scale","linear_scale")); expectedItem.addAttribute(new Attribute("isBackground","false")); expectedItem.addReference(new Reference("analysis","-1_1")); Item expectedItem2 = createItem(tgtNs+"OntologyTerm", "1_611", ""); expectedItem2.addAttribute(new Attribute("name","linear_scale")); HashSet expected=new HashSet(Arrays.asList(new Object[]{expectedItem, expectedItem2})); MockItemWriter tgtIw = new MockItemWriter(new LinkedHashMap()); translator.translate(tgtIw); assertEquals(expected, tgtIw.getItems()); } public void testBioEntity() throws Exception { Item srcItem= createItem(ns+"BioSequence", "0_11", ""); srcItem.addReference(new Reference("type","1_13")); srcItem.addCollection(new ReferenceList("sequenceDatabases", new ArrayList(Arrays.asList(new Object[]{"2_14", "2_15", "2_16", "2_17"})))); Item srcItem1= createItem(ns+"OntologyEntry", "1_13", ""); srcItem1.addAttribute(new Attribute("value", "cDNA_clone")); Item srcItem2= createItem(ns+"DatabaseEntry", "2_14", ""); srcItem2.addAttribute(new Attribute("accession", "FBgn0010173")); srcItem2.addReference(new Reference("database", "3_7")); Item srcItem3= createItem(ns+"DatabaseEntry", "2_15", ""); srcItem3.addAttribute(new Attribute("accession", "AY069331")); srcItem3.addReference(new Reference("database", "3_9")); Item srcItem4= createItem(ns+"DatabaseEntry", "2_16", ""); srcItem4.addAttribute(new Attribute("accession", "AA201663")); srcItem4.addReference(new Reference("database", "3_9")); Item srcItem5= createItem(ns+"DatabaseEntry", "2_17", ""); srcItem5.addAttribute(new Attribute("accession", "AW941561")); srcItem5.addReference(new Reference("database", "3_9")); Item srcItem6= createItem(ns+"Database", "3_7", ""); srcItem6.addAttribute(new Attribute("name", "flybase")); Item srcItem7= createItem(ns+"Database", "3_9", ""); srcItem7.addAttribute(new Attribute("name", "embl")); Item srcItem10=createItem(ns+"Reporter", "12_50", ""); srcItem10.addAttribute(new Attribute("name","LD04815")); srcItem10.addCollection(new ReferenceList("featureReporterMaps", new ArrayList(Arrays.asList(new Object[]{"7_46"})))); srcItem10.addCollection(new ReferenceList("immobilizedCharacteristics", new ArrayList(Arrays.asList(new Object[]{"0_11"})))); Item srcItem11 = createItem(ns+"FeatureReporterMap", "7_46", ""); srcItem11.addReference(new Reference("reporter", "12_50")); srcItem11.addCollection(new ReferenceList("featureInformationSources", new ArrayList(Arrays.asList(new Object[]{"8_47"})))); Item srcItem12= createItem(ns+"FeatureInformation", "8_47", ""); srcItem12.addReference(new Reference("feature", "11_49")); Item srcItem13= createItem(ns+"Feature", "11_49", ""); srcItem13.addReference(new Reference("featureLocation", "9_480")); srcItem13.addReference(new Reference("zone", "10_290")); Item srcItem14= createItem(ns+"FeatureLocation", "9_480", ""); srcItem14.addAttribute(new Attribute("column", "1")); srcItem14.addAttribute(new Attribute("row", "3")); Item srcItem15= createItem(ns+"FeatureLocation", "10_290", ""); srcItem15.addAttribute(new Attribute("column", "2")); srcItem15.addAttribute(new Attribute("row", "5")); Item srcItem20= createItem(ns+"BioAssayDatum", "58_828", ""); srcItem20.addAttribute(new Attribute("normalised", "false")); srcItem20.addReference(new Reference("designElement", "11_49")); Item srcItem21= createItem(ns+"BioAssayDatum", "58_821", ""); srcItem21.addAttribute(new Attribute("normalised", "false")); srcItem21.addReference(new Reference("designElement", "11_49")); Item srcItem22= createItem(ns+"BioAssayDatum", "58_823", ""); srcItem22.addAttribute(new Attribute("normalised", "false")); srcItem22.addReference(new Reference("designElement", "11_49")); Item srcItem30=createItem(ns+"PhysicalArrayDesign", "20_69", ""); srcItem30.addCollection(new ReferenceList("featureGroups", new ArrayList(Arrays.asList(new Object[]{ "17_63"})))); Item srcItem31=createItem(ns+"FeatureGroup", "17_63", ""); srcItem31.addCollection(new ReferenceList("features", new ArrayList(Arrays.asList(new Object[]{"11_49"})))); Set src = new HashSet(Arrays.asList(new Object[]{srcItem, srcItem1, srcItem2, srcItem3, srcItem4, srcItem5, srcItem6, srcItem7, srcItem10, srcItem11, srcItem12, srcItem13, srcItem14, srcItem15, srcItem20, srcItem21, srcItem22, srcItem30, srcItem31 })); Map srcMap = writeItems(src); MageDataTranslator translator = new MageDataTranslator(new MockItemReader(srcMap), mapping, srcModel, getTargetModel(tgtNs)); Item expectedItem = createItem(tgtNs+"CDNAClone", "0_11", ""); expectedItem.addAttribute(new Attribute("identifier","LD04815")); expectedItem.addCollection(new ReferenceList("synonyms", new ArrayList(Arrays.asList(new Object[]{"2_15", "2_16", "2_17"})))); Item expectedItem1 = createItem(tgtNs+"Gene", "2_14", ""); expectedItem1.addAttribute(new Attribute("organismDbId", "FBgn0010173")); Item expectedItem2 = createItem(tgtNs+"Synonym", "2_15", ""); expectedItem2.addAttribute(new Attribute("type", "accession")); expectedItem2.addAttribute(new Attribute("value", "AY069331")); expectedItem2.addReference(new Reference("source", "-1_3")); expectedItem2.addReference(new Reference("subject", "0_11")); Item expectedItem3 = createItem(tgtNs+"Synonym", "2_16", ""); expectedItem3.addAttribute(new Attribute("type", "accession")); expectedItem3.addAttribute(new Attribute("value", "AA201663")); expectedItem3.addReference(new Reference("source", "-1_3")); expectedItem3.addReference(new Reference("subject", "0_11")); Item expectedItem4 = createItem(tgtNs+"Synonym", "2_17", ""); expectedItem4.addAttribute(new Attribute("type", "accession")); expectedItem4.addAttribute(new Attribute("value", "AW941561")); expectedItem4.addReference(new Reference("source", "-1_3")); expectedItem4.addReference(new Reference("subject", "0_11")); Item expectedItem5 = createItem(tgtNs+"OntologyTerm", "1_13", ""); expectedItem5.addAttribute(new Attribute("name", "cDNA_clone")); Item expectedItem7 = createItem(tgtNs+"Database", "-1_3", ""); expectedItem7.addAttribute(new Attribute("title", "embl")); Item expectedItem10 = createItem(tgtNs+"MicroArrayExperimentalResult", "58_821", ""); expectedItem10.addAttribute(new Attribute("normalised", "false")); expectedItem10.addReference(new Reference("analysis","-1_1")); expectedItem10.addReference(new Reference("material","0_11")); expectedItem10.addReference(new Reference("reporter","12_50")); expectedItem10.addCollection(new ReferenceList("genes", new ArrayList(Arrays.asList(new Object[]{"2_14"})))); Item expectedItem11 = createItem(tgtNs+"MicroArrayExperimentalResult", "58_823", ""); expectedItem11.addAttribute(new Attribute("normalised", "false")); expectedItem11.addReference(new Reference("analysis","-1_1")); expectedItem11.addReference(new Reference("material","0_11")); expectedItem11.addReference(new Reference("reporter","12_50")); expectedItem11.addCollection(new ReferenceList("genes", new ArrayList(Arrays.asList(new Object[]{"2_14"})))); Item expectedItem12 = createItem(tgtNs+"MicroArrayExperimentalResult", "58_828", ""); expectedItem12.addAttribute(new Attribute("normalised", "false")); expectedItem12.addReference(new Reference("analysis","-1_1")); expectedItem12.addReference(new Reference("material","0_11")); expectedItem12.addReference(new Reference("reporter","12_50")); expectedItem12.addCollection(new ReferenceList("genes", new ArrayList(Arrays.asList(new Object[]{"2_14"})))); Item expectedItem13 = createItem(tgtNs+"Reporter", "12_50", ""); expectedItem13.addReference(new Reference("material", "0_11")); expectedItem13.addReference(new Reference("location", "7_46")); Item expectedItem14 = createItem(tgtNs+"MicroArraySlideDesign", "20_69", ""); Item expectedItem15 = createItem(tgtNs + "ReporterLocation", "7_46", ""); expectedItem15.addAttribute(new Attribute("localX", "1")); expectedItem15.addAttribute(new Attribute("localY", "3")); expectedItem15.addAttribute(new Attribute("zoneX", "2")); expectedItem15.addAttribute(new Attribute("zoneY", "5")); expectedItem15.addReference(new Reference("design", "20_69")); expectedItem15.addReference(new Reference("reporter", "12_50")); HashSet expected=new HashSet(Arrays.asList(new Object[]{expectedItem, expectedItem1, expectedItem2,expectedItem3, expectedItem4, expectedItem5, expectedItem7,expectedItem10, expectedItem11, expectedItem12, expectedItem13, expectedItem14, expectedItem15 })); MockItemWriter tgtIw = new MockItemWriter(new LinkedHashMap()); translator.translate(tgtIw); assertEquals(expected, tgtIw.getItems()); } public void testBioEntity2MAER() throws Exception { Item srcItem= createItem(ns+"Reporter", "12_45", ""); srcItem.addCollection(new ReferenceList("featureReporterMaps", new ArrayList(Arrays.asList(new Object[]{"7_41"})))); srcItem.addCollection(new ReferenceList("immobilizedCharacteristics", new ArrayList(Arrays.asList(new Object[]{"0_3"})))); Item srcItem1= createItem(ns+"FeatureReporterMap", "7_41", ""); srcItem1.addCollection(new ReferenceList("featureInformationSources", new ArrayList(Arrays.asList(new Object[]{"8_42"})))); Item srcItem2= createItem(ns+"FeatureInformation", "8_42", ""); srcItem2.addReference(new Reference("feature", "9_43")); Item srcItem3= createItem(ns+"BioSequence", "0_3", ""); srcItem3.addReference(new Reference("type", "1_5")); Item srcItem4 =createItem(ns+"OntologyEntry", "1_5", ""); srcItem4.addAttribute(new Attribute("value", "cDNA_clone")); Set srcItems = new HashSet(Arrays.asList(new Object[] {srcItem, srcItem1, srcItem2, srcItem3, srcItem4})); Map itemMap = writeItems(srcItems); MageDataTranslator translator = new MageDataTranslator(new MockItemReader(itemMap), mapping, srcModel, getTargetModel(tgtNs)); Item tgtItem = createItem(tgtNs+"cDNAClone", "0_3", ""); Map expected = new HashMap(); expected.put("0_3", "9_43"); translator.setBioEntityMap(srcItem,tgtItem); assertEquals(expected, translator.bioEntity2Feature); } public void testBioEntity2Identifier() throws Exception { Item srcItem= createItem(ns+"Reporter", "12_45", ""); srcItem.addAttribute(new Attribute("name", "LD14383")); srcItem.addCollection(new ReferenceList("immobilizedCharacteristics", new ArrayList(Arrays.asList(new Object[]{"0_3"})))); srcItem.addCollection(new ReferenceList("featureReporterMaps", new ArrayList(Arrays.asList(new Object[]{"7_41"})))); Item srcItem1= createItem(ns+"FeatureReporterMap", "7_41", ""); srcItem1.addCollection(new ReferenceList("featureInformationSources", new ArrayList(Arrays.asList(new Object[]{"8_42"})))); Item srcItem2= createItem(ns+"FeatureInformation", "8_42", ""); srcItem2.addReference(new Reference("feature","11_44")); Item srcItem3= createItem(ns+"BioSequence", "0_3", ""); srcItem3.addReference(new Reference("type", "1_5")); Item srcItem4 =createItem(ns+"OntologyEntry", "1_5", ""); srcItem4.addAttribute(new Attribute("value", "cDNA_clone")); Set srcItems = new HashSet(Arrays.asList(new Object[] {srcItem, srcItem1,srcItem2, srcItem3, srcItem4})); Map itemMap = writeItems(srcItems); MageDataTranslator translator = new MageDataTranslator(new MockItemReader(itemMap), mapping, srcModel, getTargetModel(tgtNs)); Item tgtItem = createItem(tgtNs+"cDNAClone", "0_3", ""); Map expected = new HashMap(); expected.put("0_3", "LD14383"); translator.setBioEntityMap(srcItem,tgtItem); assertEquals(expected, translator.bioEntity2IdentifierMap); } protected Collection getSrcItems() throws Exception { BufferedReader srcReader = new BufferedReader(new InputStreamReader(getClass().getClassLoader().getResourceAsStream("test/MageTestData_adf.xml"))); MockItemWriter mockIw = new MockItemWriter(new LinkedHashMap()); MageConverter converter = new MageConverter(mockIw, new HashSet()); converter.process(srcReader); //BufferedReader srcReader = new BufferedReader(new InputStreamReader(getClass().getClassLoader().getResourceAsStream("test/MageTestData_exp.xml"))); //converter = new MageConverter( mockIw); converter.process(srcReader); converter.close(); return mockIw.getItems(); } protected Collection getExpectedItems() throws Exception { Collection srcItems = getSrcItems(); Map itemMap = writeItems(srcItems); MageDataTranslator translator = new MageDataTranslator(new MockItemReader(itemMap), mapping, srcModel, getTargetModel(tgtNs)); MockItemWriter tgtIw = new MockItemWriter(new LinkedHashMap()); translator.translate(tgtIw); return tgtIw.getItems(); } protected String getModelName() { return "genomic"; } protected String getSrcModelName() { return "mage"; } private Item createItem(String className, String itemId, String implementation){ Item item=new Item(); item.setIdentifier(itemId); item.setClassName(className); item.setImplementations(implementation); return item; } }
corrected MageCOnverter constructor
flymine/model/mage/src/test/org/flymine/dataconversion/MageDataTranslatorTest.java
corrected MageCOnverter constructor
<ide><path>lymine/model/mage/src/test/org/flymine/dataconversion/MageDataTranslatorTest.java <ide> protected Collection getSrcItems() throws Exception { <ide> BufferedReader srcReader = new BufferedReader(new InputStreamReader(getClass().getClassLoader().getResourceAsStream("test/MageTestData_adf.xml"))); <ide> MockItemWriter mockIw = new MockItemWriter(new LinkedHashMap()); <del> MageConverter converter = new MageConverter(mockIw, new HashSet()); <add> MageConverter converter = new MageConverter(mockIw); <ide> converter.process(srcReader); <ide> <ide>
Java
apache-2.0
58085f00dcefa48d51cef01f619ecc7051c42c21
0
SpineEventEngine/core-java,SpineEventEngine/core-java,SpineEventEngine/core-java
/* * Copyright 2017, TeamDev Ltd. All rights reserved. * * Redistribution and use in source and/or binary forms, with or without * modification, must retain the above copyright notice and the following * disclaimer. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ package org.spine3.server.projection; import com.google.common.collect.ImmutableSet; import com.google.protobuf.BoolValue; import com.google.protobuf.Int32Value; import com.google.protobuf.Message; import com.google.protobuf.StringValue; import org.junit.Before; import org.junit.Test; import org.spine3.base.EventContext; import org.spine3.server.event.Subscribe; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertTrue; import static org.spine3.base.Identifiers.newUuid; import static org.spine3.protobuf.Values.newIntValue; import static org.spine3.protobuf.Values.newStringValue; @SuppressWarnings("InstanceMethodNamingConvention") public class ProjectionShould { private TestProjection projection; @Before public void setUp() { projection = org.spine3.test.Given.projectionOfClass(TestProjection.class) .withId(newUuid()) .withVersion(1) .withState(newStringValue("Initial state")) .build(); } @Test public void handle_events() { final String stringValue = newUuid(); projection.handle(newStringValue(stringValue), EventContext.getDefaultInstance()); assertTrue(projection.getState() .getValue() .contains(stringValue)); final Integer integerValue = 1024; projection.handle(newIntValue(integerValue), EventContext.getDefaultInstance()); assertTrue(projection.getState() .getValue() .contains(String.valueOf(integerValue))); } @Test(expected = IllegalStateException.class) public void throw_exception_if_no_handler_for_event() { projection.handle(BoolValue.getDefaultInstance(), EventContext.getDefaultInstance()); } @Test public void return_event_classes_which_it_handles() { final ImmutableSet<Class<? extends Message>> classes = Projection.getEventClasses(TestProjection.class); assertEquals(TestProjection.HANDLING_EVENT_COUNT, classes.size()); assertTrue(classes.contains(StringValue.class)); assertTrue(classes.contains(Int32Value.class)); } private static class TestProjection extends Projection<String, StringValue> { /** The number of events this class handles. */ private static final int HANDLING_EVENT_COUNT = 2; protected TestProjection(String id) { super(id); } @Subscribe public void on(StringValue event, EventContext ignored) { final StringValue newSate = createNewState("stringState", event.getValue()); incrementState(newSate); } @Subscribe public void on(Int32Value event) { final StringValue newSate = createNewState("integerState", String.valueOf(event.getValue())); incrementState(newSate); } private StringValue createNewState(String type, String value) { final String currentState = getState().getValue(); final String result = currentState + (currentState.length() > 0 ? " + " : "") + type + '(' + value + ')' + System.lineSeparator(); return newStringValue(result); } } }
server/src/test/java/org/spine3/server/projection/ProjectionShould.java
/* * Copyright 2017, TeamDev Ltd. All rights reserved. * * Redistribution and use in source and/or binary forms, with or without * modification, must retain the above copyright notice and the following * disclaimer. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ package org.spine3.server.projection; import com.google.common.collect.ImmutableSet; import com.google.protobuf.BoolValue; import com.google.protobuf.Int32Value; import com.google.protobuf.Message; import com.google.protobuf.StringValue; import org.junit.Before; import org.junit.Test; import org.spine3.base.EventContext; import org.spine3.server.event.Subscribe; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertTrue; import static org.spine3.base.Identifiers.newUuid; import static org.spine3.protobuf.Values.newIntValue; import static org.spine3.protobuf.Values.newStringValue; @SuppressWarnings("InstanceMethodNamingConvention") public class ProjectionShould { private TestProjection projection; @Before public void setUp() { projection = org.spine3.test.Given.projectionOfClass(TestProjection.class) .withId(newUuid()) .withVersion(1) .withState(newStringValue("Initial state")) .build(); } @Test public void handle_events() { final String stringValue = newUuid(); projection.handle(newStringValue(stringValue), EventContext.getDefaultInstance()); assertTrue(projection.getState() .getValue() .contains(stringValue)); final Integer integerValue = 1024; projection.handle(newIntValue(integerValue), EventContext.getDefaultInstance()); assertTrue(projection.getState() .getValue() .contains(String.valueOf(integerValue))); } @Test(expected = IllegalStateException.class) public void throw_exception_if_no_handler_for_event() { projection.handle(BoolValue.getDefaultInstance(), EventContext.getDefaultInstance()); } @Test public void return_event_classes_which_it_handles() { final ImmutableSet<Class<? extends Message>> classes = Projection.getEventClasses(TestProjection.class); assertEquals(TestProjection.HANDLING_EVENT_COUNT, classes.size()); assertTrue(classes.contains(StringValue.class)); assertTrue(classes.contains(Int32Value.class)); } private static class TestProjection extends Projection<String, StringValue> { /** The number of events this class handles. */ private static final int HANDLING_EVENT_COUNT = 2; protected TestProjection(String id) { super(id); } @Subscribe public void on(StringValue event, EventContext ignored) { final StringValue newSate = createNewState("stringState", event.getValue()); incrementState(newSate); } @Subscribe public void on(Int32Value event) { final StringValue newSate = createNewState("integerState", String.valueOf(event.getValue())); incrementState(newSate); } private StringValue createNewState(String type, String value) { final String currentState = getState().getValue(); final String result = currentState + (currentState.length() > 0 ? " + " : "") + type + '(' + value + ')' + System.lineSeparator(); return newStringValue(result); } } }
Yet more alignment.
server/src/test/java/org/spine3/server/projection/ProjectionShould.java
Yet more alignment.
<ide><path>erver/src/test/java/org/spine3/server/projection/ProjectionShould.java <ide> @Before <ide> public void setUp() { <ide> projection = org.spine3.test.Given.projectionOfClass(TestProjection.class) <del> .withId(newUuid()) <del> .withVersion(1) <del> .withState(newStringValue("Initial state")) <del> .build(); <add> .withId(newUuid()) <add> .withVersion(1) <add> .withState(newStringValue("Initial state")) <add> .build(); <ide> } <ide> <ide> @Test
Java
mit
eeaedc09268c3cc0512c2e0894bdb1658411f841
0
DayNoone/DinSykkelvei
package com.mobile.countme.implementation.controllers; import android.content.Intent; import android.content.res.Configuration; import android.content.res.Resources; import android.os.Bundle; import android.support.v4.view.ViewPager; import android.support.v7.widget.Toolbar; import android.util.DisplayMetrics; import android.util.Log; import android.view.Menu; import android.view.MenuItem; import android.view.View; import com.mobile.countme.R; import com.mobile.countme.framework.AppMenu; import com.mobile.countme.framework.MainViewPagerAdapter; import com.mobile.countme.framework.SlidingTabLayout; import com.mobile.countme.implementation.AndroidFileIO; import com.mobile.countme.implementation.menus.BikingActive; import com.mobile.countme.implementation.models.EnvironmentModel; import java.util.Locale; /** * Created by Kristian on 16/09/2015. */ public class MainPages extends AppMenu { Toolbar toolbar; ViewPager pager; MainViewPagerAdapter adapter; SlidingTabLayout tabs; CharSequence Titles[]; int Numboftabs =4; AndroidFileIO fileIO; // File IO to save and get internally saved statistics. private int[] places = new int[]{1 , 10, 100, 1000, 10000, 100000, 1000000}; /** * The models in the MVC architecture. */ EnvironmentModel environmentModel; public void onCreate(Bundle savedInstanceBundle){ super.onCreate(savedInstanceBundle); setContentView(R.layout.main_activity); Titles= new CharSequence[]{ getResources().getString(R.string.biking_idle), getResources().getString(R.string.environment_page), getResources().getString(R.string.statistics_page), getResources().getString(R.string.info_page)}; toolbar = (Toolbar) findViewById(R.id.main_tool_bar); setSupportActionBar(toolbar); // Creating The ViewPagerAdapter and Passing Fragment Manager, Titles fot the Tabs and Number Of Tabs. adapter = new MainViewPagerAdapter(getSupportFragmentManager(),Titles,Numboftabs); // Assigning ViewPager View and setting the adapter pager = (ViewPager) findViewById(R.id.main_pager); pager.setAdapter(adapter); // Assiging the Sliding Tab Layout View tabs = (SlidingTabLayout) findViewById(R.id.main_tabs); tabs.setDistributeEvenly(true); // To make the Tabs Fixed set this true, This makes the tabs Space Evenly in Available width // Setting Custom Color for the Scroll bar indicator of the Tab View tabs.setCustomTabColorizer(new SlidingTabLayout.TabColorizer() { @Override public int getIndicatorColor(int position) { return getResources().getColor(R.color.TabScroller); } }); // Setting the ViewPager For the SlidingTabsLayout tabs.setViewPager(pager); //Not functional ( view is not made yet) //((TextView) findViewById(R.id.start_tur)).setTypeface(Assets.getTypeface(this, Assets.baskerville_old_face_regular)); //Instantiate the models and load the internal statistics environmentModel = new EnvironmentModel(this); loadStatistics(); getUser().setMainPages(this); } @Override public boolean onCreateOptionsMenu(Menu menu) { // Inflate the menu; this adds items to the action bar if it is present. getMenuInflater().inflate(R.menu.menu_main, menu); return true; } @Override public boolean onOptionsItemSelected(MenuItem item) { // Handle action bar item clicks here. The action bar will // automatically handle clicks on the Home/Up button, so long // as you specify a parent activity in AndroidManifest.xml. int id = item.getItemId(); Log.w("onOptionsItemSelected", "Start of method"); //noinspection SimplifiableIfStatement if (id == R.id.action_settings) { return true; } else if (id == R.id.lang_norwegian) { setLocale("no"); return true; } else if (id == R.id.lang_english) { Log.w("MainPages, itemSelected", "Setting language to english"); setLocale("en"); return true; } return super.onOptionsItemSelected(item); } public void goToIntroduction(View view){ goTo(IntroductionMenu.class); } public void startBiking(View view) { goTo(BikingActive.class); } public void setLocale(String lang) { Locale locale = new Locale(lang); Resources res = getResources(); DisplayMetrics dm = res.getDisplayMetrics(); Configuration conf = res.getConfiguration(); conf.locale = locale; res.updateConfiguration(conf, dm); Intent refresh = new Intent(this, MainPages.class); startActivity(refresh); finish(); } /** * Loads the environmental statistics of the user from phones internal storage */ public void loadStatistics(){ String environmentStatistics = fileIO.readEnvironmentSaveFile(); Log.w("User","loadStatistics: " + environmentStatistics); Character charAt; int positionInList = 0; int tempValue = 0; String tempString = ""; //For every char in statistics for (int i = 0; i < environmentStatistics.length(); i++){ charAt = environmentStatistics.charAt(i); if(charAt == '@'){ break; } //If the charAt pos i is the separation char '#' then // add current temp value to the statList and move on to the next stat. if(charAt == '#'){ for (int l=0; l < tempString.length(); l++) { tempValue += Character.getNumericValue(tempString.charAt(l)) * places[(tempString.length() - 1) - l]; } environmentModel.setStat(positionInList, tempValue); positionInList += 1; tempValue = 0; tempString = ""; continue; }else{ tempString += charAt; } } } //Saves all game statistics to internal storage //Current solution puts all statistics as a long string with the @ as an end char. public void saveEnvironmentStatistics(){ String environmentStatistics = ""+ environmentModel.getCo2_savedToday() +'#'+ environmentModel.getCo2_carDistance() + '@'; fileIO.writeEnvironmentSaveFile(environmentStatistics); } public EnvironmentModel getEnvironmentModel() { return environmentModel; } public void setEnvironmentGain(){ adapter.getEnvironmentMenu().setEnvironmentGain(environmentModel.getCo2_savedToday()); } //TODO: MOVE THIS CODE TO USER.JAVA }
app/src/main/java/com/mobile/countme/implementation/controllers/MainPages.java
package com.mobile.countme.implementation.controllers; import android.content.Intent; import android.content.res.Configuration; import android.content.res.Resources; import android.os.Bundle; import android.support.v4.view.ViewPager; import android.support.v7.widget.Toolbar; import android.util.DisplayMetrics; import android.util.Log; import android.view.Menu; import android.view.MenuItem; import android.view.View; import com.mobile.countme.R; import com.mobile.countme.framework.AppMenu; import com.mobile.countme.framework.MainViewPagerAdapter; import com.mobile.countme.framework.SlidingTabLayout; import com.mobile.countme.implementation.AndroidFileIO; import com.mobile.countme.implementation.menus.BikingActive; import com.mobile.countme.implementation.models.EnvironmentModel; import java.util.Locale; /** * Created by Kristian on 16/09/2015. */ public class MainPages extends AppMenu { Toolbar toolbar; ViewPager pager; MainViewPagerAdapter adapter; SlidingTabLayout tabs; CharSequence Titles[]; int Numboftabs =4; AndroidFileIO fileIO; // File IO to save and get internally saved statistics. private int[] places = new int[]{1 , 10, 100, 1000, 10000, 100000, 1000000}; /** * The models in the MVC architecture. */ EnvironmentModel environmentModel; public void onCreate(Bundle savedInstanceBundle){ super.onCreate(savedInstanceBundle); setContentView(R.layout.main_activity); Titles= new CharSequence[]{ getResources().getString(R.string.biking_idle), getResources().getString(R.string.environment_page), getResources().getString(R.string.statistics_page), getResources().getString(R.string.info_page)}; toolbar = (Toolbar) findViewById(R.id.main_tool_bar); setSupportActionBar(toolbar); // Creating The ViewPagerAdapter and Passing Fragment Manager, Titles fot the Tabs and Number Of Tabs. adapter = new MainViewPagerAdapter(getSupportFragmentManager(),Titles,Numboftabs); // Assigning ViewPager View and setting the adapter pager = (ViewPager) findViewById(R.id.main_pager); pager.setAdapter(adapter); // Assiging the Sliding Tab Layout View tabs = (SlidingTabLayout) findViewById(R.id.main_tabs); tabs.setDistributeEvenly(true); // To make the Tabs Fixed set this true, This makes the tabs Space Evenly in Available width // Setting Custom Color for the Scroll bar indicator of the Tab View tabs.setCustomTabColorizer(new SlidingTabLayout.TabColorizer() { @Override public int getIndicatorColor(int position) { return getResources().getColor(R.color.TabScroller); } }); // Setting the ViewPager For the SlidingTabsLayout tabs.setViewPager(pager); //Not functional ( view is not made yet) //((TextView) findViewById(R.id.start_tur)).setTypeface(Assets.getTypeface(this, Assets.baskerville_old_face_regular)); //Instantiate the models and load the internal statistics environmentModel = new EnvironmentModel(this); loadStatistics(); getUser().setMainPages(this); } @Override public boolean onCreateOptionsMenu(Menu menu) { // Inflate the menu; this adds items to the action bar if it is present. getMenuInflater().inflate(R.menu.menu_main, menu); return true; } @Override public boolean onOptionsItemSelected(MenuItem item) { // Handle action bar item clicks here. The action bar will // automatically handle clicks on the Home/Up button, so long // as you specify a parent activity in AndroidManifest.xml. int id = item.getItemId(); Log.w("onOptionsItemSelected", "Start of method"); //noinspection SimplifiableIfStatement if (id == R.id.action_settings) { return true; } else if (id == R.id.lang_norwegian) { setLocale("no"); return true; } else if (id == R.id.lang_english) { Log.w("MainPages, itemSelected", "Setting language to english"); setLocale("en"); return true; } return super.onOptionsItemSelected(item); } public void goToIntroduction(View view){ goTo(IntroductionMenu.class); } public void startBiking(View view) { goTo(BikingActive.class); } public void setLocale(String lang) { Locale locale = new Locale(lang); Resources res = getResources(); DisplayMetrics dm = res.getDisplayMetrics(); Configuration conf = res.getConfiguration(); conf.locale = locale; res.updateConfiguration(conf, dm); Intent refresh = new Intent(this, MainPages.class); startActivity(refresh); finish(); } /** * Loads the environmental statistics of the user from phones internal storage */ public void loadStatistics(){ String environmentStatistics = fileIO.readEnvironmentSaveFile(); Log.w("User","loadStatistics: " + environmentStatistics); Character charAt; int positionInList = 0; int tempValue = 0; String tempString = ""; //For every char in statistics for (int i = 0; i < environmentStatistics.length(); i++){ charAt = environmentStatistics.charAt(i); if(charAt == '@'){ break; } //If the charAt pos i is the separation char '#' then // add current temp value to the statList and move on to the next stat. if(charAt == '#'){ for (int l=0; l < tempString.length(); l++) { tempValue += Character.getNumericValue(tempString.charAt(l)) * places[(tempString.length() - 1) - l]; } environmentModel.setStat(positionInList, tempValue); positionInList += 1; tempValue = 0; tempString = ""; continue; }else{ tempString += charAt; } } } //Saves all game statistics to internal storage //Current solution puts all statistics as a long string with the @ as an end char. public void saveEnvironmentStatistics(){ String environmentStatistics = ""+ environmentModel.getCo2_savedToday() +'#'+ environmentModel.getCo2_carDistance() + '@'; fileIO.writeEnvironmentSaveFile(environmentStatistics); } public EnvironmentModel getEnvironmentModel() { return environmentModel; } public void setEnvironmentGain(){ adapter.getEnvironmentMenu().setEnvironmentGain(environmentModel.getCo2_savedToday()); } }
Added TODO
app/src/main/java/com/mobile/countme/implementation/controllers/MainPages.java
Added TODO
<ide><path>pp/src/main/java/com/mobile/countme/implementation/controllers/MainPages.java <ide> public void setEnvironmentGain(){ <ide> adapter.getEnvironmentMenu().setEnvironmentGain(environmentModel.getCo2_savedToday()); <ide> } <add> <add> //TODO: MOVE THIS CODE TO USER.JAVA <ide> }
Java
apache-2.0
c31e50ffb1e8c3bec548c11784bf7996b2cdb418
0
oscarbou/isis,kidaa/isis,peridotperiod/isis,niv0/isis,peridotperiod/isis,apache/isis,niv0/isis,incodehq/isis,howepeng/isis,apache/isis,howepeng/isis,incodehq/isis,estatio/isis,niv0/isis,incodehq/isis,oscarbou/isis,peridotperiod/isis,sanderginn/isis,howepeng/isis,sanderginn/isis,apache/isis,peridotperiod/isis,oscarbou/isis,apache/isis,kidaa/isis,sanderginn/isis,apache/isis,kidaa/isis,apache/isis,incodehq/isis,howepeng/isis,oscarbou/isis,estatio/isis,estatio/isis,kidaa/isis,estatio/isis,niv0/isis,sanderginn/isis
/* * 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.isis.viewer.wicket.viewer; import java.util.Collection; import java.util.Collections; import java.util.List; import java.util.ServiceLoader; import java.util.Set; import javax.servlet.ServletContext; import com.google.common.base.Function; import com.google.common.base.Throwables; import com.google.common.collect.Iterables; import com.google.common.collect.Lists; import com.google.common.collect.Sets; import com.google.inject.Guice; import com.google.inject.Inject; import com.google.inject.Injector; import com.google.inject.Module; import de.agilecoders.wicket.webjars.WicketWebjars; import de.agilecoders.wicket.webjars.collectors.AssetPathCollector; import de.agilecoders.wicket.webjars.collectors.VfsJarAssetPathCollector; import de.agilecoders.wicket.webjars.settings.WebjarsSettings; import org.apache.wicket.Application; import org.apache.wicket.ConverterLocator; import org.apache.wicket.IConverterLocator; import org.apache.wicket.Page; import org.apache.wicket.RuntimeConfigurationType; import org.apache.wicket.SharedResources; import org.apache.wicket.authroles.authentication.AuthenticatedWebApplication; import org.apache.wicket.authroles.authentication.AuthenticatedWebSession; import org.apache.wicket.core.request.mapper.MountedMapper; import org.apache.wicket.guice.GuiceComponentInjector; import org.apache.wicket.markup.head.IHeaderResponse; import org.apache.wicket.markup.head.filter.JavaScriptFilteredIntoFooterHeaderResponse; import org.apache.wicket.markup.html.IHeaderResponseDecorator; import org.apache.wicket.markup.html.WebPage; import org.apache.wicket.request.Request; import org.apache.wicket.request.Response; import org.apache.wicket.request.cycle.IRequestCycleListener; import org.apache.wicket.request.cycle.RequestCycle; import org.apache.wicket.request.resource.CssResourceReference; import org.apache.wicket.settings.IRequestCycleSettings.RenderStrategy; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.apache.isis.core.commons.authentication.AuthenticationSession; import org.apache.isis.core.commons.authentication.AuthenticationSessionProvider; import org.apache.isis.core.commons.authentication.AuthenticationSessionProviderAware; import org.apache.isis.core.commons.config.IsisConfiguration; import org.apache.isis.core.commons.config.IsisConfigurationBuilder; import org.apache.isis.core.commons.config.IsisConfigurationBuilderPrimer; import org.apache.isis.core.commons.config.IsisConfigurationBuilderResourceStreams; import org.apache.isis.core.commons.resource.ResourceStreamSourceComposite; import org.apache.isis.core.commons.resource.ResourceStreamSourceContextLoaderClassPath; import org.apache.isis.core.commons.resource.ResourceStreamSourceCurrentClassClassPath; import org.apache.isis.core.commons.resource.ResourceStreamSourceFileSystem; import org.apache.isis.core.metamodel.adapter.ObjectAdapter; import org.apache.isis.core.metamodel.specloader.validator.MetaModelInvalidException; import org.apache.isis.core.runtime.logging.IsisLoggingConfigurer; import org.apache.isis.core.runtime.runner.IsisInjectModule; import org.apache.isis.core.runtime.system.DeploymentType; import org.apache.isis.core.runtime.system.IsisSystem; import org.apache.isis.core.runtime.system.context.IsisContext; import org.apache.isis.core.webapp.IsisWebAppBootstrapperUtil; import org.apache.isis.core.webapp.WebAppConstants; import org.apache.isis.core.webapp.config.ResourceStreamSourceForWebInf; import org.apache.isis.viewer.wicket.model.isis.WicketViewerSettings; import org.apache.isis.viewer.wicket.model.mementos.ObjectAdapterMemento; import org.apache.isis.viewer.wicket.model.models.ImageResourceCache; import org.apache.isis.viewer.wicket.model.models.PageType; import org.apache.isis.viewer.wicket.ui.ComponentFactory; import org.apache.isis.viewer.wicket.ui.app.registry.ComponentFactoryRegistrar; import org.apache.isis.viewer.wicket.ui.app.registry.ComponentFactoryRegistry; import org.apache.isis.viewer.wicket.ui.app.registry.ComponentFactoryRegistryAccessor; import org.apache.isis.viewer.wicket.ui.components.additionallinks.AdditionalLinksPanel; import org.apache.isis.viewer.wicket.ui.components.entity.properties.EntityPropertiesForm; import org.apache.isis.viewer.wicket.ui.components.scalars.string.MultiLineStringPanel; import org.apache.isis.viewer.wicket.ui.components.widgets.cssmenu.CssMenuItemPanel; import org.apache.isis.viewer.wicket.ui.components.widgets.cssmenu.CssSubMenuItemsPanel; import org.apache.isis.viewer.wicket.ui.overlays.Overlays; import org.apache.isis.viewer.wicket.ui.pages.PageAbstract; import org.apache.isis.viewer.wicket.ui.pages.PageClassList; import org.apache.isis.viewer.wicket.ui.pages.PageClassRegistry; import org.apache.isis.viewer.wicket.ui.pages.PageClassRegistryAccessor; import org.apache.isis.viewer.wicket.ui.panels.PanelUtil; import org.apache.isis.viewer.wicket.viewer.integration.isis.DeploymentTypeWicketAbstract; import org.apache.isis.viewer.wicket.viewer.integration.isis.WicketServer; import org.apache.isis.viewer.wicket.viewer.integration.isis.WicketServerPrototype; import org.apache.isis.viewer.wicket.viewer.integration.wicket.AuthenticatedWebSessionForIsis; import org.apache.isis.viewer.wicket.viewer.integration.wicket.ConverterForObjectAdapter; import org.apache.isis.viewer.wicket.viewer.integration.wicket.ConverterForObjectAdapterMemento; import org.apache.isis.viewer.wicket.viewer.integration.wicket.WebRequestCycleForIsis; /** * Main application, subclassing the Wicket {@link Application} and * bootstrapping Isis. * * <p> * Its main responsibility is to allow the set of {@link ComponentFactory}s used * to render the domain objects to be registered. This type of customisation is * commonplace. At a more fundamental level, also allows the {@link Page} * implementation for each {@link PageType page type} to be overridden. This is * probably less common, because CSS can also be used for this purpose. * * <p> * New {@link ComponentFactory}s can be specified in two ways. The preferred * approach is to use the {@link ServiceLoader} mechanism, whereby the * {@link ComponentFactory} implementation class is specified in a file under * <tt>META-INF/services</tt>. See <tt>views-gmaps2</tt> for an example of this. * Including a jar that uses this mechanism on the classpath will automatically * make the {@link ComponentFactory} defined within it available. * * <p> * Alternatively, {@link ComponentFactory}s can be specified by overridding {@link #newIsisWicketModule()}. * This mechanism allows a number of other aspects to be customized. */ public class IsisWicketApplication extends AuthenticatedWebApplication implements ComponentFactoryRegistryAccessor, PageClassRegistryAccessor, AuthenticationSessionProvider { private static final long serialVersionUID = 1L; private static final Logger LOG = LoggerFactory.getLogger(IsisWicketApplication.class); private static final String STRIP_WICKET_TAGS_KEY = "isis.viewer.wicket.stripWicketTags"; private final IsisLoggingConfigurer loggingConfigurer = new IsisLoggingConfigurer(); /** * Convenience locator, downcasts inherited functionality. */ public static IsisWicketApplication get() { return (IsisWicketApplication) AuthenticatedWebApplication.get(); } /** * {@link Inject}ed when {@link #init() initialized}. */ @Inject private ComponentFactoryRegistry componentFactoryRegistry; /** * {@link Inject}ed when {@link #init() initialized}. */ @SuppressWarnings("unused") @Inject private ImageResourceCache imageCache; /** * {@link Inject}ed when {@link #init() initialized}. */ @SuppressWarnings("unused") @Inject private WicketViewerSettings wicketViewerSettings; /** * {@link Inject}ed when {@link #init() initialized}. */ @Inject private PageClassRegistry pageClassRegistry; /** * {@link Inject}ed when {@link #init() initialized}. */ @SuppressWarnings("unused") @Inject private IsisSystem system; private boolean determiningDeploymentType; private DeploymentTypeWicketAbstract deploymentType; private final List<String> validationErrors = Lists.newArrayList(); // ///////////////////////////////////////////////// // constructor, init // ///////////////////////////////////////////////// public IsisWicketApplication() { } /** * Initializes the application; in particular, bootstrapping the Isis * backend, and initializing the {@link ComponentFactoryRegistry} to be used * for rendering. */ @Override protected void init() { try { super.init(); configureWebJars(); String isisConfigDir = getServletContext().getInitParameter("isis.config.dir"); configureLogging(isisConfigDir); getRequestCycleSettings().setRenderStrategy(RenderStrategy.REDIRECT_TO_RENDER); getRequestCycleListeners().add(newWebRequestCycleForIsis()); getResourceSettings().setParentFolderPlaceholder("$up$"); determineDeploymentTypeIfRequired(); final IsisConfigurationBuilder isisConfigurationBuilder = createConfigBuilder(); final IsisInjectModule isisModule = newIsisModule(deploymentType, isisConfigurationBuilder); final Injector injector = Guice.createInjector(isisModule, newIsisWicketModule()); injector.injectMembers(this); final IsisConfiguration configuration = isisConfigurationBuilder.getConfiguration(); this.getMarkupSettings().setStripWicketTags(determineStripWicketTags(deploymentType, configuration)); initWicketComponentInjection(injector); // must be done after injected componentFactoryRegistry into the app itself buildCssBundle(); filterJavascriptContributions(); // // map entity and action to provide prettier URLs // // nb: action mount cannot contain {actionArgs}, because the default // parameters encoder doesn't seem to be able to handle multiple args // mountPage("/entity/${objectOid}", PageType.ENTITY); mountPage("/action/${objectOid}/${actionOwningSpec}/${actionId}/${actionType}", PageType.ACTION_PROMPT); @SuppressWarnings("unused") SharedResources sharedResources = getSharedResources(); } catch(RuntimeException ex) { List<MetaModelInvalidException> mmies = Lists.newArrayList( Iterables.filter(Throwables.getCausalChain(ex), MetaModelInvalidException.class)); if(!mmies.isEmpty()) { final MetaModelInvalidException mmie = mmies.get(0); log(""); logBanner(); log(""); validationErrors.addAll(mmie.getValidationErrors()); for (String validationError : validationErrors) { logError(validationError); } log(""); log("Please inspect the above messages and correct your domain model."); log(""); logBanner(); log(""); } else { // because Wicket's handling in its WicketFilter (that calls this method) does not log the exception. LOG.error("Failed to initialize", ex); throw ex; } } } // ////////////////////////////////////// /** * Install 2 default collector instances: (FileAssetPathCollector(WEBJARS_PATH_PREFIX), JarAssetPathCollector), * and a webjars resource finder. * * <p> * Factored out for easy (informal) pluggability. * </p> */ protected void configureWebJars() { WebjarsSettings settings = new WebjarsSettings(); WicketWebjars.install(this, settings); } // ////////////////////////////////////// /** * Factored out for easy (informal) pluggability. */ protected void configureLogging(String isisConfigDir) { final String loggingPropertiesDir; if(isisConfigDir != null) { loggingPropertiesDir = isisConfigDir; } else { loggingPropertiesDir = getServletContext().getRealPath("/WEB-INF"); } loggingConfigurer.configureLogging(loggingPropertiesDir, new String[0]); } // ////////////////////////////////////// /** * Factored out for easy (informal) pluggability. */ protected IRequestCycleListener newWebRequestCycleForIsis() { return new WebRequestCycleForIsis(); } // ////////////////////////////////////// /** * Made protected visibility for easy (informal) pluggability. */ protected void determineDeploymentTypeIfRequired() { if(deploymentType != null) { return; } determiningDeploymentType = true; try { final IsisConfigurationBuilder isisConfigurationBuilder = createConfigBuilder(); final IsisConfiguration configuration = isisConfigurationBuilder.getConfiguration(); String deploymentTypeFromConfig = configuration.getString("isis.deploymentType"); deploymentType = determineDeploymentType(deploymentTypeFromConfig); } finally { determiningDeploymentType = false; } } /** * Made protected visibility for easy (informal) pluggability. */ protected DeploymentTypeWicketAbstract determineDeploymentType(String deploymentTypeFromConfig) { final DeploymentTypeWicketAbstract prototype = new WicketServerPrototype(); final DeploymentTypeWicketAbstract deployment = new WicketServer(); if(deploymentTypeFromConfig != null) { final DeploymentType deploymentType = DeploymentType.lookup(deploymentTypeFromConfig); return !deploymentType.getDeploymentCategory().isProduction() ? prototype : deployment; } else { return usesDevelopmentConfig() ? prototype : deployment; } } // ////////////////////////////////////// private IsisConfigurationBuilder createConfigBuilder() { return createConfigBuilder(getServletContext()); } protected IsisConfigurationBuilder createConfigBuilder(final ServletContext servletContext) { final String configLocation = servletContext.getInitParameter(WebAppConstants.CONFIG_DIR_PARAM); final ResourceStreamSourceForWebInf rssWebInf = new ResourceStreamSourceForWebInf(servletContext); final ResourceStreamSourceContextLoaderClassPath rssContextLoaderClassPath = ResourceStreamSourceContextLoaderClassPath.create(); final ResourceStreamSourceCurrentClassClassPath rssCurrentClassPath = new ResourceStreamSourceCurrentClassClassPath(); final ResourceStreamSourceComposite compositeSource = new ResourceStreamSourceComposite(rssWebInf, rssContextLoaderClassPath, rssCurrentClassPath); if ( configLocation != null ) { LOG.info( "Config override location: " + configLocation ); compositeSource.addResourceStreamSource(ResourceStreamSourceFileSystem.create(configLocation)); } else { LOG.info( "Config override location: No override location configured!" ); } final IsisConfigurationBuilder configurationBuilder = new IsisConfigurationBuilderResourceStreams(compositeSource); primeConfigurationBuilder(configurationBuilder, servletContext); configurationBuilder.addDefaultConfigurationResources(); IsisWebAppBootstrapperUtil.addConfigurationResourcesForViewers(configurationBuilder, servletContext); return configurationBuilder; } @SuppressWarnings("unchecked") private static void primeConfigurationBuilder(final IsisConfigurationBuilder isisConfigurationBuilder, final ServletContext servletContext) { final List<IsisConfigurationBuilderPrimer> isisConfigurationBuilderPrimers = (List<IsisConfigurationBuilderPrimer>) servletContext.getAttribute(WebAppConstants.CONFIGURATION_PRIMERS_KEY); if (isisConfigurationBuilderPrimers == null) { return; } for (final IsisConfigurationBuilderPrimer isisConfigurationBuilderPrimer : isisConfigurationBuilderPrimers) { isisConfigurationBuilderPrimer.primeConfigurationBuilder(isisConfigurationBuilder); } } // ////////////////////////////////////// /** * Override if required */ protected Module newIsisWicketModule() { return new IsisWicketModule(); } // ////////////////////////////////////// /** * Made protected visibility for easy (informal) pluggability. */ protected void buildCssBundle() { // get the css for all components built by component factories final Set<CssResourceReference> references = cssResourceReferencesForAllComponents(); // some additional special cases. addSpecialCasesToCssBundle(references); // create the bundle getResourceBundles().addCssBundle( IsisWicketApplication.class, "isis-wicket-viewer-bundle.css", references.toArray(new CssResourceReference[]{})); } /** * Additional special cases to be included in the main CSS bundle. * * <p> * These are typically either superclasses or components that don't have their own ComponentFactory, or * for {@link ComponentFactory}s (such as <tt>StringPanelFactory</tt>) that don't quite follow the usual pattern * (because they create different types of panels). * * <p> * Note that it doesn't really matter if we miss one or two; their CSS will simply be served up individually. */ protected void addSpecialCasesToCssBundle(final Set<CssResourceReference> references) { // abstract classes // ... though it turns out we cannot add this particular one to the bundle, because // it has CSS image links intended to be resolved relative to LinksSelectorPanelAbstract.class. // Adding them into the bundle would mean these CSS links are resolved relative to IsisWicketApplication.class // instead. // references.add(PanelUtil.cssResourceReferenceFor(LinksSelectorPanelAbstract.class)); // components without factories references.add(PanelUtil.cssResourceReferenceFor(AdditionalLinksPanel.class)); references.add(PanelUtil.cssResourceReferenceFor(CssSubMenuItemsPanel.class)); references.add(PanelUtil.cssResourceReferenceFor(CssMenuItemPanel.class)); references.add(PanelUtil.cssResourceReferenceFor(EntityPropertiesForm.class)); // non-conforming component factories references.add(PanelUtil.cssResourceReferenceFor(MultiLineStringPanel.class)); } protected final static Function<ComponentFactory, Iterable<CssResourceReference>> getCssResourceReferences = new Function<ComponentFactory, Iterable<CssResourceReference>>(){ @Override public Iterable<CssResourceReference> apply(final ComponentFactory input) { final CssResourceReference cssResourceReference = input.getCssResourceReference(); return cssResourceReference != null? Collections.singletonList(cssResourceReference): Collections.<CssResourceReference>emptyList(); } }; protected Set<CssResourceReference> cssResourceReferencesForAllComponents() { Collection<ComponentFactory> componentFactories = getComponentFactoryRegistry().listComponentFactories(); return Sets.newLinkedHashSet( Iterables.concat( Iterables.transform( componentFactories, getCssResourceReferences))); } // ////////////////////////////////////// /** * filters Javascript header contributions so rendered to bottom of page. * * <p> * Factored out for easy (informal) pluggability. * </p> */ protected void filterJavascriptContributions() { setHeaderResponseDecorator(new IHeaderResponseDecorator() { @Override public IHeaderResponse decorate(IHeaderResponse response) { // use this header resource decorator to load all JavaScript resources in the page // footer (after </body>) return new JavaScriptFilteredIntoFooterHeaderResponse(response, "footerJS"); } }); } // ////////////////////////////////////// /** * The validation errors, if any, that occurred on {@link #init() startup}. */ public List<String> getValidationErrors() { return validationErrors; } private void logError(String validationError) { log(validationError); } private static void logBanner() { String msg = "################################################ ISIS METAMODEL VALIDATION ERRORS ################################################################"; log(msg); } private static void log(String msg) { System.err.println(msg); LOG.error(msg); } private void mountPage(final String mountPath, final PageType pageType) { final Class<? extends Page> pageClass = this.pageClassRegistry.getPageClass(pageType); mount(new MountedMapper(mountPath, pageClass){ @Override protected String getOptionalPlaceholder(String s) { return getPlaceholder(s, '~'); } }); } /** * Whether Wicket tags should be stripped from the markup, as specified by configuration settings (otherwise * depends on the {@link #deploymentType deployment type}. * * <p> * If the <tt>isis.viewer.wicket.stripWicketTags</tt> is set, then this is used, otherwise the default is to strip * tags if in {@link DeploymentType#isProduction() production} mode, but not to strip if in prototyping mode. */ private boolean determineStripWicketTags(final DeploymentType deploymentType, IsisConfiguration configuration) { final boolean strip = configuration.getBoolean(STRIP_WICKET_TAGS_KEY, deploymentType.isProduction()); return strip; } @Override protected void onDestroy() { try { IsisContext.shutdown(); super.onDestroy(); } catch(final RuntimeException ex) { // symmetry with #init() LOG.error("Failed to destroy", ex); throw ex; } } @Override public RuntimeConfigurationType getConfigurationType() { if(determiningDeploymentType) { // avoiding an infinite loop; have already passed through here once before // this time around, just delegate to web-inf return super.getConfigurationType(); } determineDeploymentTypeIfRequired(); return deploymentType.getConfigurationType(); } protected IsisInjectModule newIsisModule(final DeploymentType deploymentType, final IsisConfigurationBuilder isisConfigurationBuilder) { return new IsisInjectModule(deploymentType, isisConfigurationBuilder); } // ////////////////////////////////////// protected void initWicketComponentInjection(final Injector injector) { getComponentInstantiationListeners().add(new GuiceComponentInjector(this, injector, false)); } // ///////////////////////////////////////////////// // Wicket Hooks // ///////////////////////////////////////////////// /** * Installs a {@link AuthenticatedWebSessionForIsis custom implementation} * of Wicket's own {@link AuthenticatedWebSession}, effectively associating * the Wicket session with the Isis's equivalent session object. * * <p> * In general, it shouldn't be necessary to override this method. */ @Override protected Class<? extends AuthenticatedWebSession> getWebSessionClass() { return AuthenticatedWebSessionForIsis.class; } /** * Installs a {@link ConverterLocator} preconfigured with a number of * implementations to support Isis specific objects. */ @Override protected IConverterLocator newConverterLocator() { final ConverterLocator converterLocator = new ConverterLocator(); converterLocator.set(ObjectAdapter.class, new ConverterForObjectAdapter()); converterLocator.set(ObjectAdapterMemento.class, new ConverterForObjectAdapterMemento()); return converterLocator; } // ///////////////////////////////////////////////// // Component Factories // ///////////////////////////////////////////////// /** * The {@link ComponentFactoryRegistry} created in * {@link #newComponentFactoryRegistry()}. */ @Override public final ComponentFactoryRegistry getComponentFactoryRegistry() { return componentFactoryRegistry; } // ///////////////////////////////////////////////// // Page Registry // ///////////////////////////////////////////////// /** * Access to other page types. * * <p> * Non-final only for testing purposes; should not typically be overridden. */ @Override public PageClassRegistry getPageClassRegistry() { return pageClassRegistry; } /** * Delegates to the {@link #getPageClassRegistry() PageClassRegistry}. */ @Override public Class<? extends Page> getHomePage() { return getPageClassRegistry().getPageClass(PageType.HOME); } /** * Delegates to the {@link #getPageClassRegistry() PageClassRegistry}. */ @SuppressWarnings("unchecked") @Override public Class<? extends WebPage> getSignInPageClass() { return (Class<? extends WebPage>) getPageClassRegistry().getPageClass(PageType.SIGN_IN); } // ///////////////////////////////////////////////// // Authentication Session // ///////////////////////////////////////////////// @Override public AuthenticationSession getAuthenticationSession() { return IsisContext.getAuthenticationSession(); } // ///////////////////////////////////////////////// // *Provider impl. // ///////////////////////////////////////////////// @Override public void injectInto(final Object candidate) { if (AuthenticationSessionProviderAware.class.isAssignableFrom(candidate.getClass())) { final AuthenticationSessionProviderAware cast = AuthenticationSessionProviderAware.class.cast(candidate); cast.setAuthenticationSessionProvider(this); } } }
component/viewer/wicket/impl/src/main/java/org/apache/isis/viewer/wicket/viewer/IsisWicketApplication.java
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.apache.isis.viewer.wicket.viewer; import java.util.Collection; import java.util.Collections; import java.util.List; import java.util.ServiceLoader; import java.util.Set; import javax.servlet.ServletContext; import com.google.common.base.Function; import com.google.common.base.Throwables; import com.google.common.collect.Iterables; import com.google.common.collect.Lists; import com.google.common.collect.Sets; import com.google.inject.Guice; import com.google.inject.Inject; import com.google.inject.Injector; import com.google.inject.Module; import de.agilecoders.wicket.webjars.WicketWebjars; import de.agilecoders.wicket.webjars.collectors.AssetPathCollector; import de.agilecoders.wicket.webjars.collectors.VfsJarAssetPathCollector; import de.agilecoders.wicket.webjars.settings.WebjarsSettings; import org.apache.wicket.Application; import org.apache.wicket.ConverterLocator; import org.apache.wicket.IConverterLocator; import org.apache.wicket.Page; import org.apache.wicket.RuntimeConfigurationType; import org.apache.wicket.SharedResources; import org.apache.wicket.authroles.authentication.AuthenticatedWebApplication; import org.apache.wicket.authroles.authentication.AuthenticatedWebSession; import org.apache.wicket.core.request.mapper.MountedMapper; import org.apache.wicket.guice.GuiceComponentInjector; import org.apache.wicket.markup.head.IHeaderResponse; import org.apache.wicket.markup.head.filter.JavaScriptFilteredIntoFooterHeaderResponse; import org.apache.wicket.markup.html.IHeaderResponseDecorator; import org.apache.wicket.markup.html.WebPage; import org.apache.wicket.request.Request; import org.apache.wicket.request.Response; import org.apache.wicket.request.cycle.IRequestCycleListener; import org.apache.wicket.request.cycle.RequestCycle; import org.apache.wicket.request.resource.CssResourceReference; import org.apache.wicket.settings.IRequestCycleSettings.RenderStrategy; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.apache.isis.core.commons.authentication.AuthenticationSession; import org.apache.isis.core.commons.authentication.AuthenticationSessionProvider; import org.apache.isis.core.commons.authentication.AuthenticationSessionProviderAware; import org.apache.isis.core.commons.config.IsisConfiguration; import org.apache.isis.core.commons.config.IsisConfigurationBuilder; import org.apache.isis.core.commons.config.IsisConfigurationBuilderPrimer; import org.apache.isis.core.commons.config.IsisConfigurationBuilderResourceStreams; import org.apache.isis.core.commons.resource.ResourceStreamSourceComposite; import org.apache.isis.core.commons.resource.ResourceStreamSourceContextLoaderClassPath; import org.apache.isis.core.commons.resource.ResourceStreamSourceCurrentClassClassPath; import org.apache.isis.core.commons.resource.ResourceStreamSourceFileSystem; import org.apache.isis.core.metamodel.adapter.ObjectAdapter; import org.apache.isis.core.metamodel.specloader.validator.MetaModelInvalidException; import org.apache.isis.core.runtime.logging.IsisLoggingConfigurer; import org.apache.isis.core.runtime.runner.IsisInjectModule; import org.apache.isis.core.runtime.system.DeploymentType; import org.apache.isis.core.runtime.system.IsisSystem; import org.apache.isis.core.runtime.system.context.IsisContext; import org.apache.isis.core.webapp.IsisWebAppBootstrapperUtil; import org.apache.isis.core.webapp.WebAppConstants; import org.apache.isis.core.webapp.config.ResourceStreamSourceForWebInf; import org.apache.isis.viewer.wicket.model.isis.WicketViewerSettings; import org.apache.isis.viewer.wicket.model.mementos.ObjectAdapterMemento; import org.apache.isis.viewer.wicket.model.models.ImageResourceCache; import org.apache.isis.viewer.wicket.model.models.PageType; import org.apache.isis.viewer.wicket.ui.ComponentFactory; import org.apache.isis.viewer.wicket.ui.app.registry.ComponentFactoryRegistrar; import org.apache.isis.viewer.wicket.ui.app.registry.ComponentFactoryRegistry; import org.apache.isis.viewer.wicket.ui.app.registry.ComponentFactoryRegistryAccessor; import org.apache.isis.viewer.wicket.ui.components.additionallinks.AdditionalLinksPanel; import org.apache.isis.viewer.wicket.ui.components.entity.properties.EntityPropertiesForm; import org.apache.isis.viewer.wicket.ui.components.scalars.string.MultiLineStringPanel; import org.apache.isis.viewer.wicket.ui.components.widgets.cssmenu.CssMenuItemPanel; import org.apache.isis.viewer.wicket.ui.components.widgets.cssmenu.CssSubMenuItemsPanel; import org.apache.isis.viewer.wicket.ui.overlays.Overlays; import org.apache.isis.viewer.wicket.ui.pages.PageAbstract; import org.apache.isis.viewer.wicket.ui.pages.PageClassList; import org.apache.isis.viewer.wicket.ui.pages.PageClassRegistry; import org.apache.isis.viewer.wicket.ui.pages.PageClassRegistryAccessor; import org.apache.isis.viewer.wicket.ui.panels.PanelUtil; import org.apache.isis.viewer.wicket.viewer.integration.isis.DeploymentTypeWicketAbstract; import org.apache.isis.viewer.wicket.viewer.integration.isis.WicketServer; import org.apache.isis.viewer.wicket.viewer.integration.isis.WicketServerPrototype; import org.apache.isis.viewer.wicket.viewer.integration.wicket.AuthenticatedWebSessionForIsis; import org.apache.isis.viewer.wicket.viewer.integration.wicket.ConverterForObjectAdapter; import org.apache.isis.viewer.wicket.viewer.integration.wicket.ConverterForObjectAdapterMemento; import org.apache.isis.viewer.wicket.viewer.integration.wicket.WebRequestCycleForIsis; /** * Main application, subclassing the Wicket {@link Application} and * bootstrapping Isis. * * <p> * Its main responsibility is to allow the set of {@link ComponentFactory}s used * to render the domain objects to be registered. This type of customisation is * commonplace. At a more fundamental level, also allows the {@link Page} * implementation for each {@link PageType page type} to be overridden. This is * probably less common, because CSS can also be used for this purpose. * * <p> * New {@link ComponentFactory}s can be specified in two ways. The preferred * approach is to use the {@link ServiceLoader} mechanism, whereby the * {@link ComponentFactory} implementation class is specified in a file under * <tt>META-INF/services</tt>. See <tt>views-gmaps2</tt> for an example of this. * Including a jar that uses this mechanism on the classpath will automatically * make the {@link ComponentFactory} defined within it available. * * <p> * Alternatively, {@link ComponentFactory}s can be specified by overridding {@link #newIsisWicketModule()}. * This mechanism allows a number of other aspects to be customized. */ public class IsisWicketApplication extends AuthenticatedWebApplication implements ComponentFactoryRegistryAccessor, PageClassRegistryAccessor, AuthenticationSessionProvider { private static final long serialVersionUID = 1L; private static final Logger LOG = LoggerFactory.getLogger(IsisWicketApplication.class); private static final String STRIP_WICKET_TAGS_KEY = "isis.viewer.wicket.stripWicketTags"; private final IsisLoggingConfigurer loggingConfigurer = new IsisLoggingConfigurer(); /** * Convenience locator, downcasts inherited functionality. */ public static IsisWicketApplication get() { return (IsisWicketApplication) AuthenticatedWebApplication.get(); } /** * {@link Inject}ed when {@link #init() initialized}. */ @Inject private ComponentFactoryRegistry componentFactoryRegistry; /** * {@link Inject}ed when {@link #init() initialized}. */ @SuppressWarnings("unused") @Inject private ImageResourceCache imageCache; /** * {@link Inject}ed when {@link #init() initialized}. */ @SuppressWarnings("unused") @Inject private WicketViewerSettings wicketViewerSettings; /** * {@link Inject}ed when {@link #init() initialized}. */ @Inject private PageClassRegistry pageClassRegistry; /** * {@link Inject}ed when {@link #init() initialized}. */ @SuppressWarnings("unused") @Inject private IsisSystem system; private boolean determiningDeploymentType; private DeploymentTypeWicketAbstract deploymentType; private final List<String> validationErrors = Lists.newArrayList(); // ///////////////////////////////////////////////// // constructor, init // ///////////////////////////////////////////////// public IsisWicketApplication() { } /** * Initializes the application; in particular, bootstrapping the Isis * backend, and initializing the {@link ComponentFactoryRegistry} to be used * for rendering. */ @Override protected void init() { try { super.init(); configureWebJars(); String isisConfigDir = getServletContext().getInitParameter("isis.config.dir"); configureLogging(isisConfigDir); getRequestCycleSettings().setRenderStrategy(RenderStrategy.REDIRECT_TO_RENDER); getRequestCycleListeners().add(newWebRequestCycleForIsis()); getResourceSettings().setParentFolderPlaceholder("$up$"); determineDeploymentTypeIfRequired(); final IsisConfigurationBuilder isisConfigurationBuilder = createConfigBuilder(); final IsisInjectModule isisModule = newIsisModule(deploymentType, isisConfigurationBuilder); final Injector injector = Guice.createInjector(isisModule, newIsisWicketModule()); injector.injectMembers(this); final IsisConfiguration configuration = isisConfigurationBuilder.getConfiguration(); this.getMarkupSettings().setStripWicketTags(determineStripWicketTags(deploymentType, configuration)); initWicketComponentInjection(injector); // must be done after injected componentFactoryRegistry into the app itself buildCssBundle(); // filters Javascript header contributions so rendered to bottom of page setHeaderResponseDecorator(new IHeaderResponseDecorator() { @Override public IHeaderResponse decorate(IHeaderResponse response) { // use this header resource decorator to load all JavaScript resources in the page // footer (after </body>) return new JavaScriptFilteredIntoFooterHeaderResponse(response, "footerJS"); } }); // // map entity and action to provide prettier URLs // // nb: action mount cannot contain {actionArgs}, because the default // parameters encoder doesn't seem to be able to handle multiple args // mountPage("/entity/${objectOid}", PageType.ENTITY); mountPage("/action/${objectOid}/${actionOwningSpec}/${actionId}/${actionType}", PageType.ACTION_PROMPT); @SuppressWarnings("unused") SharedResources sharedResources = getSharedResources(); } catch(RuntimeException ex) { List<MetaModelInvalidException> mmies = Lists.newArrayList( Iterables.filter(Throwables.getCausalChain(ex), MetaModelInvalidException.class)); if(!mmies.isEmpty()) { final MetaModelInvalidException mmie = mmies.get(0); log(""); logBanner(); log(""); validationErrors.addAll(mmie.getValidationErrors()); for (String validationError : validationErrors) { logError(validationError); } log(""); log("Please inspect the above messages and correct your domain model."); log(""); logBanner(); log(""); } else { // because Wicket's handling in its WicketFilter (that calls this method) does not log the exception. LOG.error("Failed to initialize", ex); throw ex; } } } // ////////////////////////////////////// /** * Install 2 default collector instances: (FileAssetPathCollector(WEBJARS_PATH_PREFIX), JarAssetPathCollector), * and a webjars resource finder. * * <p> * Factored out for easy (informal) pluggability. * </p> */ protected void configureWebJars() { WebjarsSettings settings = new WebjarsSettings(); WicketWebjars.install(this, settings); } // ////////////////////////////////////// /** * Factored out for easy (informal) pluggability. */ protected void configureLogging(String isisConfigDir) { final String loggingPropertiesDir; if(isisConfigDir != null) { loggingPropertiesDir = isisConfigDir; } else { loggingPropertiesDir = getServletContext().getRealPath("/WEB-INF"); } loggingConfigurer.configureLogging(loggingPropertiesDir, new String[0]); } // ////////////////////////////////////// /** * Factored out for easy (informal) pluggability. */ protected IRequestCycleListener newWebRequestCycleForIsis() { return new WebRequestCycleForIsis(); } // ////////////////////////////////////// /** * Made protected visibility for easy (informal) pluggability. */ protected void determineDeploymentTypeIfRequired() { if(deploymentType != null) { return; } determiningDeploymentType = true; try { final IsisConfigurationBuilder isisConfigurationBuilder = createConfigBuilder(); final IsisConfiguration configuration = isisConfigurationBuilder.getConfiguration(); String deploymentTypeFromConfig = configuration.getString("isis.deploymentType"); deploymentType = determineDeploymentType(deploymentTypeFromConfig); } finally { determiningDeploymentType = false; } } /** * Made protected visibility for easy (informal) pluggability. */ protected DeploymentTypeWicketAbstract determineDeploymentType(String deploymentTypeFromConfig) { final DeploymentTypeWicketAbstract prototype = new WicketServerPrototype(); final DeploymentTypeWicketAbstract deployment = new WicketServer(); if(deploymentTypeFromConfig != null) { final DeploymentType deploymentType = DeploymentType.lookup(deploymentTypeFromConfig); return !deploymentType.getDeploymentCategory().isProduction() ? prototype : deployment; } else { return usesDevelopmentConfig() ? prototype : deployment; } } // ////////////////////////////////////// private IsisConfigurationBuilder createConfigBuilder() { return createConfigBuilder(getServletContext()); } protected IsisConfigurationBuilder createConfigBuilder(final ServletContext servletContext) { final String configLocation = servletContext.getInitParameter(WebAppConstants.CONFIG_DIR_PARAM); final ResourceStreamSourceForWebInf rssWebInf = new ResourceStreamSourceForWebInf(servletContext); final ResourceStreamSourceContextLoaderClassPath rssContextLoaderClassPath = ResourceStreamSourceContextLoaderClassPath.create(); final ResourceStreamSourceCurrentClassClassPath rssCurrentClassPath = new ResourceStreamSourceCurrentClassClassPath(); final ResourceStreamSourceComposite compositeSource = new ResourceStreamSourceComposite(rssWebInf, rssContextLoaderClassPath, rssCurrentClassPath); if ( configLocation != null ) { LOG.info( "Config override location: " + configLocation ); compositeSource.addResourceStreamSource(ResourceStreamSourceFileSystem.create(configLocation)); } else { LOG.info( "Config override location: No override location configured!" ); } final IsisConfigurationBuilder configurationBuilder = new IsisConfigurationBuilderResourceStreams(compositeSource); primeConfigurationBuilder(configurationBuilder, servletContext); configurationBuilder.addDefaultConfigurationResources(); IsisWebAppBootstrapperUtil.addConfigurationResourcesForViewers(configurationBuilder, servletContext); return configurationBuilder; } @SuppressWarnings("unchecked") private static void primeConfigurationBuilder(final IsisConfigurationBuilder isisConfigurationBuilder, final ServletContext servletContext) { final List<IsisConfigurationBuilderPrimer> isisConfigurationBuilderPrimers = (List<IsisConfigurationBuilderPrimer>) servletContext.getAttribute(WebAppConstants.CONFIGURATION_PRIMERS_KEY); if (isisConfigurationBuilderPrimers == null) { return; } for (final IsisConfigurationBuilderPrimer isisConfigurationBuilderPrimer : isisConfigurationBuilderPrimers) { isisConfigurationBuilderPrimer.primeConfigurationBuilder(isisConfigurationBuilder); } } // ////////////////////////////////////// /** * Override if required */ protected Module newIsisWicketModule() { return new IsisWicketModule(); } // ////////////////////////////////////// /** * Made protected visibility for easy (informal) pluggability. */ protected void buildCssBundle() { // get the css for all components built by component factories final Set<CssResourceReference> references = cssResourceReferencesForAllComponents(); // some additional special cases. addSpecialCasesToCssBundle(references); // create the bundle getResourceBundles().addCssBundle( IsisWicketApplication.class, "isis-wicket-viewer-bundle.css", references.toArray(new CssResourceReference[]{})); } /** * Additional special cases to be included in the main CSS bundle. * * <p> * These are typically either superclasses or components that don't have their own ComponentFactory, or * for {@link ComponentFactory}s (such as <tt>StringPanelFactory</tt>) that don't quite follow the usual pattern * (because they create different types of panels). * * <p> * Note that it doesn't really matter if we miss one or two; their CSS will simply be served up individually. */ protected void addSpecialCasesToCssBundle(final Set<CssResourceReference> references) { // abstract classes // ... though it turns out we cannot add this particular one to the bundle, because // it has CSS image links intended to be resolved relative to LinksSelectorPanelAbstract.class. // Adding them into the bundle would mean these CSS links are resolved relative to IsisWicketApplication.class // instead. // references.add(PanelUtil.cssResourceReferenceFor(LinksSelectorPanelAbstract.class)); // components without factories references.add(PanelUtil.cssResourceReferenceFor(AdditionalLinksPanel.class)); references.add(PanelUtil.cssResourceReferenceFor(CssSubMenuItemsPanel.class)); references.add(PanelUtil.cssResourceReferenceFor(CssMenuItemPanel.class)); references.add(PanelUtil.cssResourceReferenceFor(EntityPropertiesForm.class)); // non-conforming component factories references.add(PanelUtil.cssResourceReferenceFor(MultiLineStringPanel.class)); } protected final static Function<ComponentFactory, Iterable<CssResourceReference>> getCssResourceReferences = new Function<ComponentFactory, Iterable<CssResourceReference>>(){ @Override public Iterable<CssResourceReference> apply(final ComponentFactory input) { final CssResourceReference cssResourceReference = input.getCssResourceReference(); return cssResourceReference != null? Collections.singletonList(cssResourceReference): Collections.<CssResourceReference>emptyList(); } }; protected Set<CssResourceReference> cssResourceReferencesForAllComponents() { Collection<ComponentFactory> componentFactories = getComponentFactoryRegistry().listComponentFactories(); return Sets.newLinkedHashSet( Iterables.concat( Iterables.transform( componentFactories, getCssResourceReferences))); } // ////////////////////////////////////// /** * The validation errors, if any, that occurred on {@link #init() startup}. */ public List<String> getValidationErrors() { return validationErrors; } private void logError(String validationError) { log(validationError); } private static void logBanner() { String msg = "################################################ ISIS METAMODEL VALIDATION ERRORS ################################################################"; log(msg); } private static void log(String msg) { System.err.println(msg); LOG.error(msg); } private void mountPage(final String mountPath, final PageType pageType) { final Class<? extends Page> pageClass = this.pageClassRegistry.getPageClass(pageType); mount(new MountedMapper(mountPath, pageClass){ @Override protected String getOptionalPlaceholder(String s) { return getPlaceholder(s, '~'); } }); } /** * Whether Wicket tags should be stripped from the markup, as specified by configuration settings (otherwise * depends on the {@link #deploymentType deployment type}. * * <p> * If the <tt>isis.viewer.wicket.stripWicketTags</tt> is set, then this is used, otherwise the default is to strip * tags if in {@link DeploymentType#isProduction() production} mode, but not to strip if in prototyping mode. */ private boolean determineStripWicketTags(final DeploymentType deploymentType, IsisConfiguration configuration) { final boolean strip = configuration.getBoolean(STRIP_WICKET_TAGS_KEY, deploymentType.isProduction()); return strip; } @Override protected void onDestroy() { try { IsisContext.shutdown(); super.onDestroy(); } catch(final RuntimeException ex) { // symmetry with #init() LOG.error("Failed to destroy", ex); throw ex; } } @Override public RuntimeConfigurationType getConfigurationType() { if(determiningDeploymentType) { // avoiding an infinite loop; have already passed through here once before // this time around, just delegate to web-inf return super.getConfigurationType(); } determineDeploymentTypeIfRequired(); return deploymentType.getConfigurationType(); } protected IsisInjectModule newIsisModule(final DeploymentType deploymentType, final IsisConfigurationBuilder isisConfigurationBuilder) { return new IsisInjectModule(deploymentType, isisConfigurationBuilder); } // ////////////////////////////////////// protected void initWicketComponentInjection(final Injector injector) { getComponentInstantiationListeners().add(new GuiceComponentInjector(this, injector, false)); } // ///////////////////////////////////////////////// // Wicket Hooks // ///////////////////////////////////////////////// /** * Installs a {@link AuthenticatedWebSessionForIsis custom implementation} * of Wicket's own {@link AuthenticatedWebSession}, effectively associating * the Wicket session with the Isis's equivalent session object. * * <p> * In general, it shouldn't be necessary to override this method. */ @Override protected Class<? extends AuthenticatedWebSession> getWebSessionClass() { return AuthenticatedWebSessionForIsis.class; } /** * Installs a {@link ConverterLocator} preconfigured with a number of * implementations to support Isis specific objects. */ @Override protected IConverterLocator newConverterLocator() { final ConverterLocator converterLocator = new ConverterLocator(); converterLocator.set(ObjectAdapter.class, new ConverterForObjectAdapter()); converterLocator.set(ObjectAdapterMemento.class, new ConverterForObjectAdapterMemento()); return converterLocator; } // ///////////////////////////////////////////////// // Component Factories // ///////////////////////////////////////////////// /** * The {@link ComponentFactoryRegistry} created in * {@link #newComponentFactoryRegistry()}. */ @Override public final ComponentFactoryRegistry getComponentFactoryRegistry() { return componentFactoryRegistry; } // ///////////////////////////////////////////////// // Page Registry // ///////////////////////////////////////////////// /** * Access to other page types. * * <p> * Non-final only for testing purposes; should not typically be overridden. */ @Override public PageClassRegistry getPageClassRegistry() { return pageClassRegistry; } /** * Delegates to the {@link #getPageClassRegistry() PageClassRegistry}. */ @Override public Class<? extends Page> getHomePage() { return getPageClassRegistry().getPageClass(PageType.HOME); } /** * Delegates to the {@link #getPageClassRegistry() PageClassRegistry}. */ @SuppressWarnings("unchecked") @Override public Class<? extends WebPage> getSignInPageClass() { return (Class<? extends WebPage>) getPageClassRegistry().getPageClass(PageType.SIGN_IN); } // ///////////////////////////////////////////////// // Authentication Session // ///////////////////////////////////////////////// @Override public AuthenticationSession getAuthenticationSession() { return IsisContext.getAuthenticationSession(); } // ///////////////////////////////////////////////// // *Provider impl. // ///////////////////////////////////////////////// @Override public void injectInto(final Object candidate) { if (AuthenticationSessionProviderAware.class.isAssignableFrom(candidate.getClass())) { final AuthenticationSessionProviderAware cast = AuthenticationSessionProviderAware.class.cast(candidate); cast.setAuthenticationSessionProvider(this); } } }
ISIS-793: make easier to override filtering of Javascript contributions
component/viewer/wicket/impl/src/main/java/org/apache/isis/viewer/wicket/viewer/IsisWicketApplication.java
ISIS-793: make easier to override filtering of Javascript contributions
<ide><path>omponent/viewer/wicket/impl/src/main/java/org/apache/isis/viewer/wicket/viewer/IsisWicketApplication.java <ide> // must be done after injected componentFactoryRegistry into the app itself <ide> buildCssBundle(); <ide> <del> // filters Javascript header contributions so rendered to bottom of page <del> setHeaderResponseDecorator(new IHeaderResponseDecorator() <del> { <del> @Override <del> public IHeaderResponse decorate(IHeaderResponse response) <del> { <del> // use this header resource decorator to load all JavaScript resources in the page <del> // footer (after </body>) <del> return new JavaScriptFilteredIntoFooterHeaderResponse(response, "footerJS"); <del> } <del> }); <add> filterJavascriptContributions(); <add> <ide> <ide> // <ide> // map entity and action to provide prettier URLs <ide> // ////////////////////////////////////// <ide> <ide> /** <add> * filters Javascript header contributions so rendered to bottom of page. <add> * <add> * <p> <add> * Factored out for easy (informal) pluggability. <add> * </p> <add> */ <add> protected void filterJavascriptContributions() { <add> setHeaderResponseDecorator(new IHeaderResponseDecorator() <add> { <add> @Override <add> public IHeaderResponse decorate(IHeaderResponse response) <add> { <add> // use this header resource decorator to load all JavaScript resources in the page <add> // footer (after </body>) <add> return new JavaScriptFilteredIntoFooterHeaderResponse(response, "footerJS"); <add> } <add> }); <add> } <add> <add> <add> // ////////////////////////////////////// <add> <add> /** <ide> * The validation errors, if any, that occurred on {@link #init() startup}. <ide> */ <ide> public List<String> getValidationErrors() {
Java
agpl-3.0
error: pathspec 'src/algorithms/searching/HybridBinarySearch.java' did not match any file(s) known to git
7dc69cd608dead825535b23c26ad5406b2aa1e58
1
maandree/algorithms-and-data-structures,maandree/algorithms-and-data-structures,maandree/algorithms-and-data-structures
/** * Copyright © 2014 Mattias Andrée ([email protected]) * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package algorithms.searching; import java.util.*; /** * Hybrid binary search class. Binary search runs in logarithmic time, constant * memory, and requires the list to be sorted. Binary search often out preforms * linear search, interpolation sort however often out preforms binary search * for lists with smooth distribution. Hybrid binary search uses binary search * and falls back to linear search when the number of elemetns left are small * enough. Identity search is not possible, only equality search. Null elements * are not allowed, unless the specified compator allows it. */ public class HybridBinarySearch { /** * All elements in the array is the searched for item */ public static final int EVERY_ELEMENT = -1; /** * Item was not on the edges, but may be inside * Values lower than this value indicate that the value does * not exist. */ public static final int MAYBE = -2; /** * The item's value is smaller than the smallest in the array. * This value and lower values indicate that the value does * not exist. */ public static final int TOO_SMALL = -3; /** * The item's value is larger than the largest in the array */ public static final int TOO_LARGE = -4; /** * List sort order */ public static enum SortOrder { /** * Bigger index, bigger value */ ASCENDING, /** * Bigger index, smaller value */ DESCENDING, } /** * List sort order */ public static enum SearchMode { /** * Look for the index of the easiest to find occurence */ FIND_ANY, /** * Look for the index of the first occurence */ FIND_FIRST, /** * Look for the index of the last occurence */ FIND_LAST, /** * Look for both the index of the fist occurence and of the last occurence.<br> * The returned value will be {@code (LAST << 32) | FIRST}. */ FIND_FIST_AND_LAST, } £>for T in boolean char byte short int long float double T T++; do . src/comparable /** * Gets whether an item may be contained by a list * * @param item The item for which to search * @param array The list in which to search * @param order The list's element order * @return {@link #MAYBE}, {@link #TOO_SMALL}, {@link #TOO_LARGE}, {@link #EVERY_ELEMENT} * or the index of a(!) found item [first or last position] */ public static £(fun "int" contains "${T} item, ${Tarray} array, SortOrder order") { /* This is identical to as in BinarySearch */ int low = £(cmp "array[0]" "item"); if (order == SortOrder.ASCENDING) { if (low > 0) return TOO_SMALL; int high = £(cmp "array[1]" "item"); if (low == 0) return high == 0 ? EVERY_ELEMENT : 0; return high == 0 ? array.length - 1 : high < 0 ? TOO_LARGE : MAYBE; } { if (low < 0) return TOO_SMALL; int n = array.length - 1; int high = £(cmp "array[n]" "item"); if (low == 0) return high == 0 ? EVERY_ELEMENT : 0; return high == 0 ? n : high > 0 ? TOO_LARGE : MAYBE; } } /** * Finds the index of the first occurance of an item in a list * * @param item The item for which to search * @param array The list in which to search * @param start Offset for the list or search range * @param end End of the list or search range * @return The index of the first occurance of the item within the list, {@code -1} if it was not found */ private static £(fun "int" linearFirst "${T} item, ${T}[] array, int start, int end") { /* This is nearly identical to LinearSearch.indexOfFirst */ int i = start < 0 ? (array.length - start) : start; int n = end < 0 ? (array.length - end) : end; for (;;) { if (i == n) break; if (array[i] == item) return i; i++; } return -1; } /** * Finds the first, last or any occurance of an item in a list * * @param item The item for which to search * @param array The list in which to search * @param order The list's element order * @param mode The search mode * @param fallback The number of elements at when to fall back to linear search * @return The index of the found item, if not mode does not say otherwise, or, if not * found, the bitwise negation of the position to which it should be inserted */ public static £(fun "long" indexOf "${T} item, ${Tarray} array, SortOrder order, SearchMode mode, int fallback") { £{Telement} x; int min = 0, mid, rc = -1; int max = array.length - 1; £>function f £>{ if (mode == SearchMode.£{1}) for (;;) { if (min + fallback >= max) return linearFirst(item, array, min, max); if (item == (x = array[mid = (min + max) >>> 1])) £{2}; /* NB! (x R item), instead of (item R x) */ if (£(${3} x item)) min = mid + 1; else max = mid - 1; if (min > max) return £{4}; } £>} £>function p £>{ for (;;) { £>if [ $3 = 0 ]; then if (min + fallback >= max) { first = last = rc = linearFirst(item, array, min, max); easyMin = first + 1; easyMax = max; normal = true; if (last >= 0) break; } £>else if (!normal && (min + fallback >= max)) { first = last = rc = linearFirst(item, array, min, max); normal = true; if (last >= 0) { easyMin = first + 1; easyMax = max; break; } } £>fi if (item == (x = array[mid = (min + max) >>> 1])) { rc = mid; £>if [ $3 = 0 ]; then if (easyMin == -1) { easyMax = mid - 1; easyMin = min; } £>fi } /* NB! (x R item), instead of (item R x) */ if (£(${1} x item)) min = mid + 1; else max = mid - 1; if (min > max) { if (rc < 0) return ~((long)min); £{2} = rc; break; } } £>} £>function _ £>{ { £>f FIND_ANY 'return (long)mid' "${1}" '~((long)min)' £>f FIND_FIRST 'rc = mid' "${1}" 'rc < 0 ? ~((long)min) : (long)rc' £>f FIND_LAST 'rc = mid' "${1}=" 'rc < 0 ? ~((long)min) : (long)rc' int easyMin = -1, easyMax = -1, first, last; boolean normal = false; £>p "${1}" first 0 min = easyMin; max = easyMax; £>p "${1}=" last 1 return (((long)last) << 32) | (long)first; } £>} if (order == SortOrder.ASCENDING) £>_ 'less' £>_ 'greater' } £>done }
src/algorithms/searching/HybridBinarySearch.java
add hybrid binary search Signed-off-by: Mattias Andrée <[email protected]>
src/algorithms/searching/HybridBinarySearch.java
add hybrid binary search
<ide><path>rc/algorithms/searching/HybridBinarySearch.java <add>/** <add> * Copyright © 2014 Mattias Andrée ([email protected]) <add> * <add> * This program is free software: you can redistribute it and/or modify <add> * it under the terms of the GNU Affero General Public License as published by <add> * the Free Software Foundation, either version 3 of the License, or <add> * (at your option) any later version. <add> * <add> * This program is distributed in the hope that it will be useful, <add> * but WITHOUT ANY WARRANTY; without even the implied warranty of <add> * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the <add> * GNU Affero General Public License for more details. <add> * <add> * You should have received a copy of the GNU Affero General Public License <add> * along with this program. If not, see <http://www.gnu.org/licenses/>. <add> */ <add>package algorithms.searching; <add> <add>import java.util.*; <add> <add> <add>/** <add> * Hybrid binary search class. Binary search runs in logarithmic time, constant <add> * memory, and requires the list to be sorted. Binary search often out preforms <add> * linear search, interpolation sort however often out preforms binary search <add> * for lists with smooth distribution. Hybrid binary search uses binary search <add> * and falls back to linear search when the number of elemetns left are small <add> * enough. Identity search is not possible, only equality search. Null elements <add> * are not allowed, unless the specified compator allows it. <add> */ <add>public class HybridBinarySearch <add>{ <add> /** <add> * All elements in the array is the searched for item <add> */ <add> public static final int EVERY_ELEMENT = -1; <add> <add> /** <add> * Item was not on the edges, but may be inside <add> * Values lower than this value indicate that the value does <add> * not exist. <add> */ <add> public static final int MAYBE = -2; <add> <add> /** <add> * The item's value is smaller than the smallest in the array. <add> * This value and lower values indicate that the value does <add> * not exist. <add> */ <add> public static final int TOO_SMALL = -3; <add> <add> /** <add> * The item's value is larger than the largest in the array <add> */ <add> public static final int TOO_LARGE = -4; <add> <add> <add> <add> /** <add> * List sort order <add> */ <add> public static enum SortOrder <add> { <add> /** <add> * Bigger index, bigger value <add> */ <add> ASCENDING, <add> <add> /** <add> * Bigger index, smaller value <add> */ <add> DESCENDING, <add> <add> } <add> <add> /** <add> * List sort order <add> */ <add> public static enum SearchMode <add> { <add> /** <add> * Look for the index of the easiest to find occurence <add> */ <add> FIND_ANY, <add> <add> /** <add> * Look for the index of the first occurence <add> */ <add> FIND_FIRST, <add> <add> /** <add> * Look for the index of the last occurence <add> */ <add> FIND_LAST, <add> <add> /** <add> * Look for both the index of the fist occurence and of the last occurence.<br> <add> * The returned value will be {@code (LAST << 32) | FIRST}. <add> */ <add> FIND_FIST_AND_LAST, <add> <add> } <add> <add> <add> <add>£>for T in boolean char byte short int long float double T T++; do . src/comparable <add> <add> /** <add> * Gets whether an item may be contained by a list <add> * <add> * @param item The item for which to search <add> * @param array The list in which to search <add> * @param order The list's element order <add> * @return {@link #MAYBE}, {@link #TOO_SMALL}, {@link #TOO_LARGE}, {@link #EVERY_ELEMENT} <add> * or the index of a(!) found item [first or last position] <add> */ <add> public static £(fun "int" contains "${T} item, ${Tarray} array, SortOrder order") <add> { <add> /* This is identical to as in BinarySearch */ <add> <add> int low = £(cmp "array[0]" "item"); <add> <add> if (order == SortOrder.ASCENDING) <add> { <add> if (low > 0) <add> return TOO_SMALL; <add> <add> int high = £(cmp "array[1]" "item"); <add> <add> if (low == 0) <add> return high == 0 ? EVERY_ELEMENT : 0; <add> <add> return high == 0 ? array.length - 1 : high < 0 ? TOO_LARGE : MAYBE; <add> } <add> <add> { <add> if (low < 0) <add> return TOO_SMALL; <add> <add> int n = array.length - 1; <add> int high = £(cmp "array[n]" "item"); <add> <add> if (low == 0) <add> return high == 0 ? EVERY_ELEMENT : 0; <add> <add> return high == 0 ? n : high > 0 ? TOO_LARGE : MAYBE; <add> } <add> } <add> <add> <add> /** <add> * Finds the index of the first occurance of an item in a list <add> * <add> * @param item The item for which to search <add> * @param array The list in which to search <add> * @param start Offset for the list or search range <add> * @param end End of the list or search range <add> * @return The index of the first occurance of the item within the list, {@code -1} if it was not found <add> */ <add> private static £(fun "int" linearFirst "${T} item, ${T}[] array, int start, int end") <add> { <add> /* This is nearly identical to LinearSearch.indexOfFirst */ <add> <add> int i = start < 0 ? (array.length - start) : start; <add> int n = end < 0 ? (array.length - end) : end; <add> <add> for (;;) <add> { <add> if (i == n) <add> break; <add> <add> if (array[i] == item) <add> return i; <add> <add> i++; <add> } <add> <add> return -1; <add> } <add> <add> /** <add> * Finds the first, last or any occurance of an item in a list <add> * <add> * @param item The item for which to search <add> * @param array The list in which to search <add> * @param order The list's element order <add> * @param mode The search mode <add> * @param fallback The number of elements at when to fall back to linear search <add> * @return The index of the found item, if not mode does not say otherwise, or, if not <add> * found, the bitwise negation of the position to which it should be inserted <add> */ <add> public static £(fun "long" indexOf "${T} item, ${Tarray} array, SortOrder order, SearchMode mode, int fallback") <add> { <add> £{Telement} x; <add> <add> int min = 0, mid, rc = -1; <add> int max = array.length - 1; <add> <add>£>function f <add>£>{ <add> if (mode == SearchMode.£{1}) <add> for (;;) <add> { <add> if (min + fallback >= max) <add> return linearFirst(item, array, min, max); <add> <add> if (item == (x = array[mid = (min + max) >>> 1])) <add> £{2}; <add> <add> /* NB! (x R item), instead of (item R x) */ <add> if (£(${3} x item)) min = mid + 1; <add> else max = mid - 1; <add> <add> if (min > max) <add> return £{4}; <add> } <add>£>} <add> <add>£>function p <add>£>{ <add> for (;;) <add> { <add>£>if [ $3 = 0 ]; then <add> if (min + fallback >= max) <add> { <add> first = last = rc = linearFirst(item, array, min, max); <add> easyMin = first + 1; <add> easyMax = max; <add> normal = true; <add> if (last >= 0) <add> break; <add> } <add>£>else <add> if (!normal && (min + fallback >= max)) <add> { <add> first = last = rc = linearFirst(item, array, min, max); <add> normal = true; <add> if (last >= 0) <add> { <add> easyMin = first + 1; <add> easyMax = max; <add> break; <add> } <add> } <add>£>fi <add> <add> if (item == (x = array[mid = (min + max) >>> 1])) <add> { <add> rc = mid; <add>£>if [ $3 = 0 ]; then <add> if (easyMin == -1) <add> { <add> easyMax = mid - 1; <add> easyMin = min; <add> } <add>£>fi <add> } <add> <add> /* NB! (x R item), instead of (item R x) */ <add> if (£(${1} x item)) min = mid + 1; <add> else max = mid - 1; <add> <add> if (min > max) <add> { <add> if (rc < 0) <add> return ~((long)min); <add> £{2} = rc; <add> break; <add> } <add> } <add> <add>£>} <add> <add>£>function _ <add>£>{ <add> { <add>£>f FIND_ANY 'return (long)mid' "${1}" '~((long)min)' <add>£>f FIND_FIRST 'rc = mid' "${1}" 'rc < 0 ? ~((long)min) : (long)rc' <add>£>f FIND_LAST 'rc = mid' "${1}=" 'rc < 0 ? ~((long)min) : (long)rc' <add> <add> int easyMin = -1, easyMax = -1, first, last; <add> boolean normal = false; <add>£>p "${1}" first 0 <add> min = easyMin; <add> max = easyMax; <add>£>p "${1}=" last 1 <add> return (((long)last) << 32) | (long)first; <add> } <add>£>} <add> <add> if (order == SortOrder.ASCENDING) <add>£>_ 'less' <add>£>_ 'greater' <add> } <add>£>done <add>} <add>
Java
apache-2.0
5aacf3e2053d52b9a2d05156c8498ddd9c6676e4
0
gingerwizard/elasticsearch,HonzaKral/elasticsearch,HonzaKral/elasticsearch,gfyoung/elasticsearch,coding0011/elasticsearch,uschindler/elasticsearch,robin13/elasticsearch,gfyoung/elasticsearch,scorpionvicky/elasticsearch,nknize/elasticsearch,strapdata/elassandra,gingerwizard/elasticsearch,GlenRSmith/elasticsearch,vroyer/elassandra,strapdata/elassandra,coding0011/elasticsearch,gingerwizard/elasticsearch,GlenRSmith/elasticsearch,strapdata/elassandra,uschindler/elasticsearch,scorpionvicky/elasticsearch,GlenRSmith/elasticsearch,gfyoung/elasticsearch,scorpionvicky/elasticsearch,nknize/elasticsearch,GlenRSmith/elasticsearch,strapdata/elassandra,scorpionvicky/elasticsearch,HonzaKral/elasticsearch,coding0011/elasticsearch,strapdata/elassandra,nknize/elasticsearch,vroyer/elassandra,nknize/elasticsearch,gingerwizard/elasticsearch,robin13/elasticsearch,gingerwizard/elasticsearch,scorpionvicky/elasticsearch,gfyoung/elasticsearch,uschindler/elasticsearch,vroyer/elassandra,uschindler/elasticsearch,robin13/elasticsearch,HonzaKral/elasticsearch,nknize/elasticsearch,robin13/elasticsearch,coding0011/elasticsearch,gingerwizard/elasticsearch,uschindler/elasticsearch,gfyoung/elasticsearch,GlenRSmith/elasticsearch,coding0011/elasticsearch,gingerwizard/elasticsearch,robin13/elasticsearch
/* * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one * or more contributor license agreements. Licensed under the Elastic License; * you may not use this file except in compliance with the Elastic License. */ package org.elasticsearch.xpack.watcher; import org.apache.logging.log4j.Logger; import org.elasticsearch.action.ActionRequest; import org.elasticsearch.action.ActionResponse; import org.elasticsearch.client.Client; import org.elasticsearch.cluster.metadata.MetaData; import org.elasticsearch.common.Booleans; import org.elasticsearch.common.Strings; import org.elasticsearch.common.inject.Module; import org.elasticsearch.common.logging.LoggerMessageFormat; import org.elasticsearch.common.logging.Loggers; import org.elasticsearch.common.regex.Regex; import org.elasticsearch.common.settings.Setting; import org.elasticsearch.common.settings.Settings; import org.elasticsearch.common.unit.TimeValue; import org.elasticsearch.common.util.concurrent.EsExecutors; import org.elasticsearch.plugins.ActionPlugin; import org.elasticsearch.plugins.ScriptPlugin; import org.elasticsearch.rest.RestHandler; import org.elasticsearch.script.ScriptContext; import org.elasticsearch.threadpool.ExecutorBuilder; import org.elasticsearch.threadpool.FixedExecutorBuilder; import org.elasticsearch.xpack.XPackPlugin; import org.elasticsearch.xpack.XPackSettings; import org.elasticsearch.xpack.watcher.actions.WatcherActionModule; import org.elasticsearch.xpack.watcher.client.WatcherClientModule; import org.elasticsearch.xpack.watcher.condition.ConditionModule; import org.elasticsearch.xpack.watcher.execution.ExecutionModule; import org.elasticsearch.xpack.watcher.execution.ExecutionService; import org.elasticsearch.xpack.watcher.execution.InternalWatchExecutor; import org.elasticsearch.xpack.watcher.execution.TriggeredWatchStore; import org.elasticsearch.xpack.watcher.history.HistoryModule; import org.elasticsearch.xpack.watcher.history.HistoryStore; import org.elasticsearch.xpack.watcher.input.InputModule; import org.elasticsearch.xpack.watcher.rest.action.RestAckWatchAction; import org.elasticsearch.xpack.watcher.rest.action.RestActivateWatchAction; import org.elasticsearch.xpack.watcher.rest.action.RestDeleteWatchAction; import org.elasticsearch.xpack.watcher.rest.action.RestExecuteWatchAction; import org.elasticsearch.xpack.watcher.rest.action.RestGetWatchAction; import org.elasticsearch.xpack.watcher.rest.action.RestHijackOperationAction; import org.elasticsearch.xpack.watcher.rest.action.RestPutWatchAction; import org.elasticsearch.xpack.watcher.rest.action.RestWatchServiceAction; import org.elasticsearch.xpack.watcher.rest.action.RestWatcherStatsAction; import org.elasticsearch.xpack.watcher.support.WatcherIndexTemplateRegistry; import org.elasticsearch.xpack.watcher.support.WatcherIndexTemplateRegistry.TemplateConfig; import org.elasticsearch.xpack.watcher.transform.TransformModule; import org.elasticsearch.xpack.watcher.transport.actions.ack.AckWatchAction; import org.elasticsearch.xpack.watcher.transport.actions.ack.TransportAckWatchAction; import org.elasticsearch.xpack.watcher.transport.actions.activate.ActivateWatchAction; import org.elasticsearch.xpack.watcher.transport.actions.activate.TransportActivateWatchAction; import org.elasticsearch.xpack.watcher.transport.actions.delete.DeleteWatchAction; import org.elasticsearch.xpack.watcher.transport.actions.delete.TransportDeleteWatchAction; import org.elasticsearch.xpack.watcher.transport.actions.execute.ExecuteWatchAction; import org.elasticsearch.xpack.watcher.transport.actions.execute.TransportExecuteWatchAction; import org.elasticsearch.xpack.watcher.transport.actions.get.GetWatchAction; import org.elasticsearch.xpack.watcher.transport.actions.get.TransportGetWatchAction; import org.elasticsearch.xpack.watcher.transport.actions.put.PutWatchAction; import org.elasticsearch.xpack.watcher.transport.actions.put.TransportPutWatchAction; import org.elasticsearch.xpack.watcher.transport.actions.service.TransportWatcherServiceAction; import org.elasticsearch.xpack.watcher.transport.actions.service.WatcherServiceAction; import org.elasticsearch.xpack.watcher.transport.actions.stats.TransportWatcherStatsAction; import org.elasticsearch.xpack.watcher.transport.actions.stats.WatcherStatsAction; import org.elasticsearch.xpack.watcher.trigger.TriggerModule; import org.elasticsearch.xpack.watcher.trigger.schedule.ScheduleModule; import org.elasticsearch.xpack.watcher.watch.WatchModule; import org.elasticsearch.xpack.watcher.watch.WatchStore; import org.joda.time.DateTime; import org.joda.time.DateTimeZone; import java.util.ArrayList; import java.util.Arrays; import java.util.Collection; import java.util.Collections; import java.util.List; import java.util.function.Function; import static java.util.Collections.emptyList; public class Watcher implements ActionPlugin, ScriptPlugin { public static final Setting<String> INDEX_WATCHER_VERSION_SETTING = new Setting<>("index.xpack.watcher.plugin.version", "", Function.identity(), Setting.Property.IndexScope); public static final Setting<String> INDEX_WATCHER_TEMPLATE_VERSION_SETTING = new Setting<>("index.xpack.watcher.template.version", "", Function.identity(), Setting.Property.IndexScope); public static final Setting<Boolean> ENCRYPT_SENSITIVE_DATA_SETTING = Setting.boolSetting("xpack.watcher.encrypt_sensitive_data", false, Setting.Property.NodeScope); public static final Setting<TimeValue> MAX_STOP_TIMEOUT_SETTING = Setting.timeSetting("xpack.watcher.stop.timeout", TimeValue.timeValueSeconds(30), Setting.Property.NodeScope); private static final ScriptContext.Plugin SCRIPT_PLUGIN = new ScriptContext.Plugin("xpack", "watch"); public static final ScriptContext SCRIPT_CONTEXT = SCRIPT_PLUGIN::getKey; private static final Logger logger = Loggers.getLogger(XPackPlugin.class); static { MetaData.registerPrototype(WatcherMetaData.TYPE, WatcherMetaData.PROTO); } protected final Settings settings; protected final boolean transportClient; protected final boolean enabled; public Watcher(Settings settings) { this.settings = settings; transportClient = "transport".equals(settings.get(Client.CLIENT_TYPE_SETTING_S.getKey())); this.enabled = XPackSettings.WATCHER_ENABLED.get(settings); validAutoCreateIndex(settings); } public Collection<Module> nodeModules() { List<Module> modules = new ArrayList<>(); modules.add(new WatcherModule(enabled, transportClient)); if (enabled && transportClient == false) { modules.add(new WatchModule()); modules.add(new WatcherClientModule()); modules.add(new TransformModule()); modules.add(new TriggerModule(settings)); modules.add(new ScheduleModule()); modules.add(new ConditionModule()); modules.add(new InputModule()); modules.add(new WatcherActionModule()); modules.add(new HistoryModule()); modules.add(new ExecutionModule()); } return modules; } public Settings additionalSettings() { return Settings.EMPTY; } public List<Setting<?>> getSettings() { List<Setting<?>> settings = new ArrayList<>(); for (TemplateConfig templateConfig : WatcherIndexTemplateRegistry.TEMPLATE_CONFIGS) { settings.add(templateConfig.getSetting()); } settings.add(INDEX_WATCHER_VERSION_SETTING); settings.add(INDEX_WATCHER_TEMPLATE_VERSION_SETTING); settings.add(MAX_STOP_TIMEOUT_SETTING); settings.add(ExecutionService.DEFAULT_THROTTLE_PERIOD_SETTING); settings.add(Setting.intSetting("xpack.watcher.execution.scroll.size", 0, Setting.Property.NodeScope)); settings.add(Setting.intSetting("xpack.watcher.watch.scroll.size", 0, Setting.Property.NodeScope)); settings.add(ENCRYPT_SENSITIVE_DATA_SETTING); settings.add(Setting.simpleString("xpack.watcher.internal.ops.search.default_timeout", Setting.Property.NodeScope)); settings.add(Setting.simpleString("xpack.watcher.internal.ops.bulk.default_timeout", Setting.Property.NodeScope)); settings.add(Setting.simpleString("xpack.watcher.internal.ops.index.default_timeout", Setting.Property.NodeScope)); settings.add(Setting.simpleString("xpack.watcher.actions.index.default_timeout", Setting.Property.NodeScope)); settings.add(Setting.simpleString("xpack.watcher.index.rest.direct_access", Setting.Property.NodeScope)); settings.add(Setting.simpleString("xpack.watcher.trigger.schedule.engine", Setting.Property.NodeScope)); settings.add(Setting.simpleString("xpack.watcher.input.search.default_timeout", Setting.Property.NodeScope)); settings.add(Setting.simpleString("xpack.watcher.transform.search.default_timeout", Setting.Property.NodeScope)); settings.add(Setting.simpleString("xpack.watcher.trigger.schedule.ticker.tick_interval", Setting.Property.NodeScope)); settings.add(Setting.simpleString("xpack.watcher.execution.scroll.timeout", Setting.Property.NodeScope)); settings.add(Setting.simpleString("xpack.watcher.start_immediately", Setting.Property.NodeScope)); return settings; } public List<ExecutorBuilder<?>> getExecutorBuilders(final Settings settings) { if (enabled) { final FixedExecutorBuilder builder = new FixedExecutorBuilder( settings, InternalWatchExecutor.THREAD_POOL_NAME, 5 * EsExecutors.boundedNumberOfProcessors(settings), 1000, "xpack.watcher.thread_pool"); return Collections.singletonList(builder); } return Collections.emptyList(); } @Override public List<ActionHandler<? extends ActionRequest<?>, ? extends ActionResponse>> getActions() { if (false == enabled) { return emptyList(); } return Arrays.asList(new ActionHandler<>(PutWatchAction.INSTANCE, TransportPutWatchAction.class), new ActionHandler<>(DeleteWatchAction.INSTANCE, TransportDeleteWatchAction.class), new ActionHandler<>(GetWatchAction.INSTANCE, TransportGetWatchAction.class), new ActionHandler<>(WatcherStatsAction.INSTANCE, TransportWatcherStatsAction.class), new ActionHandler<>(AckWatchAction.INSTANCE, TransportAckWatchAction.class), new ActionHandler<>(ActivateWatchAction.INSTANCE, TransportActivateWatchAction.class), new ActionHandler<>(WatcherServiceAction.INSTANCE, TransportWatcherServiceAction.class), new ActionHandler<>(ExecuteWatchAction.INSTANCE, TransportExecuteWatchAction.class)); } @Override public List<Class<? extends RestHandler>> getRestHandlers() { if (false == enabled) { return emptyList(); } return Arrays.asList(RestPutWatchAction.class, RestDeleteWatchAction.class, RestWatcherStatsAction.class, RestGetWatchAction.class, RestWatchServiceAction.class, RestAckWatchAction.class, RestActivateWatchAction.class, RestExecuteWatchAction.class, RestHijackOperationAction.class); } @Override public ScriptContext.Plugin getCustomScriptContexts() { return SCRIPT_PLUGIN; } static void validAutoCreateIndex(Settings settings) { String value = settings.get("action.auto_create_index"); if (value == null) { return; } String errorMessage = LoggerMessageFormat.format("the [action.auto_create_index] setting value [{}] is too" + " restrictive. disable [action.auto_create_index] or set it to " + "[{}, {}, {}*]", (Object) value, WatchStore.INDEX, TriggeredWatchStore.INDEX_NAME, HistoryStore.INDEX_PREFIX); if (Booleans.isExplicitFalse(value)) { throw new IllegalArgumentException(errorMessage); } if (Booleans.isExplicitTrue(value)) { return; } String[] matches = Strings.commaDelimitedListToStringArray(value); List<String> indices = new ArrayList<>(); indices.add(".watches"); indices.add(".triggered_watches"); DateTime now = new DateTime(DateTimeZone.UTC); indices.add(HistoryStore.getHistoryIndexNameForTime(now)); indices.add(HistoryStore.getHistoryIndexNameForTime(now.plusDays(1))); indices.add(HistoryStore.getHistoryIndexNameForTime(now.plusMonths(1))); indices.add(HistoryStore.getHistoryIndexNameForTime(now.plusMonths(2))); indices.add(HistoryStore.getHistoryIndexNameForTime(now.plusMonths(3))); indices.add(HistoryStore.getHistoryIndexNameForTime(now.plusMonths(4))); indices.add(HistoryStore.getHistoryIndexNameForTime(now.plusMonths(5))); indices.add(HistoryStore.getHistoryIndexNameForTime(now.plusMonths(6))); for (String index : indices) { boolean matched = false; for (String match : matches) { char c = match.charAt(0); if (c == '-') { if (Regex.simpleMatch(match.substring(1), index)) { throw new IllegalArgumentException(errorMessage); } } else if (c == '+') { if (Regex.simpleMatch(match.substring(1), index)) { matched = true; break; } } else { if (Regex.simpleMatch(match, index)) { matched = true; break; } } } if (!matched) { throw new IllegalArgumentException(errorMessage); } } logger.warn("the [action.auto_create_index] setting is configured to be restrictive [{}]. " + " for the next 6 months daily history indices are allowed to be created, but please make sure" + " that any future history indices after 6 months with the pattern " + "[.watcher-history-YYYY.MM.dd] are allowed to be created", value); } }
elasticsearch/src/main/java/org/elasticsearch/xpack/watcher/Watcher.java
/* * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one * or more contributor license agreements. Licensed under the Elastic License; * you may not use this file except in compliance with the Elastic License. */ package org.elasticsearch.xpack.watcher; import org.apache.logging.log4j.Logger; import org.elasticsearch.action.ActionRequest; import org.elasticsearch.action.ActionResponse; import org.elasticsearch.client.Client; import org.elasticsearch.cluster.metadata.MetaData; import org.elasticsearch.common.Booleans; import org.elasticsearch.common.Strings; import org.elasticsearch.common.inject.Module; import org.elasticsearch.common.logging.LoggerMessageFormat; import org.elasticsearch.common.logging.Loggers; import org.elasticsearch.common.regex.Regex; import org.elasticsearch.common.settings.Setting; import org.elasticsearch.common.settings.Settings; import org.elasticsearch.common.unit.TimeValue; import org.elasticsearch.common.util.concurrent.EsExecutors; import org.elasticsearch.plugins.ActionPlugin; import org.elasticsearch.plugins.ScriptPlugin; import org.elasticsearch.rest.RestHandler; import org.elasticsearch.script.ScriptContext; import org.elasticsearch.threadpool.ExecutorBuilder; import org.elasticsearch.threadpool.ScalingExecutorBuilder; import org.elasticsearch.xpack.XPackPlugin; import org.elasticsearch.xpack.XPackSettings; import org.elasticsearch.xpack.watcher.actions.WatcherActionModule; import org.elasticsearch.xpack.watcher.client.WatcherClientModule; import org.elasticsearch.xpack.watcher.condition.ConditionModule; import org.elasticsearch.xpack.watcher.execution.ExecutionModule; import org.elasticsearch.xpack.watcher.execution.ExecutionService; import org.elasticsearch.xpack.watcher.execution.InternalWatchExecutor; import org.elasticsearch.xpack.watcher.execution.TriggeredWatchStore; import org.elasticsearch.xpack.watcher.history.HistoryModule; import org.elasticsearch.xpack.watcher.history.HistoryStore; import org.elasticsearch.xpack.watcher.input.InputModule; import org.elasticsearch.xpack.watcher.rest.action.RestAckWatchAction; import org.elasticsearch.xpack.watcher.rest.action.RestActivateWatchAction; import org.elasticsearch.xpack.watcher.rest.action.RestDeleteWatchAction; import org.elasticsearch.xpack.watcher.rest.action.RestExecuteWatchAction; import org.elasticsearch.xpack.watcher.rest.action.RestGetWatchAction; import org.elasticsearch.xpack.watcher.rest.action.RestHijackOperationAction; import org.elasticsearch.xpack.watcher.rest.action.RestPutWatchAction; import org.elasticsearch.xpack.watcher.rest.action.RestWatchServiceAction; import org.elasticsearch.xpack.watcher.rest.action.RestWatcherStatsAction; import org.elasticsearch.xpack.watcher.support.WatcherIndexTemplateRegistry; import org.elasticsearch.xpack.watcher.support.WatcherIndexTemplateRegistry.TemplateConfig; import org.elasticsearch.xpack.watcher.transform.TransformModule; import org.elasticsearch.xpack.watcher.transport.actions.ack.AckWatchAction; import org.elasticsearch.xpack.watcher.transport.actions.ack.TransportAckWatchAction; import org.elasticsearch.xpack.watcher.transport.actions.activate.ActivateWatchAction; import org.elasticsearch.xpack.watcher.transport.actions.activate.TransportActivateWatchAction; import org.elasticsearch.xpack.watcher.transport.actions.delete.DeleteWatchAction; import org.elasticsearch.xpack.watcher.transport.actions.delete.TransportDeleteWatchAction; import org.elasticsearch.xpack.watcher.transport.actions.execute.ExecuteWatchAction; import org.elasticsearch.xpack.watcher.transport.actions.execute.TransportExecuteWatchAction; import org.elasticsearch.xpack.watcher.transport.actions.get.GetWatchAction; import org.elasticsearch.xpack.watcher.transport.actions.get.TransportGetWatchAction; import org.elasticsearch.xpack.watcher.transport.actions.put.PutWatchAction; import org.elasticsearch.xpack.watcher.transport.actions.put.TransportPutWatchAction; import org.elasticsearch.xpack.watcher.transport.actions.service.TransportWatcherServiceAction; import org.elasticsearch.xpack.watcher.transport.actions.service.WatcherServiceAction; import org.elasticsearch.xpack.watcher.transport.actions.stats.TransportWatcherStatsAction; import org.elasticsearch.xpack.watcher.transport.actions.stats.WatcherStatsAction; import org.elasticsearch.xpack.watcher.trigger.TriggerModule; import org.elasticsearch.xpack.watcher.trigger.schedule.ScheduleModule; import org.elasticsearch.xpack.watcher.watch.WatchModule; import org.elasticsearch.xpack.watcher.watch.WatchStore; import org.joda.time.DateTime; import org.joda.time.DateTimeZone; import java.util.ArrayList; import java.util.Arrays; import java.util.Collection; import java.util.Collections; import java.util.List; import java.util.function.Function; import static java.util.Collections.emptyList; public class Watcher implements ActionPlugin, ScriptPlugin { public static final Setting<String> INDEX_WATCHER_VERSION_SETTING = new Setting<>("index.xpack.watcher.plugin.version", "", Function.identity(), Setting.Property.IndexScope); public static final Setting<String> INDEX_WATCHER_TEMPLATE_VERSION_SETTING = new Setting<>("index.xpack.watcher.template.version", "", Function.identity(), Setting.Property.IndexScope); public static final Setting<Boolean> ENCRYPT_SENSITIVE_DATA_SETTING = Setting.boolSetting("xpack.watcher.encrypt_sensitive_data", false, Setting.Property.NodeScope); public static final Setting<TimeValue> MAX_STOP_TIMEOUT_SETTING = Setting.timeSetting("xpack.watcher.stop.timeout", TimeValue.timeValueSeconds(30), Setting.Property.NodeScope); private static final ScriptContext.Plugin SCRIPT_PLUGIN = new ScriptContext.Plugin("xpack", "watch"); public static final ScriptContext SCRIPT_CONTEXT = SCRIPT_PLUGIN::getKey; private static final Logger logger = Loggers.getLogger(XPackPlugin.class); static { MetaData.registerPrototype(WatcherMetaData.TYPE, WatcherMetaData.PROTO); } protected final Settings settings; protected final boolean transportClient; protected final boolean enabled; public Watcher(Settings settings) { this.settings = settings; transportClient = "transport".equals(settings.get(Client.CLIENT_TYPE_SETTING_S.getKey())); this.enabled = XPackSettings.WATCHER_ENABLED.get(settings); validAutoCreateIndex(settings); } public Collection<Module> nodeModules() { List<Module> modules = new ArrayList<>(); modules.add(new WatcherModule(enabled, transportClient)); if (enabled && transportClient == false) { modules.add(new WatchModule()); modules.add(new WatcherClientModule()); modules.add(new TransformModule()); modules.add(new TriggerModule(settings)); modules.add(new ScheduleModule()); modules.add(new ConditionModule()); modules.add(new InputModule()); modules.add(new WatcherActionModule()); modules.add(new HistoryModule()); modules.add(new ExecutionModule()); } return modules; } public Settings additionalSettings() { return Settings.EMPTY; } public List<Setting<?>> getSettings() { List<Setting<?>> settings = new ArrayList<>(); for (TemplateConfig templateConfig : WatcherIndexTemplateRegistry.TEMPLATE_CONFIGS) { settings.add(templateConfig.getSetting()); } settings.add(INDEX_WATCHER_VERSION_SETTING); settings.add(INDEX_WATCHER_TEMPLATE_VERSION_SETTING); settings.add(MAX_STOP_TIMEOUT_SETTING); settings.add(ExecutionService.DEFAULT_THROTTLE_PERIOD_SETTING); settings.add(Setting.intSetting("xpack.watcher.execution.scroll.size", 0, Setting.Property.NodeScope)); settings.add(Setting.intSetting("xpack.watcher.watch.scroll.size", 0, Setting.Property.NodeScope)); settings.add(ENCRYPT_SENSITIVE_DATA_SETTING); settings.add(Setting.simpleString("xpack.watcher.internal.ops.search.default_timeout", Setting.Property.NodeScope)); settings.add(Setting.simpleString("xpack.watcher.internal.ops.bulk.default_timeout", Setting.Property.NodeScope)); settings.add(Setting.simpleString("xpack.watcher.internal.ops.index.default_timeout", Setting.Property.NodeScope)); settings.add(Setting.simpleString("xpack.watcher.actions.index.default_timeout", Setting.Property.NodeScope)); settings.add(Setting.simpleString("xpack.watcher.index.rest.direct_access", Setting.Property.NodeScope)); settings.add(Setting.simpleString("xpack.watcher.trigger.schedule.engine", Setting.Property.NodeScope)); settings.add(Setting.simpleString("xpack.watcher.input.search.default_timeout", Setting.Property.NodeScope)); settings.add(Setting.simpleString("xpack.watcher.transform.search.default_timeout", Setting.Property.NodeScope)); settings.add(Setting.simpleString("xpack.watcher.trigger.schedule.ticker.tick_interval", Setting.Property.NodeScope)); settings.add(Setting.simpleString("xpack.watcher.execution.scroll.timeout", Setting.Property.NodeScope)); settings.add(Setting.simpleString("xpack.watcher.start_immediately", Setting.Property.NodeScope)); return settings; } public List<ExecutorBuilder<?>> getExecutorBuilders(final Settings settings) { if (enabled) { final ScalingExecutorBuilder builder = new ScalingExecutorBuilder( InternalWatchExecutor.THREAD_POOL_NAME, 0, // watcher threads can block on I/O for a long time, so we let this // pool be large so that execution of unblocked watches can proceed 5 * EsExecutors.boundedNumberOfProcessors(settings), TimeValue.timeValueMinutes(5), "xpack.watcher.thread_pool"); return Collections.singletonList(builder); } return Collections.emptyList(); } @Override public List<ActionHandler<? extends ActionRequest<?>, ? extends ActionResponse>> getActions() { if (false == enabled) { return emptyList(); } return Arrays.asList(new ActionHandler<>(PutWatchAction.INSTANCE, TransportPutWatchAction.class), new ActionHandler<>(DeleteWatchAction.INSTANCE, TransportDeleteWatchAction.class), new ActionHandler<>(GetWatchAction.INSTANCE, TransportGetWatchAction.class), new ActionHandler<>(WatcherStatsAction.INSTANCE, TransportWatcherStatsAction.class), new ActionHandler<>(AckWatchAction.INSTANCE, TransportAckWatchAction.class), new ActionHandler<>(ActivateWatchAction.INSTANCE, TransportActivateWatchAction.class), new ActionHandler<>(WatcherServiceAction.INSTANCE, TransportWatcherServiceAction.class), new ActionHandler<>(ExecuteWatchAction.INSTANCE, TransportExecuteWatchAction.class)); } @Override public List<Class<? extends RestHandler>> getRestHandlers() { if (false == enabled) { return emptyList(); } return Arrays.asList(RestPutWatchAction.class, RestDeleteWatchAction.class, RestWatcherStatsAction.class, RestGetWatchAction.class, RestWatchServiceAction.class, RestAckWatchAction.class, RestActivateWatchAction.class, RestExecuteWatchAction.class, RestHijackOperationAction.class); } @Override public ScriptContext.Plugin getCustomScriptContexts() { return SCRIPT_PLUGIN; } static void validAutoCreateIndex(Settings settings) { String value = settings.get("action.auto_create_index"); if (value == null) { return; } String errorMessage = LoggerMessageFormat.format("the [action.auto_create_index] setting value [{}] is too" + " restrictive. disable [action.auto_create_index] or set it to " + "[{}, {}, {}*]", (Object) value, WatchStore.INDEX, TriggeredWatchStore.INDEX_NAME, HistoryStore.INDEX_PREFIX); if (Booleans.isExplicitFalse(value)) { throw new IllegalArgumentException(errorMessage); } if (Booleans.isExplicitTrue(value)) { return; } String[] matches = Strings.commaDelimitedListToStringArray(value); List<String> indices = new ArrayList<>(); indices.add(".watches"); indices.add(".triggered_watches"); DateTime now = new DateTime(DateTimeZone.UTC); indices.add(HistoryStore.getHistoryIndexNameForTime(now)); indices.add(HistoryStore.getHistoryIndexNameForTime(now.plusDays(1))); indices.add(HistoryStore.getHistoryIndexNameForTime(now.plusMonths(1))); indices.add(HistoryStore.getHistoryIndexNameForTime(now.plusMonths(2))); indices.add(HistoryStore.getHistoryIndexNameForTime(now.plusMonths(3))); indices.add(HistoryStore.getHistoryIndexNameForTime(now.plusMonths(4))); indices.add(HistoryStore.getHistoryIndexNameForTime(now.plusMonths(5))); indices.add(HistoryStore.getHistoryIndexNameForTime(now.plusMonths(6))); for (String index : indices) { boolean matched = false; for (String match : matches) { char c = match.charAt(0); if (c == '-') { if (Regex.simpleMatch(match.substring(1), index)) { throw new IllegalArgumentException(errorMessage); } } else if (c == '+') { if (Regex.simpleMatch(match.substring(1), index)) { matched = true; break; } } else { if (Regex.simpleMatch(match, index)) { matched = true; break; } } } if (!matched) { throw new IllegalArgumentException(errorMessage); } } logger.warn("the [action.auto_create_index] setting is configured to be restrictive [{}]. " + " for the next 6 months daily history indices are allowed to be created, but please make sure" + " that any future history indices after 6 months with the pattern " + "[.watcher-history-YYYY.MM.dd] are allowed to be created", value); } }
Revert "Change Watcher thread pool to be scaling" This reverts commit elastic/x-pack@943bd259f939111dccc3d204b5f32727ebc334ed. See discussion in elastic/elasticsearch#3660 Original commit: elastic/x-pack-elasticsearch@35d236df59012b483f48cae1827afee4d19997a9
elasticsearch/src/main/java/org/elasticsearch/xpack/watcher/Watcher.java
Revert "Change Watcher thread pool to be scaling"
<ide><path>lasticsearch/src/main/java/org/elasticsearch/xpack/watcher/Watcher.java <ide> import org.elasticsearch.rest.RestHandler; <ide> import org.elasticsearch.script.ScriptContext; <ide> import org.elasticsearch.threadpool.ExecutorBuilder; <del>import org.elasticsearch.threadpool.ScalingExecutorBuilder; <add>import org.elasticsearch.threadpool.FixedExecutorBuilder; <ide> import org.elasticsearch.xpack.XPackPlugin; <ide> import org.elasticsearch.xpack.XPackSettings; <ide> import org.elasticsearch.xpack.watcher.actions.WatcherActionModule; <ide> <ide> public List<ExecutorBuilder<?>> getExecutorBuilders(final Settings settings) { <ide> if (enabled) { <del> final ScalingExecutorBuilder builder = <del> new ScalingExecutorBuilder( <add> final FixedExecutorBuilder builder = <add> new FixedExecutorBuilder( <add> settings, <ide> InternalWatchExecutor.THREAD_POOL_NAME, <del> 0, <del> // watcher threads can block on I/O for a long time, so we let this <del> // pool be large so that execution of unblocked watches can proceed <ide> 5 * EsExecutors.boundedNumberOfProcessors(settings), <del> TimeValue.timeValueMinutes(5), <add> 1000, <ide> "xpack.watcher.thread_pool"); <ide> return Collections.singletonList(builder); <ide> }
Java
apache-2.0
c0c42d4b88232ade4093cf24a92e735767912861
0
hgl888/hellocharts-android,AndroidMarv/hellocharts-android,HKMOpen/hellocharts-android,hzw1199/hellocharts-android,wizardly1985/hellocharts-android,xy2009/hellocharts-android,jiangzhonghui/hellocharts-android,huangsongyan/hellocharts-android,makbn/hellocharts-android,harshul1610/hellocharts-android,MateuszMlodawski/hellocharts-android,awesome-niu/hellocharts-android,xialeizhou/hellocharts-android,altihou/hellocharts-android,finch0219/hellocharts-android,Thought-Technology-Ltd/hellocharts-android,oursky/hellocharts-android,ishan1604/hellocharts-android,beingmiakashs/hellocharts-android,wanghao200906/hellocharts-android,heamon7/hellocharts-android,tsdl2013/hellocharts-android,lecho/hellocharts-android,chenrui2014/hellocharts-android,amozoss/hellocharts-android,lemaiyan/hellocharts-android,a19920714liou/hellocharts-android,quki/hellocharts-android,jiancao/hellocharts-android,Nicasso/hellocharts-android,jingle1267/hellocharts-android,WellframeInc/hellocharts-android,WasimMemon/hellocharts-android,leokemp/hellocharts-android,wv1124/hellocharts-android,yangl080124/hellocharts-android,damianflannery/hellocharts-android,mohcicin/hellocharts-android,viii2050/hellocharts-android,jinglinxiao/hellocharts,SmarkSeven/hellocharts-android
package lecho.lib.hellocharts.renderer; import lecho.lib.hellocharts.Chart; import lecho.lib.hellocharts.ChartComputator; import lecho.lib.hellocharts.ColumnChartDataProvider; import lecho.lib.hellocharts.model.Column; import lecho.lib.hellocharts.model.ColumnChartData; import lecho.lib.hellocharts.model.ColumnValue; import lecho.lib.hellocharts.util.Utils; import android.content.Context; import android.graphics.Canvas; import android.graphics.Paint; import android.graphics.Paint.Cap; import android.graphics.PointF; import android.graphics.RectF; public class ColumnChartRenderer extends AbstractChartRenderer { public static final int DEFAULT_SUBCOLUMN_SPACING_DP = 1; public static final int DEFAULT_COLUMN_TOUCH_ADDITIONAL_WIDTH_DP = 4; private static final float DEFAULT_BASE_VALUE = 0.0f; private static final int MODE_DRAW = 0; private static final int MODE_CHECK_TOUCH = 1; private static final int MODE_HIGHLIGHT = 2; private ColumnChartDataProvider dataProvider; private int touchAdditionalWidth; private int subcolumnSpacing; private Paint columnPaint = new Paint(); private RectF drawRect = new RectF(); private PointF touchedPoint = new PointF(); public ColumnChartRenderer(Context context, Chart chart, ColumnChartDataProvider dataProvider) { super(context, chart); this.dataProvider = dataProvider; subcolumnSpacing = Utils.dp2px(density, DEFAULT_SUBCOLUMN_SPACING_DP); touchAdditionalWidth = Utils.dp2px(density, DEFAULT_COLUMN_TOUCH_ADDITIONAL_WIDTH_DP); columnPaint.setAntiAlias(true); columnPaint.setStyle(Paint.Style.FILL); columnPaint.setStrokeCap(Cap.SQUARE); } @Override public void initMaxViewport() { calculateMaxViewport(); chart.getChartComputator().setMaxViewport(tempMaxViewport); } @Override public void initDataMeasuremetns() { chart.getChartComputator().setInternalMargin(labelMargin);// Using label margin because I'm lazy:P labelPaint.setTextSize(Utils.sp2px(scaledDensity, chart.getChartData().getValueLabelTextSize())); labelPaint.getFontMetricsInt(fontMetrics); } public void draw(Canvas canvas) { final ColumnChartData data = dataProvider.getColumnChartData(); if (data.isStacked()) { drawColumnForStacked(canvas); if (isTouched()) { highlightColumnForStacked(canvas); } } else { drawColumnsForSubcolumns(canvas); if (isTouched()) { highlightColumnsForSubcolumns(canvas); } } } @Override public void drawUnclipped(Canvas canvas) { // Do nothing, for this kind of chart there is nothing to draw beyond clipped area } public boolean checkTouch(float touchX, float touchY) { oldSelectedValue.set(selectedValue); selectedValue.clear(); final ColumnChartData data = dataProvider.getColumnChartData(); if (data.isStacked()) { checkTouchForStacked(touchX, touchY); } else { checkTouchForSubcolumns(touchX, touchY); } // Check if touch is still on the same value, if not return false. if (oldSelectedValue.isSet() && selectedValue.isSet() && !oldSelectedValue.equals(selectedValue)) { return false; } return isTouched(); } private void calculateMaxViewport() { final ColumnChartData data = dataProvider.getColumnChartData(); // Column chart always has X values from 0 to numColumns-1, to add some margin on the left and right I added // extra 0.5 to the each side, that margins will be negative scaled according to number of columns, so for more // columns there will be less margin. tempMaxViewport.set(-0.5f, DEFAULT_BASE_VALUE, data.getColumns().size() - 0.5f, DEFAULT_BASE_VALUE); if (data.isStacked()) { calculateMaxViewportForStacked(data); } else { calculateMaxViewportForSubcolumns(data); } } private void calculateMaxViewportForSubcolumns(ColumnChartData data) { for (Column column : data.getColumns()) { for (ColumnValue columnValue : column.getValues()) { if (columnValue.getValue() >= DEFAULT_BASE_VALUE && columnValue.getValue() > tempMaxViewport.top) { tempMaxViewport.top = columnValue.getValue(); } if (columnValue.getValue() < DEFAULT_BASE_VALUE && columnValue.getValue() < tempMaxViewport.bottom) { tempMaxViewport.bottom = columnValue.getValue(); } } } } private void calculateMaxViewportForStacked(ColumnChartData data) { for (Column column : data.getColumns()) { float sumPositive = DEFAULT_BASE_VALUE; float sumNegative = DEFAULT_BASE_VALUE; for (ColumnValue columnValue : column.getValues()) { if (columnValue.getValue() >= DEFAULT_BASE_VALUE) { sumPositive += columnValue.getValue(); } else { sumNegative += columnValue.getValue(); } } if (sumPositive > tempMaxViewport.top) { tempMaxViewport.top = sumPositive; } if (sumNegative < tempMaxViewport.bottom) { tempMaxViewport.bottom = sumNegative; } } } private void drawColumnsForSubcolumns(Canvas canvas) { final ColumnChartData data = dataProvider.getColumnChartData(); final ChartComputator computator = chart.getChartComputator(); final float columnWidth = calculateColumnWidth(computator, data.getFillRatio()); int columnIndex = 0; for (Column column : data.getColumns()) { processColumnForSubcolumns(canvas, computator, column, columnWidth, columnIndex, MODE_DRAW); ++columnIndex; } } private void highlightColumnsForSubcolumns(Canvas canvas) { final ColumnChartData data = dataProvider.getColumnChartData(); final ChartComputator computator = chart.getChartComputator(); final float columnWidth = calculateColumnWidth(computator, data.getFillRatio()); Column column = data.getColumns().get(selectedValue.firstIndex); processColumnForSubcolumns(canvas, computator, column, columnWidth, selectedValue.firstIndex, MODE_HIGHLIGHT); } private void checkTouchForSubcolumns(float touchX, float touchY) { // Using member variable to hold touch point to avoid too much parameters in methods. touchedPoint.x = touchX; touchedPoint.y = touchY; final ColumnChartData data = dataProvider.getColumnChartData(); final ChartComputator computator = chart.getChartComputator(); final float columnWidth = calculateColumnWidth(computator, data.getFillRatio()); int columnIndex = 0; for (Column column : data.getColumns()) { // canvas is not needed for checking touch processColumnForSubcolumns(null, computator, column, columnWidth, columnIndex, MODE_CHECK_TOUCH); ++columnIndex; } } private void processColumnForSubcolumns(Canvas canvas, ChartComputator computator, Column column, float columnWidth, int columnIndex, int mode) { // For n subcolumns there will be n-1 spacing and there will be one // subcolumn for every columnValue float subcolumnWidth = (columnWidth - (subcolumnSpacing * (column.getValues().size() - 1))) / column.getValues().size(); if (subcolumnWidth < 1) { subcolumnWidth = 1; } // Columns are indexes from 0 to n, column index is also column X value final float rawX = computator.computeRawX(columnIndex); final float halfColumnWidth = columnWidth / 2; final float baseRawY = computator.computeRawY(DEFAULT_BASE_VALUE); // First subcolumn will starts at the left edge of current column, // rawValueX is horizontal center of that column float subcolumnRawX = rawX - halfColumnWidth; int valueIndex = 0; for (ColumnValue columnValue : column.getValues()) { columnPaint.setColor(columnValue.getColor()); if (subcolumnRawX > rawX + halfColumnWidth) { break; } final float rawY = computator.computeRawY(columnValue.getValue()); calculateRectToDraw(columnValue, subcolumnRawX, subcolumnRawX + subcolumnWidth, baseRawY, rawY); switch (mode) { case MODE_DRAW: drawSubcolumn(canvas, column, columnValue, false); break; case MODE_HIGHLIGHT: highlightSubcolumn(canvas, column, columnValue, valueIndex, false); break; case MODE_CHECK_TOUCH: checkRectToDraw(columnIndex, valueIndex); break; default: // There no else, every case should be handled or exception will // be thrown throw new IllegalStateException("Cannot process column in mode: " + mode); } subcolumnRawX += subcolumnWidth + subcolumnSpacing; ++valueIndex; } } private void drawColumnForStacked(Canvas canvas) { final ColumnChartData data = dataProvider.getColumnChartData(); final ChartComputator computator = chart.getChartComputator(); final float columnWidth = calculateColumnWidth(computator, data.getFillRatio()); // Columns are indexes from 0 to n, column index is also column X value int columnIndex = 0; for (Column column : data.getColumns()) { processColumnForStacked(canvas, computator, column, columnWidth, columnIndex, MODE_DRAW); ++columnIndex; } } private void highlightColumnForStacked(Canvas canvas) { final ColumnChartData data = dataProvider.getColumnChartData(); final ChartComputator computator = chart.getChartComputator(); final float columnWidth = calculateColumnWidth(computator, data.getFillRatio()); // Columns are indexes from 0 to n, column index is also column X value Column column = data.getColumns().get(selectedValue.firstIndex); processColumnForStacked(canvas, computator, column, columnWidth, selectedValue.firstIndex, MODE_HIGHLIGHT); } private void checkTouchForStacked(float touchX, float touchY) { touchedPoint.x = touchX; touchedPoint.y = touchY; final ColumnChartData data = dataProvider.getColumnChartData(); final ChartComputator computator = chart.getChartComputator(); final float columnWidth = calculateColumnWidth(computator, data.getFillRatio()); int columnIndex = 0; for (Column column : data.getColumns()) { // canvas is not needed for checking touch processColumnForStacked(null, computator, column, columnWidth, columnIndex, MODE_CHECK_TOUCH); ++columnIndex; } } private void processColumnForStacked(Canvas canvas, ChartComputator computator, Column column, float columnWidth, int columnIndex, int mode) { final float rawX = computator.computeRawX(columnIndex); final float halfColumnWidth = columnWidth / 2; float mostPositiveValue = DEFAULT_BASE_VALUE; float mostNegativeValue = DEFAULT_BASE_VALUE; float baseValue = DEFAULT_BASE_VALUE; int valueIndex = 0; for (ColumnValue columnValue : column.getValues()) { columnPaint.setColor(columnValue.getColor()); if (columnValue.getValue() >= DEFAULT_BASE_VALUE) { // Using values instead of raw pixels make code easier to // understand(for me) baseValue = mostPositiveValue; mostPositiveValue += columnValue.getValue(); } else { baseValue = mostNegativeValue; mostNegativeValue += columnValue.getValue(); } final float rawBaseY = computator.computeRawY(baseValue); final float rawY = computator.computeRawY(baseValue + columnValue.getValue()); calculateRectToDraw(columnValue, rawX - halfColumnWidth, rawX + halfColumnWidth, rawBaseY, rawY); switch (mode) { case MODE_DRAW: drawSubcolumn(canvas, column, columnValue, true); break; case MODE_HIGHLIGHT: highlightSubcolumn(canvas, column, columnValue, valueIndex, true); break; case MODE_CHECK_TOUCH: checkRectToDraw(columnIndex, valueIndex); break; default: // There no else, every case should be handled or exception will // be thrown throw new IllegalStateException("Cannot process column in mode: " + mode); } ++valueIndex; } } private void drawSubcolumn(Canvas canvas, Column column, ColumnValue columnValue, boolean isStacked) { canvas.drawRect(drawRect, columnPaint); if (column.hasLabels()) { drawLabel(canvas, column, columnValue, isStacked, labelOffset); } } private void highlightSubcolumn(Canvas canvas, Column column, ColumnValue columnValue, int valueIndex, boolean isStacked) { if (selectedValue.secondIndex == valueIndex) { columnPaint.setColor(columnValue.getDarkenColor()); canvas.drawRect(drawRect.left - touchAdditionalWidth, drawRect.top, drawRect.right + touchAdditionalWidth, drawRect.bottom, columnPaint); if (column.hasLabels() || column.hasLabelsOnlyForSelected()) { drawLabel(canvas, column, columnValue, isStacked, labelOffset); } } } private void checkRectToDraw(int columnIndex, int valueIndex) { if (drawRect.contains(touchedPoint.x, touchedPoint.y)) { selectedValue.set(columnIndex, valueIndex); } } private float calculateColumnWidth(final ChartComputator computator, float fillRatio) { // columnWidht should be at least 2 px float columnWidth = fillRatio * computator.getContentRect().width() / computator.getVisibleViewport().width(); if (columnWidth < 2) { columnWidth = 2; } return columnWidth; } private void calculateRectToDraw(ColumnValue columnValue, float left, float right, float rawBaseY, float rawY) { // Calculate rect that will be drawn as column, subcolumn or label background. drawRect.left = left; drawRect.right = right; if (columnValue.getValue() >= DEFAULT_BASE_VALUE) { drawRect.top = rawY; drawRect.bottom = rawBaseY - subcolumnSpacing; } else { drawRect.bottom = rawY; drawRect.top = rawBaseY + subcolumnSpacing; } } private void drawLabel(Canvas canvas, Column column, ColumnValue columnValue, boolean isStacked, float offset) { final ChartComputator computator = chart.getChartComputator(); final int nummChars = column.getFormatter().formatValue(labelBuffer, columnValue.getValue()); final float labelWidth = labelPaint.measureText(labelBuffer, labelBuffer.length - nummChars, nummChars); final int labelHeight = Math.abs(fontMetrics.ascent); float left = drawRect.centerX() - labelWidth / 2 - labelMargin; float right = drawRect.centerX() + labelWidth / 2 + labelMargin; float top; float bottom; if (isStacked && labelHeight < drawRect.height() - (2 * labelMargin)) { // For stacked columns draw label only if label height is less than subcolumn height - (2 * labelMargin). if (columnValue.getValue() >= DEFAULT_BASE_VALUE) { top = drawRect.top; bottom = drawRect.top + labelHeight + labelMargin * 2; } else { top = drawRect.bottom - labelHeight - labelMargin * 2; bottom = drawRect.bottom; } } else if (!isStacked) { // For not stacked draw label at the top for positive and at the bottom for negative values if (columnValue.getValue() >= DEFAULT_BASE_VALUE) { top = drawRect.top - offset - labelHeight - labelMargin * 2; if (top < computator.getContentRect().top) { top = drawRect.top + offset; bottom = drawRect.top + offset + labelHeight + labelMargin * 2; } else { bottom = drawRect.top - offset; } } else { bottom = drawRect.bottom + offset + labelHeight + labelMargin * 2; if (bottom > computator.getContentRect().bottom) { top = drawRect.bottom - offset - labelHeight - labelMargin * 2; bottom = drawRect.bottom - offset; } else { top = drawRect.bottom + offset; } } } else { return; } int orginColor = labelPaint.getColor(); labelPaint.setColor(columnValue.getDarkenColor()); canvas.drawRect(left, top, right, bottom, labelPaint); labelPaint.setColor(orginColor); canvas.drawText(labelBuffer, labelBuffer.length - nummChars, nummChars, left + labelMargin, bottom - labelMargin, labelPaint); } }
hellocharts-library/src/lecho/lib/hellocharts/renderer/ColumnChartRenderer.java
package lecho.lib.hellocharts.renderer; import lecho.lib.hellocharts.Chart; import lecho.lib.hellocharts.ChartComputator; import lecho.lib.hellocharts.ColumnChartDataProvider; import lecho.lib.hellocharts.model.Column; import lecho.lib.hellocharts.model.ColumnChartData; import lecho.lib.hellocharts.model.ColumnValue; import lecho.lib.hellocharts.util.Utils; import android.content.Context; import android.graphics.Canvas; import android.graphics.Paint; import android.graphics.Paint.Cap; import android.graphics.PointF; import android.graphics.RectF; public class ColumnChartRenderer extends AbstractChartRenderer { public static final int DEFAULT_SUBCOLUMN_SPACING_DP = 1; public static final int DEFAULT_COLUMN_TOUCH_ADDITIONAL_WIDTH_DP = 4; private static final float DEFAULT_BASE_VALUE = 0.0f; private static final int MODE_DRAW = 0; private static final int MODE_CHECK_TOUCH = 1; private static final int MODE_HIGHLIGHT = 2; private ColumnChartDataProvider dataProvider; private int touchAdditionalWidth; private int subcolumnSpacing; private Paint columnPaint = new Paint(); private RectF drawRect = new RectF(); private PointF touchedPoint = new PointF(); public ColumnChartRenderer(Context context, Chart chart, ColumnChartDataProvider dataProvider) { super(context, chart); this.dataProvider = dataProvider; subcolumnSpacing = Utils.dp2px(density, DEFAULT_SUBCOLUMN_SPACING_DP); touchAdditionalWidth = Utils.dp2px(density, DEFAULT_COLUMN_TOUCH_ADDITIONAL_WIDTH_DP); columnPaint.setAntiAlias(true); columnPaint.setStyle(Paint.Style.FILL); columnPaint.setStrokeCap(Cap.SQUARE); } @Override public void initMaxViewport() { calculateMaxViewport(); chart.getChartComputator().setMaxViewport(tempMaxViewport); } @Override public void initDataMeasuremetns() { chart.getChartComputator().setInternalMargin(labelMargin);// Using label margin because I'm lazy:P labelPaint.setTextSize(Utils.sp2px(scaledDensity, chart.getChartData().getValueLabelTextSize())); labelPaint.getFontMetricsInt(fontMetrics); } public void draw(Canvas canvas) { final ColumnChartData data = dataProvider.getColumnChartData(); if (data.isStacked()) { drawColumnForStacked(canvas); if (isTouched()) { highlightColumnForStacked(canvas); } } else { drawColumnsForSubcolumns(canvas); if (isTouched()) { highlightColumnsForSubcolumns(canvas); } } } @Override public void drawUnclipped(Canvas canvas) { // Do nothing, for this kind of chart there is nothing to draw beyond clipped area } public boolean checkTouch(float touchX, float touchY) { oldSelectedValue.set(selectedValue); selectedValue.clear(); final ColumnChartData data = dataProvider.getColumnChartData(); if (data.isStacked()) { checkTouchForStacked(touchX, touchY); } else { checkTouchForSubcolumns(touchX, touchY); } // Check if touch is still on the same value, if not return false. if (oldSelectedValue.isSet() && selectedValue.isSet() && !oldSelectedValue.equals(selectedValue)) { return false; } return isTouched(); } private void calculateMaxViewport() { final ColumnChartData data = dataProvider.getColumnChartData(); // Column chart always has X values from 0 to numColumns-1, to add some margin on the left and right I added // extra 0.5 to the each side, that margins will be negative scaled according to number of columns, so for more // columns there will be less margin. tempMaxViewport.set(-0.5f, DEFAULT_BASE_VALUE, data.getColumns().size() - 0.5f, DEFAULT_BASE_VALUE); if (data.isStacked()) { calculateMaxViewportForStacked(data); } else { calculateMaxViewportForSubcolumns(data); } } private void calculateMaxViewportForSubcolumns(ColumnChartData data) { for (Column column : data.getColumns()) { for (ColumnValue columnValue : column.getValues()) { if (columnValue.getValue() >= DEFAULT_BASE_VALUE && columnValue.getValue() > tempMaxViewport.top) { tempMaxViewport.top = columnValue.getValue(); } if (columnValue.getValue() < DEFAULT_BASE_VALUE && columnValue.getValue() < tempMaxViewport.bottom) { tempMaxViewport.bottom = columnValue.getValue(); } } } } private void calculateMaxViewportForStacked(ColumnChartData data) { for (Column column : data.getColumns()) { float sumPositive = DEFAULT_BASE_VALUE; float sumNegative = DEFAULT_BASE_VALUE; for (ColumnValue columnValue : column.getValues()) { if (columnValue.getValue() >= DEFAULT_BASE_VALUE) { sumPositive += columnValue.getValue(); } else { sumNegative += columnValue.getValue(); } } if (sumPositive > tempMaxViewport.top) { tempMaxViewport.top = sumPositive; } if (sumNegative < tempMaxViewport.bottom) { tempMaxViewport.bottom = sumNegative; } } } private void drawColumnsForSubcolumns(Canvas canvas) { final ColumnChartData data = dataProvider.getColumnChartData(); final ChartComputator computator = chart.getChartComputator(); final float columnWidth = calculateColumnWidth(computator, data.getFillRatio()); int columnIndex = 0; for (Column column : data.getColumns()) { processColumnForSubcolumns(canvas, computator, column, columnWidth, columnIndex, MODE_DRAW); ++columnIndex; } } private void highlightColumnsForSubcolumns(Canvas canvas) { final ColumnChartData data = dataProvider.getColumnChartData(); final ChartComputator computator = chart.getChartComputator(); final float columnWidth = calculateColumnWidth(computator, data.getFillRatio()); Column column = data.getColumns().get(selectedValue.firstIndex); processColumnForSubcolumns(canvas, computator, column, columnWidth, selectedValue.firstIndex, MODE_HIGHLIGHT); } private void checkTouchForSubcolumns(float touchX, float touchY) { // Using member variable to hold touch point to avoid too much parameters in methods. touchedPoint.x = touchX; touchedPoint.y = touchY; final ColumnChartData data = dataProvider.getColumnChartData(); final ChartComputator computator = chart.getChartComputator(); final float columnWidth = calculateColumnWidth(computator, data.getFillRatio()); int columnIndex = 0; for (Column column : data.getColumns()) { // canvas is not needed for checking touch processColumnForSubcolumns(null, computator, column, columnWidth, columnIndex, MODE_CHECK_TOUCH); ++columnIndex; } } private void processColumnForSubcolumns(Canvas canvas, ChartComputator computator, Column column, float columnWidth, int columnIndex, int mode) { // For n subcolumns there will be n-1 spacing and there will be one // subcolumn for every columnValue float subcolumnWidth = (columnWidth - (subcolumnSpacing * (column.getValues().size() - 1))) / column.getValues().size(); if (subcolumnWidth < 1) { subcolumnWidth = 1; } // Columns are indexes from 0 to n, column index is also column X value final float rawX = computator.computeRawX(columnIndex); final float halfColumnWidth = columnWidth / 2; final float baseRawY = computator.computeRawY(DEFAULT_BASE_VALUE); // First subcolumn will starts at the left edge of current column, // rawValueX is horizontal center of that column float subcolumnRawX = rawX - halfColumnWidth; int valueIndex = 0; for (ColumnValue columnValue : column.getValues()) { columnPaint.setColor(columnValue.getColor()); if (subcolumnRawX > rawX + halfColumnWidth) { break; } final float rawY = computator.computeRawY(columnValue.getValue()); calculateRectToDraw(columnValue, subcolumnRawX, subcolumnRawX + subcolumnWidth, baseRawY, rawY); switch (mode) { case MODE_DRAW: drawSubcolumn(canvas, column, columnValue, false); break; case MODE_HIGHLIGHT: highlightSubcolumn(canvas, column, columnValue, valueIndex, false); break; case MODE_CHECK_TOUCH: checkRectToDraw(columnIndex, valueIndex); break; default: // There no else, every case should be handled or exception will // be thrown throw new IllegalStateException("Cannot process column in mode: " + mode); } subcolumnRawX += subcolumnWidth + subcolumnSpacing; ++valueIndex; } } private void drawColumnForStacked(Canvas canvas) { final ColumnChartData data = dataProvider.getColumnChartData(); final ChartComputator computator = chart.getChartComputator(); final float columnWidth = calculateColumnWidth(computator, data.getFillRatio()); // Columns are indexes from 0 to n, column index is also column X value int columnIndex = 0; for (Column column : data.getColumns()) { processColumnForStacked(canvas, computator, column, columnWidth, columnIndex, MODE_DRAW); ++columnIndex; } } private void highlightColumnForStacked(Canvas canvas) { final ColumnChartData data = dataProvider.getColumnChartData(); final ChartComputator computator = chart.getChartComputator(); final float columnWidth = calculateColumnWidth(computator, data.getFillRatio()); // Columns are indexes from 0 to n, column index is also column X value Column column = data.getColumns().get(selectedValue.firstIndex); processColumnForStacked(canvas, computator, column, columnWidth, selectedValue.firstIndex, MODE_HIGHLIGHT); } private void checkTouchForStacked(float touchX, float touchY) { touchedPoint.x = touchX; touchedPoint.y = touchY; final ColumnChartData data = dataProvider.getColumnChartData(); final ChartComputator computator = chart.getChartComputator(); final float columnWidth = calculateColumnWidth(computator, data.getFillRatio()); int columnIndex = 0; for (Column column : data.getColumns()) { // canvas is not needed for checking touch processColumnForStacked(null, computator, column, columnWidth, columnIndex, MODE_CHECK_TOUCH); ++columnIndex; } } private void processColumnForStacked(Canvas canvas, ChartComputator computator, Column column, float columnWidth, int columnIndex, int mode) { final float rawX = computator.computeRawX(columnIndex); final float halfColumnWidth = columnWidth / 2; float mostPositiveValue = DEFAULT_BASE_VALUE; float mostNegativeValue = DEFAULT_BASE_VALUE; float baseValue = DEFAULT_BASE_VALUE; int valueIndex = 0; for (ColumnValue columnValue : column.getValues()) { columnPaint.setColor(columnValue.getColor()); if (columnValue.getValue() >= DEFAULT_BASE_VALUE) { // Using values instead of raw pixels make code easier to // understand(for me) baseValue = mostPositiveValue; mostPositiveValue += columnValue.getValue(); } else { baseValue = mostNegativeValue; mostNegativeValue += columnValue.getValue(); } final float rawBaseY = computator.computeRawY(baseValue); final float rawY = computator.computeRawY(baseValue + columnValue.getValue()); calculateRectToDraw(columnValue, rawX - halfColumnWidth, rawX + halfColumnWidth, rawBaseY, rawY); switch (mode) { case MODE_DRAW: drawSubcolumn(canvas, column, columnValue, true); break; case MODE_HIGHLIGHT: highlightSubcolumn(canvas, column, columnValue, valueIndex, true); break; case MODE_CHECK_TOUCH: checkRectToDraw(columnIndex, valueIndex); break; default: // There no else, every case should be handled or exception will // be thrown throw new IllegalStateException("Cannot process column in mode: " + mode); } ++valueIndex; } } private void drawSubcolumn(Canvas canvas, Column column, ColumnValue columnValue, boolean isStacked) { canvas.drawRect(drawRect, columnPaint); if (column.hasLabels()) { drawLabel(canvas, column, columnValue, isStacked, labelOffset); } } private void highlightSubcolumn(Canvas canvas, Column column, ColumnValue columnValue, int valueIndex, boolean isStacked) { if (selectedValue.secondIndex == valueIndex) { columnPaint.setColor(columnValue.getDarkenColor()); canvas.drawRect(drawRect.left - touchAdditionalWidth, drawRect.top, drawRect.right + touchAdditionalWidth, drawRect.bottom, columnPaint); if (column.hasLabels() || column.hasLabelsOnlyForSelected()) { drawLabel(canvas, column, columnValue, isStacked, labelOffset); } } } private void checkRectToDraw(int columnIndex, int valueIndex) { if (drawRect.contains(touchedPoint.x, touchedPoint.y)) { selectedValue.set(columnIndex, valueIndex); } } private float calculateColumnWidth(final ChartComputator computator, float fillRatio) { // columnWidht should be at least 2 px float columnWidth = fillRatio * computator.getContentRect().width() / computator.getVisibleViewport().width(); if (columnWidth < 2) { columnWidth = 2; } return columnWidth; } private void calculateRectToDraw(ColumnValue columnValue, float left, float right, float rawBaseY, float rawY) { // Calculate rect that will be drawn as column, subcolumn or label background. drawRect.left = left; drawRect.right = right; if (columnValue.getValue() >= DEFAULT_BASE_VALUE) { drawRect.top = rawY; drawRect.bottom = rawBaseY - subcolumnSpacing; } else { drawRect.bottom = rawY; drawRect.top = rawBaseY + subcolumnSpacing; } } private void drawLabel(Canvas canvas, Column column, ColumnValue columnValue, boolean isStacked, float offset) { final ChartComputator computator = chart.getChartComputator(); final int nummChars = column.getFormatter().formatValue(labelBuffer, columnValue.getValue()); final float labelWidth = labelPaint.measureText(labelBuffer, labelBuffer.length - nummChars, nummChars); final int labelHeight = Math.abs(fontMetrics.ascent); float left = drawRect.centerX() - labelWidth / 2 - labelMargin; float right = drawRect.centerX() + labelWidth / 2 + labelMargin; float top; float bottom; if (isStacked && labelHeight < drawRect.height()) { // For stacked columns draw label only if label height is less than subcolumn height if (columnValue.getValue() >= DEFAULT_BASE_VALUE) { top = drawRect.top; bottom = drawRect.top + labelHeight + labelMargin * 2; } else { top = drawRect.bottom - labelHeight - labelMargin * 2; bottom = drawRect.bottom; } canvas.drawText(labelBuffer, labelBuffer.length - nummChars, nummChars, left + labelMargin, bottom - labelMargin, labelPaint); } else if (!isStacked) { // For not stacked draw label at the top for positive and at the bottom for negative values if (columnValue.getValue() >= DEFAULT_BASE_VALUE) { top = drawRect.top - offset - labelHeight - labelMargin * 2; if (top < computator.getContentRect().top) { top = drawRect.top + offset; bottom = drawRect.top + offset + labelHeight + labelMargin * 2; } else { bottom = drawRect.top - offset; } } else { bottom = drawRect.bottom + offset + labelHeight + labelMargin * 2; if (bottom > computator.getContentRect().bottom) { top = drawRect.bottom - offset - labelHeight - labelMargin * 2; bottom = drawRect.bottom - offset; } else { top = drawRect.bottom + offset; } } int orginColor = labelPaint.getColor(); labelPaint.setColor(columnValue.getDarkenColor()); canvas.drawRect(left, top, right, bottom, labelPaint); labelPaint.setColor(orginColor); canvas.drawText(labelBuffer, labelBuffer.length - nummChars, nummChars, left + labelMargin, bottom - labelMargin, labelPaint); } else { // do nothing } } }
Improved labels for stacked ColumnChart
hellocharts-library/src/lecho/lib/hellocharts/renderer/ColumnChartRenderer.java
Improved labels for stacked ColumnChart
<ide><path>ellocharts-library/src/lecho/lib/hellocharts/renderer/ColumnChartRenderer.java <ide> float right = drawRect.centerX() + labelWidth / 2 + labelMargin; <ide> float top; <ide> float bottom; <del> if (isStacked && labelHeight < drawRect.height()) { <del> // For stacked columns draw label only if label height is less than subcolumn height <add> if (isStacked && labelHeight < drawRect.height() - (2 * labelMargin)) { <add> // For stacked columns draw label only if label height is less than subcolumn height - (2 * labelMargin). <ide> if (columnValue.getValue() >= DEFAULT_BASE_VALUE) { <ide> top = drawRect.top; <ide> bottom = drawRect.top + labelHeight + labelMargin * 2; <ide> top = drawRect.bottom - labelHeight - labelMargin * 2; <ide> bottom = drawRect.bottom; <ide> } <del> canvas.drawText(labelBuffer, labelBuffer.length - nummChars, nummChars, left + labelMargin, bottom <del> - labelMargin, labelPaint); <ide> } else if (!isStacked) { <ide> // For not stacked draw label at the top for positive and at the bottom for negative values <ide> if (columnValue.getValue() >= DEFAULT_BASE_VALUE) { <ide> top = drawRect.bottom + offset; <ide> } <ide> } <del> int orginColor = labelPaint.getColor(); <del> labelPaint.setColor(columnValue.getDarkenColor()); <del> canvas.drawRect(left, top, right, bottom, labelPaint); <del> labelPaint.setColor(orginColor); <del> canvas.drawText(labelBuffer, labelBuffer.length - nummChars, nummChars, left + labelMargin, bottom <del> - labelMargin, labelPaint); <del> } else { <del> // do nothing <del> } <add> } else { <add> return; <add> } <add> <add> int orginColor = labelPaint.getColor(); <add> labelPaint.setColor(columnValue.getDarkenColor()); <add> canvas.drawRect(left, top, right, bottom, labelPaint); <add> labelPaint.setColor(orginColor); <add> canvas.drawText(labelBuffer, labelBuffer.length - nummChars, nummChars, left + labelMargin, bottom <add> - labelMargin, labelPaint); <add> <ide> } <ide> <ide> }
Java
agpl-3.0
0c6fb8688c98156558f41678d55773e77b154c3a
0
bitsquare/bitsquare,bitsquare/bitsquare,bisq-network/exchange,bisq-network/exchange
/* * This file is part of Bisq. * * Bisq is free software: you can redistribute it and/or modify it * under the terms of the GNU Affero General Public License as published by * the Free Software Foundation, either version 3 of the License, or (at * your option) any later version. * * Bisq is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public * License for more details. * * You should have received a copy of the GNU Affero General Public License * along with Bisq. If not, see <http://www.gnu.org/licenses/>. */ package bisq.desktop.main; import bisq.desktop.common.model.ViewModel; import bisq.desktop.components.BalanceWithConfirmationTextField; import bisq.desktop.components.TxIdTextField; import bisq.desktop.main.overlays.notifications.NotificationCenter; import bisq.desktop.main.overlays.popups.Popup; import bisq.desktop.main.overlays.windows.DisplayAlertMessageWindow; import bisq.desktop.main.overlays.windows.TacWindow; import bisq.desktop.main.overlays.windows.TorNetworkSettingsWindow; import bisq.desktop.main.overlays.windows.WalletPasswordWindow; import bisq.desktop.main.overlays.windows.downloadupdate.DisplayUpdateDownloadWindow; import bisq.desktop.util.GUIUtil; import bisq.core.alert.Alert; import bisq.core.alert.AlertManager; import bisq.core.alert.PrivateNotificationManager; import bisq.core.alert.PrivateNotificationPayload; import bisq.core.app.AppOptionKeys; import bisq.core.app.BisqEnvironment; import bisq.core.app.SetupUtils; import bisq.core.arbitration.ArbitratorManager; import bisq.core.arbitration.DisputeManager; import bisq.core.btc.AddressEntry; import bisq.core.btc.BalanceModel; import bisq.core.btc.listeners.BalanceListener; import bisq.core.btc.wallet.BtcWalletService; import bisq.core.btc.wallet.WalletsManager; import bisq.core.btc.wallet.WalletsSetup; import bisq.core.dao.DaoSetup; import bisq.core.filter.FilterManager; import bisq.core.locale.CurrencyUtil; import bisq.core.locale.FiatCurrency; import bisq.core.locale.Res; import bisq.core.locale.TradeCurrency; import bisq.core.offer.OpenOffer; import bisq.core.offer.OpenOfferManager; import bisq.core.payment.AccountAgeWitnessService; import bisq.core.payment.CryptoCurrencyAccount; import bisq.core.payment.PaymentAccount; import bisq.core.payment.PerfectMoneyAccount; import bisq.core.payment.payload.PaymentMethod; import bisq.core.presentation.BalancePresentation; import bisq.core.presentation.DisputePresentation; import bisq.core.presentation.TradePresentation; import bisq.core.provider.fee.FeeService; import bisq.core.provider.price.MarketPrice; import bisq.core.provider.price.PriceFeedService; import bisq.core.trade.Trade; import bisq.core.trade.TradeManager; import bisq.core.trade.closed.ClosedTradableManager; import bisq.core.trade.failed.FailedTradesManager; import bisq.core.trade.statistics.TradeStatisticsManager; import bisq.core.user.DontShowAgainLookup; import bisq.core.user.Preferences; import bisq.core.user.User; import bisq.core.util.BSFormatter; import bisq.network.crypto.DecryptedDataTuple; import bisq.network.crypto.EncryptionService; import bisq.network.p2p.BootstrapListener; import bisq.network.p2p.P2PService; import bisq.network.p2p.P2PServiceListener; import bisq.network.p2p.network.CloseConnectionReason; import bisq.network.p2p.network.Connection; import bisq.network.p2p.network.ConnectionListener; import bisq.network.p2p.peers.keepalive.messages.Ping; import bisq.common.Clock; import bisq.common.Timer; import bisq.common.UserThread; import bisq.common.app.DevEnv; import bisq.common.app.Version; import bisq.common.crypto.CryptoException; import bisq.common.crypto.KeyRing; import bisq.common.crypto.SealedAndSigned; import bisq.common.storage.CorruptedDatabaseFilesHandler; import org.bitcoinj.core.Coin; import org.bitcoinj.core.Transaction; import org.bitcoinj.store.BlockStoreException; import org.bitcoinj.store.ChainFileLockedException; import com.google.inject.Inject; import com.google.common.net.InetAddresses; import org.fxmisc.easybind.EasyBind; import org.fxmisc.easybind.Subscription; import org.fxmisc.easybind.monadic.MonadicBinding; import javafx.beans.property.BooleanProperty; import javafx.beans.property.DoubleProperty; import javafx.beans.property.IntegerProperty; import javafx.beans.property.ObjectProperty; import javafx.beans.property.SimpleBooleanProperty; import javafx.beans.property.SimpleDoubleProperty; import javafx.beans.property.SimpleIntegerProperty; import javafx.beans.property.SimpleObjectProperty; import javafx.beans.property.SimpleStringProperty; import javafx.beans.property.StringProperty; import javafx.beans.value.ChangeListener; import javafx.collections.FXCollections; import javafx.collections.ListChangeListener; import javafx.collections.ObservableList; import javafx.collections.SetChangeListener; import java.security.Security; import java.net.InetSocketAddress; import java.net.Socket; import java.io.IOException; import java.util.Date; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Optional; import java.util.Random; import java.util.Set; import java.util.concurrent.TimeUnit; import java.util.concurrent.TimeoutException; import java.util.stream.Collectors; import lombok.extern.slf4j.Slf4j; @Slf4j public class MainViewModel implements ViewModel { private static final long STARTUP_TIMEOUT_MINUTES = 4; private final WalletsManager walletsManager; private final WalletsSetup walletsSetup; private final BtcWalletService btcWalletService; private final ArbitratorManager arbitratorManager; private final P2PService p2PService; private final TradeManager tradeManager; private final OpenOfferManager openOfferManager; private final DisputeManager disputeManager; final Preferences preferences; private final AlertManager alertManager; private final PrivateNotificationManager privateNotificationManager; @SuppressWarnings({"unused", "FieldCanBeLocal"}) private final FilterManager filterManager; private final WalletPasswordWindow walletPasswordWindow; private final TradeStatisticsManager tradeStatisticsManager; private final NotificationCenter notificationCenter; private final TacWindow tacWindow; private final Clock clock; private final FeeService feeService; private final DaoSetup daoSetup; private final EncryptionService encryptionService; private final KeyRing keyRing; private final BisqEnvironment bisqEnvironment; private final FailedTradesManager failedTradesManager; private final ClosedTradableManager closedTradableManager; private final AccountAgeWitnessService accountAgeWitnessService; final TorNetworkSettingsWindow torNetworkSettingsWindow; private final CorruptedDatabaseFilesHandler corruptedDatabaseFilesHandler; private final BSFormatter formatter; // BTC network final StringProperty btcInfo = new SimpleStringProperty(Res.get("mainView.footer.btcInfo.initializing")); @SuppressWarnings("ConstantConditions") final DoubleProperty btcSyncProgress = new SimpleDoubleProperty(-1); final StringProperty walletServiceErrorMsg = new SimpleStringProperty(); final StringProperty btcSplashSyncIconId = new SimpleStringProperty(); private final StringProperty marketPriceCurrencyCode = new SimpleStringProperty(""); final ObjectProperty<PriceFeedComboBoxItem> selectedPriceFeedComboBoxItemProperty = new SimpleObjectProperty<>(); final BooleanProperty isFiatCurrencyPriceFeedSelected = new SimpleBooleanProperty(true); final BooleanProperty isCryptoCurrencyPriceFeedSelected = new SimpleBooleanProperty(false); final BooleanProperty isExternallyProvidedPrice = new SimpleBooleanProperty(true); final BooleanProperty isPriceAvailable = new SimpleBooleanProperty(false); final BooleanProperty newVersionAvailableProperty = new SimpleBooleanProperty(false); final IntegerProperty marketPriceUpdated = new SimpleIntegerProperty(0); @SuppressWarnings("FieldCanBeLocal") private MonadicBinding<String> btcInfoBinding; private final StringProperty marketPrice = new SimpleStringProperty(Res.get("shared.na")); // P2P network final StringProperty p2PNetworkInfo = new SimpleStringProperty(); @SuppressWarnings("FieldCanBeLocal") private MonadicBinding<String> p2PNetworkInfoBinding; final BooleanProperty splashP2PNetworkAnimationVisible = new SimpleBooleanProperty(true); final StringProperty p2pNetworkWarnMsg = new SimpleStringProperty(); final StringProperty p2PNetworkIconId = new SimpleStringProperty(); final BooleanProperty bootstrapComplete = new SimpleBooleanProperty(); final BooleanProperty showAppScreen = new SimpleBooleanProperty(); private final BooleanProperty isSplashScreenRemoved = new SimpleBooleanProperty(); final StringProperty p2pNetworkLabelId = new SimpleStringProperty("footer-pane"); @SuppressWarnings("FieldCanBeLocal") private MonadicBinding<Boolean> allServicesDone, tradesAndUIReady; private final BalanceModel balanceModel; private final BalancePresentation balancePresentation; private final TradePresentation tradePresentation; private final DisputePresentation disputePresentation; final PriceFeedService priceFeedService; private final User user; private int numBtcPeers = 0; private Timer checkNumberOfBtcPeersTimer; private Timer checkNumberOfP2pNetworkPeersTimer; private final Map<String, Subscription> disputeIsClosedSubscriptionsMap = new HashMap<>(); final ObservableList<PriceFeedComboBoxItem> priceFeedComboBoxItems = FXCollections.observableArrayList(); @SuppressWarnings("FieldCanBeLocal") private MonadicBinding<String> marketPriceBinding; @SuppressWarnings({"unused", "FieldCanBeLocal"}) private Subscription priceFeedAllLoadedSubscription; private BooleanProperty p2pNetWorkReady; private final BooleanProperty walletInitialized = new SimpleBooleanProperty(); private boolean allBasicServicesInitialized; /////////////////////////////////////////////////////////////////////////////////////////// // Constructor /////////////////////////////////////////////////////////////////////////////////////////// @SuppressWarnings("WeakerAccess") @Inject public MainViewModel(WalletsManager walletsManager, WalletsSetup walletsSetup, BtcWalletService btcWalletService, BalanceModel balanceModel, BalancePresentation balancePresentation, TradePresentation tradePresentation, DisputePresentation disputePresentation, PriceFeedService priceFeedService, ArbitratorManager arbitratorManager, P2PService p2PService, TradeManager tradeManager, OpenOfferManager openOfferManager, DisputeManager disputeManager, Preferences preferences, User user, AlertManager alertManager, PrivateNotificationManager privateNotificationManager, FilterManager filterManager, WalletPasswordWindow walletPasswordWindow, TradeStatisticsManager tradeStatisticsManager, NotificationCenter notificationCenter, TacWindow tacWindow, Clock clock, FeeService feeService, DaoSetup daoSetup, EncryptionService encryptionService, KeyRing keyRing, BisqEnvironment bisqEnvironment, FailedTradesManager failedTradesManager, ClosedTradableManager closedTradableManager, AccountAgeWitnessService accountAgeWitnessService, TorNetworkSettingsWindow torNetworkSettingsWindow, CorruptedDatabaseFilesHandler corruptedDatabaseFilesHandler, BSFormatter formatter) { this.walletsManager = walletsManager; this.walletsSetup = walletsSetup; this.btcWalletService = btcWalletService; this.balanceModel = balanceModel; this.balancePresentation = balancePresentation; this.tradePresentation = tradePresentation; this.disputePresentation = disputePresentation; this.priceFeedService = priceFeedService; this.user = user; this.arbitratorManager = arbitratorManager; this.p2PService = p2PService; this.tradeManager = tradeManager; this.openOfferManager = openOfferManager; this.disputeManager = disputeManager; this.preferences = preferences; this.alertManager = alertManager; this.privateNotificationManager = privateNotificationManager; this.filterManager = filterManager; // Reference so it's initialized and eventListener gets registered this.walletPasswordWindow = walletPasswordWindow; this.tradeStatisticsManager = tradeStatisticsManager; this.notificationCenter = notificationCenter; this.tacWindow = tacWindow; this.clock = clock; this.feeService = feeService; this.daoSetup = daoSetup; this.encryptionService = encryptionService; this.keyRing = keyRing; this.bisqEnvironment = bisqEnvironment; this.failedTradesManager = failedTradesManager; this.closedTradableManager = closedTradableManager; this.accountAgeWitnessService = accountAgeWitnessService; this.torNetworkSettingsWindow = torNetworkSettingsWindow; this.corruptedDatabaseFilesHandler = corruptedDatabaseFilesHandler; this.formatter = formatter; TxIdTextField.setPreferences(preferences); // TODO TxIdTextField.setWalletService(btcWalletService); BalanceWithConfirmationTextField.setWalletService(btcWalletService); } /////////////////////////////////////////////////////////////////////////////////////////// // API /////////////////////////////////////////////////////////////////////////////////////////// public void start() { // We do the delete of the spv file at startup before BitcoinJ is initialized to avoid issues with locked files under Windows. if (preferences.isResyncSpvRequested()) { try { walletsSetup.reSyncSPVChain(); } catch (IOException e) { log.error(e.toString()); e.printStackTrace(); } } //noinspection ConstantConditions,ConstantConditions,PointlessBooleanExpression if (!preferences.isTacAccepted() && !DevEnv.isDevMode()) { UserThread.runAfter(() -> { tacWindow.onAction(() -> { preferences.setTacAccepted(true); checkIfLocalHostNodeIsRunning(); }).show(); }, 1); } else { checkIfLocalHostNodeIsRunning(); } } private void readMapsFromResources() { SetupUtils.readFromResources(p2PService.getP2PDataStorage()).addListener((observable, oldValue, newValue) -> { if (newValue) startBasicServices(); }); // TODO can be removed in jdk 9 checkCryptoSetup(); } private void startBasicServices() { log.info("startBasicServices"); ChangeListener<Boolean> walletInitializedListener = (observable, oldValue, newValue) -> { // TODO that seems to be called too often if Tor takes longer to start up... if (newValue && !p2pNetWorkReady.get()) showTorNetworkSettingsWindow(); }; Timer startupTimeout = UserThread.runAfter(() -> { log.warn("startupTimeout called"); if (walletsManager.areWalletsEncrypted()) walletInitialized.addListener(walletInitializedListener); else showTorNetworkSettingsWindow(); }, STARTUP_TIMEOUT_MINUTES, TimeUnit.MINUTES); p2pNetWorkReady = initP2PNetwork(); // We only init wallet service here if not using Tor for bitcoinj. // When using Tor, wallet init must be deferred until Tor is ready. if (!preferences.getUseTorForBitcoinJ() || bisqEnvironment.isBitcoinLocalhostNodeRunning()) initWalletService(); // need to store it to not get garbage collected allServicesDone = EasyBind.combine(walletInitialized, p2pNetWorkReady, (a, b) -> { log.debug("\nwalletInitialized={}\n" + "p2pNetWorkReady={}", a, b); return a && b; }); allServicesDone.subscribe((observable, oldValue, newValue) -> { if (newValue) { startupTimeout.stop(); walletInitialized.removeListener(walletInitializedListener); onBasicServicesInitialized(); if (torNetworkSettingsWindow != null) torNetworkSettingsWindow.hide(); } }); } private void showTorNetworkSettingsWindow() { torNetworkSettingsWindow.show(); } /////////////////////////////////////////////////////////////////////////////////////////// // Initialisation /////////////////////////////////////////////////////////////////////////////////////////// private BooleanProperty initP2PNetwork() { log.info("initP2PNetwork"); StringProperty bootstrapState = new SimpleStringProperty(); StringProperty bootstrapWarning = new SimpleStringProperty(); BooleanProperty hiddenServicePublished = new SimpleBooleanProperty(); BooleanProperty initialP2PNetworkDataReceived = new SimpleBooleanProperty(); p2PNetworkInfoBinding = EasyBind.combine(bootstrapState, bootstrapWarning, p2PService.getNumConnectedPeers(), hiddenServicePublished, initialP2PNetworkDataReceived, (state, warning, numPeers, hiddenService, dataReceived) -> { String result = ""; int peers = (int) numPeers; if (warning != null && peers == 0) { result = warning; } else { String p2pInfo = Res.get("mainView.footer.p2pInfo", numPeers); if (dataReceived && hiddenService) { result = p2pInfo; } else if (peers == 0) result = state; else result = state + " / " + p2pInfo; } return result; }); p2PNetworkInfoBinding.subscribe((observable, oldValue, newValue) -> { p2PNetworkInfo.set(newValue); }); bootstrapState.set(Res.get("mainView.bootstrapState.connectionToTorNetwork")); p2PService.getNetworkNode().addConnectionListener(new ConnectionListener() { @Override public void onConnection(Connection connection) { } @Override public void onDisconnect(CloseConnectionReason closeConnectionReason, Connection connection) { // We only check at seed nodes as they are running the latest version // Other disconnects might be caused by peers running an older version if (connection.getPeerType() == Connection.PeerType.SEED_NODE && closeConnectionReason == CloseConnectionReason.RULE_VIOLATION) { log.warn("RULE_VIOLATION onDisconnect closeConnectionReason=" + closeConnectionReason); log.warn("RULE_VIOLATION onDisconnect connection=" + connection); } } @Override public void onError(Throwable throwable) { } }); final BooleanProperty p2pNetworkInitialized = new SimpleBooleanProperty(); p2PService.start(new P2PServiceListener() { @Override public void onTorNodeReady() { log.debug("onTorNodeReady"); bootstrapState.set(Res.get("mainView.bootstrapState.torNodeCreated")); p2PNetworkIconId.set("image-connection-tor"); if (preferences.getUseTorForBitcoinJ()) initWalletService(); // We want to get early connected to the price relay so we call it already now priceFeedService.setCurrencyCodeOnInit(); priceFeedService.initialRequestPriceFeed(); } @Override public void onHiddenServicePublished() { log.debug("onHiddenServicePublished"); hiddenServicePublished.set(true); bootstrapState.set(Res.get("mainView.bootstrapState.hiddenServicePublished")); } @Override public void onDataReceived() { log.debug("onRequestingDataCompleted"); initialP2PNetworkDataReceived.set(true); bootstrapState.set(Res.get("mainView.bootstrapState.initialDataReceived")); splashP2PNetworkAnimationVisible.set(false); p2pNetworkInitialized.set(true); } @Override public void onNoSeedNodeAvailable() { log.warn("onNoSeedNodeAvailable"); if (p2PService.getNumConnectedPeers().get() == 0) bootstrapWarning.set(Res.get("mainView.bootstrapWarning.noSeedNodesAvailable")); else bootstrapWarning.set(null); splashP2PNetworkAnimationVisible.set(false); p2pNetworkInitialized.set(true); } @Override public void onNoPeersAvailable() { log.warn("onNoPeersAvailable"); if (p2PService.getNumConnectedPeers().get() == 0) { p2pNetworkWarnMsg.set(Res.get("mainView.p2pNetworkWarnMsg.noNodesAvailable")); bootstrapWarning.set(Res.get("mainView.bootstrapWarning.noNodesAvailable")); p2pNetworkLabelId.set("splash-error-state-msg"); } else { bootstrapWarning.set(null); p2pNetworkLabelId.set("footer-pane"); } splashP2PNetworkAnimationVisible.set(false); p2pNetworkInitialized.set(true); } @Override public void onUpdatedDataReceived() { log.debug("onBootstrapComplete"); splashP2PNetworkAnimationVisible.set(false); bootstrapComplete.set(true); } @Override public void onSetupFailed(Throwable throwable) { log.warn("onSetupFailed"); p2pNetworkWarnMsg.set(Res.get("mainView.p2pNetworkWarnMsg.connectionToP2PFailed", throwable.getMessage())); splashP2PNetworkAnimationVisible.set(false); bootstrapWarning.set(Res.get("mainView.bootstrapWarning.bootstrappingToP2PFailed")); p2pNetworkLabelId.set("splash-error-state-msg"); } @Override public void onRequestCustomBridges() { showTorNetworkSettingsWindow(); } }); return p2pNetworkInitialized; } private void initWalletService() { log.info("initWalletService"); ObjectProperty<Throwable> walletServiceException = new SimpleObjectProperty<>(); btcInfoBinding = EasyBind.combine(walletsSetup.downloadPercentageProperty(), walletsSetup.numPeersProperty(), walletServiceException, (downloadPercentage, numPeers, exception) -> { String result = ""; if (exception == null) { double percentage = (double) downloadPercentage; int peers = (int) numPeers; btcSyncProgress.set(percentage); if (percentage == 1) { result = Res.get("mainView.footer.btcInfo", peers, Res.get("mainView.footer.btcInfo.synchronizedWith"), getBtcNetworkAsString()); btcSplashSyncIconId.set("image-connection-synced"); if (allBasicServicesInitialized) checkForLockedUpFunds(); } else if (percentage > 0.0) { result = Res.get("mainView.footer.btcInfo", peers, Res.get("mainView.footer.btcInfo.synchronizedWith"), getBtcNetworkAsString() + ": " + formatter.formatToPercentWithSymbol(percentage)); } else { result = Res.get("mainView.footer.btcInfo", peers, Res.get("mainView.footer.btcInfo.connectingTo"), getBtcNetworkAsString()); } } else { result = Res.get("mainView.footer.btcInfo", numBtcPeers, Res.get("mainView.footer.btcInfo.connectionFailed"), getBtcNetworkAsString()); log.error(exception.getMessage()); if (exception instanceof TimeoutException) { walletServiceErrorMsg.set(Res.get("mainView.walletServiceErrorMsg.timeout")); } else if (exception.getCause() instanceof BlockStoreException) { if (exception.getCause().getCause() instanceof ChainFileLockedException) { new Popup<>().warning(Res.get("popup.warning.startupFailed.twoInstances")) .useShutDownButton() .show(); } else { new Popup<>().warning(Res.get("error.spvFileCorrupted", exception.getMessage())) .actionButtonText(Res.get("settings.net.reSyncSPVChainButton")) .onAction(() -> GUIUtil.reSyncSPVChain(walletsSetup, preferences)) .show(); } } else { walletServiceErrorMsg.set(Res.get("mainView.walletServiceErrorMsg.connectionError", exception.toString())); } } return result; }); btcInfoBinding.subscribe((observable, oldValue, newValue) -> { btcInfo.set(newValue); }); walletsSetup.initialize(null, () -> { log.debug("walletsSetup.onInitialized"); numBtcPeers = walletsSetup.numPeersProperty().get(); // We only check one as we apply encryption to all or none if (walletsManager.areWalletsEncrypted()) { if (p2pNetWorkReady.get()) splashP2PNetworkAnimationVisible.set(false); walletPasswordWindow .onAesKey(aesKey -> { walletsManager.setAesKey(aesKey); if (preferences.isResyncSpvRequested()) { showFirstPopupIfResyncSPVRequested(); } else { walletInitialized.set(true); } }) .hideCloseButton() .show(); } else { if (preferences.isResyncSpvRequested()) { showFirstPopupIfResyncSPVRequested(); } else { walletInitialized.set(true); } } }, walletServiceException::set); } private void onBasicServicesInitialized() { log.info("onBasicServicesInitialized"); clock.start(); PaymentMethod.onAllServicesInitialized(); disputeManager.onAllServicesInitialized(); initTradeManager(); btcWalletService.addBalanceListener(new BalanceListener() { @Override public void onBalanceChanged(Coin balance, Transaction tx) { balanceModel.updateBalance(); } }); openOfferManager.getObservableList().addListener((ListChangeListener<OpenOffer>) c -> balanceModel.updateBalance()); openOfferManager.onAllServicesInitialized(); arbitratorManager.onAllServicesInitialized(); alertManager.alertMessageProperty().addListener((observable, oldValue, newValue) -> displayAlertIfPresent(newValue, false)); privateNotificationManager.privateNotificationProperty().addListener((observable, oldValue, newValue) -> displayPrivateNotification(newValue)); displayAlertIfPresent(alertManager.alertMessageProperty().get(), false); p2PService.onAllServicesInitialized(); feeService.onAllServicesInitialized(); GUIUtil.setFeeService(feeService); daoSetup.onAllServicesInitialized(errorMessage -> new Popup<>().error(errorMessage).show()); tradeStatisticsManager.onAllServicesInitialized(); accountAgeWitnessService.onAllServicesInitialized(); priceFeedService.setCurrencyCodeOnInit(); filterManager.onAllServicesInitialized(); filterManager.addListener(filter -> { if (filter != null) { if (filter.getSeedNodes() != null && !filter.getSeedNodes().isEmpty()) new Popup<>().warning(Res.get("popup.warning.nodeBanned", Res.get("popup.warning.seed"))).show(); if (filter.getPriceRelayNodes() != null && !filter.getPriceRelayNodes().isEmpty()) new Popup<>().warning(Res.get("popup.warning.nodeBanned", Res.get("popup.warning.priceRelay"))).show(); } }); setupBtcNumPeersWatcher(); setupP2PNumPeersWatcher(); balanceModel.updateBalance(); if (DevEnv.isDevMode()) { preferences.setShowOwnOffersInOfferBook(true); setupDevDummyPaymentAccounts(); } fillPriceFeedComboBoxItems(); setupMarketPriceFeed(); swapPendingOfferFundingEntries(); showAppScreen.set(true); String key = "remindPasswordAndBackup"; user.getPaymentAccountsAsObservable().addListener((SetChangeListener<PaymentAccount>) change -> { if (!walletsManager.areWalletsEncrypted() && preferences.showAgain(key) && change.wasAdded()) { new Popup<>().headLine(Res.get("popup.securityRecommendation.headline")) .information(Res.get("popup.securityRecommendation.msg")) .dontShowAgainId(key) .show(); } }); checkIfOpenOffersMatchTradeProtocolVersion(); if (walletsSetup.downloadPercentageProperty().get() == 1) checkForLockedUpFunds(); checkForCorruptedDataBaseFiles(); allBasicServicesInitialized = true; } private void initTradeManager() { // tradeManager tradeManager.onAllServicesInitialized(); tradeManager.getTradableList().addListener((ListChangeListener<Trade>) change -> balanceModel.updateBalance()); tradeManager.setTakeOfferRequestErrorMessageHandler(errorMessage -> new Popup<>() .warning(Res.get("popup.error.takeOfferRequestFailed", errorMessage)) .show()); // We handle the trade period here as we display a global popup if we reached dispute time tradesAndUIReady = EasyBind.combine(isSplashScreenRemoved, tradeManager.pendingTradesInitializedProperty(), (a, b) -> a && b); tradesAndUIReady.subscribe((observable, oldValue, newValue) -> { if (newValue) { tradeManager.applyTradePeriodState(); tradeManager.getTradableList().forEach(trade -> { Date maxTradePeriodDate = trade.getMaxTradePeriodDate(); String key; switch (trade.getTradePeriodState()) { case FIRST_HALF: break; case SECOND_HALF: key = "displayHalfTradePeriodOver" + trade.getId(); if (DontShowAgainLookup.showAgain(key)) { DontShowAgainLookup.dontShowAgain(key, true); new Popup<>().warning(Res.get("popup.warning.tradePeriod.halfReached", trade.getShortId(), formatter.formatDateTime(maxTradePeriodDate))) .show(); } break; case TRADE_PERIOD_OVER: key = "displayTradePeriodOver" + trade.getId(); if (DontShowAgainLookup.showAgain(key)) { DontShowAgainLookup.dontShowAgain(key, true); new Popup<>().warning(Res.get("popup.warning.tradePeriod.ended", trade.getShortId(), formatter.formatDateTime(maxTradePeriodDate))) .show(); } break; } }); } }); } private void showFirstPopupIfResyncSPVRequested() { Popup firstPopup = new Popup<>(); firstPopup.information(Res.get("settings.net.reSyncSPVAfterRestart")).show(); if (btcSyncProgress.get() == 1) { showSecondPopupIfResyncSPVRequested(firstPopup); } else { btcSyncProgress.addListener((observable, oldValue, newValue) -> { if ((double) newValue == 1) showSecondPopupIfResyncSPVRequested(firstPopup); }); } } private void showSecondPopupIfResyncSPVRequested(Popup firstPopup) { firstPopup.hide(); preferences.setResyncSpvRequested(false); new Popup<>().information(Res.get("settings.net.reSyncSPVAfterRestartCompleted")) .hideCloseButton() .useShutDownButton() .show(); } private void checkIfLocalHostNodeIsRunning() { Thread checkIfLocalHostNodeIsRunningThread = new Thread() { @Override public void run() { Thread.currentThread().setName("checkIfLocalHostNodeIsRunningThread"); Socket socket = null; try { socket = new Socket(); socket.connect(new InetSocketAddress(InetAddresses.forString("127.0.0.1"), BisqEnvironment.getBaseCurrencyNetwork().getParameters().getPort()), 5000); log.info("Localhost peer detected."); UserThread.execute(() -> { bisqEnvironment.setBitcoinLocalhostNodeRunning(true); readMapsFromResources(); }); } catch (Throwable e) { log.info("Localhost peer not detected."); UserThread.execute(MainViewModel.this::readMapsFromResources); } finally { if (socket != null) { try { socket.close(); } catch (IOException ignore) { } } } } }; checkIfLocalHostNodeIsRunningThread.start(); } private void checkCryptoSetup() { BooleanProperty result = new SimpleBooleanProperty(); // We want to test if the client is compiled with the correct crypto provider (BountyCastle) // and if the unlimited Strength for cryptographic keys is set. // If users compile themselves they might miss that step and then would get an exception in the trade. // To avoid that we add here at startup a sample encryption and signing to see if it don't causes an exception. // See: https://github.com/bisq-network/exchange/blob/master/doc/build.md#7-enable-unlimited-strength-for-cryptographic-keys Thread checkCryptoThread = new Thread() { @Override public void run() { try { Thread.currentThread().setName("checkCryptoThread"); log.trace("Run crypto test"); // just use any simple dummy msg Ping payload = new Ping(1, 1); SealedAndSigned sealedAndSigned = EncryptionService.encryptHybridWithSignature(payload, keyRing.getSignatureKeyPair(), keyRing.getPubKeyRing().getEncryptionPubKey()); DecryptedDataTuple tuple = encryptionService.decryptHybridWithSignature(sealedAndSigned, keyRing.getEncryptionKeyPair().getPrivate()); if (tuple.getNetworkEnvelope() instanceof Ping && ((Ping) tuple.getNetworkEnvelope()).getNonce() == payload.getNonce() && ((Ping) tuple.getNetworkEnvelope()).getLastRoundTripTime() == payload.getLastRoundTripTime()) { log.debug("Crypto test succeeded"); if (Security.getProvider("BC") != null) { UserThread.execute(() -> result.set(true)); } else { throw new CryptoException("Security provider BountyCastle is not available."); } } else { throw new CryptoException("Payload not correct after decryption"); } } catch (CryptoException e) { e.printStackTrace(); String msg = Res.get("popup.warning.cryptoTestFailed", e.getMessage()); log.error(msg); UserThread.execute(() -> new Popup<>().warning(msg) .useShutDownButton() .useReportBugButton() .show()); } } }; checkCryptoThread.start(); } private void checkIfOpenOffersMatchTradeProtocolVersion() { List<OpenOffer> outDatedOffers = openOfferManager.getObservableList() .stream() .filter(e -> e.getOffer().getProtocolVersion() != Version.TRADE_PROTOCOL_VERSION) .collect(Collectors.toList()); if (!outDatedOffers.isEmpty()) { String offers = outDatedOffers.stream() .map(e -> e.getId() + "\n") .collect(Collectors.toList()).toString() .replace("[", "").replace("]", ""); new Popup<>() .warning(Res.get("popup.warning.oldOffers.msg", offers)) .actionButtonText(Res.get("popup.warning.oldOffers.buttonText")) .onAction(() -> openOfferManager.removeOpenOffers(outDatedOffers, null)) .useShutDownButton() .show(); } } /////////////////////////////////////////////////////////////////////////////////////////// // UI handlers /////////////////////////////////////////////////////////////////////////////////////////// // After showAppScreen is set and splash screen is faded out void onSplashScreenRemoved() { isSplashScreenRemoved.set(true); // Delay that as we want to know what is the current path of the navigation which is set // in MainView showAppScreen handler notificationCenter.onAllServicesAndViewsInitialized(); } /////////////////////////////////////////////////////////////////////////////////////////// // Private /////////////////////////////////////////////////////////////////////////////////////////// private void setupP2PNumPeersWatcher() { p2PService.getNumConnectedPeers().addListener((observable, oldValue, newValue) -> { int numPeers = (int) newValue; if ((int) oldValue > 0 && numPeers == 0) { // give a bit of tolerance if (checkNumberOfP2pNetworkPeersTimer != null) checkNumberOfP2pNetworkPeersTimer.stop(); checkNumberOfP2pNetworkPeersTimer = UserThread.runAfter(() -> { // check again numPeers if (p2PService.getNumConnectedPeers().get() == 0) { p2pNetworkWarnMsg.set(Res.get("mainView.networkWarning.allConnectionsLost", Res.get("shared.P2P"))); p2pNetworkLabelId.set("splash-error-state-msg"); } else { p2pNetworkWarnMsg.set(null); p2pNetworkLabelId.set("footer-pane"); } }, 5); } else if ((int) oldValue == 0 && numPeers > 0) { if (checkNumberOfP2pNetworkPeersTimer != null) checkNumberOfP2pNetworkPeersTimer.stop(); p2pNetworkWarnMsg.set(null); p2pNetworkLabelId.set("footer-pane"); } }); } private void setupBtcNumPeersWatcher() { walletsSetup.numPeersProperty().addListener((observable, oldValue, newValue) -> { int numPeers = (int) newValue; if ((int) oldValue > 0 && numPeers == 0) { if (checkNumberOfBtcPeersTimer != null) checkNumberOfBtcPeersTimer.stop(); checkNumberOfBtcPeersTimer = UserThread.runAfter(() -> { // check again numPeers if (walletsSetup.numPeersProperty().get() == 0) { if (bisqEnvironment.isBitcoinLocalhostNodeRunning()) walletServiceErrorMsg.set(Res.get("mainView.networkWarning.localhostBitcoinLost", Res.getBaseCurrencyName().toLowerCase())); else walletServiceErrorMsg.set(Res.get("mainView.networkWarning.allConnectionsLost", Res.getBaseCurrencyName().toLowerCase())); } else { walletServiceErrorMsg.set(null); } }, 5); } else if ((int) oldValue == 0 && numPeers > 0) { if (checkNumberOfBtcPeersTimer != null) checkNumberOfBtcPeersTimer.stop(); walletServiceErrorMsg.set(null); } }); } private void setupMarketPriceFeed() { priceFeedService.requestPriceFeed(price -> marketPrice.set(formatter.formatMarketPrice(price, priceFeedService.getCurrencyCode())), (errorMessage, throwable) -> marketPrice.set(Res.get("shared.na"))); marketPriceBinding = EasyBind.combine( marketPriceCurrencyCode, marketPrice, (currencyCode, price) -> formatter.getCurrencyPair(currencyCode) + ": " + price); marketPriceBinding.subscribe((observable, oldValue, newValue) -> { if (newValue != null && !newValue.equals(oldValue)) { setMarketPriceInItems(); String code = priceFeedService.currencyCodeProperty().get(); Optional<PriceFeedComboBoxItem> itemOptional = findPriceFeedComboBoxItem(code); if (itemOptional.isPresent()) { itemOptional.get().setDisplayString(newValue); selectedPriceFeedComboBoxItemProperty.set(itemOptional.get()); } else { if (CurrencyUtil.isCryptoCurrency(code)) { CurrencyUtil.getCryptoCurrency(code).ifPresent(cryptoCurrency -> { preferences.addCryptoCurrency(cryptoCurrency); fillPriceFeedComboBoxItems(); }); } else { CurrencyUtil.getFiatCurrency(code).ifPresent(fiatCurrency -> { preferences.addFiatCurrency(fiatCurrency); fillPriceFeedComboBoxItems(); }); } } if (selectedPriceFeedComboBoxItemProperty.get() != null) selectedPriceFeedComboBoxItemProperty.get().setDisplayString(newValue); } }); marketPriceCurrencyCode.bind(priceFeedService.currencyCodeProperty()); priceFeedAllLoadedSubscription = EasyBind.subscribe(priceFeedService.updateCounterProperty(), updateCounter -> setMarketPriceInItems()); preferences.getTradeCurrenciesAsObservable().addListener((ListChangeListener<TradeCurrency>) c -> UserThread.runAfter(() -> { fillPriceFeedComboBoxItems(); setMarketPriceInItems(); }, 100, TimeUnit.MILLISECONDS)); } private void setMarketPriceInItems() { priceFeedComboBoxItems.stream().forEach(item -> { String currencyCode = item.currencyCode; MarketPrice marketPrice = priceFeedService.getMarketPrice(currencyCode); String priceString; if (marketPrice != null && marketPrice.isPriceAvailable()) { priceString = formatter.formatMarketPrice(marketPrice.getPrice(), currencyCode); item.setPriceAvailable(true); item.setExternallyProvidedPrice(marketPrice.isExternallyProvidedPrice()); } else { priceString = Res.get("shared.na"); item.setPriceAvailable(false); } item.setDisplayString(formatter.getCurrencyPair(currencyCode) + ": " + priceString); final String code = item.currencyCode; if (selectedPriceFeedComboBoxItemProperty.get() != null && selectedPriceFeedComboBoxItemProperty.get().currencyCode.equals(code)) { isFiatCurrencyPriceFeedSelected.set(CurrencyUtil.isFiatCurrency(code) && CurrencyUtil.getFiatCurrency(code).isPresent() && item.isPriceAvailable() && item.isExternallyProvidedPrice()); isCryptoCurrencyPriceFeedSelected.set(CurrencyUtil.isCryptoCurrency(code) && CurrencyUtil.getCryptoCurrency(code).isPresent() && item.isPriceAvailable() && item.isExternallyProvidedPrice()); isExternallyProvidedPrice.set(item.isExternallyProvidedPrice()); isPriceAvailable.set(item.isPriceAvailable()); marketPriceUpdated.set(marketPriceUpdated.get() + 1); } }); } public void setPriceFeedComboBoxItem(PriceFeedComboBoxItem item) { if (item != null) { Optional<PriceFeedComboBoxItem> itemOptional = findPriceFeedComboBoxItem(priceFeedService.currencyCodeProperty().get()); if (itemOptional.isPresent()) selectedPriceFeedComboBoxItemProperty.set(itemOptional.get()); else findPriceFeedComboBoxItem(preferences.getPreferredTradeCurrency().getCode()) .ifPresent(selectedPriceFeedComboBoxItemProperty::set); priceFeedService.setCurrencyCode(item.currencyCode); } else { findPriceFeedComboBoxItem(preferences.getPreferredTradeCurrency().getCode()) .ifPresent(selectedPriceFeedComboBoxItemProperty::set); } } private Optional<PriceFeedComboBoxItem> findPriceFeedComboBoxItem(String currencyCode) { return priceFeedComboBoxItems.stream() .filter(item -> item.currencyCode.equals(currencyCode)) .findAny(); } private void fillPriceFeedComboBoxItems() { List<PriceFeedComboBoxItem> currencyItems = preferences.getTradeCurrenciesAsObservable() .stream() .map(tradeCurrency -> new PriceFeedComboBoxItem(tradeCurrency.getCode())) .collect(Collectors.toList()); priceFeedComboBoxItems.setAll(currencyItems); } private void displayAlertIfPresent(Alert alert, boolean openNewVersionPopup) { if (alert != null) { if (alert.isUpdateInfo()) { user.setDisplayedAlert(alert); final boolean isNewVersion = alert.isNewVersion(); newVersionAvailableProperty.set(isNewVersion); String key = "Update_" + alert.getVersion(); if (isNewVersion && (preferences.showAgain(key) || openNewVersionPopup)) { new DisplayUpdateDownloadWindow(alert) .actionButtonText(Res.get("displayUpdateDownloadWindow.button.downloadLater")) .onAction(() -> { preferences.dontShowAgain(key, false); // update later }) .closeButtonText(Res.get("shared.cancel")) .onClose(() -> { preferences.dontShowAgain(key, true); // ignore update }) .show(); } } else { final Alert displayedAlert = user.getDisplayedAlert(); if (displayedAlert == null || !displayedAlert.equals(alert)) new DisplayAlertMessageWindow() .alertMessage(alert) .onClose(() -> { user.setDisplayedAlert(alert); }) .show(); } } } private void displayPrivateNotification(PrivateNotificationPayload privateNotification) { new Popup<>().headLine(Res.get("popup.privateNotification.headline")) .attention(privateNotification.getMessage()) .setHeadlineStyle("-fx-text-fill: -bs-error-red; -fx-font-weight: bold; -fx-font-size: 16;") .onClose(privateNotificationManager::removePrivateNotification) .useIUnderstandButton() .show(); } private void swapPendingOfferFundingEntries() { tradeManager.getAddressEntriesForAvailableBalanceStream() .filter(addressEntry -> addressEntry.getOfferId() != null) .forEach(addressEntry -> { log.debug("swapPendingOfferFundingEntries, offerId={}, OFFER_FUNDING", addressEntry.getOfferId()); btcWalletService.swapTradeEntryToAvailableEntry(addressEntry.getOfferId(), AddressEntry.Context.OFFER_FUNDING); }); } private void checkForLockedUpFunds() { Set<String> tradesIdSet = tradeManager.getLockedTradesStream() .filter(Trade::hasFailed) .map(Trade::getId) .collect(Collectors.toSet()); tradesIdSet.addAll(failedTradesManager.getLockedTradesStream() .map(Trade::getId) .collect(Collectors.toSet())); tradesIdSet.addAll(closedTradableManager.getLockedTradesStream() .map(e -> { log.warn("We found a closed trade with locked up funds. " + "That should never happen. trade ID=" + e.getId()); return e.getId(); }) .collect(Collectors.toSet())); btcWalletService.getAddressEntriesForTrade().stream() .filter(e -> tradesIdSet.contains(e.getOfferId()) && e.getContext() == AddressEntry.Context.MULTI_SIG) .forEach(e -> { final Coin balance = e.getCoinLockedInMultiSig(); final String message = Res.get("popup.warning.lockedUpFunds", formatter.formatCoinWithCode(balance), e.getAddressString(), e.getOfferId()); log.warn(message); new Popup<>().warning(message).show(); }); } private void checkForCorruptedDataBaseFiles() { List<String> files = corruptedDatabaseFilesHandler.getCorruptedDatabaseFiles(); if (files.size() == 0) return; if (files.size() == 1 && files.get(0).equals("ViewPathAsString")) { log.debug("We detected incompatible data base file for Navigation. " + "That is a minor issue happening with refactoring of UI classes " + "and we don't display a warning popup to the user."); return; } // show warning that some files have been corrupted new Popup<>() .warning(Res.get("popup.warning.incompatibleDB", files.toString(), getAppDateDir())) .useShutDownButton() .show(); } private void setupDevDummyPaymentAccounts() { if (user.getPaymentAccounts() != null && user.getPaymentAccounts().isEmpty()) { PerfectMoneyAccount perfectMoneyAccount = new PerfectMoneyAccount(); perfectMoneyAccount.init(); perfectMoneyAccount.setAccountNr("dummy_" + new Random().nextInt(100)); perfectMoneyAccount.setAccountName("PerfectMoney dummy");// Don't translate only for dev perfectMoneyAccount.setSelectedTradeCurrency(new FiatCurrency("USD")); user.addPaymentAccount(perfectMoneyAccount); if (p2PService.isBootstrapped()) { accountAgeWitnessService.publishMyAccountAgeWitness(perfectMoneyAccount.getPaymentAccountPayload()); } else { p2PService.addP2PServiceListener(new BootstrapListener() { @Override public void onUpdatedDataReceived() { accountAgeWitnessService.publishMyAccountAgeWitness(perfectMoneyAccount.getPaymentAccountPayload()); } }); } CryptoCurrencyAccount cryptoCurrencyAccount = new CryptoCurrencyAccount(); cryptoCurrencyAccount.init(); cryptoCurrencyAccount.setAccountName("ETH dummy");// Don't translate only for dev cryptoCurrencyAccount.setAddress("0x" + new Random().nextInt(1000000)); cryptoCurrencyAccount.setSingleTradeCurrency(CurrencyUtil.getCryptoCurrency("ETH").get()); user.addPaymentAccount(cryptoCurrencyAccount); } } String getAppDateDir() { return bisqEnvironment.getProperty(AppOptionKeys.APP_DATA_DIR_KEY); } void openDownloadWindow() { displayAlertIfPresent(user.getDisplayedAlert(), true); } public String getBtcNetworkAsString() { String postFix; if (bisqEnvironment.isBitcoinLocalhostNodeRunning()) postFix = " " + Res.get("mainView.footer.localhostBitcoinNode"); else if (preferences.getUseTorForBitcoinJ()) postFix = " " + Res.get("mainView.footer.usingTor"); else postFix = ""; return Res.get(BisqEnvironment.getBaseCurrencyNetwork().name()) + postFix; } StringProperty getNumOpenDisputes() { return disputePresentation.getNumOpenDisputes(); } BooleanProperty getShowOpenDisputesNotification() { return disputePresentation.getShowOpenDisputesNotification(); } BooleanProperty getShowPendingTradesNotification() { return tradePresentation.getShowPendingTradesNotification(); } StringProperty getNumPendingTrades() { return tradePresentation.getNumPendingTrades(); } StringProperty getAvailableBalance() { return balancePresentation.getAvailableBalance(); } StringProperty getReservedBalance() { return balancePresentation.getReservedBalance(); } StringProperty getLockedBalance() { return balancePresentation.getLockedBalance(); } }
src/main/java/bisq/desktop/main/MainViewModel.java
/* * This file is part of Bisq. * * Bisq is free software: you can redistribute it and/or modify it * under the terms of the GNU Affero General Public License as published by * the Free Software Foundation, either version 3 of the License, or (at * your option) any later version. * * Bisq is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public * License for more details. * * You should have received a copy of the GNU Affero General Public License * along with Bisq. If not, see <http://www.gnu.org/licenses/>. */ package bisq.desktop.main; import bisq.desktop.common.model.ViewModel; import bisq.desktop.components.BalanceWithConfirmationTextField; import bisq.desktop.components.TxIdTextField; import bisq.desktop.main.overlays.notifications.NotificationCenter; import bisq.desktop.main.overlays.popups.Popup; import bisq.desktop.main.overlays.windows.DisplayAlertMessageWindow; import bisq.desktop.main.overlays.windows.TacWindow; import bisq.desktop.main.overlays.windows.TorNetworkSettingsWindow; import bisq.desktop.main.overlays.windows.WalletPasswordWindow; import bisq.desktop.main.overlays.windows.downloadupdate.DisplayUpdateDownloadWindow; import bisq.desktop.util.GUIUtil; import bisq.core.alert.Alert; import bisq.core.alert.AlertManager; import bisq.core.alert.PrivateNotificationManager; import bisq.core.alert.PrivateNotificationPayload; import bisq.core.app.AppOptionKeys; import bisq.core.app.BisqEnvironment; import bisq.core.app.SetupUtils; import bisq.core.arbitration.ArbitratorManager; import bisq.core.arbitration.DisputeManager; import bisq.core.btc.AddressEntry; import bisq.core.btc.BalanceModel; import bisq.core.btc.listeners.BalanceListener; import bisq.core.btc.wallet.BtcWalletService; import bisq.core.btc.wallet.WalletsManager; import bisq.core.btc.wallet.WalletsSetup; import bisq.core.dao.DaoSetup; import bisq.core.filter.FilterManager; import bisq.core.locale.CurrencyUtil; import bisq.core.locale.FiatCurrency; import bisq.core.locale.Res; import bisq.core.locale.TradeCurrency; import bisq.core.offer.OpenOffer; import bisq.core.offer.OpenOfferManager; import bisq.core.payment.AccountAgeWitnessService; import bisq.core.payment.CryptoCurrencyAccount; import bisq.core.payment.PaymentAccount; import bisq.core.payment.PerfectMoneyAccount; import bisq.core.payment.payload.PaymentMethod; import bisq.core.presentation.BalancePresentation; import bisq.core.presentation.DisputePresentation; import bisq.core.presentation.TradePresentation; import bisq.core.provider.fee.FeeService; import bisq.core.provider.price.MarketPrice; import bisq.core.provider.price.PriceFeedService; import bisq.core.trade.Trade; import bisq.core.trade.TradeManager; import bisq.core.trade.closed.ClosedTradableManager; import bisq.core.trade.failed.FailedTradesManager; import bisq.core.trade.statistics.TradeStatisticsManager; import bisq.core.user.DontShowAgainLookup; import bisq.core.user.Preferences; import bisq.core.user.User; import bisq.core.util.BSFormatter; import bisq.network.crypto.DecryptedDataTuple; import bisq.network.crypto.EncryptionService; import bisq.network.p2p.BootstrapListener; import bisq.network.p2p.P2PService; import bisq.network.p2p.P2PServiceListener; import bisq.network.p2p.network.CloseConnectionReason; import bisq.network.p2p.network.Connection; import bisq.network.p2p.network.ConnectionListener; import bisq.network.p2p.peers.keepalive.messages.Ping; import bisq.common.Clock; import bisq.common.Timer; import bisq.common.UserThread; import bisq.common.app.DevEnv; import bisq.common.app.Version; import bisq.common.crypto.CryptoException; import bisq.common.crypto.KeyRing; import bisq.common.crypto.SealedAndSigned; import bisq.common.storage.CorruptedDatabaseFilesHandler; import org.bitcoinj.core.Coin; import org.bitcoinj.core.Transaction; import org.bitcoinj.store.BlockStoreException; import org.bitcoinj.store.ChainFileLockedException; import com.google.inject.Inject; import com.google.common.net.InetAddresses; import org.fxmisc.easybind.EasyBind; import org.fxmisc.easybind.Subscription; import org.fxmisc.easybind.monadic.MonadicBinding; import javafx.beans.property.BooleanProperty; import javafx.beans.property.DoubleProperty; import javafx.beans.property.IntegerProperty; import javafx.beans.property.ObjectProperty; import javafx.beans.property.SimpleBooleanProperty; import javafx.beans.property.SimpleDoubleProperty; import javafx.beans.property.SimpleIntegerProperty; import javafx.beans.property.SimpleObjectProperty; import javafx.beans.property.SimpleStringProperty; import javafx.beans.property.StringProperty; import javafx.beans.value.ChangeListener; import javafx.collections.FXCollections; import javafx.collections.ListChangeListener; import javafx.collections.ObservableList; import javafx.collections.SetChangeListener; import java.security.Security; import java.net.InetSocketAddress; import java.net.Socket; import java.io.IOException; import java.util.Date; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Optional; import java.util.Random; import java.util.Set; import java.util.concurrent.TimeUnit; import java.util.concurrent.TimeoutException; import java.util.stream.Collectors; import lombok.extern.slf4j.Slf4j; @Slf4j public class MainViewModel implements ViewModel { private static final long STARTUP_TIMEOUT_MINUTES = 4; private final WalletsManager walletsManager; private final WalletsSetup walletsSetup; private final BtcWalletService btcWalletService; private final ArbitratorManager arbitratorManager; private final P2PService p2PService; private final TradeManager tradeManager; private final OpenOfferManager openOfferManager; private final DisputeManager disputeManager; final Preferences preferences; private final AlertManager alertManager; private final PrivateNotificationManager privateNotificationManager; @SuppressWarnings({"unused", "FieldCanBeLocal"}) private final FilterManager filterManager; private final WalletPasswordWindow walletPasswordWindow; private final TradeStatisticsManager tradeStatisticsManager; private final NotificationCenter notificationCenter; private final TacWindow tacWindow; private final Clock clock; private final FeeService feeService; private final DaoSetup daoSetup; private final EncryptionService encryptionService; private final KeyRing keyRing; private final BisqEnvironment bisqEnvironment; private final FailedTradesManager failedTradesManager; private final ClosedTradableManager closedTradableManager; private final AccountAgeWitnessService accountAgeWitnessService; final TorNetworkSettingsWindow torNetworkSettingsWindow; private final CorruptedDatabaseFilesHandler corruptedDatabaseFilesHandler; private final BSFormatter formatter; // BTC network final StringProperty btcInfo = new SimpleStringProperty(Res.get("mainView.footer.btcInfo.initializing")); @SuppressWarnings("ConstantConditions") final DoubleProperty btcSyncProgress = new SimpleDoubleProperty(-1); final StringProperty walletServiceErrorMsg = new SimpleStringProperty(); final StringProperty btcSplashSyncIconId = new SimpleStringProperty(); private final StringProperty marketPriceCurrencyCode = new SimpleStringProperty(""); final ObjectProperty<PriceFeedComboBoxItem> selectedPriceFeedComboBoxItemProperty = new SimpleObjectProperty<>(); final BooleanProperty isFiatCurrencyPriceFeedSelected = new SimpleBooleanProperty(true); final BooleanProperty isCryptoCurrencyPriceFeedSelected = new SimpleBooleanProperty(false); final BooleanProperty isExternallyProvidedPrice = new SimpleBooleanProperty(true); final BooleanProperty isPriceAvailable = new SimpleBooleanProperty(false); final BooleanProperty newVersionAvailableProperty = new SimpleBooleanProperty(false); final IntegerProperty marketPriceUpdated = new SimpleIntegerProperty(0); @SuppressWarnings("FieldCanBeLocal") private MonadicBinding<String> btcInfoBinding; private final StringProperty marketPrice = new SimpleStringProperty(Res.get("shared.na")); // P2P network final StringProperty p2PNetworkInfo = new SimpleStringProperty(); @SuppressWarnings("FieldCanBeLocal") private MonadicBinding<String> p2PNetworkInfoBinding; final BooleanProperty splashP2PNetworkAnimationVisible = new SimpleBooleanProperty(true); final StringProperty p2pNetworkWarnMsg = new SimpleStringProperty(); final StringProperty p2PNetworkIconId = new SimpleStringProperty(); final BooleanProperty bootstrapComplete = new SimpleBooleanProperty(); final BooleanProperty showAppScreen = new SimpleBooleanProperty(); private final BooleanProperty isSplashScreenRemoved = new SimpleBooleanProperty(); final StringProperty p2pNetworkLabelId = new SimpleStringProperty("footer-pane"); @SuppressWarnings("FieldCanBeLocal") private MonadicBinding<Boolean> allServicesDone, tradesAndUIReady; private final BalanceModel balanceModel; private final BalancePresentation balancePresentation; private final TradePresentation tradePresentation; private final DisputePresentation disputePresentation; final PriceFeedService priceFeedService; private final User user; private int numBtcPeers = 0; private Timer checkNumberOfBtcPeersTimer; private Timer checkNumberOfP2pNetworkPeersTimer; private final Map<String, Subscription> disputeIsClosedSubscriptionsMap = new HashMap<>(); final ObservableList<PriceFeedComboBoxItem> priceFeedComboBoxItems = FXCollections.observableArrayList(); @SuppressWarnings("FieldCanBeLocal") private MonadicBinding<String> marketPriceBinding; @SuppressWarnings({"unused", "FieldCanBeLocal"}) private Subscription priceFeedAllLoadedSubscription; private BooleanProperty p2pNetWorkReady; private final BooleanProperty walletInitialized = new SimpleBooleanProperty(); private boolean allBasicServicesInitialized; /////////////////////////////////////////////////////////////////////////////////////////// // Constructor /////////////////////////////////////////////////////////////////////////////////////////// @SuppressWarnings("WeakerAccess") @Inject public MainViewModel(WalletsManager walletsManager, WalletsSetup walletsSetup, BtcWalletService btcWalletService, BalanceModel balanceModel, BalancePresentation balancePresentation, TradePresentation tradePresentation, DisputePresentation disputePresentation, PriceFeedService priceFeedService, ArbitratorManager arbitratorManager, P2PService p2PService, TradeManager tradeManager, OpenOfferManager openOfferManager, DisputeManager disputeManager, Preferences preferences, User user, AlertManager alertManager, PrivateNotificationManager privateNotificationManager, FilterManager filterManager, WalletPasswordWindow walletPasswordWindow, TradeStatisticsManager tradeStatisticsManager, NotificationCenter notificationCenter, TacWindow tacWindow, Clock clock, FeeService feeService, DaoSetup daoSetup, EncryptionService encryptionService, KeyRing keyRing, BisqEnvironment bisqEnvironment, FailedTradesManager failedTradesManager, ClosedTradableManager closedTradableManager, AccountAgeWitnessService accountAgeWitnessService, TorNetworkSettingsWindow torNetworkSettingsWindow, CorruptedDatabaseFilesHandler corruptedDatabaseFilesHandler, BSFormatter formatter) { this.walletsManager = walletsManager; this.walletsSetup = walletsSetup; this.btcWalletService = btcWalletService; this.balanceModel = balanceModel; this.balancePresentation = balancePresentation; this.tradePresentation = tradePresentation; this.disputePresentation = disputePresentation; this.priceFeedService = priceFeedService; this.user = user; this.arbitratorManager = arbitratorManager; this.p2PService = p2PService; this.tradeManager = tradeManager; this.openOfferManager = openOfferManager; this.disputeManager = disputeManager; this.preferences = preferences; this.alertManager = alertManager; this.privateNotificationManager = privateNotificationManager; this.filterManager = filterManager; // Reference so it's initialized and eventListener gets registered this.walletPasswordWindow = walletPasswordWindow; this.tradeStatisticsManager = tradeStatisticsManager; this.notificationCenter = notificationCenter; this.tacWindow = tacWindow; this.clock = clock; this.feeService = feeService; this.daoSetup = daoSetup; this.encryptionService = encryptionService; this.keyRing = keyRing; this.bisqEnvironment = bisqEnvironment; this.failedTradesManager = failedTradesManager; this.closedTradableManager = closedTradableManager; this.accountAgeWitnessService = accountAgeWitnessService; this.torNetworkSettingsWindow = torNetworkSettingsWindow; this.corruptedDatabaseFilesHandler = corruptedDatabaseFilesHandler; this.formatter = formatter; TxIdTextField.setPreferences(preferences); // TODO TxIdTextField.setWalletService(btcWalletService); BalanceWithConfirmationTextField.setWalletService(btcWalletService); } /////////////////////////////////////////////////////////////////////////////////////////// // API /////////////////////////////////////////////////////////////////////////////////////////// public void start() { // We do the delete of the spv file at startup before BitcoinJ is initialized to avoid issues with locked files under Windows. if (preferences.isResyncSpvRequested()) { try { walletsSetup.reSyncSPVChain(); } catch (IOException e) { log.error(e.toString()); e.printStackTrace(); } } //noinspection ConstantConditions,ConstantConditions,PointlessBooleanExpression if (!preferences.isTacAccepted() && !DevEnv.isDevMode()) { UserThread.runAfter(() -> { tacWindow.onAction(() -> { preferences.setTacAccepted(true); checkIfLocalHostNodeIsRunning(); }).show(); }, 1); } else { checkIfLocalHostNodeIsRunning(); } } private void readMapsFromResources() { SetupUtils.readFromResources(p2PService.getP2PDataStorage()).addListener((observable, oldValue, newValue) -> { if (newValue) startBasicServices(); }); // TODO can be removed in jdk 9 checkCryptoSetup(); } private void startBasicServices() { log.info("startBasicServices"); ChangeListener<Boolean> walletInitializedListener = (observable, oldValue, newValue) -> { // TODO that seems to be called too often if Tor takes longer to start up... if (newValue && !p2pNetWorkReady.get()) showTorNetworkSettingsWindow(); }; Timer startupTimeout = UserThread.runAfter(() -> { log.warn("startupTimeout called"); if (walletsManager.areWalletsEncrypted()) walletInitialized.addListener(walletInitializedListener); else showTorNetworkSettingsWindow(); }, STARTUP_TIMEOUT_MINUTES, TimeUnit.MINUTES); p2pNetWorkReady = initP2PNetwork(); // We only init wallet service here if not using Tor for bitcoinj. // When using Tor, wallet init must be deferred until Tor is ready. if (!preferences.getUseTorForBitcoinJ() || bisqEnvironment.isBitcoinLocalhostNodeRunning()) initWalletService(); // need to store it to not get garbage collected allServicesDone = EasyBind.combine(walletInitialized, p2pNetWorkReady, (a, b) -> { log.debug("\nwalletInitialized={}\n" + "p2pNetWorkReady={}", a, b); return a && b; }); allServicesDone.subscribe((observable, oldValue, newValue) -> { if (newValue) { startupTimeout.stop(); walletInitialized.removeListener(walletInitializedListener); onBasicServicesInitialized(); if (torNetworkSettingsWindow != null) torNetworkSettingsWindow.hide(); } }); } private void showTorNetworkSettingsWindow() { torNetworkSettingsWindow.show(); } /////////////////////////////////////////////////////////////////////////////////////////// // Initialisation /////////////////////////////////////////////////////////////////////////////////////////// private BooleanProperty initP2PNetwork() { log.info("initP2PNetwork"); StringProperty bootstrapState = new SimpleStringProperty(); StringProperty bootstrapWarning = new SimpleStringProperty(); BooleanProperty hiddenServicePublished = new SimpleBooleanProperty(); BooleanProperty initialP2PNetworkDataReceived = new SimpleBooleanProperty(); p2PNetworkInfoBinding = EasyBind.combine(bootstrapState, bootstrapWarning, p2PService.getNumConnectedPeers(), hiddenServicePublished, initialP2PNetworkDataReceived, (state, warning, numPeers, hiddenService, dataReceived) -> { String result = ""; int peers = (int) numPeers; if (warning != null && peers == 0) { result = warning; } else { String p2pInfo = Res.get("mainView.footer.p2pInfo", numPeers); if (dataReceived && hiddenService) { result = p2pInfo; } else if (peers == 0) result = state; else result = state + " / " + p2pInfo; } return result; }); p2PNetworkInfoBinding.subscribe((observable, oldValue, newValue) -> { p2PNetworkInfo.set(newValue); }); bootstrapState.set(Res.get("mainView.bootstrapState.connectionToTorNetwork")); p2PService.getNetworkNode().addConnectionListener(new ConnectionListener() { @Override public void onConnection(Connection connection) { } @Override public void onDisconnect(CloseConnectionReason closeConnectionReason, Connection connection) { // We only check at seed nodes as they are running the latest version // Other disconnects might be caused by peers running an older version if (connection.getPeerType() == Connection.PeerType.SEED_NODE && closeConnectionReason == CloseConnectionReason.RULE_VIOLATION) { log.warn("RULE_VIOLATION onDisconnect closeConnectionReason=" + closeConnectionReason); log.warn("RULE_VIOLATION onDisconnect connection=" + connection); } } @Override public void onError(Throwable throwable) { } }); final BooleanProperty p2pNetworkInitialized = new SimpleBooleanProperty(); p2PService.start(new P2PServiceListener() { @Override public void onTorNodeReady() { log.debug("onTorNodeReady"); bootstrapState.set(Res.get("mainView.bootstrapState.torNodeCreated")); p2PNetworkIconId.set("image-connection-tor"); if (preferences.getUseTorForBitcoinJ()) initWalletService(); // We want to get early connected to the price relay so we call it already now priceFeedService.setCurrencyCodeOnInit(); priceFeedService.initialRequestPriceFeed(); } @Override public void onHiddenServicePublished() { log.debug("onHiddenServicePublished"); hiddenServicePublished.set(true); bootstrapState.set(Res.get("mainView.bootstrapState.hiddenServicePublished")); } @Override public void onDataReceived() { log.debug("onRequestingDataCompleted"); initialP2PNetworkDataReceived.set(true); bootstrapState.set(Res.get("mainView.bootstrapState.initialDataReceived")); splashP2PNetworkAnimationVisible.set(false); p2pNetworkInitialized.set(true); } @Override public void onNoSeedNodeAvailable() { log.warn("onNoSeedNodeAvailable"); if (p2PService.getNumConnectedPeers().get() == 0) bootstrapWarning.set(Res.get("mainView.bootstrapWarning.noSeedNodesAvailable")); else bootstrapWarning.set(null); splashP2PNetworkAnimationVisible.set(false); p2pNetworkInitialized.set(true); } @Override public void onNoPeersAvailable() { log.warn("onNoPeersAvailable"); if (p2PService.getNumConnectedPeers().get() == 0) { p2pNetworkWarnMsg.set(Res.get("mainView.p2pNetworkWarnMsg.noNodesAvailable")); bootstrapWarning.set(Res.get("mainView.bootstrapWarning.noNodesAvailable")); p2pNetworkLabelId.set("splash-error-state-msg"); } else { bootstrapWarning.set(null); p2pNetworkLabelId.set("footer-pane"); } splashP2PNetworkAnimationVisible.set(false); p2pNetworkInitialized.set(true); } @Override public void onUpdatedDataReceived() { log.debug("onBootstrapComplete"); splashP2PNetworkAnimationVisible.set(false); bootstrapComplete.set(true); } @Override public void onSetupFailed(Throwable throwable) { log.warn("onSetupFailed"); p2pNetworkWarnMsg.set(Res.get("mainView.p2pNetworkWarnMsg.connectionToP2PFailed", throwable.getMessage())); splashP2PNetworkAnimationVisible.set(false); bootstrapWarning.set(Res.get("mainView.bootstrapWarning.bootstrappingToP2PFailed")); p2pNetworkLabelId.set("splash-error-state-msg"); } @Override public void onRequestCustomBridges() { showTorNetworkSettingsWindow(); } }); return p2pNetworkInitialized; } private void initWalletService() { log.info("initWalletService"); ObjectProperty<Throwable> walletServiceException = new SimpleObjectProperty<>(); btcInfoBinding = EasyBind.combine(walletsSetup.downloadPercentageProperty(), walletsSetup.numPeersProperty(), walletServiceException, (downloadPercentage, numPeers, exception) -> { String result = ""; if (exception == null) { double percentage = (double) downloadPercentage; int peers = (int) numPeers; btcSyncProgress.set(percentage); if (percentage == 1) { result = Res.get("mainView.footer.btcInfo", peers, Res.get("mainView.footer.btcInfo.synchronizedWith"), getBtcNetworkAsString()); btcSplashSyncIconId.set("image-connection-synced"); if (allBasicServicesInitialized) checkForLockedUpFunds(); } else if (percentage > 0.0) { result = Res.get("mainView.footer.btcInfo", peers, Res.get("mainView.footer.btcInfo.synchronizedWith"), getBtcNetworkAsString() + ": " + formatter.formatToPercentWithSymbol(percentage)); } else { result = Res.get("mainView.footer.btcInfo", peers, Res.get("mainView.footer.btcInfo.connectingTo"), getBtcNetworkAsString()); } } else { result = Res.get("mainView.footer.btcInfo", numBtcPeers, Res.get("mainView.footer.btcInfo.connectionFailed"), getBtcNetworkAsString()); log.error(exception.getMessage()); if (exception instanceof TimeoutException) { walletServiceErrorMsg.set(Res.get("mainView.walletServiceErrorMsg.timeout")); } else if (exception.getCause() instanceof BlockStoreException) { if (exception.getCause().getCause() instanceof ChainFileLockedException) { new Popup<>().warning(Res.get("popup.warning.startupFailed.twoInstances")) .useShutDownButton() .show(); } else { new Popup<>().warning(Res.get("error.spvFileCorrupted", exception.getMessage())) .actionButtonText(Res.get("settings.net.reSyncSPVChainButton")) .onAction(() -> GUIUtil.reSyncSPVChain(walletsSetup, preferences)) .show(); } } else { walletServiceErrorMsg.set(Res.get("mainView.walletServiceErrorMsg.connectionError", exception.toString())); } } return result; }); btcInfoBinding.subscribe((observable, oldValue, newValue) -> { btcInfo.set(newValue); }); walletsSetup.initialize(null, () -> { log.debug("walletsSetup.onInitialized"); numBtcPeers = walletsSetup.numPeersProperty().get(); // We only check one as we apply encryption to all or none if (walletsManager.areWalletsEncrypted()) { if (p2pNetWorkReady.get()) splashP2PNetworkAnimationVisible.set(false); walletPasswordWindow .onAesKey(aesKey -> { walletsManager.setAesKey(aesKey); if (preferences.isResyncSpvRequested()) { showFirstPopupIfResyncSPVRequested(); } else { walletInitialized.set(true); } }) .hideCloseButton() .show(); } else { if (preferences.isResyncSpvRequested()) { showFirstPopupIfResyncSPVRequested(); } else { walletInitialized.set(true); } } }, walletServiceException::set); } private void onBasicServicesInitialized() { log.info("onBasicServicesInitialized"); clock.start(); PaymentMethod.onAllServicesInitialized(); // disputeManager disputeManager.onAllServicesInitialized(); initTradeManager(); // btcWalletService btcWalletService.addBalanceListener(new BalanceListener() { @Override public void onBalanceChanged(Coin balance, Transaction tx) { balanceModel.updateBalance(); } }); openOfferManager.getObservableList().addListener((ListChangeListener<OpenOffer>) c -> balanceModel.updateBalance()); openOfferManager.onAllServicesInitialized(); removeOffersWithoutAccountAgeWitness(); arbitratorManager.onAllServicesInitialized(); alertManager.alertMessageProperty().addListener((observable, oldValue, newValue) -> displayAlertIfPresent(newValue, false)); privateNotificationManager.privateNotificationProperty().addListener((observable, oldValue, newValue) -> displayPrivateNotification(newValue)); displayAlertIfPresent(alertManager.alertMessageProperty().get(), false); p2PService.onAllServicesInitialized(); feeService.onAllServicesInitialized(); GUIUtil.setFeeService(feeService); daoSetup.onAllServicesInitialized(errorMessage -> new Popup<>().error(errorMessage).show()); tradeStatisticsManager.onAllServicesInitialized(); accountAgeWitnessService.onAllServicesInitialized(); priceFeedService.setCurrencyCodeOnInit(); filterManager.onAllServicesInitialized(); filterManager.addListener(filter -> { if (filter != null) { if (filter.getSeedNodes() != null && !filter.getSeedNodes().isEmpty()) new Popup<>().warning(Res.get("popup.warning.nodeBanned", Res.get("popup.warning.seed"))).show(); if (filter.getPriceRelayNodes() != null && !filter.getPriceRelayNodes().isEmpty()) new Popup<>().warning(Res.get("popup.warning.nodeBanned", Res.get("popup.warning.priceRelay"))).show(); } }); setupBtcNumPeersWatcher(); setupP2PNumPeersWatcher(); balanceModel.updateBalance(); if (DevEnv.isDevMode()) { preferences.setShowOwnOffersInOfferBook(true); setupDevDummyPaymentAccounts(); } fillPriceFeedComboBoxItems(); setupMarketPriceFeed(); swapPendingOfferFundingEntries(); showAppScreen.set(true); String key = "remindPasswordAndBackup"; user.getPaymentAccountsAsObservable().addListener((SetChangeListener<PaymentAccount>) change -> { if (!walletsManager.areWalletsEncrypted() && preferences.showAgain(key) && change.wasAdded()) { new Popup<>().headLine(Res.get("popup.securityRecommendation.headline")) .information(Res.get("popup.securityRecommendation.msg")) .dontShowAgainId(key) .show(); } }); checkIfOpenOffersMatchTradeProtocolVersion(); if (walletsSetup.downloadPercentageProperty().get() == 1) checkForLockedUpFunds(); checkForCorruptedDataBaseFiles(); allBasicServicesInitialized = true; } private void initTradeManager() { // tradeManager tradeManager.onAllServicesInitialized(); tradeManager.getTradableList().addListener((ListChangeListener<Trade>) change -> balanceModel.updateBalance()); tradeManager.setTakeOfferRequestErrorMessageHandler(errorMessage -> new Popup<>() .warning(Res.get("popup.error.takeOfferRequestFailed", errorMessage)) .show()); // We handle the trade period here as we display a global popup if we reached dispute time tradesAndUIReady = EasyBind.combine(isSplashScreenRemoved, tradeManager.pendingTradesInitializedProperty(), (a, b) -> a && b); tradesAndUIReady.subscribe((observable, oldValue, newValue) -> { if (newValue) { tradeManager.applyTradePeriodState(); tradeManager.getTradableList().forEach(trade -> { Date maxTradePeriodDate = trade.getMaxTradePeriodDate(); String key; switch (trade.getTradePeriodState()) { case FIRST_HALF: break; case SECOND_HALF: key = "displayHalfTradePeriodOver" + trade.getId(); if (DontShowAgainLookup.showAgain(key)) { DontShowAgainLookup.dontShowAgain(key, true); new Popup<>().warning(Res.get("popup.warning.tradePeriod.halfReached", trade.getShortId(), formatter.formatDateTime(maxTradePeriodDate))) .show(); } break; case TRADE_PERIOD_OVER: key = "displayTradePeriodOver" + trade.getId(); if (DontShowAgainLookup.showAgain(key)) { DontShowAgainLookup.dontShowAgain(key, true); new Popup<>().warning(Res.get("popup.warning.tradePeriod.ended", trade.getShortId(), formatter.formatDateTime(maxTradePeriodDate))) .show(); } break; } }); } }); } private void showFirstPopupIfResyncSPVRequested() { Popup firstPopup = new Popup<>(); firstPopup.information(Res.get("settings.net.reSyncSPVAfterRestart")).show(); if (btcSyncProgress.get() == 1) { showSecondPopupIfResyncSPVRequested(firstPopup); } else { btcSyncProgress.addListener((observable, oldValue, newValue) -> { if ((double) newValue == 1) showSecondPopupIfResyncSPVRequested(firstPopup); }); } } private void showSecondPopupIfResyncSPVRequested(Popup firstPopup) { firstPopup.hide(); preferences.setResyncSpvRequested(false); new Popup<>().information(Res.get("settings.net.reSyncSPVAfterRestartCompleted")) .hideCloseButton() .useShutDownButton() .show(); } private void checkIfLocalHostNodeIsRunning() { Thread checkIfLocalHostNodeIsRunningThread = new Thread() { @Override public void run() { Thread.currentThread().setName("checkIfLocalHostNodeIsRunningThread"); Socket socket = null; try { socket = new Socket(); socket.connect(new InetSocketAddress(InetAddresses.forString("127.0.0.1"), BisqEnvironment.getBaseCurrencyNetwork().getParameters().getPort()), 5000); log.info("Localhost peer detected."); UserThread.execute(() -> { bisqEnvironment.setBitcoinLocalhostNodeRunning(true); readMapsFromResources(); }); } catch (Throwable e) { log.info("Localhost peer not detected."); UserThread.execute(MainViewModel.this::readMapsFromResources); } finally { if (socket != null) { try { socket.close(); } catch (IOException ignore) { } } } } }; checkIfLocalHostNodeIsRunningThread.start(); } private void checkCryptoSetup() { BooleanProperty result = new SimpleBooleanProperty(); // We want to test if the client is compiled with the correct crypto provider (BountyCastle) // and if the unlimited Strength for cryptographic keys is set. // If users compile themselves they might miss that step and then would get an exception in the trade. // To avoid that we add here at startup a sample encryption and signing to see if it don't causes an exception. // See: https://github.com/bisq-network/exchange/blob/master/doc/build.md#7-enable-unlimited-strength-for-cryptographic-keys Thread checkCryptoThread = new Thread() { @Override public void run() { try { Thread.currentThread().setName("checkCryptoThread"); log.trace("Run crypto test"); // just use any simple dummy msg Ping payload = new Ping(1, 1); SealedAndSigned sealedAndSigned = EncryptionService.encryptHybridWithSignature(payload, keyRing.getSignatureKeyPair(), keyRing.getPubKeyRing().getEncryptionPubKey()); DecryptedDataTuple tuple = encryptionService.decryptHybridWithSignature(sealedAndSigned, keyRing.getEncryptionKeyPair().getPrivate()); if (tuple.getNetworkEnvelope() instanceof Ping && ((Ping) tuple.getNetworkEnvelope()).getNonce() == payload.getNonce() && ((Ping) tuple.getNetworkEnvelope()).getLastRoundTripTime() == payload.getLastRoundTripTime()) { log.debug("Crypto test succeeded"); if (Security.getProvider("BC") != null) { UserThread.execute(() -> result.set(true)); } else { throw new CryptoException("Security provider BountyCastle is not available."); } } else { throw new CryptoException("Payload not correct after decryption"); } } catch (CryptoException e) { e.printStackTrace(); String msg = Res.get("popup.warning.cryptoTestFailed", e.getMessage()); log.error(msg); UserThread.execute(() -> new Popup<>().warning(msg) .useShutDownButton() .useReportBugButton() .show()); } } }; checkCryptoThread.start(); } private void checkIfOpenOffersMatchTradeProtocolVersion() { List<OpenOffer> outDatedOffers = openOfferManager.getObservableList() .stream() .filter(e -> e.getOffer().getProtocolVersion() != Version.TRADE_PROTOCOL_VERSION) .collect(Collectors.toList()); if (!outDatedOffers.isEmpty()) { String offers = outDatedOffers.stream() .map(e -> e.getId() + "\n") .collect(Collectors.toList()).toString() .replace("[", "").replace("]", ""); new Popup<>() .warning(Res.get("popup.warning.oldOffers.msg", offers)) .actionButtonText(Res.get("popup.warning.oldOffers.buttonText")) .onAction(() -> openOfferManager.removeOpenOffers(outDatedOffers, null)) .useShutDownButton() .show(); } } /////////////////////////////////////////////////////////////////////////////////////////// // UI handlers /////////////////////////////////////////////////////////////////////////////////////////// // After showAppScreen is set and splash screen is faded out void onSplashScreenRemoved() { isSplashScreenRemoved.set(true); // Delay that as we want to know what is the current path of the navigation which is set // in MainView showAppScreen handler notificationCenter.onAllServicesAndViewsInitialized(); } /////////////////////////////////////////////////////////////////////////////////////////// // Private /////////////////////////////////////////////////////////////////////////////////////////// private void setupP2PNumPeersWatcher() { p2PService.getNumConnectedPeers().addListener((observable, oldValue, newValue) -> { int numPeers = (int) newValue; if ((int) oldValue > 0 && numPeers == 0) { // give a bit of tolerance if (checkNumberOfP2pNetworkPeersTimer != null) checkNumberOfP2pNetworkPeersTimer.stop(); checkNumberOfP2pNetworkPeersTimer = UserThread.runAfter(() -> { // check again numPeers if (p2PService.getNumConnectedPeers().get() == 0) { p2pNetworkWarnMsg.set(Res.get("mainView.networkWarning.allConnectionsLost", Res.get("shared.P2P"))); p2pNetworkLabelId.set("splash-error-state-msg"); } else { p2pNetworkWarnMsg.set(null); p2pNetworkLabelId.set("footer-pane"); } }, 5); } else if ((int) oldValue == 0 && numPeers > 0) { if (checkNumberOfP2pNetworkPeersTimer != null) checkNumberOfP2pNetworkPeersTimer.stop(); p2pNetworkWarnMsg.set(null); p2pNetworkLabelId.set("footer-pane"); } }); } private void setupBtcNumPeersWatcher() { walletsSetup.numPeersProperty().addListener((observable, oldValue, newValue) -> { int numPeers = (int) newValue; if ((int) oldValue > 0 && numPeers == 0) { if (checkNumberOfBtcPeersTimer != null) checkNumberOfBtcPeersTimer.stop(); checkNumberOfBtcPeersTimer = UserThread.runAfter(() -> { // check again numPeers if (walletsSetup.numPeersProperty().get() == 0) { if (bisqEnvironment.isBitcoinLocalhostNodeRunning()) walletServiceErrorMsg.set(Res.get("mainView.networkWarning.localhostBitcoinLost", Res.getBaseCurrencyName().toLowerCase())); else walletServiceErrorMsg.set(Res.get("mainView.networkWarning.allConnectionsLost", Res.getBaseCurrencyName().toLowerCase())); } else { walletServiceErrorMsg.set(null); } }, 5); } else if ((int) oldValue == 0 && numPeers > 0) { if (checkNumberOfBtcPeersTimer != null) checkNumberOfBtcPeersTimer.stop(); walletServiceErrorMsg.set(null); } }); } private void setupMarketPriceFeed() { priceFeedService.requestPriceFeed(price -> marketPrice.set(formatter.formatMarketPrice(price, priceFeedService.getCurrencyCode())), (errorMessage, throwable) -> marketPrice.set(Res.get("shared.na"))); marketPriceBinding = EasyBind.combine( marketPriceCurrencyCode, marketPrice, (currencyCode, price) -> formatter.getCurrencyPair(currencyCode) + ": " + price); marketPriceBinding.subscribe((observable, oldValue, newValue) -> { if (newValue != null && !newValue.equals(oldValue)) { setMarketPriceInItems(); String code = priceFeedService.currencyCodeProperty().get(); Optional<PriceFeedComboBoxItem> itemOptional = findPriceFeedComboBoxItem(code); if (itemOptional.isPresent()) { itemOptional.get().setDisplayString(newValue); selectedPriceFeedComboBoxItemProperty.set(itemOptional.get()); } else { if (CurrencyUtil.isCryptoCurrency(code)) { CurrencyUtil.getCryptoCurrency(code).ifPresent(cryptoCurrency -> { preferences.addCryptoCurrency(cryptoCurrency); fillPriceFeedComboBoxItems(); }); } else { CurrencyUtil.getFiatCurrency(code).ifPresent(fiatCurrency -> { preferences.addFiatCurrency(fiatCurrency); fillPriceFeedComboBoxItems(); }); } } if (selectedPriceFeedComboBoxItemProperty.get() != null) selectedPriceFeedComboBoxItemProperty.get().setDisplayString(newValue); } }); marketPriceCurrencyCode.bind(priceFeedService.currencyCodeProperty()); priceFeedAllLoadedSubscription = EasyBind.subscribe(priceFeedService.updateCounterProperty(), updateCounter -> setMarketPriceInItems()); preferences.getTradeCurrenciesAsObservable().addListener((ListChangeListener<TradeCurrency>) c -> UserThread.runAfter(() -> { fillPriceFeedComboBoxItems(); setMarketPriceInItems(); }, 100, TimeUnit.MILLISECONDS)); } private void setMarketPriceInItems() { priceFeedComboBoxItems.stream().forEach(item -> { String currencyCode = item.currencyCode; MarketPrice marketPrice = priceFeedService.getMarketPrice(currencyCode); String priceString; if (marketPrice != null && marketPrice.isPriceAvailable()) { priceString = formatter.formatMarketPrice(marketPrice.getPrice(), currencyCode); item.setPriceAvailable(true); item.setExternallyProvidedPrice(marketPrice.isExternallyProvidedPrice()); } else { priceString = Res.get("shared.na"); item.setPriceAvailable(false); } item.setDisplayString(formatter.getCurrencyPair(currencyCode) + ": " + priceString); final String code = item.currencyCode; if (selectedPriceFeedComboBoxItemProperty.get() != null && selectedPriceFeedComboBoxItemProperty.get().currencyCode.equals(code)) { isFiatCurrencyPriceFeedSelected.set(CurrencyUtil.isFiatCurrency(code) && CurrencyUtil.getFiatCurrency(code).isPresent() && item.isPriceAvailable() && item.isExternallyProvidedPrice()); isCryptoCurrencyPriceFeedSelected.set(CurrencyUtil.isCryptoCurrency(code) && CurrencyUtil.getCryptoCurrency(code).isPresent() && item.isPriceAvailable() && item.isExternallyProvidedPrice()); isExternallyProvidedPrice.set(item.isExternallyProvidedPrice()); isPriceAvailable.set(item.isPriceAvailable()); marketPriceUpdated.set(marketPriceUpdated.get() + 1); } }); } public void setPriceFeedComboBoxItem(PriceFeedComboBoxItem item) { if (item != null) { Optional<PriceFeedComboBoxItem> itemOptional = findPriceFeedComboBoxItem(priceFeedService.currencyCodeProperty().get()); if (itemOptional.isPresent()) selectedPriceFeedComboBoxItemProperty.set(itemOptional.get()); else findPriceFeedComboBoxItem(preferences.getPreferredTradeCurrency().getCode()) .ifPresent(selectedPriceFeedComboBoxItemProperty::set); priceFeedService.setCurrencyCode(item.currencyCode); } else { findPriceFeedComboBoxItem(preferences.getPreferredTradeCurrency().getCode()) .ifPresent(selectedPriceFeedComboBoxItemProperty::set); } } private Optional<PriceFeedComboBoxItem> findPriceFeedComboBoxItem(String currencyCode) { return priceFeedComboBoxItems.stream() .filter(item -> item.currencyCode.equals(currencyCode)) .findAny(); } private void fillPriceFeedComboBoxItems() { List<PriceFeedComboBoxItem> currencyItems = preferences.getTradeCurrenciesAsObservable() .stream() .map(tradeCurrency -> new PriceFeedComboBoxItem(tradeCurrency.getCode())) .collect(Collectors.toList()); priceFeedComboBoxItems.setAll(currencyItems); } private void displayAlertIfPresent(Alert alert, boolean openNewVersionPopup) { if (alert != null) { if (alert.isUpdateInfo()) { user.setDisplayedAlert(alert); final boolean isNewVersion = alert.isNewVersion(); newVersionAvailableProperty.set(isNewVersion); String key = "Update_" + alert.getVersion(); if (isNewVersion && (preferences.showAgain(key) || openNewVersionPopup)) { new DisplayUpdateDownloadWindow(alert) .actionButtonText(Res.get("displayUpdateDownloadWindow.button.downloadLater")) .onAction(() -> { preferences.dontShowAgain(key, false); // update later }) .closeButtonText(Res.get("shared.cancel")) .onClose(() -> { preferences.dontShowAgain(key, true); // ignore update }) .show(); } } else { final Alert displayedAlert = user.getDisplayedAlert(); if (displayedAlert == null || !displayedAlert.equals(alert)) new DisplayAlertMessageWindow() .alertMessage(alert) .onClose(() -> { user.setDisplayedAlert(alert); }) .show(); } } } private void displayPrivateNotification(PrivateNotificationPayload privateNotification) { new Popup<>().headLine(Res.get("popup.privateNotification.headline")) .attention(privateNotification.getMessage()) .setHeadlineStyle("-fx-text-fill: -bs-error-red; -fx-font-weight: bold; -fx-font-size: 16;") .onClose(privateNotificationManager::removePrivateNotification) .useIUnderstandButton() .show(); } private void swapPendingOfferFundingEntries() { tradeManager.getAddressEntriesForAvailableBalanceStream() .filter(addressEntry -> addressEntry.getOfferId() != null) .forEach(addressEntry -> { log.debug("swapPendingOfferFundingEntries, offerId={}, OFFER_FUNDING", addressEntry.getOfferId()); btcWalletService.swapTradeEntryToAvailableEntry(addressEntry.getOfferId(), AddressEntry.Context.OFFER_FUNDING); }); } private void checkForLockedUpFunds() { Set<String> tradesIdSet = tradeManager.getLockedTradesStream() .filter(Trade::hasFailed) .map(Trade::getId) .collect(Collectors.toSet()); tradesIdSet.addAll(failedTradesManager.getLockedTradesStream() .map(Trade::getId) .collect(Collectors.toSet())); tradesIdSet.addAll(closedTradableManager.getLockedTradesStream() .map(e -> { log.warn("We found a closed trade with locked up funds. " + "That should never happen. trade ID=" + e.getId()); return e.getId(); }) .collect(Collectors.toSet())); btcWalletService.getAddressEntriesForTrade().stream() .filter(e -> tradesIdSet.contains(e.getOfferId()) && e.getContext() == AddressEntry.Context.MULTI_SIG) .forEach(e -> { final Coin balance = e.getCoinLockedInMultiSig(); final String message = Res.get("popup.warning.lockedUpFunds", formatter.formatCoinWithCode(balance), e.getAddressString(), e.getOfferId()); log.warn(message); new Popup<>().warning(message).show(); }); } private void removeOffersWithoutAccountAgeWitness() { if (new Date().after(AccountAgeWitnessService.FULL_ACTIVATION)) { openOfferManager.getObservableList().stream() .filter(e -> CurrencyUtil.isFiatCurrency(e.getOffer().getCurrencyCode())) .filter(e -> !e.getOffer().getAccountAgeWitnessHashAsHex().isPresent()) .forEach(e -> { new Popup<>().warning(Res.get("popup.warning.offerWithoutAccountAgeWitness", e.getId())) .actionButtonText(Res.get("popup.warning.offerWithoutAccountAgeWitness.confirm")) .onAction(() -> { openOfferManager.removeOffer(e.getOffer(), () -> { log.info("Offer with ID {} is removed", e.getId()); }, log::error); }) .hideCloseButton() .show(); }); } } private void checkForCorruptedDataBaseFiles() { List<String> files = corruptedDatabaseFilesHandler.getCorruptedDatabaseFiles(); if (files.size() == 0) return; if (files.size() == 1 && files.get(0).equals("ViewPathAsString")) { log.debug("We detected incompatible data base file for Navigation. " + "That is a minor issue happening with refactoring of UI classes " + "and we don't display a warning popup to the user."); return; } // show warning that some files have been corrupted new Popup<>() .warning(Res.get("popup.warning.incompatibleDB", files.toString(), getAppDateDir())) .useShutDownButton() .show(); } private void setupDevDummyPaymentAccounts() { if (user.getPaymentAccounts() != null && user.getPaymentAccounts().isEmpty()) { PerfectMoneyAccount perfectMoneyAccount = new PerfectMoneyAccount(); perfectMoneyAccount.init(); perfectMoneyAccount.setAccountNr("dummy_" + new Random().nextInt(100)); perfectMoneyAccount.setAccountName("PerfectMoney dummy");// Don't translate only for dev perfectMoneyAccount.setSelectedTradeCurrency(new FiatCurrency("USD")); user.addPaymentAccount(perfectMoneyAccount); if (p2PService.isBootstrapped()) { accountAgeWitnessService.publishMyAccountAgeWitness(perfectMoneyAccount.getPaymentAccountPayload()); } else { p2PService.addP2PServiceListener(new BootstrapListener() { @Override public void onUpdatedDataReceived() { accountAgeWitnessService.publishMyAccountAgeWitness(perfectMoneyAccount.getPaymentAccountPayload()); } }); } CryptoCurrencyAccount cryptoCurrencyAccount = new CryptoCurrencyAccount(); cryptoCurrencyAccount.init(); cryptoCurrencyAccount.setAccountName("ETH dummy");// Don't translate only for dev cryptoCurrencyAccount.setAddress("0x" + new Random().nextInt(1000000)); cryptoCurrencyAccount.setSingleTradeCurrency(CurrencyUtil.getCryptoCurrency("ETH").get()); user.addPaymentAccount(cryptoCurrencyAccount); } } String getAppDateDir() { return bisqEnvironment.getProperty(AppOptionKeys.APP_DATA_DIR_KEY); } void openDownloadWindow() { displayAlertIfPresent(user.getDisplayedAlert(), true); } public String getBtcNetworkAsString() { String postFix; if (bisqEnvironment.isBitcoinLocalhostNodeRunning()) postFix = " " + Res.get("mainView.footer.localhostBitcoinNode"); else if (preferences.getUseTorForBitcoinJ()) postFix = " " + Res.get("mainView.footer.usingTor"); else postFix = ""; return Res.get(BisqEnvironment.getBaseCurrencyNetwork().name()) + postFix; } StringProperty getNumOpenDisputes() { return disputePresentation.getNumOpenDisputes(); } BooleanProperty getShowOpenDisputesNotification() { return disputePresentation.getShowOpenDisputesNotification(); } BooleanProperty getShowPendingTradesNotification() { return tradePresentation.getShowPendingTradesNotification(); } StringProperty getNumPendingTrades() { return tradePresentation.getNumPendingTrades(); } StringProperty getAvailableBalance() { return balancePresentation.getAvailableBalance(); } StringProperty getReservedBalance() { return balancePresentation.getReservedBalance(); } StringProperty getLockedBalance() { return balancePresentation.getLockedBalance(); } }
Remove removeOffersWithoutAccountAgeWitness method
src/main/java/bisq/desktop/main/MainViewModel.java
Remove removeOffersWithoutAccountAgeWitness method
<ide><path>rc/main/java/bisq/desktop/main/MainViewModel.java <ide> <ide> PaymentMethod.onAllServicesInitialized(); <ide> <del> // disputeManager <ide> disputeManager.onAllServicesInitialized(); <ide> <del> <ide> initTradeManager(); <ide> <del> // btcWalletService <ide> btcWalletService.addBalanceListener(new BalanceListener() { <ide> @Override <ide> public void onBalanceChanged(Coin balance, Transaction tx) { <ide> <ide> openOfferManager.getObservableList().addListener((ListChangeListener<OpenOffer>) c -> balanceModel.updateBalance()); <ide> openOfferManager.onAllServicesInitialized(); <del> removeOffersWithoutAccountAgeWitness(); <ide> <ide> arbitratorManager.onAllServicesInitialized(); <ide> alertManager.alertMessageProperty().addListener((observable, oldValue, newValue) -> displayAlertIfPresent(newValue, false)); <ide> }); <ide> } <ide> <del> private void removeOffersWithoutAccountAgeWitness() { <del> if (new Date().after(AccountAgeWitnessService.FULL_ACTIVATION)) { <del> openOfferManager.getObservableList().stream() <del> .filter(e -> CurrencyUtil.isFiatCurrency(e.getOffer().getCurrencyCode())) <del> .filter(e -> !e.getOffer().getAccountAgeWitnessHashAsHex().isPresent()) <del> .forEach(e -> { <del> new Popup<>().warning(Res.get("popup.warning.offerWithoutAccountAgeWitness", e.getId())) <del> .actionButtonText(Res.get("popup.warning.offerWithoutAccountAgeWitness.confirm")) <del> .onAction(() -> { <del> openOfferManager.removeOffer(e.getOffer(), <del> () -> { <del> log.info("Offer with ID {} is removed", e.getId()); <del> }, <del> log::error); <del> }) <del> .hideCloseButton() <del> .show(); <del> }); <del> } <del> } <del> <ide> private void checkForCorruptedDataBaseFiles() { <ide> List<String> files = corruptedDatabaseFilesHandler.getCorruptedDatabaseFiles(); <ide>
JavaScript
apache-2.0
c7c618dbc572c2fba20068185306c1f6d9ce33b0
0
Unleash/unleash,Unleash/unleash,Unleash/unleash,Unleash/unleash
'use strict'; /** * Copyright (c) 2017-present, Facebook, Inc. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. */ // See https://docusaurus.io/docs/site-config for all the possible // site configuration options. // List of projects/orgs using your project for the users page. const users = [ { caption: 'FINN.no', // You will need to prepend the image path with your baseUrl // if it is not '/', like: '/test-site/img/docusaurus.svg'. image: '/img/finn.jpg', infoLink: 'https://www.finn.no', pinned: true, }, { caption: 'NAV.no', // You will need to prepend the image path with your baseUrl // if it is not '/', like: '/test-site/img/docusaurus.svg'. image: '/img/nav.jpg', infoLink: 'https://www.nav.no', pinned: true, }, { caption: 'Unleash Hosted', image: '/img/unleash-hosted.svg', infoLink: 'https://www.unleash-hosted.com', pinned: true, }, { caption: 'Budgets', image: '/img/budgets.png', infoLink: 'https://budgets.money', pinned: true, }, { caption: 'Otovo', image: '/img/otovo.png', infoLink: 'https://www.otovo.com', pinned: true, }, ]; const siteConfig = { title: 'Unleash', // Title for your website. tagline: 'The enterprise ready feature toggle service', url: 'https://unleash.github.io', // Your website URL baseUrl: '/', // Base URL for your project */ // For github.io type URLs, you would set the url and baseUrl like: // url: 'https://facebook.github.io', // baseUrl: '/test-site/', // Used for publishing and more projectName: 'unleash.github.io', organizationName: 'Unleash', // For top-level user or org sites, the organization is still the same. // e.g., for the https://JoelMarcey.github.io site, it would be set like... // organizationName: 'JoelMarcey' // For no header links in the top nav bar -> headerLinks: [], headerLinks: [ { doc: 'user_guide/connect_sdk', label: 'Documentation' }, { doc: 'api/client/features', label: 'API' }, { doc: 'deploy/getting_started', label: 'Deploy and manage' }, { doc: 'integrations/integrations', label: 'Integrations' }, { doc: 'developer_guide', label: 'Contribute' }, { page: 'help', label: 'Help' }, // {blog: true, label: 'Blog'}, ], // If you have users set above, you add it here: users, /* path to images for header/footer */ headerIcon: 'img/logo-inverted.png', footerIcon: 'img/logo-inverted.png', favicon: 'img/favicon/favicon.ico', /* Colors for website */ colors: { primaryColor: '#3f51b5', secondaryColor: '#697ce5', }, /* Custom fonts for website */ /* fonts: { myFont: [ "Times New Roman", "Serif" ], myOtherFont: [ "-apple-system", "system-ui" ] }, */ // This copyright info is used in /core/Footer.js and blog RSS/Atom feeds. copyright: `Copyright © ${new Date().getFullYear()}`, highlight: { // Highlight.js theme to use for syntax highlighting in code blocks. theme: 'default', }, // Add custom scripts here that would be placed in <script> tags. scripts: ['https://buttons.github.io/buttons.js'], // On page navigation for the current documentation page. onPageNav: 'separate', // No .html extensions for paths. cleanUrl: true, // Open Graph and Twitter card images. ogImage: 'img/unleash_logo.png', twitterImage: 'img/unleash_logo.png', // Show documentation's last contributor's name. // enableUpdateBy: true, // Show documentation's last update time. // enableUpdateTime: true, // You may provide arbitrary config keys to be used as needed by your // template. For example, if you need your repo's URL... repoUrl: 'https://github.com/unleash/unleash', gaTrackingId: 'UA-134882379-1', gaGtag: true, }; module.exports = siteConfig;
website/siteConfig.js
'use strict'; /** * Copyright (c) 2017-present, Facebook, Inc. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. */ // See https://docusaurus.io/docs/site-config for all the possible // site configuration options. // List of projects/orgs using your project for the users page. const users = [ { caption: 'FINN.no', // You will need to prepend the image path with your baseUrl // if it is not '/', like: '/test-site/img/docusaurus.svg'. image: '/img/finn.jpg', infoLink: 'https://www.finn.no', pinned: true, }, { caption: 'NAV.no', // You will need to prepend the image path with your baseUrl // if it is not '/', like: '/test-site/img/docusaurus.svg'. image: '/img/nav.jpg', infoLink: 'https://www.nav.no', pinned: true, }, { caption: 'Unleash Hosted', image: '/img/unleash-hosted.svg', infoLink: 'https://www.unleash-hosted.com', pinned: true, }, { caption: 'Budgets', image: '/img/budgets.png', infoLink: 'https://budgets.money', pinned: true, }, { caption: 'Otovo', image: '/img/otovo.png', infoLink: 'https://www.otovo.com', pinned: true, }, ]; const siteConfig = { title: 'Unleash', // Title for your website. tagline: 'The enterprise ready feature toggle service', url: 'https://unleash.github.io', // Your website URL baseUrl: '/', // Base URL for your project */ // For github.io type URLs, you would set the url and baseUrl like: // url: 'https://facebook.github.io', // baseUrl: '/test-site/', // Used for publishing and more projectName: 'unleash.github.io', organizationName: 'Unleash', // For top-level user or org sites, the organization is still the same. // e.g., for the https://JoelMarcey.github.io site, it would be set like... // organizationName: 'JoelMarcey' // For no header links in the top nav bar -> headerLinks: [], headerLinks: [ { doc: 'user_guide/connect_sdk', label: 'Documentation' }, { doc: 'api/client/features', label: 'API' }, { doc: 'deploy/getting_started', label: 'Deploy and manage' }, { doc: 'integrations/integrations', label: 'Integrations' }, { doc: 'developer_guide', label: 'Contribute' }, { page: 'help', label: 'Help' }, // {blog: true, label: 'Blog'}, ], // If you have users set above, you add it here: users, /* path to images for header/footer */ headerIcon: 'img/logo-inverted.png', footerIcon: 'img/logo-inverted.png', favicon: 'img/favicon/favicon.ico', /* Colors for website */ colors: { primaryColor: '#3f51b5', secondaryColor: '#697ce5', }, /* Custom fonts for website */ /* fonts: { myFont: [ "Times New Roman", "Serif" ], myOtherFont: [ "-apple-system", "system-ui" ] }, */ // This copyright info is used in /core/Footer.js and blog RSS/Atom feeds. copyright: `Copyright © ${new Date().getFullYear()}`, highlight: { // Highlight.js theme to use for syntax highlighting in code blocks. theme: 'default', }, // Add custom scripts here that would be placed in <script> tags. scripts: ['https://buttons.github.io/buttons.js'], // On page navigation for the current documentation page. onPageNav: 'separate', // No .html extensions for paths. cleanUrl: true, // Open Graph and Twitter card images. ogImage: 'img/unleash_logo.png', twitterImage: 'img/unleash_logo.png', // Show documentation's last contributor's name. // enableUpdateBy: true, // Show documentation's last update time. // enableUpdateTime: true, // You may provide arbitrary config keys to be used as needed by your // template. For example, if you need your repo's URL... repoUrl: 'https://github.com/unleash/unleash', gaTrackingId: 'UA-129659197-1', gaGtag: true, }; module.exports = siteConfig;
chore: update gaTrackingId for user docs
website/siteConfig.js
chore: update gaTrackingId for user docs
<ide><path>ebsite/siteConfig.js <ide> // template. For example, if you need your repo's URL... <ide> repoUrl: 'https://github.com/unleash/unleash', <ide> <del> gaTrackingId: 'UA-129659197-1', <add> gaTrackingId: 'UA-134882379-1', <ide> gaGtag: true, <ide> }; <ide>
JavaScript
mit
7d28913b91c53a967b90279bf67f111277a763d4
0
lisfan/logger
/** * @file 日志打印器 * @author lisfan <[email protected]> * @version 1.3.2 * @licence MIT */ import validation from '@~lisfan/validation' /** * 从`localStorage`的`LOGGER_RULES`键中读取**打印规则**配置,以便可以在生产环境开启日志打印调试 */ const LOGGER_RULES = JSON.parse(global.localStorage.getItem('LOGGER_RULES')) || {} /** * 从`localStorage`的`IS_DEV`键中读取是否为**开发环境**配置,以便可以在生产环境开启日志打印调试 */ const IS_DEV = JSON.parse(global.localStorage.getItem('IS_DEV')) || process.env.NODE_ENV === 'development' // 私有方法 const _actions = { /** * 打印器工厂函数 * 查找ls中是否存在打印命名空间配置项,若存在,则进行替换覆盖 * 判断是否存在子命名空间,依次判断子命名空间的长度 * * @since 1.3.0 * * @param {Logger} self - Logger实例 * @param {string} method - 打印方法 * @param {string} color - 颜色值,web安全色 http://www.w3school.com.cn/tiy/color.asp?color=LightGoldenRodYellow * * @returns {function} */ logFactory(self, method, color) { return (...args) => { return _actions.logProxyRun(self, method, color, ...args) } }, /** * 代理运行打印方法 * * @since 1.3.0 * * @param {Logger} self - Logger实例 * @param {string} method - 打印方法 * @param {string} color - 打印颜色,颜色值,web安全色 http://www.w3school.com.cn/tiy/color.asp?color=LightGoldenRodYellow * @param {...*} args - 其他参数 * * @returns {Logger} */ logProxyRun(self, method, color, ...args) { // 处于非激活状态的话则不输出日志 if (!self.isActivated(method)) { return self } let formatStr = `%c[${self.$name}]:%c` // 遍历参数列表,找出dom元素,进行转换 args = args.map((arg) => { return validation.isElement(arg) ? [arg] : arg }) /* eslint-disable no-console */ console[method](formatStr, `color: ${color}`, '', ...args) /* eslint-enable no-console */ return self }, /** * 代理运行console方法 * [注] 内部会进行判断是否允许日志输出 * * @since 1.3.0 * * @param {Logger} self - Logger实例 * @param {string} method - 打印方法 * @param {...*} args - 其他参数 * * @returns {Logger} */ proxyRun(self, method, ...args) { /* eslint-disable no-console */ self.isActivated(method) && console[method](...args) /* eslint-enable no-console */ return self } } /** * @classdesc 日志打印类 * * @class */ class Logger { /** * 打印器命名空间规则配置项 * - 可以配置整个命名空间是否输出日志 * - 也可以配置命名空间下某个实例方法是否输出日志 * * @since 1.2.0 * * @static * @readonly * @memberOf Logger * * @type {object} * @property {object} rules - 打印器命名空间规则配置集合 */ static rules = LOGGER_RULES /** * 更改命名空间规则配置项 * [注]从`localStorage`的`LOGGER_RULES`键中读取规则配置优先级最高,始终会覆盖其他规则 * * @since 1.2.0 * * @param {object} rules - 配置参数 * @param {string} [rules.name] - 日志器命名空间 * @param {boolean} [rules.debug] - 调试模式是否开启 * * @returns {Logger} * * @example * // 定义规则 * Logger.configRules = { * utils-http:false // 整个utils-http不可打印输出 * utils-calc.log=true // utils-calc打印器的log方法不支持打印输出 * } */ static configRules(rules) { Logger.rules = { ...Logger.rules, ...rules, ...LOGGER_RULES, } return this } /** * 默认配置选项 * 为了在生产环境能开启调试模式 * 提供了从localStorage获取默认配置项的措施 * * @since 1.0.0 * * @static * @readonly * @memberOf Logger * * @type {object} * @property {string} name='logger' - 日志器命名空间,默认为'logger' * @property {boolean} debug=true - 调试模式是否开启,默认开启 */ static options = { name: 'logger', debug: true, } /** * 更新默认配置选项 * * @since 1.0.0 * * @see Logger.options * * @param {object} options - 配置选项见{@link Logger.options} * * @returns {Logger} */ static config(options) { // 以内置配置为优先 Logger.options = { ...Logger.options, ...options } return this } /** * 构造函数 * * @see Logger.options * * @param {object} options - 配置选项见{@link Logger.options},若参数为`string`类型,则表示设定为`options.name`的值 */ constructor(options) { this.$options = validation.isString(options) ? { ...Logger.options, name: options } : { ...Logger.options, ...options } } /** * 实例的配置项 * * @since 1.0.0 * * @readonly * * @type {object} */ $options = undefined /** * 获取实例的命名空间配置项 * * @since 1.1.0 * * @getter * @readonly * * @type {string} */ get $name() { return this.$options.name } /** * 获取实例的调试模式配置项 * * @since 1.1.0 * * @getter * @readonly * * @type {boolean} */ get $debug() { return this.$options.debug } /** * 检测当前是否调试模式是否激活:可以打印日志 * * @since 1.1.0 * * @param {string} [method] - 若指定了该参数,则精确检测具体的实例方法 * * @returns {boolean} */ isActivated(method) { // 如果不是开发模式 if (!IS_DEV) { return false } // 以子命名空间的状态优先 let status = Logger.rules[this.$name] // 先判断其子命名空间的状态 // 如果存在放法名,则判断子命名空间 // 当前方法名存在子命名空间里且明确设置为false时,则不打印 // 当前子命名空间如果明确false,则不打印 if (method) { const subStatus = Logger.rules[`${this.$name}.${method}`] if (validation.isBoolean(subStatus)) status = subStatus } // 如果明确指定该命名空间不开启日志打印,则不打印 if (status === false) { return false } // 最后才判断实例是否禁用了调试 if (!this.$debug) { return false } return true } /** * 创建一个指定颜色的打印方法 * * @since 1.1.0 * * @param {string} color - 颜色值 * * @returns {Function} */ color(color) { return _actions.logFactory(this, 'log', `${color}`) } /** * 启用日志输出 * * @since 1.1.0 * * @returns {Logger} */ enable() { this.$options.debug = true return this } /** * 禁用日志输出 * * @since 1.1.0 * * @returns {Logger} */ disable() { this.$options.debug = false return this } /** * 常规日志打印 * * @since 1.0.0 * * @param {...*} args - 任意数据 * * @returns {Logger} */ log(...args) { return _actions.logProxyRun(this, 'log', 'lightseagreen', ...args) } /** * 警告日志打印 * * @since 1.0.0 * * @param {...*} args - 任意数据 * * @returns {Logger} */ warn(...args) { return _actions.logProxyRun(this, 'warn', 'goldenrod', ...args) } /** * 调用栈日志打印 * * @since 1.0.1 * * @param {...*} args - 任意数据 * * @returns {Logger} */ trace(...args) { return _actions.logProxyRun(this, 'trace', 'lightseagreen', ...args) } /** * 错误日志打印,同时会抛出错误,阻塞后续逻辑 * * @since 1.0.0 * * @param {...*} args - 参数列表 * * @throws Error - 抛出错误提示 */ error(...args) { const message = args.map((value) => { return value.toString() }).join(' ') throw new Error(message) } /** * log的同名方法,使用方法请参考{@link Logger#log} * * @since 1.1.0 * * @see Logger#log * * @param {...*} args - 任意数据 * * @returns {Logger} */ info(...args) { return this.log(...args) } /** * log的同名方法,使用方法请参考{@link Logger#log} * * @since 1.1.0 * * @see Logger#log * * @param {...*} args - 任意数据 * * @returns {Logger} */ debug(...args) { return this.log(...args) } /** * 区别于console.table * - 对象或数组类型数据以表格的方式打印 * - 若非这两种数据类型,则调用log方法打印 * * @since 1.1.0 * * @param {*} data - 任意数据 * * @returns {Logger} */ table(data) { return validation.isArray(data) && validation.isPlainObject(data) ? this.log(data) : _actions.proxyRun(this, 'table', data) } /** * 打印纯对象数据 * * @since 1.1.0 * * @param {...*} args - 任意数据 * * @returns {Logger} */ dir(...args) { return _actions.proxyRun(this, 'dir', ...args) } /** * 打印纯对象数据 * * @since 1.1.0 * * @param {...*} args - 任意数据 * * @returns {Logger} */ dirxml(...args) { return _actions.proxyRun(this, 'dirxml', ...args) } /** * 创建一个组,接下来所有的打印内容,都会包裹在组内,直到调用groupEnd()方法结束,退出组 * * @since 1.1.0 * * @param {string} label - 标签名称 * * @returns {Logger} */ group(label) { return _actions.proxyRun(this, 'group', label) } /** * 类似group()方法,区别在于调用该方法后打印的内容都是折叠的,需要手动展开 * * @since 1.1.0 * * @param {string} label - 标签名称 * * @returns {Logger} */ groupCollapsed(label) { return _actions.proxyRun(this, 'groupCollapsed', label) } /** * 关闭组 * * @since 1.1.0 * * @returns {Logger} */ groupEnd() { return _actions.proxyRun(this, 'groupEnd') } /** * 统计被执行的次数 * * @since 1.1.0 * * @param {string} label - 标签名称 * * @returns {Logger} */ count(label) { return _actions.proxyRun(this, 'count', label) } /** * 开始设置一个timer追踪操作任意的消耗时间,直到调用timeEnd()结束追踪,消耗时间单位为毫秒 * * @since 1.1.0 * * @param {string} label - 标签名称 * * @returns {Logger} */ time(label) { return _actions.proxyRun(this, 'time', label) } /** * 结束追踪 * * @since 1.1.0 * * @returns {Logger} */ timeEnd() { return _actions.proxyRun(this, 'timeEnd') } /** * 结束追踪 * * @since 1.1.0 * * @returns {Logger} */ timeStamp(...args) { return _actions.proxyRun(this, 'timeStamp', ...args) } /** * 开始记录一个性能分析简报,直到调用profileEnd()结束记录 * * @since 1.1.0 * * @param {string} label - 标签名称 * * @returns {Logger} */ profile(label) { return _actions.proxyRun(this, 'profile', label) } /** * 结束记录 * * @since 1.1.0 * * @returns {Logger} */ profileEnd() { return _actions.proxyRun(this, 'profileEnd') } /** * 断言表达式,若结果为false,是抛出失败输出 * * @since 1.1.0 * * @param {boolean} assertion - 表达式 * @param {...*} args - 断言失败输出 * * @returns {Logger} */ assert(assertion, ...args) { return _actions.proxyRun(this, 'assert', assertion, ...args) } /** * 清空控制台 * * @since 1.1.0 * * @returns {Logger} */ clear() { return _actions.proxyRun(this, 'clear') } } export default Logger
src/logger.js
/** * @file 日志打印器 * @author lisfan <[email protected]> * @version 1.3.2 * @licence MIT */ import validation from '@~lisfan/validation' /** * 从`localStorage`的`LOGGER_RULES`键中读取**打印规则**配置,以便可以在生产环境开启日志打印调试 */ const LOGGER_RULES = JSON.parse(global.localStorage.getItem('LOGGER_RULES')) || {} /** * 从`localStorage`的`IS_DEV`键中读取是否为**开发环境**配置,以便可以在生产环境开启日志打印调试 */ const IS_DEV = JSON.parse(global.localStorage.getItem('IS_DEV')) || process.env.NODE_ENV === 'development' // 私有方法 const _actions = { /** * 打印器工厂函数 * 查找ls中是否存在打印命名空间配置项,若存在,则进行替换覆盖 * 判断是否存在子命名空间,依次判断子命名空间的长度 * * @since 1.3.0 * * @param {Logger} self - Logger实例 * @param {string} method - 打印方法 * @param {string} color - 颜色值,web安全色 http://www.w3school.com.cn/tiy/color.asp?color=LightGoldenRodYellow * * @returns {function} */ logFactory(self, method, color) { return (...args) => { return _actions.logProxyRun(self, method, color, ...args) } }, /** * 代理运行打印方法 * * @since 1.3.0 * * @param {Logger} self - Logger实例 * @param {string} method - 打印方法 * @param {string} color - 打印颜色,颜色值,web安全色 http://www.w3school.com.cn/tiy/color.asp?color=LightGoldenRodYellow * @param {...*} args - 其他参数 * * @returns {Logger} */ logProxyRun(self, method, color, ...args) { // 处于非激活状态的话则不输出日志 if (!self.isActivated(method)) { return self } let formatStr = `%c[${self.$name}]:%c` // 遍历参数列表,找出dom元素,进行转换 args = args.map((arg) => { return validation.isElement(arg) ? [arg] : arg }) /* eslint-disable no-console */ console[method](formatStr, `color: ${color}`, '', ...args) /* eslint-enable no-console */ return self }, /** * 代理运行console方法 * [注] 内部会进行判断是否允许日志输出 * * @since 1.3.0 * * @param {Logger} self - Logger实例 * @param {string} method - 打印方法 * @param {...*} args - 其他参数 * * @returns {Logger} */ proxyRun(self, method, ...args) { /* eslint-disable no-console */ self.isActivated(method) && console[method](...args) /* eslint-enable no-console */ return self } } /** * @classdesc * 日志打印类 * * @class */ class Logger { /** * 打印器命名空间规则配置项 * - 可以配置整个命名空间是否输出日志 * - 也可以配置命名空间下某个实例方法是否输出日志 * * @since 1.2.0 * * @static * @readonly * @memberOf Logger * * @property {object} rules - 打印器命名空间规则配置集合 */ static rules = LOGGER_RULES /** * 更改命名空间规则配置项 * [注]从`localStorage`的`LOGGER_RULES`键中读取规则配置优先级最高,始终会覆盖其他规则 * * @since 1.2.0 * * @static * * @param {object} rules - 配置参数 * @param {string} [rules.name] - 日志器命名空间 * @param {boolean} [rules.debug] - 调试模式是否开启 * * @returns {Logger} * * @example * // 定义规则 * Logger.configRules = { * utils-http:false // 整个utils-http不可打印输出 * utils-calc.log=true // utils-calc打印器的log方法不支持打印输出 * } */ static configRules(rules) { Logger.rules = { ...Logger.rules, ...rules, ...LOGGER_RULES, } return this } /** * 默认配置选项 * 为了在生产环境能开启调试模式 * 提供了从localStorage获取默认配置项的措施 * * @since 1.0.0 * * @static * @readonly * @memberOf Logger * * @property {string} name='logger' - 日志器命名空间,默认为'logger' * @property {boolean} debug=true - 调试模式是否开启,默认开启 */ static options = { name: 'logger', debug: true, } /** * 更新默认配置选项 * * @since 1.0.0 * * @static * * @param {object} options - 配置参数 * @param {string} [options.name='logger'] - 日志器命名空间 * @param {boolean} [options.debug=true] - 调试模式是否开启 * * @returns {Logger} */ static config(options) { // 以内置配置为优先 Logger.options = { ...Logger.options, ...options } return this } /** * 构造函数 * * @param {object} [options] - 实例配置选项,若参数为`string`类型,则表示设定为`options.name`的值 * @param {string} [options.name='logger'] - 日志器命名空间 * @param {boolean} [options.debug=true] - 调试模式是否开启 */ constructor(options) { this.$options = validation.isString(options) ? { ...Logger.options, name: options } : { ...Logger.options, ...options } } /** * 实例的配置项 * * @since 1.0.0 * * @readonly * * @returns {object} */ $options = undefined /** * 获取实例的命名空间配置项 * * @since 1.1.0 * * @readonly * * @returns {string} */ get $name() { return this.$options.name } /** * 获取实例的调试模式配置项 * * @since 1.1.0 * * @returns {string} */ get $debug() { return this.$options.debug } /** * 检测当前是否调试模式是否激活:可以打印日志 * * @since 1.1.0 * * @param {string} [method] - 若指定了该参数,则精确检测具体的实例方法 * * @returns {boolean} */ isActivated(method) { // 如果不是开发模式 if (!IS_DEV) { return false } // 以子命名空间的状态优先 let status = Logger.rules[this.$name] // 先判断其子命名空间的状态 // 如果存在放法名,则判断子命名空间 // 当前方法名存在子命名空间里且明确设置为false时,则不打印 // 当前子命名空间如果明确false,则不打印 if (method) { const subStatus = Logger.rules[`${this.$name}.${method}`] if (validation.isBoolean(subStatus)) status = subStatus } // 如果明确指定该命名空间不开启日志打印,则不打印 if (status === false) { return false } // 最后才判断实例是否禁用了调试 if (!this.$debug) { return false } return true } /** * 创建一个指定颜色的打印方法 * * @since 1.1.0 * * @param {string} color - 颜色值 * * @returns {Function} */ color(color) { return _actions.logFactory(this, 'log', `${color}`) } /** * 启用日志输出 * * @since 1.1.0 * * @returns {Logger} */ enable() { this.$options.debug = true return this } /** * 禁用日志输出 * * @since 1.1.0 * * @returns {Logger} */ disable() { this.$options.debug = false return this } /** * 常规日志打印 * * @since 1.0.0 * * @param {...*} args - 任意数据 * * @returns {Logger} */ log(...args) { return _actions.logProxyRun(this, 'log', 'lightseagreen', ...args) } /** * 警告日志打印 * * @since 1.0.0 * * @param {...*} args - 任意数据 * * @returns {Logger} */ warn(...args) { return _actions.logProxyRun(this, 'warn', 'goldenrod', ...args) } /** * 调用栈日志打印 * * @since 1.0.1 * * @param {...*} args - 任意数据 * * @returns {Logger} */ trace(...args) { return _actions.logProxyRun(this, 'trace', 'lightseagreen', ...args) } /** * 错误日志打印,同时会抛出错误,阻塞后续逻辑 * * @since 1.0.0 * * @param {...*} args - 参数列表 * * @throws Error - 抛出错误提示 */ error(...args) { const message = args.map((value) => { return value.toString() }).join(' ') throw new Error(message) } /** * log的同名方法,使用方法请参考{@link Logger#log} * * @since 1.1.0 * * @see Logger#log * * @param {...*} args - 任意数据 * * @returns {Logger} */ info(...args) { return this.log(...args) } /** * log的同名方法,使用方法请参考{@link Logger#log} * * @since 1.1.0 * * @see Logger#log * * @param {...*} args - 任意数据 * * @returns {Logger} */ debug(...args) { return this.log(...args) } /** * 区别于console.table * - 对象或数组类型数据以表格的方式打印 * - 若非这两种数据类型,则调用log方法打印 * * @since 1.1.0 * * @param {*} data - 任意数据 * * @returns {Logger} */ table(data) { return validation.isArray(data) && validation.isPlainObject(data) ? this.log(data) : _actions.proxyRun(this, 'table', data) } /** * 打印纯对象数据 * * @since 1.1.0 * * @param {...*} args - 任意数据 * * @returns {Logger} */ dir(...args) { return _actions.proxyRun(this, 'dir', ...args) } /** * 打印纯对象数据 * * @since 1.1.0 * * @param {...*} args - 任意数据 * * @returns {Logger} */ dirxml(...args) { return _actions.proxyRun(this, 'dirxml', ...args) } /** * 创建一个组,接下来所有的打印内容,都会包裹在组内,直到调用groupEnd()方法结束,退出组 * * @since 1.1.0 * * @param {string} label - 标签名称 * * @returns {Logger} */ group(label) { return _actions.proxyRun(this, 'group', label) } /** * 类似group()方法,区别在于调用该方法后打印的内容都是折叠的,需要手动展开 * * @since 1.1.0 * * @param {string} label - 标签名称 * * @returns {Logger} */ groupCollapsed(label) { return _actions.proxyRun(this, 'groupCollapsed', label) } /** * 关闭组 * * @since 1.1.0 * * @returns {Logger} */ groupEnd() { return _actions.proxyRun(this, 'groupEnd') } /** * 统计被执行的次数 * * @since 1.1.0 * * @param {string} label - 标签名称 * * @returns {Logger} */ count(label) { return _actions.proxyRun(this, 'count', label) } /** * 开始设置一个timer追踪操作任意的消耗时间,直到调用timeEnd()结束追踪,消耗时间单位为毫秒 * * @since 1.1.0 * * @param {string} label - 标签名称 * * @returns {Logger} */ time(label) { return _actions.proxyRun(this, 'time', label) } /** * 结束追踪 * * @since 1.1.0 * * @returns {Logger} */ timeEnd() { return _actions.proxyRun(this, 'timeEnd') } /** * 结束追踪 * * @since 1.1.0 * * @returns {Logger} */ timeStamp(...args) { return _actions.proxyRun(this, 'timeStamp', ...args) } /** * 开始记录一个性能分析简报,直到调用profileEnd()结束记录 * * @since 1.1.0 * * @param {string} label - 标签名称 * * @returns {Logger} */ profile(label) { return _actions.proxyRun(this, 'profile', label) } /** * 结束记录 * * @since 1.1.0 * * @returns {Logger} */ profileEnd() { return _actions.proxyRun(this, 'profileEnd') } /** * 断言表达式,若结果为false,是抛出失败输出 * * @since 1.1.0 * * @param {boolean} assertion - 表达式 * @param {...*} args - 断言失败输出 * * @returns {Logger} */ assert(assertion, ...args) { return _actions.proxyRun(this, 'assert', assertion, ...args) } /** * 清空控制台 * * @since 1.1.0 * * @returns {Logger} */ clear() { return _actions.proxyRun(this, 'clear') } } export default Logger
docs: 更新jsdoc
src/logger.js
docs: 更新jsdoc
<ide><path>rc/logger.js <ide> } <ide> <ide> /** <del> * @classdesc <del> * 日志打印类 <add> * @classdesc 日志打印类 <ide> * <ide> * @class <ide> */ <ide> * @readonly <ide> * @memberOf Logger <ide> * <add> * @type {object} <ide> * @property {object} rules - 打印器命名空间规则配置集合 <ide> */ <ide> static rules = LOGGER_RULES <ide> * [注]从`localStorage`的`LOGGER_RULES`键中读取规则配置优先级最高,始终会覆盖其他规则 <ide> * <ide> * @since 1.2.0 <del> * <del> * @static <ide> * <ide> * @param {object} rules - 配置参数 <ide> * @param {string} [rules.name] - 日志器命名空间 <ide> * @readonly <ide> * @memberOf Logger <ide> * <add> * @type {object} <ide> * @property {string} name='logger' - 日志器命名空间,默认为'logger' <ide> * @property {boolean} debug=true - 调试模式是否开启,默认开启 <ide> */ <ide> * <ide> * @since 1.0.0 <ide> * <del> * @static <del> * <del> * @param {object} options - 配置参数 <del> * @param {string} [options.name='logger'] - 日志器命名空间 <del> * @param {boolean} [options.debug=true] - 调试模式是否开启 <add> * @see Logger.options <add> * <add> * @param {object} options - 配置选项见{@link Logger.options} <ide> * <ide> * @returns {Logger} <ide> */ <ide> /** <ide> * 构造函数 <ide> * <del> * @param {object} [options] - 实例配置选项,若参数为`string`类型,则表示设定为`options.name`的值 <del> * @param {string} [options.name='logger'] - 日志器命名空间 <del> * @param {boolean} [options.debug=true] - 调试模式是否开启 <add> * @see Logger.options <add> * <add> * @param {object} options - 配置选项见{@link Logger.options},若参数为`string`类型,则表示设定为`options.name`的值 <ide> */ <ide> constructor(options) { <ide> this.$options = validation.isString(options) <ide> * <ide> * @readonly <ide> * <del> * @returns {object} <add> * @type {object} <ide> */ <ide> $options = undefined <ide> <ide> * <ide> * @since 1.1.0 <ide> * <add> * @getter <ide> * @readonly <ide> * <del> * @returns {string} <add> * @type {string} <ide> */ <ide> get $name() { <ide> return this.$options.name <ide> * <ide> * @since 1.1.0 <ide> * <del> * @returns {string} <add> * @getter <add> * @readonly <add> * <add> * @type {boolean} <ide> */ <ide> get $debug() { <ide> return this.$options.debug
Java
epl-1.0
77e5b1a27490035f9c7235ddf449a2caaad20969
0
RandallDW/Aruba_plugin,rgom/Pydev,fabioz/Pydev,akurtakov/Pydev,RandallDW/Aruba_plugin,fabioz/Pydev,rgom/Pydev,akurtakov/Pydev,rajul/Pydev,rajul/Pydev,aptana/Pydev,akurtakov/Pydev,akurtakov/Pydev,rgom/Pydev,fabioz/Pydev,rgom/Pydev,rajul/Pydev,fabioz/Pydev,rgom/Pydev,akurtakov/Pydev,rgom/Pydev,fabioz/Pydev,aptana/Pydev,rajul/Pydev,RandallDW/Aruba_plugin,RandallDW/Aruba_plugin,rajul/Pydev,RandallDW/Aruba_plugin,fabioz/Pydev,aptana/Pydev,rajul/Pydev,RandallDW/Aruba_plugin,akurtakov/Pydev
/* * License: Common Public License v1.0 * Created on Mar 11, 2004 * * @author Fabio Zadrozny * @author atotic */ package org.python.pydev.plugin.nature; import java.io.File; import java.util.List; import org.eclipse.core.resources.ICommand; import org.eclipse.core.resources.IFile; import org.eclipse.core.resources.IProject; import org.eclipse.core.resources.IProjectDescription; import org.eclipse.core.resources.IProjectNature; import org.eclipse.core.resources.IResource; import org.eclipse.core.runtime.CoreException; import org.eclipse.core.runtime.IPath; import org.eclipse.core.runtime.IProgressMonitor; import org.eclipse.core.runtime.IStatus; import org.eclipse.core.runtime.NullProgressMonitor; import org.eclipse.core.runtime.QualifiedName; import org.eclipse.core.runtime.Status; import org.eclipse.core.runtime.jobs.Job; import org.eclipse.ui.IEditorInput; import org.eclipse.ui.part.FileEditorInput; import org.python.pydev.builder.PyDevBuilderPrefPage; import org.python.pydev.core.ExtensionHelper; import org.python.pydev.core.ICodeCompletionASTManager; import org.python.pydev.core.IPythonNature; import org.python.pydev.core.IPythonPathNature; import org.python.pydev.core.REF; import org.python.pydev.editor.codecompletion.revisited.ASTManager; import org.python.pydev.plugin.PydevPlugin; import org.python.pydev.ui.interpreters.IInterpreterObserver; import org.python.pydev.utils.JobProgressComunicator; /** * PythonNature is currently used as a marker class. * * When python nature is present, project gets extra properties. Project gets assigned python nature when: - a python file is edited - a * python project wizard is created * * */ public class PythonNature implements IPythonNature { /** * This is the nature ID */ public static final String PYTHON_NATURE_ID = "org.python.pydev.pythonNature"; /** * This is the nature name */ public static final String PYTHON_NATURE_NAME = "pythonNature"; /** * Builder id for pydev (code completion todo and others) */ public static final String BUILDER_ID = "org.python.pydev.PyDevBuilder"; /** * constant that stores the name of the python version we are using for the project with this nature */ private static final QualifiedName PYTHON_PROJECT_VERSION = new QualifiedName(PydevPlugin.getPluginID(), "PYTHON_PROJECT_VERSION"); /** * Project associated with this nature. */ private IProject project; /** * This is the completions cache for the nature represented by this object (it is associated with a project). */ private ICodeCompletionASTManager astManager; /** * We have to know if it has already been initialized. */ private boolean initialized; /** * Manages pythonpath things */ private IPythonPathNature pythonPathNature = new PythonPathNature(); /** * This method is called only when the project has the nature added.. * * @see org.eclipse.core.resources.IProjectNature#configure() */ public void configure() throws CoreException { } /** * @see org.eclipse.core.resources.IProjectNature#deconfigure() */ public void deconfigure() throws CoreException { } /** * Returns the project * * @see org.eclipse.core.resources.IProjectNature#getProject() */ public IProject getProject() { return project; } /** * Sets this nature's project - called from the eclipse platform. * * @see org.eclipse.core.resources.IProjectNature#setProject(org.eclipse.core.resources.IProject) */ public void setProject(IProject project) { this.project = project; this.pythonPathNature.setProject(project); } public static synchronized IPythonNature addNature(IEditorInput element) { if(element instanceof FileEditorInput){ IFile file = (IFile)((FileEditorInput)element).getAdapter(IFile.class); if (file != null){ try { return PythonNature.addNature(file.getProject(), null); } catch (CoreException e) { PydevPlugin.log(e); } } } return null; } /** * Utility routine to add PythonNature to the project * @return */ public static synchronized IPythonNature addNature(IProject project, IProgressMonitor monitor) throws CoreException { if (project == null) { return null; } if(monitor == null){ monitor = new NullProgressMonitor(); } IProjectDescription desc = project.getDescription(); //only add the nature if it still hasn't been added. if (project.hasNature(PYTHON_NATURE_ID) == false) { String[] natures = desc.getNatureIds(); String[] newNatures = new String[natures.length + 1]; System.arraycopy(natures, 0, newNatures, 0, natures.length); newNatures[natures.length] = PYTHON_NATURE_ID; desc.setNatureIds(newNatures); project.setDescription(desc, monitor); } //add the builder. It is used for pylint, pychecker, code completion, etc. ICommand[] commands = desc.getBuildSpec(); //now, add the builder if it still hasn't been added. if (hasBuilder(commands) == false && PyDevBuilderPrefPage.usePydevBuilders()) { ICommand command = desc.newCommand(); command.setBuilderName(BUILDER_ID); ICommand[] newCommands = new ICommand[commands.length + 1]; System.arraycopy(commands, 0, newCommands, 1, commands.length); newCommands[0] = command; desc.setBuildSpec(newCommands); project.setDescription(desc, monitor); } IProjectNature n = project.getNature(PYTHON_NATURE_ID); if (n instanceof PythonNature) { PythonNature nature = (PythonNature) n; //call initialize always - let it do the control. nature.init(); return nature; } return null; } /** * Utility to know if the pydev builder is in one of the commands passed. * * @param commands */ private static boolean hasBuilder(ICommand[] commands) { for (int i = 0; i < commands.length; i++) { if (commands[i].getBuilderName().equals(BUILDER_ID)) { return true; } } return false; } /** * Initializes the python nature if it still has not been for this session. * * Actions includes restoring the dump from the code completion cache */ private void init() { final PythonNature nature = this; if (initialized == false) { initialized = true; Job codeCompletionLoadJob = new Job("Pydev code completion") { @SuppressWarnings("unchecked") protected IStatus run(IProgressMonitor monitorArg) { //begins task automatically JobProgressComunicator jobProgressComunicator = new JobProgressComunicator(monitorArg, "Pydev restoring cache info...", IProgressMonitor.UNKNOWN, this); astManager = (ICodeCompletionASTManager) ASTManager.loadFromFile(getAstOutputFile()); //errors can happen when restoring it if(astManager == null){ try { String pythonPathStr = pythonPathNature.getOnlyProjectPythonPathStr(); rebuildPath(pythonPathStr); } catch (Exception e) { PydevPlugin.log(e); } }else{ synchronized(astManager){ astManager.setProject(getProject(), true); // this is the project related to it, restore the deltas (we may have some crash) List<IInterpreterObserver> participants = ExtensionHelper.getParticipants(ExtensionHelper.PYDEV_INTERPRETER_OBSERVER); for (IInterpreterObserver observer : participants) { try { observer.notifyNatureRecreated(nature, jobProgressComunicator); } catch (Exception e) { //let's not fail because of other plugins PydevPlugin.log(e); } } } } jobProgressComunicator.done(); return Status.OK_STATUS; } }; codeCompletionLoadJob.schedule(); } } /** * Returns the directory that should store completions. * * @param p * @return */ public static File getCompletionsCacheDir(IProject p) { IPath location = p.getWorkingLocation(PydevPlugin.getPluginID()); IPath path = location; File file = new File(path.toOSString()); return file; } public File getCompletionsCacheDir() { return getCompletionsCacheDir(getProject()); } /** * @param dir: parent directory where file should be. * @return the file where the python path helper should be saved. */ private File getAstOutputFile() { return new File(getCompletionsCacheDir(), "asthelper.completions"); } /** * This method is called whenever the pythonpath for the project with this nature is changed. */ public void rebuildPath(final String paths) { final PythonNature nature = this; Job myJob = new Job("Pydev code completion: rebuilding modules") { @SuppressWarnings("unchecked") protected IStatus run(IProgressMonitor monitorArg) { JobProgressComunicator jobProgressComunicator = new JobProgressComunicator(monitorArg, "Rebuilding modules", IProgressMonitor.UNKNOWN, this); try { ICodeCompletionASTManager tempAstManager = astManager; if (tempAstManager == null) { tempAstManager = new ASTManager(); } synchronized(tempAstManager){ astManager = tempAstManager; tempAstManager.setProject(getProject(), false); //it is a new manager, so, remove all deltas //begins task automatically tempAstManager.changePythonPath(paths, project, jobProgressComunicator); saveAstManager(); List<IInterpreterObserver> participants = ExtensionHelper.getParticipants(ExtensionHelper.PYDEV_INTERPRETER_OBSERVER); for (IInterpreterObserver observer : participants) { try { //let's keep it safe observer.notifyProjectPythonpathRestored(nature, jobProgressComunicator); } catch (Exception e) { PydevPlugin.log(e); } } } } catch (Exception e) { PydevPlugin.log(e); } //end task jobProgressComunicator.done(); return Status.OK_STATUS; } }; myJob.schedule(); } /** * @return Returns the completionsCache. */ public ICodeCompletionASTManager getAstManager() { return astManager; } public void setAstManager(ICodeCompletionASTManager astManager){ this.astManager = astManager; } public IPythonPathNature getPythonPathNature() { return pythonPathNature; } public static IPythonPathNature getPythonPathNature(IProject project) { PythonNature pythonNature = getPythonNature(project); if(pythonNature != null){ return pythonNature.pythonPathNature; } return null; } /** * @param project the project we want to know about (if it is null, null is returned) * @return the python nature for a project (or null if it does not exist for the project) */ public static PythonNature getPythonNature(IProject project) { if(project != null){ try { if(project.hasNature(PYTHON_NATURE_ID)){ IProjectNature n = project.getNature(PYTHON_NATURE_ID); if(n instanceof PythonNature){ return (PythonNature) n; } } } catch (CoreException e) { PydevPlugin.log(e); } } return null; } /** * @return the python version for the project * @throws CoreException */ public String getVersion() throws CoreException { if(project != null){ String persistentProperty = project.getPersistentProperty(PYTHON_PROJECT_VERSION); if(persistentProperty == null){ //there is no such property set (let's set it to the default String defaultVersion = getDefaultVersion(); setVersion(defaultVersion); persistentProperty = defaultVersion; } return persistentProperty; } return null; } /** * set the project version given the constants provided * @throws CoreException */ public void setVersion(String version) throws CoreException{ if(project != null){ project.setPersistentProperty(PYTHON_PROJECT_VERSION, version); } } public String getDefaultVersion(){ return PYTHON_VERSION_2_4; } public boolean isJython() throws CoreException { return getVersion().equals(JYTHON_VERSION_2_1); } public boolean isPython() throws CoreException { return !isJython(); } public boolean acceptsDecorators() throws CoreException { return getVersion().equals(PYTHON_VERSION_2_4); } public void saveAstManager() { synchronized(astManager){ REF.writeToFile(astManager, getAstOutputFile()); } } public int getRelatedId() throws CoreException { return getRelatedId(this); } public static int getRelatedId(IPythonNature nature) throws CoreException { if(nature.isPython()){ return PYTHON_RELATED; }else if(nature.isJython()){ return JYTHON_RELATED; } throw new RuntimeException("Unable to get the id to which this nature is related"); } /** * @param resource the resource we want to get the name from * @return the name of the module in the environment */ public static String getModuleNameForResource(IResource resource) { String moduleName = null; PythonNature nature = getPythonNature(resource.getProject()); if(nature != null){ String file = PydevPlugin.getIResourceOSString(resource); ICodeCompletionASTManager astManager = nature.getAstManager(); if(astManager != null){ moduleName = astManager.getModulesManager().resolveModule(file); } } return moduleName; } /** * @param resource the resource we want info on * @return whether the passed resource is in the pythonpath or not (it must be in a source folder for that). */ public static boolean isResourceInPythonpath(IResource resource) { return getModuleNameForResource(resource) != null; } public String resolveModule(File file) { String moduleName = null; if(astManager != null){ moduleName = astManager.getModulesManager().resolveModule(REF.getFileAbsolutePath(file)); } return moduleName; } public static String[] getStrAsStrItems(String str){ return str.split("\\|"); } }
org.python.pydev/src/org/python/pydev/plugin/nature/PythonNature.java
/* * License: Common Public License v1.0 * Created on Mar 11, 2004 * * @author Fabio Zadrozny * @author atotic */ package org.python.pydev.plugin.nature; import java.io.File; import java.util.List; import org.eclipse.core.resources.ICommand; import org.eclipse.core.resources.IFile; import org.eclipse.core.resources.IProject; import org.eclipse.core.resources.IProjectDescription; import org.eclipse.core.resources.IProjectNature; import org.eclipse.core.resources.IResource; import org.eclipse.core.runtime.CoreException; import org.eclipse.core.runtime.IPath; import org.eclipse.core.runtime.IProgressMonitor; import org.eclipse.core.runtime.IStatus; import org.eclipse.core.runtime.NullProgressMonitor; import org.eclipse.core.runtime.QualifiedName; import org.eclipse.core.runtime.Status; import org.eclipse.core.runtime.jobs.Job; import org.eclipse.ui.IEditorInput; import org.eclipse.ui.part.FileEditorInput; import org.python.pydev.builder.PyDevBuilderPrefPage; import org.python.pydev.core.ExtensionHelper; import org.python.pydev.core.ICodeCompletionASTManager; import org.python.pydev.core.IPythonNature; import org.python.pydev.core.IPythonPathNature; import org.python.pydev.core.REF; import org.python.pydev.editor.codecompletion.revisited.ASTManager; import org.python.pydev.plugin.PydevPlugin; import org.python.pydev.ui.interpreters.IInterpreterObserver; import org.python.pydev.utils.JobProgressComunicator; /** * PythonNature is currently used as a marker class. * * When python nature is present, project gets extra properties. Project gets assigned python nature when: - a python file is edited - a * python project wizard is created * * */ public class PythonNature implements IPythonNature { /** * This is the nature ID */ public static final String PYTHON_NATURE_ID = "org.python.pydev.pythonNature"; /** * This is the nature name */ public static final String PYTHON_NATURE_NAME = "pythonNature"; /** * Builder id for pydev (code completion todo and others) */ public static final String BUILDER_ID = "org.python.pydev.PyDevBuilder"; /** * constant that stores the name of the python version we are using for the project with this nature */ private static final QualifiedName PYTHON_PROJECT_VERSION = new QualifiedName(PydevPlugin.getPluginID(), "PYTHON_PROJECT_VERSION"); /** * Project associated with this nature. */ private IProject project; /** * This is the completions cache for the nature represented by this object (it is associated with a project). */ private ICodeCompletionASTManager astManager; /** * We have to know if it has already been initialized. */ private boolean initialized; /** * Manages pythonpath things */ private IPythonPathNature pythonPathNature = new PythonPathNature(); /** * This method is called only when the project has the nature added.. * * @see org.eclipse.core.resources.IProjectNature#configure() */ public void configure() throws CoreException { } /** * @see org.eclipse.core.resources.IProjectNature#deconfigure() */ public void deconfigure() throws CoreException { } /** * Returns the project * * @see org.eclipse.core.resources.IProjectNature#getProject() */ public IProject getProject() { return project; } /** * Sets this nature's project - called from the eclipse platform. * * @see org.eclipse.core.resources.IProjectNature#setProject(org.eclipse.core.resources.IProject) */ public void setProject(IProject project) { this.project = project; this.pythonPathNature.setProject(project); } public static synchronized IPythonNature addNature(IEditorInput element) { if(element instanceof FileEditorInput){ IFile file = (IFile)((FileEditorInput)element).getAdapter(IFile.class); if (file != null){ try { return PythonNature.addNature(file.getProject(), null); } catch (CoreException e) { PydevPlugin.log(e); } } } return null; } /** * Utility routine to add PythonNature to the project * @return */ public static synchronized IPythonNature addNature(IProject project, IProgressMonitor monitor) throws CoreException { if (project == null) { return null; } if(monitor == null){ monitor = new NullProgressMonitor(); } IProjectDescription desc = project.getDescription(); //only add the nature if it still hasn't been added. if (project.hasNature(PYTHON_NATURE_ID) == false) { String[] natures = desc.getNatureIds(); String[] newNatures = new String[natures.length + 1]; System.arraycopy(natures, 0, newNatures, 0, natures.length); newNatures[natures.length] = PYTHON_NATURE_ID; desc.setNatureIds(newNatures); project.setDescription(desc, monitor); } //add the builder. It is used for pylint, pychecker, code completion, etc. ICommand[] commands = desc.getBuildSpec(); //now, add the builder if it still hasn't been added. if (hasBuilder(commands) == false && PyDevBuilderPrefPage.usePydevBuilders()) { ICommand command = desc.newCommand(); command.setBuilderName(BUILDER_ID); ICommand[] newCommands = new ICommand[commands.length + 1]; System.arraycopy(commands, 0, newCommands, 1, commands.length); newCommands[0] = command; desc.setBuildSpec(newCommands); project.setDescription(desc, monitor); } IProjectNature n = project.getNature(PYTHON_NATURE_ID); if (n instanceof PythonNature) { PythonNature nature = (PythonNature) n; //call initialize always - let it do the control. nature.init(); return nature; } return null; } /** * Utility to know if the pydev builder is in one of the commands passed. * * @param commands */ private static boolean hasBuilder(ICommand[] commands) { for (int i = 0; i < commands.length; i++) { if (commands[i].getBuilderName().equals(BUILDER_ID)) { return true; } } return false; } /** * Initializes the python nature if it still has not been for this session. * * Actions includes restoring the dump from the code completion cache */ private void init() { final PythonNature nature = this; if (initialized == false) { initialized = true; Job codeCompletionLoadJob = new Job("Pydev code completion") { @SuppressWarnings("unchecked") protected IStatus run(IProgressMonitor monitorArg) { //begins task automatically JobProgressComunicator jobProgressComunicator = new JobProgressComunicator(monitorArg, "Pydev restoring cache info...", IProgressMonitor.UNKNOWN, this); astManager = (ICodeCompletionASTManager) ASTManager.loadFromFile(getAstOutputFile()); //errors can happen when restoring it if(astManager == null){ try { String pythonPathStr = pythonPathNature.getOnlyProjectPythonPathStr(); rebuildPath(pythonPathStr); } catch (Exception e) { PydevPlugin.log(e); } }else{ synchronized(astManager){ astManager.setProject(getProject(), true); // this is the project related to it, restore the deltas (we may have some crash) List<IInterpreterObserver> participants = ExtensionHelper.getParticipants(ExtensionHelper.PYDEV_INTERPRETER_OBSERVER); for (IInterpreterObserver observer : participants) { try { observer.notifyNatureRecreated(nature, jobProgressComunicator); } catch (Exception e) { //let's not fail because of other plugins PydevPlugin.log(e); } } } } jobProgressComunicator.done(); return Status.OK_STATUS; } }; codeCompletionLoadJob.schedule(); } } /** * Returns the directory that should store completions. * * @param p * @return */ public static File getCompletionsCacheDir(IProject p) { IPath location = p.getWorkingLocation(PydevPlugin.getPluginID()); IPath path = location; File file = new File(path.toOSString()); return file; } public File getCompletionsCacheDir() { return getCompletionsCacheDir(getProject()); } /** * @param dir: parent directory where file should be. * @return the file where the python path helper should be saved. */ private File getAstOutputFile() { return new File(getCompletionsCacheDir(), "asthelper.completions"); } /** * This method is called whenever the pythonpath for the project with this nature is changed. */ public void rebuildPath(final String paths) { final PythonNature nature = this; Job myJob = new Job("Pydev code completion: rebuilding modules") { @SuppressWarnings("unchecked") protected IStatus run(IProgressMonitor monitorArg) { JobProgressComunicator jobProgressComunicator = new JobProgressComunicator(monitorArg, "Rebuilding modules", IProgressMonitor.UNKNOWN, this); try { ICodeCompletionASTManager tempAstManager = astManager; if (tempAstManager == null) { tempAstManager = new ASTManager(); } synchronized(tempAstManager){ tempAstManager.setProject(getProject(), false); //it is a new manager, so, remove all deltas //begins task automatically tempAstManager.changePythonPath(paths, project, jobProgressComunicator); astManager = tempAstManager; saveAstManager(); List<IInterpreterObserver> participants = ExtensionHelper.getParticipants(ExtensionHelper.PYDEV_INTERPRETER_OBSERVER); for (IInterpreterObserver observer : participants) { try { //let's keep it safe observer.notifyProjectPythonpathRestored(nature, jobProgressComunicator); } catch (Exception e) { PydevPlugin.log(e); } } } } catch (Exception e) { PydevPlugin.log(e); } //end task jobProgressComunicator.done(); return Status.OK_STATUS; } }; myJob.schedule(); } /** * @return Returns the completionsCache. */ public ICodeCompletionASTManager getAstManager() { return astManager; } public void setAstManager(ICodeCompletionASTManager astManager){ this.astManager = astManager; } public IPythonPathNature getPythonPathNature() { return pythonPathNature; } public static IPythonPathNature getPythonPathNature(IProject project) { PythonNature pythonNature = getPythonNature(project); if(pythonNature != null){ return pythonNature.pythonPathNature; } return null; } /** * @param project the project we want to know about (if it is null, null is returned) * @return the python nature for a project (or null if it does not exist for the project) */ public static PythonNature getPythonNature(IProject project) { if(project != null){ try { if(project.hasNature(PYTHON_NATURE_ID)){ IProjectNature n = project.getNature(PYTHON_NATURE_ID); if(n instanceof PythonNature){ return (PythonNature) n; } } } catch (CoreException e) { PydevPlugin.log(e); } } return null; } /** * @return the python version for the project * @throws CoreException */ public String getVersion() throws CoreException { if(project != null){ String persistentProperty = project.getPersistentProperty(PYTHON_PROJECT_VERSION); if(persistentProperty == null){ //there is no such property set (let's set it to the default String defaultVersion = getDefaultVersion(); setVersion(defaultVersion); persistentProperty = defaultVersion; } return persistentProperty; } return null; } /** * set the project version given the constants provided * @throws CoreException */ public void setVersion(String version) throws CoreException{ if(project != null){ project.setPersistentProperty(PYTHON_PROJECT_VERSION, version); } } public String getDefaultVersion(){ return PYTHON_VERSION_2_4; } public boolean isJython() throws CoreException { return getVersion().equals(JYTHON_VERSION_2_1); } public boolean isPython() throws CoreException { return !isJython(); } public boolean acceptsDecorators() throws CoreException { return getVersion().equals(PYTHON_VERSION_2_4); } public void saveAstManager() { synchronized(astManager){ REF.writeToFile(astManager, getAstOutputFile()); } } public int getRelatedId() throws CoreException { return getRelatedId(this); } public static int getRelatedId(IPythonNature nature) throws CoreException { if(nature.isPython()){ return PYTHON_RELATED; }else if(nature.isJython()){ return JYTHON_RELATED; } throw new RuntimeException("Unable to get the id to which this nature is related"); } /** * @param resource the resource we want to get the name from * @return the name of the module in the environment */ public static String getModuleNameForResource(IResource resource) { String moduleName = null; PythonNature nature = getPythonNature(resource.getProject()); if(nature != null){ String file = PydevPlugin.getIResourceOSString(resource); ICodeCompletionASTManager astManager = nature.getAstManager(); if(astManager != null){ moduleName = astManager.getModulesManager().resolveModule(file); } } return moduleName; } /** * @param resource the resource we want info on * @return whether the passed resource is in the pythonpath or not (it must be in a source folder for that). */ public static boolean isResourceInPythonpath(IResource resource) { return getModuleNameForResource(resource) != null; } public String resolveModule(File file) { String moduleName = null; if(astManager != null){ moduleName = astManager.getModulesManager().resolveModule(REF.getFileAbsolutePath(file)); } return moduleName; } public static String[] getStrAsStrItems(String str){ return str.split("\\|"); } }
*** empty log message *** git-svn-id: cdbd3c3453b226d8644b39c93ea790e37ea3ca1b@877 7f4d9e04-a92a-ab41-bea9-970b690ef4a7
org.python.pydev/src/org/python/pydev/plugin/nature/PythonNature.java
*** empty log message ***
<ide><path>rg.python.pydev/src/org/python/pydev/plugin/nature/PythonNature.java <ide> tempAstManager = new ASTManager(); <ide> } <ide> synchronized(tempAstManager){ <add> astManager = tempAstManager; <ide> tempAstManager.setProject(getProject(), false); //it is a new manager, so, remove all deltas <ide> <ide> //begins task automatically <ide> tempAstManager.changePythonPath(paths, project, jobProgressComunicator); <del> astManager = tempAstManager; <ide> saveAstManager(); <ide> <ide> List<IInterpreterObserver> participants = ExtensionHelper.getParticipants(ExtensionHelper.PYDEV_INTERPRETER_OBSERVER);
Java
apache-2.0
d5f5fa61247b9668e939fcb1f6bb61af20a5c91d
0
dimagi/commcare-android,dimagi/commcare-android,dimagi/commcare-android,dimagi/commcare-android,dimagi/commcare-android,dimagi/commcare-android
package org.commcare.views.widgets; import android.content.Context; import android.content.Intent; import android.util.Log; import org.commcare.android.javarosa.AndroidXFormExtensions; import org.commcare.android.javarosa.IntentCallout; import org.commcare.logic.PendingCalloutInterface; import org.javarosa.core.model.Constants; import org.javarosa.core.model.FormDef; import org.javarosa.core.model.QuestionDataExtension; import org.javarosa.core.model.condition.EvaluationContext; import org.javarosa.core.services.locale.Localization; import org.javarosa.form.api.FormEntryPrompt; /** * Convenience class that handles creation of widgets. * * @author Carl Hartung ([email protected]) */ public class WidgetFactory { private final FormDef formDef; private final PendingCalloutInterface pendingCalloutInterface; public WidgetFactory(FormDef formDef, PendingCalloutInterface pendingCalloutInterface) { this.formDef = formDef; this.pendingCalloutInterface = pendingCalloutInterface; } /** * Returns the appropriate QuestionWidget for the given FormEntryPrompt. * * @param fep prompt element to be rendered * @param context Android context */ public QuestionWidget createWidgetFromPrompt(FormEntryPrompt fep, Context context) { QuestionWidget questionWidget; String appearance = fep.getAppearanceHint(); switch (fep.getControlType()) { case Constants.CONTROL_INPUT: if (appearance != null && appearance.startsWith("intent:")) { questionWidget = buildIntentWidget(appearance, fep, context); break; } case Constants.CONTROL_SECRET: questionWidget = buildBasicWidget(appearance, fep, context); break; case Constants.CONTROL_IMAGE_CHOOSE: if (appearance != null && appearance.equals("signature")) { questionWidget = new SignatureWidget(context, fep, pendingCalloutInterface); } else { questionWidget = new ImageWidget(context, fep, pendingCalloutInterface); } break; case Constants.CONTROL_AUDIO_CAPTURE: if (appearance != null && appearance.contains("prototype")) { questionWidget = new CommCareAudioWidget(context, fep, pendingCalloutInterface); } else { questionWidget = new AudioWidget(context, fep, pendingCalloutInterface); } break; case Constants.CONTROL_VIDEO_CAPTURE: questionWidget = new VideoWidget(context, fep, pendingCalloutInterface); break; case Constants.CONTROL_SELECT_ONE: questionWidget = buildSelectOne(appearance, fep, context); break; case Constants.CONTROL_SELECT_MULTI: questionWidget = buildSelectMulti(appearance, fep, context); break; case Constants.CONTROL_TRIGGER: questionWidget = new TriggerWidget(context, fep, appearance); break; default: questionWidget = new StringWidget(context, fep, false); break; } // Apply all of the QuestionDataExtensions registered with this widget's associated // QuestionDef to the widget for (QuestionDataExtension extension : fep.getQuestion().getExtensions()) { questionWidget.applyExtension(extension); } return questionWidget; } private QuestionWidget buildBasicWidget(String appearance, FormEntryPrompt fep, Context context) { switch (fep.getDataType()) { case Constants.DATATYPE_DATE_TIME: return new DateTimeWidget(context, fep); case Constants.DATATYPE_DATE: if (appearance != null && appearance.toLowerCase().equals("ethiopian")) { return new EthiopianDateWidget(context, fep); } else if (appearance != null && appearance.toLowerCase().equals("nepali")) { return new NepaliDateWidget(context, fep); } else if(appearance != null && appearance.toLowerCase().contains("gregorian")){ return new DatePrototypeFactory().getWidget(context, fep, appearance.toLowerCase()); } else { return new DateWidget(context, fep); } case Constants.DATATYPE_TIME: return new TimeWidget(context, fep); case Constants.DATATYPE_LONG: return new IntegerWidget(context, fep, fep.getControlType() == Constants.CONTROL_SECRET, 2); case Constants.DATATYPE_DECIMAL: return new DecimalWidget(context, fep, fep.getControlType() == Constants.CONTROL_SECRET); case Constants.DATATYPE_INTEGER: return new IntegerWidget(context, fep, fep.getControlType() == Constants.CONTROL_SECRET, 1); case Constants.DATATYPE_GEOPOINT: return new GeoPointWidget(context, fep, pendingCalloutInterface); case Constants.DATATYPE_BARCODE: IntentCallout mIntentCallout = new IntentCallout("com.google.zxing.client.android.SCAN", null, null, null, null, null, Localization.get("intent.barcode.get"), Localization.get("intent.barcode.update"), appearance); Intent mIntent = mIntentCallout.generate(formDef.getEvaluationContext()); return new BarcodeWidget(context, fep, mIntent, mIntentCallout, pendingCalloutInterface); case Constants.DATATYPE_TEXT: if (appearance != null && (appearance.equalsIgnoreCase("numbers") || appearance.equalsIgnoreCase("numeric"))) { return new StringNumberWidget(context, fep, fep.getControlType() == Constants.CONTROL_SECRET); } else { return new StringWidget(context, fep, fep.getControlType() == Constants.CONTROL_SECRET); } default: return new StringWidget(context, fep, fep.getControlType() == Constants.CONTROL_SECRET); } } private IntentWidget buildIntentWidget(String appearance, FormEntryPrompt fep, Context context) { String intentId = appearance.substring("intent:".length()); IntentCallout ic = formDef.getExtension(AndroidXFormExtensions.class).getIntent(intentId, formDef); //Hm, so what do we do if no callout is found? Error? For now, fail fast if (ic == null) { throw new RuntimeException("No intent callout could be found for requested id " + intentId + "!"); } //NOTE: No path specific stuff for now Intent i = ic.generate(new EvaluationContext(formDef.getEvaluationContext(),fep.getIndex().getReference())); return new IntentWidget(context, fep, i, ic, pendingCalloutInterface); } private static QuestionWidget buildSelectOne(String appearance, FormEntryPrompt fep, Context context) { if (appearance != null && appearance.contains("compact")) { int numColumns = -1; try { numColumns = Integer.parseInt(appearance.substring(appearance.indexOf('-') + 1)); } catch (Exception e) { // Do nothing, leave numColumns as -1 Log.e("WidgetFactory", "Exception parsing numColumns"); } if (appearance.contains("quick")) { return new GridWidget(context, fep, numColumns, true); } else { return new GridWidget(context, fep, numColumns, false); } } else if (appearance != null && appearance.equals("minimal")) { return new SpinnerWidget(context, fep); } else if (appearance != null && appearance.equals("quick")) { return new SelectOneAutoAdvanceWidget(context, fep); } else if (appearance != null && appearance.equals("list")) { return new ListWidget(context, fep, true); } else if (appearance != null && appearance.equals("list-nolabel")) { return new ListWidget(context, fep, false); } else if (appearance != null && appearance.equals("label")) { return new LabelWidget(context, fep); } else { return new SelectOneWidget(context, fep); } } private static QuestionWidget buildSelectMulti(String appearance, FormEntryPrompt fep, Context context) { if (appearance != null && appearance.contains("compact")) { int numColumns = -1; try { numColumns = Integer.parseInt(appearance.substring(appearance.indexOf('-') + 1)); } catch (Exception e) { // Do nothing, leave numColumns as -1 Log.e("WidgetFactory", "Exception parsing numColumns"); } return new GridMultiWidget(context, fep, numColumns); } else if (appearance != null && appearance.equals("minimal")) { return new SpinnerMultiWidget(context, fep); } else if (appearance != null && appearance.equals("list")) { return new ListMultiWidget(context, fep, true); } else if (appearance != null && appearance.equals("list-nolabel")) { return new ListMultiWidget(context, fep, false); } else if (appearance != null && appearance.equals("label")) { return new LabelWidget(context, fep); } else { return new SelectMultiWidget(context, fep); } } }
app/src/org/commcare/views/widgets/WidgetFactory.java
package org.commcare.views.widgets; import android.content.Context; import android.content.Intent; import android.util.Log; import org.commcare.android.javarosa.AndroidXFormExtensions; import org.commcare.android.javarosa.IntentCallout; import org.commcare.logic.PendingCalloutInterface; import org.javarosa.core.model.Constants; import org.javarosa.core.model.FormDef; import org.javarosa.core.model.QuestionDataExtension; import org.javarosa.core.model.condition.EvaluationContext; import org.javarosa.core.services.locale.Localization; import org.javarosa.form.api.FormEntryPrompt; /** * Convenience class that handles creation of widgets. * * @author Carl Hartung ([email protected]) */ public class WidgetFactory { private final FormDef formDef; private final PendingCalloutInterface pendingCalloutInterface; public WidgetFactory(FormDef formDef, PendingCalloutInterface pendingCalloutInterface) { this.formDef = formDef; this.pendingCalloutInterface = pendingCalloutInterface; } /** * Returns the appropriate QuestionWidget for the given FormEntryPrompt. * * @param fep prompt element to be rendered * @param context Android context */ public QuestionWidget createWidgetFromPrompt(FormEntryPrompt fep, Context context) { QuestionWidget questionWidget; String appearance = fep.getAppearanceHint(); switch (fep.getControlType()) { case Constants.CONTROL_INPUT: if (appearance != null && appearance.startsWith("intent:")) { questionWidget = buildIntentWidget(appearance, fep, context); break; } case Constants.CONTROL_SECRET: questionWidget = buildBasicWidget(appearance, fep, context); break; case Constants.CONTROL_IMAGE_CHOOSE: if (appearance != null && appearance.equals("signature")) { questionWidget = new SignatureWidget(context, fep, pendingCalloutInterface); } else { questionWidget = new ImageWidget(context, fep, pendingCalloutInterface); } break; case Constants.CONTROL_AUDIO_CAPTURE: if(appearance != null){ questionWidget = new CommCareAudioWidget(context, fep, pendingCalloutInterface); } else{ questionWidget = new AudioWidget(context, fep, pendingCalloutInterface); } break; case Constants.CONTROL_VIDEO_CAPTURE: questionWidget = new VideoWidget(context, fep, pendingCalloutInterface); break; case Constants.CONTROL_SELECT_ONE: questionWidget = buildSelectOne(appearance, fep, context); break; case Constants.CONTROL_SELECT_MULTI: questionWidget = buildSelectMulti(appearance, fep, context); break; case Constants.CONTROL_TRIGGER: questionWidget = new TriggerWidget(context, fep, appearance); break; default: questionWidget = new StringWidget(context, fep, false); break; } // Apply all of the QuestionDataExtensions registered with this widget's associated // QuestionDef to the widget for (QuestionDataExtension extension : fep.getQuestion().getExtensions()) { questionWidget.applyExtension(extension); } return questionWidget; } private QuestionWidget buildBasicWidget(String appearance, FormEntryPrompt fep, Context context) { switch (fep.getDataType()) { case Constants.DATATYPE_DATE_TIME: return new DateTimeWidget(context, fep); case Constants.DATATYPE_DATE: if (appearance != null && appearance.toLowerCase().equals("ethiopian")) { return new EthiopianDateWidget(context, fep); } else if (appearance != null && appearance.toLowerCase().equals("nepali")) { return new NepaliDateWidget(context, fep); } else if(appearance != null && appearance.toLowerCase().contains("gregorian")){ return new DatePrototypeFactory().getWidget(context, fep, appearance.toLowerCase()); } else { return new DateWidget(context, fep); } case Constants.DATATYPE_TIME: return new TimeWidget(context, fep); case Constants.DATATYPE_LONG: return new IntegerWidget(context, fep, fep.getControlType() == Constants.CONTROL_SECRET, 2); case Constants.DATATYPE_DECIMAL: return new DecimalWidget(context, fep, fep.getControlType() == Constants.CONTROL_SECRET); case Constants.DATATYPE_INTEGER: return new IntegerWidget(context, fep, fep.getControlType() == Constants.CONTROL_SECRET, 1); case Constants.DATATYPE_GEOPOINT: return new GeoPointWidget(context, fep, pendingCalloutInterface); case Constants.DATATYPE_BARCODE: IntentCallout mIntentCallout = new IntentCallout("com.google.zxing.client.android.SCAN", null, null, null, null, null, Localization.get("intent.barcode.get"), Localization.get("intent.barcode.update"), appearance); Intent mIntent = mIntentCallout.generate(formDef.getEvaluationContext()); return new BarcodeWidget(context, fep, mIntent, mIntentCallout, pendingCalloutInterface); case Constants.DATATYPE_TEXT: if (appearance != null && (appearance.equalsIgnoreCase("numbers") || appearance.equalsIgnoreCase("numeric"))) { return new StringNumberWidget(context, fep, fep.getControlType() == Constants.CONTROL_SECRET); } else { return new StringWidget(context, fep, fep.getControlType() == Constants.CONTROL_SECRET); } default: return new StringWidget(context, fep, fep.getControlType() == Constants.CONTROL_SECRET); } } private IntentWidget buildIntentWidget(String appearance, FormEntryPrompt fep, Context context) { String intentId = appearance.substring("intent:".length()); IntentCallout ic = formDef.getExtension(AndroidXFormExtensions.class).getIntent(intentId, formDef); //Hm, so what do we do if no callout is found? Error? For now, fail fast if (ic == null) { throw new RuntimeException("No intent callout could be found for requested id " + intentId + "!"); } //NOTE: No path specific stuff for now Intent i = ic.generate(new EvaluationContext(formDef.getEvaluationContext(),fep.getIndex().getReference())); return new IntentWidget(context, fep, i, ic, pendingCalloutInterface); } private static QuestionWidget buildSelectOne(String appearance, FormEntryPrompt fep, Context context) { if (appearance != null && appearance.contains("compact")) { int numColumns = -1; try { numColumns = Integer.parseInt(appearance.substring(appearance.indexOf('-') + 1)); } catch (Exception e) { // Do nothing, leave numColumns as -1 Log.e("WidgetFactory", "Exception parsing numColumns"); } if (appearance.contains("quick")) { return new GridWidget(context, fep, numColumns, true); } else { return new GridWidget(context, fep, numColumns, false); } } else if (appearance != null && appearance.equals("minimal")) { return new SpinnerWidget(context, fep); } else if (appearance != null && appearance.equals("quick")) { return new SelectOneAutoAdvanceWidget(context, fep); } else if (appearance != null && appearance.equals("list")) { return new ListWidget(context, fep, true); } else if (appearance != null && appearance.equals("list-nolabel")) { return new ListWidget(context, fep, false); } else if (appearance != null && appearance.equals("label")) { return new LabelWidget(context, fep); } else { return new SelectOneWidget(context, fep); } } private static QuestionWidget buildSelectMulti(String appearance, FormEntryPrompt fep, Context context) { if (appearance != null && appearance.contains("compact")) { int numColumns = -1; try { numColumns = Integer.parseInt(appearance.substring(appearance.indexOf('-') + 1)); } catch (Exception e) { // Do nothing, leave numColumns as -1 Log.e("WidgetFactory", "Exception parsing numColumns"); } return new GridMultiWidget(context, fep, numColumns); } else if (appearance != null && appearance.equals("minimal")) { return new SpinnerMultiWidget(context, fep); } else if (appearance != null && appearance.equals("list")) { return new ListMultiWidget(context, fep, true); } else if (appearance != null && appearance.equals("list-nolabel")) { return new ListMultiWidget(context, fep, false); } else if (appearance != null && appearance.equals("label")) { return new LabelWidget(context, fep); } else { return new SelectMultiWidget(context, fep); } } }
only use new audio widget w/ specific appr attr
app/src/org/commcare/views/widgets/WidgetFactory.java
only use new audio widget w/ specific appr attr
<ide><path>pp/src/org/commcare/views/widgets/WidgetFactory.java <ide> } <ide> break; <ide> case Constants.CONTROL_AUDIO_CAPTURE: <del> if(appearance != null){ <add> if (appearance != null && appearance.contains("prototype")) { <ide> questionWidget = new CommCareAudioWidget(context, fep, pendingCalloutInterface); <del> } <del> else{ <add> } else { <ide> questionWidget = new AudioWidget(context, fep, pendingCalloutInterface); <ide> } <ide> break;
Java
apache-2.0
446578991d37d650950215f660a8993daa7e9ab0
0
onepf/OPFPush
/* * Copyright 2012-2014 One Platform Foundation * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.onepf.opfpush; import android.app.AlarmManager; import android.app.PendingIntent; import android.content.BroadcastReceiver; import android.content.Context; import android.content.Intent; import android.os.Bundle; import android.os.Handler; import android.os.Looper; import android.support.annotation.IntDef; import android.support.annotation.NonNull; import android.support.annotation.Nullable; import android.text.TextUtils; import junit.framework.Assert; import org.onepf.opfpush.util.Utils; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.text.SimpleDateFormat; import java.util.Date; import java.util.List; import static org.onepf.opfpush.OPFPushLog.LOGD; import static org.onepf.opfpush.OPFPushLog.LOGI; import static org.onepf.opfpush.OPFPushLog.LOGW; /** * Main class for manage push providers. * For get instance of this class call {@link #getInstance(android.content.Context)}. * <p/> * Before do any operations with {@code OpenPushHelper} you must call {@link #init(Options)}. * <p/> * For start select provider for registerWithNext call {@link #register()}. * * @author Kirill Rozov * @since 04.09.2014 */ public class OPFPushHelper { /** * Use for {@code messagesCount} argument in * {@link ProviderCallback#onDeletedMessages(String, int)} when messages count is unknown. */ public static final int MESSAGES_COUNT_UNKNOWN = Integer.MIN_VALUE; static final int STATE_UNREGISTERED = 0; static final int STATE_REGISTERING = 1; static final int STATE_REGISTERED = 2; static final int STATE_UNREGISTERING = 3; @Retention(RetentionPolicy.SOURCE) @IntDef(value = { STATE_UNREGISTERED, STATE_UNREGISTERING, STATE_REGISTERING, STATE_REGISTERED }) @interface State { } @Nullable private static OPFPushHelper sInstance; @NonNull private final Context mAppContext; @Nullable private EventListener mListener; @Nullable private MessageListener mMessageListener; @Nullable private BroadcastReceiver mPackageReceiver; @Nullable private PushProvider mCurrentProvider; @Nullable private AlarmManager mAlarmManager; private Options mOptions; private final Object mRegistrationLock = new Object(); private final Object mInitLock = new Object(); private final ProviderCallback mProviderCallback = new ProviderCallback(); private final Settings mSettings; /** * <b>Use for test purposes only!!!</b> */ OPFPushHelper(@NonNull Context context) { mAppContext = context.getApplicationContext(); mSettings = new Settings(context); } /** * Get instance of {@code OpenPushHelper}. * * @param context The current context. * @return Instance of {@link OPFPushHelper}. */ public static OPFPushHelper getInstance(@NonNull Context context) { if (sInstance == null) { synchronized (OPFPushHelper.class) { if (sInstance == null) { sInstance = new OPFPushHelper(context); } } } return sInstance; } static OPFPushHelper newInstance(@NonNull Context context) { synchronized (OPFPushHelper.class) { sInstance = new OPFPushHelper(context); } return sInstance; } public ProviderCallback getProviderCallback() { checkInitDone(); return mProviderCallback; } /** * Is init done and you may work with {@code OpenPushHelper}. * * @return True if init is done, else - false. */ public boolean isInitDone() { synchronized (mInitLock) { return mOptions != null; } } /** * Check can you send message in current time. This method return only if provider is registered * and it is implement {@link SenderPushProvider} interface. */ public boolean canSendMessages() { return mCurrentProvider instanceof SenderPushProvider; } /** * Send message to server. * * @param message Message to send. * @throws OPFPushException When try send message when any provider isn't registered or it isn't * implement {@link SenderPushProvider} interface. */ public void sendMessage(@NonNull Message message) { synchronized (mRegistrationLock) { if (mCurrentProvider instanceof SenderPushProvider) { ((SenderPushProvider) mCurrentProvider).send(message); } else if (isRegistered()) { throw new OPFPushException( "Current provider '%s' not support send messages.", mCurrentProvider); } else { throw new OPFPushException("Provider not registered."); } } } /** * Is push registered. * * @return True if push registered, else - false. */ public boolean isRegistered() { final int state = mSettings.getState(); return state == STATE_REGISTERED || state == STATE_UNREGISTERING; } public boolean isUnregistered() { return mSettings.getState() == STATE_UNREGISTERED; } public boolean isRegistering() { return mSettings.getState() == STATE_REGISTERING; } public boolean isUnregistering() { return mSettings.getState() == STATE_UNREGISTERING; } private void checkInitDone() { if (!isInitDone()) { throw new OPFPushException("Before work with OpenPushHelper call init() first."); } } /** * Init {@code OpenPushHelper}. You must call this method before do any operation. * * @param options Instance of {@code Options}. */ public void init(@NonNull Options options) { if (isInitDone()) { throw new OPFPushException("You can init OpenPushHelper only one time."); } if (mOptions == null) { synchronized (mInitLock) { if (mOptions == null) { mOptions = options; } } } initLastProvider(); LOGI("Init done."); } private void initLastProvider() { synchronized (mRegistrationLock) { final PushProvider lastProvider = getLastProvider(); if (lastProvider == null) { LOGI("No last provider."); return; } LOGI("Try restore last provider '%s'.", lastProvider); if (lastProvider.isAvailable()) { if (lastProvider.isRegistered()) { LOGI("Last provider running."); mCurrentProvider = lastProvider; mSettings.saveState(STATE_REGISTERED); } else { LOGI("Last provider need register."); if (!register(lastProvider)) { mSettings.saveLastProvider(null); } } } else { mSettings.saveLastProvider(null); mSettings.saveState(STATE_UNREGISTERED); onProviderUnavailable(lastProvider); } } } /** * Check if at least one provider available. */ public boolean hasAvailableProvider() { for (PushProvider provider : mOptions.getProviders()) { if (provider.isAvailable()) { return true; } } return false; } public void setListener(@Nullable EventListener l) { mListener = l == null ? null : new EventListenerWrapper(l); } public void setMessageListener(@Nullable MessageListener l) { mMessageListener = l; } void restartRegisterOnBoot() { checkInitDone(); mSettings.clear(); register(); } /** * Start select push provider and registered it. * <p/> * If you want to modify current registered provider, you must call unregister() first. * <p/> * * @throws OPFPushException When try call this method while init not done, * unregistration process in progress or already registered. */ public void register() { checkInitDone(); synchronized (mRegistrationLock) { switch (mSettings.getState()) { case STATE_REGISTERING: break; case STATE_UNREGISTERED: mSettings.saveState(STATE_REGISTERING); if (mOptions.isSelectSystemPreferred() && registerSystemPreferredProvider()) { return; } registerNextProvider(null); break; case STATE_UNREGISTERING: throw new OPFPushException("Can't register while unregistration is running."); case STATE_REGISTERED: throw new OPFPushException("Attempt to register twice!"); } } } private boolean registerSystemPreferredProvider() { for (PushProvider provider : mOptions.getProviders()) { if (PackageUtils.isSystemApp(mAppContext, provider.getHostAppPackage()) && register(provider)) { return true; } } return false; } /** * Register first available provider. Iterate all provider from the next provider after * {@code lastProvider} param. * * @param lastProvider Last provider what check to registerWithNext or null if has no. * @return True if find provider that can try to registerWithNext, otherwise false. */ private boolean registerNextProvider(@Nullable PushProvider lastProvider) { int nextProviderIndex = 0; final List<PushProvider> providers = mOptions.getProviders(); if (lastProvider != null) { int lastProviderIndex = providers.indexOf(lastProvider); if (lastProviderIndex != -1) { nextProviderIndex = lastProviderIndex + 1; } } for (int providersCount = providers.size(); nextProviderIndex < providersCount; ++nextProviderIndex) { if (register(providers.get(nextProviderIndex))) { return true; } } mSettings.saveState(STATE_UNREGISTERED); LOGW("No more available providers."); if (mListener != null) { mListener.onNoAvailableProvider(); } return false; } boolean register(@NonNull String providerName) { return register(getProviderWithException(providerName)); } /** * Start register provider. * * @param provider Provider for registration. * @return If provider available and can start registration return true, otherwise - false. */ private boolean register(@NonNull PushProvider provider) { if (provider.isAvailable()) { if (Utils.isNetworkConnected(mAppContext)) { LOGD("Try register %s.", provider); provider.register(); } else { mProviderCallback.onRegistrationError( Result.error(provider.getName(), Error.SERVICE_NOT_AVAILABLE, Result.Type.REGISTRATION) ); } return true; } return false; } /** * Unregister the application. Calling unregister() stops any messages from the server. * This is a not blocking call. You should rarely (if ever) need to call this method. * Not only is it expensive in terms of resources, but it invalidates your registration ID, * which you should never change unnecessarily. * A better approach is to simply have your server stop sending messages. * Only use unregister if you want to change your sender ID. * * @throws OPFPushException When try call this method while init not done, * registration process in progress or registration not done. */ public void unregister() { checkInitDone(); synchronized (mRegistrationLock) { switch (mSettings.getState()) { case STATE_REGISTERED: Assert.assertNotNull(mCurrentProvider); mSettings.saveState(STATE_UNREGISTERING); unregisterPackageChangeReceiver(); mCurrentProvider.unregister(); break; case STATE_UNREGISTERING: break; case STATE_REGISTERING: throw new OPFPushException("Can't unregister when registration in progress.!"); case STATE_UNREGISTERED: throw new OPFPushException("Before to unregister you must register provider.!"); } } } private void unregisterPackageChangeReceiver() { if (mPackageReceiver != null) { mAppContext.unregisterReceiver(mPackageReceiver); mPackageReceiver = null; } } @Nullable public PushProvider getCurrentProvider() { return mCurrentProvider; } /** * Search provider by name in {@code options} and return in. * If {@code} doesn't contain provider with described name return null. * * @param providerName Name of provider for search. * @return Provider with described name or null if nothing have found. */ @Nullable private PushProvider getProvider(@NonNull String providerName) { for (PushProvider provider : mOptions.getProviders()) { if (providerName.equals(provider.getName())) { return provider; } } return null; } /** * Same that {@link #getProvider(String)} but if provider not found throw exception. * * @param providerName Name of provider for search. * @return Provider with name {@code providerName}. * @throws OPFPushException When {@code PushProvider} with name {@code providerName} not found. */ @NonNull private PushProvider getProviderWithException(@NonNull String providerName) { PushProvider provider = getProvider(providerName); if (provider == null) { throw new OPFPushException("Provider with name '%s' not found.", providerName); } return provider; } @Nullable private PushProvider getLastProvider() { String storedProviderName = mSettings.getLastProviderName(); if (!TextUtils.isEmpty(storedProviderName)) { PushProvider provider = getProvider(storedProviderName); if (provider != null) { return provider; } mSettings.saveLastProvider(null); } return null; } @Override public String toString() { return "OpenPushHelper{" + "options=" + mOptions + ", currentProvider=" + mCurrentProvider + ", initDone=" + isInitDone() + ", registered=" + isRegistered() + '}'; } void postRetryRegister(@NonNull String providerName) { Assert.assertNotNull(mOptions.getBackoff()); final long when = System.currentTimeMillis() + mOptions.getBackoff().getTryDelay(); LOGI("Post retry register provider '%s' at %s", providerName, SimpleDateFormat.getDateTimeInstance().format(new Date(when))); Intent intent = new Intent(mAppContext, RetryBroadcastReceiver.class); intent.setAction(Constants.ACTION_REGISTER); intent.putExtra(Constants.EXTRA_PROVIDER_NAME, providerName); if (mAlarmManager == null) { mAlarmManager = (AlarmManager) mAppContext.getSystemService(Context.ALARM_SERVICE); } if (mAlarmManager != null) { mAlarmManager.set( AlarmManager.RTC, when, PendingIntent.getBroadcast(mAppContext, 0, intent, 0) ); } } static boolean canHandleResult(@NonNull Result result, @State int state) { switch (result.getType()) { case UNKNOWN: return state == STATE_REGISTERING || state == STATE_UNREGISTERING; case REGISTRATION: return state == STATE_REGISTERING; case UNREGISTRATION: return state == STATE_UNREGISTERING; default: return false; } } /** * Call this method when device state changed and need retry registration. * May be call only when the helper in registered state. * * @throws OPFPushException When call this method when registration not done * or {@code providerName} isn't current registered provider. */ void onNeedRetryRegister() { Assert.assertNotNull(mCurrentProvider); LOGD("onNeedRetryRegister(providerName = %s).", mCurrentProvider); mSettings.clear(); mCurrentProvider.onRegistrationInvalid(); mSettings.saveState(STATE_REGISTERING); if (!register(mCurrentProvider)) { mSettings.saveState(STATE_UNREGISTERED); } } /** * Call this method when provider become unavailable. * * @param provider Provider that become unavailable. * @throws OPFPushException When call this method when registration not done * or {@code providerName} isn't current registered provider. */ void onProviderUnavailable(@NonNull PushProvider provider) { LOGD("onProviderUnavailable(provider = %s).", provider); if (mCurrentProvider != null && provider.equals(mCurrentProvider)) { mCurrentProvider = null; mSettings.saveState(STATE_UNREGISTERED); } provider.onUnavailable(); if (mListener != null) { mListener.onProviderBecameUnavailable(provider.getName()); } if (mOptions.isRecoverProvider()) { OPFPushHelper.this.register(); //Restart registration } } public class ProviderCallback { ProviderCallback() { } /** * Provider must call this method when new message received. * * @param providerName Name of provider from what message received. * @param extras Message extras. * @throws OPFPushException When call this method when registration not done * or {@code providerName} isn't current registered provider. */ public void onMessage(@NonNull String providerName, @Nullable Bundle extras) { checkProviderWorking(providerName); LOGD("onMessageReceive(providerName = %s).", providerName); if (mMessageListener != null) { mMessageListener.onMessageReceive(providerName, extras); } } private void checkProviderWorking(String providerName) { checkInitDone(); if (!isRegistered()) { throw new OPFPushException("Can't receive message when not registered."); } if (mCurrentProvider != null && !providerName.equalsIgnoreCase(mCurrentProvider.getName())) { throw new OPFPushException("Can't receive message from not registered provider. " + "Current provider '%s', message source ='%s'", mCurrentProvider.getName(), providerName); } } /** * Provider must call this method when new message deleted. * * @param providerName Name of provider from what message deleted. * @param messagesCount Deleted messages count. If messages count is unknown pass -1. * @throws OPFPushException When call this method when registration not done * or {@code providerName} isn't current registered provider. */ public void onDeletedMessages(@NonNull String providerName, int messagesCount) { checkProviderWorking(providerName); LOGD("onDeletedMessages(providerName = %s, messagesCount = %d).", providerName, messagesCount); if (mMessageListener != null) { mMessageListener.onDeletedMessages(providerName, messagesCount); } } /** * Call this method on new registration or unregistration result. * * @param result Registration or unregistration result. * @throws OPFPushException When result type can't be handle * in current state of {@code OpenPushHelper}. */ public void onResult(@NonNull Result result) { synchronized (mRegistrationLock) { final int state = mSettings.getState(); if (canHandleResult(result, state)) { switch (result.getType()) { case REGISTRATION: onRegistrationResult(result); return; case UNREGISTRATION: onUnregistrationResult(result); return; case UNKNOWN: switch (state) { case STATE_REGISTERING: onRegistrationResult(result); return; case STATE_UNREGISTERING: onUnregistrationResult(result); return; } throw new OPFPushException("Result not handled."); } } else { throw new IllegalStateException("Result can't be handle."); } } } private void onUnregistrationResult(@NonNull Result result) { if (result.isSuccess()) { LOGI("Successfully unregister provider '%s'.", result.getProviderName()); mSettings.clear(); mCurrentProvider = null; if (mListener != null) { Assert.assertNotNull(result.getRegistrationId()); mListener.onUnregistered(result.getProviderName(), result.getRegistrationId()); } } else if (mListener != null) { mSettings.saveState(STATE_REGISTERED); Assert.assertNotNull(result.getError()); LOGI("Error unregister provider '%s'.", result.getProviderName()); mListener.onUnregistrationError(result.getProviderName(), result.getError()); } } private void onRegistrationResult(@NonNull Result result) { if (result.isSuccess()) { onRegistrationSuccess(result); } else { onRegistrationError(result); } } private void onRegistrationError(@NonNull Result result) { Assert.assertNotNull(result.getError()); LOGI("Error register provider '%s'.", result.getProviderName()); PushProvider provider = getProviderWithException(result.getProviderName()); if (mListener != null) { mListener.onRegistrationError(provider.getName(), result.getError()); } final Backoff backoff = mOptions.getBackoff(); if (result.getError() == Error.SERVICE_NOT_AVAILABLE && backoff != null && backoff.hasTries()) { postRetryRegister(provider.getName()); } else { if (backoff != null) { backoff.reset(); } registerNextProvider(provider); } } private void onRegistrationSuccess(Result result) { final Backoff backoff = mOptions.getBackoff(); if (backoff != null) { backoff.reset(); } LOGI("Successfully register provider '%s'.", result.getProviderName()); LOGI("Register id '%s'.", result.getRegistrationId()); mSettings.saveState(STATE_REGISTERED); mSettings.saveLastAndroidId(android.provider.Settings.Secure.ANDROID_ID); mCurrentProvider = getProviderWithException(result.getProviderName()); mSettings.saveLastProvider(mCurrentProvider); Assert.assertNotNull(result.getRegistrationId()); if (mListener != null) { mListener.onRegistered(result.getProviderName(), result.getRegistrationId()); } mPackageReceiver = PackageUtils.registerPackageChangeReceiver(mAppContext, mCurrentProvider); } } /** * Wrapper for execute all method on main thread. * * @author Kirill Rozov * @since 24.09.14. */ private static class EventListenerWrapper implements EventListener { private static final Handler HANDLER = new Handler(Looper.getMainLooper()); private final EventListener mListener; EventListenerWrapper(EventListener listener) { mListener = listener; } @Override public void onRegistered(@NonNull final String providerName, @NonNull final String registrationId) { HANDLER.post(new Runnable() { @Override public void run() { mListener.onRegistered(providerName, registrationId); } }); } @Override public void onRegistrationError(@NonNull final String providerName, @NonNull final Error error) { HANDLER.post(new Runnable() { @Override public void run() { mListener.onRegistrationError(providerName, error); } }); } @Override public void onUnregistrationError(@NonNull final String providerName, @NonNull final Error error) { HANDLER.post(new Runnable() { @Override public void run() { mListener.onUnregistrationError(providerName, error); } }); } @Override public void onNoAvailableProvider() { HANDLER.post(new Runnable() { @Override public void run() { mListener.onNoAvailableProvider(); } }); } @Override public void onUnregistered(@NonNull final String providerName, @NonNull final String registrationId) { HANDLER.post(new Runnable() { @Override public void run() { mListener.onUnregistered(providerName, registrationId); } }); } @Override public void onProviderBecameUnavailable(@NonNull final String providerName) { HANDLER.post(new Runnable() { @Override public void run() { mListener.onProviderBecameUnavailable(providerName); } }); } } }
opfpush/src/main/java/org/onepf/opfpush/OPFPushHelper.java
/* * Copyright 2012-2014 One Platform Foundation * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.onepf.opfpush; import android.app.AlarmManager; import android.app.PendingIntent; import android.content.BroadcastReceiver; import android.content.Context; import android.content.Intent; import android.os.Bundle; import android.os.Handler; import android.os.Looper; import android.support.annotation.IntDef; import android.support.annotation.NonNull; import android.support.annotation.Nullable; import android.text.TextUtils; import junit.framework.Assert; import org.onepf.opfpush.util.Utils; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.text.SimpleDateFormat; import java.util.Date; import java.util.List; import static org.onepf.opfpush.OPFPushLog.LOGD; import static org.onepf.opfpush.OPFPushLog.LOGI; import static org.onepf.opfpush.OPFPushLog.LOGW; /** * Main class for manage push providers. * For get instance of this class call {@link #getInstance(android.content.Context)}. * <p/> * Before do any operations with {@code OpenPushHelper} you must call {@link #init(Options)}. * <p/> * For start select provider for registerWithNext call {@link #register()}. * * @author Kirill Rozov * @since 04.09.2014 */ public class OPFPushHelper { /** * Use for {@code messagesCount} argument in * {@link ProviderCallback#onDeletedMessages(String, int)} when messages count is unknown. */ public static final int MESSAGES_COUNT_UNKNOWN = Integer.MIN_VALUE; static final int STATE_UNREGISTERED = 0; static final int STATE_REGISTERING = 1; static final int STATE_REGISTERED = 2; static final int STATE_UNREGISTERING = 3; @Retention(RetentionPolicy.SOURCE) @IntDef(value = { STATE_UNREGISTERED, STATE_UNREGISTERING, STATE_REGISTERING, STATE_REGISTERED }) @interface State { } @Nullable private static OPFPushHelper sInstance; @NonNull private final Context mAppContext; @Nullable private EventListener mListener; @Nullable private MessageListener mMessageListener; @Nullable private BroadcastReceiver mPackageReceiver; @Nullable private PushProvider mCurrentProvider; @Nullable private AlarmManager mAlarmManager; private Options mOptions; private final Object mRegistrationLock = new Object(); private final Object mInitLock = new Object(); private final ProviderCallback mProviderCallback = new ProviderCallback(); private final Settings mSettings; /** * <b>Use for test purposes only!!!</b> */ OPFPushHelper(@NonNull Context context) { mAppContext = context.getApplicationContext(); mSettings = new Settings(context); } /** * Get instance of {@code OpenPushHelper}. * * @param context The current context. * @return Instance of {@link OPFPushHelper}. */ public static OPFPushHelper getInstance(@NonNull Context context) { if (sInstance == null) { synchronized (OPFPushHelper.class) { if (sInstance == null) { sInstance = new OPFPushHelper(context); } } } return sInstance; } static OPFPushHelper newInstance(@NonNull Context context) { synchronized (OPFPushHelper.class) { sInstance = new OPFPushHelper(context); } return sInstance; } public ProviderCallback getProviderCallback() { checkInitDone(); return mProviderCallback; } /** * Is init done and you may work with {@code OpenPushHelper}. * * @return True if init is done, else - false. */ public boolean isInitDone() { synchronized (mInitLock) { return mOptions != null; } } public boolean canSendMessages() { return mCurrentProvider instanceof SenderPushProvider; } public void sendMessage(Message message) { if (mCurrentProvider instanceof SenderPushProvider) { ((SenderPushProvider) mCurrentProvider).send(message); } else if (isRegistered()) { throw new OPFPushException( "Current provider '%s' not support send messages.", mCurrentProvider); } else { throw new OPFPushException("Provider not registered."); } } /** * Is push registered. * * @return True if push registered, else - false. */ public boolean isRegistered() { final int state = mSettings.getState(); return state == STATE_REGISTERED || state == STATE_UNREGISTERING; } public boolean isUnregistered() { return mSettings.getState() == STATE_UNREGISTERED; } public boolean isRegistering() { return mSettings.getState() == STATE_REGISTERING; } public boolean isUnregistering() { return mSettings.getState() == STATE_UNREGISTERING; } private void checkInitDone() { if (!isInitDone()) { throw new OPFPushException("Before work with OpenPushHelper call init() first."); } } /** * Init {@code OpenPushHelper}. You must call this method before do any operation. * * @param options Instance of {@code Options}. */ public void init(@NonNull Options options) { if (isInitDone()) { throw new OPFPushException("You can init OpenPushHelper only one time."); } if (mOptions == null) { synchronized (mInitLock) { if (mOptions == null) { mOptions = options; } } } initLastProvider(); LOGI("Init done."); } private void initLastProvider() { synchronized (mRegistrationLock) { final PushProvider lastProvider = getLastProvider(); if (lastProvider == null) { LOGI("No last provider."); return; } LOGI("Try restore last provider '%s'.", lastProvider); if (lastProvider.isAvailable()) { if (lastProvider.isRegistered()) { LOGI("Last provider running."); mCurrentProvider = lastProvider; mSettings.saveState(STATE_REGISTERED); } else { LOGI("Last provider need register."); if (!register(lastProvider)) { mSettings.saveLastProvider(null); } } } else { mSettings.saveLastProvider(null); mSettings.saveState(STATE_UNREGISTERED); onProviderUnavailable(lastProvider); } } } /** * Check if at least one provider available. */ public boolean hasAvailableProvider() { for (PushProvider provider : mOptions.getProviders()) { if (provider.isAvailable()) { return true; } } return false; } public void setListener(@Nullable EventListener l) { mListener = l == null ? null : new EventListenerWrapper(l); } public void setMessageListener(@Nullable MessageListener l) { mMessageListener = l; } void restartRegisterOnBoot() { checkInitDone(); mSettings.clear(); register(); } /** * Start select push provider and registered it. * <p/> * If you want to modify current registered provider, you must call unregister() first. * <p/> * * @throws OPFPushException When try call this method while init not done, * unregistration process in progress or already registered. */ public void register() { checkInitDone(); synchronized (mRegistrationLock) { switch (mSettings.getState()) { case STATE_REGISTERING: break; case STATE_UNREGISTERED: mSettings.saveState(STATE_REGISTERING); if (mOptions.isSelectSystemPreferred() && registerSystemPreferredProvider()) { return; } registerNextProvider(null); break; case STATE_UNREGISTERING: throw new OPFPushException("Can't register while unregistration is running."); case STATE_REGISTERED: throw new OPFPushException("Attempt to register twice!"); } } } private boolean registerSystemPreferredProvider() { for (PushProvider provider : mOptions.getProviders()) { if (PackageUtils.isSystemApp(mAppContext, provider.getHostAppPackage()) && register(provider)) { return true; } } return false; } /** * Register first available provider. Iterate all provider from the next provider after * {@code lastProvider} param. * * @param lastProvider Last provider what check to registerWithNext or null if has no. * @return True if find provider that can try to registerWithNext, otherwise false. */ private boolean registerNextProvider(@Nullable PushProvider lastProvider) { int nextProviderIndex = 0; final List<PushProvider> providers = mOptions.getProviders(); if (lastProvider != null) { int lastProviderIndex = providers.indexOf(lastProvider); if (lastProviderIndex != -1) { nextProviderIndex = lastProviderIndex + 1; } } for (int providersCount = providers.size(); nextProviderIndex < providersCount; ++nextProviderIndex) { if (register(providers.get(nextProviderIndex))) { return true; } } mSettings.saveState(STATE_UNREGISTERED); LOGW("No more available providers."); if (mListener != null) { mListener.onNoAvailableProvider(); } return false; } boolean register(@NonNull String providerName) { return register(getProviderWithException(providerName)); } /** * Start register provider. * * @param provider Provider for registration. * @return If provider available and can start registration return true, otherwise - false. */ private boolean register(@NonNull PushProvider provider) { if (provider.isAvailable()) { if (Utils.isNetworkConnected(mAppContext)) { LOGD("Try register %s.", provider); provider.register(); } else { mProviderCallback.onRegistrationError( Result.error(provider.getName(), Error.SERVICE_NOT_AVAILABLE, Result.Type.REGISTRATION) ); } return true; } return false; } /** * Unregister the application. Calling unregister() stops any messages from the server. * This is a not blocking call. You should rarely (if ever) need to call this method. * Not only is it expensive in terms of resources, but it invalidates your registration ID, * which you should never change unnecessarily. * A better approach is to simply have your server stop sending messages. * Only use unregister if you want to change your sender ID. * * @throws OPFPushException When try call this method while init not done, * registration process in progress or registration not done. */ public void unregister() { checkInitDone(); synchronized (mRegistrationLock) { switch (mSettings.getState()) { case STATE_REGISTERED: Assert.assertNotNull(mCurrentProvider); mSettings.saveState(STATE_UNREGISTERING); unregisterPackageChangeReceiver(); mCurrentProvider.unregister(); break; case STATE_UNREGISTERING: break; case STATE_REGISTERING: throw new OPFPushException("Can't unregister when registration in progress.!"); case STATE_UNREGISTERED: throw new OPFPushException("Before to unregister you must register provider.!"); } } } private void unregisterPackageChangeReceiver() { if (mPackageReceiver != null) { mAppContext.unregisterReceiver(mPackageReceiver); mPackageReceiver = null; } } @Nullable public PushProvider getCurrentProvider() { return mCurrentProvider; } /** * Search provider by name in {@code options} and return in. * If {@code} doesn't contain provider with described name return null. * * @param providerName Name of provider for search. * @return Provider with described name or null if nothing have found. */ @Nullable private PushProvider getProvider(@NonNull String providerName) { for (PushProvider provider : mOptions.getProviders()) { if (providerName.equals(provider.getName())) { return provider; } } return null; } /** * Same that {@link #getProvider(String)} but if provider not found throw exception. * * @param providerName Name of provider for search. * @return Provider with name {@code providerName}. * @throws OPFPushException When {@code PushProvider} with name {@code providerName} not found. */ @NonNull private PushProvider getProviderWithException(@NonNull String providerName) { PushProvider provider = getProvider(providerName); if (provider == null) { throw new OPFPushException("Provider with name '%s' not found.", providerName); } return provider; } @Nullable private PushProvider getLastProvider() { String storedProviderName = mSettings.getLastProviderName(); if (!TextUtils.isEmpty(storedProviderName)) { PushProvider provider = getProvider(storedProviderName); if (provider != null) { return provider; } mSettings.saveLastProvider(null); } return null; } @Override public String toString() { return "OpenPushHelper{" + "options=" + mOptions + ", currentProvider=" + mCurrentProvider + ", initDone=" + isInitDone() + ", registered=" + isRegistered() + '}'; } void postRetryRegister(@NonNull String providerName) { Assert.assertNotNull(mOptions.getBackoff()); final long when = System.currentTimeMillis() + mOptions.getBackoff().getTryDelay(); LOGI("Post retry register provider '%s' at %s", providerName, SimpleDateFormat.getDateTimeInstance().format(new Date(when))); Intent intent = new Intent(mAppContext, RetryBroadcastReceiver.class); intent.setAction(Constants.ACTION_REGISTER); intent.putExtra(Constants.EXTRA_PROVIDER_NAME, providerName); if (mAlarmManager == null) { mAlarmManager = (AlarmManager) mAppContext.getSystemService(Context.ALARM_SERVICE); } if (mAlarmManager != null) { mAlarmManager.set( AlarmManager.RTC, when, PendingIntent.getBroadcast(mAppContext, 0, intent, 0) ); } } static boolean canHandleResult(@NonNull Result result, @State int state) { switch (result.getType()) { case UNKNOWN: return state == STATE_REGISTERING || state == STATE_UNREGISTERING; case REGISTRATION: return state == STATE_REGISTERING; case UNREGISTRATION: return state == STATE_UNREGISTERING; default: return false; } } /** * Call this method when device state changed and need retry registration. * May be call only when the helper in registered state. * * @throws OPFPushException When call this method when registration not done * or {@code providerName} isn't current registered provider. */ void onNeedRetryRegister() { Assert.assertNotNull(mCurrentProvider); LOGD("onNeedRetryRegister(providerName = %s).", mCurrentProvider); mSettings.clear(); mCurrentProvider.onRegistrationInvalid(); mSettings.saveState(STATE_REGISTERING); if (!register(mCurrentProvider)) { mSettings.saveState(STATE_UNREGISTERED); } } /** * Call this method when provider become unavailable. * * @param provider Provider that become unavailable. * @throws OPFPushException When call this method when registration not done * or {@code providerName} isn't current registered provider. */ void onProviderUnavailable(@NonNull PushProvider provider) { LOGD("onProviderUnavailable(provider = %s).", provider); if (mCurrentProvider != null && provider.equals(mCurrentProvider)) { mCurrentProvider = null; mSettings.saveState(STATE_UNREGISTERED); } provider.onUnavailable(); if (mListener != null) { mListener.onProviderBecameUnavailable(provider.getName()); } if (mOptions.isRecoverProvider()) { OPFPushHelper.this.register(); //Restart registration } } public class ProviderCallback { ProviderCallback() { } /** * Provider must call this method when new message received. * * @param providerName Name of provider from what message received. * @param extras Message extras. * @throws OPFPushException When call this method when registration not done * or {@code providerName} isn't current registered provider. */ public void onMessage(@NonNull String providerName, @Nullable Bundle extras) { checkProviderWorking(providerName); LOGD("onMessageReceive(providerName = %s).", providerName); if (mMessageListener != null) { mMessageListener.onMessageReceive(providerName, extras); } } private void checkProviderWorking(String providerName) { checkInitDone(); if (!isRegistered()) { throw new OPFPushException("Can't receive message when not registered."); } if (mCurrentProvider != null && !providerName.equalsIgnoreCase(mCurrentProvider.getName())) { throw new OPFPushException("Can't receive message from not registered provider. " + "Current provider '%s', message source ='%s'", mCurrentProvider.getName(), providerName); } } /** * Provider must call this method when new message deleted. * * @param providerName Name of provider from what message deleted. * @param messagesCount Deleted messages count. If messages count is unknown pass -1. * @throws OPFPushException When call this method when registration not done * or {@code providerName} isn't current registered provider. */ public void onDeletedMessages(@NonNull String providerName, int messagesCount) { checkProviderWorking(providerName); LOGD("onDeletedMessages(providerName = %s, messagesCount = %d).", providerName, messagesCount); if (mMessageListener != null) { mMessageListener.onDeletedMessages(providerName, messagesCount); } } /** * Call this method on new registration or unregistration result. * * @param result Registration or unregistration result. * @throws OPFPushException When result type can't be handle * in current state of {@code OpenPushHelper}. */ public void onResult(@NonNull Result result) { synchronized (mRegistrationLock) { final int state = mSettings.getState(); if (canHandleResult(result, state)) { switch (result.getType()) { case REGISTRATION: onRegistrationResult(result); return; case UNREGISTRATION: onUnregistrationResult(result); return; case UNKNOWN: switch (state) { case STATE_REGISTERING: onRegistrationResult(result); return; case STATE_UNREGISTERING: onUnregistrationResult(result); return; } throw new OPFPushException("Result not handled."); } } else { throw new IllegalStateException("Result can't be handle."); } } } private void onUnregistrationResult(@NonNull Result result) { if (result.isSuccess()) { LOGI("Successfully unregister provider '%s'.", result.getProviderName()); mSettings.clear(); mCurrentProvider = null; if (mListener != null) { Assert.assertNotNull(result.getRegistrationId()); mListener.onUnregistered(result.getProviderName(), result.getRegistrationId()); } } else if (mListener != null) { mSettings.saveState(STATE_REGISTERED); Assert.assertNotNull(result.getError()); LOGI("Error unregister provider '%s'.", result.getProviderName()); mListener.onUnregistrationError(result.getProviderName(), result.getError()); } } private void onRegistrationResult(@NonNull Result result) { if (result.isSuccess()) { onRegistrationSuccess(result); } else { onRegistrationError(result); } } private void onRegistrationError(@NonNull Result result) { Assert.assertNotNull(result.getError()); LOGI("Error register provider '%s'.", result.getProviderName()); PushProvider provider = getProviderWithException(result.getProviderName()); if (mListener != null) { mListener.onRegistrationError(provider.getName(), result.getError()); } final Backoff backoff = mOptions.getBackoff(); if (result.getError() == Error.SERVICE_NOT_AVAILABLE && backoff != null && backoff.hasTries()) { postRetryRegister(provider.getName()); } else { if (backoff != null) { backoff.reset(); } registerNextProvider(provider); } } private void onRegistrationSuccess(Result result) { final Backoff backoff = mOptions.getBackoff(); if (backoff != null) { backoff.reset(); } LOGI("Successfully register provider '%s'.", result.getProviderName()); LOGI("Register id '%s'.", result.getRegistrationId()); mSettings.saveState(STATE_REGISTERED); mSettings.saveLastAndroidId(android.provider.Settings.Secure.ANDROID_ID); mCurrentProvider = getProviderWithException(result.getProviderName()); mSettings.saveLastProvider(mCurrentProvider); Assert.assertNotNull(result.getRegistrationId()); if (mListener != null) { mListener.onRegistered(result.getProviderName(), result.getRegistrationId()); } mPackageReceiver = PackageUtils.registerPackageChangeReceiver(mAppContext, mCurrentProvider); } } /** * Wrapper for execute all method on main thread. * * @author Kirill Rozov * @since 24.09.14. */ private static class EventListenerWrapper implements EventListener { private static final Handler HANDLER = new Handler(Looper.getMainLooper()); private final EventListener mListener; EventListenerWrapper(EventListener listener) { mListener = listener; } @Override public void onRegistered(@NonNull final String providerName, @NonNull final String registrationId) { HANDLER.post(new Runnable() { @Override public void run() { mListener.onRegistered(providerName, registrationId); } }); } @Override public void onRegistrationError(@NonNull final String providerName, @NonNull final Error error) { HANDLER.post(new Runnable() { @Override public void run() { mListener.onRegistrationError(providerName, error); } }); } @Override public void onUnregistrationError(@NonNull final String providerName, @NonNull final Error error) { HANDLER.post(new Runnable() { @Override public void run() { mListener.onUnregistrationError(providerName, error); } }); } @Override public void onNoAvailableProvider() { HANDLER.post(new Runnable() { @Override public void run() { mListener.onNoAvailableProvider(); } }); } @Override public void onUnregistered(@NonNull final String providerName, @NonNull final String registrationId) { HANDLER.post(new Runnable() { @Override public void run() { mListener.onUnregistered(providerName, registrationId); } }); } @Override public void onProviderBecameUnavailable(@NonNull final String providerName) { HANDLER.post(new Runnable() { @Override public void run() { mListener.onProviderBecameUnavailable(providerName); } }); } } }
Add send message java docs.
opfpush/src/main/java/org/onepf/opfpush/OPFPushHelper.java
Add send message java docs.
<ide><path>pfpush/src/main/java/org/onepf/opfpush/OPFPushHelper.java <ide> } <ide> } <ide> <add> /** <add> * Check can you send message in current time. This method return only if provider is registered <add> * and it is implement {@link SenderPushProvider} interface. <add> */ <ide> public boolean canSendMessages() { <ide> return mCurrentProvider instanceof SenderPushProvider; <ide> } <ide> <del> public void sendMessage(Message message) { <del> if (mCurrentProvider instanceof SenderPushProvider) { <del> ((SenderPushProvider) mCurrentProvider).send(message); <del> } else if (isRegistered()) { <del> throw new OPFPushException( <del> "Current provider '%s' not support send messages.", mCurrentProvider); <del> } else { <del> throw new OPFPushException("Provider not registered."); <add> /** <add> * Send message to server. <add> * <add> * @param message Message to send. <add> * @throws OPFPushException When try send message when any provider isn't registered or it isn't <add> * implement {@link SenderPushProvider} interface. <add> */ <add> public void sendMessage(@NonNull Message message) { <add> synchronized (mRegistrationLock) { <add> if (mCurrentProvider instanceof SenderPushProvider) { <add> ((SenderPushProvider) mCurrentProvider).send(message); <add> } else if (isRegistered()) { <add> throw new OPFPushException( <add> "Current provider '%s' not support send messages.", mCurrentProvider); <add> } else { <add> throw new OPFPushException("Provider not registered."); <add> } <ide> } <ide> } <ide>
Java
bsd-2-clause
92585f198ba96cf98d250b05f02ca50e364fabfb
0
marschall/pgjdbc,lonnyj/pgjdbc,rjmac/pgjdbc,Gordiychuk/pgjdbc,lordnelson/pgjdbc,schlosna/pgjdbc,lordnelson/pgjdbc,golovnin/pgjdbc,jorsol/pgjdbc,jkutner/pgjdbc,zapov/pgjdbc,marschall/pgjdbc,sehrope/pgjdbc,zapov/pgjdbc,jamesthomp/pgjdbc,underyx/pgjdbc,jorsol/pgjdbc,zemian/pgjdbc,AlexElin/pgjdbc,panchenko/pgjdbc,phillipross/pgjdbc,davecramer/pgjdbc,amozhenin/pgjdbc,schlosna/pgjdbc,amozhenin/pgjdbc,underyx/pgjdbc,bocap/pgjdbc,ekoontz/pgjdbc,rjmac/pgjdbc,lordnelson/pgjdbc,panchenko/pgjdbc,panchenko/pgjdbc,davecramer/pgjdbc,sehrope/pgjdbc,jkutner/pgjdbc,sehrope/pgjdbc,jamesthomp/pgjdbc,phillipross/pgjdbc,zapov/pgjdbc,sehrope/pgjdbc,davecramer/pgjdbc,golovnin/pgjdbc,golovnin/pgjdbc,alexismeneses/pgjdbc,marschall/pgjdbc,whitingjr/pgjdbc,jamesthomp/pgjdbc,AlexElin/pgjdbc,bocap/pgjdbc,jorsol/pgjdbc,alexismeneses/pgjdbc,whitingjr/pgjdbc,amozhenin/pgjdbc,bocap/pgjdbc,zemian/pgjdbc,davecramer/pgjdbc,pgjdbc/pgjdbc,pgjdbc/pgjdbc,marschall/pgjdbc,zemian/pgjdbc,Gordiychuk/pgjdbc,lonnyj/pgjdbc,phillipross/pgjdbc,jorsol/pgjdbc,underyx/pgjdbc,jkutner/pgjdbc,pgjdbc/pgjdbc,AlexElin/pgjdbc,rjmac/pgjdbc,ekoontz/pgjdbc,whitingjr/pgjdbc,Gordiychuk/pgjdbc,pgjdbc/pgjdbc
/*------------------------------------------------------------------------- * * Copyright (c) 2003-2014, PostgreSQL Global Development Group * * *------------------------------------------------------------------------- */ package org.postgresql.jdbc2; import java.sql.*; import java.util.Calendar; import java.util.GregorianCalendar; import java.util.TimeZone; import java.util.SimpleTimeZone; import org.postgresql.PGStatement; import org.postgresql.core.Oid; import org.postgresql.util.ByteConverter; import org.postgresql.util.GT; import org.postgresql.util.PSQLState; import org.postgresql.util.PSQLException; /** * Misc utils for handling time and date values. */ public class TimestampUtils { /** * Number of milliseconds in one day. */ private static final int ONEDAY = 24 * 3600 * 1000; private StringBuffer sbuf = new StringBuffer(); private Calendar defaultCal = new GregorianCalendar(); private final TimeZone defaultTz = defaultCal.getTimeZone(); private Calendar calCache; private int calCacheZone; private final boolean min74; private final boolean min82; /** * True if the backend uses doubles for time values. False if long is used. */ private final boolean usesDouble; TimestampUtils(boolean min74, boolean min82, boolean usesDouble) { this.min74 = min74; this.min82 = min82; this.usesDouble = usesDouble; } private Calendar getCalendar(int sign, int hr, int min, int sec) { int rawOffset = sign * (((hr * 60 + min) * 60 + sec) * 1000); if (calCache != null && calCacheZone == rawOffset) return calCache; StringBuffer zoneID = new StringBuffer("GMT"); zoneID.append(sign < 0 ? '-' : '+'); if (hr < 10) zoneID.append('0'); zoneID.append(hr); if (min < 10) zoneID.append('0'); zoneID.append(min); if (sec < 10) zoneID.append('0'); zoneID.append(sec); TimeZone syntheticTZ = new SimpleTimeZone(rawOffset, zoneID.toString()); calCache = new GregorianCalendar(syntheticTZ); calCacheZone = rawOffset; return calCache; } private static class ParsedTimestamp { boolean hasDate = false; int era = GregorianCalendar.AD; int year = 1970; int month = 1; boolean hasTime = false; int day = 1; int hour = 0; int minute = 0; int second = 0; int nanos = 0; Calendar tz = null; } /** * Load date/time information into the provided calendar * returning the fractional seconds. */ private ParsedTimestamp loadCalendar(Calendar defaultTz, String str, String type) throws SQLException { char []s = str.toCharArray(); int slen = s.length; // This is pretty gross.. ParsedTimestamp result = new ParsedTimestamp(); // We try to parse these fields in order; all are optional // (but some combinations don't make sense, e.g. if you have // both date and time then they must be whitespace-separated). // At least one of date and time must be present. // leading whitespace // yyyy-mm-dd // whitespace // hh:mm:ss // whitespace // timezone in one of the formats: +hh, -hh, +hh:mm, -hh:mm // whitespace // if date is present, an era specifier: AD or BC // trailing whitespace try { int start = skipWhitespace(s, 0); // Skip leading whitespace int end = firstNonDigit(s, start); int num; char sep; // Possibly read date. if (charAt(s, end) == '-') { // // Date // result.hasDate = true; // year result.year = number(s, start, end); start = end + 1; // Skip '-' // month end = firstNonDigit(s, start); result.month = number(s, start, end); sep = charAt(s, end); if (sep != '-') throw new NumberFormatException("Expected date to be dash-separated, got '" + sep + "'"); start = end + 1; // Skip '-' // day of month end = firstNonDigit(s, start); result.day = number(s, start, end); start = skipWhitespace(s, end); // Skip trailing whitespace } // Possibly read time. if (Character.isDigit(charAt(s, start))) { // // Time. // result.hasTime = true; // Hours end = firstNonDigit(s, start); result.hour = number(s, start, end); sep = charAt(s, end); if (sep != ':') throw new NumberFormatException("Expected time to be colon-separated, got '" + sep + "'"); start = end + 1; // Skip ':' // minutes end = firstNonDigit(s, start); result.minute = number(s, start, end); sep = charAt(s, end); if (sep != ':') throw new NumberFormatException("Expected time to be colon-separated, got '" + sep + "'"); start = end + 1; // Skip ':' // seconds end = firstNonDigit(s, start); result.second = number(s, start, end); start = end; // Fractional seconds. if (charAt(s, start) == '.') { end = firstNonDigit(s, start+1); // Skip '.' num = number(s, start+1, end); for (int numlength = (end - (start+1)); numlength < 9; ++numlength) num *= 10; result.nanos = num; start = end; } start = skipWhitespace(s, start); // Skip trailing whitespace } // Possibly read timezone. sep = charAt(s, start); if (sep == '-' || sep == '+') { int tzsign = (sep == '-') ? -1 : 1; int tzhr, tzmin, tzsec; end = firstNonDigit(s, start+1); // Skip +/- tzhr = number(s, start+1, end); start = end; sep = charAt(s, start); if (sep == ':') { end = firstNonDigit(s, start+1); // Skip ':' tzmin = number(s, start+1, end); start = end; } else { tzmin = 0; } tzsec = 0; if (min82) { sep = charAt(s, start); if (sep == ':') { end = firstNonDigit(s, start+1); // Skip ':' tzsec = number(s, start+1, end); start = end; } } // Setting offset does not seem to work correctly in all // cases.. So get a fresh calendar for a synthetic timezone // instead result.tz = getCalendar(tzsign, tzhr, tzmin, tzsec); start = skipWhitespace(s, start); // Skip trailing whitespace } if (result.hasDate && start < slen) { String eraString = new String(s, start, slen - start) ; if (eraString.startsWith("AD")) { result.era = GregorianCalendar.AD; start += 2; } else if (eraString.startsWith("BC")) { result.era = GregorianCalendar.BC; start += 2; } } if (start < slen) throw new NumberFormatException("Trailing junk on timestamp: '" + new String(s, start, slen - start) + "'"); if (!result.hasTime && !result.hasDate) throw new NumberFormatException("Timestamp has neither date nor time"); } catch (NumberFormatException nfe) { throw new PSQLException(GT.tr("Bad value for type {0} : {1}", new Object[]{type,str}), PSQLState.BAD_DATETIME_FORMAT, nfe); } return result; } // // Debugging hooks, not normally used unless developing -- uncomment the // bodies for stderr debug spam. // private static void showParse(String type, String what, Calendar cal, java.util.Date result, Calendar resultCal) { // java.text.SimpleDateFormat sdf = new java.text.SimpleDateFormat("yyyy-MM-dd G HH:mm:ss Z"); // sdf.setTimeZone(resultCal.getTimeZone()); // StringBuffer sb = new StringBuffer("Parsed "); // sb.append(type); // sb.append(" '"); // sb.append(what); // sb.append("' in zone "); // sb.append(cal.getTimeZone().getID()); // sb.append(" as "); // sb.append(sdf.format(result)); // sb.append(" (millis="); // sb.append(result.getTime()); // sb.append(")"); // System.err.println(sb.toString()); } private static void showString(String type, Calendar cal, java.util.Date value, String result) { // java.text.SimpleDateFormat sdf = new java.text.SimpleDateFormat("yyyy-MM-dd G HH:mm:ss Z"); // sdf.setTimeZone(cal.getTimeZone()); // StringBuffer sb = new StringBuffer("Stringized "); // sb.append(type); // sb.append(" "); // sb.append(sdf.format(value)); // sb.append(" (millis="); // sb.append(value.getTime()); // sb.append(") as '"); // sb.append(result); // sb.append("'"); // System.err.println(sb.toString()); } /** * Parse a string and return a timestamp representing its value. * * @param s The ISO formated date string to parse. * * @return null if s is null or a timestamp of the parsed string s. * * @throws SQLException if there is a problem parsing s. **/ public synchronized Timestamp toTimestamp(Calendar cal, String s) throws SQLException { if (s == null) return null; int slen = s.length(); // convert postgres's infinity values to internal infinity magic value if (slen == 8 && s.equals("infinity")) { return new Timestamp(PGStatement.DATE_POSITIVE_INFINITY); } if (slen == 9 && s.equals("-infinity")) { return new Timestamp(PGStatement.DATE_NEGATIVE_INFINITY); } if (cal == null) cal = defaultCal; ParsedTimestamp ts = loadCalendar(cal, s, "timestamp"); Calendar useCal = (ts.tz == null ? cal : ts.tz); useCal.set(Calendar.ERA, ts.era); useCal.set(Calendar.YEAR, ts.year); useCal.set(Calendar.MONTH, ts.month-1); useCal.set(Calendar.DAY_OF_MONTH, ts.day); useCal.set(Calendar.HOUR_OF_DAY, ts.hour); useCal.set(Calendar.MINUTE, ts.minute); useCal.set(Calendar.SECOND, ts.second); useCal.set(Calendar.MILLISECOND, 0); Timestamp result = new Timestamp(useCal.getTime().getTime()); result.setNanos(ts.nanos); showParse("timestamp", s, cal, result, useCal); return result; } public synchronized Time toTime(Calendar cal, String s) throws SQLException { if (s == null) return null; int slen = s.length(); // infinity cannot be represented as Time // so there's not much we can do here. if ((slen == 8 && s.equals("infinity")) || (slen == 9 && s.equals("-infinity"))) { throw new PSQLException(GT.tr("Infinite value found for timestamp/date. This cannot be represented as time."), PSQLState.DATETIME_OVERFLOW); } if (cal == null) cal = defaultCal; ParsedTimestamp ts = loadCalendar(cal, s, "time"); Calendar useCal = (ts.tz == null ? cal : ts.tz); useCal.set(Calendar.HOUR_OF_DAY, ts.hour); useCal.set(Calendar.MINUTE, ts.minute); useCal.set(Calendar.SECOND, ts.second); useCal.set(Calendar.MILLISECOND, (ts.nanos + 500000) / 1000000); if (ts.hasDate) { // Rotate it into the requested timezone before we zero out the date useCal.set(Calendar.ERA, ts.era); useCal.set(Calendar.YEAR, ts.year); useCal.set(Calendar.MONTH, ts.month-1); useCal.set(Calendar.DAY_OF_MONTH, ts.day); cal.setTime(new Date(useCal.getTime().getTime())); useCal = cal; } useCal.set(Calendar.ERA, GregorianCalendar.AD); useCal.set(Calendar.YEAR, 1970); useCal.set(Calendar.MONTH, 0); useCal.set(Calendar.DAY_OF_MONTH, 1); Time result = new Time(useCal.getTime().getTime()); showParse("time", s, cal, result, useCal); return result; } public synchronized Date toDate(Calendar cal, String s) throws SQLException { if (s == null) return null; int slen = s.length(); // convert postgres's infinity values to internal infinity magic value if (slen == 8 && s.equals("infinity")) { return new Date(PGStatement.DATE_POSITIVE_INFINITY); } if (slen == 9 && s.equals("-infinity")) { return new Date(PGStatement.DATE_NEGATIVE_INFINITY); } if (cal == null) cal = defaultCal; ParsedTimestamp ts = loadCalendar(cal, s, "date"); Calendar useCal = (ts.tz == null ? cal : ts.tz); useCal.set(Calendar.ERA, ts.era); useCal.set(Calendar.YEAR, ts.year); useCal.set(Calendar.MONTH, ts.month-1); useCal.set(Calendar.DAY_OF_MONTH, ts.day); if (ts.hasTime) { // Rotate it into the requested timezone before we zero out the time useCal.set(Calendar.HOUR_OF_DAY, ts.hour); useCal.set(Calendar.MINUTE, ts.minute); useCal.set(Calendar.SECOND, ts.second); useCal.set(Calendar.MILLISECOND, (ts.nanos + 500000) / 1000000); cal.setTime(new Date(useCal.getTime().getTime())); useCal = cal; } useCal.set(Calendar.HOUR_OF_DAY, 0); useCal.set(Calendar.MINUTE, 0); useCal.set(Calendar.SECOND, 0); useCal.set(Calendar.MILLISECOND, 0); Date result = new Date(useCal.getTime().getTime()); showParse("date", s, cal, result, useCal); return result; } public synchronized String toString(Calendar cal, Timestamp x) { if (cal == null) cal = defaultCal; cal.setTime(x); sbuf.setLength(0); if (x.getTime() == PGStatement.DATE_POSITIVE_INFINITY) { sbuf.append("infinity"); } else if (x.getTime() == PGStatement.DATE_NEGATIVE_INFINITY) { sbuf.append("-infinity"); } else { appendDate(sbuf, cal); sbuf.append(' '); appendTime(sbuf, cal, x.getNanos()); appendTimeZone(sbuf, cal); appendEra(sbuf, cal); } showString("timestamp", cal, x, sbuf.toString()); return sbuf.toString(); } public synchronized String toString(Calendar cal, Date x) { if (cal == null) cal = defaultCal; cal.setTime(x); sbuf.setLength(0); if (x.getTime() == PGStatement.DATE_POSITIVE_INFINITY) { sbuf.append("infinity"); } else if (x.getTime() == PGStatement.DATE_NEGATIVE_INFINITY) { sbuf.append("-infinity"); } else { appendDate(sbuf, cal); appendEra(sbuf, cal); appendTimeZone(sbuf, cal); } showString("date", cal, x, sbuf.toString()); return sbuf.toString(); } public synchronized String toString(Calendar cal, Time x) { if (cal == null) cal = defaultCal; cal.setTime(x); sbuf.setLength(0); appendTime(sbuf, cal, cal.get(Calendar.MILLISECOND) * 1000000); // The 'time' parser for <= 7.3 doesn't like timezones. if (min74) appendTimeZone(sbuf, cal); showString("time", cal, x, sbuf.toString()); return sbuf.toString(); } private static void appendDate(StringBuffer sb, Calendar cal) { int l_year = cal.get(Calendar.YEAR); // always use at least four digits for the year so very // early years, like 2, don't get misinterpreted // int l_yearlen = String.valueOf(l_year).length(); for (int i = 4; i > l_yearlen; i--) { sb.append("0"); } sb.append(l_year); sb.append('-'); int l_month = cal.get(Calendar.MONTH) + 1; if (l_month < 10) sb.append('0'); sb.append(l_month); sb.append('-'); int l_day = cal.get(Calendar.DAY_OF_MONTH); if (l_day < 10) sb.append('0'); sb.append(l_day); } private static void appendTime(StringBuffer sb, Calendar cal, int nanos) { int hours = cal.get(Calendar.HOUR_OF_DAY); if (hours < 10) sb.append('0'); sb.append(hours); sb.append(':'); int minutes = cal.get(Calendar.MINUTE); if (minutes < 10) sb.append('0'); sb.append(minutes); sb.append(':'); int seconds = cal.get(Calendar.SECOND); if (seconds < 10) sb.append('0'); sb.append(seconds); // Add nanoseconds. // This won't work for server versions < 7.2 which only want // a two digit fractional second, but we don't need to support 7.1 // anymore and getting the version number here is difficult. // char[] decimalStr = {'0', '0', '0', '0', '0', '0', '0', '0', '0'}; char[] nanoStr = Integer.toString(nanos).toCharArray(); System.arraycopy(nanoStr, 0, decimalStr, decimalStr.length - nanoStr.length, nanoStr.length); sb.append('.'); sb.append(decimalStr, 0, 6); } private void appendTimeZone(StringBuffer sb, java.util.Calendar cal) { int offset = (cal.get(Calendar.ZONE_OFFSET) + cal.get(Calendar.DST_OFFSET)) / 1000; int absoff = Math.abs(offset); int hours = absoff / 60 / 60; int mins = (absoff - hours * 60 * 60) / 60; int secs = absoff - hours * 60 * 60 - mins * 60; sb.append((offset >= 0) ? " +" : " -"); if (hours < 10) sb.append('0'); sb.append(hours); sb.append(':'); if (mins < 10) sb.append('0'); sb.append(mins); if (min82) { sb.append(':'); if (secs < 10) sb.append('0'); sb.append(secs); } } private static void appendEra(StringBuffer sb, Calendar cal) { if (cal.get(Calendar.ERA) == GregorianCalendar.BC) { sb.append(" BC"); } } private static int skipWhitespace(char []s, int start) { int slen = s.length; for (int i=start; i<slen; i++) { if (!Character.isSpace(s[i])) return i; } return slen; } private static int firstNonDigit(char []s, int start) { int slen = s.length; for (int i=start; i<slen; i++) { if (!Character.isDigit(s[i])) { return i; } } return slen; } private static int number(char []s, int start, int end) { if (start >= end) { throw new NumberFormatException(); } int n=0; for ( int i=start; i < end; i++) { n = 10 * n + (s[i]-'0'); } return n; } private static char charAt(char []s, int pos) { if (pos >= 0 && pos < s.length) { return s[pos]; } return '\0'; } /** * Returns the SQL Date object matching the given bytes with * {@link Oid#DATE}. * * @param tz The timezone used. * @param bytes The binary encoded date value. * @return The parsed date object. * @throws PSQLException If binary format could not be parsed. */ public Date toDateBin(TimeZone tz, byte[] bytes) throws PSQLException { if (bytes.length != 4) { throw new PSQLException(GT.tr("Unsupported binary encoding of {0}.", "date"), PSQLState.BAD_DATETIME_FORMAT); } int days = ByteConverter.int4(bytes, 0); if (tz == null) { tz = defaultTz; } long secs = toJavaSecs(days * 86400L); long millis = secs * 1000L; int offset = tz.getOffset(millis); if (millis <= PGStatement.DATE_NEGATIVE_SMALLER_INFINITY) { millis = PGStatement.DATE_NEGATIVE_INFINITY; offset = 0; } else if (millis >= PGStatement.DATE_POSITIVE_SMALLER_INFINITY) { millis = PGStatement.DATE_POSITIVE_INFINITY; offset = 0; } return new Date(millis - offset); } /** * Returns the SQL Time object matching the given bytes with * {@link Oid#TIME} or {@link Oid#TIMETZ}. * * @param tz The timezone used when received data is {@link Oid#TIME}, * ignored if data already contains {@link Oid#TIMETZ}. * @param bytes The binary encoded time value. * @return The parsed time object. * @throws PSQLException If binary format could not be parsed. */ public Time toTimeBin(TimeZone tz, byte[] bytes) throws PSQLException { if ((bytes.length != 8 && bytes.length != 12)) { throw new PSQLException(GT.tr("Unsupported binary encoding of {0}.", "time"), PSQLState.BAD_DATETIME_FORMAT); } long millis; int timeOffset; if (usesDouble) { double time = ByteConverter.float8(bytes, 0); millis = (long) (time * 1000); } else { long time = ByteConverter.int8(bytes, 0); millis = time / 1000; } if (bytes.length == 12) { timeOffset = ByteConverter.int4(bytes, 8); timeOffset *= -1000; } else { if (tz == null) { tz = defaultTz; } timeOffset = tz.getOffset(millis); } millis -= timeOffset; return new Time(millis); } /** * Returns the SQL Timestamp object matching the given bytes with * {@link Oid#TIMESTAMP} or {@link Oid#TIMESTAMPTZ}. * * @param tz The timezone used when received data is {@link Oid#TIMESTAMP}, * ignored if data already contains {@link Oid#TIMESTAMPTZ}. * @param bytes The binary encoded timestamp value. * @param timestamptz True if the binary is in GMT. * @return The parsed timestamp object. * @throws PSQLException If binary format could not be parsed. */ public Timestamp toTimestampBin(TimeZone tz, byte[] bytes, boolean timestamptz) throws PSQLException { if (bytes.length != 8) { throw new PSQLException(GT.tr("Unsupported binary encoding of {0}.", "timestamp"), PSQLState.BAD_DATETIME_FORMAT); } long secs; int nanos; if (usesDouble) { double time = ByteConverter.float8(bytes, 0); if (time == Double.POSITIVE_INFINITY) { return new Timestamp(PGStatement.DATE_POSITIVE_INFINITY); } else if (time == Double.NEGATIVE_INFINITY) { return new Timestamp(PGStatement.DATE_NEGATIVE_INFINITY); } secs = (long) time; nanos = (int) ((time - secs) * 1000000); } else { long time = ByteConverter.int8(bytes, 0); // compatibility with text based receiving, not strictly necessary // and can actually be confusing because there are timestamps // that are larger than infinite if (time == Long.MAX_VALUE) { return new Timestamp(PGStatement.DATE_POSITIVE_INFINITY); } else if (time == Long.MIN_VALUE) { return new Timestamp(PGStatement.DATE_NEGATIVE_INFINITY); } secs = time / 1000000; nanos = (int) (time - secs * 1000000); } if (nanos < 0) { secs--; nanos += 1000000; } nanos *= 1000; secs = toJavaSecs(secs); long millis = secs * 1000L; if (!timestamptz) { if (tz == null) { tz = defaultTz; } millis -= tz.getOffset(millis) + tz.getDSTSavings(); } Timestamp ts = new Timestamp(millis); ts.setNanos(nanos); return ts; } /** * Extracts the date part from a timestamp. * * @param timestamp The timestamp from which to extract the date. * @param tz The time zone of the date. * @return The extracted date. */ public Date convertToDate(Timestamp timestamp, TimeZone tz) { long millis = timestamp.getTime(); // no adjustments for the inifity hack values if (millis <= PGStatement.DATE_NEGATIVE_INFINITY || millis >= PGStatement.DATE_POSITIVE_INFINITY) { return new Date(millis); } if (tz == null) { tz = defaultTz; } int offset = tz.getOffset(millis) + tz.getDSTSavings(); long timePart = millis % ONEDAY; if (timePart + offset >= ONEDAY) { millis += ONEDAY; } millis -= timePart; millis -= offset; return new Date(millis); } /** * Extracts the time part from a timestamp. * * @param timestamp The timestamp from which to extract the time. * @param tz The time zone of the time. * @return The extracted time. */ public Time convertToTime(Timestamp timestamp, TimeZone tz) { long millis = timestamp.getTime(); if (tz == null) { tz = defaultTz; } int offset = tz.getOffset(millis); long low = - tz.getOffset(millis); long high = low + ONEDAY; if (millis < low) { do { millis += ONEDAY; } while (millis < low); } else if (millis >= high) { do { millis -= ONEDAY; } while (millis > high); } return new Time(millis); } /** * Returns the given time value as String matching what the * current postgresql server would send in text mode. */ public String timeToString(java.util.Date time) { long millis = time.getTime(); if (millis <= PGStatement.DATE_NEGATIVE_INFINITY) { return "-infinity"; } if (millis >= PGStatement.DATE_POSITIVE_INFINITY) { return "infinity"; } return time.toString(); } /** * Converts the given postgresql seconds to java seconds. * Reverse engineered by inserting varying dates to postgresql * and tuning the formula until the java dates matched. * See {@link #toPgSecs} for the reverse operation. * * @param secs Postgresql seconds. * @return Java seconds. */ private static long toJavaSecs(long secs) { // postgres epoc to java epoc secs += 946684800L; // Julian/Gregorian calendar cutoff point if (secs < -12219292800L) { // October 4, 1582 -> October 15, 1582 secs += 86400 * 10; if (secs < -14825808000L) { // 1500-02-28 -> 1500-03-01 int extraLeaps = (int) ((secs + 14825808000L) / 3155760000L); extraLeaps--; extraLeaps -= extraLeaps / 4; secs += extraLeaps * 86400L; } } return secs; } /** * Converts the given java seconds to postgresql seconds. * See {@link #toJavaSecs} for the reverse operation. * The conversion is valid for any year 100 BC onwards. * * @param secs Postgresql seconds. * @return Java seconds. */ private static long toPgSecs(long secs) { // java epoc to postgres epoc secs -= 946684800L; // Julian/Greagorian calendar cutoff point if (secs < -13165977600L) { // October 15, 1582 -> October 4, 1582 secs -= 86400 * 10; if (secs < -15773356800L) { // 1500-03-01 -> 1500-02-28 int years = (int) ((secs + 15773356800L) / -3155823050L); years++; years -= years/4; secs += years * 86400; } } return secs; } /** * Converts the SQL Date to binary representation for {@link Oid#DATE}. * * @param tz The timezone used. * @param bytes The binary encoded date value. * @throws PSQLException If binary format could not be parsed. */ public void toBinDate(TimeZone tz, byte[] bytes, Date value) throws PSQLException { long millis = value.getTime(); if (tz == null) { tz = defaultTz; } millis += tz.getOffset(millis); long secs = toPgSecs(millis / 1000); ByteConverter.int4(bytes, 0, (int) (secs / 86400)); } }
org/postgresql/jdbc2/TimestampUtils.java
/*------------------------------------------------------------------------- * * Copyright (c) 2003-2011, PostgreSQL Global Development Group * * *------------------------------------------------------------------------- */ package org.postgresql.jdbc2; import java.sql.*; import java.util.Calendar; import java.util.GregorianCalendar; import java.util.TimeZone; import java.util.SimpleTimeZone; import org.postgresql.PGStatement; import org.postgresql.core.Oid; import org.postgresql.util.ByteConverter; import org.postgresql.util.GT; import org.postgresql.util.PSQLState; import org.postgresql.util.PSQLException; /** * Misc utils for handling time and date values. */ public class TimestampUtils { /** * Number of milliseconds in one day. */ private static final int ONEDAY = 24 * 3600 * 1000; private StringBuffer sbuf = new StringBuffer(); private Calendar defaultCal = new GregorianCalendar(); private final TimeZone defaultTz = defaultCal.getTimeZone(); private Calendar calCache; private int calCacheZone; private final boolean min74; private final boolean min82; /** * True if the backend uses doubles for time values. False if long is used. */ private final boolean usesDouble; TimestampUtils(boolean min74, boolean min82, boolean usesDouble) { this.min74 = min74; this.min82 = min82; this.usesDouble = usesDouble; } private Calendar getCalendar(int sign, int hr, int min, int sec) { int rawOffset = sign * (((hr * 60 + min) * 60 + sec) * 1000); if (calCache != null && calCacheZone == rawOffset) return calCache; StringBuffer zoneID = new StringBuffer("GMT"); zoneID.append(sign < 0 ? '-' : '+'); if (hr < 10) zoneID.append('0'); zoneID.append(hr); if (min < 10) zoneID.append('0'); zoneID.append(min); if (sec < 10) zoneID.append('0'); zoneID.append(sec); TimeZone syntheticTZ = new SimpleTimeZone(rawOffset, zoneID.toString()); calCache = new GregorianCalendar(syntheticTZ); calCacheZone = rawOffset; return calCache; } private static class ParsedTimestamp { boolean hasDate = false; int era = GregorianCalendar.AD; int year = 1970; int month = 1; boolean hasTime = false; int day = 1; int hour = 0; int minute = 0; int second = 0; int nanos = 0; Calendar tz = null; } /** * Load date/time information into the provided calendar * returning the fractional seconds. */ private ParsedTimestamp loadCalendar(Calendar defaultTz, String str, String type) throws SQLException { char []s = str.toCharArray(); int slen = s.length; // This is pretty gross.. ParsedTimestamp result = new ParsedTimestamp(); // We try to parse these fields in order; all are optional // (but some combinations don't make sense, e.g. if you have // both date and time then they must be whitespace-separated). // At least one of date and time must be present. // leading whitespace // yyyy-mm-dd // whitespace // hh:mm:ss // whitespace // timezone in one of the formats: +hh, -hh, +hh:mm, -hh:mm // whitespace // if date is present, an era specifier: AD or BC // trailing whitespace try { int start = skipWhitespace(s, 0); // Skip leading whitespace int end = firstNonDigit(s, start); int num; char sep; // Possibly read date. if (charAt(s, end) == '-') { // // Date // result.hasDate = true; // year result.year = number(s, start, end); start = end + 1; // Skip '-' // month end = firstNonDigit(s, start); result.month = number(s, start, end); sep = charAt(s, end); if (sep != '-') throw new NumberFormatException("Expected date to be dash-separated, got '" + sep + "'"); start = end + 1; // Skip '-' // day of month end = firstNonDigit(s, start); result.day = number(s, start, end); start = skipWhitespace(s, end); // Skip trailing whitespace } // Possibly read time. if (Character.isDigit(charAt(s, start))) { // // Time. // result.hasTime = true; // Hours end = firstNonDigit(s, start); result.hour = number(s, start, end); sep = charAt(s, end); if (sep != ':') throw new NumberFormatException("Expected time to be colon-separated, got '" + sep + "'"); start = end + 1; // Skip ':' // minutes end = firstNonDigit(s, start); result.minute = number(s, start, end); sep = charAt(s, end); if (sep != ':') throw new NumberFormatException("Expected time to be colon-separated, got '" + sep + "'"); start = end + 1; // Skip ':' // seconds end = firstNonDigit(s, start); result.second = number(s, start, end); start = end; // Fractional seconds. if (charAt(s, start) == '.') { end = firstNonDigit(s, start+1); // Skip '.' num = number(s, start+1, end); for (int numlength = (end - (start+1)); numlength < 9; ++numlength) num *= 10; result.nanos = num; start = end; } start = skipWhitespace(s, start); // Skip trailing whitespace } // Possibly read timezone. sep = charAt(s, start); if (sep == '-' || sep == '+') { int tzsign = (sep == '-') ? -1 : 1; int tzhr, tzmin, tzsec; end = firstNonDigit(s, start+1); // Skip +/- tzhr = number(s, start+1, end); start = end; sep = charAt(s, start); if (sep == ':') { end = firstNonDigit(s, start+1); // Skip ':' tzmin = number(s, start+1, end); start = end; } else { tzmin = 0; } tzsec = 0; if (min82) { sep = charAt(s, start); if (sep == ':') { end = firstNonDigit(s, start+1); // Skip ':' tzsec = number(s, start+1, end); start = end; } } // Setting offset does not seem to work correctly in all // cases.. So get a fresh calendar for a synthetic timezone // instead result.tz = getCalendar(tzsign, tzhr, tzmin, tzsec); start = skipWhitespace(s, start); // Skip trailing whitespace } if (result.hasDate && start < slen) { String eraString = new String(s, start, slen - start) ; if (eraString.startsWith("AD")) { result.era = GregorianCalendar.AD; start += 2; } else if (eraString.startsWith("BC")) { result.era = GregorianCalendar.BC; start += 2; } } if (start < slen) throw new NumberFormatException("Trailing junk on timestamp: '" + new String(s, start, slen - start) + "'"); if (!result.hasTime && !result.hasDate) throw new NumberFormatException("Timestamp has neither date nor time"); } catch (NumberFormatException nfe) { throw new PSQLException(GT.tr("Bad value for type {0} : {1}", new Object[]{type,str}), PSQLState.BAD_DATETIME_FORMAT, nfe); } return result; } // // Debugging hooks, not normally used unless developing -- uncomment the // bodies for stderr debug spam. // private static void showParse(String type, String what, Calendar cal, java.util.Date result, Calendar resultCal) { // java.text.SimpleDateFormat sdf = new java.text.SimpleDateFormat("yyyy-MM-dd G HH:mm:ss Z"); // sdf.setTimeZone(resultCal.getTimeZone()); // StringBuffer sb = new StringBuffer("Parsed "); // sb.append(type); // sb.append(" '"); // sb.append(what); // sb.append("' in zone "); // sb.append(cal.getTimeZone().getID()); // sb.append(" as "); // sb.append(sdf.format(result)); // sb.append(" (millis="); // sb.append(result.getTime()); // sb.append(")"); // System.err.println(sb.toString()); } private static void showString(String type, Calendar cal, java.util.Date value, String result) { // java.text.SimpleDateFormat sdf = new java.text.SimpleDateFormat("yyyy-MM-dd G HH:mm:ss Z"); // sdf.setTimeZone(cal.getTimeZone()); // StringBuffer sb = new StringBuffer("Stringized "); // sb.append(type); // sb.append(" "); // sb.append(sdf.format(value)); // sb.append(" (millis="); // sb.append(value.getTime()); // sb.append(") as '"); // sb.append(result); // sb.append("'"); // System.err.println(sb.toString()); } /** * Parse a string and return a timestamp representing its value. * * @param s The ISO formated date string to parse. * * @return null if s is null or a timestamp of the parsed string s. * * @throws SQLException if there is a problem parsing s. **/ public synchronized Timestamp toTimestamp(Calendar cal, String s) throws SQLException { if (s == null) return null; int slen = s.length(); // convert postgres's infinity values to internal infinity magic value if (slen == 8 && s.equals("infinity")) { return new Timestamp(PGStatement.DATE_POSITIVE_INFINITY); } if (slen == 9 && s.equals("-infinity")) { return new Timestamp(PGStatement.DATE_NEGATIVE_INFINITY); } if (cal == null) cal = defaultCal; ParsedTimestamp ts = loadCalendar(cal, s, "timestamp"); Calendar useCal = (ts.tz == null ? cal : ts.tz); useCal.set(Calendar.ERA, ts.era); useCal.set(Calendar.YEAR, ts.year); useCal.set(Calendar.MONTH, ts.month-1); useCal.set(Calendar.DAY_OF_MONTH, ts.day); useCal.set(Calendar.HOUR_OF_DAY, ts.hour); useCal.set(Calendar.MINUTE, ts.minute); useCal.set(Calendar.SECOND, ts.second); useCal.set(Calendar.MILLISECOND, 0); Timestamp result = new Timestamp(useCal.getTime().getTime()); result.setNanos(ts.nanos); showParse("timestamp", s, cal, result, useCal); return result; } public synchronized Time toTime(Calendar cal, String s) throws SQLException { if (s == null) return null; int slen = s.length(); // infinity cannot be represented as Time // so there's not much we can do here. if ((slen == 8 && s.equals("infinity")) || (slen == 9 && s.equals("-infinity"))) { throw new PSQLException(GT.tr("Infinite value found for timestamp/date. This cannot be represented as time."), PSQLState.DATETIME_OVERFLOW); } if (cal == null) cal = defaultCal; ParsedTimestamp ts = loadCalendar(cal, s, "time"); Calendar useCal = (ts.tz == null ? cal : ts.tz); useCal.set(Calendar.HOUR_OF_DAY, ts.hour); useCal.set(Calendar.MINUTE, ts.minute); useCal.set(Calendar.SECOND, ts.second); useCal.set(Calendar.MILLISECOND, (ts.nanos + 500000) / 1000000); if (ts.hasDate) { // Rotate it into the requested timezone before we zero out the date useCal.set(Calendar.ERA, ts.era); useCal.set(Calendar.YEAR, ts.year); useCal.set(Calendar.MONTH, ts.month-1); useCal.set(Calendar.DAY_OF_MONTH, ts.day); cal.setTime(new Date(useCal.getTime().getTime())); useCal = cal; } useCal.set(Calendar.ERA, GregorianCalendar.AD); useCal.set(Calendar.YEAR, 1970); useCal.set(Calendar.MONTH, 0); useCal.set(Calendar.DAY_OF_MONTH, 1); Time result = new Time(useCal.getTime().getTime()); showParse("time", s, cal, result, useCal); return result; } public synchronized Date toDate(Calendar cal, String s) throws SQLException { if (s == null) return null; int slen = s.length(); // convert postgres's infinity values to internal infinity magic value if (slen == 8 && s.equals("infinity")) { return new Date(PGStatement.DATE_POSITIVE_INFINITY); } if (slen == 9 && s.equals("-infinity")) { return new Date(PGStatement.DATE_NEGATIVE_INFINITY); } if (cal == null) cal = defaultCal; ParsedTimestamp ts = loadCalendar(cal, s, "date"); Calendar useCal = (ts.tz == null ? cal : ts.tz); useCal.set(Calendar.ERA, ts.era); useCal.set(Calendar.YEAR, ts.year); useCal.set(Calendar.MONTH, ts.month-1); useCal.set(Calendar.DAY_OF_MONTH, ts.day); if (ts.hasTime) { // Rotate it into the requested timezone before we zero out the time useCal.set(Calendar.HOUR_OF_DAY, ts.hour); useCal.set(Calendar.MINUTE, ts.minute); useCal.set(Calendar.SECOND, ts.second); useCal.set(Calendar.MILLISECOND, (ts.nanos + 500000) / 1000000); cal.setTime(new Date(useCal.getTime().getTime())); useCal = cal; } useCal.set(Calendar.HOUR_OF_DAY, 0); useCal.set(Calendar.MINUTE, 0); useCal.set(Calendar.SECOND, 0); useCal.set(Calendar.MILLISECOND, 0); Date result = new Date(useCal.getTime().getTime()); showParse("date", s, cal, result, useCal); return result; } public synchronized String toString(Calendar cal, Timestamp x) { if (cal == null) cal = defaultCal; cal.setTime(x); sbuf.setLength(0); if (x.getTime() == PGStatement.DATE_POSITIVE_INFINITY) { sbuf.append("infinity"); } else if (x.getTime() == PGStatement.DATE_NEGATIVE_INFINITY) { sbuf.append("-infinity"); } else { appendDate(sbuf, cal); sbuf.append(' '); appendTime(sbuf, cal, x.getNanos()); appendTimeZone(sbuf, cal); appendEra(sbuf, cal); } showString("timestamp", cal, x, sbuf.toString()); return sbuf.toString(); } public synchronized String toString(Calendar cal, Date x) { if (cal == null) cal = defaultCal; cal.setTime(x); sbuf.setLength(0); if (x.getTime() == PGStatement.DATE_POSITIVE_INFINITY) { sbuf.append("infinity"); } else if (x.getTime() == PGStatement.DATE_NEGATIVE_INFINITY) { sbuf.append("-infinity"); } else { appendDate(sbuf, cal); appendEra(sbuf, cal); appendTimeZone(sbuf, cal); } showString("date", cal, x, sbuf.toString()); return sbuf.toString(); } public synchronized String toString(Calendar cal, Time x) { if (cal == null) cal = defaultCal; cal.setTime(x); sbuf.setLength(0); appendTime(sbuf, cal, cal.get(Calendar.MILLISECOND) * 1000000); // The 'time' parser for <= 7.3 doesn't like timezones. if (min74) appendTimeZone(sbuf, cal); showString("time", cal, x, sbuf.toString()); return sbuf.toString(); } private static void appendDate(StringBuffer sb, Calendar cal) { int l_year = cal.get(Calendar.YEAR); // always use at least four digits for the year so very // early years, like 2, don't get misinterpreted // int l_yearlen = String.valueOf(l_year).length(); for (int i = 4; i > l_yearlen; i--) { sb.append("0"); } sb.append(l_year); sb.append('-'); int l_month = cal.get(Calendar.MONTH) + 1; if (l_month < 10) sb.append('0'); sb.append(l_month); sb.append('-'); int l_day = cal.get(Calendar.DAY_OF_MONTH); if (l_day < 10) sb.append('0'); sb.append(l_day); } private static void appendTime(StringBuffer sb, Calendar cal, int nanos) { int hours = cal.get(Calendar.HOUR_OF_DAY); if (hours < 10) sb.append('0'); sb.append(hours); sb.append(':'); int minutes = cal.get(Calendar.MINUTE); if (minutes < 10) sb.append('0'); sb.append(minutes); sb.append(':'); int seconds = cal.get(Calendar.SECOND); if (seconds < 10) sb.append('0'); sb.append(seconds); // Add nanoseconds. // This won't work for server versions < 7.2 which only want // a two digit fractional second, but we don't need to support 7.1 // anymore and getting the version number here is difficult. // char[] decimalStr = {'0', '0', '0', '0', '0', '0', '0', '0', '0'}; char[] nanoStr = Integer.toString(nanos).toCharArray(); System.arraycopy(nanoStr, 0, decimalStr, decimalStr.length - nanoStr.length, nanoStr.length); sb.append('.'); sb.append(decimalStr, 0, 6); } private void appendTimeZone(StringBuffer sb, java.util.Calendar cal) { int offset = (cal.get(Calendar.ZONE_OFFSET) + cal.get(Calendar.DST_OFFSET)) / 1000; int absoff = Math.abs(offset); int hours = absoff / 60 / 60; int mins = (absoff - hours * 60 * 60) / 60; int secs = absoff - hours * 60 * 60 - mins * 60; sb.append((offset >= 0) ? " +" : " -"); if (hours < 10) sb.append('0'); sb.append(hours); sb.append(':'); if (mins < 10) sb.append('0'); sb.append(mins); if (min82) { sb.append(':'); if (secs < 10) sb.append('0'); sb.append(secs); } } private static void appendEra(StringBuffer sb, Calendar cal) { if (cal.get(Calendar.ERA) == GregorianCalendar.BC) { sb.append(" BC"); } } private static int skipWhitespace(char []s, int start) { int slen = s.length; for (int i=start; i<slen; i++) { if (!Character.isSpace(s[i])) return i; } return slen; } private static int firstNonDigit(char []s, int start) { int slen = s.length; for (int i=start; i<slen; i++) { if (!Character.isDigit(s[i])) { return i; } } return slen; } private static int number(char []s, int start, int end) { if (start >= end) { throw new NumberFormatException(); } int n=0; for ( int i=start; i < end; i++) { n = 10 * n + (s[i]-'0'); } return n; } private static char charAt(char []s, int pos) { if (pos >= 0 && pos < s.length) { return s[pos]; } return '\0'; } /** * Returns the SQL Date object matching the given bytes with * {@link Oid#DATE}. * * @param tz The timezone used. * @param bytes The binary encoded date value. * @return The parsed date object. * @throws PSQLException If binary format could not be parsed. */ public Date toDateBin(TimeZone tz, byte[] bytes) throws PSQLException { if (bytes.length != 4) { throw new PSQLException(GT.tr("Unsupported binary encoding of {0}.", "date"), PSQLState.BAD_DATETIME_FORMAT); } int days = ByteConverter.int4(bytes, 0); if (tz == null) { tz = defaultTz; } long secs = toJavaSecs(days * 86400L); long millis = secs * 1000L; int offset = tz.getOffset(millis); if (millis <= PGStatement.DATE_NEGATIVE_SMALLER_INFINITY) { millis = PGStatement.DATE_NEGATIVE_INFINITY; offset = 0; } else if (millis >= PGStatement.DATE_POSITIVE_SMALLER_INFINITY) { millis = PGStatement.DATE_POSITIVE_INFINITY; offset = 0; } return new Date(millis - offset); } /** * Returns the SQL Time object matching the given bytes with * {@link Oid#TIME} or {@link Oid#TIMETZ}. * * @param tz The timezone used when received data is {@link Oid#TIME}, * ignored if data already contains {@link Oid#TIMETZ}. * @param bytes The binary encoded time value. * @return The parsed time object. * @throws PSQLException If binary format could not be parsed. */ public Time toTimeBin(TimeZone tz, byte[] bytes) throws PSQLException { if ((bytes.length != 8 && bytes.length != 12)) { throw new PSQLException(GT.tr("Unsupported binary encoding of {0}.", "time"), PSQLState.BAD_DATETIME_FORMAT); } long millis; int timeOffset; if (usesDouble) { double time = ByteConverter.float8(bytes, 0); millis = (long) (time * 1000); } else { long time = ByteConverter.int8(bytes, 0); millis = time / 1000; } if (bytes.length == 12) { timeOffset = ByteConverter.int4(bytes, 8); timeOffset *= -1000; } else { if (tz == null) { tz = defaultTz; } timeOffset = tz.getOffset(millis); } millis -= timeOffset; return new Time(millis); } /** * Returns the SQL Timestamp object matching the given bytes with * {@link Oid#TIMESTAMP} or {@link Oid#TIMESTAMPTZ}. * * @param tz The timezone used when received data is {@link Oid#TIMESTAMP}, * ignored if data already contains {@link Oid#TIMESTAMPTZ}. * @param bytes The binary encoded timestamp value. * @param timestamptz True if the binary is in GMT. * @return The parsed timestamp object. * @throws PSQLException If binary format could not be parsed. */ public Timestamp toTimestampBin(TimeZone tz, byte[] bytes, boolean timestamptz) throws PSQLException { if (bytes.length != 8) { throw new PSQLException(GT.tr("Unsupported binary encoding of {0}.", "timestamp"), PSQLState.BAD_DATETIME_FORMAT); } long secs; int nanos; if (usesDouble) { double time = ByteConverter.float8(bytes, 0); if (time == Double.POSITIVE_INFINITY) { return new Timestamp(PGStatement.DATE_POSITIVE_INFINITY); } else if (time == Double.NEGATIVE_INFINITY) { return new Timestamp(PGStatement.DATE_NEGATIVE_INFINITY); } secs = (long) time; nanos = (int) ((time - secs) * 1000000); } else { long time = ByteConverter.int8(bytes, 0); // compatibility with text based receiving, not strictly necessary // and can actually be confusing because there are timestamps // that are larger than infinite if (time == Long.MAX_VALUE) { return new Timestamp(PGStatement.DATE_POSITIVE_INFINITY); } else if (time == Long.MIN_VALUE) { return new Timestamp(PGStatement.DATE_NEGATIVE_INFINITY); } secs = time / 1000000; nanos = (int) (time - secs * 1000000); } if (nanos < 0) { secs--; nanos += 1000000; } nanos *= 1000; secs = toJavaSecs(secs); long millis = secs * 1000L; if (!timestamptz) { if (tz == null) { tz = defaultTz; } millis -= tz.getOffset(millis) + tz.getDSTSavings(); } Timestamp ts = new Timestamp(millis); ts.setNanos(nanos); return ts; } /** * Extracts the date part from a timestamp. * * @param timestamp The timestamp from which to extract the date. * @param tz The time zone of the date. * @return The extracted date. */ public Date convertToDate(Timestamp timestamp, TimeZone tz) { long millis = timestamp.getTime(); // no adjustments for the inifity hack values if (millis <= PGStatement.DATE_NEGATIVE_INFINITY || millis >= PGStatement.DATE_POSITIVE_INFINITY) { return new Date(millis); } if (tz == null) { tz = defaultTz; } int offset = tz.getOffset(millis); long timePart = millis % ONEDAY; if (timePart + offset >= ONEDAY) { millis += ONEDAY; } millis -= timePart; millis -= offset; return new Date(millis); } /** * Extracts the time part from a timestamp. * * @param timestamp The timestamp from which to extract the time. * @param tz The time zone of the time. * @return The extracted time. */ public Time convertToTime(Timestamp timestamp, TimeZone tz) { long millis = timestamp.getTime(); if (tz == null) { tz = defaultTz; } int offset = tz.getOffset(millis); long low = - tz.getOffset(millis); long high = low + ONEDAY; if (millis < low) { do { millis += ONEDAY; } while (millis < low); } else if (millis >= high) { do { millis -= ONEDAY; } while (millis > high); } return new Time(millis); } /** * Returns the given time value as String matching what the * current postgresql server would send in text mode. */ public String timeToString(java.util.Date time) { long millis = time.getTime(); if (millis <= PGStatement.DATE_NEGATIVE_INFINITY) { return "-infinity"; } if (millis >= PGStatement.DATE_POSITIVE_INFINITY) { return "infinity"; } return time.toString(); } /** * Converts the given postgresql seconds to java seconds. * Reverse engineered by inserting varying dates to postgresql * and tuning the formula until the java dates matched. * See {@link #toPgSecs} for the reverse operation. * * @param secs Postgresql seconds. * @return Java seconds. */ private static long toJavaSecs(long secs) { // postgres epoc to java epoc secs += 946684800L; // Julian/Gregorian calendar cutoff point if (secs < -12219292800L) { // October 4, 1582 -> October 15, 1582 secs += 86400 * 10; if (secs < -14825808000L) { // 1500-02-28 -> 1500-03-01 int extraLeaps = (int) ((secs + 14825808000L) / 3155760000L); extraLeaps--; extraLeaps -= extraLeaps / 4; secs += extraLeaps * 86400L; } } return secs; } /** * Converts the given java seconds to postgresql seconds. * See {@link #toJavaSecs} for the reverse operation. * The conversion is valid for any year 100 BC onwards. * * @param secs Postgresql seconds. * @return Java seconds. */ private static long toPgSecs(long secs) { // java epoc to postgres epoc secs -= 946684800L; // Julian/Greagorian calendar cutoff point if (secs < -13165977600L) { // October 15, 1582 -> October 4, 1582 secs -= 86400 * 10; if (secs < -15773356800L) { // 1500-03-01 -> 1500-02-28 int years = (int) ((secs + 15773356800L) / -3155823050L); years++; years -= years/4; secs += years * 86400; } } return secs; } /** * Converts the SQL Date to binary representation for {@link Oid#DATE}. * * @param tz The timezone used. * @param bytes The binary encoded date value. * @throws PSQLException If binary format could not be parsed. */ public void toBinDate(TimeZone tz, byte[] bytes, Date value) throws PSQLException { long millis = value.getTime(); if (tz == null) { tz = defaultTz; } millis += tz.getOffset(millis); long secs = toPgSecs(millis / 1000); ByteConverter.int4(bytes, 0, (int) (secs / 86400)); } }
use DSTSavings when converting to timestamp
org/postgresql/jdbc2/TimestampUtils.java
use DSTSavings when converting to timestamp
<ide><path>rg/postgresql/jdbc2/TimestampUtils.java <ide> /*------------------------------------------------------------------------- <ide> * <del>* Copyright (c) 2003-2011, PostgreSQL Global Development Group <add>* Copyright (c) 2003-2014, PostgreSQL Global Development Group <ide> * <ide> * <ide> *------------------------------------------------------------------------- <ide> if (tz == null) { <ide> tz = defaultTz; <ide> } <del> int offset = tz.getOffset(millis); <add> int offset = tz.getOffset(millis) + tz.getDSTSavings(); <ide> long timePart = millis % ONEDAY; <ide> if (timePart + offset >= ONEDAY) { <ide> millis += ONEDAY;
JavaScript
mit
e5837a86ddc49b4dcdbabfabae61d9213982651e
0
k15z/soccer-ai,k15z/soccer-ai
/** * The Engine class does everything from doing the math for the simulation * to rendering the canvas after every frame is processed. * * Usage: var engine = new Engine(); engine.setCanvas(document.getElementById('field')); // engine.setPlayer1(Player); // engine.setPlayer2(Player); function step(timestamp) { engine.drawFrame(); if (!engine.isDone()) window.requestAnimationFrame(step); } window.requestAnimationFrame(step); * * @author Kevin Zhang & Felipe Hofmann */ function Engine() { var IS_DONE = false; var MAX_SPEED = 2; var NUM_PLAYER = 6; var LINE_WIDTH = 5; var GOAL_HEIGHT = 200; var FIELD_WIDTH = 1100; var FIELD_HEIGHT = 700; var PLAYER_RADIUS = 25; var cvs = false; var ctx = false; var team1 = []; var team2 = []; var time = 0; /** * This function prepares the canvas by setting the width and height and * then calling the `drawField` function to fill the canvas with a * beautiful forest green background. It also stores references to the * canvas and context variables. */ function setCanvas(canvas) { cvs = canvas; ctx = cvs.getContext("2d"); cvs.width = FIELD_WIDTH; cvs.height = FIELD_HEIGHT; } /** * Create NUM_PLAYER instances of the Player function, and append each * instance to the team1 array. Each instances is placed at a random * location on team1's side of the field. */ function setPlayer1(Player) { for (var p = 0; p < NUM_PLAYER; p++) { var player = new Player() player.id = p; team1.push({ x: Math.random() * (FIELD_WIDTH/2 - 2*PLAYER_RADIUS) + PLAYER_RADIUS, y: Math.random() * (FIELD_HEIGHT - 2*PLAYER_RADIUS) + PLAYER_RADIUS, vx: 0, vy: 0, player: player }); } } /** * Create NUM_PLAYER instances of the Player function, and append each * instance to the team2 array. Each instances is placed at a random * location on team2's side of the field. */ function setPlayer2(Player) { for (var p = 0; p < NUM_PLAYER; p++) { var player = new Player() player.id = p; team2.push({ x: Math.random() * (FIELD_WIDTH/2 - 2*PLAYER_RADIUS) + FIELD_WIDTH/2 + PLAYER_RADIUS, y: Math.random() * (FIELD_HEIGHT - 2*PLAYER_RADIUS) + PLAYER_RADIUS, vx: 0, vy: 0, player: player }); } } /** * Draws the field. Computes the state. Simulates a step. And increments * the time. */ function drawFrame() { var goal = updateView(); var state = currentState(goal); simulateStep(state); time++; } /** * Draw the background, players, and goals. Return an object describing * the location of the goals. */ function updateView() { // fill background ctx.fillStyle = "#009900"; ctx.fillRect(0, 0, FIELD_WIDTH, FIELD_HEIGHT); // draw half-way line ctx.lineWidth = LINE_WIDTH; ctx.beginPath(); ctx.strokeStyle = "#FFFFFF"; ctx.moveTo(FIELD_WIDTH/2, 0); ctx.lineTo(FIELD_WIDTH/2, FIELD_HEIGHT); ctx.stroke(); ctx.closePath(); // draw center circle ctx.beginPath(); ctx.arc(FIELD_WIDTH/2, FIELD_HEIGHT/2, 75, 0, 2*Math.PI); ctx.stroke(); ctx.closePath(); // draw end zones ctx.strokeRect(0 - LINE_WIDTH, FIELD_HEIGHT/2 - GOAL_HEIGHT, GOAL_HEIGHT, GOAL_HEIGHT*2); ctx.strokeRect(FIELD_WIDTH - GOAL_HEIGHT + LINE_WIDTH, FIELD_HEIGHT/2 - GOAL_HEIGHT, GOAL_HEIGHT, GOAL_HEIGHT*2); // draw players ctx.fillStyle = "deepskyblue"; for (var p = 0; p < NUM_PLAYER; p++) { ctx.beginPath(); ctx.arc(team1[p].x, team1[p].y, PLAYER_RADIUS, 0, Math.PI*2); ctx.fill(); ctx.closePath(); } ctx.fillStyle = "salmon"; for (var p = 0; p < NUM_PLAYER; p++) { ctx.beginPath(); ctx.arc(team2[p].x, team2[p].y, PLAYER_RADIUS, 0, Math.PI*2); ctx.fill(); ctx.closePath(); } // draw goals var goal = [ { x1: LINE_WIDTH, y1: FIELD_HEIGHT/2 - GOAL_HEIGHT/2, x2: (LINE_WIDTH) + (LINE_WIDTH*3), y2: (FIELD_HEIGHT/2 - GOAL_HEIGHT/2) + (GOAL_HEIGHT) }, { x1: FIELD_WIDTH - LINE_WIDTH*3 - LINE_WIDTH, y1: FIELD_HEIGHT/2 - GOAL_HEIGHT/2, x2: (FIELD_WIDTH - LINE_WIDTH*3 - LINE_WIDTH) + (LINE_WIDTH*3), y2: (FIELD_HEIGHT/2 - GOAL_HEIGHT/2) + (GOAL_HEIGHT) } ]; ctx.fillStyle = "#FFFFFF"; ctx.fillRect(goal[0].x1, goal[0].y1, goal[0].x2 - goal[0].x1, goal[0].y2 - goal[0].y1); ctx.fillRect(goal[1].x1, goal[1].y1, goal[1].x2 - goal[1].x1, goal[1].y2 - goal[1].y1); return goal; }; /** * Compute the state of the game using the location of the goals. */ function currentState(goal) { return { time: time, goal: goal, team1: team1, team2: team2 } } /** * Call the action function on each player using the given state object. * Apply the returned acceleration vector. */ function simulateStep(state) { for (var p = 0; p < NUM_PLAYER; p++) { var vector = team1[p].player.action(state); team1[p].x += team1[p].vx; if (team1[p].x < 0 + PLAYER_RADIUS) team1[p].x = 0 + PLAYER_RADIUS; if (team1[p].x > FIELD_WIDTH - PLAYER_RADIUS) team1[p].x = FIELD_WIDTH - PLAYER_RADIUS; team1[p].y += team1[p].vy; if (team1[p].y < 0 + PLAYER_RADIUS) team1[p].y = 0 + PLAYER_RADIUS; if (team1[p].y > FIELD_HEIGHT - PLAYER_RADIUS) team1[p].y = FIELD_HEIGHT - PLAYER_RADIUS; team1[p].vx += vector.x; if (Math.abs(team1[p].vx) > MAX_SPEED) team1[p].vx = MAX_SPEED*team1[p].vx/Math.abs(team1[p].vx); team1[p].vy += vector.y; if (Math.abs(team1[p].vy) > MAX_SPEED) team1[p].vy = MAX_SPEED*team1[p].vy/Math.abs(team1[p].vy); } for (var p = 0; p < NUM_PLAYER; p++) { var vector = team2[p].player.action(state); team2[p].x += team2[p].vx; if (team2[p].x < 0 + PLAYER_RADIUS) team2[p].x = 0 + PLAYER_RADIUS; if (team2[p].x > FIELD_WIDTH - PLAYER_RADIUS) team2[p].x = FIELD_WIDTH - PLAYER_RADIUS; team2[p].y += team2[p].vy; if (team2[p].y < 0 + PLAYER_RADIUS) team2[p].y = 0 + PLAYER_RADIUS; if (team2[p].y > FIELD_HEIGHT - PLAYER_RADIUS) team2[p].y = FIELD_HEIGHT - PLAYER_RADIUS; team2[p].vx += vector.x; if (Math.abs(team2[p].vx) > MAX_SPEED) team2[p].vx = MAX_SPEED*team2[p].vx/Math.abs(team2[p].vx); team2[p].vy += vector.y; if (Math.abs(team2[p].vy) > MAX_SPEED) team2[p].vy = MAX_SPEED*team2[p].vy/Math.abs(team2[p].vy); } } var exports = {}; exports.setCanvas = setCanvas; exports.setPlayer1 = setPlayer1; exports.setPlayer2 = setPlayer2; exports.drawFrame = drawFrame; return exports; }
src/engine.js
/** * The Engine class does everything from doing the math for the simulation * to rendering the canvas after every frame is processed. * * Usage: var engine = new Engine(); engine.setCanvas(document.getElementById('field')); // engine.setPlayer1(Player); // engine.setPlayer2(Player); function step(timestamp) { engine.drawFrame(); if (!engine.isDone()) window.requestAnimationFrame(step); } window.requestAnimationFrame(step); * * @author Kevin Zhang & Felipe Hofmann */ function Engine() { var IS_DONE = false; var MAX_SPEED = 2; var NUM_PLAYER = 6; var LINE_WIDTH = 5; var GOAL_HEIGHT = 200; var FIELD_WIDTH = 1100; var FIELD_HEIGHT = 700; var PLAYER_RADIUS = 25; var cvs = false; var ctx = false; var team1 = []; var team2 = []; var time = 0; /** * This function prepares the canvas by setting the width and height and * then calling the `drawField` function to fill the canvas with a * beautiful forest green background. It also stores references to the * canvas and context variables. */ function setCanvas(canvas) { cvs = canvas; ctx = cvs.getContext("2d"); cvs.width = FIELD_WIDTH; cvs.height = FIELD_HEIGHT; } /** * Create NUM_PLAYER instances of the Player function, and append each * instance to the team1 array. Each instances is placed at a random * location on team1's side of the field. */ function setPlayer1(Player) { for (var p = 0; p < NUM_PLAYER; p++) { var player = new Player() player.id = p; team1.push({ x: Math.random() * (FIELD_WIDTH/2 - 2*PLAYER_RADIUS) + PLAYER_RADIUS, y: Math.random() * (FIELD_HEIGHT - 2*PLAYER_RADIUS) + PLAYER_RADIUS, vx: 0, vy: 0, player: player }); } } /** * Create NUM_PLAYER instances of the Player function, and append each * instance to the team2 array. Each instances is placed at a random * location on team2's side of the field. */ function setPlayer2(Player) { for (var p = 0; p < NUM_PLAYER; p++) { var player = new Player() player.id = p; team2.push({ x: Math.random() * (FIELD_WIDTH/2 - 2*PLAYER_RADIUS) + FIELD_WIDTH/2 + PLAYER_RADIUS, y: Math.random() * (FIELD_HEIGHT - 2*PLAYER_RADIUS) + PLAYER_RADIUS, vx: 0, vy: 0, player: player }); } } /** * Draws the field. Computes the state. Simulates a step. And increments * the time. */ function drawFrame() { var goal = drawField(); var state = computeState(goal); simulateStep(state); time++; } /** * Draw the background, players, and goals. Return an object describing * the location of the goals. */ function drawField() { // fill background ctx.fillStyle = "#009900"; ctx.fillRect(0, 0, FIELD_WIDTH, FIELD_HEIGHT); // draw half-way line ctx.lineWidth = LINE_WIDTH; ctx.beginPath(); ctx.strokeStyle = "#FFFFFF"; ctx.moveTo(FIELD_WIDTH/2, 0); ctx.lineTo(FIELD_WIDTH/2, FIELD_HEIGHT); ctx.stroke(); ctx.closePath(); // draw center circle ctx.beginPath(); ctx.arc(FIELD_WIDTH/2, FIELD_HEIGHT/2, 75, 0, 2*Math.PI); ctx.stroke(); ctx.closePath(); // draw end zones ctx.strokeRect(0 - LINE_WIDTH, FIELD_HEIGHT/2 - GOAL_HEIGHT, GOAL_HEIGHT, GOAL_HEIGHT*2); ctx.strokeRect(FIELD_WIDTH - GOAL_HEIGHT + LINE_WIDTH, FIELD_HEIGHT/2 - GOAL_HEIGHT, GOAL_HEIGHT, GOAL_HEIGHT*2); // draw players ctx.fillStyle = "deepskyblue"; for (var p = 0; p < NUM_PLAYER; p++) { ctx.beginPath(); ctx.arc(team1[p].x, team1[p].y, PLAYER_RADIUS, 0, Math.PI*2); ctx.fill(); ctx.closePath(); } ctx.fillStyle = "salmon"; for (var p = 0; p < NUM_PLAYER; p++) { ctx.beginPath(); ctx.arc(team2[p].x, team2[p].y, PLAYER_RADIUS, 0, Math.PI*2); ctx.fill(); ctx.closePath(); } // draw goals var goal = [ { x1: LINE_WIDTH, y1: FIELD_HEIGHT/2 - GOAL_HEIGHT/2, x2: (LINE_WIDTH) + (LINE_WIDTH*3), y2: (FIELD_HEIGHT/2 - GOAL_HEIGHT/2) + (GOAL_HEIGHT) }, { x1: FIELD_WIDTH - LINE_WIDTH*3 - LINE_WIDTH, y1: FIELD_HEIGHT/2 - GOAL_HEIGHT/2, x2: (FIELD_WIDTH - LINE_WIDTH*3 - LINE_WIDTH) + (LINE_WIDTH*3), y2: (FIELD_HEIGHT/2 - GOAL_HEIGHT/2) + (GOAL_HEIGHT) } ]; ctx.fillStyle = "#FFFFFF"; ctx.fillRect(goal[0].x1, goal[0].y1, goal[0].x2 - goal[0].x1, goal[0].y2 - goal[0].y1); ctx.fillRect(goal[1].x1, goal[1].y1, goal[1].x2 - goal[1].x1, goal[1].y2 - goal[1].y1); return goal; }; /** * Compute the state of the game using the location of the goals. */ function computeState(goal) { return { time: time } } /** * Call the action function on each player using the given state object. * Apply the returned acceleration vector. */ function simulateStep(state) { for (var p = 0; p < NUM_PLAYER; p++) { var vector = false; vector = team1[p].player.action(state); team1[p].x += team1[p].vx; team1[p].y += team1[p].vy; team1[p].vx += vector.x; if (Math.abs(team1[p].vx) > MAX_SPEED) team1[p].vx = MAX_SPEED*team1[p].vx/Math.abs(team1[p].vx); team1[p].vy += vector.y; if (Math.abs(team1[p].vy) > MAX_SPEED) team1[p].vy = MAX_SPEED*team1[p].vy/Math.abs(team1[p].vy); vector = team2[p].player.action(state); team2[p].x += team2[p].vx; team2[p].y += team2[p].vy; team2[p].vx += vector.x; if (Math.abs(team2[p].vx) > MAX_SPEED) team2[p].vx = MAX_SPEED*team2[p].vx/Math.abs(team2[p].vx); team2[p].vy += vector.y; if (Math.abs(team2[p].vy) > MAX_SPEED) team2[p].vy = MAX_SPEED*team2[p].vy/Math.abs(team2[p].vy); } } var exports = {}; exports.setCanvas = setCanvas; exports.setPlayer1 = setPlayer1; exports.setPlayer2 = setPlayer2; exports.drawFrame = drawFrame; return exports; }
Pass state variables
src/engine.js
Pass state variables
<ide><path>rc/engine.js <ide> * the time. <ide> */ <ide> function drawFrame() { <del> var goal = drawField(); <del> var state = computeState(goal); <add> var goal = updateView(); <add> var state = currentState(goal); <ide> simulateStep(state); <ide> time++; <ide> } <ide> * Draw the background, players, and goals. Return an object describing <ide> * the location of the goals. <ide> */ <del> function drawField() { <add> function updateView() { <ide> // fill background <ide> ctx.fillStyle = "#009900"; <ide> ctx.fillRect(0, 0, FIELD_WIDTH, FIELD_HEIGHT); <ide> /** <ide> * Compute the state of the game using the location of the goals. <ide> */ <del> function computeState(goal) { <add> function currentState(goal) { <ide> return { <del> time: time <add> time: time, <add> goal: goal, <add> team1: team1, <add> team2: team2 <ide> } <ide> } <ide> <ide> */ <ide> function simulateStep(state) { <ide> for (var p = 0; p < NUM_PLAYER; p++) { <del> var vector = false; <del> vector = team1[p].player.action(state); <add> var vector = team1[p].player.action(state); <add> <ide> team1[p].x += team1[p].vx; <add> if (team1[p].x < 0 + PLAYER_RADIUS) <add> team1[p].x = 0 + PLAYER_RADIUS; <add> if (team1[p].x > FIELD_WIDTH - PLAYER_RADIUS) <add> team1[p].x = FIELD_WIDTH - PLAYER_RADIUS; <add> <ide> team1[p].y += team1[p].vy; <add> if (team1[p].y < 0 + PLAYER_RADIUS) <add> team1[p].y = 0 + PLAYER_RADIUS; <add> if (team1[p].y > FIELD_HEIGHT - PLAYER_RADIUS) <add> team1[p].y = FIELD_HEIGHT - PLAYER_RADIUS; <add> <ide> team1[p].vx += vector.x; <ide> if (Math.abs(team1[p].vx) > MAX_SPEED) <ide> team1[p].vx = MAX_SPEED*team1[p].vx/Math.abs(team1[p].vx); <add> <ide> team1[p].vy += vector.y; <ide> if (Math.abs(team1[p].vy) > MAX_SPEED) <ide> team1[p].vy = MAX_SPEED*team1[p].vy/Math.abs(team1[p].vy); <del> <del> vector = team2[p].player.action(state); <add> } <add> <add> for (var p = 0; p < NUM_PLAYER; p++) { <add> var vector = team2[p].player.action(state); <add> <ide> team2[p].x += team2[p].vx; <add> if (team2[p].x < 0 + PLAYER_RADIUS) <add> team2[p].x = 0 + PLAYER_RADIUS; <add> if (team2[p].x > FIELD_WIDTH - PLAYER_RADIUS) <add> team2[p].x = FIELD_WIDTH - PLAYER_RADIUS; <add> <ide> team2[p].y += team2[p].vy; <add> if (team2[p].y < 0 + PLAYER_RADIUS) <add> team2[p].y = 0 + PLAYER_RADIUS; <add> if (team2[p].y > FIELD_HEIGHT - PLAYER_RADIUS) <add> team2[p].y = FIELD_HEIGHT - PLAYER_RADIUS; <add> <ide> team2[p].vx += vector.x; <ide> if (Math.abs(team2[p].vx) > MAX_SPEED) <ide> team2[p].vx = MAX_SPEED*team2[p].vx/Math.abs(team2[p].vx); <add> <ide> team2[p].vy += vector.y; <ide> if (Math.abs(team2[p].vy) > MAX_SPEED) <ide> team2[p].vy = MAX_SPEED*team2[p].vy/Math.abs(team2[p].vy);
Java
lgpl-2.1
2285ea273fc7088790100d208f281045abed5505
0
ekiwi/jade-mirror,ekiwi/jade-mirror,ekiwi/jade-mirror,ekiwi/jade-mirror
package jade.core; import java.util.Enumeration; import java.util.Hashtable; import java.util.Vector; import java.rmi.*; import java.rmi.server.UnicastRemoteObject; import jade.domain.ams; import jade.domain.df; import jade.domain.AgentManagementOntology; import jade.domain.FIPAException; import jade.domain.AgentAlreadyRegisteredException; public class AgentPlatformImpl extends AgentContainerImpl implements AgentPlatform { // Initial size of agent hash table private static final int GLOBALMAP_SIZE = 100; // Load factor of agent hash table private static final float GLOBALMAP_LOAD_FACTOR = 0.25f; private ams theAMS; private df defaultDF; private Vector containers = new Vector(); private Hashtable platformAgents = new Hashtable(GLOBALMAP_SIZE, GLOBALMAP_LOAD_FACTOR); private void initAMS() { System.out.print("Starting AMS... "); theAMS = new ams(this, "ams"); // Subscribe as a listener for the AMS agent theAMS.addCommListener(this); // Insert AMS into local agents table localAgents.put("ams", theAMS); AgentDescriptor desc = new AgentDescriptor(); desc.setAll("ams", myDispatcher, "ams@" + platformAddress, null, null, null, Agent.AP_INITIATED); desc.setName("ams"); desc.setDemux(myDispatcher); platformAgents.put(desc.getName(), desc); System.out.println("AMS OK"); } private void initACC() { } private void initDF() { System.out.print("Starting Default DF... "); defaultDF = new df(); // Subscribe as a listener for the AMS agent defaultDF.addCommListener(this); // Insert AMS into local agents table localAgents.put("df", defaultDF); AgentDescriptor desc = new AgentDescriptor(); desc.setAll("df", myDispatcher, "df@" + platformAddress, null, null, null, Agent.AP_INITIATED); desc.setName("df"); desc.setDemux(myDispatcher); platformAgents.put(desc.getName(), desc); System.out.println("DF OK"); } public AgentPlatformImpl() throws RemoteException { initAMS(); initACC(); initDF(); } public void addContainer(AgentContainer ac) throws RemoteException { System.out.println("Adding container..."); containers.addElement(ac); } public void removeContainer(AgentContainer ac) throws RemoteException { System.out.println("Removing container..."); containers.removeElement(ac); } public void bornAgent(AgentDescriptor desc) throws RemoteException { System.out.println("Born agent " + desc.getName()); platformAgents.put(desc.getName(), desc); } public void deadAgent(String name) throws RemoteException { System.out.println("Dead agent " + name); platformAgents.remove(name); // FIXME: Must update all container caches } public AgentDescriptor lookup(String agentName) throws RemoteException, NotFoundException { System.out.println("Looking up " + agentName + " in agents table..."); Object o = platformAgents.get(agentName); if(o == null) throw new NotFoundException("Failed to find " + agentName); else return (AgentDescriptor)o; } // These methods are to be used only by AMS agent. // This one is called in response to a 'register-agent' action public void AMSNewData(String agentName, String address, String signature, String delegateAgent, String forwardAddress, String APState) throws FIPAException, AgentAlreadyRegisteredException { try { AgentDescriptor ad = (AgentDescriptor)platformAgents.get(agentName); if(ad == null) throw new NotFoundException("Failed to find " + agentName); if(ad.getAPState() != Agent.AP_INITIATED) { throw new AgentAlreadyRegisteredException(); } AgentManagementOntology o = AgentManagementOntology.instance(); int state = o.getAPStateByName(APState); MessageDispatcher md = ad.getDemux(); // Preserve original MessageDispatcher ad.setAll(agentName, md, address, signature, delegateAgent, forwardAddress, state); } catch(NotFoundException nfe) { nfe.printStackTrace(); } } // This one is called in response to a 'modify-agent' action public void AMSChangeData(String agentName, String address, String signature, String delegateAgent, String forwardAddress, String APState) throws FIPAException { try { AgentDescriptor ad = (AgentDescriptor)platformAgents.get(agentName); if(ad == null) throw new NotFoundException("Failed to find " + agentName); if(address != null) ad.setAddress(address); if(signature != null) ad.setSignature(signature); if(signature != null) ad.setDelegateAgent(delegateAgent); if(forwardAddress != null) ad.setAddress(forwardAddress); if(APState != null) { AgentManagementOntology o = AgentManagementOntology.instance(); int state = o.getAPStateByName(APState); ad.setAPState(state); } } catch(NotFoundException nfe) { nfe.printStackTrace(); } } // This one is called in response to a 'deregister-agent' action public void AMSRemoveData(String agentName, String address, String signature, String delegateAgent, String forwardAddress, String APState) throws FIPAException { AgentDescriptor ad = (AgentDescriptor)platformAgents.remove(agentName); if(ad == null) throw new jade.domain.UnableToDeregisterException(); } public void AMSDumpData() { Enumeration descriptors = platformAgents.elements(); while(descriptors.hasMoreElements()) { AgentDescriptor desc = (AgentDescriptor)descriptors.nextElement(); desc.dump(); } } public void AMSDumpData(String agentName) { AgentDescriptor desc = (AgentDescriptor)platformAgents.get(agentName); desc.dump(); } }
src/jade/core/AgentPlatformImpl.java
package jade.core; import java.util.Enumeration; import java.util.Hashtable; import java.util.Vector; import java.rmi.*; import java.rmi.server.UnicastRemoteObject; import jade.domain.ams; import jade.domain.AgentManagementOntology; import jade.domain.FIPAException; import jade.domain.AgentAlreadyRegisteredException; public class AgentPlatformImpl extends AgentContainerImpl implements AgentPlatform { // Initial size of agent hash table private static final int GLOBALMAP_SIZE = 100; // Load factor of agent hash table private static final float GLOBALMAP_LOAD_FACTOR = 0.25f; private ams theAMS; private Vector containers = new Vector(); private Hashtable platformAgents = new Hashtable(GLOBALMAP_SIZE, GLOBALMAP_LOAD_FACTOR); private void initAMS() { System.out.print("Starting AMS... "); theAMS = new ams(this, "ams"); // Subscribe as a listener for the AMS agent theAMS.addCommListener(this); // Insert AMS into local agents table localAgents.put("ams", theAMS); AgentDescriptor desc = new AgentDescriptor(); desc.setAll("ams", myDispatcher, "ams@" + platformAddress, null, null, null, Agent.AP_INITIATED); desc.setName("ams"); desc.setDemux(myDispatcher); platformAgents.put(desc.getName(), desc); System.out.println("AMS OK"); } private void initACC() { } private void initDF() { } public AgentPlatformImpl() throws RemoteException { initAMS(); initACC(); initDF(); } public void addContainer(AgentContainer ac) throws RemoteException { System.out.println("Adding container..."); containers.addElement(ac); } public void removeContainer(AgentContainer ac) throws RemoteException { System.out.println("Removing container..."); containers.removeElement(ac); } public void bornAgent(AgentDescriptor desc) throws RemoteException { System.out.println("Born agent " + desc.getName()); platformAgents.put(desc.getName(), desc); } public void deadAgent(String name) throws RemoteException { System.out.println("Dead agent " + name); platformAgents.remove(name); // FIXME: Must update all container caches } public AgentDescriptor lookup(String agentName) throws RemoteException, NotFoundException { System.out.println("Looking up " + agentName + " in agents table..."); Object o = platformAgents.get(agentName); if(o == null) throw new NotFoundException("Failed to find " + agentName); else return (AgentDescriptor)o; } // These methods are to be used only by AMS agent. // This one is called in response to a 'register-agent' action public void AMSNewData(String agentName, String address, String signature, String delegateAgent, String forwardAddress, String APState) throws FIPAException, AgentAlreadyRegisteredException { try { AgentDescriptor ad = (AgentDescriptor)platformAgents.get(agentName); if(ad == null) throw new NotFoundException("Failed to find " + agentName); if(ad.getAPState() != Agent.AP_INITIATED) { throw new AgentAlreadyRegisteredException(); } AgentManagementOntology o = AgentManagementOntology.instance(); int state = o.getAPStateByName(APState); MessageDispatcher md = ad.getDemux(); // Preserve original MessageDispatcher ad.setAll(agentName, md, address, signature, delegateAgent, forwardAddress, state); } catch(NotFoundException nfe) { nfe.printStackTrace(); } } // This one is called in response to a 'modify-agent' action public void AMSChangeData(String agentName, String address, String signature, String delegateAgent, String forwardAddress, String APState) throws FIPAException { try { AgentDescriptor ad = (AgentDescriptor)platformAgents.get(agentName); if(ad == null) throw new NotFoundException("Failed to find " + agentName); if(address != null) ad.setAddress(address); if(signature != null) ad.setSignature(signature); if(signature != null) ad.setDelegateAgent(delegateAgent); if(forwardAddress != null) ad.setAddress(forwardAddress); if(APState != null) { AgentManagementOntology o = AgentManagementOntology.instance(); int state = o.getAPStateByName(APState); ad.setAPState(state); } } catch(NotFoundException nfe) { nfe.printStackTrace(); } } // This one is called in response to a 'deregister-agent' action public void AMSRemoveData(String agentName, String address, String signature, String delegateAgent, String forwardAddress, String APState) throws FIPAException { AgentDescriptor ad = (AgentDescriptor)platformAgents.remove(agentName); if(ad == null) throw new jade.domain.UnableToDeregisterException(); } public void AMSDumpData() { Enumeration descriptors = platformAgents.elements(); while(descriptors.hasMoreElements()) { AgentDescriptor desc = (AgentDescriptor)descriptors.nextElement(); desc.dump(); } } public void AMSDumpData(String agentName) { AgentDescriptor desc = (AgentDescriptor)platformAgents.get(agentName); desc.dump(); } }
Added Directory Facilitator support. Now a default DF is automatically started by the Agent Platform.
src/jade/core/AgentPlatformImpl.java
Added Directory Facilitator support. Now a default DF is automatically started by the Agent Platform.
<ide><path>rc/jade/core/AgentPlatformImpl.java <ide> import java.rmi.server.UnicastRemoteObject; <ide> <ide> import jade.domain.ams; <add>import jade.domain.df; <ide> import jade.domain.AgentManagementOntology; <ide> <ide> import jade.domain.FIPAException; <ide> private static final float GLOBALMAP_LOAD_FACTOR = 0.25f; <ide> <ide> private ams theAMS; <add> private df defaultDF; <ide> <ide> private Vector containers = new Vector(); <ide> private Hashtable platformAgents = new Hashtable(GLOBALMAP_SIZE, GLOBALMAP_LOAD_FACTOR); <ide> } <ide> <ide> private void initDF() { <add> System.out.print("Starting Default DF... "); <add> defaultDF = new df(); <add> <add> // Subscribe as a listener for the AMS agent <add> defaultDF.addCommListener(this); <add> <add> // Insert AMS into local agents table <add> localAgents.put("df", defaultDF); <add> <add> AgentDescriptor desc = new AgentDescriptor(); <add> desc.setAll("df", myDispatcher, "df@" + platformAddress, null, null, null, Agent.AP_INITIATED); <add> desc.setName("df"); <add> desc.setDemux(myDispatcher); <add> <add> platformAgents.put(desc.getName(), desc); <add> System.out.println("DF OK"); <add> <ide> } <ide> <ide> public AgentPlatformImpl() throws RemoteException {
JavaScript
mit
3b79e11b5ebf89123267601f2711e6f29ebe93de
0
seppevs/migrate-mongo
const fs = require("fs-extra"); const path = require("path"); const crypto = require("crypto"); const config = require("./config"); const DEFAULT_MIGRATIONS_DIR_NAME = "migrations"; const DEFAULT_MIGRATION_EXT = ".js"; async function resolveMigrationsDirPath() { let migrationsDir; try { const configContent = await config.read(); migrationsDir = configContent.migrationsDir; // eslint-disable-line // if config file doesn't have migrationsDir key, assume default 'migrations' dir if (!migrationsDir) { migrationsDir = DEFAULT_MIGRATIONS_DIR_NAME; } } catch (err) { // config file could not be read, assume default 'migrations' dir migrationsDir = DEFAULT_MIGRATIONS_DIR_NAME; } if (path.isAbsolute(migrationsDir)) { return migrationsDir; } return path.join(process.cwd(), migrationsDir); } async function resolveMigrationFileExtension() { let migrationFileExtension; try { const configContent = await config.read(); migrationFileExtension = configContent.migrationFileExtension || DEFAULT_MIGRATION_EXT; } catch (err) { // config file could not be read, assume default extension migrationFileExtension = DEFAULT_MIGRATION_EXT; } if (migrationFileExtension && !migrationFileExtension.startsWith('.')) { throw new Error('migrationFileExtension must start with dot'); } return migrationFileExtension; } async function resolveSampleMigrationFileName() { const migrationFileExtention = await resolveMigrationFileExtension(); return `sample-migration${migrationFileExtention}`; } async function resolveSampleMigrationPath() { const migrationsDir = await resolveMigrationsDirPath(); const sampleMigrationSampleFileName = await resolveSampleMigrationFileName(); return path.join(migrationsDir, sampleMigrationSampleFileName); } module.exports = { resolve: resolveMigrationsDirPath, resolveSampleMigrationPath, resolveMigrationFileExtension, async shouldExist() { const migrationsDir = await resolveMigrationsDirPath(); try { await fs.stat(migrationsDir); } catch (err) { throw new Error(`migrations directory does not exist: ${migrationsDir}`); } }, async shouldNotExist() { const migrationsDir = await resolveMigrationsDirPath(); const error = new Error( `migrations directory already exists: ${migrationsDir}` ); try { await fs.stat(migrationsDir); throw error; } catch (err) { if (err.code !== "ENOENT") { throw error; } } }, async getFileNames() { const migrationsDir = await resolveMigrationsDirPath(); const migrationExt = await resolveMigrationFileExtension(); const files = await fs.readdir(migrationsDir); const sampleMigrationFileName = await resolveSampleMigrationFileName(); return files.filter(file => path.extname(file) === migrationExt && path.basename(file) !== sampleMigrationFileName).sort(); }, async loadMigration(fileName) { const migrationsDir = await resolveMigrationsDirPath(); return require(path.join(migrationsDir, fileName)); // eslint-disable-line }, async loadFileHash(fileName) { const migrationsDir = await resolveMigrationsDirPath(); const filePath = path.join(migrationsDir, fileName) const hash = crypto.createHash('sha256'); const input = await fs.readFile(filePath); hash.update(input); return hash.digest('hex'); }, async doesSampleMigrationExist() { const samplePath = await resolveSampleMigrationPath(); try { await fs.stat(samplePath); return true; } catch (err) { return false; } }, };
lib/env/migrationsDir.js
const fs = require("fs-extra"); const path = require("path"); const crypto = require("crypto"); const config = require("./config"); const DEFAULT_MIGRATIONS_DIR_NAME = "migrations"; const DEFAULT_MIGRATION_EXT = ".js"; async function resolveMigrationsDirPath() { let migrationsDir; try { const configContent = await config.read(); migrationsDir = configContent.migrationsDir; // eslint-disable-line // if config file doesn't have migrationsDir key, assume default 'migrations' dir if (!migrationsDir) { migrationsDir = DEFAULT_MIGRATIONS_DIR_NAME; } } catch (err) { // config file could not be read, assume default 'migrations' dir migrationsDir = DEFAULT_MIGRATIONS_DIR_NAME; } if (path.isAbsolute(migrationsDir)) { return migrationsDir; } return path.join(process.cwd(), migrationsDir); } async function resolveSampleMigrationPath() { const migrationsDir = await resolveMigrationsDirPath(); return path.join(migrationsDir, 'sample-migration.js'); } async function resolveMigrationFileExtension() { let migrationFileExtension; try { const configContent = await config.read(); migrationFileExtension = configContent.migrationFileExtension || DEFAULT_MIGRATION_EXT; } catch (err) { // config file could not be read, assume default extension migrationFileExtension = DEFAULT_MIGRATION_EXT; } if (migrationFileExtension && !migrationFileExtension.startsWith('.')) { throw new Error('migrationFileExtension must start with dot'); } return migrationFileExtension; } module.exports = { resolve: resolveMigrationsDirPath, resolveSampleMigrationPath, resolveMigrationFileExtension, async shouldExist() { const migrationsDir = await resolveMigrationsDirPath(); try { await fs.stat(migrationsDir); } catch (err) { throw new Error(`migrations directory does not exist: ${migrationsDir}`); } }, async shouldNotExist() { const migrationsDir = await resolveMigrationsDirPath(); const error = new Error( `migrations directory already exists: ${migrationsDir}` ); try { await fs.stat(migrationsDir); throw error; } catch (err) { if (err.code !== "ENOENT") { throw error; } } }, async getFileNames() { const migrationsDir = await resolveMigrationsDirPath(); const migrationExt = await resolveMigrationFileExtension(); const files = await fs.readdir(migrationsDir); return files.filter(file => path.extname(file) === migrationExt && path.basename(file) !== 'sample-migration.js').sort(); }, async loadMigration(fileName) { const migrationsDir = await resolveMigrationsDirPath(); return require(path.join(migrationsDir, fileName)); // eslint-disable-line }, async loadFileHash(fileName) { const migrationsDir = await resolveMigrationsDirPath(); const filePath = path.join(migrationsDir, fileName) const hash = crypto.createHash('sha256'); const input = await fs.readFile(filePath); hash.update(input); return hash.digest('hex'); }, async doesSampleMigrationExist() { const samplePath = await resolveSampleMigrationPath(); try { await fs.stat(samplePath); return true; } catch (err) { return false; } }, };
Made migration sample file take custom file extension into account
lib/env/migrationsDir.js
Made migration sample file take custom file extension into account
<ide><path>ib/env/migrationsDir.js <ide> return path.join(process.cwd(), migrationsDir); <ide> } <ide> <del>async function resolveSampleMigrationPath() { <del> const migrationsDir = await resolveMigrationsDirPath(); <del> return path.join(migrationsDir, 'sample-migration.js'); <del>} <del> <ide> async function resolveMigrationFileExtension() { <ide> let migrationFileExtension; <ide> try { <ide> } <ide> <ide> return migrationFileExtension; <add>} <add> <add>async function resolveSampleMigrationFileName() { <add> const migrationFileExtention = await resolveMigrationFileExtension(); <add> return `sample-migration${migrationFileExtention}`; <add>} <add> <add>async function resolveSampleMigrationPath() { <add> const migrationsDir = await resolveMigrationsDirPath(); <add> const sampleMigrationSampleFileName = await resolveSampleMigrationFileName(); <add> return path.join(migrationsDir, sampleMigrationSampleFileName); <ide> } <ide> <ide> module.exports = { <ide> const migrationsDir = await resolveMigrationsDirPath(); <ide> const migrationExt = await resolveMigrationFileExtension(); <ide> const files = await fs.readdir(migrationsDir); <del> return files.filter(file => path.extname(file) === migrationExt && path.basename(file) !== 'sample-migration.js').sort(); <add> const sampleMigrationFileName = await resolveSampleMigrationFileName(); <add> return files.filter(file => path.extname(file) === migrationExt && path.basename(file) !== sampleMigrationFileName).sort(); <ide> }, <ide> <ide> async loadMigration(fileName) {
Java
apache-2.0
54b904e77971c3b0d06a228b9d76a2e781873ae6
0
Sotera/distributed-graph-analytics,atomicjets/distributed-graph-analytics,Sotera/distributed-graph-analytics,atomicjets/distributed-graph-analytics,Sotera/distributed-graph-analytics,atomicjets/distributed-graph-analytics
package com.soteradefense.dga.weaklyconnectedcomponents; import com.soteradefense.dga.io.formats.SimpleTsvUndirectedEdgeInputFormat; import org.apache.giraph.conf.GiraphConfiguration; import org.apache.giraph.conf.ImmutableClassesGiraphConfiguration; import org.apache.giraph.io.formats.InMemoryVertexOutputFormat; import org.apache.giraph.utils.InMemoryVertexInputFormat; import org.apache.giraph.utils.InternalVertexRunner; import org.apache.giraph.utils.TestGraph; import org.apache.hadoop.io.NullWritable; import org.apache.hadoop.io.Text; import org.junit.Test; import java.util.Map; import static junit.framework.Assert.assertEquals; public class WeaklyConnectedComponentsTest { @Test public void testComputeOutput() throws Exception { GiraphConfiguration conf = new GiraphConfiguration(); conf.setComputationClass(WeaklyConnectedComponents.class); conf.setVertexOutputFormatClass(InMemoryVertexOutputFormat.class); conf.set(SimpleTsvUndirectedEdgeInputFormat.EXPECTED_NUMBER_OF_COLUMNS_KEY, "2"); TestGraph<Text,Text,NullWritable> testGraph = getGraph(conf); InMemoryVertexOutputFormat.initializeOutputGraph(conf); InternalVertexRunner.run(conf, testGraph); TestGraph<Text, Text, NullWritable> graph = InMemoryVertexOutputFormat.getOutputGraph(); assertEquals(6, graph.getVertices().size()); assertEquals("2", graph.getVertex(new Text("1")).getValue().toString()); assertEquals("2", graph.getVertex(new Text("2")).getValue().toString()); assertEquals("4", graph.getVertex(new Text("3")).getValue().toString()); assertEquals("4", graph.getVertex(new Text("4")).getValue().toString()); assertEquals("6", graph.getVertex(new Text("5")).getValue().toString()); assertEquals("6", graph.getVertex(new Text("6")).getValue().toString()); } private TestGraph<Text,Text,NullWritable> getGraph(GiraphConfiguration conf){ TestGraph<Text, Text, NullWritable> testGraph = new TestGraph<Text, Text, NullWritable>(conf); testGraph.addEdge(new Text("1"), new Text("2"), NullWritable.get()); testGraph.addEdge(new Text("2"), new Text("1"), NullWritable.get()); testGraph.addEdge(new Text("3"), new Text("4"), NullWritable.get()); testGraph.addEdge(new Text("4"), new Text("3"), NullWritable.get()); testGraph.addEdge(new Text("5"), new Text("6"), NullWritable.get()); testGraph.addEdge(new Text("6"), new Text("5"), NullWritable.get()); return testGraph; } }
dga-giraph/src/test/java/com/soteradefense/dga/weaklyconnectedcomponents/WeaklyConnectedComponentsTest.java
package com.soteradefense.dga.weaklyconnectedcomponents; import com.soteradefense.dga.io.formats.SimpleTsvUndirectedEdgeInputFormat; import org.apache.giraph.conf.GiraphConfiguration; import org.apache.giraph.conf.ImmutableClassesGiraphConfiguration; import org.apache.giraph.io.formats.InMemoryVertexOutputFormat; import org.apache.giraph.utils.InMemoryVertexInputFormat; import org.apache.giraph.utils.InternalVertexRunner; import org.apache.giraph.utils.TestGraph; import org.apache.hadoop.io.NullWritable; import org.apache.hadoop.io.Text; import org.junit.Test; import java.util.Map; import static junit.framework.Assert.assertEquals; public class WeaklyConnectedComponentsTest { @Test public void testComputeOutput() throws Exception { GiraphConfiguration conf = new GiraphConfiguration(); conf.setComputationClass(WeaklyConnectedComponents.class); conf.setVertexOutputFormatClass(InMemoryVertexOutputFormat.class); conf.set(SimpleTsvUndirectedEdgeInputFormat.EXPECTED_NUMBER_OF_COLUMNS_KEY, "2"); TestGraph<Text,Text,NullWritable> testGraph = getGraph(conf); InMemoryVertexOutputFormat.initializeOutputGraph(conf); InternalVertexRunner.run(conf, testGraph); TestGraph<Text, Text, NullWritable> graph = InMemoryVertexOutputFormat.getOutputGraph(); assertEquals(6, graph.getVertices().size()); assertEquals("2", graph.getVertex(new Text("1")).getValue().toString()); assertEquals("2", graph.getVertex(new Text("2")).getValue().toString()); assertEquals("4", graph.getVertex(new Text("3")).getValue().toString()); assertEquals("4", graph.getVertex(new Text("4")).getValue().toString()); assertEquals("6", graph.getVertex(new Text("5")).getValue().toString()); assertEquals("6", graph.getVertex(new Text("6")).getValue().toString()); } private TestGraph<Text,Text,NullWritable> getGraph(GiraphConfiguration conf){ Text defaultVal = new Text(""); TestGraph<Text, Text, NullWritable> testGraph = new TestGraph<Text, Text, NullWritable>(conf); testGraph.addEdge(new Text("1"), new Text("2"), NullWritable.get()); testGraph.addEdge(new Text("2"), new Text("1"), NullWritable.get()); testGraph.addEdge(new Text("3"), new Text("4"), NullWritable.get()); testGraph.addEdge(new Text("4"), new Text("3"), NullWritable.get()); testGraph.addEdge(new Text("5"), new Text("6"), NullWritable.get()); testGraph.addEdge(new Text("6"), new Text("5"), NullWritable.get()); return testGraph; } }
Removed defaultVal because it was already being set
dga-giraph/src/test/java/com/soteradefense/dga/weaklyconnectedcomponents/WeaklyConnectedComponentsTest.java
Removed defaultVal because it was already being set
<ide><path>ga-giraph/src/test/java/com/soteradefense/dga/weaklyconnectedcomponents/WeaklyConnectedComponentsTest.java <ide> assertEquals("6", graph.getVertex(new Text("6")).getValue().toString()); <ide> } <ide> private TestGraph<Text,Text,NullWritable> getGraph(GiraphConfiguration conf){ <del> Text defaultVal = new Text(""); <ide> TestGraph<Text, Text, NullWritable> testGraph = new TestGraph<Text, Text, NullWritable>(conf); <ide> testGraph.addEdge(new Text("1"), new Text("2"), NullWritable.get()); <ide> testGraph.addEdge(new Text("2"), new Text("1"), NullWritable.get());
JavaScript
apache-2.0
0f951e494cb0c0478b1cd92320fc19ea1bff3156
0
APTrust/easy-store,APTrust/easy-store,APTrust/easy-store,APTrust/easy-store
const electron = require('electron'); const app = (process.type === 'renderer') ? electron.remote.app : electron.app; const { spawn } = require('child_process'); const decoder = new TextDecoder("utf-8"); const fs = require('fs'); const mkdirp = require('mkdirp'); const os = require('os'); const path = require('path'); const tar = require('tar-stream') const AppSetting = require('../../core/app_setting'); const Util = require('../../core/util'); // We're reading output from a Golang program, which uses "\n" // as the newline character when printing to STDOUT on all // platforms, including Windows. See: // https://golang.org/src/fmt/print.go?s=7595:7644#L253 const NEWLINE = "\n"; //const NEWLINE = require('os').EOL; const name = "APTrust BagIt Provider"; const description = "Provides access to the APTrust command-line bagging library." const version = "0.1"; const format = "BagIt"; const formatMimeType = ""; /* TODO: Implement bagger in JavaScript. Will need the following: 1. Crypto: https://nodejs.org/api/crypto.html#crypto_class_hash Md5 example: https://gist.github.com/kitek/1579117 2. Tar: https://www.npmjs.com/package/archiver Supports streams and zip. 3. Multiwriter candidates: https://github.com/mafintosh/multi-write-stream https://www.npmjs.com/package/multiwriter Or use builtin Node streams and pipes, as described here: https://stackoverflow.com/questions/17957525/multiple-consumption-of-single-stream */ class BagIt { /** * Custom packager. * @constructor * @param {object} job - The job object. See easy/job.js. * @param {object} emitter - An Node event object that can emit events * @returns {object} - A new custom packager. */ constructor(job, emitter) { this.job = job; this.emitter = emitter; } /** * Returns a map with descriptive info about this provider. * @returns {object} - Contains descriptive info about this provider. */ describe() { return { name: name, description: description, version: version, format: format, formatMimeType: formatMimeType }; } /** * Assembles all job.files into a package (e.g. a zip file, * tar file, rar file, etc.). */ packageFiles() { var packager = this; packager.job.packagedFile = ""; try { // Make sure the bagging directory exists var baggingDir = AppSetting.findByName("Bagging Directory").value; console.log("Creating" + baggingDir); mkdirp.sync(baggingDir, { mode: 0o755 }); // Start the bagger executable // TODO: Set up the spawn env to include the PATH in which apt_create_bag resides. // Maybe that goes in AppSettings? var started = false; var fileCount = 0; var baggerProgram = this.getBaggerProgramPath(); var bagger = spawn(baggerProgram, [ "--stdin" ]); bagger.on('error', (err) => { var msg = `Bagger ${baggerProgram} exited with error: ${err}`; if (String(err).includes("ENOENT")) { msg += ". Make sure the program exists and is in your PATH."; } packager.emitter.emit('error', msg); console.log(msg); return; }); bagger.on('exit', function (code, signal) { var msg = `Bagger failed with code ${code} and signal ${signal}`; var succeeded = false; if (code == 0) { msg = 'Bagger completed successfully'; succeeded = true; } packager.dumpManifests(); packager.emitter.emit('complete', succeeded, msg); }); bagger.stdout.on('data', (data) => { if (started == false) { packager.emitter.emit('start', 'Building bag...'); started = true; } var lines = decoder.decode(data).split(NEWLINE); for (var line of lines) { if (line.startsWith('Adding')) { fileCount += 1; packager.emitter.emit('fileAddStart', line); } else if (line.startsWith('Writing')) { packager.emitter.emit('fileAddComplete', true, `Added ${fileCount} files`); packager.emitter.emit('packageStart', line); } else if (line.startsWith('Validating')) { packager.emitter.emit('packageComplete', true, 'Finished packaging'); packager.emitter.emit('validateStart', line); } else if (line.startsWith('Bag at')) { var isValid = false; if (line.endsWith("is valid")) { isValid = true; } packager.emitter.emit('validateComplete', isValid, line); } else if (line.startsWith('Created')) { var filePath = line.substring(7); packager.job.packagedFile = filePath.trim(); } else { console.log(line); } } // console.log(decoder.decode(data)); }); bagger.stderr.on('data', (data) => { var lines = decoder.decode(data).split(NEWLINE); for (var line of lines) { packager.emitter.emit('error', line); } }); bagger.stdin.write(JSON.stringify(packager.job)); } catch (ex) { packager.emitter.emit('error', ex); console.error(ex); } } getBaggerProgramPath() { var baggerProgram = ""; var setting = AppSetting.findByName("Path to Bagger"); if (setting) { baggerProgram = setting.value; } else { if (os.platform == 'win32') { baggerProgram = "apt_create_bag.exe"; } else { baggerProgram = "apt_create_bag"; } } console.log("Bagger program: " + baggerProgram); return baggerProgram; } getManifestDirName() { var dir = app.getPath('userData'); return path.join(dir, 'manifests'); } ensureManifestDir() { var packager = this; var manifestDir = packager.getManifestDirName(); if (!fs.existsSync(manifestDir)){ fs.mkdirSync(manifestDir); } } dumpManifests() { // For each manifest listed in profile, // copy from bag or tar to special dir or to Electron Storage. // Throw exception if there is one, so the UI can show it. // This will cause performance problems for larger bags. // We wouldn't need this if we were creating the bag in JavaScript. var packager = this; packager.ensureManifestDir(); if (packager.job.packagedFile.endsWith(".tar")) { return packager.dumpTarredManifests(); } else if (packager.job.packagedFile.endsWith(".gzip")) { console.log("Dump manifests does not yet support gzip format") } else if (packager.job.packagedFile.endsWith(".tgz")) { console.log("Dump manifests does not yet support tgz format") } else if (packager.job.packagedFile.endsWith(".rar")) { console.log("Dump manifests does not yet support rar format") } else if (packager.job.packagedFile.endsWith(".zip")) { console.log("Dump manifests does not yet support zip format") } else { console.log("Dump manifests: unknown and unsupported format") } } dumpTarredManifests() { var packager = this; var extract = tar.extract(); var filename = ''; var data = ''; var manifestDir = packager.getManifestDirName(); extract.on('entry', function(header, stream, cb) { stream.on('data', function(chunk) { var isTagManifest = header.name.match(/tagmanifest-(\w+).txt$/) != null; var match = header.name.match(/manifest-(\w+).txt$/); if (match && !isTagManifest) { filename = `${packager.job.id}_${match[1]}_${new Date().getTime()}.txt`; console.log(filename); data += chunk; } }); stream.on('end', function() { if (filename != '') { var fullFileName = path.join(manifestDir, filename); fs.writeFileSync(fullFileName, data); console.log(`Wrote manifest to ${fullFileName}`); data = ''; filename = ''; } cb(); }); //stream.resume(); }); extract.on('finish', function() { //fs.writeFile(filename, data); }); fs.createReadStream(packager.job.packagedFile) //.pipe(zlib.createGunzip()) .pipe(extract); } } module.exports.Provider = BagIt; module.exports.name = name; module.exports.description = description; module.exports.version = version; module.exports.format = format; module.exports.formatMimeType = formatMimeType;
electron/easy/plugins/packaging/bagit.js
const electron = require('electron'); const app = (process.type === 'renderer') ? electron.remote.app : electron.app; const { spawn } = require('child_process'); const decoder = new TextDecoder("utf-8"); const fs = require('fs'); const mkdirp = require('mkdirp'); const os = require('os'); const path = require('path'); const tar = require('tar-stream') const AppSetting = require('../../core/app_setting'); const Util = require('../../core/util'); // We're reading output from a Golang program, which uses "\n" // as the newline character when printing to STDOUT on all // platforms, including Windows. See: // https://golang.org/src/fmt/print.go?s=7595:7644#L253 const NEWLINE = "\n"; //const NEWLINE = require('os').EOL; const name = "APTrust BagIt Provider"; const description = "Provides access to the APTrust command-line bagging library." const version = "0.1"; const format = "BagIt"; const formatMimeType = ""; /* TODO: Implement bagger in JavaScript. Will need the following: 1. Crypto: https://nodejs.org/api/crypto.html#crypto_class_hash Md5 example: https://gist.github.com/kitek/1579117 2. Tar: https://www.npmjs.com/package/archiver Supports streams and zip. 3. Multiwriter candidates: https://github.com/mafintosh/multi-write-stream https://www.npmjs.com/package/multiwriter Or use builtin Node streams and pipes, as described here: https://stackoverflow.com/questions/17957525/multiple-consumption-of-single-stream */ class BagIt { /** * Custom packager. * @constructor * @param {object} job - The job object. See easy/job.js. * @param {object} emitter - An Node event object that can emit events * @returns {object} - A new custom packager. */ constructor(job, emitter) { this.job = job; this.emitter = emitter; } /** * Returns a map with descriptive info about this provider. * @returns {object} - Contains descriptive info about this provider. */ describe() { return { name: name, description: description, version: version, format: format, formatMimeType: formatMimeType }; } /** * Assembles all job.files into a package (e.g. a zip file, * tar file, rar file, etc.). */ packageFiles() { var packager = this; packager.job.packagedFile = ""; try { // Make sure the bagging directory exists var baggingDir = AppSetting.findByName("Bagging Directory").value; console.log("Creating" + baggingDir); mkdirp.sync(baggingDir, { mode: 0o755 }); // Start the bagger executable // TODO: Set up the spawn env to include the PATH in which apt_create_bag resides. // Maybe that goes in AppSettings? var started = false; var fileCount = 0; var baggerProgram = this.getBaggerProgramPath(); var bagger = spawn(baggerProgram, [ "--stdin" ]); bagger.on('error', (err) => { var msg = `Bagger ${baggerProgram} exited with error: ${err}`; if (String(err).includes("ENOENT")) { msg += ". Make sure the program exists and is in your PATH."; } packager.emitter.emit('error', msg); console.log(msg); return; }); bagger.on('exit', function (code, signal) { var msg = `Bagger exited with code ${code} and signal ${signal}`; var succeeded = false; if (code == 0) { msg = `Bagger completed successfully with code ${code} and signal ${signal}`; succeeded = true; } packager.dumpManifests(); packager.emitter.emit('complete', succeeded, msg); }); bagger.stdout.on('data', (data) => { if (started == false) { packager.emitter.emit('start', 'Building bag...'); started = true; } var lines = decoder.decode(data).split(NEWLINE); for (var line of lines) { if (line.startsWith('Adding')) { fileCount += 1; packager.emitter.emit('fileAddStart', line); } else if (line.startsWith('Writing')) { packager.emitter.emit('fileAddComplete', true, `Added ${fileCount} files`); packager.emitter.emit('packageStart', line); } else if (line.startsWith('Validating')) { packager.emitter.emit('packageComplete', true, 'Finished packaging'); packager.emitter.emit('validateStart', line); } else if (line.startsWith('Bag at')) { var isValid = false; if (line.endsWith("is valid")) { isValid = true; } packager.emitter.emit('validateComplete', isValid, line); } else if (line.startsWith('Created')) { var filePath = line.substring(7); packager.job.packagedFile = filePath.trim(); } else { console.log(line); } } // console.log(decoder.decode(data)); }); bagger.stderr.on('data', (data) => { var lines = decoder.decode(data).split(NEWLINE); for (var line of lines) { packager.emitter.emit('error', line); } }); bagger.stdin.write(JSON.stringify(packager.job)); } catch (ex) { packager.emitter.emit('error', ex); console.error(ex); } } getBaggerProgramPath() { var baggerProgram = ""; var setting = AppSetting.findByName("Path to Bagger"); if (setting) { baggerProgram = setting.value; } else { if (os.platform == 'win32') { baggerProgram = "apt_create_bag.exe"; } else { baggerProgram = "apt_create_bag"; } } console.log("Bagger program: " + baggerProgram); return baggerProgram; } getManifestDirName() { var dir = app.getPath('userData'); return path.join(dir, 'manifests'); } ensureManifestDir() { var packager = this; var manifestDir = packager.getManifestDirName(); if (!fs.existsSync(manifestDir)){ fs.mkdirSync(manifestDir); } } dumpManifests() { // For each manifest listed in profile, // copy from bag or tar to special dir or to Electron Storage. // Throw exception if there is one, so the UI can show it. // This will cause performance problems for larger bags. // We wouldn't need this if we were creating the bag in JavaScript. var packager = this; packager.ensureManifestDir(); if (packager.job.packagedFile.endsWith(".tar")) { return packager.dumpTarredManifests(); } else if (packager.job.packagedFile.endsWith(".gzip")) { console.log("Dump manifests does not yet support gzip format") } else if (packager.job.packagedFile.endsWith(".tgz")) { console.log("Dump manifests does not yet support tgz format") } else if (packager.job.packagedFile.endsWith(".rar")) { console.log("Dump manifests does not yet support rar format") } else if (packager.job.packagedFile.endsWith(".zip")) { console.log("Dump manifests does not yet support zip format") } else { console.log("Dump manifests: unknown and unsupported format") } } dumpTarredManifests() { var packager = this; var extract = tar.extract(); var filename = ''; var data = ''; var manifestDir = packager.getManifestDirName(); extract.on('entry', function(header, stream, cb) { stream.on('data', function(chunk) { var isTagManifest = header.name.match(/tagmanifest-(\w+).txt$/) != null; var match = header.name.match(/manifest-(\w+).txt$/); if (match && !isTagManifest) { filename = `${packager.job.id}_${match[1]}_${new Date().getTime()}.txt`; console.log(filename); data += chunk; } }); stream.on('end', function() { if (filename != '') { var fullFileName = path.join(manifestDir, filename); fs.writeFileSync(fullFileName, data); console.log(`Wrote manifest to ${fullFileName}`); data = ''; filename = ''; } cb(); }); //stream.resume(); }); extract.on('finish', function() { //fs.writeFile(filename, data); }); fs.createReadStream(packager.job.packagedFile) //.pipe(zlib.createGunzip()) .pipe(extract); } } module.exports.Provider = BagIt; module.exports.name = name; module.exports.description = description; module.exports.version = version; module.exports.format = format; module.exports.formatMimeType = formatMimeType;
Simplify success message
electron/easy/plugins/packaging/bagit.js
Simplify success message
<ide><path>lectron/easy/plugins/packaging/bagit.js <ide> }); <ide> <ide> bagger.on('exit', function (code, signal) { <del> var msg = `Bagger exited with code ${code} and signal ${signal}`; <add> var msg = `Bagger failed with code ${code} and signal ${signal}`; <ide> var succeeded = false; <ide> if (code == 0) { <del> msg = `Bagger completed successfully with code ${code} and signal ${signal}`; <add> msg = 'Bagger completed successfully'; <ide> succeeded = true; <ide> } <ide> packager.dumpManifests();
Java
lgpl-2.1
25487ff8b9fe700345dd2d38cd152aa6bbf84243
0
svartika/ccnx,ebollens/ccnmp,svartika/ccnx,cawka/ndnx,svartika/ccnx,ebollens/ccnmp,svartika/ccnx,cawka/ndnx,cawka/ndnx,svartika/ccnx,ebollens/ccnmp,svartika/ccnx,svartika/ccnx,cawka/ndnx,ebollens/ccnmp,cawka/ndnx
package com.parc.ccn.library.io; import java.io.IOException; import java.io.OutputStream; import java.security.InvalidKeyException; import java.security.NoSuchAlgorithmException; import java.security.PrivateKey; import java.security.SignatureException; import java.sql.Timestamp; import java.util.ArrayList; import java.util.Arrays; import javax.xml.stream.XMLStreamException; import com.parc.ccn.Library; import com.parc.ccn.data.ContentName; import com.parc.ccn.data.content.Header; import com.parc.ccn.data.security.ContentAuthenticator; import com.parc.ccn.data.security.KeyLocator; import com.parc.ccn.data.security.PublisherKeyID; import com.parc.ccn.library.CCNLibrary; import com.parc.ccn.security.crypto.CCNDigestHelper; import com.parc.ccn.security.crypto.CCNMerkleTree; public class CCNOutputStream extends OutputStream { /** * Maximum number of blocks we keep around before we build a * Merkle tree and flush. Should be based on lengths of merkle * paths and signatures and so on. */ protected static final int BLOCK_BUF_COUNT = 128; protected CCNLibrary _library = null; /** * The name for the content fragments, up to just before the sequence number. */ protected ContentName _baseName = null; protected int _totalLength = 0; protected int _blockOffset = 0; // offset into current block protected int _blockIndex = 0; // index into array of block buffers protected byte [][] _blockBuffers = null; protected int _baseBlockIndex; // base index of current set of block buffers. protected Timestamp _timestamp; // timestamp we use for writing, set to first time we write protected PublisherKeyID _publisher; protected KeyLocator _locator; protected PrivateKey _signingKey; protected ContentAuthenticator.ContentType _type; protected CCNDigestHelper _dh; protected ArrayList<byte []> _roots = new ArrayList<byte[]>(); public CCNOutputStream(ContentName name, PublisherKeyID publisher, KeyLocator locator, PrivateKey signingKey, CCNLibrary library) throws XMLStreamException, IOException, InterruptedException { _library = library; if (null == _library) { _library = CCNLibrary.getLibrary(); } _publisher = publisher; _locator = locator; _signingKey = signingKey; ContentName nameToOpen = name; if (CCNLibrary.isFragment(nameToOpen)) { // DKS TODO: should we do this? nameToOpen = CCNLibrary.fragmentRoot(nameToOpen); } // Assume if name is already versioned, caller knows what name // to write. If caller specifies authentication information, // ignore it for now. if (!CCNLibrary.isVersioned(nameToOpen)) { // if publisherID is null, will get any publisher ContentName currentVersionName = _library.getLatestVersionName(nameToOpen, null); if (null == currentVersionName) { nameToOpen = CCNLibrary.versionName(nameToOpen, CCNLibrary.baseVersion()); } else { nameToOpen = CCNLibrary.versionName(currentVersionName, (_library.getVersionNumber(currentVersionName) + 1)); } } // Should have name of root of version we want to // open. Get the header block. Already stripped to // root. We've altered the header semantics, so that // we can just get headers rather than a plethora of // fragments. _baseName = nameToOpen; _blockBuffers = new byte[BLOCK_BUF_COUNT][]; _baseBlockIndex = CCNLibrary.baseFragment(); _dh = new CCNDigestHelper(); } @Override public void close() throws IOException { try { closeNetworkData(); } catch (InvalidKeyException e) { throw new IOException("Cannot sign content -- invalid key!: " + e.getMessage()); } catch (SignatureException e) { throw new IOException("Cannot sign content -- signature failure!: " + e.getMessage()); } catch (NoSuchAlgorithmException e) { throw new IOException("Cannot sign content -- unknown algorithm!: " + e.getMessage()); } catch (InterruptedException e) { throw new IOException("Low-level network failure!: " + e.getMessage()); } } @Override public void flush() throws IOException { try { flushToNetwork(); } catch (InvalidKeyException e) { throw new IOException("Cannot sign content -- invalid key!: " + e.getMessage()); } catch (SignatureException e) { throw new IOException("Cannot sign content -- signature failure!: " + e.getMessage()); } catch (NoSuchAlgorithmException e) { throw new IOException("Cannot sign content -- unknown algorithm!: " + e.getMessage()); } catch (InterruptedException e) { throw new IOException("Low-level network failure!: " + e.getMessage()); } } @Override public void write(byte[] b, int off, int len) throws IOException { try { writeToNetwork(b, off, len); } catch (InvalidKeyException e) { throw new IOException("Cannot sign content -- invalid key!: " + e.getMessage()); } catch (SignatureException e) { throw new IOException("Cannot sign content -- signature failure!: " + e.getMessage()); } catch (NoSuchAlgorithmException e) { throw new IOException("Cannot sign content -- unknown algorithm!: " + e.getMessage()); } catch (InterruptedException e) { throw new IOException("Low-level network failure!: " + e.getMessage()); } } @Override public void write(byte[] b) throws IOException { write(b, 0, b.length); } @Override public void write(int b) throws IOException { byte buf[] = {(byte)b}; write(buf, 0, 1); } protected int writeToNetwork(byte[] buf, long offset, long len) throws IOException, InvalidKeyException, SignatureException, NoSuchAlgorithmException, InterruptedException { if ((len <= 0) || (null == buf) || (buf.length == 0) || (offset >= buf.length)) throw new IllegalArgumentException("Invalid argument!"); long bytesToWrite = len; while (bytesToWrite > 0) { if (_blockIndex >= BLOCK_BUF_COUNT) { Library.logger().fine("write: about to sync one tree's worth of blocks (" + BLOCK_BUF_COUNT +") to the network."); flush(); } if (null == _blockBuffers[_blockIndex]) { _blockBuffers[_blockIndex] = new byte[Header.DEFAULT_BLOCKSIZE]; _blockOffset = 0; } long thisBufAvail = _blockBuffers[_blockIndex].length - _blockOffset; long toWriteNow = (thisBufAvail > bytesToWrite) ? bytesToWrite : thisBufAvail; System.arraycopy(buf, (int)offset, _blockBuffers[_blockIndex], (int)_blockOffset, (int)toWriteNow); _dh.update(buf, (int) offset, (int)toWriteNow); bytesToWrite -= toWriteNow; _blockOffset += toWriteNow; Library.logger().finer("write: added " + toWriteNow + " bytes to block. blockIndex: " + _blockIndex + " ( " + (BLOCK_BUF_COUNT-_blockIndex-1) + " left) blockOffset: " + _blockOffset + "( " + (thisBufAvail - toWriteNow) + " left in block)."); if (_blockOffset >= _blockBuffers[_blockIndex].length) { Library.logger().finer("write: finished writing block " + _blockIndex); ++_blockIndex; _blockOffset = 0; } } _totalLength += len; return 0; } protected void closeNetworkData() throws InvalidKeyException, SignatureException, NoSuchAlgorithmException, IOException, InterruptedException { // Special case; if we don't need to fragment, don't. Can't // do this in sync(), as we can't tell a manual sync from a close. // Though that means a manual sync(); close(); on a short piece of // content would end up with unnecessary fragmentation... if ((_baseBlockIndex == CCNLibrary.baseFragment()) && ((_blockIndex == 0) || ((_blockIndex == 1) && (_blockOffset == 0)))) { // maybe need put with offset and length if ((_blockIndex == 1) || (_blockOffset == _blockBuffers[0].length)) { Library.logger().finest("close(): writing single-block file in one put, length: " + _blockBuffers[0].length); _library.put(_baseName, _blockBuffers[0], _type, _publisher, _locator, _signingKey); } else { byte [] tempBuf = new byte[_blockOffset]; System.arraycopy(_blockBuffers[0],0,tempBuf,0,_blockOffset); Library.logger().finest("close(): writing single-block file in one put, copied buffer length = " + _blockOffset); _library.put(_baseName, tempBuf, _type, _publisher, _locator, _signingKey); } } else { // DKS TODO Needs to cope with partial last block. flush(); writeHeader(); } } /** * DKS TODO: make it easier to write streams with block names that say correspond * to byte or time offsets... Right now this API focuses on writing fragmented files. * @throws InvalidKeyException * @throws SignatureException * @throws NoSuchAlgorithmException * @throws InterruptedException * @throws IOException */ protected void flushToNetwork() throws InvalidKeyException, SignatureException, NoSuchAlgorithmException, InterruptedException, IOException { // DKS TODO needs to cope with partial last block. if (null == _timestamp) _timestamp = ContentAuthenticator.now(); Library.logger().finer("sync: putting merkle tree to the network, " + (_blockIndex+1) + " blocks."); // Generate Merkle tree (or other auth structure) and authenticators and put contents. CCNMerkleTree tree = _library.putMerkleTree(_baseName, _baseBlockIndex, _blockBuffers, _blockIndex+1, _baseBlockIndex, _timestamp, _publisher, _locator, _signingKey); _roots.add(tree.root()); // Set contents of blocks to 0 for (int i=0; i < _blockBuffers.length; ++i) { if (null != _blockBuffers[i]) Arrays.fill(_blockBuffers[i], 0, _blockBuffers[i].length, (byte)0); } _baseBlockIndex += _blockIndex; _blockIndex = 0; } protected void writeHeader() throws InvalidKeyException, SignatureException, IOException, InterruptedException { // What do we put in the header if we have multiple merkle trees? _library.putHeader(_baseName, (int)_totalLength, _dh.digest(), ((_roots.size() > 0) ? _roots.get(0) : null), _type, _timestamp, _publisher, _locator, _signingKey); Library.logger().info("Wrote header: " + CCNLibrary.headerName(_baseName)); } }
Java_CCN/com/parc/ccn/library/io/CCNOutputStream.java
package com.parc.ccn.library.io; import java.io.IOException; import java.io.OutputStream; import java.security.InvalidKeyException; import java.security.NoSuchAlgorithmException; import java.security.PrivateKey; import java.security.SignatureException; import java.sql.Timestamp; import java.util.ArrayList; import java.util.Arrays; import javax.xml.stream.XMLStreamException; import com.parc.ccn.Library; import com.parc.ccn.data.ContentName; import com.parc.ccn.data.content.Header; import com.parc.ccn.data.security.ContentAuthenticator; import com.parc.ccn.data.security.KeyLocator; import com.parc.ccn.data.security.PublisherKeyID; import com.parc.ccn.library.CCNLibrary; import com.parc.ccn.security.crypto.CCNDigestHelper; import com.parc.ccn.security.crypto.CCNMerkleTree; public class CCNOutputStream extends OutputStream { /** * Maximum number of blocks we keep around before we build a * Merkle tree and flush. Should be based on lengths of merkle * paths and signatures and so on. */ protected static final int BLOCK_BUF_COUNT = 128; protected CCNLibrary _library = null; /** * The name for the content fragments, up to just before the sequence number. */ protected ContentName _baseName = null; protected int _totalLength = 0; protected int _blockOffset = 0; // offset into current block protected int _blockIndex = 0; // index into array of block buffers protected byte [][] _blockBuffers = null; protected int _baseBlockIndex; // base index of current set of block buffers. protected Timestamp _timestamp; // timestamp we use for writing, set to first time we write protected PublisherKeyID _publisher; protected KeyLocator _locator; protected PrivateKey _signingKey; protected ContentAuthenticator.ContentType _type; protected CCNDigestHelper _dh; protected ArrayList<byte []> _roots = new ArrayList<byte[]>(); public CCNOutputStream(ContentName name, PublisherKeyID publisher, KeyLocator locator, PrivateKey signingKey, CCNLibrary library) throws XMLStreamException, IOException, InterruptedException { _library = library; if (null == _library) { _library = CCNLibrary.getLibrary(); } _publisher = publisher; _locator = locator; _signingKey = signingKey; ContentName nameToOpen = name; if (CCNLibrary.isFragment(nameToOpen)) { // DKS TODO: should we do this? nameToOpen = CCNLibrary.fragmentRoot(nameToOpen); } // Assume if name is already versioned, caller knows what name // to write. If caller specifies authentication information, // ignore it for now. if (!CCNLibrary.isVersioned(nameToOpen)) { // if publisherID is null, will get any publisher ContentName currentVersionName = _library.getLatestVersionName(nameToOpen, null); if (null == currentVersionName) { nameToOpen = CCNLibrary.versionName(nameToOpen, CCNLibrary.baseVersion()); } else { nameToOpen = CCNLibrary.versionName(currentVersionName, (_library.getVersionNumber(currentVersionName) + 1)); } } // Should have name of root of version we want to // open. Get the header block. Already stripped to // root. We've altered the header semantics, so that // we can just get headers rather than a plethora of // fragments. _baseName = nameToOpen; _blockBuffers = new byte[BLOCK_BUF_COUNT][]; _baseBlockIndex = CCNLibrary.baseFragment(); _dh = new CCNDigestHelper(); } @Override public void close() throws IOException { try { closeNetworkData(); } catch (InvalidKeyException e) { throw new IOException("Cannot sign content -- invalid key!", e); } catch (SignatureException e) { throw new IOException("Cannot sign content -- signature failure!", e); } catch (NoSuchAlgorithmException e) { throw new IOException("Cannot sign content -- unknown algorithm!", e); } catch (InterruptedException e) { throw new IOException("Low-level network failure!", e); } } @Override public void flush() throws IOException { try { flushToNetwork(); } catch (InvalidKeyException e) { throw new IOException("Cannot sign content -- invalid key!", e); } catch (SignatureException e) { throw new IOException("Cannot sign content -- signature failure!", e); } catch (NoSuchAlgorithmException e) { throw new IOException("Cannot sign content -- unknown algorithm!", e); } catch (InterruptedException e) { throw new IOException("Low-level network failure!", e); } } @Override public void write(byte[] b, int off, int len) throws IOException { try { writeToNetwork(b, off, len); } catch (InvalidKeyException e) { throw new IOException("Cannot sign content -- invalid key!", e); } catch (SignatureException e) { throw new IOException("Cannot sign content -- signature failure!", e); } catch (NoSuchAlgorithmException e) { throw new IOException("Cannot sign content -- unknown algorithm!", e); } catch (InterruptedException e) { throw new IOException("Low-level network failure!", e); } } @Override public void write(byte[] b) throws IOException { write(b, 0, b.length); } @Override public void write(int b) throws IOException { byte buf[] = {(byte)b}; write(buf, 0, 1); } protected int writeToNetwork(byte[] buf, long offset, long len) throws IOException, InvalidKeyException, SignatureException, NoSuchAlgorithmException, InterruptedException { if ((len <= 0) || (null == buf) || (buf.length == 0) || (offset >= buf.length)) throw new IllegalArgumentException("Invalid argument!"); long bytesToWrite = len; while (bytesToWrite > 0) { if (_blockIndex >= BLOCK_BUF_COUNT) { Library.logger().fine("write: about to sync one tree's worth of blocks (" + BLOCK_BUF_COUNT +") to the network."); flush(); } if (null == _blockBuffers[_blockIndex]) { _blockBuffers[_blockIndex] = new byte[Header.DEFAULT_BLOCKSIZE]; _blockOffset = 0; } long thisBufAvail = _blockBuffers[_blockIndex].length - _blockOffset; long toWriteNow = (thisBufAvail > bytesToWrite) ? bytesToWrite : thisBufAvail; System.arraycopy(buf, (int)offset, _blockBuffers[_blockIndex], (int)_blockOffset, (int)toWriteNow); _dh.update(buf, (int) offset, (int)toWriteNow); bytesToWrite -= toWriteNow; _blockOffset += toWriteNow; Library.logger().finer("write: added " + toWriteNow + " bytes to block. blockIndex: " + _blockIndex + " ( " + (BLOCK_BUF_COUNT-_blockIndex-1) + " left) blockOffset: " + _blockOffset + "( " + (thisBufAvail - toWriteNow) + " left in block)."); if (_blockOffset >= _blockBuffers[_blockIndex].length) { Library.logger().finer("write: finished writing block " + _blockIndex); ++_blockIndex; _blockOffset = 0; } } _totalLength += len; return 0; } protected void closeNetworkData() throws InvalidKeyException, SignatureException, NoSuchAlgorithmException, IOException, InterruptedException { // Special case; if we don't need to fragment, don't. Can't // do this in sync(), as we can't tell a manual sync from a close. // Though that means a manual sync(); close(); on a short piece of // content would end up with unnecessary fragmentation... if ((_baseBlockIndex == CCNLibrary.baseFragment()) && ((_blockIndex == 0) || ((_blockIndex == 1) && (_blockOffset == 0)))) { // maybe need put with offset and length if ((_blockIndex == 1) || (_blockOffset == _blockBuffers[0].length)) { Library.logger().finest("close(): writing single-block file in one put, length: " + _blockBuffers[0].length); _library.put(_baseName, _blockBuffers[0], _type, _publisher, _locator, _signingKey); } else { byte [] tempBuf = new byte[_blockOffset]; System.arraycopy(_blockBuffers[0],0,tempBuf,0,_blockOffset); Library.logger().finest("close(): writing single-block file in one put, copied buffer length = " + _blockOffset); _library.put(_baseName, tempBuf, _type, _publisher, _locator, _signingKey); } } else { // DKS TODO Needs to cope with partial last block. flush(); writeHeader(); } } /** * DKS TODO: make it easier to write streams with block names that say correspond * to byte or time offsets... Right now this API focuses on writing fragmented files. * @throws InvalidKeyException * @throws SignatureException * @throws NoSuchAlgorithmException * @throws InterruptedException * @throws IOException */ protected void flushToNetwork() throws InvalidKeyException, SignatureException, NoSuchAlgorithmException, InterruptedException, IOException { // DKS TODO needs to cope with partial last block. if (null == _timestamp) _timestamp = ContentAuthenticator.now(); Library.logger().finer("sync: putting merkle tree to the network, " + (_blockIndex+1) + " blocks."); // Generate Merkle tree (or other auth structure) and authenticators and put contents. CCNMerkleTree tree = _library.putMerkleTree(_baseName, _baseBlockIndex, _blockBuffers, _blockIndex+1, _baseBlockIndex, _timestamp, _publisher, _locator, _signingKey); _roots.add(tree.root()); // Set contents of blocks to 0 for (int i=0; i < _blockBuffers.length; ++i) { if (null != _blockBuffers[i]) Arrays.fill(_blockBuffers[i], 0, _blockBuffers[i].length, (byte)0); } _baseBlockIndex += _blockIndex; _blockIndex = 0; } protected void writeHeader() throws InvalidKeyException, SignatureException, IOException, InterruptedException { // What do we put in the header if we have multiple merkle trees? _library.putHeader(_baseName, (int)_totalLength, _dh.digest(), ((_roots.size() > 0) ? _roots.get(0) : null), _type, _timestamp, _publisher, _locator, _signingKey); Library.logger().info("Wrote header: " + CCNLibrary.headerName(_baseName)); } }
Removing 1.6-isms
Java_CCN/com/parc/ccn/library/io/CCNOutputStream.java
Removing 1.6-isms
<ide><path>ava_CCN/com/parc/ccn/library/io/CCNOutputStream.java <ide> try { <ide> closeNetworkData(); <ide> } catch (InvalidKeyException e) { <del> throw new IOException("Cannot sign content -- invalid key!", e); <add> throw new IOException("Cannot sign content -- invalid key!: " + e.getMessage()); <ide> } catch (SignatureException e) { <del> throw new IOException("Cannot sign content -- signature failure!", e); <add> throw new IOException("Cannot sign content -- signature failure!: " + e.getMessage()); <ide> } catch (NoSuchAlgorithmException e) { <del> throw new IOException("Cannot sign content -- unknown algorithm!", e); <add> throw new IOException("Cannot sign content -- unknown algorithm!: " + e.getMessage()); <ide> } catch (InterruptedException e) { <del> throw new IOException("Low-level network failure!", e); <add> throw new IOException("Low-level network failure!: " + e.getMessage()); <ide> } <ide> } <ide> <ide> try { <ide> flushToNetwork(); <ide> } catch (InvalidKeyException e) { <del> throw new IOException("Cannot sign content -- invalid key!", e); <add> throw new IOException("Cannot sign content -- invalid key!: " + e.getMessage()); <ide> } catch (SignatureException e) { <del> throw new IOException("Cannot sign content -- signature failure!", e); <add> throw new IOException("Cannot sign content -- signature failure!: " + e.getMessage()); <ide> } catch (NoSuchAlgorithmException e) { <del> throw new IOException("Cannot sign content -- unknown algorithm!", e); <add> throw new IOException("Cannot sign content -- unknown algorithm!: " + e.getMessage()); <ide> } catch (InterruptedException e) { <del> throw new IOException("Low-level network failure!", e); <add> throw new IOException("Low-level network failure!: " + e.getMessage()); <ide> } <ide> } <ide> <ide> try { <ide> writeToNetwork(b, off, len); <ide> } catch (InvalidKeyException e) { <del> throw new IOException("Cannot sign content -- invalid key!", e); <add> throw new IOException("Cannot sign content -- invalid key!: " + e.getMessage()); <ide> } catch (SignatureException e) { <del> throw new IOException("Cannot sign content -- signature failure!", e); <add> throw new IOException("Cannot sign content -- signature failure!: " + e.getMessage()); <ide> } catch (NoSuchAlgorithmException e) { <del> throw new IOException("Cannot sign content -- unknown algorithm!", e); <add> throw new IOException("Cannot sign content -- unknown algorithm!: " + e.getMessage()); <ide> } catch (InterruptedException e) { <del> throw new IOException("Low-level network failure!", e); <add> throw new IOException("Low-level network failure!: " + e.getMessage()); <ide> } <ide> } <ide>
Java
apache-2.0
deb1f5a1d634c1ba601b49e228b748daf4a45903
0
ZuInnoTe/hadoopoffice,ZuInnoTe/hadoopoffice
/** * Copyright 2016 ZuInnoTe (Jörn Franke) <[email protected]> * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. **/ package org.zuinnote.hadoop.office.format.common.writer; import java.util.ArrayList; import java.util.List; import java.util.Locale; import java.util.Map; import java.util.HashMap; import java.util.Date; import java.text.ParseException; import java.text.SimpleDateFormat; import java.io.InputStream; import java.io.OutputStream; import java.io.IOException; import java.security.GeneralSecurityException; import org.apache.poi.ss.usermodel.FormulaEvaluator; import org.apache.poi.ss.usermodel.Workbook; import org.apache.poi.ss.usermodel.Drawing; import org.apache.poi.ss.usermodel.ClientAnchor; import org.apache.poi.ss.usermodel.Sheet; import org.apache.poi.ss.usermodel.Row; import org.apache.poi.ss.usermodel.Cell; import org.apache.poi.ss.usermodel.Comment; import org.apache.poi.xssf.usermodel.XSSFWorkbook; import org.apache.poi.hssf.usermodel.HSSFWorkbook; import org.apache.poi.ss.util.CellAddress; import org.apache.poi.ss.util.WorkbookUtil; import org.apache.poi.poifs.filesystem.POIFSFileSystem; import org.apache.poi.poifs.crypt.CipherAlgorithm; import org.apache.poi.poifs.crypt.HashAlgorithm; import org.apache.poi.poifs.crypt.EncryptionMode; import org.apache.poi.poifs.crypt.Encryptor; import org.apache.poi.poifs.crypt.EncryptionInfo; import org.apache.poi.poifs.crypt.ChainingMode; import org.apache.poi.hssf.record.crypto.Biff8EncryptionKey; import org.apache.poi.POIXMLProperties; import org.apache.poi.hpsf.SummaryInformation; import org.apache.poi.openxml4j.util.Nullable; import org.apache.commons.logging.LogFactory; import org.apache.commons.logging.Log; import org.zuinnote.hadoop.office.format.common.HadoopOfficeReadConfiguration; import org.zuinnote.hadoop.office.format.common.HadoopOfficeWriteConfiguration; import org.zuinnote.hadoop.office.format.common.dao.SpreadSheetCellDAO; import org.zuinnote.hadoop.office.format.common.parser.FormatNotUnderstoodException; import org.zuinnote.hadoop.office.format.common.parser.MSExcelParser; public class MSExcelWriter implements OfficeSpreadSheetWriterInterface { public static final String FORMAT_OOXML = "ooxmlexcel"; public static final String FORMAT_OLD = "oldexcel"; protected static final String[] VALID_FORMAT = {FORMAT_OOXML, FORMAT_OLD}; private static final Log LOG = LogFactory.getLog(MSExcelWriter.class.getName()); private static final String DEFAULT_FORMAT = VALID_FORMAT[0]; private String format=DEFAULT_FORMAT; private OutputStream oStream; private Workbook currentWorkbook; private Map<String,Drawing> mappedDrawings; private List<Workbook> listOfWorkbooks; private POIFSFileSystem ooxmlDocumentFileSystem; private HadoopOfficeWriteConfiguration howc; private CipherAlgorithm encryptAlgorithmCipher; private HashAlgorithm hashAlgorithmCipher; private EncryptionMode encryptionModeCipher; private ChainingMode chainModeCipher; /** * * Creates a new writer for MS Excel files * * @param excelFormat format of the Excel: ooxmlexcel: Excel 2007-2013 (.xlsx), oldexcel: Excel 2003 (.xls) * @param howc HadoopOfficeWriteConfiguration * locale Locale to be used to evaluate cells * ignoreMissingLinkedWorkbooks if true then missing linked workbooks are ignored during writing, if false then missing linked workbooks are not ignored and need to be present * fileName filename without path of the workbook * commentAuthor default author for comments * commentWidth width of comments in terms of number of columns * commentHeight height of commments in terms of number of rows * password Password of this document (null if no password) * encryptAlgorithm algorithm use for encryption. It is recommended to carefully choose the algorithm. Supported for .xlsx: aes128,aes192,aes256,des,des3,des3_112,rc2,rc4,rsa. Support for .xls: rc4 * hashAlgorithm Hash algorithm, Supported for .xslx: sha512, sha384, sha256, sha224, whirlpool, sha1, ripemd160,ripemd128, md5, md4, md2,none. Ignored for .xls * encryptMode Encrypt mode, Supported for .xlsx: binaryRC4,standard,agile,cryptoAPI. Ignored for .xls * chainMode Chain mode, Supported for .xlsx: cbc, cfb, ecb. Ignored for .xls * metadata properties as metadata. Currently the following are supported for .xlsx documents: category,contentstatus, contenttype,created (date),creator,description,identifier,keywords,lastmodifiedbyuser,lastprinted (date),modified (date),revision,subject,title. Everything refering to a date needs to be in the format (EEE MMM dd hh:mm:ss zzz yyyy) see http://docs.oracle.com/javase/7/docs/api/java/util/Date.html#toString() Additionally all custom.* are defined as custom properties. Example custom.myproperty. Currently the following are supported for .xls documents: applicationname,author,charcount, comments, createdatetime,edittime,keywords,lastauthor,lastprinted,lastsavedatetime,pagecount,revnumber,security,subject,template,title,wordcount * * @throws org.zuinnote.hadoop.office.format.common.writer.InvalidWriterConfigurationException in case the writer is not configured correctly * */ public MSExcelWriter(String excelFormat, HadoopOfficeWriteConfiguration howc) throws InvalidWriterConfigurationException { boolean formatFound=isSupportedFormat(excelFormat); if (!(formatFound)) { LOG.error("Unknown Excel format: "+this.format); throw new InvalidWriterConfigurationException("Unknown Excel format: "+this.format); } this.format=excelFormat; this.howc=howc; this.encryptAlgorithmCipher=getAlgorithmCipher(this.howc.getEncryptAlgorithm()); this.hashAlgorithmCipher=getHashAlgorithm(this.howc.getHashAlgorithm()); this.encryptionModeCipher=getEncryptionModeCipher(this.howc.getEncryptMode()); this.chainModeCipher=getChainMode(this.howc.getChainMode()); } /** * Creates a new Excel workbook for the output stream. Note: You need to save it AFTER adding the cells via addSpreadSheetCell using the method finalizeWrite * * @param oStream OutputStream where the Workbook should be written when calling finalizeWrite * @param linkedWorkbooks linked workbooks that are already existing and linked to this spreadsheet * @param linkedWorkbooksPasswords a map of passwords and linkedworkbooks. The key is the filename without path of the linkedworkbook and the value is the password * * @throws org.zuinnote.hadoop.office.format.common.writer.OfficeWriterException in case of errors writing to the outputstream * */ public void create(OutputStream oStream, Map<String,InputStream> linkedWorkbooks,Map<String,String> linkedWorkbooksPasswords) throws OfficeWriterException { this.oStream=oStream; // create a new Workbook either in old Excel or "new" Excel format if (this.format.equals(MSExcelWriter.FORMAT_OOXML)) { this.currentWorkbook=new XSSFWorkbook(); this.ooxmlDocumentFileSystem = new POIFSFileSystem(); } else if (this.format.equals(MSExcelWriter.FORMAT_OLD)) { this.currentWorkbook=new HSSFWorkbook(); ((HSSFWorkbook)this.currentWorkbook).createInformationProperties(); } FormulaEvaluator currentFormulaEvaluator=this.currentWorkbook.getCreationHelper().createFormulaEvaluator(); HashMap<String,FormulaEvaluator> linkedFormulaEvaluators=new HashMap<>(); linkedFormulaEvaluators.put(this.howc.getFileName(),currentFormulaEvaluator); this.mappedDrawings=new HashMap<>(); // add current workbook to list of linked workbooks this.listOfWorkbooks=new ArrayList<>(); // parse linked workbooks try { for (Map.Entry<String,InputStream> entry: linkedWorkbooks.entrySet()) { // parse linked workbook HadoopOfficeReadConfiguration currentLinkedWBHOCR = new HadoopOfficeReadConfiguration(); currentLinkedWBHOCR.setLocale(this.howc.getLocale()); currentLinkedWBHOCR.setSheets(null); currentLinkedWBHOCR.setIgnoreMissingLinkedWorkbooks(this.howc.getIgnoreMissingLinkedWorkbooks()); currentLinkedWBHOCR.setFileName(entry.getKey()); currentLinkedWBHOCR.setPassword(linkedWorkbooksPasswords.get(entry.getKey())); currentLinkedWBHOCR.setMetaDataFilter(null); MSExcelParser currentLinkedWorkbookParser = new MSExcelParser(currentLinkedWBHOCR,null); try { currentLinkedWorkbookParser.parse(entry.getValue()); } catch (FormatNotUnderstoodException e) { LOG.error(e); throw new OfficeWriterException(e.toString()); } this.listOfWorkbooks.add(currentLinkedWorkbookParser.getCurrentWorkbook()); linkedFormulaEvaluators.put(entry.getKey(),currentLinkedWorkbookParser.getCurrentFormulaEvaluator()); this.currentWorkbook.linkExternalWorkbook(entry.getKey(),currentLinkedWorkbookParser.getCurrentWorkbook()); } } finally { // close linked workbook inputstreams for (InputStream currentIS: linkedWorkbooks.values()) { try { currentIS.close(); } catch (IOException e) { LOG.error(e); } } } LOG.debug("Size of linked formula evaluators map: "+linkedFormulaEvaluators.size()); currentFormulaEvaluator.setupReferencedWorkbooks(linkedFormulaEvaluators); } /** * Add a cell to the current Workbook * * @param newDAO cell to add. If it is already existing an exception will be thrown. Note that the sheet name is sanitized using org.apache.poi.ss.util.WorkbookUtil.createSafeSheetName. The Cell address needs to be in A1 format. Either formula or formattedValue must be not null. * */ @Override public void write(Object newDAO) throws OfficeWriterException { if (!(newDAO instanceof SpreadSheetCellDAO)) { throw new OfficeWriterException("Objects which are not of the class SpreadSheetCellDAO are not supported for writing."); } SpreadSheetCellDAO sscd = (SpreadSheetCellDAO)newDAO; // check sheetname (needs to be there) if ((sscd.getSheetName()==null) || ("".equals(sscd.getSheetName()))) { throw new OfficeWriterException("Invalid cell specification: empy sheet name not allowed."); } // check celladdress (needs to be there) if ((sscd.getAddress()==null) || ("".equals(sscd.getAddress()))) { throw new OfficeWriterException("Invalid cell specification: empy cell address not allowed."); } // check that either formula or formatted value is filled if ((sscd.getFormula()==null) && (sscd.getFormattedValue()==null)) { throw new OfficeWriterException("Invalid cell specification: either formula or formattedValue needs to be specified for cell."); } String safeSheetName=WorkbookUtil.createSafeSheetName(sscd.getSheetName()); Sheet currentSheet=this.currentWorkbook.getSheet(safeSheetName); if (currentSheet==null) {// create sheet if it does not exist yet currentSheet=this.currentWorkbook.createSheet(safeSheetName); if (!(safeSheetName.equals(sscd.getSheetName()))) { LOG.warn("Sheetname modified from \""+sscd.getSheetName()+"\" to \""+safeSheetName+"\" to correspond to Excel conventions."); } // create drawing anchor (needed for comments...) this.mappedDrawings.put(safeSheetName,currentSheet.createDrawingPatriarch()); } // check if cell exist CellAddress currentCA = new CellAddress(sscd.getAddress()); Row currentRow = currentSheet.getRow(currentCA.getRow()); if (currentRow==null) { // row does not exist? => create it currentRow=currentSheet.createRow(currentCA.getRow()); } Cell currentCell = currentRow.getCell(currentCA.getColumn()); if (currentCell!=null) { // cell already exists? => throw exception throw new OfficeWriterException("Invalid cell specification: cell already exists at "+currentCA); } // create cell currentCell=currentRow.createCell(currentCA.getColumn()); // set the values accordingly if (!("".equals(sscd.getFormula()))) { // if formula exists then use formula currentCell.setCellFormula(sscd.getFormula()); } else { // else use formattedValue currentCell.setCellValue(sscd.getFormattedValue()); } // set comment if ((sscd.getComment()!=null) && (!("".equals(sscd.getComment())))) { /** the following operations are necessary to create comments **/ /** Define size of the comment window **/ ClientAnchor anchor = this.currentWorkbook.getCreationHelper().createClientAnchor(); anchor.setCol1(currentCell.getColumnIndex()); anchor.setCol2(currentCell.getColumnIndex()+this.howc.getCommentWidth()); anchor.setRow1(currentRow.getRowNum()); anchor.setRow2(currentRow.getRowNum()+this.howc.getCommentHeight()); /** create comment **/ Comment currentComment = mappedDrawings.get(safeSheetName).createCellComment(anchor); currentComment.setString(this.currentWorkbook.getCreationHelper().createRichTextString(sscd.getComment())); currentComment.setAuthor(this.howc.getCommentAuthor()); currentCell.setCellComment(currentComment); } } /** * Writes the document in-memory representation to the OutputStream. Afterwards, it closes all related workbooks. * * @throws java.io.IOException in case of issues writing * * */ @Override public void close() throws IOException { try { // prepare metadata prepareMetaData(); // write if (this.oStream!=null) { if (this.howc.getPassword()==null) { // no encryption this.currentWorkbook.write(this.oStream); this.oStream.close(); } else { // encryption if (this.currentWorkbook instanceof HSSFWorkbook) { // old Excel format LOG.debug("encrypting HSSFWorkbook"); Biff8EncryptionKey.setCurrentUserPassword(this.howc.getPassword()); this.currentWorkbook.write(this.oStream); this.oStream.close(); Biff8EncryptionKey.setCurrentUserPassword(null); } else if (this.currentWorkbook instanceof XSSFWorkbook) { if (this.encryptAlgorithmCipher==null) { LOG.error("No encryption algorithm specified"); } else if (this.hashAlgorithmCipher==null) { LOG.error("No hash algorithm specified"); } else if (this.encryptionModeCipher==null) { LOG.error("No encryption mode specified"); } else if (this.chainModeCipher==null) { LOG.error("No chain mode specified"); } else { try { EncryptionInfo info = new EncryptionInfo(this.encryptionModeCipher, this.encryptAlgorithmCipher, this.hashAlgorithmCipher, -1, -1, this.chainModeCipher); Encryptor enc = info.getEncryptor(); enc.confirmPassword(this.howc.getPassword()); OutputStream os = null; try { os = enc.getDataStream(ooxmlDocumentFileSystem); } catch (GeneralSecurityException e) { LOG.error(e); } if (os!=null) { this.currentWorkbook.write(os); } ooxmlDocumentFileSystem.writeFilesystem(this.oStream); } finally { this.oStream.close(); } } } else { LOG.error("Could not write encrypted workbook, because type of workbook is unknown"); } } } } finally { // close filesystems if (this.ooxmlDocumentFileSystem!=null) { ooxmlDocumentFileSystem.close(); } // close main workbook if (this.currentWorkbook!=null) { this.currentWorkbook.close(); } // close linked workbooks for (Workbook currentWorkbookItem: this.listOfWorkbooks) { if (currentWorkbookItem!=null) { currentWorkbookItem.close(); } } } } /** * Checks if format is supported * * @param format String describing format * * @return true, if supported, false if not * */ public static boolean isSupportedFormat(String format) { for (int i=0;i<MSExcelWriter.VALID_FORMAT.length;i++) { if (VALID_FORMAT[i].equals(format)) { return true; } } return false; } /** * Returns the CipherAlgorithm object matching the String. * * @param encryptAlgorithm encryption algorithm * *@return CipherAlgorithm object corresponding to encryption algorithm. Null if does not correspond to any algorithm. * * */ private static CipherAlgorithm getAlgorithmCipher(String encryptAlgorithm) { if (encryptAlgorithm==null) { return null; } switch (encryptAlgorithm) { case "aes128": return CipherAlgorithm.aes128; case "aes192": return CipherAlgorithm.aes192; case "aes256": return CipherAlgorithm.aes256; case "des": return CipherAlgorithm.des; case "des3": return CipherAlgorithm.des3; case "des3_112": return CipherAlgorithm.des3_112; case "rc2": return CipherAlgorithm.rc2; case "rc4": return CipherAlgorithm.rc4; case "rsa": return CipherAlgorithm.rsa; default: LOG.error("Uknown encryption algorithm: \""+encryptAlgorithm+"\""); break; } return null; } /** * Returns the HashAlgorithm object matching the String. * * @param hashAlgorithm hash algorithm * *@return HashAlgorithm object corresponding to hash algorithm. Null if does not correspond to any algorithm. * * */ private static HashAlgorithm getHashAlgorithm(String hashAlgorithm) { if (hashAlgorithm==null) { return null; } switch (hashAlgorithm) { case "md2": return HashAlgorithm.md2; case "md4": return HashAlgorithm.md4; case "md5": return HashAlgorithm.md5; case "none": return HashAlgorithm.none; case "ripemd128": return HashAlgorithm.ripemd128; case "ripemd160": return HashAlgorithm.ripemd160; case "sha1": return HashAlgorithm.sha1; case "sha224": return HashAlgorithm.sha224; case "sha256": return HashAlgorithm.sha256; case "sha384": return HashAlgorithm.sha384; case "sha512": return HashAlgorithm.sha512; case "whirlpool": return HashAlgorithm.whirlpool; default: LOG.error("Uknown hash algorithm: \""+hashAlgorithm+"\""); break; } return null; } /** * Returns the EncryptionMode object matching the String. * * @param encryptionMode encryption mode * *@return EncryptionMode object corresponding to encryption mode. Null if does not correspond to any mode. * * */ private static EncryptionMode getEncryptionModeCipher(String encryptionMode) { if (encryptionMode==null) { return null; } switch (encryptionMode) { case "agile": return EncryptionMode.agile; case "binaryRC4": return EncryptionMode.binaryRC4; case "cryptoAPI": return EncryptionMode.cryptoAPI; case "standard": return EncryptionMode.standard; default: LOG.error("Uknown enncryption mode \""+encryptionMode+"\""); break; //case "xor": return EncryptionMode.xor; // does not seem to be supported anymore } return null; } /** * Returns the ChainMode object matching the String. * * @param chainMode chain mode * *@return ChainMode object corresponding to chain mode. Null if does not correspond to any mode. * * */ private static ChainingMode getChainMode(String chainMode) { if (chainMode==null) { return null; } switch (chainMode) { case "cbc": return ChainingMode.cbc; case "cfb": return ChainingMode.cfb; case "ecb": return ChainingMode.ecb; default: LOG.error("Uknown chainmode: \""+chainMode+"\""); break; } return null; } /** * writes metadata into document * * */ private void prepareMetaData() { if (this.currentWorkbook instanceof HSSFWorkbook) { prepareHSSFMetaData(); } else if (this.currentWorkbook instanceof XSSFWorkbook) { prepareXSSFMetaData(); } else { LOG.error("Unknown workbook type. Cannot write metadata."); } } /** * * Write metadata into HSSF document * */ private void prepareHSSFMetaData() { HSSFWorkbook currentHSSFWorkbook = (HSSFWorkbook) this.currentWorkbook; SummaryInformation summaryInfo = currentHSSFWorkbook.getSummaryInformation(); if (summaryInfo==null) { currentHSSFWorkbook.createInformationProperties(); summaryInfo = currentHSSFWorkbook.getSummaryInformation(); } SimpleDateFormat formatSDF = new SimpleDateFormat(MSExcelParser.DATE_FORMAT); for (Map.Entry<String,String> entry: this.howc.getMetadata().entrySet()) { // process general properties try { switch(entry.getKey()) { case "applicationname": summaryInfo.setApplicationName(entry.getValue()); break; case "author": summaryInfo.setAuthor(entry.getValue()); break; case "charcount": summaryInfo.setCharCount(Integer.parseInt(entry.getValue())); break; case "comments": summaryInfo.setComments(entry.getValue()); break; case "createdatetime": summaryInfo.setCreateDateTime(formatSDF.parse(entry.getValue())); break; case "edittime": summaryInfo.setEditTime(Long.parseLong(entry.getValue())); break; case "keywords": summaryInfo.setKeywords(entry.getValue()); break; case "lastauthor": summaryInfo.setLastAuthor(entry.getValue()); break; case "lastprinted": summaryInfo.setLastPrinted(formatSDF.parse(entry.getValue())); break; case "lastsavedatetime": summaryInfo.setLastSaveDateTime(formatSDF.parse(entry.getValue())); break; case "pagecount": summaryInfo.setPageCount(Integer.parseInt(entry.getValue())); break; case "revnumber": summaryInfo.setRevNumber(entry.getValue()); break; case "security": summaryInfo.setSecurity(Integer.parseInt(entry.getValue())); break; case "subject": summaryInfo.setSubject(entry.getValue()); break; case "template": summaryInfo.setTemplate(entry.getValue()); break; case "title": summaryInfo.setTitle(entry.getValue()); break; case "wordcount": summaryInfo.setWordCount(Integer.parseInt(entry.getValue())); break; default: LOG.warn("Unknown metadata key: "+entry.getKey()); break; } } catch (ParseException pe) { LOG.error(pe); } } } /** * * Write metadata into XSSF document * */ private void prepareXSSFMetaData() { XSSFWorkbook currentXSSFWorkbook = (XSSFWorkbook) this.currentWorkbook; POIXMLProperties props = currentXSSFWorkbook.getProperties(); POIXMLProperties.CoreProperties coreProp=props.getCoreProperties(); POIXMLProperties.CustomProperties custProp = props.getCustomProperties(); SimpleDateFormat formatSDF = new SimpleDateFormat(MSExcelParser.DATE_FORMAT); for (Map.Entry<String,String> entry: this.howc.getMetadata().entrySet()) { // process general properties boolean attribMatch=false; try { switch(entry.getKey()) { case "category": coreProp.setCategory(entry.getValue()); attribMatch=true; break; case "contentstatus": coreProp.setContentStatus(entry.getValue()); attribMatch=true; break; case "contenttype": coreProp.setContentType(entry.getValue()); attribMatch=true; break; case "created": coreProp.setCreated(new Nullable<Date>(formatSDF.parse(entry.getValue()))); attribMatch=true; break; case "creator": coreProp.setCreator(entry.getValue()); attribMatch=true; break; case "description": coreProp.setDescription(entry.getValue()); attribMatch=true; break; case "identifier": coreProp.setIdentifier(entry.getValue()); attribMatch=true; break; case "keywords": coreProp.setKeywords(entry.getValue()); attribMatch=true; break; case "lastmodifiedbyuser": coreProp.setLastModifiedByUser(entry.getValue()); attribMatch=true; break; case "lastprinted": coreProp.setLastPrinted(new Nullable<Date>(formatSDF.parse(entry.getValue()))); attribMatch=true; break; case "modified": coreProp.setModified(new Nullable<Date>(formatSDF.parse(entry.getValue()))); attribMatch=true; break; case "revision": coreProp.setRevision(entry.getValue()); attribMatch=true; break; case "subject": coreProp.setSubjectProperty(entry.getValue()); attribMatch=true; break; case "title": coreProp.setTitle(entry.getValue()); attribMatch=true; break; default: // later we check if custom properties need to be added break; } if (!(attribMatch)) { // process custom properties if (entry.getKey().startsWith("custom.")) { String strippedKey=entry.getKey().substring("custom.".length()); if (strippedKey.length()>0) { custProp.addProperty(strippedKey,entry.getValue()); } } else { LOG.warn("Unknown metadata key: "+entry.getKey()); } } } catch (ParseException pe) { LOG.error(pe); } } } }
fileformat/src/main/java/org/zuinnote/hadoop/office/format/common/writer/MSExcelWriter.java
/** * Copyright 2016 ZuInnoTe (Jörn Franke) <[email protected]> * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. **/ package org.zuinnote.hadoop.office.format.common.writer; import java.util.ArrayList; import java.util.List; import java.util.Locale; import java.util.Map; import java.util.HashMap; import java.util.Date; import java.text.ParseException; import java.text.SimpleDateFormat; import java.io.InputStream; import java.io.OutputStream; import java.io.IOException; import java.security.GeneralSecurityException; import org.apache.poi.ss.usermodel.FormulaEvaluator; import org.apache.poi.ss.usermodel.Workbook; import org.apache.poi.ss.usermodel.Drawing; import org.apache.poi.ss.usermodel.ClientAnchor; import org.apache.poi.ss.usermodel.Sheet; import org.apache.poi.ss.usermodel.Row; import org.apache.poi.ss.usermodel.Cell; import org.apache.poi.ss.usermodel.Comment; import org.apache.poi.xssf.usermodel.XSSFWorkbook; import org.apache.poi.hssf.usermodel.HSSFWorkbook; import org.apache.poi.ss.util.CellAddress; import org.apache.poi.ss.util.WorkbookUtil; import org.apache.poi.poifs.filesystem.POIFSFileSystem; import org.apache.poi.poifs.crypt.CipherAlgorithm; import org.apache.poi.poifs.crypt.HashAlgorithm; import org.apache.poi.poifs.crypt.EncryptionMode; import org.apache.poi.poifs.crypt.Encryptor; import org.apache.poi.poifs.crypt.EncryptionInfo; import org.apache.poi.poifs.crypt.ChainingMode; import org.apache.poi.hssf.record.crypto.Biff8EncryptionKey; import org.apache.poi.POIXMLProperties; import org.apache.poi.hpsf.SummaryInformation; import org.apache.poi.openxml4j.util.Nullable; import org.apache.commons.logging.LogFactory; import org.apache.commons.logging.Log; import org.zuinnote.hadoop.office.format.common.HadoopOfficeReadConfiguration; import org.zuinnote.hadoop.office.format.common.HadoopOfficeWriteConfiguration; import org.zuinnote.hadoop.office.format.common.dao.SpreadSheetCellDAO; import org.zuinnote.hadoop.office.format.common.parser.FormatNotUnderstoodException; import org.zuinnote.hadoop.office.format.common.parser.MSExcelParser; public class MSExcelWriter implements OfficeSpreadSheetWriterInterface { public static final String FORMAT_OOXML = "ooxmlexcel"; public static final String FORMAT_OLD = "oldexcel"; protected static final String[] VALID_FORMAT = {FORMAT_OOXML, FORMAT_OLD}; private static final Log LOG = LogFactory.getLog(MSExcelWriter.class.getName()); private static final String DEFAULT_FORMAT = VALID_FORMAT[0]; private String format=DEFAULT_FORMAT; private OutputStream oStream; private Workbook currentWorkbook; private Map<String,Drawing> mappedDrawings; private List<Workbook> listOfWorkbooks; private POIFSFileSystem ooxmlDocumentFileSystem; private HadoopOfficeWriteConfiguration howc; private CipherAlgorithm encryptAlgorithmCipher; private HashAlgorithm hashAlgorithmCipher; private EncryptionMode encryptionModeCipher; private ChainingMode chainModeCipher; /** * * Creates a new writer for MS Excel files * * @param excelFormat format of the Excel: ooxmlexcel: Excel 2007-2013 (.xlsx), oldexcel: Excel 2003 (.xls) * @param howc HadoopOfficeWriteConfiguration * locale Locale to be used to evaluate cells * ignoreMissingLinkedWorkbooks if true then missing linked workbooks are ignored during writing, if false then missing linked workbooks are not ignored and need to be present * fileName filename without path of the workbook * commentAuthor default author for comments * commentWidth width of comments in terms of number of columns * commentHeight height of commments in terms of number of rows * password Password of this document (null if no password) * encryptAlgorithm algorithm use for encryption. It is recommended to carefully choose the algorithm. Supported for .xlsx: aes128,aes192,aes256,des,des3,des3_112,rc2,rc4,rsa. Support for .xls: rc4 * hashAlgorithm Hash algorithm, Supported for .xslx: sha512, sha384, sha256, sha224, whirlpool, sha1, ripemd160,ripemd128, md5, md4, md2,none. Ignored for .xls * encryptMode Encrypt mode, Supported for .xlsx: binaryRC4,standard,agile,cryptoAPI. Ignored for .xls * chainMode Chain mode, Supported for .xlsx: cbc, cfb, ecb. Ignored for .xls * metadata properties as metadata. Currently the following are supported for .xlsx documents: category,contentstatus, contenttype,created (date),creator,description,identifier,keywords,lastmodifiedbyuser,lastprinted (date),modified (date),revision,subject,title. Everything refering to a date needs to be in the format (EEE MMM dd hh:mm:ss zzz yyyy) see http://docs.oracle.com/javase/7/docs/api/java/util/Date.html#toString() Additionally all custom.* are defined as custom properties. Example custom.myproperty. Currently the following are supported for .xls documents: applicationname,author,charcount, comments, createdatetime,edittime,keywords,lastauthor,lastprinted,lastsavedatetime,pagecount,revnumber,security,subject,template,title,wordcount * * @throws org.zuinnote.hadoop.office.format.common.writer.InvalidWriterConfigurationException in case the writer is not configured correctly * */ public MSExcelWriter(String excelFormat, HadoopOfficeWriteConfiguration howc) throws InvalidWriterConfigurationException { boolean formatFound=isSupportedFormat(excelFormat); if (!(formatFound)) { LOG.error("Unknown Excel format: "+this.format); throw new InvalidWriterConfigurationException("Unknown Excel format: "+this.format); } this.format=excelFormat; this.howc=howc; this.encryptAlgorithmCipher=getAlgorithmCipher(this.howc.getEncryptAlgorithm()); this.hashAlgorithmCipher=getHashAlgorithm(this.howc.getHashAlgorithm()); this.encryptionModeCipher=getEncryptionModeCipher(this.howc.getEncryptMode()); this.chainModeCipher=getChainMode(this.howc.getChainMode()); } /** * Creates a new Excel workbook for the output stream. Note: You need to save it AFTER adding the cells via addSpreadSheetCell using the method finalizeWrite * * @param oStream OutputStream where the Workbook should be written when calling finalizeWrite * @param linkedWorkbooks linked workbooks that are already existing and linked to this spreadsheet * @param linkedWorkbooksPasswords a map of passwords and linkedworkbooks. The key is the filename without path of the linkedworkbook and the value is the password * * @throws org.zuinnote.hadoop.office.format.common.writer.OfficeWriterException in case of errors writing to the outputstream * */ public void create(OutputStream oStream, Map<String,InputStream> linkedWorkbooks,Map<String,String> linkedWorkbooksPasswords) throws OfficeWriterException { this.oStream=oStream; // create a new Workbook either in old Excel or "new" Excel format if (this.format.equals(MSExcelWriter.FORMAT_OOXML)) { this.currentWorkbook=new XSSFWorkbook(); this.ooxmlDocumentFileSystem = new POIFSFileSystem(); } else if (this.format.equals(MSExcelWriter.FORMAT_OLD)) { this.currentWorkbook=new HSSFWorkbook(); ((HSSFWorkbook)this.currentWorkbook).createInformationProperties(); } FormulaEvaluator currentFormulaEvaluator=this.currentWorkbook.getCreationHelper().createFormulaEvaluator(); HashMap<String,FormulaEvaluator> linkedFormulaEvaluators=new HashMap<>(); linkedFormulaEvaluators.put(this.howc.getFileName(),currentFormulaEvaluator); this.mappedDrawings=new HashMap<>(); // add current workbook to list of linked workbooks this.listOfWorkbooks=new ArrayList<>(); // parse linked workbooks try { for (Map.Entry<String,InputStream> entry: linkedWorkbooks.entrySet()) { // parse linked workbook HadoopOfficeReadConfiguration currentLinkedWBHOCR = new HadoopOfficeReadConfiguration(); currentLinkedWBHOCR.setLocale(this.howc.getLocale()); currentLinkedWBHOCR.setSheets(null); currentLinkedWBHOCR.setIgnoreMissingLinkedWorkbooks(this.howc.getIgnoreMissingLinkedWorkbooks()); currentLinkedWBHOCR.setFileName(entry.getKey()); currentLinkedWBHOCR.setPassword(linkedWorkbooksPasswords.get(entry.getKey())); currentLinkedWBHOCR.setMetaDataFilter(null); MSExcelParser currentLinkedWorkbookParser = new MSExcelParser(currentLinkedWBHOCR,null); try { currentLinkedWorkbookParser.parse(entry.getValue()); } catch (FormatNotUnderstoodException e) { LOG.error(e); throw new OfficeWriterException(e.toString()); } this.listOfWorkbooks.add(currentLinkedWorkbookParser.getCurrentWorkbook()); linkedFormulaEvaluators.put(entry.getKey(),currentLinkedWorkbookParser.getCurrentFormulaEvaluator()); this.currentWorkbook.linkExternalWorkbook(entry.getKey(),currentLinkedWorkbookParser.getCurrentWorkbook()); } } finally { // close linked workbook inputstreams for (InputStream currentIS: linkedWorkbooks.values()) { try { currentIS.close(); } catch (IOException e) { LOG.error(e); } } } LOG.debug("Size of linked formula evaluators map: "+linkedFormulaEvaluators.size()); currentFormulaEvaluator.setupReferencedWorkbooks(linkedFormulaEvaluators); } /** * Add a cell to the current Workbook * * @param newDAO cell to add. If it is already existing an exception will be thrown. Note that the sheet name is sanitized using org.apache.poi.ss.util.WorkbookUtil.createSafeSheetName. The Cell address needs to be in A1 format. Either formula or formattedValue must be not null. * */ public void write(Object newDAO) throws OfficeWriterException { if (!(newDAO instanceof SpreadSheetCellDAO)) { throw new OfficeWriterException("Objects which are not of the class SpreadSheetCellDAO are not supported for writing."); } SpreadSheetCellDAO sscd = (SpreadSheetCellDAO)newDAO; // check sheetname (needs to be there) if ((sscd.getSheetName()==null) || ("".equals(sscd.getSheetName()))) { throw new OfficeWriterException("Invalid cell specification: empy sheet name not allowed."); } // check celladdress (needs to be there) if ((sscd.getAddress()==null) || ("".equals(sscd.getAddress()))) { throw new OfficeWriterException("Invalid cell specification: empy cell address not allowed."); } // check that either formula or formatted value is filled if ((sscd.getFormula()==null) && (sscd.getFormattedValue()==null)) { throw new OfficeWriterException("Invalid cell specification: either formula or formattedValue needs to be specified for cell."); } String safeSheetName=WorkbookUtil.createSafeSheetName(sscd.getSheetName()); Sheet currentSheet=this.currentWorkbook.getSheet(safeSheetName); if (currentSheet==null) {// create sheet if it does not exist yet currentSheet=this.currentWorkbook.createSheet(safeSheetName); if (!(safeSheetName.equals(sscd.getSheetName()))) { LOG.warn("Sheetname modified from \""+sscd.getSheetName()+"\" to \""+safeSheetName+"\" to correspond to Excel conventions."); } // create drawing anchor (needed for comments...) this.mappedDrawings.put(safeSheetName,currentSheet.createDrawingPatriarch()); } // check if cell exist CellAddress currentCA = new CellAddress(sscd.getAddress()); Row currentRow = currentSheet.getRow(currentCA.getRow()); if (currentRow==null) { // row does not exist? => create it currentRow=currentSheet.createRow(currentCA.getRow()); } Cell currentCell = currentRow.getCell(currentCA.getColumn()); if (currentCell!=null) { // cell already exists? => throw exception throw new OfficeWriterException("Invalid cell specification: cell already exists at "+currentCA); } // create cell currentCell=currentRow.createCell(currentCA.getColumn()); // set the values accordingly if (!("".equals(sscd.getFormula()))) { // if formula exists then use formula currentCell.setCellFormula(sscd.getFormula()); } else { // else use formattedValue currentCell.setCellValue(sscd.getFormattedValue()); } // set comment if ((sscd.getComment()!=null) && (!("".equals(sscd.getComment())))) { /** the following operations are necessary to create comments **/ /** Define size of the comment window **/ ClientAnchor anchor = this.currentWorkbook.getCreationHelper().createClientAnchor(); anchor.setCol1(currentCell.getColumnIndex()); anchor.setCol2(currentCell.getColumnIndex()+this.howc.getCommentWidth()); anchor.setRow1(currentRow.getRowNum()); anchor.setRow2(currentRow.getRowNum()+this.howc.getCommentHeight()); /** create comment **/ Comment currentComment = mappedDrawings.get(safeSheetName).createCellComment(anchor); currentComment.setString(this.currentWorkbook.getCreationHelper().createRichTextString(sscd.getComment())); currentComment.setAuthor(this.howc.getCommentAuthor()); currentCell.setCellComment(currentComment); } } /** * Writes the document in-memory representation to the OutputStream. Afterwards, it closes all related workbooks. * * @throws java.io.IOException in case of issues writing * * */ public void close() throws IOException { try { // prepare metadata prepareMetaData(); // write if (this.oStream!=null) { if (this.howc.getPassword()==null) { // no encryption this.currentWorkbook.write(this.oStream); this.oStream.close(); } else { // encryption if (this.currentWorkbook instanceof HSSFWorkbook) { // old Excel format LOG.debug("encrypting HSSFWorkbook"); Biff8EncryptionKey.setCurrentUserPassword(this.howc.getPassword()); this.currentWorkbook.write(this.oStream); this.oStream.close(); Biff8EncryptionKey.setCurrentUserPassword(null); } else if (this.currentWorkbook instanceof XSSFWorkbook) { if (this.encryptAlgorithmCipher==null) { LOG.error("No encryption algorithm specified"); } else if (this.hashAlgorithmCipher==null) { LOG.error("No hash algorithm specified"); } else if (this.encryptionModeCipher==null) { LOG.error("No encryption mode specified"); } else if (this.chainModeCipher==null) { LOG.error("No chain mode specified"); } else { try { EncryptionInfo info = new EncryptionInfo(this.encryptionModeCipher, this.encryptAlgorithmCipher, this.hashAlgorithmCipher, -1, -1, this.chainModeCipher); Encryptor enc = info.getEncryptor(); enc.confirmPassword(this.howc.getPassword()); OutputStream os = null; try { os = enc.getDataStream(ooxmlDocumentFileSystem); } catch (GeneralSecurityException e) { LOG.error(e); } if (os!=null) { this.currentWorkbook.write(os); } ooxmlDocumentFileSystem.writeFilesystem(this.oStream); } finally { this.oStream.close(); } } } else { LOG.error("Could not write encrypted workbook, because type of workbook is unknown"); } } } } finally { // close filesystems if (this.ooxmlDocumentFileSystem!=null) { ooxmlDocumentFileSystem.close(); } // close main workbook if (this.currentWorkbook!=null) { this.currentWorkbook.close(); } // close linked workbooks for (Workbook currentWorkbookItem: this.listOfWorkbooks) { if (currentWorkbookItem!=null) { currentWorkbookItem.close(); } } } } /** * Checks if format is supported * * @param format String describing format * * @return true, if supported, false if not * */ public static boolean isSupportedFormat(String format) { for (int i=0;i<MSExcelWriter.VALID_FORMAT.length;i++) { if (VALID_FORMAT[i].equals(format)) { return true; } } return false; } /** * Returns the CipherAlgorithm object matching the String. * * @param encryptAlgorithm encryption algorithm * *@return CipherAlgorithm object corresponding to encryption algorithm. Null if does not correspond to any algorithm. * * */ private static CipherAlgorithm getAlgorithmCipher(String encryptAlgorithm) { if (encryptAlgorithm==null) { return null; } switch (encryptAlgorithm) { case "aes128": return CipherAlgorithm.aes128; case "aes192": return CipherAlgorithm.aes192; case "aes256": return CipherAlgorithm.aes256; case "des": return CipherAlgorithm.des; case "des3": return CipherAlgorithm.des3; case "des3_112": return CipherAlgorithm.des3_112; case "rc2": return CipherAlgorithm.rc2; case "rc4": return CipherAlgorithm.rc4; case "rsa": return CipherAlgorithm.rsa; default: LOG.error("Uknown encryption algorithm: \""+encryptAlgorithm+"\""); break; } return null; } /** * Returns the HashAlgorithm object matching the String. * * @param hashAlgorithm hash algorithm * *@return HashAlgorithm object corresponding to hash algorithm. Null if does not correspond to any algorithm. * * */ private static HashAlgorithm getHashAlgorithm(String hashAlgorithm) { if (hashAlgorithm==null) { return null; } switch (hashAlgorithm) { case "md2": return HashAlgorithm.md2; case "md4": return HashAlgorithm.md4; case "md5": return HashAlgorithm.md5; case "none": return HashAlgorithm.none; case "ripemd128": return HashAlgorithm.ripemd128; case "ripemd160": return HashAlgorithm.ripemd160; case "sha1": return HashAlgorithm.sha1; case "sha224": return HashAlgorithm.sha224; case "sha256": return HashAlgorithm.sha256; case "sha384": return HashAlgorithm.sha384; case "sha512": return HashAlgorithm.sha512; case "whirlpool": return HashAlgorithm.whirlpool; default: LOG.error("Uknown hash algorithm: \""+hashAlgorithm+"\""); break; } return null; } /** * Returns the EncryptionMode object matching the String. * * @param encryptionMode encryption mode * *@return EncryptionMode object corresponding to encryption mode. Null if does not correspond to any mode. * * */ private static EncryptionMode getEncryptionModeCipher(String encryptionMode) { if (encryptionMode==null) { return null; } switch (encryptionMode) { case "agile": return EncryptionMode.agile; case "binaryRC4": return EncryptionMode.binaryRC4; case "cryptoAPI": return EncryptionMode.cryptoAPI; case "standard": return EncryptionMode.standard; default: LOG.error("Uknown enncryption mode \""+encryptionMode+"\""); break; //case "xor": return EncryptionMode.xor; // does not seem to be supported anymore } return null; } /** * Returns the ChainMode object matching the String. * * @param chainMode chain mode * *@return ChainMode object corresponding to chain mode. Null if does not correspond to any mode. * * */ private static ChainingMode getChainMode(String chainMode) { if (chainMode==null) { return null; } switch (chainMode) { case "cbc": return ChainingMode.cbc; case "cfb": return ChainingMode.cfb; case "ecb": return ChainingMode.ecb; default: LOG.error("Uknown chainmode: \""+chainMode+"\""); break; } return null; } /** * writes metadata into document * * */ private void prepareMetaData() { if (this.currentWorkbook instanceof HSSFWorkbook) { prepareHSSFMetaData(); } else if (this.currentWorkbook instanceof XSSFWorkbook) { prepareXSSFMetaData(); } else { LOG.error("Unknown workbook type. Cannot write metadata."); } } /** * * Write metadata into HSSF document * */ private void prepareHSSFMetaData() { HSSFWorkbook currentHSSFWorkbook = (HSSFWorkbook) this.currentWorkbook; SummaryInformation summaryInfo = currentHSSFWorkbook.getSummaryInformation(); if (summaryInfo==null) { currentHSSFWorkbook.createInformationProperties(); summaryInfo = currentHSSFWorkbook.getSummaryInformation(); } SimpleDateFormat formatSDF = new SimpleDateFormat(MSExcelParser.DATE_FORMAT); for (Map.Entry<String,String> entry: this.howc.getMetadata().entrySet()) { // process general properties try { switch(entry.getKey()) { case "applicationname": summaryInfo.setApplicationName(entry.getValue()); break; case "author": summaryInfo.setAuthor(entry.getValue()); break; case "charcount": summaryInfo.setCharCount(Integer.parseInt(entry.getValue())); break; case "comments": summaryInfo.setComments(entry.getValue()); break; case "createdatetime": summaryInfo.setCreateDateTime(formatSDF.parse(entry.getValue())); break; case "edittime": summaryInfo.setEditTime(Long.parseLong(entry.getValue())); break; case "keywords": summaryInfo.setKeywords(entry.getValue()); break; case "lastauthor": summaryInfo.setLastAuthor(entry.getValue()); break; case "lastprinted": summaryInfo.setLastPrinted(formatSDF.parse(entry.getValue())); break; case "lastsavedatetime": summaryInfo.setLastSaveDateTime(formatSDF.parse(entry.getValue())); break; case "pagecount": summaryInfo.setPageCount(Integer.parseInt(entry.getValue())); break; case "revnumber": summaryInfo.setRevNumber(entry.getValue()); break; case "security": summaryInfo.setSecurity(Integer.parseInt(entry.getValue())); break; case "subject": summaryInfo.setSubject(entry.getValue()); break; case "template": summaryInfo.setTemplate(entry.getValue()); break; case "title": summaryInfo.setTitle(entry.getValue()); break; case "wordcount": summaryInfo.setWordCount(Integer.parseInt(entry.getValue())); break; default: LOG.warn("Unknown metadata key: "+entry.getKey()); break; } } catch (ParseException pe) { LOG.error(pe); } } } /** * * Write metadata into XSSF document * */ private void prepareXSSFMetaData() { XSSFWorkbook currentXSSFWorkbook = (XSSFWorkbook) this.currentWorkbook; POIXMLProperties props = currentXSSFWorkbook.getProperties(); POIXMLProperties.CoreProperties coreProp=props.getCoreProperties(); POIXMLProperties.CustomProperties custProp = props.getCustomProperties(); SimpleDateFormat formatSDF = new SimpleDateFormat(MSExcelParser.DATE_FORMAT); for (Map.Entry<String,String> entry: this.howc.getMetadata().entrySet()) { // process general properties boolean attribMatch=false; try { switch(entry.getKey()) { case "category": coreProp.setCategory(entry.getValue()); attribMatch=true; break; case "contentstatus": coreProp.setContentStatus(entry.getValue()); attribMatch=true; break; case "contenttype": coreProp.setContentType(entry.getValue()); attribMatch=true; break; case "created": coreProp.setCreated(new Nullable<Date>(formatSDF.parse(entry.getValue()))); attribMatch=true; break; case "creator": coreProp.setCreator(entry.getValue()); attribMatch=true; break; case "description": coreProp.setDescription(entry.getValue()); attribMatch=true; break; case "identifier": coreProp.setIdentifier(entry.getValue()); attribMatch=true; break; case "keywords": coreProp.setKeywords(entry.getValue()); attribMatch=true; break; case "lastmodifiedbyuser": coreProp.setLastModifiedByUser(entry.getValue()); attribMatch=true; break; case "lastprinted": coreProp.setLastPrinted(new Nullable<Date>(formatSDF.parse(entry.getValue()))); attribMatch=true; break; case "modified": coreProp.setModified(new Nullable<Date>(formatSDF.parse(entry.getValue()))); attribMatch=true; break; case "revision": coreProp.setRevision(entry.getValue()); attribMatch=true; break; case "subject": coreProp.setSubjectProperty(entry.getValue()); attribMatch=true; break; case "title": coreProp.setTitle(entry.getValue()); attribMatch=true; break; default: // later we check if custom properties need to be added break; } if (!(attribMatch)) { // process custom properties if (entry.getKey().startsWith("custom.")) { String strippedKey=entry.getKey().substring("custom.".length()); if (strippedKey.length()>0) { custProp.addProperty(strippedKey,entry.getValue()); } } else { LOG.warn("Unknown metadata key: "+entry.getKey()); } } } catch (ParseException pe) { LOG.error(pe); } } } }
fixed sonarqube code smell
fileformat/src/main/java/org/zuinnote/hadoop/office/format/common/writer/MSExcelWriter.java
fixed sonarqube code smell
<ide><path>ileformat/src/main/java/org/zuinnote/hadoop/office/format/common/writer/MSExcelWriter.java <ide> * @param newDAO cell to add. If it is already existing an exception will be thrown. Note that the sheet name is sanitized using org.apache.poi.ss.util.WorkbookUtil.createSafeSheetName. The Cell address needs to be in A1 format. Either formula or formattedValue must be not null. <ide> * <ide> */ <del> <add>@Override <ide> public void write(Object newDAO) throws OfficeWriterException { <ide> if (!(newDAO instanceof SpreadSheetCellDAO)) { <ide> throw new OfficeWriterException("Objects which are not of the class SpreadSheetCellDAO are not supported for writing."); <ide> * <ide> * <ide> */ <del> <add>@Override <ide> public void close() throws IOException { <ide> try { <ide> // prepare metadata
Java
apache-2.0
539e4f41665ff2c8a086299a896889dc07b3004e
0
apache/pdfbox,apache/pdfbox,kalaspuffar/pdfbox,kalaspuffar/pdfbox
/* * 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.pdfbox.examples.pdmodel; import org.apache.pdfbox.pdmodel.PDDocument; import org.apache.pdfbox.pdmodel.PDDocumentCatalog; import org.apache.pdfbox.pdmodel.PDDocumentInformation; import org.apache.pdfbox.pdmodel.common.PDMetadata; import java.io.File; import java.io.IOException; import java.text.DateFormat; import java.util.Calendar; import java.util.List; import org.apache.xmpbox.XMPMetadata; import org.apache.xmpbox.schema.AdobePDFSchema; import org.apache.xmpbox.schema.DublinCoreSchema; import org.apache.xmpbox.schema.XMPBasicSchema; import org.apache.xmpbox.xml.DomXmpParser; import org.apache.xmpbox.xml.XmpParsingException; /** * This is an example on how to extract metadata from a PDF document. * */ public final class ExtractMetadata { private ExtractMetadata() { // utility class } /** * This is the main method. * * @param args The command line arguments. * * @throws IOException If there is an error parsing the document. * @throws XmpParsingException */ public static void main(String[] args) throws IOException, XmpParsingException { if (args.length != 1) { usage(); System.exit(1); } else { PDDocument document = null; try { document = PDDocument.load(new File(args[0])); PDDocumentCatalog catalog = document.getDocumentCatalog(); PDMetadata meta = catalog.getMetadata(); if (meta != null) { DomXmpParser xmpParser = new DomXmpParser(); try { XMPMetadata metadata = xmpParser.parse(meta.createInputStream()); DublinCoreSchema dc = metadata.getDublinCoreSchema(); if (dc != null) { display("Title:", dc.getTitle()); display("Description:", dc.getDescription()); listString("Creators: ", dc.getCreators()); listCalendar("Dates:", dc.getDates()); listString("Subjects:", dc.getSubjects()); } AdobePDFSchema pdf = metadata.getAdobePDFSchema(); if (pdf != null) { display("Keywords:", pdf.getKeywords()); display("PDF Version:", pdf.getPDFVersion()); display("PDF Producer:", pdf.getProducer()); } XMPBasicSchema basic = metadata.getXMPBasicSchema(); if (basic != null) { display("Create Date:", basic.getCreateDate()); display("Modify Date:", basic.getModifyDate()); display("Creator Tool:", basic.getCreatorTool()); } } catch (XmpParsingException e) { System.err.println("An error ouccred when parsing the meta data: " + e.getMessage()); } } else { // The pdf doesn't contain any metadata, try to use the // document information instead PDDocumentInformation information = document.getDocumentInformation(); if (information != null) { showDocumentInformation(information); } } } finally { if (document != null) { document.close(); } } } } private static void showDocumentInformation(PDDocumentInformation information) { display("Title:", information.getTitle()); display("Subject:", information.getSubject()); display("Author:", information.getAuthor()); display("Creator:", information.getCreator()); display("Producer:", information.getProducer()); } private static void listString(String title, List<String> list) { if (list == null) { return; } System.out.println(title); for (String string : list) { System.out.println(" " + string); } } private static void listCalendar(String title, List<Calendar> list) { if (list == null) { return; } System.out.println(title); for (Calendar calendar : list) { System.out.println(" " + format(calendar)); } } private static String format(Object o) { if (o instanceof Calendar) { Calendar cal = (Calendar) o; return DateFormat.getDateInstance().format(cal.getTime()); } else { return o.toString(); } } private static void display(String title, Object value) { if (value != null) { System.out.println(title + " " + format(value)); } } /** * This will print the usage for this program. */ private static void usage() { System.err.println("Usage: java " + ExtractMetadata.class.getName() + " <input-pdf>"); } }
examples/src/main/java/org/apache/pdfbox/examples/pdmodel/ExtractMetadata.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.pdfbox.examples.pdmodel; import org.apache.pdfbox.pdmodel.PDDocument; import org.apache.pdfbox.pdmodel.PDDocumentCatalog; import org.apache.pdfbox.pdmodel.PDDocumentInformation; import org.apache.pdfbox.pdmodel.common.PDMetadata; import java.io.File; import java.io.IOException; import java.text.DateFormat; import java.util.Calendar; import java.util.Iterator; import java.util.List; import org.apache.xmpbox.XMPMetadata; import org.apache.xmpbox.schema.AdobePDFSchema; import org.apache.xmpbox.schema.DublinCoreSchema; import org.apache.xmpbox.schema.XMPBasicSchema; import org.apache.xmpbox.xml.DomXmpParser; import org.apache.xmpbox.xml.XmpParsingException; /** * This is an example on how to extract metadata from a PDF document. * */ public final class ExtractMetadata { private ExtractMetadata() { // utility class } /** * This is the main method. * * @param args The command line arguments. * * @throws IOException If there is an error parsing the document. * @throws XmpParsingException */ public static void main(String[] args) throws IOException, XmpParsingException { if (args.length != 1) { usage(); System.exit(1); } else { PDDocument document = null; try { document = PDDocument.load(new File(args[0])); PDDocumentCatalog catalog = document.getDocumentCatalog(); PDMetadata meta = catalog.getMetadata(); if (meta != null) { DomXmpParser xmpParser = new DomXmpParser(); try { XMPMetadata metadata = xmpParser.parse(meta.createInputStream()); DublinCoreSchema dc = metadata.getDublinCoreSchema(); if (dc != null) { display("Title:", dc.getTitle()); display("Description:", dc.getDescription()); listString("Creators: ", dc.getCreators()); listCalendar("Dates:", dc.getDates()); listString("Subjects:", dc.getSubjects()); } AdobePDFSchema pdf = metadata.getAdobePDFSchema(); if (pdf != null) { display("Keywords:", pdf.getKeywords()); display("PDF Version:", pdf.getPDFVersion()); display("PDF Producer:", pdf.getProducer()); } XMPBasicSchema basic = metadata.getXMPBasicSchema(); if (basic != null) { display("Create Date:", basic.getCreateDate()); display("Modify Date:", basic.getModifyDate()); display("Creator Tool:", basic.getCreatorTool()); } } catch (XmpParsingException e) { System.err.println("An error ouccred when parsing the meta data: " + e.getMessage()); } } else { // The pdf doesn't contain any metadata, try to use the // document information instead PDDocumentInformation information = document.getDocumentInformation(); if (information != null) { showDocumentInformation(information); } } } finally { if (document != null) { document.close(); } } } } private static void showDocumentInformation(PDDocumentInformation information) { display("Title:", information.getTitle()); display("Subject:", information.getSubject()); display("Author:", information.getAuthor()); display("Creator:", information.getCreator()); display("Producer:", information.getProducer()); } private static void listString(String title, List<String> list) { if (list == null) { return; } System.out.println(title); for (String string : list) { System.out.println(" " + string); } } private static void listCalendar(String title, List<Calendar> list) { if (list == null) { return; } System.out.println(title); for (Calendar calendar : list) { System.out.println(" " + format(calendar)); } } private static String format(Object o) { if (o instanceof Calendar) { Calendar cal = (Calendar) o; return DateFormat.getDateInstance().format(cal.getTime()); } else { return o.toString(); } } private static void display(String title, Object value) { if (value != null) { System.out.println(title + " " + format(value)); } } /** * This will print the usage for this program. */ private static void usage() { System.err.println("Usage: java " + ExtractMetadata.class.getName() + " <input-pdf>"); } }
PDFBOX-2852: fix imports git-svn-id: c3ad59981690829a43dc34c293c4e2cd04bcd994@1768734 13f79535-47bb-0310-9956-ffa450edef68
examples/src/main/java/org/apache/pdfbox/examples/pdmodel/ExtractMetadata.java
PDFBOX-2852: fix imports
<ide><path>xamples/src/main/java/org/apache/pdfbox/examples/pdmodel/ExtractMetadata.java <ide> import java.io.IOException; <ide> import java.text.DateFormat; <ide> import java.util.Calendar; <del>import java.util.Iterator; <ide> import java.util.List; <ide> <ide> import org.apache.xmpbox.XMPMetadata;
Java
mit
c335d83556ae1892c6feefa08931d6334abb77c4
0
GitHubRGI/swagd,GitHubRGI/swagd,GitHubRGI/swagd,GitHubRGI/swagd
/* The MIT License (MIT) * * Copyright (c) 2015 Reinventing Geospatial, Inc. * * 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 com.rgi.geopackage.verification; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; import java.sql.Statement; import java.util.AbstractMap; import java.util.ArrayList; import java.util.Arrays; import java.util.Collection; import java.util.List; import java.util.Map; import java.util.Map.Entry; import java.util.Objects; import java.util.Set; import java.util.TreeMap; import java.util.stream.Collectors; import java.util.stream.Stream; import com.rgi.common.util.jdbc.ResultSetStream; /** * @author Luke Lambert * @author Jenifer Cochran */ public class Verifier { /** * Constructor * * @param verificationLevel * Controls the level of verification testing performed * @param sqliteConnection JDBC connection to the SQLite database * */ public Verifier(final Connection sqliteConnection, final VerificationLevel verificationLevel) { if(sqliteConnection == null) { throw new IllegalArgumentException("SQLite connection cannot be null"); } this.sqliteConnection = sqliteConnection; this.verificationLevel = verificationLevel; } /** * Checks a GeoPackage (via it's {@link java.sql.Connection}) for violations of the requirements outlined in the <a href="http://www.geopackage.org/spec/">standard</a>. * * @return Returns the definition for all failed requirements */ public Collection<VerificationIssue> getVerificationIssues() { return this.getRequirements() .map(requirementTestMethod -> { try { requirementTestMethod.invoke(this); return null; } catch(final InvocationTargetException ex) { final Requirement requirement = requirementTestMethod.getAnnotation(Requirement.class); // The ruling on the field, right now, is that everything will be wrapped in a failed requirement, even if it's an issue in the test code. //if(ex.getCause() instanceof AssertionError) //{ return new VerificationIssue(ex.getCause().getMessage(), requirement); //} //throw new RuntimeException(String.format("Unexpected exception thrown when testing requirement %d for GeoPackage verification: %s", // requirement.number(), // ex.getCause().getMessage())); } catch(final IllegalAccessException ex) { // TODO ex.printStackTrace(); return null; } }) .filter(Objects::nonNull) .collect(Collectors.toCollection(ArrayList::new)); } /** * @param dataType * Data type type string * @return Returns true if dataType is one of the known SQL types or * matches one of the formatted TEXT or BLOB types */ protected static boolean checkDataType(final String dataType) { return Verifier.AllowedSqlTypes.contains(dataType) || dataType.matches("TEXT\\([0-9]+\\)") || dataType.matches("BLOB\\([0-9]+\\)"); } /** * @return Returns a stream of methods that are annotated with @Requirement */ protected Stream<Method> getRequirements() { return Stream.of(this.getClass().getDeclaredMethods()) .filter(method -> method.isAnnotationPresent(Requirement.class)) .sorted((method1, method2) -> Integer.compare(method1.getAnnotation(Requirement.class).number(), method2.getAnnotation(Requirement.class).number())); } /** * @param table * Table definition to * @throws AssertionError * @throws SQLException */ protected void verifyTable(final TableDefinition table) throws AssertionError, SQLException { this.verifyTableDefinition(table.getName()); final Set<UniqueDefinition> uniques = this.getUniques(table.getName()); this.verifyColumns(table.getName(), table.getColumns(), uniques); this.verifyForeignKeys(table.getName(), table.getForeignKeys()); Verifier.verifyGroupUniques(table.getName(), table.getGroupUniques(), uniques); } /** * @param table * @throws SQLException * @throws AssertionError */ protected void verifyTableDefinition(final String tableName) throws SQLException, AssertionError { try(final PreparedStatement statement = this.sqliteConnection.prepareStatement("SELECT sql FROM sqlite_master WHERE (type = 'table' OR type = 'view') AND tbl_name = ?;")) { statement.setString(1, tableName); try(ResultSet gpkgContents = statement.executeQuery()) { final String sql = gpkgContents.getString("sql"); Assert.assertTrue(String.format("The sql field must include the %s Table SQL Definition.", tableName), sql != null); } } } /** * @param table * @throws SQLException * @throws AssertionError */ protected void verifyColumns(final String tableName, final Map<String, ColumnDefinition> requiredColumns, final Set<UniqueDefinition> uniques) throws SQLException, AssertionError { try(final Statement statement = this.sqliteConnection.createStatement(); final ResultSet tableInfo = statement.executeQuery(String.format("PRAGMA table_info(%s);", tableName))) { final TreeMap<String, ColumnDefinition> columns = ResultSetStream.getStream(tableInfo) .map(resultSet -> { try { final String columnName = resultSet.getString("name"); return new AbstractMap.SimpleImmutableEntry<>(columnName, new ColumnDefinition(tableInfo.getString ("type"), tableInfo.getBoolean("notnull"), tableInfo.getBoolean("pk"), uniques.stream().anyMatch(unique -> unique.equals(columnName)), tableInfo.getString ("dflt_value"))); // TODO manipulate values so that they're "normalized" sql expressions, e.g. "" -> '', strftime ( '%Y-%m-%dT%H:%M:%fZ' , 'now' ) -> strftime('%Y-%m-%dT%H:%M:%fZ','now') } catch(final SQLException ex) { ex.printStackTrace(); return null; } }) .collect(Collectors.toMap(entry -> entry.getKey(), entry -> entry.getValue(), (a, b) -> a, () -> new TreeMap<>(String.CASE_INSENSITIVE_ORDER))); // Make sure the required fields exist in the table for(final Entry<String, ColumnDefinition> column : requiredColumns.entrySet()) { Assert.assertTrue(String.format("Required column: %s.%s is missing", tableName, column.getKey()), columns.containsKey(column.getKey())); final ColumnDefinition columnDefinition = columns.get(column.getKey()); if(columnDefinition != null) { Assert.assertTrue(String.format("Required column %s is defined as:\n%s\nbut should be:\n%s", column.getKey(), columnDefinition.toString(), column.getValue().toString()), columnDefinition.equals(column.getValue())); } } } } protected void verifyForeignKeys(final String tableName, final Set<ForeignKeyDefinition> requiredForeignKeys) throws AssertionError, SQLException { try(Statement statement = this.sqliteConnection.createStatement()) { try(ResultSet fkInfo = statement.executeQuery(String.format("PRAGMA foreign_key_list(%s);", tableName))) { final Set<ForeignKeyDefinition> foreignKeys = ResultSetStream.getStream(fkInfo) .map(resultSet -> { try { return new ForeignKeyDefinition(resultSet.getString("table"), resultSet.getString("from"), resultSet.getString("to")); } catch(final SQLException ex) { ex.printStackTrace(); return null; } }) .filter(Objects::nonNull) .collect(Collectors.toSet()); // check to see if the correct foreign key constraints are placed for(final ForeignKeyDefinition foreignKey : requiredForeignKeys) { Assert.assertTrue(String.format("The table %s is missing the foreign key constraint: %1$s.%s => %s.%s", tableName, foreignKey.getFromColumnName(), foreignKey.getReferenceTableName(), foreignKey.getToColumnName()), foreignKeys.contains(foreignKey)); } } catch(final SQLException ex) { // If a table has no foreign keys, executing the query // PRAGMA foreign_key_list(<table_name>) will throw an // exception complaining that result set is empty. // The issue has been posted about it here: // https://bitbucket.org/xerial/sqlite-jdbc/issue/162/ // If the result set is empty (no foreign keys), there's no // work to be done. Unfortunately .executeQuery() may throw an // SQLException for other reasons that may require some // attention. } } } protected static void verifyGroupUniques(final String tableName, final Set<UniqueDefinition> requiredGroupUniques, final Set<UniqueDefinition> uniques) throws AssertionError { for(final UniqueDefinition groupUnique : requiredGroupUniques) { Assert.assertTrue(String.format("The table %s is missing the column group unique constraint: (%s)", tableName, String.join(", ", groupUnique.getColumnNames())), uniques.contains(groupUnique)); } } protected Set<UniqueDefinition> getUniques(final String tableName) throws SQLException { try(final Statement statement = this.sqliteConnection.createStatement(); final ResultSet indices = statement.executeQuery(String.format("PRAGMA index_list(%s);", tableName))) { return ResultSetStream.getStream(indices) .map(resultSet -> { try { final String indexName = resultSet.getString("name"); try(Statement nameStatement = this.sqliteConnection.createStatement(); ResultSet namesSet = nameStatement.executeQuery(String.format("PRAGMA index_info(%s);", indexName));) { return new UniqueDefinition(ResultSetStream.getStream(namesSet) .map(names -> { try { return names.getString("name"); } catch(final Exception ex) { ex.printStackTrace(); return null; } }) .filter(Objects::nonNull) .collect(Collectors.toList())); } } catch(final Exception ex) { ex.printStackTrace(); return null; } }) .filter(Objects::nonNull) .collect(Collectors.toSet()); } } /** * @return The SQLite connection */ protected Connection getSqliteConnection() { return this.sqliteConnection; } /** * @return The list of allowed SQL types */ protected static List<String> getAllowedSqlTypes() { return Verifier.AllowedSqlTypes; } private final Connection sqliteConnection; protected final VerificationLevel verificationLevel; private static final List<String> AllowedSqlTypes = Arrays.asList("BOOLEAN", "TINYINT", "SMALLINT", "MEDIUMINT", "INT", "FLOAT", "DOUBLE", "REAL", "TEXT", "BLOB", "DATE", "DATETIME", "GEOMETRY", "POINT", "LINESTRING", "POLYGON", "MULTIPOINT", "MULTILINESTRING", "MULTIPOLYGON", "GEOMETRYCOLLECTION", "INTEGER"); }
GeoPackage/src/com/rgi/geopackage/verification/Verifier.java
/* The MIT License (MIT) * * Copyright (c) 2015 Reinventing Geospatial, Inc. * * 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 com.rgi.geopackage.verification; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; import java.sql.Statement; import java.util.AbstractMap; import java.util.ArrayList; import java.util.Arrays; import java.util.Collection; import java.util.List; import java.util.Map; import java.util.Map.Entry; import java.util.Objects; import java.util.Set; import java.util.stream.Collectors; import java.util.stream.Stream; import com.rgi.common.util.jdbc.ResultSetStream; /** * @author Luke Lambert * @author Jenifer Cochran */ public class Verifier { /** * Constructor * * @param verificationLevel * Controls the level of verification testing performed * @param sqliteConnection JDBC connection to the SQLite database * */ public Verifier(final Connection sqliteConnection, final VerificationLevel verificationLevel) { if(sqliteConnection == null) { throw new IllegalArgumentException("SQLite connection cannot be null"); } this.sqliteConnection = sqliteConnection; this.verificationLevel = verificationLevel; } /** * Checks a GeoPackage (via it's {@link java.sql.Connection}) for violations of the requirements outlined in the <a href="http://www.geopackage.org/spec/">standard</a>. * * @return Returns the definition for all failed requirements */ public Collection<VerificationIssue> getVerificationIssues() { return this.getRequirements() .map(requirementTestMethod -> { try { requirementTestMethod.invoke(this); return null; } catch(final InvocationTargetException ex) { final Requirement requirement = requirementTestMethod.getAnnotation(Requirement.class); // The ruling on the field, right now, is that everything will be wrapped in a failed requirement, even if it's an issue in the test code. //if(ex.getCause() instanceof AssertionError) //{ return new VerificationIssue(ex.getCause().getMessage(), requirement); //} //throw new RuntimeException(String.format("Unexpected exception thrown when testing requirement %d for GeoPackage verification: %s", // requirement.number(), // ex.getCause().getMessage())); } catch(final IllegalAccessException ex) { // TODO ex.printStackTrace(); return null; } }) .filter(Objects::nonNull) .collect(Collectors.toCollection(ArrayList::new)); } /** * @param dataType * Data type type string * @return Returns true if dataType is one of the known SQL types or * matches one of the formatted TEXT or BLOB types */ protected static boolean checkDataType(final String dataType) { return Verifier.AllowedSqlTypes.contains(dataType) || dataType.matches("TEXT\\([0-9]+\\)") || dataType.matches("BLOB\\([0-9]+\\)"); } /** * @return Returns a stream of methods that are annotated with @Requirement */ protected Stream<Method> getRequirements() { return Stream.of(this.getClass().getDeclaredMethods()) .filter(method -> method.isAnnotationPresent(Requirement.class)) .sorted((method1, method2) -> Integer.compare(method1.getAnnotation(Requirement.class).number(), method2.getAnnotation(Requirement.class).number())); } /** * @param table * Table definition to * @throws AssertionError * @throws SQLException */ protected void verifyTable(final TableDefinition table) throws AssertionError, SQLException { this.verifyTableDefinition(table.getName()); final Set<UniqueDefinition> uniques = this.getUniques(table.getName()); this.verifyColumns(table.getName(), table.getColumns(), uniques); this.verifyForeignKeys(table.getName(), table.getForeignKeys()); Verifier.verifyGroupUniques(table.getName(), table.getGroupUniques(), uniques); } /** * @param table * @throws SQLException * @throws AssertionError */ protected void verifyTableDefinition(final String tableName) throws SQLException, AssertionError { try(final PreparedStatement statement = this.sqliteConnection.prepareStatement("SELECT sql FROM sqlite_master WHERE (type = 'table' OR type = 'view') AND tbl_name = ?;")) { statement.setString(1, tableName); try(ResultSet gpkgContents = statement.executeQuery()) { final String sql = gpkgContents.getString("sql"); Assert.assertTrue(String.format("The sql field must include the %s Table SQL Definition.", tableName), sql != null); } } } /** * @param table * @throws SQLException * @throws AssertionError */ protected void verifyColumns(final String tableName, final Map<String, ColumnDefinition> requiredColumns, final Set<UniqueDefinition> uniques) throws SQLException, AssertionError { try(final Statement statement = this.sqliteConnection.createStatement(); final ResultSet tableInfo = statement.executeQuery(String.format("PRAGMA table_info(%s);", tableName))) { final Map<String, ColumnDefinition> columns = ResultSetStream.getStream(tableInfo) .map(resultSet -> { try { final String columnName = resultSet.getString("name"); return new AbstractMap.SimpleImmutableEntry<>(columnName, new ColumnDefinition(tableInfo.getString ("type"), tableInfo.getBoolean("notnull"), tableInfo.getBoolean("pk"), uniques.stream().anyMatch(unique -> unique.equals(columnName)), tableInfo.getString ("dflt_value"))); // TODO manipulate values so that they're "normalized" sql expressions, e.g. "" -> '', strftime ( '%Y-%m-%dT%H:%M:%fZ' , 'now' ) -> strftime('%Y-%m-%dT%H:%M:%fZ','now') } catch(final SQLException ex) { ex.printStackTrace(); return null; } }) .filter(Objects::nonNull) .collect(Collectors.toMap(entry -> entry.getKey(), entry -> entry.getValue())); // Make sure the required fields exist in the table for(final Entry<String, ColumnDefinition> column : requiredColumns.entrySet()) { final ColumnDefinition columnDefinition = columns.get(column.getKey()); Assert.assertTrue(String.format("Required column: %s.%s is missing", tableName, column.getKey()), columnDefinition != null); if(columnDefinition != null) { Assert.assertTrue(String.format("Required column %s is defined as:\n%s\nbut should be:\n%s", column.getKey(), columnDefinition.toString(), column.getValue().toString()), columnDefinition.equals(column.getValue())); } } } } protected void verifyForeignKeys(final String tableName, final Set<ForeignKeyDefinition> requiredForeignKeys) throws AssertionError, SQLException { try(Statement statement = this.sqliteConnection.createStatement()) { try(ResultSet fkInfo = statement.executeQuery(String.format("PRAGMA foreign_key_list(%s);", tableName))) { final Set<ForeignKeyDefinition> foreignKeys = ResultSetStream.getStream(fkInfo) .map(resultSet -> { try { return new ForeignKeyDefinition(resultSet.getString("table"), resultSet.getString("from"), resultSet.getString("to")); } catch(final SQLException ex) { ex.printStackTrace(); return null; } }) .filter(Objects::nonNull) .collect(Collectors.toSet()); // check to see if the correct foreign key constraints are placed for(final ForeignKeyDefinition foreignKey : requiredForeignKeys) { Assert.assertTrue(String.format("The table %s is missing the foreign key constraint: %1$s.%s => %s.%s", tableName, foreignKey.getFromColumnName(), foreignKey.getReferenceTableName(), foreignKey.getToColumnName()), foreignKeys.contains(foreignKey)); } } catch(final SQLException ex) { // If a table has no foreign keys, executing the query // PRAGMA foreign_key_list(<table_name>) will throw an // exception complaining that result set is empty. // The issue has been posted about it here: // https://bitbucket.org/xerial/sqlite-jdbc/issue/162/ // If the result set is empty (no foreign keys), there's no // work to be done. Unfortunately .executeQuery() may throw an // SQLException for other reasons that may require some // attention. } } } protected static void verifyGroupUniques(final String tableName, final Set<UniqueDefinition> requiredGroupUniques, final Set<UniqueDefinition> uniques) throws AssertionError { for(final UniqueDefinition groupUnique : requiredGroupUniques) { Assert.assertTrue(String.format("The table %s is missing the column group unique constraint: (%s)", tableName, String.join(", ", groupUnique.getColumnNames())), uniques.contains(groupUnique)); } } protected Set<UniqueDefinition> getUniques(final String tableName) throws SQLException { try(final Statement statement = this.sqliteConnection.createStatement(); final ResultSet indices = statement.executeQuery(String.format("PRAGMA index_list(%s);", tableName))) { return ResultSetStream.getStream(indices) .map(resultSet -> { try { final String indexName = resultSet.getString("name"); try(Statement nameStatement = this.sqliteConnection.createStatement(); ResultSet namesSet = nameStatement.executeQuery(String.format("PRAGMA index_info(%s);", indexName));) { return new UniqueDefinition(ResultSetStream.getStream(namesSet) .map(names -> { try { return names.getString("name"); } catch(final Exception ex) { ex.printStackTrace(); return null; } }) .filter(Objects::nonNull) .collect(Collectors.toList())); } } catch(final Exception ex) { ex.printStackTrace(); return null; } }) .filter(Objects::nonNull) .collect(Collectors.toSet()); } } /** * @return The SQLite connection */ protected Connection getSqliteConnection() { return this.sqliteConnection; } /** * @return The list of allowed SQL types */ protected static List<String> getAllowedSqlTypes() { return Verifier.AllowedSqlTypes; } private final Connection sqliteConnection; protected final VerificationLevel verificationLevel; private static final List<String> AllowedSqlTypes = Arrays.asList("BOOLEAN", "TINYINT", "SMALLINT", "MEDIUMINT", "INT", "FLOAT", "DOUBLE", "REAL", "TEXT", "BLOB", "DATE", "DATETIME", "GEOMETRY", "POINT", "LINESTRING", "POLYGON", "MULTIPOINT", "MULTILINESTRING", "MULTIPOLYGON", "GEOMETRYCOLLECTION", "INTEGER"); }
Changing it to a treeMap allows us to check the column names with case insensitive searches. This is changed bc SQLite does not do case sensitive searches
GeoPackage/src/com/rgi/geopackage/verification/Verifier.java
Changing it to a treeMap allows us to check
<ide><path>eoPackage/src/com/rgi/geopackage/verification/Verifier.java <ide> import java.util.Map.Entry; <ide> import java.util.Objects; <ide> import java.util.Set; <add>import java.util.TreeMap; <ide> import java.util.stream.Collectors; <ide> import java.util.stream.Stream; <ide> <ide> try(final Statement statement = this.sqliteConnection.createStatement(); <ide> final ResultSet tableInfo = statement.executeQuery(String.format("PRAGMA table_info(%s);", tableName))) <ide> { <del> final Map<String, ColumnDefinition> columns = ResultSetStream.getStream(tableInfo) <del> .map(resultSet -> { try <del> { <del> final String columnName = resultSet.getString("name"); <del> return new AbstractMap.SimpleImmutableEntry<>(columnName, <del> new ColumnDefinition(tableInfo.getString ("type"), <del> tableInfo.getBoolean("notnull"), <del> tableInfo.getBoolean("pk"), <del> uniques.stream().anyMatch(unique -> unique.equals(columnName)), <del> tableInfo.getString ("dflt_value"))); // TODO manipulate values so that they're "normalized" sql expressions, e.g. "" -> '', strftime ( '%Y-%m-%dT%H:%M:%fZ' , 'now' ) -> strftime('%Y-%m-%dT%H:%M:%fZ','now') <del> } <del> catch(final SQLException ex) <del> { <del> ex.printStackTrace(); <del> return null; <del> } <del> }) <del> .filter(Objects::nonNull) <del> .collect(Collectors.toMap(entry -> entry.getKey(), <del> entry -> entry.getValue())); <add> final TreeMap<String, ColumnDefinition> columns = ResultSetStream.getStream(tableInfo) <add> .map(resultSet -> { try <add> { <add> final String columnName = resultSet.getString("name"); <add> return new AbstractMap.SimpleImmutableEntry<>(columnName, <add> new ColumnDefinition(tableInfo.getString ("type"), <add> tableInfo.getBoolean("notnull"), <add> tableInfo.getBoolean("pk"), <add> uniques.stream().anyMatch(unique -> unique.equals(columnName)), <add> tableInfo.getString ("dflt_value"))); // TODO manipulate values so that they're "normalized" sql expressions, e.g. "" -> '', strftime ( '%Y-%m-%dT%H:%M:%fZ' , 'now' ) -> strftime('%Y-%m-%dT%H:%M:%fZ','now') <add> } <add> catch(final SQLException ex) <add> { <add> ex.printStackTrace(); <add> return null; <add> } <add> }) <add> .collect(Collectors.toMap(entry -> entry.getKey(), <add> entry -> entry.getValue(), <add> (a, b) -> a, <add> () -> new TreeMap<>(String.CASE_INSENSITIVE_ORDER))); <ide> // Make sure the required fields exist in the table <ide> for(final Entry<String, ColumnDefinition> column : requiredColumns.entrySet()) <ide> { <add> Assert.assertTrue(String.format("Required column: %s.%s is missing", tableName, column.getKey()), <add> columns.containsKey(column.getKey())); <add> <ide> final ColumnDefinition columnDefinition = columns.get(column.getKey()); <del> Assert.assertTrue(String.format("Required column: %s.%s is missing", tableName, column.getKey()), <del> columnDefinition != null); <ide> <ide> if(columnDefinition != null) <ide> {
Java
bsd-3-clause
ead457155771391e4e7f3886a70f3ff557e5a50d
0
sailajaa/CONNECT,healthreveal/CONNECT,beiyuxinke/CONNECT,beiyuxinke/CONNECT,healthreveal/CONNECT,healthreveal/CONNECT,sailajaa/CONNECT,beiyuxinke/CONNECT,sailajaa/CONNECT,beiyuxinke/CONNECT,healthreveal/CONNECT,beiyuxinke/CONNECT,healthreveal/CONNECT
/* * Copyright (c) 2012, United States Government, as represented by the Secretary of Health and Human Services. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * Redistributions of source code must retain the above * copyright notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * Neither the name of the United States Government nor the * names of its contributors may be used to endorse or promote products * derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE UNITED STATES GOVERNMENT BE LIABLE FOR ANY * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ package gov.hhs.fha.nhinc.patientcorrelation.nhinc.proxy; import gov.hhs.fha.nhinc.common.nhinccommon.AssertionType; import gov.hhs.fha.nhinc.messaging.client.CONNECTClient; import gov.hhs.fha.nhinc.messaging.client.CONNECTClientFactory; import gov.hhs.fha.nhinc.messaging.service.port.ServicePortDescriptor; import gov.hhs.fha.nhinc.nhinccomponentpatientcorrelation.PatientCorrelationPortType; import gov.hhs.fha.nhinc.nhinclib.NhincConstants; import gov.hhs.fha.nhinc.patientcorrelation.nhinc.proxy.description.PatientCorrelationAddServicePortDescriptor; import gov.hhs.fha.nhinc.patientcorrelation.nhinc.proxy.description.PatientCorrelationRetrieveServicePortDescriptor; import gov.hhs.fha.nhinc.webserviceproxy.WebServiceProxyHelper; import org.apache.log4j.Logger; import org.hl7.v3.AddPatientCorrelationRequestType; import org.hl7.v3.AddPatientCorrelationResponseType; import org.hl7.v3.PRPAIN201301UV02; import org.hl7.v3.PRPAIN201309UV02; import org.hl7.v3.RetrievePatientCorrelationsRequestType; import org.hl7.v3.RetrievePatientCorrelationsResponseType; /** * * @author jhoppesc */ public class PatientCorrelationProxyWebServiceUnsecuredImpl implements PatientCorrelationProxy { private static final Logger LOG = Logger.getLogger(PatientCorrelationProxyWebServiceUnsecuredImpl.class); private WebServiceProxyHelper oProxyHelper = null; /** * Default Constructor. */ public PatientCorrelationProxyWebServiceUnsecuredImpl() { oProxyHelper = createWebServiceProxyHelper(); } /** * @return WebServiceProxyHelper Object. */ protected WebServiceProxyHelper createWebServiceProxyHelper() { return new WebServiceProxyHelper(); } /** * This method returns WS_ADDRESSING_ACTION_RETRIEVE. * @param apiLevel Adapter apiLevel (this is a0,a1). * @return WS_ADDRESSING_ACTION_RETRIEVE. */ public ServicePortDescriptor<PatientCorrelationPortType> getRetrieveServicePortDescriptor( NhincConstants.ADAPTER_API_LEVEL apiLevel) { switch (apiLevel) { case LEVEL_a0: return new PatientCorrelationRetrieveServicePortDescriptor(); default: return new PatientCorrelationRetrieveServicePortDescriptor(); } } /** * returns WS_ADDRESSING_ACTION_ADD. * @param apiLevel Adapter apiLevel (this is a0,a1). * @return WS_ADDRESSING_ACTION_ADD. */ public ServicePortDescriptor<PatientCorrelationPortType> getAddServicePortDescriptor( NhincConstants.ADAPTER_API_LEVEL apiLevel) { switch (apiLevel) { case LEVEL_a0: return new PatientCorrelationAddServicePortDescriptor(); default: return new PatientCorrelationAddServicePortDescriptor(); } } /** * This method retrieves PatientCorrelation from the targeted community. * @param msg PRPAIN201309UV02 HL7 type of Request received. * @param assertion Assertion received. * @return PatientCorrelationresponse. */ public RetrievePatientCorrelationsResponseType retrievePatientCorrelations(PRPAIN201309UV02 msg, AssertionType assertion) { LOG.debug("Begin retrievePatientCorrelations"); RetrievePatientCorrelationsResponseType response = null; try { String url = oProxyHelper.getUrlLocalHomeCommunity(NhincConstants.PATIENT_CORRELATION_SERVICE_NAME); if (msg == null) { LOG.error("Message was null"); } else if (assertion == null) { LOG.error("assertion was null"); } else { RetrievePatientCorrelationsRequestType request = new RetrievePatientCorrelationsRequestType(); request.setPRPAIN201309UV02(msg); request.setAssertion(assertion); ServicePortDescriptor<PatientCorrelationPortType> portDescriptor = getRetrieveServicePortDescriptor(NhincConstants.ADAPTER_API_LEVEL.LEVEL_a0); CONNECTClient<PatientCorrelationPortType> client = CONNECTClientFactory.getInstance() .getCONNECTClientUnsecured(portDescriptor, url, assertion); response = (RetrievePatientCorrelationsResponseType) client .invokePort(PatientCorrelationPortType.class, "retrievePatientCorrelations", request); } } catch (Exception ex) { LOG.error("Error calling retrievePatientCorrelations: " + ex.getMessage(), ex); } LOG.debug("End retrievePatientCorrelations"); return response; } /** * This method add PatientCorrelations to database. * @param msg PRPAIN201301UV02 HL7 type of Request received. * @param assertion Assertion received. * @return PatientCorrelationResponse. */ public AddPatientCorrelationResponseType addPatientCorrelation(PRPAIN201301UV02 msg, AssertionType assertion) { LOG.debug("Begin addPatientCorrelation"); AddPatientCorrelationResponseType response = null; try { String url = oProxyHelper.getUrlLocalHomeCommunity(NhincConstants.PATIENT_CORRELATION_SERVICE_NAME); if (msg == null) { LOG.error("Message was null"); } else if (assertion == null) { LOG.error("assertion was null"); } else { AddPatientCorrelationRequestType request = new AddPatientCorrelationRequestType(); request.setPRPAIN201301UV02(msg); request.setAssertion(assertion); ServicePortDescriptor<PatientCorrelationPortType> portDescriptor = getRetrieveServicePortDescriptor(NhincConstants.ADAPTER_API_LEVEL.LEVEL_a0); CONNECTClient<PatientCorrelationPortType> client = CONNECTClientFactory.getInstance() .getCONNECTClientUnsecured(portDescriptor, url, assertion); response = (AddPatientCorrelationResponseType) client .invokePort(PatientCorrelationPortType.class, "addPatientCorrelation", request); } } catch (Exception ex) { LOG.error("Error calling addPatientCorrelation: " + ex.getMessage(), ex); } LOG.debug("End addPatientCorrelation"); return response; } }
Product/Production/Services/PatientCorrelationCore/src/main/java/gov/hhs/fha/nhinc/patientcorrelation/nhinc/proxy/PatientCorrelationProxyWebServiceUnsecuredImpl.java
/* * Copyright (c) 2012, United States Government, as represented by the Secretary of Health and Human Services. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * Redistributions of source code must retain the above * copyright notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * Neither the name of the United States Government nor the * names of its contributors may be used to endorse or promote products * derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE UNITED STATES GOVERNMENT BE LIABLE FOR ANY * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ package gov.hhs.fha.nhinc.patientcorrelation.nhinc.proxy; import gov.hhs.fha.nhinc.common.nhinccommon.AssertionType; import gov.hhs.fha.nhinc.messaging.client.CONNECTClient; import gov.hhs.fha.nhinc.messaging.client.CONNECTClientFactory; import gov.hhs.fha.nhinc.messaging.service.port.ServicePortDescriptor; import gov.hhs.fha.nhinc.nhinccomponentpatientcorrelation.PatientCorrelationPortType; import gov.hhs.fha.nhinc.nhinclib.NhincConstants; import gov.hhs.fha.nhinc.patientcorrelation.nhinc.proxy.description.PatientCorrelationAddServicePortDescriptor; import gov.hhs.fha.nhinc.patientcorrelation.nhinc.proxy.description.PatientCorrelationRetrieveServicePortDescriptor; import gov.hhs.fha.nhinc.webserviceproxy.WebServiceProxyHelper; import org.apache.log4j.Logger; import org.hl7.v3.AddPatientCorrelationRequestType; import org.hl7.v3.AddPatientCorrelationResponseType; import org.hl7.v3.PRPAIN201301UV02; import org.hl7.v3.PRPAIN201309UV02; import org.hl7.v3.RetrievePatientCorrelationsRequestType; import org.hl7.v3.RetrievePatientCorrelationsResponseType; /** * * @author jhoppesc */ public class PatientCorrelationProxyWebServiceUnsecuredImpl implements PatientCorrelationProxy { private static final Logger LOG = Logger.getLogger(PatientCorrelationProxyWebServiceUnsecuredImpl.class); private WebServiceProxyHelper oProxyHelper = null; /** * Default Constructor. */ public PatientCorrelationProxyWebServiceUnsecuredImpl() { oProxyHelper = createWebServiceProxyHelper(); } /** * @return WebServiceProxyHelper Object. */ protected WebServiceProxyHelper createWebServiceProxyHelper() { return new WebServiceProxyHelper(); } /** * This method returns WS_ADDRESSING_ACTION_RETRIEVE. * @param apiLevel Adapter apiLevel (this is a0,a1). * @return WS_ADDRESSING_ACTION_RETRIEVE. */ public ServicePortDescriptor<PatientCorrelationPortType> getRetrieveServicePortDescriptor( NhincConstants.ADAPTER_API_LEVEL apiLevel) { switch (apiLevel) { case LEVEL_a0: return new PatientCorrelationRetrieveServicePortDescriptor(); default: return new PatientCorrelationRetrieveServicePortDescriptor(); } } /** * returns WS_ADDRESSING_ACTION_ADD. * @param apiLevel Adapter apiLevel (this is a0,a1). * @return WS_ADDRESSING_ACTION_ADD. */ public ServicePortDescriptor<PatientCorrelationPortType> getAddServicePortDescriptor( NhincConstants.ADAPTER_API_LEVEL apiLevel) { switch (apiLevel) { case LEVEL_a0: return new PatientCorrelationAddServicePortDescriptor(); default: return new PatientCorrelationAddServicePortDescriptor(); } } /** * This method retrieves PatientCorrelation from the targeted community. * @param msg PRPAIN201309UV02 HL7 type of Request received. * @param assertion Assertion received. * @return PatientCorrelationresponse. */ public RetrievePatientCorrelationsResponseType retrievePatientCorrelations(PRPAIN201309UV02 msg, AssertionType assertion) { LOG.debug("Begin retrievePatientCorrelations"); RetrievePatientCorrelationsResponseType response = null; try { String url = oProxyHelper.getUrlLocalHomeCommunity(NhincConstants.PATIENT_CORRELATION_SERVICE_NAME); if (msg == null) { LOG.error("Message was null"); } else if (assertion == null) { LOG.error("assertion was null"); } else { RetrievePatientCorrelationsRequestType request = new RetrievePatientCorrelationsRequestType(); request.setPRPAIN201309UV02(msg); request.setAssertion(assertion); ServicePortDescriptor<PatientCorrelationPortType> portDescriptor = getRetrieveServicePortDescriptor(NhincConstants.ADAPTER_API_LEVEL.LEVEL_a0); CONNECTClient<PatientCorrelationPortType> client = CONNECTClientFactory.getInstance() .getCONNECTClientSecured(portDescriptor, url, assertion); response = (RetrievePatientCorrelationsResponseType) client .invokePort(PatientCorrelationPortType.class, "retrievePatientCorrelations", request); } } catch (Exception ex) { LOG.error("Error calling retrievePatientCorrelations: " + ex.getMessage(), ex); } LOG.debug("End retrievePatientCorrelations"); return response; } /** * This method add PatientCorrelations to database. * @param msg PRPAIN201301UV02 HL7 type of Request received. * @param assertion Assertion received. * @return PatientCorrelationResponse. */ public AddPatientCorrelationResponseType addPatientCorrelation(PRPAIN201301UV02 msg, AssertionType assertion) { LOG.debug("Begin addPatientCorrelation"); AddPatientCorrelationResponseType response = null; try { String url = oProxyHelper.getUrlLocalHomeCommunity(NhincConstants.PATIENT_CORRELATION_SERVICE_NAME); if (msg == null) { LOG.error("Message was null"); } else if (assertion == null) { LOG.error("assertion was null"); } else { AddPatientCorrelationRequestType request = new AddPatientCorrelationRequestType(); request.setPRPAIN201301UV02(msg); request.setAssertion(assertion); ServicePortDescriptor<PatientCorrelationPortType> portDescriptor = getRetrieveServicePortDescriptor(NhincConstants.ADAPTER_API_LEVEL.LEVEL_a0); CONNECTClient<PatientCorrelationPortType> client = CONNECTClientFactory.getInstance() .getCONNECTClientUnsecured(portDescriptor, url, assertion); response = (AddPatientCorrelationResponseType) client .invokePort(PatientCorrelationPortType.class, "addPatientCorrelation", request); } } catch (Exception ex) { LOG.error("Error calling addPatientCorrelation: " + ex.getMessage(), ex); } LOG.debug("End addPatientCorrelation"); return response; } }
GATEWAY-3309: Fixed the other operation as well.
Product/Production/Services/PatientCorrelationCore/src/main/java/gov/hhs/fha/nhinc/patientcorrelation/nhinc/proxy/PatientCorrelationProxyWebServiceUnsecuredImpl.java
GATEWAY-3309: Fixed the other operation as well.
<ide><path>roduct/Production/Services/PatientCorrelationCore/src/main/java/gov/hhs/fha/nhinc/patientcorrelation/nhinc/proxy/PatientCorrelationProxyWebServiceUnsecuredImpl.java <ide> getRetrieveServicePortDescriptor(NhincConstants.ADAPTER_API_LEVEL.LEVEL_a0); <ide> <ide> CONNECTClient<PatientCorrelationPortType> client = CONNECTClientFactory.getInstance() <del> .getCONNECTClientSecured(portDescriptor, url, assertion); <add> .getCONNECTClientUnsecured(portDescriptor, url, assertion); <ide> <ide> response = (RetrievePatientCorrelationsResponseType) client <ide> .invokePort(PatientCorrelationPortType.class, "retrievePatientCorrelations", request);
JavaScript
bsd-3-clause
a13b00e3371c8e409f680309683d460073855ac2
0
meego-tablet-ux/meego-app-browser,meego-tablet-ux/meego-app-browser,meego-tablet-ux/meego-app-browser,meego-tablet-ux/meego-app-browser,meego-tablet-ux/meego-app-browser,meego-tablet-ux/meego-app-browser,meego-tablet-ux/meego-app-browser,meego-tablet-ux/meego-app-browser,meego-tablet-ux/meego-app-browser,meego-tablet-ux/meego-app-browser
// Copyright (c) 2009 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. var chrome = chrome || {}; (function () { native function GetChromeHidden(); native function AttachEvent(eventName); native function DetachEvent(eventName); var chromeHidden = GetChromeHidden(); // Event object. If opt_eventName is provided, this object represents // the unique instance of that named event, and dispatching an event // with that name will route through this object's listeners. // // Example: // chrome.tabs.onChanged = new chrome.Event("tab-changed"); // chrome.tabs.onChanged.addListener(function(data) { alert(data); }); // chromeHidden.Event.dispatch("tab-changed", "hi"); // will result in an alert dialog that says 'hi'. chrome.Event = function(opt_eventName, opt_argSchemas) { this.eventName_ = opt_eventName; this.listeners_ = []; // Validate event parameters if we are in debug. if (opt_argSchemas && chromeHidden.validateCallbacks && chromeHidden.validate) { this.validate_ = function(args) { try { chromeHidden.validate(args, opt_argSchemas); } catch (exception) { return "Event validation error during " + opt_eventName + " -- " + exception; } } } }; // A map of event names to the event object that is registered to that name. var attachedNamedEvents = {}; // An array of all attached event objects, used for detaching on unload. var allAttachedEvents = []; chromeHidden.Event = {}; // Dispatches a named event with the given JSON array, which is deserialized // before dispatch. The JSON array is the list of arguments that will be // sent with the event callback. chromeHidden.Event.dispatchJSON = function(name, args) { if (attachedNamedEvents[name]) { if (args) { args = JSON.parse(args); } return attachedNamedEvents[name].dispatch.apply( attachedNamedEvents[name], args); } }; // Dispatches a named event with the given arguments, supplied as an array. chromeHidden.Event.dispatch = function(name, args) { if (attachedNamedEvents[name]) { attachedNamedEvents[name].dispatch.apply( attachedNamedEvents[name], args); } }; // Test if a named event has any listeners. chromeHidden.Event.hasListener = function(name) { return (attachedNamedEvents[name] && attachedNamedEvents[name].listeners_.length > 0); } // Registers a callback to be called when this event is dispatched. chrome.Event.prototype.addListener = function(cb) { this.listeners_.push(cb); if (this.listeners_.length == 1) { this.attach_(); } }; // Unregisters a callback. chrome.Event.prototype.removeListener = function(cb) { var idx = this.findListener_(cb); if (idx == -1) { return; } this.listeners_.splice(idx, 1); if (this.listeners_.length == 0) { this.detach_(); } }; // Test if the given callback is registered for this event. chrome.Event.prototype.hasListener = function(cb) { return this.findListener_(cb) > -1; }; // Test if any callbacks are registered for this event. chrome.Event.prototype.hasListeners = function(cb) { return this.listeners_.length > 0; }; // Returns the index of the given callback if registered, or -1 if not // found. chrome.Event.prototype.findListener_ = function(cb) { for (var i = 0; i < this.listeners_.length; i++) { if (this.listeners_[i] == cb) { return i; } } return -1; }; // Dispatches this event object to all listeners, passing all supplied // arguments to this function each listener. chrome.Event.prototype.dispatch = function(varargs) { var args = Array.prototype.slice.call(arguments); if (this.validate_) { var validationErrors = this.validate_(args); if (validationErrors) { return validationErrors; } } for (var i = 0; i < this.listeners_.length; i++) { try { this.listeners_[i].apply(null, args); } catch (e) { console.error(e); } } }; // Attaches this event object to its name. Only one object can have a given // name. chrome.Event.prototype.attach_ = function() { AttachEvent(this.eventName_); allAttachedEvents[allAttachedEvents.length] = this; if (!this.eventName_) return; if (attachedNamedEvents[this.eventName_]) { throw new Error("chrome.Event '" + this.eventName_ + "' is already attached."); } attachedNamedEvents[this.eventName_] = this; }; // Detaches this event object from its name. chrome.Event.prototype.detach_ = function() { var i = allAttachedEvents.indexOf(this); if (i >= 0) delete allAttachedEvents[i]; DetachEvent(this.eventName_); if (!this.eventName_) return; if (!attachedNamedEvents[this.eventName_]) { throw new Error("chrome.Event '" + this.eventName_ + "' is not attached."); } delete attachedNamedEvents[this.eventName_]; }; // Special load events: we don't use the DOM unload because that slows // down tab shutdown. On the other hand, onUnload might not always fire, // since Chrome will terminate renderers on shutdown (SuddenTermination). chromeHidden.onLoad = new chrome.Event(); chromeHidden.onUnload = new chrome.Event(); chromeHidden.dispatchOnLoad = function(extensionId) { chromeHidden.onLoad.dispatch(extensionId); } chromeHidden.dispatchOnUnload = function() { chromeHidden.onUnload.dispatch(); for (var i in allAttachedEvents) allAttachedEvents[i].detach_(); } chromeHidden.dispatchError = function(msg) { console.error(msg); } })();
chrome/renderer/resources/event_bindings.js
// Copyright (c) 2009 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. var chrome = chrome || {}; (function () { native function GetChromeHidden(); native function AttachEvent(eventName); native function DetachEvent(eventName); var chromeHidden = GetChromeHidden(); // Event object. If opt_eventName is provided, this object represents // the unique instance of that named event, and dispatching an event // with that name will route through this object's listeners. // // Example: // chrome.tabs.onChanged = new chrome.Event("tab-changed"); // chrome.tabs.onChanged.addListener(function(data) { alert(data); }); // chromeHidden.Event.dispatch("tab-changed", "hi"); // will result in an alert dialog that says 'hi'. chrome.Event = function(opt_eventName, opt_argSchemas) { this.eventName_ = opt_eventName; this.listeners_ = []; // Validate event parameters if we are in debug. if (opt_argSchemas && chromeHidden.validateCallbacks && chromeHidden.validate) { this.validate_ = function(args) { try { chromeHidden.validate(args, opt_argSchemas); } catch (exception) { return "Event validation error during " + opt_eventName + " -- " + exception; } } } }; // A map of event names to the event object that is registered to that name. var attachedNamedEvents = {}; // An array of all attached event objects, used for detaching on unload. var allAttachedEvents = []; chromeHidden.Event = {}; // Dispatches a named event with the given JSON array, which is deserialized // before dispatch. The JSON array is the list of arguments that will be // sent with the event callback. chromeHidden.Event.dispatchJSON = function(name, args) { if (attachedNamedEvents[name]) { if (args) { args = JSON.parse(args); } return attachedNamedEvents[name].dispatch.apply( attachedNamedEvents[name], args); } }; // Dispatches a named event with the given arguments, supplied as an array. chromeHidden.Event.dispatch = function(name, args) { if (attachedNamedEvents[name]) { attachedNamedEvents[name].dispatch.apply( attachedNamedEvents[name], args); } }; // Test if a named event has any listeners. chromeHidden.Event.hasListener = function(name) { return (attachedNamedEvents[name] && attachedNamedEvents[name].listeners_.length > 0); } // Registers a callback to be called when this event is dispatched. chrome.Event.prototype.addListener = function(cb) { this.listeners_.push(cb); if (this.listeners_.length == 1) { this.attach_(); } }; // Unregisters a callback. chrome.Event.prototype.removeListener = function(cb) { var idx = this.findListener_(cb); if (idx == -1) { return; } this.listeners_.splice(idx, 1); if (this.listeners_.length == 0) { this.detach_(); } }; // Test if the given callback is registered for this event. chrome.Event.prototype.hasListener = function(cb) { return this.findListeners_(cb) > -1; }; // Test if any callbacks are registered for this event. chrome.Event.prototype.hasListeners = function(cb) { return this.listeners_.length > 0; }; // Returns the index of the given callback if registered, or -1 if not // found. chrome.Event.prototype.findListener_ = function(cb) { for (var i = 0; i < this.listeners_.length; i++) { if (this.listeners_[i] == cb) { return i; } } return -1; }; // Dispatches this event object to all listeners, passing all supplied // arguments to this function each listener. chrome.Event.prototype.dispatch = function(varargs) { var args = Array.prototype.slice.call(arguments); if (this.validate_) { var validationErrors = this.validate_(args); if (validationErrors) { return validationErrors; } } for (var i = 0; i < this.listeners_.length; i++) { try { this.listeners_[i].apply(null, args); } catch (e) { console.error(e); } } }; // Attaches this event object to its name. Only one object can have a given // name. chrome.Event.prototype.attach_ = function() { AttachEvent(this.eventName_); allAttachedEvents[allAttachedEvents.length] = this; if (!this.eventName_) return; if (attachedNamedEvents[this.eventName_]) { throw new Error("chrome.Event '" + this.eventName_ + "' is already attached."); } attachedNamedEvents[this.eventName_] = this; }; // Detaches this event object from its name. chrome.Event.prototype.detach_ = function() { var i = allAttachedEvents.indexOf(this); if (i >= 0) delete allAttachedEvents[i]; DetachEvent(this.eventName_); if (!this.eventName_) return; if (!attachedNamedEvents[this.eventName_]) { throw new Error("chrome.Event '" + this.eventName_ + "' is not attached."); } delete attachedNamedEvents[this.eventName_]; }; // Special load events: we don't use the DOM unload because that slows // down tab shutdown. On the other hand, onUnload might not always fire, // since Chrome will terminate renderers on shutdown (SuddenTermination). chromeHidden.onLoad = new chrome.Event(); chromeHidden.onUnload = new chrome.Event(); chromeHidden.dispatchOnLoad = function(extensionId) { chromeHidden.onLoad.dispatch(extensionId); } chromeHidden.dispatchOnUnload = function() { chromeHidden.onUnload.dispatch(); for (var i in allAttachedEvents) allAttachedEvents[i].detach_(); } chromeHidden.dispatchError = function(msg) { console.error(msg); } })();
Fix typo in Event.hasListener(). Patch from Kelly Norton <[email protected]> [email protected] git-svn-id: http://src.chromium.org/svn/trunk/src@30506 4ff67af0-8c30-449e-8e8b-ad334ec8d88c Former-commit-id: a5fd38bd1f1aea6939320b113e10da47f50fd2f1
chrome/renderer/resources/event_bindings.js
Fix typo in Event.hasListener().
<ide><path>hrome/renderer/resources/event_bindings.js <ide> <ide> // Test if the given callback is registered for this event. <ide> chrome.Event.prototype.hasListener = function(cb) { <del> return this.findListeners_(cb) > -1; <add> return this.findListener_(cb) > -1; <ide> }; <ide> <ide> // Test if any callbacks are registered for this event.
Java
mit
2084975431dfe30a82834ee2a209641f74c91210
0
grimes2/jabref,ayanai1/jabref,JabRef/jabref,tobiasdiez/jabref,Siedlerchr/jabref,zellerdev/jabref,tobiasdiez/jabref,bartsch-dev/jabref,grimes2/jabref,bartsch-dev/jabref,jhshinn/jabref,mredaelli/jabref,jhshinn/jabref,oscargus/jabref,oscargus/jabref,grimes2/jabref,mairdl/jabref,obraliar/jabref,motokito/jabref,tschechlovdev/jabref,mredaelli/jabref,bartsch-dev/jabref,Braunch/jabref,shitikanth/jabref,tschechlovdev/jabref,mredaelli/jabref,sauliusg/jabref,zellerdev/jabref,motokito/jabref,mairdl/jabref,Siedlerchr/jabref,obraliar/jabref,sauliusg/jabref,Braunch/jabref,JabRef/jabref,Siedlerchr/jabref,Braunch/jabref,mredaelli/jabref,obraliar/jabref,jhshinn/jabref,obraliar/jabref,ayanai1/jabref,grimes2/jabref,shitikanth/jabref,ayanai1/jabref,obraliar/jabref,motokito/jabref,tschechlovdev/jabref,oscargus/jabref,bartsch-dev/jabref,zellerdev/jabref,ayanai1/jabref,JabRef/jabref,jhshinn/jabref,Mr-DLib/jabref,tobiasdiez/jabref,bartsch-dev/jabref,tschechlovdev/jabref,mairdl/jabref,JabRef/jabref,shitikanth/jabref,grimes2/jabref,jhshinn/jabref,Braunch/jabref,Mr-DLib/jabref,Siedlerchr/jabref,mredaelli/jabref,Braunch/jabref,oscargus/jabref,zellerdev/jabref,Mr-DLib/jabref,tobiasdiez/jabref,oscargus/jabref,shitikanth/jabref,motokito/jabref,shitikanth/jabref,tschechlovdev/jabref,sauliusg/jabref,Mr-DLib/jabref,sauliusg/jabref,Mr-DLib/jabref,zellerdev/jabref,motokito/jabref,ayanai1/jabref,mairdl/jabref,mairdl/jabref
/* All programs in this directory and subdirectories are published under the GNU General Public License as described below. This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA Further information about the GNU GPL is available at: http://www.gnu.org/copyleft/gpl.ja.html */ package net.sf.jabref.groups; import java.util.Vector; import net.sf.jabref.*; /** * Handles versioning of groups, e.g. automatic conversion from previous to * current versions, or import of flat groups (JabRef <= 1.6) to tree. * * @author jzieren (10.04.2005) */ public class VersionHandling { public static final int CURRENT_VERSION = 3; /** * Imports old (flat) groups data and converts it to a 2-level tree with an * AllEntriesGroup at the root. * * @return the root of the generated tree. */ public static GroupTreeNode importFlatGroups(Vector groups) throws IllegalArgumentException { GroupTreeNode root = new GroupTreeNode(new AllEntriesGroup()); final int number = groups.size() / 3; String name, field, regexp; for (int i = 0; i < number; ++i) { field = (String) groups.elementAt(3 * i + 0); name = (String) groups.elementAt(3 * i + 1); regexp = (String) groups.elementAt(3 * i + 2); root.add(new GroupTreeNode(new KeywordGroup(name, field, regexp, false, true, AbstractGroup.INDEPENDENT))); } return root; } public static GroupTreeNode importGroups(Vector orderedData, BibtexDatabase db, int version) throws Exception { switch (version) { case 0: case 1: return Version0_1.fromString((String) orderedData.firstElement(), db, version); case 2: case 3: return Version2_3.fromString(orderedData, db, version); default: throw new IllegalArgumentException(Globals.lang( "Failed to read groups data (unsupported version: %0)", "" + version)); } } /** Imports groups version 0 and 1. */ private static class Version0_1 { /** * Parses the textual representation obtained from * GroupTreeNode.toString() and recreates that node and all of its * children from it. * * @throws Exception * When a group could not be recreated */ private static GroupTreeNode fromString(String s, BibtexDatabase db, int version) throws Exception { GroupTreeNode root = null; GroupTreeNode newNode; int i; String g; while (s.length() > 0) { if (s.startsWith("(")) { String subtree = getSubtree(s); newNode = fromString(subtree, db, version); // continue after this subtree by removing it // and the leading/trailing braces, and // the comma (that makes 3) that always trails it // unless it's at the end of s anyway. i = 3 + subtree.length(); s = i >= s.length() ? "" : s.substring(i); } else { i = indexOfUnquoted(s, ','); g = i < 0 ? s : s.substring(0, i); if (i >= 0) s = s.substring(i + 1); else s = ""; newNode = new GroupTreeNode(AbstractGroup.fromString(Util .unquote(g, '\\'), db, version)); } if (root == null) // first node will be root root = newNode; else root.add(newNode); } return root; } /** * Returns the substring delimited by a pair of matching braces, with * the first brace at index 0. Quoted characters are skipped. * * @return the matching substring, or "" if not found. */ private static String getSubtree(String s) { int i = 1; int level = 1; while (i < s.length()) { switch (s.charAt(i)) { case '\\': ++i; break; case '(': ++level; break; case ')': --level; if (level == 0) return s.substring(1, i); break; } ++i; } return ""; } /** * Returns the index of the first occurence of c, skipping quoted * special characters (escape character: '\\'). * * @param s * The String to search in. * @param c * The character to search * @return The index of the first unescaped occurence of c in s, or -1 * if not found. */ private static int indexOfUnquoted(String s, char c) { int i = 0; while (i < s.length()) { if (s.charAt(i) == '\\') { ++i; // skip quoted special } else { if (s.charAt(i) == c) return i; } ++i; } return -1; } } private static class Version2_3 { private static GroupTreeNode fromString(Vector data, BibtexDatabase db, int version) throws Exception { GroupTreeNode cursor = null; GroupTreeNode root = null; GroupTreeNode newNode; AbstractGroup group; int spaceIndex; int level; String s; for (int i = 0; i < data.size(); ++i) { s = data.elementAt(i).toString(); spaceIndex = s.indexOf(' '); if (spaceIndex <= 0) throw new Exception("bad format"); // JZTODO lyrics level = Integer.parseInt(s.substring(0, spaceIndex)); group = AbstractGroup.fromString(s.substring(spaceIndex + 1), db, version); newNode = new GroupTreeNode(group); if (cursor == null) { // create new root cursor = newNode; root = cursor; } else { // insert at desired location while (level <= cursor.getLevel()) cursor = (GroupTreeNode) cursor.getParent(); cursor.add(newNode); cursor = newNode; } } return root; } } }
src/java/net/sf/jabref/groups/VersionHandling.java
/* All programs in this directory and subdirectories are published under the GNU General Public License as described below. This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA Further information about the GNU GPL is available at: http://www.gnu.org/copyleft/gpl.ja.html */ package net.sf.jabref.groups; import java.util.Vector; import net.sf.jabref.*; /** * Handles versioning of groups, e.g. automatic conversion from previous to * current versions, or import of flat groups (JabRef <= 1.6) to tree. * * @author jzieren (10.04.2005) */ public class VersionHandling { public static final int CURRENT_VERSION = 2; /** * Imports old (flat) groups data and converts it to a 2-level tree with an * AllEntriesGroup at the root. * * @return the root of the generated tree. */ public static GroupTreeNode importFlatGroups(Vector groups) throws IllegalArgumentException { GroupTreeNode root = new GroupTreeNode(new AllEntriesGroup()); final int number = groups.size() / 3; String name, field, regexp; for (int i = 0; i < number; ++i) { field = (String) groups.elementAt(3 * i + 0); name = (String) groups.elementAt(3 * i + 1); regexp = (String) groups.elementAt(3 * i + 2); root.add(new GroupTreeNode(new KeywordGroup(name, field, regexp, false, true))); } return root; } public static GroupTreeNode importGroups(Vector orderedData, BibtexDatabase db, int version) throws Exception { switch (version) { case 0: case 1: return Version0_1.fromString((String) orderedData.firstElement(), db, version); case 2: return Version2.fromString(orderedData, db, version); default: throw new IllegalArgumentException(Globals.lang( "Failed to read groups data (unsupported version: %0)", "" + version)); } } /** Imports groups version 0 and 1. */ private static class Version0_1 { /** * Parses the textual representation obtained from * GroupTreeNode.toString() and recreates that node and all of its * children from it. * * @throws Exception * When a group could not be recreated */ private static GroupTreeNode fromString(String s, BibtexDatabase db, int version) throws Exception { GroupTreeNode root = null; GroupTreeNode newNode; int i; String g; while (s.length() > 0) { if (s.startsWith("(")) { String subtree = getSubtree(s); newNode = fromString(subtree, db, version); // continue after this subtree by removing it // and the leading/trailing braces, and // the comma (that makes 3) that always trails it // unless it's at the end of s anyway. i = 3 + subtree.length(); s = i >= s.length() ? "" : s.substring(i); } else { i = indexOfUnquoted(s, ','); g = i < 0 ? s : s.substring(0, i); if (i >= 0) s = s.substring(i + 1); else s = ""; newNode = new GroupTreeNode(AbstractGroup.fromString(Util .unquote(g, '\\'), db, version)); } if (root == null) // first node will be root root = newNode; else root.add(newNode); } return root; } /** * Returns the substring delimited by a pair of matching braces, with * the first brace at index 0. Quoted characters are skipped. * * @return the matching substring, or "" if not found. */ private static String getSubtree(String s) { int i = 1; int level = 1; while (i < s.length()) { switch (s.charAt(i)) { case '\\': ++i; break; case '(': ++level; break; case ')': --level; if (level == 0) return s.substring(1, i); break; } ++i; } return ""; } /** * Returns the index of the first occurence of c, skipping quoted * special characters (escape character: '\\'). * * @param s * The String to search in. * @param c * The character to search * @return The index of the first unescaped occurence of c in s, or -1 * if not found. */ private static int indexOfUnquoted(String s, char c) { int i = 0; while (i < s.length()) { if (s.charAt(i) == '\\') { ++i; // skip quoted special } else { if (s.charAt(i) == c) return i; } ++i; } return -1; } } private static class Version2 { private static GroupTreeNode fromString(Vector data, BibtexDatabase db, int version) throws Exception { GroupTreeNode cursor = null; GroupTreeNode root = null; GroupTreeNode newNode; AbstractGroup group; int spaceIndex; int level; String s; for (int i = 0; i < data.size(); ++i) { s = data.elementAt(i).toString(); spaceIndex = s.indexOf(' '); if (spaceIndex <= 0) throw new Exception("bad format"); // JZTODO lyrics level = Integer.parseInt(s.substring(0, spaceIndex)); group = AbstractGroup.fromString(s.substring(spaceIndex + 1), db, version); newNode = new GroupTreeNode(group); if (cursor == null) { // create new root cursor = newNode; root = cursor; } else { // insert at desired location while (level <= cursor.getLevel()) cursor = (GroupTreeNode) cursor.getParent(); cursor.add(newNode); cursor = newNode; } } return root; } } }
added handling for new groups version that stores hierarchical context per group
src/java/net/sf/jabref/groups/VersionHandling.java
added handling for new groups version that stores hierarchical context per group
<ide><path>rc/java/net/sf/jabref/groups/VersionHandling.java <ide> * @author jzieren (10.04.2005) <ide> */ <ide> public class VersionHandling { <del> public static final int CURRENT_VERSION = 2; <add> public static final int CURRENT_VERSION = 3; <ide> <ide> /** <ide> * Imports old (flat) groups data and converts it to a 2-level tree with an <ide> name = (String) groups.elementAt(3 * i + 1); <ide> regexp = (String) groups.elementAt(3 * i + 2); <ide> root.add(new GroupTreeNode(new KeywordGroup(name, field, regexp, <del> false, true))); <add> false, true, AbstractGroup.INDEPENDENT))); <ide> } <ide> return root; <ide> } <ide> return Version0_1.fromString((String) orderedData.firstElement(), <ide> db, version); <ide> case 2: <del> return Version2.fromString(orderedData, db, version); <add> case 3: <add> return Version2_3.fromString(orderedData, db, version); <ide> default: <ide> throw new IllegalArgumentException(Globals.lang( <ide> "Failed to read groups data (unsupported version: %0)", <ide> } <ide> } <ide> <del> private static class Version2 { <add> private static class Version2_3 { <ide> private static GroupTreeNode fromString(Vector data, BibtexDatabase db, <ide> int version) throws Exception { <ide> GroupTreeNode cursor = null;
Java
apache-2.0
ea2792e27883299b92d721c840b7368d635600fa
0
JervyShi/elasticsearch,fernandozhu/elasticsearch,scottsom/elasticsearch,geidies/elasticsearch,i-am-Nathan/elasticsearch,strapdata/elassandra5-rc,mortonsykes/elasticsearch,henakamaMSFT/elasticsearch,JSCooke/elasticsearch,jimczi/elasticsearch,mortonsykes/elasticsearch,fforbeck/elasticsearch,episerver/elasticsearch,StefanGor/elasticsearch,nezirus/elasticsearch,dongjoon-hyun/elasticsearch,mjason3/elasticsearch,spiegela/elasticsearch,qwerty4030/elasticsearch,elasticdog/elasticsearch,ThiagoGarciaAlves/elasticsearch,obourgain/elasticsearch,GlenRSmith/elasticsearch,dpursehouse/elasticsearch,avikurapati/elasticsearch,liweinan0423/elasticsearch,ricardocerq/elasticsearch,uschindler/elasticsearch,qwerty4030/elasticsearch,wangtuo/elasticsearch,Helen-Zhao/elasticsearch,awislowski/elasticsearch,gfyoung/elasticsearch,lks21c/elasticsearch,bawse/elasticsearch,gfyoung/elasticsearch,shreejay/elasticsearch,ESamir/elasticsearch,ricardocerq/elasticsearch,vroyer/elasticassandra,myelin/elasticsearch,nknize/elasticsearch,scorpionvicky/elasticsearch,dongjoon-hyun/elasticsearch,avikurapati/elasticsearch,myelin/elasticsearch,rlugojr/elasticsearch,xuzha/elasticsearch,brandonkearby/elasticsearch,s1monw/elasticsearch,mohit/elasticsearch,mapr/elasticsearch,obourgain/elasticsearch,clintongormley/elasticsearch,elasticdog/elasticsearch,rajanm/elasticsearch,dongjoon-hyun/elasticsearch,markwalkom/elasticsearch,kalimatas/elasticsearch,umeshdangat/elasticsearch,ThiagoGarciaAlves/elasticsearch,brandonkearby/elasticsearch,nazarewk/elasticsearch,gingerwizard/elasticsearch,mikemccand/elasticsearch,mjason3/elasticsearch,LeoYao/elasticsearch,awislowski/elasticsearch,mapr/elasticsearch,StefanGor/elasticsearch,coding0011/elasticsearch,ricardocerq/elasticsearch,yanjunh/elasticsearch,kalimatas/elasticsearch,naveenhooda2000/elasticsearch,artnowo/elasticsearch,ThiagoGarciaAlves/elasticsearch,MaineC/elasticsearch,artnowo/elasticsearch,trangvh/elasticsearch,cwurm/elasticsearch,wangtuo/elasticsearch,rlugojr/elasticsearch,awislowski/elasticsearch,glefloch/elasticsearch,ThiagoGarciaAlves/elasticsearch,shreejay/elasticsearch,scorpionvicky/elasticsearch,yanjunh/elasticsearch,artnowo/elasticsearch,pozhidaevak/elasticsearch,LeoYao/elasticsearch,wuranbo/elasticsearch,JackyMai/elasticsearch,JSCooke/elasticsearch,henakamaMSFT/elasticsearch,dpursehouse/elasticsearch,fforbeck/elasticsearch,camilojd/elasticsearch,mmaracic/elasticsearch,Stacey-Gammon/elasticsearch,mortonsykes/elasticsearch,nazarewk/elasticsearch,JervyShi/elasticsearch,nomoa/elasticsearch,Stacey-Gammon/elasticsearch,rlugojr/elasticsearch,sneivandt/elasticsearch,bawse/elasticsearch,zkidkid/elasticsearch,glefloch/elasticsearch,dongjoon-hyun/elasticsearch,umeshdangat/elasticsearch,JervyShi/elasticsearch,palecur/elasticsearch,liweinan0423/elasticsearch,pozhidaevak/elasticsearch,StefanGor/elasticsearch,s1monw/elasticsearch,nknize/elasticsearch,nomoa/elasticsearch,yanjunh/elasticsearch,girirajsharma/elasticsearch,girirajsharma/elasticsearch,Stacey-Gammon/elasticsearch,robin13/elasticsearch,yynil/elasticsearch,rajanm/elasticsearch,naveenhooda2000/elasticsearch,ricardocerq/elasticsearch,alexshadow007/elasticsearch,mapr/elasticsearch,ESamir/elasticsearch,gmarz/elasticsearch,i-am-Nathan/elasticsearch,robin13/elasticsearch,vroyer/elassandra,uschindler/elasticsearch,yynil/elasticsearch,jprante/elasticsearch,winstonewert/elasticsearch,mmaracic/elasticsearch,Helen-Zhao/elasticsearch,IanvsPoplicola/elasticsearch,brandonkearby/elasticsearch,sreeramjayan/elasticsearch,gmarz/elasticsearch,IanvsPoplicola/elasticsearch,mikemccand/elasticsearch,fforbeck/elasticsearch,lks21c/elasticsearch,spiegela/elasticsearch,palecur/elasticsearch,maddin2016/elasticsearch,IanvsPoplicola/elasticsearch,camilojd/elasticsearch,episerver/elasticsearch,JackyMai/elasticsearch,ZTE-PaaS/elasticsearch,nazarewk/elasticsearch,mohit/elasticsearch,MisterAndersen/elasticsearch,LewayneNaidoo/elasticsearch,rlugojr/elasticsearch,nazarewk/elasticsearch,ZTE-PaaS/elasticsearch,sreeramjayan/elasticsearch,maddin2016/elasticsearch,MisterAndersen/elasticsearch,episerver/elasticsearch,LeoYao/elasticsearch,clintongormley/elasticsearch,fred84/elasticsearch,MisterAndersen/elasticsearch,camilojd/elasticsearch,gingerwizard/elasticsearch,a2lin/elasticsearch,i-am-Nathan/elasticsearch,Shepard1212/elasticsearch,naveenhooda2000/elasticsearch,strapdata/elassandra5-rc,brandonkearby/elasticsearch,jimczi/elasticsearch,mohit/elasticsearch,coding0011/elasticsearch,mikemccand/elasticsearch,pozhidaevak/elasticsearch,wangtuo/elasticsearch,camilojd/elasticsearch,IanvsPoplicola/elasticsearch,JackyMai/elasticsearch,wuranbo/elasticsearch,kalimatas/elasticsearch,wangtuo/elasticsearch,girirajsharma/elasticsearch,coding0011/elasticsearch,masaruh/elasticsearch,glefloch/elasticsearch,myelin/elasticsearch,MisterAndersen/elasticsearch,cwurm/elasticsearch,rajanm/elasticsearch,mmaracic/elasticsearch,jimczi/elasticsearch,Shepard1212/elasticsearch,GlenRSmith/elasticsearch,geidies/elasticsearch,strapdata/elassandra5-rc,yynil/elasticsearch,wuranbo/elasticsearch,glefloch/elasticsearch,strapdata/elassandra5-rc,umeshdangat/elasticsearch,jprante/elasticsearch,gfyoung/elasticsearch,glefloch/elasticsearch,shreejay/elasticsearch,JervyShi/elasticsearch,sreeramjayan/elasticsearch,mapr/elasticsearch,zkidkid/elasticsearch,qwerty4030/elasticsearch,gingerwizard/elasticsearch,henakamaMSFT/elasticsearch,fernandozhu/elasticsearch,LeoYao/elasticsearch,masaruh/elasticsearch,fred84/elasticsearch,strapdata/elassandra,mjason3/elasticsearch,strapdata/elassandra,qwerty4030/elasticsearch,lks21c/elasticsearch,elasticdog/elasticsearch,xuzha/elasticsearch,naveenhooda2000/elasticsearch,jprante/elasticsearch,MaineC/elasticsearch,robin13/elasticsearch,JSCooke/elasticsearch,spiegela/elasticsearch,alexshadow007/elasticsearch,ZTE-PaaS/elasticsearch,alexshadow007/elasticsearch,ThiagoGarciaAlves/elasticsearch,yynil/elasticsearch,JSCooke/elasticsearch,mortonsykes/elasticsearch,winstonewert/elasticsearch,wenpos/elasticsearch,scottsom/elasticsearch,vroyer/elasticassandra,nilabhsagar/elasticsearch,ESamir/elasticsearch,a2lin/elasticsearch,henakamaMSFT/elasticsearch,qwerty4030/elasticsearch,gfyoung/elasticsearch,sneivandt/elasticsearch,rajanm/elasticsearch,njlawton/elasticsearch,masaruh/elasticsearch,mikemccand/elasticsearch,masaruh/elasticsearch,ricardocerq/elasticsearch,sneivandt/elasticsearch,mapr/elasticsearch,ZTE-PaaS/elasticsearch,gingerwizard/elasticsearch,mjason3/elasticsearch,gfyoung/elasticsearch,jprante/elasticsearch,s1monw/elasticsearch,alexshadow007/elasticsearch,HonzaKral/elasticsearch,avikurapati/elasticsearch,GlenRSmith/elasticsearch,wenpos/elasticsearch,mortonsykes/elasticsearch,wenpos/elasticsearch,rlugojr/elasticsearch,naveenhooda2000/elasticsearch,njlawton/elasticsearch,bawse/elasticsearch,winstonewert/elasticsearch,nilabhsagar/elasticsearch,JackyMai/elasticsearch,nezirus/elasticsearch,JackyMai/elasticsearch,rajanm/elasticsearch,jimczi/elasticsearch,yanjunh/elasticsearch,palecur/elasticsearch,s1monw/elasticsearch,girirajsharma/elasticsearch,strapdata/elassandra,yynil/elasticsearch,fforbeck/elasticsearch,myelin/elasticsearch,vroyer/elassandra,i-am-Nathan/elasticsearch,myelin/elasticsearch,shreejay/elasticsearch,umeshdangat/elasticsearch,girirajsharma/elasticsearch,yanjunh/elasticsearch,maddin2016/elasticsearch,C-Bish/elasticsearch,spiegela/elasticsearch,fernandozhu/elasticsearch,Stacey-Gammon/elasticsearch,mmaracic/elasticsearch,winstonewert/elasticsearch,gingerwizard/elasticsearch,wenpos/elasticsearch,yynil/elasticsearch,cwurm/elasticsearch,artnowo/elasticsearch,nilabhsagar/elasticsearch,dpursehouse/elasticsearch,Helen-Zhao/elasticsearch,nezirus/elasticsearch,HonzaKral/elasticsearch,MaineC/elasticsearch,HonzaKral/elasticsearch,trangvh/elasticsearch,wangtuo/elasticsearch,vroyer/elasticassandra,nilabhsagar/elasticsearch,coding0011/elasticsearch,episerver/elasticsearch,a2lin/elasticsearch,bawse/elasticsearch,alexshadow007/elasticsearch,mmaracic/elasticsearch,maddin2016/elasticsearch,geidies/elasticsearch,JervyShi/elasticsearch,mikemccand/elasticsearch,HonzaKral/elasticsearch,jimczi/elasticsearch,spiegela/elasticsearch,wuranbo/elasticsearch,robin13/elasticsearch,i-am-Nathan/elasticsearch,xuzha/elasticsearch,sreeramjayan/elasticsearch,palecur/elasticsearch,JervyShi/elasticsearch,C-Bish/elasticsearch,awislowski/elasticsearch,StefanGor/elasticsearch,palecur/elasticsearch,jprante/elasticsearch,geidies/elasticsearch,fforbeck/elasticsearch,nknize/elasticsearch,nezirus/elasticsearch,JSCooke/elasticsearch,Shepard1212/elasticsearch,obourgain/elasticsearch,girirajsharma/elasticsearch,MaineC/elasticsearch,LeoYao/elasticsearch,markwalkom/elasticsearch,markwalkom/elasticsearch,clintongormley/elasticsearch,dpursehouse/elasticsearch,uschindler/elasticsearch,trangvh/elasticsearch,liweinan0423/elasticsearch,s1monw/elasticsearch,a2lin/elasticsearch,fernandozhu/elasticsearch,pozhidaevak/elasticsearch,pozhidaevak/elasticsearch,Helen-Zhao/elasticsearch,C-Bish/elasticsearch,markwalkom/elasticsearch,StefanGor/elasticsearch,njlawton/elasticsearch,gmarz/elasticsearch,strapdata/elassandra,C-Bish/elasticsearch,clintongormley/elasticsearch,LeoYao/elasticsearch,scorpionvicky/elasticsearch,brandonkearby/elasticsearch,wuranbo/elasticsearch,wenpos/elasticsearch,shreejay/elasticsearch,uschindler/elasticsearch,xuzha/elasticsearch,gmarz/elasticsearch,GlenRSmith/elasticsearch,lks21c/elasticsearch,ThiagoGarciaAlves/elasticsearch,trangvh/elasticsearch,avikurapati/elasticsearch,rajanm/elasticsearch,fred84/elasticsearch,MisterAndersen/elasticsearch,zkidkid/elasticsearch,henakamaMSFT/elasticsearch,masaruh/elasticsearch,njlawton/elasticsearch,xuzha/elasticsearch,dpursehouse/elasticsearch,strapdata/elassandra,kalimatas/elasticsearch,scottsom/elasticsearch,LeoYao/elasticsearch,nknize/elasticsearch,Shepard1212/elasticsearch,cwurm/elasticsearch,elasticdog/elasticsearch,MaineC/elasticsearch,scorpionvicky/elasticsearch,Stacey-Gammon/elasticsearch,ESamir/elasticsearch,mmaracic/elasticsearch,maddin2016/elasticsearch,robin13/elasticsearch,obourgain/elasticsearch,nazarewk/elasticsearch,liweinan0423/elasticsearch,obourgain/elasticsearch,dongjoon-hyun/elasticsearch,vroyer/elassandra,njlawton/elasticsearch,gingerwizard/elasticsearch,LewayneNaidoo/elasticsearch,ESamir/elasticsearch,nomoa/elasticsearch,xuzha/elasticsearch,avikurapati/elasticsearch,episerver/elasticsearch,Helen-Zhao/elasticsearch,scottsom/elasticsearch,scorpionvicky/elasticsearch,sreeramjayan/elasticsearch,uschindler/elasticsearch,winstonewert/elasticsearch,IanvsPoplicola/elasticsearch,artnowo/elasticsearch,LewayneNaidoo/elasticsearch,geidies/elasticsearch,scottsom/elasticsearch,markwalkom/elasticsearch,liweinan0423/elasticsearch,a2lin/elasticsearch,fernandozhu/elasticsearch,mapr/elasticsearch,mjason3/elasticsearch,bawse/elasticsearch,Shepard1212/elasticsearch,sneivandt/elasticsearch,camilojd/elasticsearch,zkidkid/elasticsearch,nilabhsagar/elasticsearch,zkidkid/elasticsearch,mohit/elasticsearch,nknize/elasticsearch,camilojd/elasticsearch,fred84/elasticsearch,markwalkom/elasticsearch,coding0011/elasticsearch,sneivandt/elasticsearch,clintongormley/elasticsearch,kalimatas/elasticsearch,ESamir/elasticsearch,sreeramjayan/elasticsearch,nomoa/elasticsearch,trangvh/elasticsearch,LewayneNaidoo/elasticsearch,cwurm/elasticsearch,ZTE-PaaS/elasticsearch,clintongormley/elasticsearch,awislowski/elasticsearch,strapdata/elassandra5-rc,lks21c/elasticsearch,LewayneNaidoo/elasticsearch,gmarz/elasticsearch,nomoa/elasticsearch,elasticdog/elasticsearch,GlenRSmith/elasticsearch,gingerwizard/elasticsearch,geidies/elasticsearch,umeshdangat/elasticsearch,mohit/elasticsearch,nezirus/elasticsearch,C-Bish/elasticsearch,fred84/elasticsearch
/* * Licensed to Elasticsearch under one or more contributor * license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright * ownership. Elasticsearch 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.elasticsearch.common.util.concurrent; import org.elasticsearch.common.component.Lifecycle; import org.elasticsearch.common.logging.ESLogger; import java.util.Objects; /** * {@code AbstractLifecycleRunnable} is a service-lifecycle aware {@link AbstractRunnable}. * <p> * This simplifies the running and rescheduling of {@link Lifecycle}-based {@code Runnable}s. */ public abstract class AbstractLifecycleRunnable extends AbstractRunnable { /** * The monitored lifecycle for the associated service. */ private final Lifecycle lifecycle; /** * The service's logger (note: this is passed in!). */ private final ESLogger logger; /** * {@link AbstractLifecycleRunnable} must be aware of the actual {@code lifecycle} to react properly. * * @param lifecycle The lifecycle to react too * @param logger The logger to use when logging * @throws NullPointerException if any parameter is {@code null} */ public AbstractLifecycleRunnable(Lifecycle lifecycle, ESLogger logger) { this.lifecycle = Objects.requireNonNull(lifecycle, "lifecycle must not be null"); this.logger = Objects.requireNonNull(logger, "logger must not be null"); } /** * {@inheritDoc} * <p> * This invokes {@link #doRunInLifecycle()} <em>only</em> if the {@link #lifecycle} is not stopped or closed. Otherwise it exits * immediately. */ @Override protected final void doRun() throws Exception { // prevent execution if the service is stopped if (lifecycle.stoppedOrClosed()) { logger.trace("lifecycle is stopping. exiting"); return; } doRunInLifecycle(); } /** * Perform runnable logic, but only if the {@link #lifecycle} is <em>not</em> stopped or closed. * * @throws InterruptedException if the run method throws an {@link InterruptedException} */ protected abstract void doRunInLifecycle() throws Exception; /** * {@inheritDoc} * <p> * This overrides the default behavior of {@code onAfter} to add the caveat that it only runs if the {@link #lifecycle} is <em>not</em> * stopped or closed. * <p> * Note: this does not guarantee that it won't be stopped concurrently as it invokes {@link #onAfterInLifecycle()}, * but it's a solid attempt at preventing it. For those that use this for rescheduling purposes, the next invocation would be * effectively cancelled immediately if that's the case. * * @see #onAfterInLifecycle() */ @Override public final void onAfter() { if (lifecycle.stoppedOrClosed() == false) { onAfterInLifecycle(); } } /** * This method is invoked in the finally block of the run method, but it is only executed if the {@link #lifecycle} is <em>not</em> * stopped or closed. * <p> * This method is most useful for rescheduling the next iteration of the current runnable. */ protected void onAfterInLifecycle() { // nothing by default } }
core/src/main/java/org/elasticsearch/common/util/concurrent/AbstractLifecycleRunnable.java
/* * Licensed to Elasticsearch under one or more contributor * license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright * ownership. Elasticsearch 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.elasticsearch.common.util.concurrent; import org.elasticsearch.common.component.Lifecycle; import org.elasticsearch.common.logging.ESLogger; import java.util.Objects; /** * {@code AbstractLifecycleRunnable} is a service-lifecycle aware {@link AbstractRunnable}. * <p> * This simplifies the running and rescheduling of {@link Lifecycle}-based {@code Runnable}s. */ public abstract class AbstractLifecycleRunnable extends AbstractRunnable { /** * The monitored lifecycle for the associated service. */ private final Lifecycle lifecycle; /** * The service's logger (note: this is passed in!). */ private final ESLogger logger; /** * {@link AbstractLifecycleRunnable} must be aware of the actual {@code lifecycle} to react properly. * * @param lifecycle The lifecycle to react too * @param logger The logger to use when logging * @throws NullPointerException if any parameter is {@code null} */ public AbstractLifecycleRunnable(Lifecycle lifecycle, ESLogger logger) { Objects.requireNonNull(lifecycle, "lifecycle must not be null"); Objects.requireNonNull(logger, "logger must not be null"); this.lifecycle = lifecycle; this.logger = logger; } /** * {@inheritDoc} * <p> * This invokes {@link #doRunInLifecycle()} <em>only</em> if the {@link #lifecycle} is not stopped or closed. Otherwise it exits * immediately. */ @Override protected final void doRun() throws Exception { // prevent execution if the service is stopped if (lifecycle.stoppedOrClosed()) { logger.trace("service is stopping. exiting"); return; } doRunInLifecycle(); } /** * Perform runnable logic, but only if the {@link #lifecycle} is <em>not</em> stopped or closed. * * @throws InterruptedException if the run method throws an {@link InterruptedException} */ protected abstract void doRunInLifecycle() throws Exception; /** * {@inheritDoc} * <p> * This overrides the default behavior of {@code onAfter} to add the caveat that it only runs if the {@link #lifecycle} is <em>not</em> * stopped or closed. * <p> * Note: this does not guarantee that it won't be stopped concurrently as it invokes {@link #onAfterInLifecycle()}, * but it's a solid attempt at preventing it. For those that use this for rescheduling purposes, the next invocation would be * effectively cancelled immediately if that's the case. * * @see #onAfterInLifecycle() */ @Override public final void onAfter() { if (lifecycle.stoppedOrClosed() == false) { onAfterInLifecycle(); } } /** * This method is invoked in the finally block of the run method, but it is only executed if the {@link #lifecycle} is <em>not</em> * stopped or closed. * <p> * This method is most useful for rescheduling the next iteration of the current runnable. */ protected void onAfterInLifecycle() { // nothing by default } }
Adjusting based on comments.
core/src/main/java/org/elasticsearch/common/util/concurrent/AbstractLifecycleRunnable.java
Adjusting based on comments.
<ide><path>ore/src/main/java/org/elasticsearch/common/util/concurrent/AbstractLifecycleRunnable.java <ide> * @throws NullPointerException if any parameter is {@code null} <ide> */ <ide> public AbstractLifecycleRunnable(Lifecycle lifecycle, ESLogger logger) { <del> Objects.requireNonNull(lifecycle, "lifecycle must not be null"); <del> Objects.requireNonNull(logger, "logger must not be null"); <del> <del> this.lifecycle = lifecycle; <del> this.logger = logger; <add> this.lifecycle = Objects.requireNonNull(lifecycle, "lifecycle must not be null"); <add> this.logger = Objects.requireNonNull(logger, "logger must not be null"); <ide> } <ide> <ide> /** <ide> protected final void doRun() throws Exception { <ide> // prevent execution if the service is stopped <ide> if (lifecycle.stoppedOrClosed()) { <del> logger.trace("service is stopping. exiting"); <add> logger.trace("lifecycle is stopping. exiting"); <ide> return; <ide> } <ide>
Java
apache-2.0
cf50ce1c7a055b63dbca9cc39c4d4e560a3df165
0
idea4bsd/idea4bsd,xfournet/intellij-community,Distrotech/intellij-community,ol-loginov/intellij-community,supersven/intellij-community,wreckJ/intellij-community,xfournet/intellij-community,diorcety/intellij-community,apixandru/intellij-community,pwoodworth/intellij-community,jagguli/intellij-community,hurricup/intellij-community,dslomov/intellij-community,vladmm/intellij-community,supersven/intellij-community,michaelgallacher/intellij-community,adedayo/intellij-community,ThiagoGarciaAlves/intellij-community,akosyakov/intellij-community,robovm/robovm-studio,muntasirsyed/intellij-community,retomerz/intellij-community,amith01994/intellij-community,MER-GROUP/intellij-community,TangHao1987/intellij-community,blademainer/intellij-community,kool79/intellij-community,vvv1559/intellij-community,apixandru/intellij-community,supersven/intellij-community,youdonghai/intellij-community,robovm/robovm-studio,suncycheng/intellij-community,fengbaicanhe/intellij-community,youdonghai/intellij-community,tmpgit/intellij-community,youdonghai/intellij-community,allotria/intellij-community,orekyuu/intellij-community,izonder/intellij-community,suncycheng/intellij-community,robovm/robovm-studio,retomerz/intellij-community,samthor/intellij-community,dslomov/intellij-community,da1z/intellij-community,Distrotech/intellij-community,orekyuu/intellij-community,Lekanich/intellij-community,adedayo/intellij-community,izonder/intellij-community,tmpgit/intellij-community,Lekanich/intellij-community,slisson/intellij-community,michaelgallacher/intellij-community,fitermay/intellij-community,semonte/intellij-community,suncycheng/intellij-community,holmes/intellij-community,hurricup/intellij-community,ivan-fedorov/intellij-community,blademainer/intellij-community,lucafavatella/intellij-community,idea4bsd/idea4bsd,ivan-fedorov/intellij-community,muntasirsyed/intellij-community,vvv1559/intellij-community,allotria/intellij-community,jagguli/intellij-community,fitermay/intellij-community,salguarnieri/intellij-community,clumsy/intellij-community,Distrotech/intellij-community,orekyuu/intellij-community,akosyakov/intellij-community,dslomov/intellij-community,ol-loginov/intellij-community,adedayo/intellij-community,salguarnieri/intellij-community,allotria/intellij-community,orekyuu/intellij-community,holmes/intellij-community,kool79/intellij-community,youdonghai/intellij-community,ibinti/intellij-community,youdonghai/intellij-community,asedunov/intellij-community,hurricup/intellij-community,apixandru/intellij-community,retomerz/intellij-community,MER-GROUP/intellij-community,jagguli/intellij-community,xfournet/intellij-community,semonte/intellij-community,orekyuu/intellij-community,clumsy/intellij-community,holmes/intellij-community,da1z/intellij-community,lucafavatella/intellij-community,fengbaicanhe/intellij-community,xfournet/intellij-community,lucafavatella/intellij-community,ernestp/consulo,diorcety/intellij-community,retomerz/intellij-community,diorcety/intellij-community,signed/intellij-community,petteyg/intellij-community,TangHao1987/intellij-community,blademainer/intellij-community,suncycheng/intellij-community,kool79/intellij-community,clumsy/intellij-community,tmpgit/intellij-community,salguarnieri/intellij-community,ryano144/intellij-community,asedunov/intellij-community,pwoodworth/intellij-community,slisson/intellij-community,muntasirsyed/intellij-community,hurricup/intellij-community,nicolargo/intellij-community,ol-loginov/intellij-community,consulo/consulo,asedunov/intellij-community,lucafavatella/intellij-community,ahb0327/intellij-community,nicolargo/intellij-community,kool79/intellij-community,MichaelNedzelsky/intellij-community,nicolargo/intellij-community,vladmm/intellij-community,alphafoobar/intellij-community,pwoodworth/intellij-community,SerCeMan/intellij-community,ibinti/intellij-community,adedayo/intellij-community,da1z/intellij-community,diorcety/intellij-community,MichaelNedzelsky/intellij-community,alphafoobar/intellij-community,pwoodworth/intellij-community,ryano144/intellij-community,petteyg/intellij-community,lucafavatella/intellij-community,Lekanich/intellij-community,dslomov/intellij-community,robovm/robovm-studio,holmes/intellij-community,fitermay/intellij-community,pwoodworth/intellij-community,SerCeMan/intellij-community,muntasirsyed/intellij-community,ibinti/intellij-community,alphafoobar/intellij-community,alphafoobar/intellij-community,ThiagoGarciaAlves/intellij-community,diorcety/intellij-community,amith01994/intellij-community,izonder/intellij-community,caot/intellij-community,blademainer/intellij-community,caot/intellij-community,allotria/intellij-community,TangHao1987/intellij-community,ivan-fedorov/intellij-community,slisson/intellij-community,vladmm/intellij-community,ahb0327/intellij-community,orekyuu/intellij-community,lucafavatella/intellij-community,SerCeMan/intellij-community,allotria/intellij-community,apixandru/intellij-community,diorcety/intellij-community,vvv1559/intellij-community,vvv1559/intellij-community,ivan-fedorov/intellij-community,hurricup/intellij-community,allotria/intellij-community,da1z/intellij-community,ThiagoGarciaAlves/intellij-community,clumsy/intellij-community,youdonghai/intellij-community,signed/intellij-community,salguarnieri/intellij-community,petteyg/intellij-community,retomerz/intellij-community,semonte/intellij-community,izonder/intellij-community,TangHao1987/intellij-community,diorcety/intellij-community,diorcety/intellij-community,youdonghai/intellij-community,alphafoobar/intellij-community,ivan-fedorov/intellij-community,akosyakov/intellij-community,Distrotech/intellij-community,Lekanich/intellij-community,consulo/consulo,MichaelNedzelsky/intellij-community,Lekanich/intellij-community,michaelgallacher/intellij-community,akosyakov/intellij-community,MER-GROUP/intellij-community,gnuhub/intellij-community,samthor/intellij-community,MER-GROUP/intellij-community,TangHao1987/intellij-community,adedayo/intellij-community,kdwink/intellij-community,clumsy/intellij-community,allotria/intellij-community,fnouama/intellij-community,dslomov/intellij-community,holmes/intellij-community,amith01994/intellij-community,FHannes/intellij-community,gnuhub/intellij-community,asedunov/intellij-community,ahb0327/intellij-community,michaelgallacher/intellij-community,ftomassetti/intellij-community,clumsy/intellij-community,gnuhub/intellij-community,alphafoobar/intellij-community,FHannes/intellij-community,muntasirsyed/intellij-community,da1z/intellij-community,petteyg/intellij-community,MichaelNedzelsky/intellij-community,suncycheng/intellij-community,adedayo/intellij-community,kdwink/intellij-community,robovm/robovm-studio,jagguli/intellij-community,alphafoobar/intellij-community,kdwink/intellij-community,ftomassetti/intellij-community,mglukhikh/intellij-community,ryano144/intellij-community,semonte/intellij-community,hurricup/intellij-community,apixandru/intellij-community,Lekanich/intellij-community,samthor/intellij-community,signed/intellij-community,semonte/intellij-community,vladmm/intellij-community,ryano144/intellij-community,fnouama/intellij-community,FHannes/intellij-community,ernestp/consulo,adedayo/intellij-community,ernestp/consulo,MichaelNedzelsky/intellij-community,TangHao1987/intellij-community,supersven/intellij-community,vvv1559/intellij-community,wreckJ/intellij-community,gnuhub/intellij-community,suncycheng/intellij-community,vladmm/intellij-community,fnouama/intellij-community,consulo/consulo,akosyakov/intellij-community,xfournet/intellij-community,youdonghai/intellij-community,ahb0327/intellij-community,slisson/intellij-community,tmpgit/intellij-community,kool79/intellij-community,idea4bsd/idea4bsd,supersven/intellij-community,Distrotech/intellij-community,Distrotech/intellij-community,fitermay/intellij-community,izonder/intellij-community,fengbaicanhe/intellij-community,lucafavatella/intellij-community,asedunov/intellij-community,samthor/intellij-community,samthor/intellij-community,salguarnieri/intellij-community,ibinti/intellij-community,vladmm/intellij-community,slisson/intellij-community,semonte/intellij-community,MichaelNedzelsky/intellij-community,wreckJ/intellij-community,retomerz/intellij-community,fitermay/intellij-community,SerCeMan/intellij-community,slisson/intellij-community,wreckJ/intellij-community,alphafoobar/intellij-community,gnuhub/intellij-community,xfournet/intellij-community,izonder/intellij-community,hurricup/intellij-community,signed/intellij-community,retomerz/intellij-community,orekyuu/intellij-community,kool79/intellij-community,muntasirsyed/intellij-community,ftomassetti/intellij-community,semonte/intellij-community,samthor/intellij-community,kdwink/intellij-community,wreckJ/intellij-community,amith01994/intellij-community,SerCeMan/intellij-community,ivan-fedorov/intellij-community,da1z/intellij-community,fengbaicanhe/intellij-community,ahb0327/intellij-community,SerCeMan/intellij-community,ahb0327/intellij-community,ol-loginov/intellij-community,Lekanich/intellij-community,asedunov/intellij-community,alphafoobar/intellij-community,michaelgallacher/intellij-community,ivan-fedorov/intellij-community,akosyakov/intellij-community,youdonghai/intellij-community,fitermay/intellij-community,TangHao1987/intellij-community,kdwink/intellij-community,SerCeMan/intellij-community,gnuhub/intellij-community,salguarnieri/intellij-community,ibinti/intellij-community,idea4bsd/idea4bsd,alphafoobar/intellij-community,izonder/intellij-community,gnuhub/intellij-community,slisson/intellij-community,jagguli/intellij-community,apixandru/intellij-community,holmes/intellij-community,amith01994/intellij-community,dslomov/intellij-community,retomerz/intellij-community,kdwink/intellij-community,kdwink/intellij-community,caot/intellij-community,nicolargo/intellij-community,da1z/intellij-community,orekyuu/intellij-community,da1z/intellij-community,fengbaicanhe/intellij-community,signed/intellij-community,ryano144/intellij-community,izonder/intellij-community,holmes/intellij-community,blademainer/intellij-community,dslomov/intellij-community,SerCeMan/intellij-community,ahb0327/intellij-community,retomerz/intellij-community,ftomassetti/intellij-community,muntasirsyed/intellij-community,consulo/consulo,MichaelNedzelsky/intellij-community,ibinti/intellij-community,caot/intellij-community,amith01994/intellij-community,ThiagoGarciaAlves/intellij-community,ernestp/consulo,alphafoobar/intellij-community,consulo/consulo,semonte/intellij-community,wreckJ/intellij-community,caot/intellij-community,supersven/intellij-community,caot/intellij-community,FHannes/intellij-community,akosyakov/intellij-community,idea4bsd/idea4bsd,holmes/intellij-community,FHannes/intellij-community,supersven/intellij-community,ibinti/intellij-community,FHannes/intellij-community,kool79/intellij-community,robovm/robovm-studio,vladmm/intellij-community,signed/intellij-community,petteyg/intellij-community,tmpgit/intellij-community,FHannes/intellij-community,fengbaicanhe/intellij-community,vvv1559/intellij-community,ibinti/intellij-community,vladmm/intellij-community,mglukhikh/intellij-community,Lekanich/intellij-community,adedayo/intellij-community,petteyg/intellij-community,tmpgit/intellij-community,ahb0327/intellij-community,lucafavatella/intellij-community,diorcety/intellij-community,dslomov/intellij-community,blademainer/intellij-community,fengbaicanhe/intellij-community,hurricup/intellij-community,vladmm/intellij-community,asedunov/intellij-community,allotria/intellij-community,ryano144/intellij-community,michaelgallacher/intellij-community,ibinti/intellij-community,ftomassetti/intellij-community,gnuhub/intellij-community,petteyg/intellij-community,MichaelNedzelsky/intellij-community,akosyakov/intellij-community,amith01994/intellij-community,clumsy/intellij-community,FHannes/intellij-community,MER-GROUP/intellij-community,signed/intellij-community,salguarnieri/intellij-community,ftomassetti/intellij-community,mglukhikh/intellij-community,MichaelNedzelsky/intellij-community,nicolargo/intellij-community,FHannes/intellij-community,robovm/robovm-studio,petteyg/intellij-community,pwoodworth/intellij-community,pwoodworth/intellij-community,amith01994/intellij-community,caot/intellij-community,fnouama/intellij-community,nicolargo/intellij-community,akosyakov/intellij-community,slisson/intellij-community,fitermay/intellij-community,ol-loginov/intellij-community,samthor/intellij-community,apixandru/intellij-community,da1z/intellij-community,allotria/intellij-community,izonder/intellij-community,salguarnieri/intellij-community,xfournet/intellij-community,hurricup/intellij-community,ol-loginov/intellij-community,dslomov/intellij-community,robovm/robovm-studio,Distrotech/intellij-community,mglukhikh/intellij-community,robovm/robovm-studio,kdwink/intellij-community,petteyg/intellij-community,slisson/intellij-community,holmes/intellij-community,vvv1559/intellij-community,retomerz/intellij-community,ol-loginov/intellij-community,gnuhub/intellij-community,vvv1559/intellij-community,caot/intellij-community,pwoodworth/intellij-community,caot/intellij-community,TangHao1987/intellij-community,asedunov/intellij-community,mglukhikh/intellij-community,xfournet/intellij-community,clumsy/intellij-community,kool79/intellij-community,apixandru/intellij-community,xfournet/intellij-community,ftomassetti/intellij-community,hurricup/intellij-community,robovm/robovm-studio,blademainer/intellij-community,signed/intellij-community,idea4bsd/idea4bsd,alphafoobar/intellij-community,muntasirsyed/intellij-community,ryano144/intellij-community,ol-loginov/intellij-community,ryano144/intellij-community,vvv1559/intellij-community,TangHao1987/intellij-community,idea4bsd/idea4bsd,vladmm/intellij-community,Distrotech/intellij-community,mglukhikh/intellij-community,diorcety/intellij-community,fnouama/intellij-community,muntasirsyed/intellij-community,suncycheng/intellij-community,fnouama/intellij-community,xfournet/intellij-community,ahb0327/intellij-community,idea4bsd/idea4bsd,ernestp/consulo,SerCeMan/intellij-community,holmes/intellij-community,gnuhub/intellij-community,ahb0327/intellij-community,allotria/intellij-community,blademainer/intellij-community,kdwink/intellij-community,Lekanich/intellij-community,tmpgit/intellij-community,blademainer/intellij-community,nicolargo/intellij-community,xfournet/intellij-community,clumsy/intellij-community,dslomov/intellij-community,da1z/intellij-community,samthor/intellij-community,signed/intellij-community,samthor/intellij-community,youdonghai/intellij-community,FHannes/intellij-community,wreckJ/intellij-community,pwoodworth/intellij-community,izonder/intellij-community,lucafavatella/intellij-community,SerCeMan/intellij-community,michaelgallacher/intellij-community,supersven/intellij-community,MichaelNedzelsky/intellij-community,kool79/intellij-community,supersven/intellij-community,retomerz/intellij-community,fnouama/intellij-community,fengbaicanhe/intellij-community,fengbaicanhe/intellij-community,kdwink/intellij-community,ol-loginov/intellij-community,orekyuu/intellij-community,youdonghai/intellij-community,ivan-fedorov/intellij-community,vladmm/intellij-community,Distrotech/intellij-community,diorcety/intellij-community,asedunov/intellij-community,robovm/robovm-studio,idea4bsd/idea4bsd,robovm/robovm-studio,da1z/intellij-community,apixandru/intellij-community,ftomassetti/intellij-community,fnouama/intellij-community,MER-GROUP/intellij-community,tmpgit/intellij-community,signed/intellij-community,signed/intellij-community,ryano144/intellij-community,petteyg/intellij-community,lucafavatella/intellij-community,ivan-fedorov/intellij-community,caot/intellij-community,ibinti/intellij-community,kool79/intellij-community,salguarnieri/intellij-community,muntasirsyed/intellij-community,da1z/intellij-community,ThiagoGarciaAlves/intellij-community,izonder/intellij-community,ryano144/intellij-community,wreckJ/intellij-community,idea4bsd/idea4bsd,tmpgit/intellij-community,amith01994/intellij-community,ftomassetti/intellij-community,adedayo/intellij-community,jagguli/intellij-community,nicolargo/intellij-community,supersven/intellij-community,retomerz/intellij-community,michaelgallacher/intellij-community,blademainer/intellij-community,ivan-fedorov/intellij-community,consulo/consulo,petteyg/intellij-community,pwoodworth/intellij-community,jagguli/intellij-community,MichaelNedzelsky/intellij-community,ol-loginov/intellij-community,semonte/intellij-community,samthor/intellij-community,adedayo/intellij-community,kdwink/intellij-community,fitermay/intellij-community,michaelgallacher/intellij-community,holmes/intellij-community,semonte/intellij-community,salguarnieri/intellij-community,ibinti/intellij-community,michaelgallacher/intellij-community,muntasirsyed/intellij-community,jagguli/intellij-community,ibinti/intellij-community,tmpgit/intellij-community,youdonghai/intellij-community,FHannes/intellij-community,ibinti/intellij-community,ernestp/consulo,MER-GROUP/intellij-community,SerCeMan/intellij-community,dslomov/intellij-community,nicolargo/intellij-community,mglukhikh/intellij-community,jagguli/intellij-community,Lekanich/intellij-community,ThiagoGarciaAlves/intellij-community,fitermay/intellij-community,vvv1559/intellij-community,jagguli/intellij-community,salguarnieri/intellij-community,apixandru/intellij-community,kool79/intellij-community,idea4bsd/idea4bsd,wreckJ/intellij-community,fitermay/intellij-community,tmpgit/intellij-community,Lekanich/intellij-community,suncycheng/intellij-community,fengbaicanhe/intellij-community,FHannes/intellij-community,ryano144/intellij-community,apixandru/intellij-community,mglukhikh/intellij-community,TangHao1987/intellij-community,fnouama/intellij-community,semonte/intellij-community,diorcety/intellij-community,wreckJ/intellij-community,orekyuu/intellij-community,slisson/intellij-community,MER-GROUP/intellij-community,ThiagoGarciaAlves/intellij-community,fnouama/intellij-community,ftomassetti/intellij-community,allotria/intellij-community,fnouama/intellij-community,kdwink/intellij-community,xfournet/intellij-community,ivan-fedorov/intellij-community,suncycheng/intellij-community,apixandru/intellij-community,SerCeMan/intellij-community,amith01994/intellij-community,jagguli/intellij-community,mglukhikh/intellij-community,vvv1559/intellij-community,mglukhikh/intellij-community,hurricup/intellij-community,asedunov/intellij-community,orekyuu/intellij-community,clumsy/intellij-community,amith01994/intellij-community,pwoodworth/intellij-community,ThiagoGarciaAlves/intellij-community,ftomassetti/intellij-community,MER-GROUP/intellij-community,asedunov/intellij-community,dslomov/intellij-community,jagguli/intellij-community,supersven/intellij-community,pwoodworth/intellij-community,caot/intellij-community,amith01994/intellij-community,ThiagoGarciaAlves/intellij-community,idea4bsd/idea4bsd,MER-GROUP/intellij-community,xfournet/intellij-community,izonder/intellij-community,petteyg/intellij-community,orekyuu/intellij-community,Distrotech/intellij-community,signed/intellij-community,suncycheng/intellij-community,slisson/intellij-community,suncycheng/intellij-community,MER-GROUP/intellij-community,michaelgallacher/intellij-community,vvv1559/intellij-community,MER-GROUP/intellij-community,slisson/intellij-community,wreckJ/intellij-community,FHannes/intellij-community,kool79/intellij-community,hurricup/intellij-community,lucafavatella/intellij-community,fitermay/intellij-community,vladmm/intellij-community,mglukhikh/intellij-community,fnouama/intellij-community,salguarnieri/intellij-community,asedunov/intellij-community,ThiagoGarciaAlves/intellij-community,apixandru/intellij-community,mglukhikh/intellij-community,fengbaicanhe/intellij-community,ahb0327/intellij-community,holmes/intellij-community,ryano144/intellij-community,clumsy/intellij-community,ftomassetti/intellij-community,apixandru/intellij-community,adedayo/intellij-community,ahb0327/intellij-community,ThiagoGarciaAlves/intellij-community,fitermay/intellij-community,gnuhub/intellij-community,nicolargo/intellij-community,blademainer/intellij-community,gnuhub/intellij-community,Distrotech/intellij-community,ol-loginov/intellij-community,asedunov/intellij-community,blademainer/intellij-community,MichaelNedzelsky/intellij-community,hurricup/intellij-community,ivan-fedorov/intellij-community,Distrotech/intellij-community,akosyakov/intellij-community,muntasirsyed/intellij-community,fitermay/intellij-community,fengbaicanhe/intellij-community,signed/intellij-community,akosyakov/intellij-community,ol-loginov/intellij-community,clumsy/intellij-community,Lekanich/intellij-community,samthor/intellij-community,akosyakov/intellij-community,wreckJ/intellij-community,semonte/intellij-community,allotria/intellij-community,vvv1559/intellij-community,adedayo/intellij-community,tmpgit/intellij-community,samthor/intellij-community,michaelgallacher/intellij-community,lucafavatella/intellij-community,idea4bsd/idea4bsd,ThiagoGarciaAlves/intellij-community,TangHao1987/intellij-community,TangHao1987/intellij-community,lucafavatella/intellij-community,caot/intellij-community,nicolargo/intellij-community,suncycheng/intellij-community,mglukhikh/intellij-community,retomerz/intellij-community,allotria/intellij-community,nicolargo/intellij-community,youdonghai/intellij-community,semonte/intellij-community,supersven/intellij-community,da1z/intellij-community
/* * Copyright 2000-2011 JetBrains s.r.o. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.intellij.refactoring.introduceVariable; import com.intellij.codeInsight.intention.impl.TypeExpression; import com.intellij.codeInsight.lookup.LookupElement; import com.intellij.codeInsight.lookup.LookupElementBuilder; import com.intellij.codeInsight.lookup.LookupManager; import com.intellij.codeInsight.lookup.impl.LookupImpl; import com.intellij.codeInsight.template.*; import com.intellij.codeInsight.template.impl.TemplateManagerImpl; import com.intellij.codeInsight.template.impl.TemplateState; import com.intellij.ide.IdeTooltipManager; import com.intellij.openapi.actionSystem.Shortcut; import com.intellij.openapi.application.ApplicationManager; import com.intellij.openapi.command.WriteCommandAction; import com.intellij.openapi.editor.*; import com.intellij.openapi.extensions.Extensions; import com.intellij.openapi.keymap.Keymap; import com.intellij.openapi.keymap.KeymapManager; import com.intellij.openapi.project.Project; import com.intellij.openapi.ui.popup.Balloon; import com.intellij.openapi.ui.popup.BalloonBuilder; import com.intellij.openapi.ui.popup.JBPopupFactory; import com.intellij.openapi.util.Comparing; import com.intellij.openapi.util.TextRange; import com.intellij.psi.*; import com.intellij.psi.codeStyle.CodeStyleManager; import com.intellij.psi.codeStyle.JavaCodeStyleManager; import com.intellij.psi.scope.processor.VariablesProcessor; import com.intellij.psi.util.PsiTreeUtil; import com.intellij.psi.util.TypeConversionUtil; import com.intellij.refactoring.JavaRefactoringSettings; import com.intellij.refactoring.rename.NameSuggestionProvider; import com.intellij.refactoring.rename.inplace.VariableInplaceRenamer; import com.intellij.refactoring.ui.TypeSelectorManagerImpl; import com.intellij.ui.NonFocusableCheckBox; import com.intellij.ui.TitlePanel; import com.intellij.ui.awt.RelativePoint; import org.jetbrains.annotations.Nullable; import javax.swing.*; import java.awt.*; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.util.Iterator; import java.util.LinkedHashSet; import java.util.List; /** * User: anna * Date: 12/8/10 */ public class VariableInplaceIntroducer extends VariableInplaceRenamer { private final PsiVariable myElementToRename; private final Editor myEditor; private final TypeExpression myExpression; private final Project myProject; private final SmartPsiElementPointer<PsiDeclarationStatement> myPointer; private final RangeMarker myExprMarker; private final List<RangeMarker> myOccurrenceMarkers; private final SmartTypePointer myDefaultType; protected JCheckBox myCanBeFinalCb; private Balloon myBalloon; public VariableInplaceIntroducer(final Project project, final TypeExpression expression, final Editor editor, final PsiVariable elementToRename, final boolean cantChangeFinalModifier, final boolean hasTypeSuggestion, final RangeMarker exprMarker, final List<RangeMarker> occurrenceMarkers, final String commandName) { super(elementToRename, editor); myProject = project; myEditor = editor; myElementToRename = elementToRename; myExpression = expression; myExprMarker = exprMarker; myOccurrenceMarkers = occurrenceMarkers; final PsiType defaultType = elementToRename.getType(); myDefaultType = SmartTypePointerManager.getInstance(project).createSmartTypePointer(defaultType); final PsiDeclarationStatement declarationStatement = PsiTreeUtil.getParentOfType(elementToRename, PsiDeclarationStatement.class); myPointer = declarationStatement != null ? SmartPointerManager.getInstance(project).createSmartPsiElementPointer(declarationStatement) : null; editor.putUserData(ReassignVariableUtil.DECLARATION_KEY, myPointer); editor.putUserData(ReassignVariableUtil.OCCURRENCES_KEY, occurrenceMarkers.toArray(new RangeMarker[occurrenceMarkers.size()])); setAdvertisementText(getAdvertisementText(declarationStatement, defaultType, hasTypeSuggestion)); if (!cantChangeFinalModifier) { myCanBeFinalCb = new NonFocusableCheckBox("Declare final"); myCanBeFinalCb.setSelected(createFinals()); myCanBeFinalCb.setMnemonic('f'); myCanBeFinalCb.addActionListener(new FinalListener(project, commandName)); } } @Override protected void addAdditionalVariables(TemplateBuilderImpl builder) { final PsiTypeElement typeElement = myElementToRename.getTypeElement(); builder.replaceElement(typeElement, "Variable_Type", createExpression(myExpression, typeElement.getText()), true, true); } @Override protected LookupElement[] createLookupItems(LookupElement[] lookupItems, String name) { TemplateState templateState = TemplateManagerImpl.getTemplateState(myEditor); final PsiVariable psiVariable = getVariable(); if (psiVariable != null) { final TextResult insertedValue = templateState != null ? templateState.getVariableValue(PRIMARY_VARIABLE_NAME) : null; if (insertedValue != null) { final String text = insertedValue.getText(); if (!text.isEmpty() && !Comparing.strEqual(text, name)) { final LinkedHashSet<String> names = new LinkedHashSet<String>(); names.add(text); for (NameSuggestionProvider provider : Extensions.getExtensions(NameSuggestionProvider.EP_NAME)) { provider.getSuggestedNames(psiVariable, psiVariable, names); } final LookupElement[] items = new LookupElement[names.size()]; final Iterator<String> iterator = names.iterator(); for (int i = 0; i < items.length; i++) { items[i] = LookupElementBuilder.create(iterator.next()); } return items; } } } return super.createLookupItems(lookupItems, name); } @Nullable protected PsiVariable getVariable() { final PsiDeclarationStatement declarationStatement = myPointer.getElement(); return declarationStatement != null ? (PsiVariable)declarationStatement.getDeclaredElements()[0] : null; } @Override protected TextRange preserveSelectedRange(SelectionModel selectionModel) { return null; } @Override public boolean performInplaceRename(boolean processTextOccurrences, LinkedHashSet<String> nameSuggestions) { final boolean result = super.performInplaceRename(processTextOccurrences, nameSuggestions); showBalloon(); return result; } public RangeMarker getExprMarker() { return myExprMarker; } @Override protected boolean performAutomaticRename() { return false; } @Override protected void moveOffsetAfter(boolean success) { try { if (success) { final Document document = myEditor.getDocument(); final @Nullable PsiVariable psiVariable = getVariable(); if (psiVariable == null) { return; } LOG.assertTrue(psiVariable.isValid()); saveSettings(psiVariable); adjustLine(psiVariable, document); int startOffset = myExprMarker != null && myExprMarker.isValid() ? myExprMarker.getStartOffset() : psiVariable.getTextOffset(); final PsiFile file = psiVariable.getContainingFile(); final PsiReference referenceAt = file.findReferenceAt(startOffset); if (referenceAt != null && referenceAt.resolve() instanceof PsiVariable) { startOffset = referenceAt.getElement().getTextRange().getEndOffset(); } else { final PsiDeclarationStatement declarationStatement = PsiTreeUtil.getParentOfType(psiVariable, PsiDeclarationStatement.class); if (declarationStatement != null) { startOffset = declarationStatement.getTextRange().getEndOffset(); } } myEditor.getCaretModel().moveToOffset(startOffset); myEditor.getScrollingModel().scrollToCaret(ScrollType.MAKE_VISIBLE); if (psiVariable.getInitializer() != null) { ApplicationManager.getApplication().runWriteAction(new Runnable() { public void run() { appendTypeCasts(myOccurrenceMarkers, file, myProject, psiVariable); } }); } } else { if (myExprMarker != null) { myEditor.getCaretModel().moveToOffset(myExprMarker.getStartOffset()); myEditor.getScrollingModel().scrollToCaret(ScrollType.MAKE_VISIBLE); } } } finally { myEditor.putUserData(ReassignVariableUtil.DECLARATION_KEY, null); for (RangeMarker occurrenceMarker : myOccurrenceMarkers) { occurrenceMarker.dispose(); } myEditor.putUserData(ReassignVariableUtil.OCCURRENCES_KEY, null); if (myExprMarker != null) myExprMarker.dispose(); } } @Override public void finish() { super.finish(); if (myBalloon != null) myBalloon.hide(); } protected void saveSettings(PsiVariable psiVariable) { JavaRefactoringSettings.getInstance().INTRODUCE_LOCAL_CREATE_FINALS = psiVariable.hasModifierProperty(PsiModifier.FINAL); TypeSelectorManagerImpl.typeSelected(psiVariable.getType(), myDefaultType.getType()); } @Nullable protected JComponent getComponent() { if (myCanBeFinalCb == null) return null; final JPanel panel = new JPanel(new GridBagLayout()); panel.setBorder(null); final TitlePanel titlePanel = new TitlePanel(); titlePanel.setBorder(null); titlePanel.setText(IntroduceVariableBase.REFACTORING_NAME); panel.add(titlePanel, new GridBagConstraints(0, 0, 1, 1, 1, 0, GridBagConstraints.NORTHWEST, GridBagConstraints.HORIZONTAL, new Insets(0, 0, 0, 0), 0, 0)); if (myCanBeFinalCb != null) { panel.add(myCanBeFinalCb, new GridBagConstraints(0, 1, 1, 1, 1, 0, GridBagConstraints.NORTHWEST, GridBagConstraints.HORIZONTAL, new Insets(5, 5, 5, 5), 0, 0)); } panel.add(Box.createVerticalBox(), new GridBagConstraints(0, 2, 1, 1, 1, 1, GridBagConstraints.NORTHWEST, GridBagConstraints.BOTH, new Insets(0,0,0,0), 0,0)); return panel; } private static void appendTypeCasts(List<RangeMarker> occurrenceMarkers, PsiFile file, Project project, @Nullable PsiVariable psiVariable) { for (RangeMarker occurrenceMarker : occurrenceMarkers) { final PsiElement refVariableElement = file.findElementAt(occurrenceMarker.getStartOffset()); final PsiReferenceExpression referenceExpression = PsiTreeUtil.getParentOfType(refVariableElement, PsiReferenceExpression.class); if (referenceExpression != null) { final PsiElement parent = referenceExpression.getParent(); if (parent instanceof PsiVariable) { createCastInVariableDeclaration(project, (PsiVariable)parent); } else if (parent instanceof PsiReferenceExpression && psiVariable != null) { final PsiExpression initializer = psiVariable.getInitializer(); LOG.assertTrue(initializer != null); final PsiType type = initializer.getType(); if (((PsiReferenceExpression)parent).resolve() == null && type != null) { final PsiElementFactory elementFactory = JavaPsiFacade.getElementFactory(project); final PsiExpression castedExpr = elementFactory.createExpressionFromText("((" + type.getCanonicalText() + ")" + referenceExpression.getText() + ")", parent); JavaCodeStyleManager.getInstance(project).shortenClassReferences(referenceExpression.replace(castedExpr)); } } } } if (psiVariable != null && psiVariable.isValid()) { createCastInVariableDeclaration(project, psiVariable); } } private static void createCastInVariableDeclaration(Project project, PsiVariable psiVariable) { final PsiExpression initializer = psiVariable.getInitializer(); LOG.assertTrue(initializer != null); final PsiType type = psiVariable.getType(); final PsiType initializerType = initializer.getType(); if (initializerType != null && !TypeConversionUtil.isAssignable(type, initializerType)) { final PsiElementFactory elementFactory = JavaPsiFacade.getElementFactory(project); final PsiExpression castExpr = elementFactory.createExpressionFromText("(" + psiVariable.getType().getCanonicalText() + ")" + initializer.getText(), psiVariable); JavaCodeStyleManager.getInstance(project).shortenClassReferences(initializer.replace(castExpr)); } } @Nullable private static String getAdvertisementText(final PsiDeclarationStatement declaration, final PsiType type, final boolean hasTypeSuggestion) { final VariablesProcessor processor = ReassignVariableUtil.findVariablesOfType(declaration, type); final Keymap keymap = KeymapManager.getInstance().getActiveKeymap(); if (processor.size() > 0) { final Shortcut[] shortcuts = keymap.getShortcuts("IntroduceVariable"); if (shortcuts.length > 0) { return "Press " + shortcuts[0] + " to reassign existing variable"; } } if (hasTypeSuggestion) { final Shortcut[] shortcuts = keymap.getShortcuts("PreviousTemplateVariable"); if (shortcuts.length > 0) { return "Press " + shortcuts[0] + " to change type"; } } return null; } private static Expression createExpression(final TypeExpression expression, final String defaultType) { return new Expression() { @Override public Result calculateResult(ExpressionContext context) { return new TextResult(defaultType); } @Override public Result calculateQuickResult(ExpressionContext context) { return new TextResult(defaultType); } @Override public LookupElement[] calculateLookupItems(ExpressionContext context) { return expression.calculateLookupItems(context); } @Override public String getAdvertisingText() { return null; } }; } protected boolean createFinals() { return IntroduceVariableBase.createFinals(myProject); } public static void adjustLine(final PsiVariable psiVariable, final Document document) { final int modifierListOffset = psiVariable.getTextRange().getStartOffset(); final int varLineNumber = document.getLineNumber(modifierListOffset); ApplicationManager.getApplication().runWriteAction(new Runnable() { //adjust line indent if final was inserted and then deleted public void run() { PsiDocumentManager.getInstance(psiVariable.getProject()).doPostponedOperationsAndUnblockDocument(document); CodeStyleManager.getInstance(psiVariable.getProject()).adjustLineIndent(document, document.getLineStartOffset(varLineNumber)); } }); } private void showBalloon() { final JComponent component = getComponent(); if (component == null) return; if (ApplicationManager.getApplication().isHeadlessEnvironment()) return; final BalloonBuilder balloonBuilder = JBPopupFactory.getInstance().createBalloonBuilder(component); balloonBuilder.setFadeoutTime(0) .setFillColor(IdeTooltipManager.GRAPHITE_COLOR.brighter().brighter()) .setAnimationCycle(0) .setHideOnClickOutside(false) .setHideOnKeyOutside(false) .setHideOnAction(false) .setCloseButtonEnabled(true); final RelativePoint target = JBPopupFactory.getInstance().guessBestPopupLocation(myEditor); final Point screenPoint = target.getScreenPoint(); myBalloon = balloonBuilder.createBalloon(); int y = screenPoint.y; if (target.getPoint().getY() > myEditor.getLineHeight() + myBalloon.getPreferredSize().getHeight()) { y -= myEditor.getLineHeight(); } myBalloon.show(new RelativePoint(new Point(screenPoint.x, y)), Balloon.Position.above); } public class FinalListener implements ActionListener { private final Project myProject; private final String myCommandName; public FinalListener(Project project, String commandName) { myProject = project; myCommandName = commandName; } @Override public void actionPerformed(ActionEvent e) { perform(myCanBeFinalCb.isSelected()); } public void perform(final boolean generateFinal) { perform(generateFinal, PsiModifier.FINAL); } public void perform(final boolean generateFinal, final String modifier) { new WriteCommandAction(myProject, myCommandName, myCommandName){ @Override protected void run(com.intellij.openapi.application.Result result) throws Throwable { final Document document = myEditor.getDocument(); PsiDocumentManager.getInstance(getProject()).commitDocument(document); final PsiVariable variable = getVariable(); LOG.assertTrue(variable != null); final PsiModifierList modifierList = variable.getModifierList(); LOG.assertTrue(modifierList != null); final int textOffset = modifierList.getTextOffset(); final Runnable runnable = new Runnable() { public void run() { if (generateFinal) { final PsiTypeElement typeElement = variable.getTypeElement(); final int typeOffset = typeElement != null ? typeElement.getTextOffset() : textOffset; document.insertString(typeOffset, modifier + " "); } else { final int idx = modifierList.getText().indexOf(modifier); document.deleteString(textOffset + idx, textOffset + idx + modifier.length() + 1); } } }; final LookupImpl lookup = (LookupImpl)LookupManager.getActiveLookup(myEditor); if (lookup != null) { lookup.performGuardedChange(runnable); } else { runnable.run(); } } }.execute(); } } }
java/java-impl/src/com/intellij/refactoring/introduceVariable/VariableInplaceIntroducer.java
/* * Copyright 2000-2011 JetBrains s.r.o. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.intellij.refactoring.introduceVariable; import com.intellij.codeInsight.intention.impl.TypeExpression; import com.intellij.codeInsight.lookup.LookupElement; import com.intellij.codeInsight.lookup.LookupElementBuilder; import com.intellij.codeInsight.lookup.LookupManager; import com.intellij.codeInsight.lookup.impl.LookupImpl; import com.intellij.codeInsight.template.*; import com.intellij.codeInsight.template.impl.TemplateManagerImpl; import com.intellij.codeInsight.template.impl.TemplateState; import com.intellij.ide.IdeTooltipManager; import com.intellij.openapi.actionSystem.Shortcut; import com.intellij.openapi.application.ApplicationManager; import com.intellij.openapi.command.WriteCommandAction; import com.intellij.openapi.editor.*; import com.intellij.openapi.extensions.Extensions; import com.intellij.openapi.keymap.Keymap; import com.intellij.openapi.keymap.KeymapManager; import com.intellij.openapi.project.Project; import com.intellij.openapi.ui.popup.Balloon; import com.intellij.openapi.ui.popup.BalloonBuilder; import com.intellij.openapi.ui.popup.JBPopupFactory; import com.intellij.openapi.util.Comparing; import com.intellij.openapi.util.TextRange; import com.intellij.psi.*; import com.intellij.psi.codeStyle.CodeStyleManager; import com.intellij.psi.codeStyle.JavaCodeStyleManager; import com.intellij.psi.scope.processor.VariablesProcessor; import com.intellij.psi.util.PsiTreeUtil; import com.intellij.psi.util.TypeConversionUtil; import com.intellij.refactoring.JavaRefactoringSettings; import com.intellij.refactoring.rename.NameSuggestionProvider; import com.intellij.refactoring.rename.inplace.VariableInplaceRenamer; import com.intellij.refactoring.ui.TypeSelectorManagerImpl; import com.intellij.ui.NonFocusableCheckBox; import com.intellij.ui.TitlePanel; import com.intellij.ui.awt.RelativePoint; import org.jetbrains.annotations.Nullable; import javax.swing.*; import java.awt.*; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.util.Iterator; import java.util.LinkedHashSet; import java.util.List; /** * User: anna * Date: 12/8/10 */ public class VariableInplaceIntroducer extends VariableInplaceRenamer { private final PsiVariable myElementToRename; private final Editor myEditor; private final TypeExpression myExpression; private final Project myProject; private final SmartPsiElementPointer<PsiDeclarationStatement> myPointer; private final RangeMarker myExprMarker; private final List<RangeMarker> myOccurrenceMarkers; private final SmartTypePointer myDefaultType; protected JCheckBox myCanBeFinal; private Balloon myBalloon; public VariableInplaceIntroducer(final Project project, final TypeExpression expression, final Editor editor, final PsiVariable elementToRename, final boolean cantChangeFinalModifier, final boolean hasTypeSuggestion, final RangeMarker exprMarker, final List<RangeMarker> occurrenceMarkers, final String commandName) { super(elementToRename, editor); myProject = project; myEditor = editor; myElementToRename = elementToRename; myExpression = expression; myExprMarker = exprMarker; myOccurrenceMarkers = occurrenceMarkers; final PsiType defaultType = elementToRename.getType(); myDefaultType = SmartTypePointerManager.getInstance(project).createSmartTypePointer(defaultType); final PsiDeclarationStatement declarationStatement = PsiTreeUtil.getParentOfType(elementToRename, PsiDeclarationStatement.class); myPointer = declarationStatement != null ? SmartPointerManager.getInstance(project).createSmartPsiElementPointer(declarationStatement) : null; editor.putUserData(ReassignVariableUtil.DECLARATION_KEY, myPointer); editor.putUserData(ReassignVariableUtil.OCCURRENCES_KEY, occurrenceMarkers.toArray(new RangeMarker[occurrenceMarkers.size()])); setAdvertisementText(getAdvertisementText(declarationStatement, defaultType, hasTypeSuggestion)); if (!cantChangeFinalModifier) { myCanBeFinal = new NonFocusableCheckBox("Declare final"); myCanBeFinal.setSelected(createFinals()); myCanBeFinal.setMnemonic('f'); myCanBeFinal.addActionListener(new FinalListener(project, commandName)); } } @Override protected void addAdditionalVariables(TemplateBuilderImpl builder) { final PsiTypeElement typeElement = myElementToRename.getTypeElement(); builder.replaceElement(typeElement, "Variable_Type", createExpression(myExpression, typeElement.getText()), true, true); } @Override protected LookupElement[] createLookupItems(LookupElement[] lookupItems, String name) { TemplateState templateState = TemplateManagerImpl.getTemplateState(myEditor); final PsiVariable psiVariable = getVariable(); if (psiVariable != null) { final TextResult insertedValue = templateState != null ? templateState.getVariableValue(PRIMARY_VARIABLE_NAME) : null; if (insertedValue != null) { final String text = insertedValue.getText(); if (!text.isEmpty() && !Comparing.strEqual(text, name)) { final LinkedHashSet<String> names = new LinkedHashSet<String>(); names.add(text); for (NameSuggestionProvider provider : Extensions.getExtensions(NameSuggestionProvider.EP_NAME)) { provider.getSuggestedNames(psiVariable, psiVariable, names); } final LookupElement[] items = new LookupElement[names.size()]; final Iterator<String> iterator = names.iterator(); for (int i = 0; i < items.length; i++) { items[i] = LookupElementBuilder.create(iterator.next()); } return items; } } } return super.createLookupItems(lookupItems, name); } @Nullable protected PsiVariable getVariable() { final PsiDeclarationStatement declarationStatement = myPointer.getElement(); return declarationStatement != null ? (PsiVariable)declarationStatement.getDeclaredElements()[0] : null; } @Override protected TextRange preserveSelectedRange(SelectionModel selectionModel) { return null; } @Override public boolean performInplaceRename(boolean processTextOccurrences, LinkedHashSet<String> nameSuggestions) { final boolean result = super.performInplaceRename(processTextOccurrences, nameSuggestions); showBalloon(); return result; } public RangeMarker getExprMarker() { return myExprMarker; } @Override protected boolean performAutomaticRename() { return false; } @Override protected void moveOffsetAfter(boolean success) { try { if (success) { final Document document = myEditor.getDocument(); final @Nullable PsiVariable psiVariable = getVariable(); if (psiVariable == null) { return; } LOG.assertTrue(psiVariable.isValid()); saveSettings(psiVariable); adjustLine(psiVariable, document); int startOffset = myExprMarker != null && myExprMarker.isValid() ? myExprMarker.getStartOffset() : psiVariable.getTextOffset(); final PsiFile file = psiVariable.getContainingFile(); final PsiReference referenceAt = file.findReferenceAt(startOffset); if (referenceAt != null && referenceAt.resolve() instanceof PsiVariable) { startOffset = referenceAt.getElement().getTextRange().getEndOffset(); } else { final PsiDeclarationStatement declarationStatement = PsiTreeUtil.getParentOfType(psiVariable, PsiDeclarationStatement.class); if (declarationStatement != null) { startOffset = declarationStatement.getTextRange().getEndOffset(); } } myEditor.getCaretModel().moveToOffset(startOffset); myEditor.getScrollingModel().scrollToCaret(ScrollType.MAKE_VISIBLE); if (psiVariable.getInitializer() != null) { ApplicationManager.getApplication().runWriteAction(new Runnable() { public void run() { appendTypeCasts(myOccurrenceMarkers, file, myProject, psiVariable); } }); } } else { if (myExprMarker != null) { myEditor.getCaretModel().moveToOffset(myExprMarker.getStartOffset()); myEditor.getScrollingModel().scrollToCaret(ScrollType.MAKE_VISIBLE); } } } finally { myEditor.putUserData(ReassignVariableUtil.DECLARATION_KEY, null); for (RangeMarker occurrenceMarker : myOccurrenceMarkers) { occurrenceMarker.dispose(); } myEditor.putUserData(ReassignVariableUtil.OCCURRENCES_KEY, null); if (myExprMarker != null) myExprMarker.dispose(); } } @Override public void finish() { super.finish(); if (myBalloon != null) myBalloon.hide(); } protected void saveSettings(PsiVariable psiVariable) { JavaRefactoringSettings.getInstance().INTRODUCE_LOCAL_CREATE_FINALS = psiVariable.hasModifierProperty(PsiModifier.FINAL); TypeSelectorManagerImpl.typeSelected(psiVariable.getType(), myDefaultType.getType()); } @Nullable protected JComponent getComponent() { final JPanel panel = new JPanel(new GridBagLayout()); panel.setBorder(null); final TitlePanel titlePanel = new TitlePanel(); titlePanel.setBorder(null); titlePanel.setText(IntroduceVariableBase.REFACTORING_NAME); panel.add(titlePanel, new GridBagConstraints(0, 0, 1, 1, 1, 0, GridBagConstraints.NORTHWEST, GridBagConstraints.HORIZONTAL, new Insets(0, 0, 0, 0), 0, 0)); if (myCanBeFinal != null) { panel.add(myCanBeFinal, new GridBagConstraints(0, 1, 1, 1, 1, 0, GridBagConstraints.NORTHWEST, GridBagConstraints.HORIZONTAL, new Insets(5, 5, 5, 5), 0, 0)); } panel.add(Box.createVerticalBox(), new GridBagConstraints(0, 2, 1, 1, 1, 1, GridBagConstraints.NORTHWEST, GridBagConstraints.BOTH, new Insets(0,0,0,0), 0,0)); return panel; } private static void appendTypeCasts(List<RangeMarker> occurrenceMarkers, PsiFile file, Project project, @Nullable PsiVariable psiVariable) { for (RangeMarker occurrenceMarker : occurrenceMarkers) { final PsiElement refVariableElement = file.findElementAt(occurrenceMarker.getStartOffset()); final PsiReferenceExpression referenceExpression = PsiTreeUtil.getParentOfType(refVariableElement, PsiReferenceExpression.class); if (referenceExpression != null) { final PsiElement parent = referenceExpression.getParent(); if (parent instanceof PsiVariable) { createCastInVariableDeclaration(project, (PsiVariable)parent); } else if (parent instanceof PsiReferenceExpression && psiVariable != null) { final PsiExpression initializer = psiVariable.getInitializer(); LOG.assertTrue(initializer != null); final PsiType type = initializer.getType(); if (((PsiReferenceExpression)parent).resolve() == null && type != null) { final PsiElementFactory elementFactory = JavaPsiFacade.getElementFactory(project); final PsiExpression castedExpr = elementFactory.createExpressionFromText("((" + type.getCanonicalText() + ")" + referenceExpression.getText() + ")", parent); JavaCodeStyleManager.getInstance(project).shortenClassReferences(referenceExpression.replace(castedExpr)); } } } } if (psiVariable != null && psiVariable.isValid()) { createCastInVariableDeclaration(project, psiVariable); } } private static void createCastInVariableDeclaration(Project project, PsiVariable psiVariable) { final PsiExpression initializer = psiVariable.getInitializer(); LOG.assertTrue(initializer != null); final PsiType type = psiVariable.getType(); final PsiType initializerType = initializer.getType(); if (initializerType != null && !TypeConversionUtil.isAssignable(type, initializerType)) { final PsiElementFactory elementFactory = JavaPsiFacade.getElementFactory(project); final PsiExpression castExpr = elementFactory.createExpressionFromText("(" + psiVariable.getType().getCanonicalText() + ")" + initializer.getText(), psiVariable); JavaCodeStyleManager.getInstance(project).shortenClassReferences(initializer.replace(castExpr)); } } @Nullable private static String getAdvertisementText(final PsiDeclarationStatement declaration, final PsiType type, final boolean hasTypeSuggestion) { final VariablesProcessor processor = ReassignVariableUtil.findVariablesOfType(declaration, type); final Keymap keymap = KeymapManager.getInstance().getActiveKeymap(); if (processor.size() > 0) { final Shortcut[] shortcuts = keymap.getShortcuts("IntroduceVariable"); if (shortcuts.length > 0) { return "Press " + shortcuts[0] + " to reassign existing variable"; } } if (hasTypeSuggestion) { final Shortcut[] shortcuts = keymap.getShortcuts("PreviousTemplateVariable"); if (shortcuts.length > 0) { return "Press " + shortcuts[0] + " to change type"; } } return null; } private static Expression createExpression(final TypeExpression expression, final String defaultType) { return new Expression() { @Override public Result calculateResult(ExpressionContext context) { return new TextResult(defaultType); } @Override public Result calculateQuickResult(ExpressionContext context) { return new TextResult(defaultType); } @Override public LookupElement[] calculateLookupItems(ExpressionContext context) { return expression.calculateLookupItems(context); } @Override public String getAdvertisingText() { return null; } }; } protected boolean createFinals() { return IntroduceVariableBase.createFinals(myProject); } public static void adjustLine(final PsiVariable psiVariable, final Document document) { final int modifierListOffset = psiVariable.getTextRange().getStartOffset(); final int varLineNumber = document.getLineNumber(modifierListOffset); ApplicationManager.getApplication().runWriteAction(new Runnable() { //adjust line indent if final was inserted and then deleted public void run() { PsiDocumentManager.getInstance(psiVariable.getProject()).doPostponedOperationsAndUnblockDocument(document); CodeStyleManager.getInstance(psiVariable.getProject()).adjustLineIndent(document, document.getLineStartOffset(varLineNumber)); } }); } private void showBalloon() { final JComponent component = getComponent(); if (component == null) return; if (ApplicationManager.getApplication().isHeadlessEnvironment()) return; final BalloonBuilder balloonBuilder = JBPopupFactory.getInstance().createBalloonBuilder(component); balloonBuilder.setFadeoutTime(0) .setFillColor(IdeTooltipManager.GRAPHITE_COLOR.brighter().brighter()) .setAnimationCycle(0) .setHideOnClickOutside(false) .setHideOnKeyOutside(false) .setHideOnAction(false) .setCloseButtonEnabled(true); final RelativePoint target = JBPopupFactory.getInstance().guessBestPopupLocation(myEditor); final Point screenPoint = target.getScreenPoint(); myBalloon = balloonBuilder.createBalloon(); int y = screenPoint.y; if (target.getPoint().getY() > myEditor.getLineHeight() + myBalloon.getPreferredSize().getHeight()) { y -= myEditor.getLineHeight(); } myBalloon.show(new RelativePoint(new Point(screenPoint.x, y)), Balloon.Position.above); } public class FinalListener implements ActionListener { private final Project myProject; private final String myCommandName; public FinalListener(Project project, String commandName) { myProject = project; myCommandName = commandName; } @Override public void actionPerformed(ActionEvent e) { perform(myCanBeFinal.isSelected()); } public void perform(final boolean generateFinal) { perform(generateFinal, PsiModifier.FINAL); } public void perform(final boolean generateFinal, final String modifier) { new WriteCommandAction(myProject, myCommandName, myCommandName){ @Override protected void run(com.intellij.openapi.application.Result result) throws Throwable { final Document document = myEditor.getDocument(); PsiDocumentManager.getInstance(getProject()).commitDocument(document); final PsiVariable variable = getVariable(); LOG.assertTrue(variable != null); final PsiModifierList modifierList = variable.getModifierList(); LOG.assertTrue(modifierList != null); final int textOffset = modifierList.getTextOffset(); final Runnable runnable = new Runnable() { public void run() { if (generateFinal) { final PsiTypeElement typeElement = variable.getTypeElement(); final int typeOffset = typeElement != null ? typeElement.getTextOffset() : textOffset; document.insertString(typeOffset, modifier + " "); } else { final int idx = modifierList.getText().indexOf(modifier); document.deleteString(textOffset + idx, textOffset + idx + modifier.length() + 1); } } }; final LookupImpl lookup = (LookupImpl)LookupManager.getActiveLookup(myEditor); if (lookup != null) { lookup.performGuardedChange(runnable); } else { runnable.run(); } } }.execute(); } } }
do not show popup when nothing can be changed [spleaner] (cherry picked from commit 88c50620bc5057b779fdb6bb1d1f619606a59d17)
java/java-impl/src/com/intellij/refactoring/introduceVariable/VariableInplaceIntroducer.java
do not show popup when nothing can be changed [spleaner] (cherry picked from commit 88c50620bc5057b779fdb6bb1d1f619606a59d17)
<ide><path>ava/java-impl/src/com/intellij/refactoring/introduceVariable/VariableInplaceIntroducer.java <ide> private final List<RangeMarker> myOccurrenceMarkers; <ide> private final SmartTypePointer myDefaultType; <ide> <del> protected JCheckBox myCanBeFinal; <add> protected JCheckBox myCanBeFinalCb; <ide> private Balloon myBalloon; <ide> <ide> public VariableInplaceIntroducer(final Project project, <ide> occurrenceMarkers.toArray(new RangeMarker[occurrenceMarkers.size()])); <ide> setAdvertisementText(getAdvertisementText(declarationStatement, defaultType, hasTypeSuggestion)); <ide> if (!cantChangeFinalModifier) { <del> myCanBeFinal = new NonFocusableCheckBox("Declare final"); <del> myCanBeFinal.setSelected(createFinals()); <del> myCanBeFinal.setMnemonic('f'); <del> myCanBeFinal.addActionListener(new FinalListener(project, commandName)); <add> myCanBeFinalCb = new NonFocusableCheckBox("Declare final"); <add> myCanBeFinalCb.setSelected(createFinals()); <add> myCanBeFinalCb.setMnemonic('f'); <add> myCanBeFinalCb.addActionListener(new FinalListener(project, commandName)); <ide> } <ide> } <ide> <ide> <ide> @Nullable <ide> protected JComponent getComponent() { <add> if (myCanBeFinalCb == null) return null; <ide> final JPanel panel = new JPanel(new GridBagLayout()); <ide> panel.setBorder(null); <ide> <ide> titlePanel.setText(IntroduceVariableBase.REFACTORING_NAME); <ide> panel.add(titlePanel, new GridBagConstraints(0, 0, 1, 1, 1, 0, GridBagConstraints.NORTHWEST, GridBagConstraints.HORIZONTAL, new Insets(0, 0, 0, 0), 0, 0)); <ide> <del> if (myCanBeFinal != null) { <del> panel.add(myCanBeFinal, new GridBagConstraints(0, 1, 1, 1, 1, 0, GridBagConstraints.NORTHWEST, GridBagConstraints.HORIZONTAL, new Insets(5, 5, 5, 5), 0, 0)); <add> if (myCanBeFinalCb != null) { <add> panel.add(myCanBeFinalCb, new GridBagConstraints(0, 1, 1, 1, 1, 0, GridBagConstraints.NORTHWEST, GridBagConstraints.HORIZONTAL, new Insets(5, 5, 5, 5), 0, 0)); <ide> } <ide> <ide> panel.add(Box.createVerticalBox(), new GridBagConstraints(0, 2, 1, 1, 1, 1, GridBagConstraints.NORTHWEST, GridBagConstraints.BOTH, new Insets(0,0,0,0), 0,0)); <ide> <ide> @Override <ide> public void actionPerformed(ActionEvent e) { <del> perform(myCanBeFinal.isSelected()); <add> perform(myCanBeFinalCb.isSelected()); <ide> } <ide> <ide> public void perform(final boolean generateFinal) {
Java
lgpl-2.1
6863963b2af15f0743754533b50bfe549f3bb4d5
0
pbondoer/xwiki-platform,xwiki/xwiki-platform,pbondoer/xwiki-platform,xwiki/xwiki-platform,xwiki/xwiki-platform,pbondoer/xwiki-platform,xwiki/xwiki-platform,pbondoer/xwiki-platform,pbondoer/xwiki-platform,xwiki/xwiki-platform
/* * See the NOTICE file distributed with this work for additional * information regarding copyright ownership. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package com.xpn.xwiki.plugin.activitystream.migration.hibernate; import java.sql.Connection; import java.sql.SQLException; import java.sql.Statement; import javax.inject.Inject; import javax.inject.Named; import javax.inject.Singleton; import org.hibernate.HibernateException; import org.hibernate.Session; import org.hibernate.jdbc.Work; import org.slf4j.Logger; import org.xwiki.component.annotation.Component; import com.xpn.xwiki.XWikiException; import com.xpn.xwiki.store.XWikiHibernateBaseStore.HibernateCallback; import com.xpn.xwiki.store.migration.DataMigrationException; import com.xpn.xwiki.store.migration.XWikiDBVersion; import com.xpn.xwiki.store.migration.hibernate.AbstractHibernateDataMigration; /** * Migration for XWIKI-6691: Change the mapping of the event requestId field to varchar(48). Since the even group ID is * always a GUID of length at most 36, it doesn't make sense to allocate 2000 characters for it. Since Hibernate cannot * alter existing columns to change their types, and we don't want to lose all the existing data in case of a migration, * we create a new column with the right type, and manually copy data between columns. After that we try to drop the old * column to free up some space. * * @version $Id$ * @since 3.5M1 */ @Component @Named("R35000XWIKI6691") @Singleton public class R35000XWIKI6691DataMigration extends AbstractHibernateDataMigration { /** Logging helper object. */ @Inject private static Logger logger; @Override public String getDescription() { return "See http://jira.xwiki.org/browse/XWIKI-6691"; } @Override public XWikiDBVersion getVersion() { return new XWikiDBVersion(35000); } @Override public void hibernateMigrate() throws DataMigrationException, XWikiException { getStore().executeWrite(getXWikiContext(), true, new HibernateCallback<Object>() { @Override public Object doInHibernate(Session session) throws HibernateException, XWikiException { session.doWork(new RequestToGroupRenameWork(getDescription(), getVersion().getVersion())); return Boolean.TRUE; } }); } /** * Hibernate "Work" class responsible for moving data from the old ase_requestid column to the new ase_groupid * column. * * @version $Id$ */ private static final class RequestToGroupRenameWork implements Work { private String migratorDescription; private int migratorVersion; public RequestToGroupRenameWork(String migratorDescription, int migratorVersion) { this.migratorDescription = migratorDescription; this.migratorVersion = migratorVersion; } @Override public void execute(Connection connection) throws SQLException { Statement stmt = connection.createStatement(); stmt.addBatch("UPDATE activitystream_events SET ase_groupid = ase_requestid"); stmt.addBatch("ALTER TABLE activitystream_events DROP COLUMN ase_requestid"); try { stmt.executeBatch(); } catch (SQLException ex) { // Ignore, probably the database doesn't need this migration. // Anyway, in case it really can't be performed, report it in the logs. R35000XWIKI6691DataMigration.logger.warn("Failed to apply the Data migrator for version [{}]({}). " + "Reason: [{}]. It's likely that the database schema is already up to date and you can safely " + "ignore this warning.", new Object[] {this.migratorVersion, this.migratorDescription, ex.getMessage()}); } } } }
xwiki-platform-core/xwiki-platform-activitystream/src/main/java/com/xpn/xwiki/plugin/activitystream/migration/hibernate/R35000XWIKI6691DataMigration.java
/* * See the NOTICE file distributed with this work for additional * information regarding copyright ownership. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package com.xpn.xwiki.plugin.activitystream.migration.hibernate; import java.sql.Connection; import java.sql.SQLException; import java.sql.Statement; import javax.inject.Inject; import javax.inject.Named; import javax.inject.Singleton; import org.hibernate.HibernateException; import org.hibernate.Session; import org.hibernate.jdbc.Work; import org.slf4j.Logger; import org.xwiki.component.annotation.Component; import com.xpn.xwiki.XWikiException; import com.xpn.xwiki.store.XWikiHibernateBaseStore.HibernateCallback; import com.xpn.xwiki.store.migration.DataMigrationException; import com.xpn.xwiki.store.migration.XWikiDBVersion; import com.xpn.xwiki.store.migration.hibernate.AbstractHibernateDataMigration; /** * Migration for XWIKI-6691: Change the mapping of the event requestId field to varchar(48). Since the even group ID is * always a GUID of length at most 36, it doesn't make sense to allocate 2000 characters for it. Since Hibernate cannot * alter existing columns to change their types, and we don't want to lose all the existing data in case of a migration, * we create a new column with the right type, and manually copy data between columns. After that we try to drop the old * column to free up some space. * * @version $Id$ * @since 3.5M1 */ @Component @Named("R35000XWIKI6691") @Singleton public class R35000XWIKI6691DataMigration extends AbstractHibernateDataMigration { /** Logging helper object. */ @Inject private static Logger logger; @Override public String getDescription() { return "See http://jira.xwiki.org/browse/XWIKI-6691"; } @Override public XWikiDBVersion getVersion() { return new XWikiDBVersion(35000); } @Override public void hibernateMigrate() throws DataMigrationException, XWikiException { getStore().executeWrite(getXWikiContext(), true, new HibernateCallback<Object>() { @Override public Object doInHibernate(Session session) throws HibernateException, XWikiException { session.doWork(new RequestToGroupRenameWork()); return Boolean.TRUE; } }); } /** * Hibernate "Work" class responsible for moving data from the old ase_requestid column to the new ase_groupid * column. * * @version $Id$ */ private static final class RequestToGroupRenameWork implements Work { @Override public void execute(Connection connection) throws SQLException { Statement stmt = connection.createStatement(); stmt.addBatch("UPDATE activitystream_events SET ase_groupid = ase_requestid"); stmt.addBatch("ALTER TABLE activitystream_events DROP COLUMN ase_requestid"); try { stmt.executeBatch(); } catch (SQLException ex) { // Ignore, probably the database doesn't need this migration. // Anyway, in case it really can't be performed, report it in the logs. R35000XWIKI6691DataMigration.logger.warn( "Failed to apply R35000XWIKI6691 Data Migration : {}", ex.getMessage()); } } } }
XWIKI-6691: Change the mapping of the event requestId field to varchar(48) * Improved warning message
xwiki-platform-core/xwiki-platform-activitystream/src/main/java/com/xpn/xwiki/plugin/activitystream/migration/hibernate/R35000XWIKI6691DataMigration.java
XWIKI-6691: Change the mapping of the event requestId field to varchar(48) * Improved warning message
<ide><path>wiki-platform-core/xwiki-platform-activitystream/src/main/java/com/xpn/xwiki/plugin/activitystream/migration/hibernate/R35000XWIKI6691DataMigration.java <ide> * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA <ide> * 02110-1301 USA, or see the FSF site: http://www.fsf.org. <ide> */ <del> <ide> package com.xpn.xwiki.plugin.activitystream.migration.hibernate; <ide> <ide> import java.sql.Connection; <ide> @Override <ide> public Object doInHibernate(Session session) throws HibernateException, XWikiException <ide> { <del> session.doWork(new RequestToGroupRenameWork()); <add> session.doWork(new RequestToGroupRenameWork(getDescription(), getVersion().getVersion())); <ide> return Boolean.TRUE; <ide> } <ide> }); <ide> */ <ide> private static final class RequestToGroupRenameWork implements Work <ide> { <add> private String migratorDescription; <add> private int migratorVersion; <add> <add> public RequestToGroupRenameWork(String migratorDescription, int migratorVersion) <add> { <add> this.migratorDescription = migratorDescription; <add> this.migratorVersion = migratorVersion; <add> } <add> <ide> @Override <ide> public void execute(Connection connection) throws SQLException <ide> { <ide> } catch (SQLException ex) { <ide> // Ignore, probably the database doesn't need this migration. <ide> // Anyway, in case it really can't be performed, report it in the logs. <del> R35000XWIKI6691DataMigration.logger.warn( <del> "Failed to apply R35000XWIKI6691 Data Migration : {}", ex.getMessage()); <add> R35000XWIKI6691DataMigration.logger.warn("Failed to apply the Data migrator for version [{}]({}). " <add> + "Reason: [{}]. It's likely that the database schema is already up to date and you can safely " <add> + "ignore this warning.", new Object[] {this.migratorVersion, this.migratorDescription, <add> ex.getMessage()}); <ide> } <ide> } <ide> }
JavaScript
apache-2.0
b5d9d5651cad611538f0c8868d7645d8a08d9527
0
couchbase/cbmonitor,couchbase/cbmonitor
/*jshint jquery: true, browser: true*/ /*global angular, d3*/ angular.module("insight", []) .config(["$interpolateProvider", function ($interpolateProvider) { "use strict"; $interpolateProvider.startSymbol("[["); $interpolateProvider.endSymbol("]]"); }]); var INSIGHT = { height: 548, width: 900, smallPadding: 40, largePadding: 70, fontHeight: 14, fontWidth: 10, palette: [ "#f89406", "#51A351", "#7D1935", "#4A96AD", "#DE1B1B", "#E9E581", "#A2AB58", "#FFE658", "#118C4E", "#193D4F" ] }; function Insights($scope, $http) { "use strict"; $scope.getOptions = function() { $scope.inputs = []; $scope.abscissa = null; $scope.vary_by = null; $scope.customInputs = {}; $scope.currentOptions = {}; var params = {"insight": $scope.selectedInsight.id}; $http({method: "GET", url: "/cbmonitor/get_insight_options/", params: params}) .success(function(data) { $scope.inputs = data; resetCharts(); }); }; $scope.getData = function() { var params = { "insight": $scope.selectedInsight.id, "abscissa": $scope.abscissa, "inputs": JSON.stringify($scope.currentOptions) }; if ($scope.vary_by !== null ) { params.vary_by = $scope.vary_by; } $http({method: "GET", url: "/cbmonitor/get_insight_data/", params: params}) .success(function(data) { resetCharts(); if ($.isEmptyObject(data)) { drawWarning(); } else { drawScatterPlot(data, $scope.vary_by); } }); }; $scope.updateData = function(title, value, option) { if (value === "As X-axis") { if ($scope.abscissa !== null && $scope.abscissa !== title) { $scope.currentOptions[$scope.abscissa] = $scope.resetAbscissaTo; } $scope.abscissa = title; $scope.resetAbscissaTo = $scope.inputs[option.$index].options[0]; } else if ($scope.abscissa === title) { $scope.abscissa = null; } if (value === "Vary by") { if ($scope.vary_by !== null && $scope.vary_by !== title) { $scope.currentOptions[$scope.vary_by] = $scope.resetVaryByTo; } $scope.vary_by = title; $scope.resetVaryByTo = $scope.inputs[option.$index].options[0]; } else if ($scope.vary_by === title) { $scope.vary_by = null; } if ($scope.abscissa !== null) { $scope.getData(); } else { resetCharts(); } }; $http.get("/cbmonitor/get_insight_defaults/").success(function(insights) { $scope.insights = insights; $scope.selectedInsight = insights[0]; var query = window.location.search.split("="); for (var i=0, l=insights.length; i < l; i++) { if (insights[i].id === query[query.length - 1]) { $scope.selectedInsight = insights[i]; break; } } $scope.getOptions(); }); } function drawBase() { "use strict"; d3.select("#chart").append("svg").attr({ height: INSIGHT.height, width: INSIGHT.width }); d3.select("svg").append("rect").attr({ height: INSIGHT.height, width: INSIGHT.width, rx: 5, ry: 5, fill: "white", stroke: "#cccccc" }); } function addFocus(seqid) { "use strict"; var focus = d3.select("svg").append("g") .attr("class", "focus") .style("display", "none"); focus.append("text").attr({ dx: "15px", dy: "25px", fill: INSIGHT.palette[seqid] }); return focus; } function showFocus(focus, obj, yScale) { "use strict"; var x = d3.mouse(obj)[0], y = d3.mouse(obj)[1], formatValue = d3.format(".1f"), value = formatValue(yScale.invert(y)); focus .style("display", null) .attr("transform", "translate(" + x + "," + y + ")") .select("text").text(value); } function drawDataPoints(circles, xScale, yScale, seqid) { "use strict"; var focus = addFocus(seqid); circles .append("circle") .on("mouseover", function() { showFocus(focus, this, yScale); d3.select(this).transition().duration(200) .attr({ r: 7 }); }) .on("mouseout", function() { focus.style("display", "none"); d3.select(this).transition().duration(200) .attr({ r: 5 }); }) .transition().duration(500).ease("linear").each("start", function() { d3.select(this).attr({ fill: "white", stroke: "white" }); }) .attr({ cx: function(d) { return xScale(d[0]); }, cy: function(d) { return yScale(d[1]); }, r: 5, stroke: INSIGHT.palette[seqid], "stroke-width": 3 }); } function drawSplines(data, xScale, yScale, seqid) { "use strict"; var line = d3.svg.line() .x(function(d) { return xScale(d[0]); }) .y(function(d) { return yScale(d[1]); }) .interpolate("cardinal"); var focus = addFocus(seqid); d3.select("svg") .append("path") .on("mouseover", function() { showFocus(focus, this, yScale); }) .on("mouseout", function() { focus.style("display", "none"); }) .transition().duration(500).ease("linear").each("start", function() { d3.select(this).attr({ stroke: "white" }); }) .attr({ "d": line(data), stroke: INSIGHT.palette[seqid], "stroke-width": 2, "fill-opacity": 0.0, "pointer-events": "stroke" }); } function drawLines(lines, xScale, yScale) { "use strict"; lines.append("line") .transition().duration(500).ease("linear").each("start", function() { d3.select(this).attr({ stroke: "white" }); }) .attr({ x1: function(d) { return xScale(d[0]); }, y1: function(d) { return yScale(d[1]); }, x2: function(d) { return xScale(d[2]); }, y2: function(d) { return yScale(d[3]); }, stroke: "#cccccc", "shape-rendering": "crispEdges" }); } function drawAxes(xScale, yScale, xTickValues) { "use strict"; var areaPadding = 10; var xAxis = d3.svg.axis() .scale(xScale) .orient("bottom") .tickValues(xTickValues); d3.select("svg").append("g") .attr("class", "axis") .attr("transform", "translate(0, " + (INSIGHT.height - INSIGHT.smallPadding + areaPadding) + ")") .call(xAxis); var yAxis = d3.svg.axis() .scale(yScale) .orient("left") .ticks(5); d3.select("svg").append("g") .attr("class", "axis") .attr("transform", "translate(" + (INSIGHT.largePadding - areaPadding) + ", 0)") .call(yAxis); } function drawLegendTitle(title) { "use strict"; d3.select("svg").append("g").append("text") .transition().duration(500).ease("linear").each("start", function() { d3.select(this).attr({ fill: "white" }); }) .text(title + ":") .attr({ x: INSIGHT.largePadding + 5, y: (INSIGHT.smallPadding + INSIGHT.fontHeight) / 2, "font-size": INSIGHT.fontHeight, fill: "black" }); } function drawLegend(legend, legendPadding, legendInterval) { "use strict"; legend.append("text") .transition().duration(500).ease("linear").each("start", function() { d3.select(this).attr({ fill: "white" }); }) .text(function(d) { return d; }) .attr({ x: function(d, i) { return INSIGHT.largePadding + legendPadding + i * legendInterval; }, y: (INSIGHT.smallPadding + INSIGHT.fontHeight) / 2, "font-size": INSIGHT.fontHeight, "font-weight": "bold", fill: function(d, i) { return INSIGHT.palette[i]; } }); } function drawWarning() { "use strict"; d3.select("svg").append("text") .text("No data") .attr({ x: INSIGHT.width / 2 - 50, y: INSIGHT.height / 2, class: "warning" }); } function resetCharts() { "use strict"; d3.selectAll("circle").remove(); d3.selectAll("line").remove(); d3.selectAll("g").remove(); d3.selectAll("path").remove(); d3.selectAll("text").remove(); } function drawScatterPlot(data, vary_by) { "use strict"; /******************************** MIN MAX *********************************/ var xMin = Number.MAX_VALUE, xMax = Number.MIN_VALUE, yMax = Number.MIN_VALUE; Object.keys(data).forEach(function(key) { xMin = Math.min(xMin, d3.min(data[key], function(d) { return d[0]; })); xMax = Math.max(xMax, d3.max(data[key], function(d) { return d[0]; })); yMax = Math.max(yMax, d3.max(data[key], function(d) { return d[1]; })); }); /********************************* SCALES *********************************/ var yScale = d3.scale.linear() .domain([0, yMax]) .range([INSIGHT.height - INSIGHT.smallPadding, INSIGHT.smallPadding]); var xScale; if (isNaN(xMin) || isNaN(xMax)) { xScale = d3.scale.ordinal() .range([INSIGHT.largePadding, INSIGHT.width - INSIGHT.smallPadding]); } else { xScale = d3.scale.linear() .domain([xMin, xMax]) .range([INSIGHT.largePadding, INSIGHT.width - INSIGHT.smallPadding]); } /********************************** TICKS *********************************/ var yTickValues = yScale.ticks(5); var xTickValues = []; Object.keys(data).forEach(function(key) { for (var i=0, l=data[key].length; i < l; i++) { if (xTickValues.indexOf(data[key][i][0] === -1)) { xTickValues.push(data[key][i][0]); } } }); /********************************** GRID **********************************/ var linesXY = [[xMax, yMax, xMin, yMax]]; for (var i=0, l=xTickValues.length; i<l; i++) { linesXY.push([xTickValues[i], 0, xTickValues[i], yMax]); } for (i=0, l=yTickValues.length; i<l; i++) { linesXY.push([xMin, yTickValues[i], xMax, yTickValues[i]]); } var lines = d3.select("svg").selectAll("line") .data(linesXY) .enter(); drawLines(lines, xScale, yScale); /****************************** DATA POINTS *******************************/ var circles = d3.select("svg").selectAll("circle"), seqid = 0, legendInterval = 0; Object.keys(data).forEach(function(key) { drawSplines(data[key], xScale, yScale, seqid); drawDataPoints(circles.data(data[key]).enter(), xScale, yScale, seqid); legendInterval = Math.max((key.length + 1) * INSIGHT.fontWidth, legendInterval); seqid++; }); if (vary_by !== null) { var legend = d3.select("svg").append("g").selectAll("text"), legendPadding = (vary_by.length + 1) * INSIGHT.fontWidth; drawLegendTitle(vary_by); drawLegend(legend.data(Object.keys(data)).enter(), legendPadding, legendInterval); } /********************************** AXES **********************************/ drawAxes(xScale, yScale, xTickValues); /**************************************************************************/ } $(document).ready(function(){ "use strict"; drawBase(); });
webapp/cbmonitor/static/js/insight.js
/*jshint jquery: true, browser: true*/ /*global angular, d3*/ angular.module("insight", []) .config(["$interpolateProvider", function ($interpolateProvider) { "use strict"; $interpolateProvider.startSymbol("[["); $interpolateProvider.endSymbol("]]"); }]); var INSIGHT = { height: 548, width: 900, smallPadding: 40, largePadding: 70, fontHeight: 14, fontWidth: 10, palette: [ "#f89406", "#51A351", "#7D1935", "#4A96AD", "#DE1B1B", "#E9E581", "#A2AB58", "#FFE658", "#118C4E", "#193D4F" ] }; function Insights($scope, $http) { "use strict"; $scope.getOptions = function() { $scope.inputs = []; $scope.abscissa = null; $scope.vary_by = null; $scope.customInputs = {}; $scope.currentOptions = {}; var params = {"insight": $scope.selectedInsight.id}; $http({method: "GET", url: "/cbmonitor/get_insight_options/", params: params}) .success(function(data) { $scope.inputs = data; resetCharts(); }); }; $scope.getData = function() { var params = { "insight": $scope.selectedInsight.id, "abscissa": $scope.abscissa, "inputs": JSON.stringify($scope.currentOptions) }; if ($scope.vary_by !== null ) { params.vary_by = $scope.vary_by; } $http({method: "GET", url: "/cbmonitor/get_insight_data/", params: params}) .success(function(data) { resetCharts(); if ($.isEmptyObject(data)) { drawWarning(); } else { drawScatterPlot(data, $scope.vary_by); } }); }; $scope.updateData = function(title, value, option) { if (value === "As X-axis") { if ($scope.abscissa !== null && $scope.abscissa !== title) { $scope.currentOptions[$scope.abscissa] = $scope.resetAbscissaTo; } $scope.abscissa = title; $scope.resetAbscissaTo = $scope.inputs[option.$index].options[0]; } else if ($scope.abscissa === title) { $scope.abscissa = null; } if (value === "Vary by") { if ($scope.vary_by !== null && $scope.vary_by !== title) { $scope.currentOptions[$scope.vary_by] = $scope.resetVaryByTo; } $scope.vary_by = title; $scope.resetVaryByTo = $scope.inputs[option.$index].options[0]; } else if ($scope.vary_by === title) { $scope.vary_by = null; } if ($scope.abscissa !== null) { $scope.getData(); } else { resetCharts(); } }; $http.get("/cbmonitor/get_insight_defaults/").success(function(insights) { $scope.insights = insights; $scope.selectedInsight = insights[0]; var query = window.location.search.split("="); for (var i=0, l=insights.length; i < l; i++) { if (insights[i].id === query[query.length - 1]) { $scope.selectedInsight = insights[i]; break; } } $scope.getOptions(); }); } function drawBase() { "use strict"; d3.select("#chart").append("svg").attr({ height: INSIGHT.height, width: INSIGHT.width }); d3.select("svg").append("rect").attr({ height: INSIGHT.height, width: INSIGHT.width, rx: 5, ry: 5, fill: "white", stroke: "#cccccc" }); } function drawDataPoints(circles, xScale, yScale, seqid) { "use strict"; circles .append("circle") .on("mouseover", function() { d3.select(this).transition().duration(200) .attr({ r: 7 }); }) .on("mouseout", function() { d3.select(this).transition().duration(200) .attr({ r: 5 }); }) .transition().duration(500).ease("linear").each("start", function() { d3.select(this).attr({ fill: "white", stroke: "white" }); }) .attr({ cx: function(d) { return xScale(d[0]); }, cy: function(d) { return yScale(d[1]); }, r: 5, stroke: INSIGHT.palette[seqid], "stroke-width": 3 }); } function drawSplines(data, xScale, yScale, seqid) { "use strict"; var line = d3.svg.line() .x(function(d) { return xScale(d[0]); }) .y(function(d) { return yScale(d[1]); }) .interpolate("cardinal"); var focus = d3.select("svg").append("g") .attr("class", "focus") .style("display", "none"); focus.append("text") .attr({ dx: "15px", dy: "25px", fill: INSIGHT.palette[seqid] }); d3.select("svg") .append("path") .on("mouseover", function() { focus.style("display", null); }) .on("mouseout", function() { focus.style("display", "none"); }) .on("mousemove", function(d, i, j) { var x = d3.mouse(this)[0], y = d3.mouse(this)[1]; var formatValue = d3.format(".1f"), value = formatValue(yScale.invert(y)); focus.attr("transform", "translate(" + x + "," + y + ")"); focus.select("text").text(value); }) .transition().duration(500).ease("linear").each("start", function() { d3.select(this).attr({ stroke: "white" }); }) .attr({ "d": line(data), stroke: INSIGHT.palette[seqid], "stroke-width": 2, "fill-opacity": 0.0, "pointer-events": "stroke" }); } function drawLines(lines, xScale, yScale) { "use strict"; lines.append("line") .transition().duration(500).ease("linear").each("start", function() { d3.select(this).attr({ stroke: "white" }); }) .attr({ x1: function(d) { return xScale(d[0]); }, y1: function(d) { return yScale(d[1]); }, x2: function(d) { return xScale(d[2]); }, y2: function(d) { return yScale(d[3]); }, stroke: "#cccccc", "shape-rendering": "crispEdges" }); } function drawAxes(xScale, yScale, xTickValues) { "use strict"; var areaPadding = 10; var xAxis = d3.svg.axis() .scale(xScale) .orient("bottom") .tickValues(xTickValues); d3.select("svg").append("g") .attr("class", "axis") .attr("transform", "translate(0, " + (INSIGHT.height - INSIGHT.smallPadding + areaPadding) + ")") .call(xAxis); var yAxis = d3.svg.axis() .scale(yScale) .orient("left") .ticks(5); d3.select("svg").append("g") .attr("class", "axis") .attr("transform", "translate(" + (INSIGHT.largePadding - areaPadding) + ", 0)") .call(yAxis); } function drawLegendTitle(title) { "use strict"; d3.select("svg").append("g").append("text") .transition().duration(500).ease("linear").each("start", function() { d3.select(this).attr({ fill: "white" }); }) .text(title + ":") .attr({ x: INSIGHT.largePadding + 5, y: (INSIGHT.smallPadding + INSIGHT.fontHeight) / 2, "font-size": INSIGHT.fontHeight, fill: "black" }); } function drawLegend(legend, legendPadding, legendInterval) { "use strict"; legend.append("text") .transition().duration(500).ease("linear").each("start", function() { d3.select(this).attr({ fill: "white" }); }) .text(function(d) { return d; }) .attr({ x: function(d, i) { return INSIGHT.largePadding + legendPadding + i * legendInterval; }, y: (INSIGHT.smallPadding + INSIGHT.fontHeight) / 2, "font-size": INSIGHT.fontHeight, "font-weight": "bold", fill: function(d, i) { return INSIGHT.palette[i]; } }); } function drawWarning() { "use strict"; d3.select("svg").append("text") .text("No data") .attr({ x: INSIGHT.width / 2 - 50, y: INSIGHT.height / 2, class: "warning" }); } function resetCharts() { "use strict"; d3.selectAll("circle").remove(); d3.selectAll("line").remove(); d3.selectAll("g").remove(); d3.selectAll("path").remove(); d3.selectAll("text").remove(); } function drawScatterPlot(data, vary_by) { "use strict"; /******************************** MIN MAX *********************************/ var xMin = Number.MAX_VALUE, xMax = Number.MIN_VALUE, yMax = Number.MIN_VALUE; Object.keys(data).forEach(function(key) { xMin = Math.min(xMin, d3.min(data[key], function(d) { return d[0]; })); xMax = Math.max(xMax, d3.max(data[key], function(d) { return d[0]; })); yMax = Math.max(yMax, d3.max(data[key], function(d) { return d[1]; })); }); /********************************* SCALES *********************************/ var yScale = d3.scale.linear() .domain([0, yMax]) .range([INSIGHT.height - INSIGHT.smallPadding, INSIGHT.smallPadding]); var xScale; if (isNaN(xMin) || isNaN(xMax)) { xScale = d3.scale.ordinal() .range([INSIGHT.largePadding, INSIGHT.width - INSIGHT.smallPadding]); } else { xScale = d3.scale.linear() .domain([xMin, xMax]) .range([INSIGHT.largePadding, INSIGHT.width - INSIGHT.smallPadding]); } /********************************** TICKS *********************************/ var yTickValues = yScale.ticks(5); var xTickValues = []; Object.keys(data).forEach(function(key) { for (var i=0, l=data[key].length; i < l; i++) { if (xTickValues.indexOf(data[key][i][0] === -1)) { xTickValues.push(data[key][i][0]); } } }); /********************************** GRID **********************************/ var linesXY = [[xMax, yMax, xMin, yMax]]; for (var i=0, l=xTickValues.length; i<l; i++) { linesXY.push([xTickValues[i], 0, xTickValues[i], yMax]); } for (i=0, l=yTickValues.length; i<l; i++) { linesXY.push([xMin, yTickValues[i], xMax, yTickValues[i]]); } var lines = d3.select("svg").selectAll("line") .data(linesXY) .enter(); drawLines(lines, xScale, yScale); /****************************** DATA POINTS *******************************/ var circles = d3.select("svg").selectAll("circle"), seqid = 0, legendInterval = 0; Object.keys(data).forEach(function(key) { drawSplines(data[key], xScale, yScale, seqid); drawDataPoints(circles.data(data[key]).enter(), xScale, yScale, seqid); legendInterval = Math.max((key.length + 1) * INSIGHT.fontWidth, legendInterval); seqid++; }); if (vary_by !== null) { var legend = d3.select("svg").append("g").selectAll("text"), legendPadding = (vary_by.length + 1) * INSIGHT.fontWidth; drawLegendTitle(vary_by); drawLegend(legend.data(Object.keys(data)).enter(), legendPadding, legendInterval); } /********************************** AXES **********************************/ drawAxes(xScale, yScale, xTickValues); /**************************************************************************/ } $(document).ready(function(){ "use strict"; drawBase(); });
use focus for data points as well Change-Id: I513fdd4983aa3ee81889fb14c7ca2be04415944e Reviewed-on: http://review.couchbase.org/32923 Reviewed-by: Pavel Paulau <[email protected]> Tested-by: Pavel Paulau <[email protected]>
webapp/cbmonitor/static/js/insight.js
use focus for data points as well
<ide><path>ebapp/cbmonitor/static/js/insight.js <ide> } <ide> <ide> <add>function addFocus(seqid) { <add> "use strict"; <add> <add> var focus = d3.select("svg").append("g") <add> .attr("class", "focus") <add> .style("display", "none"); <add> focus.append("text").attr({ <add> dx: "15px", dy: "25px", <add> fill: INSIGHT.palette[seqid] <add> }); <add> return focus; <add>} <add> <add> <add>function showFocus(focus, obj, yScale) { <add> "use strict"; <add> <add> var x = d3.mouse(obj)[0], <add> y = d3.mouse(obj)[1], <add> formatValue = d3.format(".1f"), <add> value = formatValue(yScale.invert(y)); <add> focus <add> .style("display", null) <add> .attr("transform", "translate(" + x + "," + y + ")") <add> .select("text").text(value); <add>} <add> <add> <ide> function drawDataPoints(circles, xScale, yScale, seqid) { <ide> "use strict"; <add> <add> var focus = addFocus(seqid); <ide> <ide> circles <ide> .append("circle") <ide> .on("mouseover", function() { <add> showFocus(focus, this, yScale); <ide> d3.select(this).transition().duration(200) <ide> .attr({ r: 7 }); <ide> }) <ide> .on("mouseout", function() { <add> focus.style("display", "none"); <ide> d3.select(this).transition().duration(200) <ide> .attr({ r: 5 }); <ide> }) <ide> .y(function(d) { return yScale(d[1]); }) <ide> .interpolate("cardinal"); <ide> <del> var focus = d3.select("svg").append("g") <del> .attr("class", "focus") <del> .style("display", "none"); <del> <del> focus.append("text") <del> .attr({ <del> dx: "15px", dy: "25px", <del> fill: INSIGHT.palette[seqid] <del> }); <add> var focus = addFocus(seqid); <ide> <ide> d3.select("svg") <ide> .append("path") <del> .on("mouseover", function() { focus.style("display", null); }) <add> .on("mouseover", function() { showFocus(focus, this, yScale); }) <ide> .on("mouseout", function() { focus.style("display", "none"); }) <del> .on("mousemove", function(d, i, j) { <del> var x = d3.mouse(this)[0], <del> y = d3.mouse(this)[1]; <del> var formatValue = d3.format(".1f"), <del> value = formatValue(yScale.invert(y)); <del> focus.attr("transform", "translate(" + x + "," + y + ")"); <del> focus.select("text").text(value); <del> }) <ide> .transition().duration(500).ease("linear").each("start", function() { <ide> d3.select(this).attr({ stroke: "white" }); <ide> })
Java
lgpl-2.1
faed4c473d6bbf44a3e5e949aaad2eb39eece36a
0
exedio/copernica,exedio/copernica,exedio/copernica
package injection; import injection.InjectorParseException; import java.io.IOException; import java.io.Writer; import java.util.*; import java.lang.reflect.Modifier; import persistence.AttributeValue; import persistence.ConstraintViolationException; import persistence.NotNullViolationException; import persistence.ReadOnlyViolationException; import persistence.SystemException; import persistence.Type; import persistence.UniqueViolationException; import tools.ClassComparator; public final class Instrumentor implements InjectionConsumer { private final Writer output; /** * Holds several properties of the class currently * worked on. */ private JavaClass class_state=null; /** * Collects the class states of outer classes, * when operating on a inner class. * @see #class_state * @element-type InstrumentorClass */ private ArrayList class_state_stack=new ArrayList(); protected final String lineSeparator; /** * The last file level doccomment that was read. */ private String lastFileDocComment = null; public Instrumentor(Writer output) { this.output=output; final String systemLineSeparator = System.getProperty("line.separator"); if(systemLineSeparator==null) { System.out.println("warning: property \"line.separator\" is null, using LF (unix style)."); lineSeparator = "\n"; } else lineSeparator = systemLineSeparator; } public void onPackage(JavaFile javafile) throws InjectorParseException { } public void onImport(String importname) { } private boolean discardnextfeature=false; /** * Tag name for persistent classes. */ private static final String PERSISTENT_CLASS = "persistent"; /** * Tag name for persistent attributes. */ private static final String PERSISTENT_ATTRIBUTE = PERSISTENT_CLASS; /** * Tag name for unique attributes. */ private static final String UNIQUE_ATTRIBUTE = "unique"; /** * Tag name for read-only attributes. */ private static final String READ_ONLY_ATTRIBUTE = "read-only"; /** * Tag name for not-null attributes. */ private static final String NOT_NULL_ATTRIBUTE = "not-null"; /** * Tag name for one qualifier of qualified attributes. */ private static final String ATTRIBUTE_QUALIFIER = "qualifier"; /** * All generated class features get this doccomment tag. */ private static final String GENERATED = "generated"; private List uniqueConstraints=null; private void handleClassComment(final JavaClass jc, final String docComment) { if(containsTag(docComment, PERSISTENT_CLASS)) jc.setPersistent(); final String uniqueConstraint = Injector.findWholeDocTag(docComment, UNIQUE_ATTRIBUTE); if(uniqueConstraint!=null) { if(uniqueConstraints==null) uniqueConstraints = new ArrayList(); uniqueConstraints.add(uniqueConstraint); } } public void onClass(final JavaClass jc) { //System.out.println("onClass("+jc.getName()+")"); discardnextfeature=false; class_state_stack.add(class_state); class_state=jc; if(lastFileDocComment != null) { handleClassComment(jc, lastFileDocComment); lastFileDocComment = null; } } private static final String lowerCamelCase(final String s) { final char first = s.charAt(0); if(Character.isLowerCase(first)) return s; else return Character.toLowerCase(first) + s.substring(1); } private void writeParameterDeclarationList(final Collection parameters) throws IOException { if(parameters!=null) { boolean first = true; for(Iterator i = parameters.iterator(); i.hasNext(); ) { if(first) first = false; else output.write(','); final String parameter = (String)i.next(); output.write("final "); output.write(parameter); output.write(' '); output.write(lowerCamelCase(parameter)); } } } private void writeParameterCallList(final Collection parameters) throws IOException { if(parameters!=null) { boolean first = true; for(Iterator i = parameters.iterator(); i.hasNext(); ) { if(first) first = false; else output.write(','); final String parameter = (String)i.next(); output.write(lowerCamelCase(parameter)); } } } private void writeThrowsClause(final Collection exceptions) throws IOException { if(!exceptions.isEmpty()) { output.write(" throws "); boolean first = true; for(final Iterator i = exceptions.iterator(); i.hasNext(); ) { if(first) first = false; else output.write(','); output.write(((Class)i.next()).getName()); } } } private final void writeCommentHeader() throws IOException { output.write("/**"); output.write(lineSeparator); output.write(lineSeparator); output.write("\t **"); output.write(lineSeparator); } private final void writeCommentFooter() throws IOException { output.write("\t * @"+GENERATED); output.write(lineSeparator); output.write("\t *"); output.write(lineSeparator); output.write(" */"); } public void writeConstructor(final JavaClass javaClass) throws IOException { final List initialAttributes = javaClass.getInitialAttributes(); writeCommentHeader(); output.write("\t * This is a generated constructor."); for(Iterator i = initialAttributes.iterator(); i.hasNext(); ) { final JavaAttribute initialAttribute = (JavaAttribute)i.next(); output.write(lineSeparator); output.write("\t * @param initial"); output.write(initialAttribute.getCamelCaseName()); output.write(" the intial value for attribute {@link #"); output.write(initialAttribute.getName()); output.write("}."); } output.write(lineSeparator); writeCommentFooter(); output.write(Modifier.toString(javaClass.getModifiers() & (Modifier.PUBLIC | Modifier.PROTECTED | Modifier.PRIVATE))); output.write(' '); output.write(javaClass.getName()); output.write('('); boolean first = true; for(Iterator i = initialAttributes.iterator(); i.hasNext(); ) { if(first) first = false; else output.write(','); final JavaAttribute initialAttribute = (JavaAttribute)i.next(); output.write("final "); output.write(initialAttribute.getPersistentType()); output.write(" initial"); output.write(initialAttribute.getCamelCaseName()); } output.write(')'); writeThrowsClause(javaClass.getContructorExceptions()); output.write(lineSeparator); output.write("\t{"); output.write(lineSeparator); output.write("\t\tsuper(new "+AttributeValue.class.getName()+"[]{"); output.write(lineSeparator); for(Iterator i = initialAttributes.iterator(); i.hasNext(); ) { final JavaAttribute initialAttribute = (JavaAttribute)i.next(); output.write("\t\t\tnew "+AttributeValue.class.getName()+"("); output.write(initialAttribute.getName()); output.write(",initial"); output.write(initialAttribute.getCamelCaseName()); output.write("),"); output.write(lineSeparator); } output.write("\t\t});"); output.write(lineSeparator); output.write("\t}"); } private void writeAccessMethods(final JavaAttribute persistentAttribute) throws IOException { final String methodModifiers = Modifier.toString(persistentAttribute.getMethodModifiers()); final String type = persistentAttribute.getPersistentType(); final List qualifiers = persistentAttribute.getQualifiers(); // getter writeCommentHeader(); output.write("\t * Returns the value of the persistent attribute {@link #"); output.write(persistentAttribute.getName()); output.write("}."); output.write(lineSeparator); writeCommentFooter(); output.write(methodModifiers); output.write(' '); output.write(type); output.write(" get"); output.write(persistentAttribute.getCamelCaseName()); output.write('('); writeParameterDeclarationList(qualifiers); output.write(')'); output.write(lineSeparator); output.write("\t{"); output.write(lineSeparator); writeGetterBody(output, persistentAttribute); output.write("\t}"); // setter if(!persistentAttribute.isReadOnly()) { writeCommentHeader(); output.write("\t * Sets a new value for the persistent attribute {@link #"); output.write(persistentAttribute.getName()); output.write("}."); output.write(lineSeparator); writeCommentFooter(); output.write(methodModifiers); output.write(" void set"); output.write(persistentAttribute.getCamelCaseName()); output.write('('); if(qualifiers!=null) { writeParameterDeclarationList(qualifiers); output.write(','); } output.write("final "); output.write(type); output.write(' '); output.write(persistentAttribute.getName()); output.write(')'); writeThrowsClause(persistentAttribute.getSetterExceptions()); output.write(lineSeparator); output.write("\t{"); output.write(lineSeparator); writeSetterBody(output, persistentAttribute); output.write("\t}"); } } private void writeUniqueFinder(final JavaAttribute[] persistentAttributes) throws IOException, InjectorParseException { int modifiers = -1; for(int i=0; i<persistentAttributes.length; i++) { if(modifiers==-1) modifiers = persistentAttributes[i].getMethodModifiers(); else { if(modifiers!=persistentAttributes[i].getMethodModifiers()) throw new InjectorParseException("Tried to write unique finder and found attribues with different modifiers"); } } final String methodModifiers = Modifier.toString(modifiers|Modifier.STATIC); final String className = persistentAttributes[0].getParent().getName(); writeCommentHeader(); output.write("\t * Finds a "); output.write(lowerCamelCase(className)); output.write(" by it's unique attributes"); for(int i=0; i<persistentAttributes.length; i++) { output.write(lineSeparator); output.write("\t * @param "); output.write(persistentAttributes[i].getName()); output.write(" shall be equal to attribute {@link #"); output.write(persistentAttributes[i].getName()); output.write("}."); } output.write(lineSeparator); writeCommentFooter(); output.write(methodModifiers); output.write(' '); output.write(className); boolean first=true; for(int i=0; i<persistentAttributes.length; i++) { if(first) { output.write(" findBy"); first = false; } else output.write("And"); output.write(persistentAttributes[i].getCamelCaseName()); } output.write('('); final Set qualifiers = new HashSet(); for(int i=0; i<persistentAttributes.length; i++) { if(i>0) output.write(','); final JavaAttribute persistentAttribute = (JavaAttribute)persistentAttributes[i]; if(persistentAttribute.getQualifiers() != null) qualifiers.addAll(persistentAttribute.getQualifiers()); output.write("final "); output.write(persistentAttribute.getPersistentType()); output.write(' '); output.write(persistentAttribute.getName()); } if(!qualifiers.isEmpty()) { output.write(','); writeParameterDeclarationList(qualifiers); } output.write(')'); output.write(lineSeparator); output.write("\t{"); output.write(lineSeparator); output.write("\t\treturn null;"); output.write(lineSeparator); output.write("\t}"); } private final void writeType(final JavaClass javaClass) throws IOException { writeCommentHeader(); output.write("\t * The persistent type information for "); output.write(lowerCamelCase(javaClass.getName())); output.write("."); output.write(lineSeparator); writeCommentFooter(); output.write("public static final "+Type.class.getName()+" TYPE = "); output.write(lineSeparator); output.write("\t\tnew "+Type.class.getName()+"("); output.write(lineSeparator); output.write("\t\t\t"); output.write(javaClass.getName()); output.write(".class,"); output.write(lineSeparator); output.write("\t\t\tnew Attribute[]{"); output.write(lineSeparator); for(Iterator i = javaClass.getPersistentAttributes().iterator(); i.hasNext(); ) { final JavaAttribute persistentAttribute = (JavaAttribute)i.next(); output.write("\t\t\t\t"); output.write(persistentAttribute.getName()); output.write(','); output.write(lineSeparator); } output.write("\t\t\t},"); output.write(lineSeparator); output.write("\t\t\tnew Runnable()"); output.write(lineSeparator); output.write("\t\t\t{"); output.write(lineSeparator); output.write("\t\t\t\tpublic void run()"); output.write(lineSeparator); output.write("\t\t\t\t{"); output.write(lineSeparator); for(Iterator i = javaClass.getPersistentAttributes().iterator(); i.hasNext(); ) { final JavaAttribute persistentAttribute = (JavaAttribute)i.next(); output.write("\t\t\t\t\t"); output.write(persistentAttribute.getName()); output.write(".initialize(\""); output.write(persistentAttribute.getName()); output.write("\","); output.write(persistentAttribute.isReadOnly() ? "true": "false"); output.write(','); output.write(persistentAttribute.isNotNull() ? "true": "false"); //private List qualifiers = null; output.write(");"); output.write(lineSeparator); } output.write("\t\t\t\t}"); output.write(lineSeparator); output.write("\t\t\t}"); output.write(lineSeparator); output.write("\t\t)"); output.write(lineSeparator); output.write(";"); } public void onClassEnd(JavaClass jc) throws IOException, InjectorParseException { if(uniqueConstraints != null) { for( final Iterator i=uniqueConstraints.iterator(); i.hasNext(); ) { final String uniqueConstraint=(String)i.next(); final List attributes = new ArrayList(); for(final StringTokenizer t=new StringTokenizer(uniqueConstraint, " "); t.hasMoreTokens(); ) { final String attributeName = t.nextToken(); final JavaAttribute ja = jc.getPersistentAttribute(attributeName); if(ja==null) throw new InjectorParseException("Attribute with name "+attributeName+" does not exist!"); attributes.add(ja); } if(attributes.isEmpty()) throw new InjectorParseException("No attributes found in unique constraint "+uniqueConstraint); jc.makeUnique((JavaAttribute[])attributes.toArray(new JavaAttribute[]{})); } } //System.out.println("onClassEnd("+jc.getName()+")"); if(!jc.isInterface() && jc.isPersistent()) { writeConstructor(jc); for(final Iterator i = jc.getPersistentAttributes().iterator(); i.hasNext(); ) { // write setter/getter methods final JavaAttribute persistentAttribute = (JavaAttribute)i.next(); writeAccessMethods(persistentAttribute); } for(final Iterator i = jc.getUniqueConstraints().iterator(); i.hasNext(); ) { // write unique finder methods final JavaAttribute[] persistentAttributes = (JavaAttribute[])i.next(); writeUniqueFinder(persistentAttributes); } writeType(jc); } if(class_state!=jc) throw new RuntimeException(); class_state=(JavaClass)(class_state_stack.remove(class_state_stack.size()-1)); } public void onBehaviourHeader(JavaBehaviour jb) throws java.io.IOException { output.write(jb.getLiteral()); } public void onAttributeHeader(JavaAttribute ja) { } public void onClassFeature(final JavaFeature jf, final String docComment) throws IOException, InjectorParseException { //System.out.println("onClassFeature("+jf.getName()+" "+docComment+")"); if(!class_state.isInterface()) { if(jf instanceof JavaAttribute && Modifier.isFinal(jf.getModifiers()) && Modifier.isStatic(jf.getModifiers()) && !discardnextfeature && containsTag(docComment, PERSISTENT_ATTRIBUTE)) { final String type = jf.getType(); final String persistentType; if("IntegerAttribute".equals(type)) persistentType = "Integer"; else if("StringAttribute".equals(type)) persistentType = "String"; else if("ItemAttribute".equals(type)) { persistentType = Injector.findDocTag(docComment, PERSISTENT_ATTRIBUTE); } else throw new RuntimeException(); final JavaAttribute ja = (JavaAttribute)jf; ja.makePersistent(persistentType); if(containsTag(docComment, UNIQUE_ATTRIBUTE)) ja.getParent().makeUnique(new JavaAttribute[]{ja}); if(containsTag(docComment, READ_ONLY_ATTRIBUTE)) ja.makeReadOnly(); if(containsTag(docComment, NOT_NULL_ATTRIBUTE)) ja.makeNotNull(); final String qualifier = Injector.findDocTag(docComment, ATTRIBUTE_QUALIFIER); if(qualifier!=null) ja.makeQualified(Collections.singletonList(qualifier)); } } discardnextfeature=false; } public boolean onDocComment(String docComment) throws IOException { //System.out.println("onDocComment("+docComment+")"); if(containsTag(docComment, GENERATED)) { discardnextfeature=true; return false; } else { output.write(docComment); return true; } } public void onFileDocComment(String docComment) throws IOException { //System.out.println("onFileDocComment("+docComment+")"); output.write(docComment); if (class_state != null) { // handle doccomment immediately handleClassComment(class_state, docComment); } else { // remember to be handled as soon as we know what class we're talking about lastFileDocComment = docComment; } } public void onFileEnd() { if(!class_state_stack.isEmpty()) throw new RuntimeException(); } private static final boolean containsTag(final String docComment, final String tagName) { return docComment!=null && docComment.indexOf('@'+tagName)>=0 ; } // ----------------- methods for a new interface abstracting the persistence // ----------------- implementation used, e.g. EJB. /** * Identation contract: * This methods is called, when output stream is immediatly after a line break, * and it should return the output stream after immediatly after a line break. * This means, doing nothing fullfils the contract. */ private void writeGetterBody(final Writer output, final JavaAttribute attribute) throws IOException { output.write("\t\treturn ("); output.write(attribute.getPersistentType()); output.write(")getAttribute(this."); output.write(attribute.getName()); final List qualifiers = attribute.getQualifiers(); if(qualifiers!=null) { output.write(",new Object[]{"); writeParameterCallList(qualifiers); output.write('}'); } output.write(");"); output.write(lineSeparator); } /** * Identation contract: * This methods is called, when output stream is immediatly after a line break, * and it should return the output stream after immediatly after a line break. * This means, doing nothing fullfils the contract. */ private void writeSetterBody(final Writer output, final JavaAttribute attribute) throws IOException { if(!attribute.isPartOfUniqueConstraint() || (attribute.getQualifiers()==null && (!attribute.isReadOnly() || !attribute.isNotNull()))) { output.write("\t\ttry"); output.write(lineSeparator); output.write("\t\t{"); output.write(lineSeparator); output.write('\t'); } output.write("\t\tsetAttribute(this."); output.write(attribute.getName()); final List qualifiers = attribute.getQualifiers(); if(qualifiers!=null) { output.write(",new Object[]{"); writeParameterCallList(qualifiers); output.write('}'); } output.write(','); output.write(attribute.getName()); output.write(");"); output.write(lineSeparator); if(!attribute.isPartOfUniqueConstraint() || (attribute.getQualifiers()==null && (!attribute.isReadOnly() || !attribute.isNotNull()))) { output.write("\t\t}"); output.write(lineSeparator); if(!attribute.isPartOfUniqueConstraint()) writeViolationExceptionCatchClause(output, UniqueViolationException.class); if(attribute.getQualifiers()==null && !attribute.isReadOnly()) writeViolationExceptionCatchClause(output, ReadOnlyViolationException.class); if(attribute.getQualifiers()==null && !attribute.isNotNull()) writeViolationExceptionCatchClause(output, NotNullViolationException.class); } } private void writeViolationExceptionCatchClause(final Writer output, final Class exceptionClass) throws IOException { output.write("\t\tcatch("+exceptionClass.getName()+" e)"); output.write(lineSeparator); output.write("\t\t{"); output.write(lineSeparator); output.write("\t\t\tthrow new "+SystemException.class.getName()+"(e);"); output.write(lineSeparator); output.write("\t\t}"); output.write(lineSeparator); } }
instrument/src/com/exedio/cope/instrument/Instrumentor.java
package injection; import injection.InjectorParseException; import java.io.IOException; import java.io.Writer; import java.util.*; import java.lang.reflect.Modifier; import persistence.AttributeValue; import persistence.ConstraintViolationException; import persistence.NotNullViolationException; import persistence.ReadOnlyViolationException; import persistence.SystemException; import persistence.Type; import persistence.UniqueViolationException; import tools.ClassComparator; public final class Instrumentor implements InjectionConsumer { private final Writer output; /** * Holds several properties of the class currently * worked on. */ private JavaClass class_state=null; /** * Collects the class states of outer classes, * when operating on a inner class. * @see #class_state * @element-type InstrumentorClass */ private ArrayList class_state_stack=new ArrayList(); protected final String lineSeparator; /** * The last file level doccomment that was read. */ private String lastFileDocComment = null; public Instrumentor(Writer output) { this.output=output; final String systemLineSeparator = System.getProperty("line.separator"); if(systemLineSeparator==null) { System.out.println("warning: property \"line.separator\" is null, using LF (unix style)."); lineSeparator = "\n"; } else lineSeparator = systemLineSeparator; } public void onPackage(JavaFile javafile) throws InjectorParseException { } public void onImport(String importname) { } private boolean discardnextfeature=false; /** * Tag name for persistent classes. */ private static final String PERSISTENT_CLASS = "persistent"; /** * Tag name for persistent attributes. */ private static final String PERSISTENT_ATTRIBUTE = PERSISTENT_CLASS; /** * Tag name for unique attributes. */ private static final String UNIQUE_ATTRIBUTE = "unique"; /** * Tag name for read-only attributes. */ private static final String READ_ONLY_ATTRIBUTE = "read-only"; /** * Tag name for not-null attributes. */ private static final String NOT_NULL_ATTRIBUTE = "not-null"; /** * Tag name for one qualifier of qualified attributes. */ private static final String ATTRIBUTE_QUALIFIER = "qualifier"; /** * All generated class features get this doccomment tag. */ private static final String GENERATED = "generated"; private List uniqueConstraints=null; private void handleClassComment(final JavaClass jc, final String docComment) { if(containsTag(docComment, PERSISTENT_CLASS)) jc.setPersistent(); final String uniqueConstraint = Injector.findWholeDocTag(docComment, UNIQUE_ATTRIBUTE); if(uniqueConstraint!=null) { if(uniqueConstraints==null) uniqueConstraints = new ArrayList(); uniqueConstraints.add(uniqueConstraint); } } public void onClass(final JavaClass jc) { //System.out.println("onClass("+jc.getName()+")"); discardnextfeature=false; class_state_stack.add(class_state); class_state=jc; if(lastFileDocComment != null) { handleClassComment(jc, lastFileDocComment); lastFileDocComment = null; } } private static final String lowerCamelCase(final String s) { final char first = s.charAt(0); if(Character.isLowerCase(first)) return s; else return Character.toLowerCase(first) + s.substring(1); } private void writeParameterDeclarationList(final Collection parameters) throws IOException { if(parameters!=null) { boolean first = true; for(Iterator i = parameters.iterator(); i.hasNext(); ) { if(first) first = false; else output.write(','); final String parameter = (String)i.next(); output.write("final "); output.write(parameter); output.write(' '); output.write(lowerCamelCase(parameter)); } } } private void writeParameterCallList(final Collection parameters) throws IOException { if(parameters!=null) { boolean first = true; for(Iterator i = parameters.iterator(); i.hasNext(); ) { if(first) first = false; else output.write(','); final String parameter = (String)i.next(); output.write(lowerCamelCase(parameter)); } } } private void writeThrowsClause(final Collection exceptions) throws IOException { if(!exceptions.isEmpty()) { output.write(" throws "); boolean first = true; for(final Iterator i = exceptions.iterator(); i.hasNext(); ) { if(first) first = false; else output.write(','); output.write(((Class)i.next()).getName()); } } } private final void writeCommentHeader() throws IOException { output.write("/**"); output.write(lineSeparator); output.write(lineSeparator); output.write("\t **"); output.write(lineSeparator); } private final void writeCommentFooter() throws IOException { output.write("\t * @"+GENERATED); output.write(lineSeparator); output.write("\t *"); output.write(lineSeparator); output.write(" */"); } public void writeConstructor(final JavaClass javaClass) throws IOException { final List initialAttributes = javaClass.getInitialAttributes(); writeCommentHeader(); output.write("\t * This is a generated constructor."); for(Iterator i = initialAttributes.iterator(); i.hasNext(); ) { final JavaAttribute initialAttribute = (JavaAttribute)i.next(); output.write(lineSeparator); output.write("\t * @param initial"); output.write(initialAttribute.getCamelCaseName()); output.write(" the intial value for attribute {@link #"); output.write(initialAttribute.getName()); output.write("}."); } output.write(lineSeparator); writeCommentFooter(); output.write(Modifier.toString(javaClass.getModifiers() & (Modifier.PUBLIC | Modifier.PROTECTED | Modifier.PRIVATE))); output.write(' '); output.write(javaClass.getName()); output.write('('); boolean first = true; for(Iterator i = initialAttributes.iterator(); i.hasNext(); ) { if(first) first = false; else output.write(','); final JavaAttribute initialAttribute = (JavaAttribute)i.next(); output.write("final "); output.write(initialAttribute.getPersistentType()); output.write(" initial"); output.write(initialAttribute.getCamelCaseName()); } output.write(')'); writeThrowsClause(javaClass.getContructorExceptions()); output.write(lineSeparator); output.write("\t{"); output.write(lineSeparator); output.write("\t\tsuper(new "+AttributeValue.class.getName()+"[]{"); output.write(lineSeparator); for(Iterator i = initialAttributes.iterator(); i.hasNext(); ) { final JavaAttribute initialAttribute = (JavaAttribute)i.next(); output.write("\t\t\tnew "+AttributeValue.class.getName()+"("); output.write(initialAttribute.getName()); output.write(",initial"); output.write(initialAttribute.getCamelCaseName()); output.write("),"); output.write(lineSeparator); } output.write("\t\t});"); output.write(lineSeparator); output.write("\t}"); } private void writeAccessMethods(final JavaAttribute persistentAttribute) throws IOException { final String methodModifiers = Modifier.toString(persistentAttribute.getMethodModifiers()); final String type = persistentAttribute.getPersistentType(); final List qualifiers = persistentAttribute.getQualifiers(); // getter writeCommentHeader(); output.write("\t * Returns the value of the persistent attribute {@link #"); output.write(persistentAttribute.getName()); output.write("}."); output.write(lineSeparator); writeCommentFooter(); output.write(methodModifiers); output.write(' '); output.write(type); output.write(" get"); output.write(persistentAttribute.getCamelCaseName()); output.write('('); writeParameterDeclarationList(qualifiers); output.write(')'); output.write(lineSeparator); output.write("\t{"); output.write(lineSeparator); writeGetterBody(output, persistentAttribute); output.write("\t}"); // setter writeCommentHeader(); output.write("\t * Sets a new value for the persistent attribute {@link #"); output.write(persistentAttribute.getName()); output.write("}."); output.write(lineSeparator); writeCommentFooter(); output.write(methodModifiers); output.write(" void set"); output.write(persistentAttribute.getCamelCaseName()); output.write('('); if(qualifiers!=null) { writeParameterDeclarationList(qualifiers); output.write(','); } output.write("final "); output.write(type); output.write(' '); output.write(persistentAttribute.getName()); output.write(')'); writeThrowsClause(persistentAttribute.getSetterExceptions()); output.write(lineSeparator); output.write("\t{"); output.write(lineSeparator); writeSetterBody(output, persistentAttribute); output.write("\t}"); } private void writeUniqueFinder(final JavaAttribute[] persistentAttributes) throws IOException, InjectorParseException { int modifiers = -1; for(int i=0; i<persistentAttributes.length; i++) { if(modifiers==-1) modifiers = persistentAttributes[i].getMethodModifiers(); else { if(modifiers!=persistentAttributes[i].getMethodModifiers()) throw new InjectorParseException("Tried to write unique finder and found attribues with different modifiers"); } } final String methodModifiers = Modifier.toString(modifiers|Modifier.STATIC); final String className = persistentAttributes[0].getParent().getName(); writeCommentHeader(); output.write("\t * Finds a "); output.write(lowerCamelCase(className)); output.write(" by it's unique attributes"); for(int i=0; i<persistentAttributes.length; i++) { output.write(lineSeparator); output.write("\t * @param "); output.write(persistentAttributes[i].getName()); output.write(" shall be equal to attribute {@link #"); output.write(persistentAttributes[i].getName()); output.write("}."); } output.write(lineSeparator); writeCommentFooter(); output.write(methodModifiers); output.write(' '); output.write(className); boolean first=true; for(int i=0; i<persistentAttributes.length; i++) { if(first) { output.write(" findBy"); first = false; } else output.write("And"); output.write(persistentAttributes[i].getCamelCaseName()); } output.write('('); final Set qualifiers = new HashSet(); for(int i=0; i<persistentAttributes.length; i++) { if(i>0) output.write(','); final JavaAttribute persistentAttribute = (JavaAttribute)persistentAttributes[i]; if(persistentAttribute.getQualifiers() != null) qualifiers.addAll(persistentAttribute.getQualifiers()); output.write("final "); output.write(persistentAttribute.getPersistentType()); output.write(' '); output.write(persistentAttribute.getName()); } if(!qualifiers.isEmpty()) { output.write(','); writeParameterDeclarationList(qualifiers); } output.write(')'); output.write(lineSeparator); output.write("\t{"); output.write(lineSeparator); output.write("\t\treturn null;"); output.write(lineSeparator); output.write("\t}"); } private final void writeType(final JavaClass javaClass) throws IOException { writeCommentHeader(); output.write("\t * The persistent type information for "); output.write(lowerCamelCase(javaClass.getName())); output.write("."); output.write(lineSeparator); writeCommentFooter(); output.write("public static final "+Type.class.getName()+" TYPE = "); output.write(lineSeparator); output.write("\t\tnew "+Type.class.getName()+"("); output.write(lineSeparator); output.write("\t\t\t"); output.write(javaClass.getName()); output.write(".class,"); output.write(lineSeparator); output.write("\t\t\tnew Attribute[]{"); output.write(lineSeparator); for(Iterator i = javaClass.getPersistentAttributes().iterator(); i.hasNext(); ) { final JavaAttribute persistentAttribute = (JavaAttribute)i.next(); output.write("\t\t\t\t"); output.write(persistentAttribute.getName()); output.write(','); output.write(lineSeparator); } output.write("\t\t\t},"); output.write(lineSeparator); output.write("\t\t\tnew Runnable()"); output.write(lineSeparator); output.write("\t\t\t{"); output.write(lineSeparator); output.write("\t\t\t\tpublic void run()"); output.write(lineSeparator); output.write("\t\t\t\t{"); output.write(lineSeparator); for(Iterator i = javaClass.getPersistentAttributes().iterator(); i.hasNext(); ) { final JavaAttribute persistentAttribute = (JavaAttribute)i.next(); output.write("\t\t\t\t\t"); output.write(persistentAttribute.getName()); output.write(".initialize(\""); output.write(persistentAttribute.getName()); output.write("\","); output.write(persistentAttribute.isReadOnly() ? "true": "false"); output.write(','); output.write(persistentAttribute.isNotNull() ? "true": "false"); //private List qualifiers = null; output.write(");"); output.write(lineSeparator); } output.write("\t\t\t\t}"); output.write(lineSeparator); output.write("\t\t\t}"); output.write(lineSeparator); output.write("\t\t)"); output.write(lineSeparator); output.write(";"); } public void onClassEnd(JavaClass jc) throws IOException, InjectorParseException { if(uniqueConstraints != null) { for( final Iterator i=uniqueConstraints.iterator(); i.hasNext(); ) { final String uniqueConstraint=(String)i.next(); final List attributes = new ArrayList(); for(final StringTokenizer t=new StringTokenizer(uniqueConstraint, " "); t.hasMoreTokens(); ) { final String attributeName = t.nextToken(); final JavaAttribute ja = jc.getPersistentAttribute(attributeName); if(ja==null) throw new InjectorParseException("Attribute with name "+attributeName+" does not exist!"); attributes.add(ja); } if(attributes.isEmpty()) throw new InjectorParseException("No attributes found in unique constraint "+uniqueConstraint); jc.makeUnique((JavaAttribute[])attributes.toArray(new JavaAttribute[]{})); } } //System.out.println("onClassEnd("+jc.getName()+")"); if(!jc.isInterface() && jc.isPersistent()) { writeConstructor(jc); for(final Iterator i = jc.getPersistentAttributes().iterator(); i.hasNext(); ) { // write setter/getter methods final JavaAttribute persistentAttribute = (JavaAttribute)i.next(); writeAccessMethods(persistentAttribute); } for(final Iterator i = jc.getUniqueConstraints().iterator(); i.hasNext(); ) { // write unique finder methods final JavaAttribute[] persistentAttributes = (JavaAttribute[])i.next(); writeUniqueFinder(persistentAttributes); } writeType(jc); } if(class_state!=jc) throw new RuntimeException(); class_state=(JavaClass)(class_state_stack.remove(class_state_stack.size()-1)); } public void onBehaviourHeader(JavaBehaviour jb) throws java.io.IOException { output.write(jb.getLiteral()); } public void onAttributeHeader(JavaAttribute ja) { } public void onClassFeature(final JavaFeature jf, final String docComment) throws IOException, InjectorParseException { //System.out.println("onClassFeature("+jf.getName()+" "+docComment+")"); if(!class_state.isInterface()) { if(jf instanceof JavaAttribute && Modifier.isFinal(jf.getModifiers()) && Modifier.isStatic(jf.getModifiers()) && !discardnextfeature && containsTag(docComment, PERSISTENT_ATTRIBUTE)) { final String type = jf.getType(); final String persistentType; if("IntegerAttribute".equals(type)) persistentType = "Integer"; else if("StringAttribute".equals(type)) persistentType = "String"; else if("ItemAttribute".equals(type)) { persistentType = Injector.findDocTag(docComment, PERSISTENT_ATTRIBUTE); } else throw new RuntimeException(); final JavaAttribute ja = (JavaAttribute)jf; ja.makePersistent(persistentType); if(containsTag(docComment, UNIQUE_ATTRIBUTE)) ja.getParent().makeUnique(new JavaAttribute[]{ja}); if(containsTag(docComment, READ_ONLY_ATTRIBUTE)) ja.makeReadOnly(); if(containsTag(docComment, NOT_NULL_ATTRIBUTE)) ja.makeNotNull(); final String qualifier = Injector.findDocTag(docComment, ATTRIBUTE_QUALIFIER); if(qualifier!=null) ja.makeQualified(Collections.singletonList(qualifier)); } } discardnextfeature=false; } public boolean onDocComment(String docComment) throws IOException { //System.out.println("onDocComment("+docComment+")"); if(containsTag(docComment, GENERATED)) { discardnextfeature=true; return false; } else { output.write(docComment); return true; } } public void onFileDocComment(String docComment) throws IOException { //System.out.println("onFileDocComment("+docComment+")"); output.write(docComment); if (class_state != null) { // handle doccomment immediately handleClassComment(class_state, docComment); } else { // remember to be handled as soon as we know what class we're talking about lastFileDocComment = docComment; } } public void onFileEnd() { if(!class_state_stack.isEmpty()) throw new RuntimeException(); } private static final boolean containsTag(final String docComment, final String tagName) { return docComment!=null && docComment.indexOf('@'+tagName)>=0 ; } // ----------------- methods for a new interface abstracting the persistence // ----------------- implementation used, e.g. EJB. /** * Identation contract: * This methods is called, when output stream is immediatly after a line break, * and it should return the output stream after immediatly after a line break. * This means, doing nothing fullfils the contract. */ private void writeGetterBody(final Writer output, final JavaAttribute attribute) throws IOException { output.write("\t\treturn ("); output.write(attribute.getPersistentType()); output.write(")getAttribute(this."); output.write(attribute.getName()); final List qualifiers = attribute.getQualifiers(); if(qualifiers!=null) { output.write(",new Object[]{"); writeParameterCallList(qualifiers); output.write('}'); } output.write(");"); output.write(lineSeparator); } /** * Identation contract: * This methods is called, when output stream is immediatly after a line break, * and it should return the output stream after immediatly after a line break. * This means, doing nothing fullfils the contract. */ private void writeSetterBody(final Writer output, final JavaAttribute attribute) throws IOException { if(!attribute.isPartOfUniqueConstraint() || (attribute.getQualifiers()==null && (!attribute.isReadOnly() || !attribute.isNotNull()))) { output.write("\t\ttry"); output.write(lineSeparator); output.write("\t\t{"); output.write(lineSeparator); output.write('\t'); } output.write("\t\tsetAttribute(this."); output.write(attribute.getName()); final List qualifiers = attribute.getQualifiers(); if(qualifiers!=null) { output.write(",new Object[]{"); writeParameterCallList(qualifiers); output.write('}'); } output.write(','); output.write(attribute.getName()); output.write(");"); output.write(lineSeparator); if(!attribute.isPartOfUniqueConstraint() || (attribute.getQualifiers()==null && (!attribute.isReadOnly() || !attribute.isNotNull()))) { output.write("\t\t}"); output.write(lineSeparator); if(!attribute.isPartOfUniqueConstraint()) writeViolationExceptionCatchClause(output, UniqueViolationException.class); if(attribute.getQualifiers()==null && !attribute.isReadOnly()) writeViolationExceptionCatchClause(output, ReadOnlyViolationException.class); if(attribute.getQualifiers()==null && !attribute.isNotNull()) writeViolationExceptionCatchClause(output, NotNullViolationException.class); } } private void writeViolationExceptionCatchClause(final Writer output, final Class exceptionClass) throws IOException { output.write("\t\tcatch("+exceptionClass.getName()+" e)"); output.write(lineSeparator); output.write("\t\t{"); output.write(lineSeparator); output.write("\t\t\tthrow new "+SystemException.class.getName()+"(e);"); output.write(lineSeparator); output.write("\t\t}"); output.write(lineSeparator); } }
bugfix: do not generate setter methods for read-only attributes git-svn-id: 9dbc6da3594b32e13bcf3b3752e372ea5bc7c2cc@112 e7d4fc99-c606-0410-b9bf-843393a9eab7
instrument/src/com/exedio/cope/instrument/Instrumentor.java
bugfix: do not generate setter methods for read-only attributes
<ide><path>nstrument/src/com/exedio/cope/instrument/Instrumentor.java <ide> output.write("\t}"); <ide> <ide> // setter <del> writeCommentHeader(); <del> output.write("\t * Sets a new value for the persistent attribute {@link #"); <del> output.write(persistentAttribute.getName()); <del> output.write("}."); <del> output.write(lineSeparator); <del> writeCommentFooter(); <del> output.write(methodModifiers); <del> output.write(" void set"); <del> output.write(persistentAttribute.getCamelCaseName()); <del> output.write('('); <del> if(qualifiers!=null) <del> { <del> writeParameterDeclarationList(qualifiers); <del> output.write(','); <del> } <del> output.write("final "); <del> output.write(type); <del> output.write(' '); <del> output.write(persistentAttribute.getName()); <del> output.write(')'); <del> writeThrowsClause(persistentAttribute.getSetterExceptions()); <del> output.write(lineSeparator); <del> output.write("\t{"); <del> output.write(lineSeparator); <del> writeSetterBody(output, persistentAttribute); <del> output.write("\t}"); <add> if(!persistentAttribute.isReadOnly()) <add> { <add> writeCommentHeader(); <add> output.write("\t * Sets a new value for the persistent attribute {@link #"); <add> output.write(persistentAttribute.getName()); <add> output.write("}."); <add> output.write(lineSeparator); <add> writeCommentFooter(); <add> output.write(methodModifiers); <add> output.write(" void set"); <add> output.write(persistentAttribute.getCamelCaseName()); <add> output.write('('); <add> if(qualifiers!=null) <add> { <add> writeParameterDeclarationList(qualifiers); <add> output.write(','); <add> } <add> output.write("final "); <add> output.write(type); <add> output.write(' '); <add> output.write(persistentAttribute.getName()); <add> output.write(')'); <add> writeThrowsClause(persistentAttribute.getSetterExceptions()); <add> output.write(lineSeparator); <add> output.write("\t{"); <add> output.write(lineSeparator); <add> writeSetterBody(output, persistentAttribute); <add> output.write("\t}"); <add> } <ide> } <ide> <ide> private void writeUniqueFinder(final JavaAttribute[] persistentAttributes)
Java
apache-2.0
ce9c6304af940514281a3ec094cfac1aadce25a2
0
rover12421/Apktool,HackerTool/Apktool,fromsatellite/Apktool,digshock/android-apktool,admin-zhx/Apktool,370829592/android-apktool,fromsatellite/Apktool,virustotalop/Apktool,zhanwei/android-apktool,zhakui/Apktool,kesuki/Apktool,iAmGhost/brut.apktool,youleyu/android-apktool,fabiand93/Apktool,alipov/Apktool,akhirasip/Apktool,nitinverma/Apktool,CheungSKei/Apktool,alipov/Apktool,Benjamin-Dobell/Apktool,simtel12/Apktool,zhanwei/android-apktool,Klozz/Apktool,nitinverma/Apktool,dankoman30/Apktool,kuter007/android-apktool,blaquee/Apktool,pandazheng/Apktool,harish123400/Apktool,kesuki/Apktool,jasonzhong/Apktool,phhusson/Apktool,androidmchen/Apktool,lovely3x/Apktool,jianglibo/Apktool,bingshi/android-apktool,blaquee/Apktool,bingshi/android-apktool,valery-barysok/Apktool,iBotPeaches/Apktool,kaneawk/Apktool,sawrus/Apktool,KuaiFaMaster/Apktool,yujokang/Apktool,guiyu/android-apktool,asolfre/android-apktool,guiyu/android-apktool,zdzhjx/android-apktool,chenrui2014/Apktool,desword/android-apktool,zhakui/Apktool,rover12421/Apktool,asolfre/android-apktool,yunemr/Apktool,pwelyn/Apktool,tmpgit/Apktool,lnln1111/android-apktool,admin-zhx/Apktool,yunemr/Apktool,ccgreen13/Apktool,Klozz/Apktool,MiCode/brut.apktool,KuaiFaMaster/Apktool,PiR43/Apktool,Yaeger/Apktool,fabiand93/Apktool,chenrui2014/Apktool,lovely3x/Apktool,lczgywzyy/Apktool,lczgywzyy/Apktool,pandazheng/Apktool,jasonzhong/Apktool,desword/android-apktool,akhirasip/Apktool,hongnguyenpro/Apktool,Yaeger/Apktool,valery-barysok/Apktool,berkus/android-apktool,phhusson/Apktool,sawrus/Apktool,draekko/Apktool,zhic5352/Apktool,youleyu/android-apktool,jianglibo/Apktool,kuter007/android-apktool,hongnguyenpro/Apktool,dankoman30/Apktool,Benjamin-Dobell/Apktool,androidmchen/Apktool,lnln1111/android-apktool,yujokang/Apktool,zhic5352/Apktool,simtel12/Apktool,harish123400/Apktool,iBotPeaches/Apktool,virustotalop/Apktool,370829592/android-apktool,kaneawk/Apktool,zdzhjx/android-apktool,draekko/Apktool,CheungSKei/Apktool,PiR43/Apktool,digshock/android-apktool,tmpgit/Apktool,ccgreen13/Apktool,HackerTool/Apktool,berkus/android-apktool,pwelyn/Apktool
/* * Copyright 2010 Ryszard Wiśniewski <[email protected]>. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * under the License. */ package brut.androlib.res; import brut.androlib.AndrolibException; import brut.androlib.err.CantFindFrameworkResException; import brut.androlib.res.data.*; import brut.androlib.res.data.value.ResXmlSerializable; import brut.androlib.res.decoder.*; import brut.androlib.res.util.ExtFile; import brut.androlib.res.util.ExtMXSerializer; import brut.common.BrutException; import brut.directory.*; import brut.util.*; import java.io.*; import java.util.*; import java.util.logging.Logger; import org.apache.commons.io.IOUtils; import org.xmlpull.v1.XmlSerializer; /** * @author Ryszard Wiśniewski <[email protected]> */ final public class AndrolibResources { public ResTable getResTable(ExtFile apkFile) throws AndrolibException { ResTable resTable = new ResTable(this); loadMainPkg(resTable, apkFile); return resTable; } public ResPackage loadMainPkg(ResTable resTable, ExtFile apkFile) throws AndrolibException { LOGGER.info("Loading resource table..."); ResPackage[] pkgs = getResPackagesFromApk(apkFile, resTable); ResPackage pkg = null; switch (pkgs.length) { case 1: pkg = pkgs[0]; break; case 2: if (pkgs[0].getName().equals("android")) { LOGGER.warning("Skipping \"android\" package group"); pkg = pkgs[1]; } break; } if (pkg == null) { throw new AndrolibException( "Arsc files with zero or multiple packages"); } resTable.addPackage(pkg, true); return pkg; } public ResPackage loadFrameworkPkg(ResTable resTable, int id, String frameTag) throws AndrolibException { File apk = getFrameworkApk(id, frameTag); LOGGER.info("Loading resource table from file: " + apk); ResPackage[] pkgs = getResPackagesFromApk(new ExtFile(apk), resTable); if (pkgs.length != 1) { throw new AndrolibException( "Arsc files with zero or multiple packages"); } ResPackage pkg = pkgs[0]; if (pkg.getId() != id) { throw new AndrolibException("Expected pkg of id: " + String.valueOf(id) + ", got: " + pkg.getId()); } resTable.addPackage(pkg, false); return pkg; } public void decode(ResTable resTable, ExtFile apkFile, File outDir) throws AndrolibException { Duo<ResFileDecoder, ResAttrDecoder> duo = getResFileDecoder(); ResFileDecoder fileDecoder = duo.m1; ResAttrDecoder attrDecoder = duo.m2; attrDecoder.setCurrentPackage( resTable.listMainPackages().iterator().next()); Directory in, out, out9Patch; try { in = apkFile.getDirectory(); out = new FileDirectory(outDir); fileDecoder.decode( in, "AndroidManifest.xml", out, "AndroidManifest.xml", "xml"); out9Patch = out.createDir("9patch/res"); in = in.getDir("res"); out = out.createDir("res"); } catch (DirectoryException ex) { throw new AndrolibException(ex); } ExtMXSerializer xmlSerializer = getResXmlSerializer(); for (ResPackage pkg : resTable.listMainPackages()) { attrDecoder.setCurrentPackage(pkg); for (ResResource res : pkg.listFiles()) { fileDecoder.decode(res, in, out, out9Patch); } for (ResValuesFile valuesFile : pkg.listValuesFiles()) { generateValuesFile(valuesFile, out, xmlSerializer); } generatePublicXml(pkg, out, xmlSerializer); } } public void aaptPackage(File apkFile, File manifest, File resDir, File rawDir, File assetDir, boolean update, boolean framework) throws AndrolibException { String[] cmd = new String[16]; int i = 0; cmd[i++] = "aapt"; cmd[i++] = "p"; if (update) { cmd[i++] = "-u"; } cmd[i++] = "-F"; cmd[i++] = apkFile.getAbsolutePath(); if (resDir != null) { if (framework) { cmd[i++] = "-x"; } else { cmd[i++] = "-I"; cmd[i++] = getAndroidResourcesFile().getAbsolutePath(); cmd[i++] = "-I"; cmd[i++] = getHtcResourcesFile().getAbsolutePath(); } cmd[i++] = "-S"; cmd[i++] = resDir.getAbsolutePath(); } else if (framework) { cmd[i++] = "-0"; cmd[i++] = "arsc"; } if (manifest != null) { cmd[i++] = "-M"; cmd[i++] = manifest.getAbsolutePath(); } if (assetDir != null) { cmd[i++] = "-A"; cmd[i++] = assetDir.getAbsolutePath(); } if (rawDir != null) { cmd[i++] = rawDir.getAbsolutePath(); } try { OS.exec(Arrays.copyOf(cmd, i)); } catch (BrutException ex) { throw new AndrolibException(ex); } } public boolean detectWhetherAppIsFramework(File appDir) throws AndrolibException { File publicXml = new File(appDir, "res/values/public.xml"); if (! publicXml.exists()) { return false; } Iterator<String> it; try { it = IOUtils.lineIterator( new FileReader(new File(appDir, "res/values/public.xml"))); } catch (FileNotFoundException ex) { throw new AndrolibException( "Could not detect whether app is framework one", ex); } it.next(); it.next(); return it.next().contains("0x01"); } public void tagSmaliResIDs(ResTable resTable, File smaliDir) throws AndrolibException { new ResSmaliUpdater().tagResIDs(resTable, smaliDir); } public void updateSmaliResIDs(ResTable resTable, File smaliDir) throws AndrolibException { new ResSmaliUpdater().updateResIDs(resTable, smaliDir); } public Duo<ResFileDecoder, ResAttrDecoder> getResFileDecoder() { ResStreamDecoderContainer decoders = new ResStreamDecoderContainer(); decoders.setDecoder("raw", new ResRawStreamDecoder()); ResAttrDecoder attrDecoder = new ResAttrDecoder(); AXmlResourceParser axmlParser = new AXmlResourceParser(); axmlParser.setAttrDecoder(attrDecoder); decoders.setDecoder("xml", new XmlPullStreamDecoder(axmlParser, getResXmlSerializer())); return new Duo<ResFileDecoder, ResAttrDecoder>( new ResFileDecoder(decoders), attrDecoder); } public ExtMXSerializer getResXmlSerializer() { ExtMXSerializer serial = new ExtMXSerializer(); serial.setProperty(serial.PROPERTY_SERIALIZER_INDENTATION, " "); serial.setProperty(serial.PROPERTY_SERIALIZER_LINE_SEPARATOR, System.getProperty("line.separator")); serial.setProperty(ExtMXSerializer.PROPERTY_DEFAULT_ENCODING, "UTF-8"); return serial; } private void generateValuesFile(ResValuesFile valuesFile, Directory out, XmlSerializer serial) throws AndrolibException { try { OutputStream outStream = out.getFileOutput(valuesFile.getPath()); serial.setOutput((outStream), null); serial.startDocument(null, null); serial.startTag(null, "resources"); for (ResResource res : valuesFile.listResources()) { if (valuesFile.isSynthesized(res)) { continue; } ((ResXmlSerializable) res.getValue()) .serializeToXml(serial, res); } serial.endTag(null, "resources"); serial.endDocument(); serial.flush(); outStream.close(); } catch (IOException ex) { throw new AndrolibException( "Could not generate: " + valuesFile.getPath(), ex); } catch (DirectoryException ex) { throw new AndrolibException( "Could not generate: " + valuesFile.getPath(), ex); } } private void generatePublicXml(ResPackage pkg, Directory out, XmlSerializer serial) throws AndrolibException { try { OutputStream outStream = out.getFileOutput("values/public.xml"); serial.setOutput(outStream, null); serial.startDocument(null, null); serial.startTag(null, "resources"); for (ResResSpec spec : pkg.listResSpecs()) { serial.startTag(null, "public"); serial.attribute(null, "type", spec.getType().getName()); serial.attribute(null, "name", spec.getName()); serial.attribute(null, "id", String.format( "0x%08x", spec.getId().id)); serial.endTag(null, "public"); } serial.endTag(null, "resources"); serial.endDocument(); serial.flush(); outStream.close(); } catch (IOException ex) { throw new AndrolibException( "Could not generate public.xml file", ex); } catch (DirectoryException ex) { throw new AndrolibException( "Could not generate public.xml file", ex); } } private ResPackage[] getResPackagesFromApk(ExtFile apkFile, ResTable resTable) throws AndrolibException { try { return ARSCDecoder.decode( apkFile.getDirectory().getFileInput("resources.arsc"), resTable); } catch (DirectoryException ex) { throw new AndrolibException( "Could not load resources.arsc from file: " + apkFile, ex); } } private File getFrameworkApk(int id, String frameTag) throws AndrolibException { File dir = getFrameworkDir(); File apk = new File(dir, String.valueOf(id) + '-' + frameTag + ".apk"); if (apk.exists()) { return apk; } apk = new File(dir, String.valueOf(id) + ".apk"); if (apk.exists()) { return apk; } if (id == 1) { InputStream in = null; OutputStream out = null; try { in = AndrolibResources.class.getResourceAsStream( "/brut/androlib/android-framework.jar"); out = new FileOutputStream(apk); IOUtils.copy(in, out); return apk; } catch (IOException ex) { throw new AndrolibException(ex); } finally { if (in != null) { try { in.close(); } catch (IOException ex) {} } if (out != null) { try { out.close(); } catch (IOException ex) {} } } } throw new CantFindFrameworkResException(id); } private File getFrameworkDir() throws AndrolibException { File dir = new File(System.getProperty("user.home") + File.separatorChar + "apktool" + File.separatorChar + "framework"); if (! dir.exists()) { if (! dir.mkdirs()) { throw new AndrolibException("Can't create directory: " + dir); } } return dir; } private File getAndroidResourcesFile() throws AndrolibException { try { return Jar.getResourceAsFile("/brut/androlib/android-framework.jar"); } catch (BrutException ex) { throw new AndrolibException(ex); } } private File getHtcResourcesFile() throws AndrolibException { try { return Jar.getResourceAsFile( "/brut/androlib/com.htc.resources.apk"); } catch (BrutException ex) { throw new AndrolibException(ex); } } public static String escapeForResXml(String value) { if (value.isEmpty()) { return value; } StringBuilder out = new StringBuilder(value.length() + 10); char[] chars = value.toCharArray(); switch (chars[0]) { case '@': case '#': case '?': out.append('\\'); } boolean space = true; for (int i = 0; i < chars.length; i++) { char c = chars[i]; if (c == ' ') { if (space) { out.append("\\u0020"); } else { out.append(c); space = true; } continue; } space = false; switch (c) { case '\\': case '\'': case '"': out.append('\\'); break; case '\n': out.append("\\n"); continue; } out.append(c); } if (space && out.charAt(out.length() - 1) == ' ') { out.deleteCharAt(out.length() - 1); out.append("\\u0020"); } return out.toString(); } private final static Logger LOGGER = Logger.getLogger(AndrolibResources.class.getName()); }
src/brut/androlib/res/AndrolibResources.java
/* * Copyright 2010 Ryszard Wiśniewski <[email protected]>. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * under the License. */ package brut.androlib.res; import brut.androlib.AndrolibException; import brut.androlib.err.CantFindFrameworkResException; import brut.androlib.res.data.*; import brut.androlib.res.data.value.ResXmlSerializable; import brut.androlib.res.decoder.*; import brut.androlib.res.util.ExtFile; import brut.androlib.res.util.ExtMXSerializer; import brut.common.BrutException; import brut.directory.*; import brut.util.*; import java.io.*; import java.util.*; import java.util.logging.Logger; import org.apache.commons.io.IOUtils; import org.xmlpull.v1.XmlSerializer; /** * @author Ryszard Wiśniewski <[email protected]> */ final public class AndrolibResources { public ResTable getResTable(ExtFile apkFile) throws AndrolibException { ResTable resTable = new ResTable(this); loadMainPkg(resTable, apkFile); return resTable; } public ResPackage loadMainPkg(ResTable resTable, ExtFile apkFile) throws AndrolibException { LOGGER.info("Loading resource table..."); ResPackage[] pkgs = getResPackagesFromApk(apkFile, resTable); ResPackage pkg = null; switch (pkgs.length) { case 1: pkg = pkgs[0]; break; case 2: if (pkgs[0].getName().equals("android")) { LOGGER.warning("Skipping \"android\" package group"); pkg = pkgs[1]; } break; } if (pkg == null) { throw new AndrolibException( "Arsc files with zero or multiple packages"); } resTable.addPackage(pkg, true); return pkg; } public ResPackage loadFrameworkPkg(ResTable resTable, int id, String frameTag) throws AndrolibException { File apk = getFrameworkApk(id, frameTag); LOGGER.info("Loading resource table from file: " + apk); ResPackage[] pkgs = getResPackagesFromApk(new ExtFile(apk), resTable); if (pkgs.length != 1) { throw new AndrolibException( "Arsc files with zero or multiple packages"); } resTable.addPackage(pkgs[0], false); return pkgs[0]; } public void decode(ResTable resTable, ExtFile apkFile, File outDir) throws AndrolibException { Duo<ResFileDecoder, ResAttrDecoder> duo = getResFileDecoder(); ResFileDecoder fileDecoder = duo.m1; ResAttrDecoder attrDecoder = duo.m2; attrDecoder.setCurrentPackage( resTable.listMainPackages().iterator().next()); Directory in, out, out9Patch; try { in = apkFile.getDirectory(); out = new FileDirectory(outDir); fileDecoder.decode( in, "AndroidManifest.xml", out, "AndroidManifest.xml", "xml"); out9Patch = out.createDir("9patch/res"); in = in.getDir("res"); out = out.createDir("res"); } catch (DirectoryException ex) { throw new AndrolibException(ex); } ExtMXSerializer xmlSerializer = getResXmlSerializer(); for (ResPackage pkg : resTable.listMainPackages()) { attrDecoder.setCurrentPackage(pkg); for (ResResource res : pkg.listFiles()) { fileDecoder.decode(res, in, out, out9Patch); } for (ResValuesFile valuesFile : pkg.listValuesFiles()) { generateValuesFile(valuesFile, out, xmlSerializer); } generatePublicXml(pkg, out, xmlSerializer); } } public void aaptPackage(File apkFile, File manifest, File resDir, File rawDir, File assetDir, boolean update, boolean framework) throws AndrolibException { String[] cmd = new String[16]; int i = 0; cmd[i++] = "aapt"; cmd[i++] = "p"; if (update) { cmd[i++] = "-u"; } cmd[i++] = "-F"; cmd[i++] = apkFile.getAbsolutePath(); if (resDir != null) { if (framework) { cmd[i++] = "-x"; } else { cmd[i++] = "-I"; cmd[i++] = getAndroidResourcesFile().getAbsolutePath(); cmd[i++] = "-I"; cmd[i++] = getHtcResourcesFile().getAbsolutePath(); } cmd[i++] = "-S"; cmd[i++] = resDir.getAbsolutePath(); } else if (framework) { cmd[i++] = "-0"; cmd[i++] = "arsc"; } if (manifest != null) { cmd[i++] = "-M"; cmd[i++] = manifest.getAbsolutePath(); } if (assetDir != null) { cmd[i++] = "-A"; cmd[i++] = assetDir.getAbsolutePath(); } if (rawDir != null) { cmd[i++] = rawDir.getAbsolutePath(); } try { OS.exec(Arrays.copyOf(cmd, i)); } catch (BrutException ex) { throw new AndrolibException(ex); } } public boolean detectWhetherAppIsFramework(File appDir) throws AndrolibException { File publicXml = new File(appDir, "res/values/public.xml"); if (! publicXml.exists()) { return false; } Iterator<String> it; try { it = IOUtils.lineIterator( new FileReader(new File(appDir, "res/values/public.xml"))); } catch (FileNotFoundException ex) { throw new AndrolibException( "Could not detect whether app is framework one", ex); } it.next(); it.next(); return it.next().contains("0x01"); } public void tagSmaliResIDs(ResTable resTable, File smaliDir) throws AndrolibException { new ResSmaliUpdater().tagResIDs(resTable, smaliDir); } public void updateSmaliResIDs(ResTable resTable, File smaliDir) throws AndrolibException { new ResSmaliUpdater().updateResIDs(resTable, smaliDir); } public Duo<ResFileDecoder, ResAttrDecoder> getResFileDecoder() { ResStreamDecoderContainer decoders = new ResStreamDecoderContainer(); decoders.setDecoder("raw", new ResRawStreamDecoder()); ResAttrDecoder attrDecoder = new ResAttrDecoder(); AXmlResourceParser axmlParser = new AXmlResourceParser(); axmlParser.setAttrDecoder(attrDecoder); decoders.setDecoder("xml", new XmlPullStreamDecoder(axmlParser, getResXmlSerializer())); return new Duo<ResFileDecoder, ResAttrDecoder>( new ResFileDecoder(decoders), attrDecoder); } public ExtMXSerializer getResXmlSerializer() { ExtMXSerializer serial = new ExtMXSerializer(); serial.setProperty(serial.PROPERTY_SERIALIZER_INDENTATION, " "); serial.setProperty(serial.PROPERTY_SERIALIZER_LINE_SEPARATOR, System.getProperty("line.separator")); serial.setProperty(ExtMXSerializer.PROPERTY_DEFAULT_ENCODING, "UTF-8"); return serial; } private void generateValuesFile(ResValuesFile valuesFile, Directory out, XmlSerializer serial) throws AndrolibException { try { OutputStream outStream = out.getFileOutput(valuesFile.getPath()); serial.setOutput((outStream), null); serial.startDocument(null, null); serial.startTag(null, "resources"); for (ResResource res : valuesFile.listResources()) { if (valuesFile.isSynthesized(res)) { continue; } ((ResXmlSerializable) res.getValue()) .serializeToXml(serial, res); } serial.endTag(null, "resources"); serial.endDocument(); serial.flush(); outStream.close(); } catch (IOException ex) { throw new AndrolibException( "Could not generate: " + valuesFile.getPath(), ex); } catch (DirectoryException ex) { throw new AndrolibException( "Could not generate: " + valuesFile.getPath(), ex); } } private void generatePublicXml(ResPackage pkg, Directory out, XmlSerializer serial) throws AndrolibException { try { OutputStream outStream = out.getFileOutput("values/public.xml"); serial.setOutput(outStream, null); serial.startDocument(null, null); serial.startTag(null, "resources"); for (ResResSpec spec : pkg.listResSpecs()) { serial.startTag(null, "public"); serial.attribute(null, "type", spec.getType().getName()); serial.attribute(null, "name", spec.getName()); serial.attribute(null, "id", String.format( "0x%08x", spec.getId().id)); serial.endTag(null, "public"); } serial.endTag(null, "resources"); serial.endDocument(); serial.flush(); outStream.close(); } catch (IOException ex) { throw new AndrolibException( "Could not generate public.xml file", ex); } catch (DirectoryException ex) { throw new AndrolibException( "Could not generate public.xml file", ex); } } private ResPackage[] getResPackagesFromApk(ExtFile apkFile, ResTable resTable) throws AndrolibException { try { return ARSCDecoder.decode( apkFile.getDirectory().getFileInput("resources.arsc"), resTable); } catch (DirectoryException ex) { throw new AndrolibException( "Could not load resources.arsc from file: " + apkFile, ex); } } private File getFrameworkApk(int id, String frameTag) throws AndrolibException { File dir = getFrameworkDir(); File apk = new File(dir, String.valueOf(id) + '-' + frameTag + ".apk"); if (apk.exists()) { return apk; } apk = new File(dir, String.valueOf(id) + ".apk"); if (apk.exists()) { return apk; } if (id == 1) { InputStream in = null; OutputStream out = null; try { in = AndrolibResources.class.getResourceAsStream( "/brut/androlib/android-framework.jar"); out = new FileOutputStream(apk); IOUtils.copy(in, out); return apk; } catch (IOException ex) { throw new AndrolibException(ex); } finally { if (in != null) { try { in.close(); } catch (IOException ex) {} } if (out != null) { try { out.close(); } catch (IOException ex) {} } } } throw new CantFindFrameworkResException(id); } private File getFrameworkDir() throws AndrolibException { File dir = new File(System.getProperty("user.home") + File.separatorChar + "apktool" + File.separatorChar + "framework"); if (! dir.exists()) { if (! dir.mkdirs()) { throw new AndrolibException("Can't create directory: " + dir); } } return dir; } private File getAndroidResourcesFile() throws AndrolibException { try { return Jar.getResourceAsFile("/brut/androlib/android-framework.jar"); } catch (BrutException ex) { throw new AndrolibException(ex); } } private File getHtcResourcesFile() throws AndrolibException { try { return Jar.getResourceAsFile( "/brut/androlib/com.htc.resources.apk"); } catch (BrutException ex) { throw new AndrolibException(ex); } } public static String escapeForResXml(String value) { if (value.isEmpty()) { return value; } StringBuilder out = new StringBuilder(value.length() + 10); char[] chars = value.toCharArray(); switch (chars[0]) { case '@': case '#': case '?': out.append('\\'); } boolean space = true; for (int i = 0; i < chars.length; i++) { char c = chars[i]; if (c == ' ') { if (space) { out.append("\\u0020"); } else { out.append(c); space = true; } continue; } space = false; switch (c) { case '\\': case '\'': case '"': out.append('\\'); break; case '\n': out.append("\\n"); continue; } out.append(c); } if (space && out.charAt(out.length() - 1) == ' ') { out.deleteCharAt(out.length() - 1); out.append("\\u0020"); } return out.toString(); } private final static Logger LOGGER = Logger.getLogger(AndrolibResources.class.getName()); }
AndrolibResources.loadFrameworkPkg(): added check for loaded pkg id.
src/brut/androlib/res/AndrolibResources.java
AndrolibResources.loadFrameworkPkg(): added check for loaded pkg id.
<ide><path>rc/brut/androlib/res/AndrolibResources.java <ide> "Arsc files with zero or multiple packages"); <ide> } <ide> <del> resTable.addPackage(pkgs[0], false); <del> return pkgs[0]; <add> ResPackage pkg = pkgs[0]; <add> if (pkg.getId() != id) { <add> throw new AndrolibException("Expected pkg of id: " + <add> String.valueOf(id) + ", got: " + pkg.getId()); <add> } <add> <add> resTable.addPackage(pkg, false); <add> return pkg; <ide> } <ide> <ide> public void decode(ResTable resTable, ExtFile apkFile, File outDir)
Java
mit
2fead8c9fa755a5395c9efd923fd999ce28a5db7
0
rrbrambley/MessageBeast-Android
package com.alwaysallthetime.adnlibutils.model; import java.util.ArrayList; import java.util.List; public class ChannelSpecSet { private List<ChannelSpec> mChannelSpecs; public ChannelSpecSet(ChannelSpec... channels) { mChannelSpecs = new ArrayList<ChannelSpec>(channels.length); for(ChannelSpec spec : channels) { mChannelSpecs.add(spec); } } public List<ChannelSpec> getChannelSpecs() { return mChannelSpecs; } public int getNumChannels() { return mChannelSpecs.size(); } }
src/main/java/com/alwaysallthetime/adnlibutils/model/ChannelSpecSet.java
package com.alwaysallthetime.adnlibutils.model; import java.util.ArrayList; import java.util.List; public class ChannelSpecSet { private List<ChannelSpec> mChannelSpecs; public ChannelSpecSet(ChannelSpec... channels) { mChannelSpecs = new ArrayList<ChannelSpec>(channels.length); for(ChannelSpec spec : channels) { mChannelSpecs.add(spec); } } public List<ChannelSpec> getChannelSpecs() { return mChannelSpecs; } }
add convenience method for getting the num channels
src/main/java/com/alwaysallthetime/adnlibutils/model/ChannelSpecSet.java
add convenience method for getting the num channels
<ide><path>rc/main/java/com/alwaysallthetime/adnlibutils/model/ChannelSpecSet.java <ide> public List<ChannelSpec> getChannelSpecs() { <ide> return mChannelSpecs; <ide> } <add> <add> public int getNumChannels() { <add> return mChannelSpecs.size(); <add> } <ide> }
Java
bsd-3-clause
4ce5d35773380459dd50aac21f21a4b22cb4d7b0
0
DataBiosphere/jade-data-repo,DataBiosphere/jade-data-repo,DataBiosphere/jade-data-repo,DataBiosphere/jade-data-repo
package scripts.deploymentscripts; import bio.terra.datarepo.api.UnauthenticatedApi; import bio.terra.datarepo.client.ApiClient; import bio.terra.datarepo.client.ApiException; import com.fasterxml.jackson.databind.JsonNode; import com.fasterxml.jackson.databind.ObjectMapper; import com.fasterxml.jackson.databind.node.ObjectNode; import com.fasterxml.jackson.dataformat.yaml.YAMLMapper; import com.google.api.client.http.HttpStatusCodes; import common.utils.FileUtils; import common.utils.ProcessUtils; import java.io.File; import java.io.IOException; import java.net.URL; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import java.util.concurrent.TimeUnit; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import runner.DeploymentScript; import runner.config.ApplicationSpecification; import runner.config.ServerSpecification; public class ModularHelmChart extends DeploymentScript { private static final Logger logger = LoggerFactory.getLogger(ModularHelmChart.class); private String helmApiFilePath; private ServerSpecification serverSpecification; private ApplicationSpecification applicationSpecification; private static int maximumSecondsToWaitForDeploy = 1000; private static int secondsIntervalToPollForDeploy = 15; /** Public constructor so that this class can be instantiated via reflection. */ public ModularHelmChart() { super(); } /** * Expects a single parameter: a URL to the Helm datarepo-api definition YAML. The URL may point * to a local (i.e. file://) or remote (e.g. https://) file. * * @param parameters list of string parameters supplied by the test configuration */ public void setParameters(List<String> parameters) throws Exception { if (parameters == null || parameters.size() < 1) { throw new IllegalArgumentException( "Must provide a file path for the Helm API definition YAML in the parameters list"); } else { helmApiFilePath = parameters.get(0); logger.debug("Helm API definition YAML: {}", helmApiFilePath); } } /** * 1. Copy the specified Helm datarepo-api definition YAML file to the current working directory. * 2. Modify the copied original YAML file to include the environment variables specified in the * application configuration. 3. Delete the existing API deployment using Helm. 4. Re-install the * API deployment using the modified datarepo-api definition YAML file. 5. Delete the two * temporary files created in the current working directory. * * @param server the server configuration supplied by the test configuration * @param app the application configuration supplied by the test configuration */ public void deploy(ServerSpecification server, ApplicationSpecification app) throws Exception { // store these on the instance to avoid passing them around to all the helper methods serverSpecification = server; applicationSpecification = app; // get file handle to original/template API deployment Helm YAML file File originalApiYamlFile = FileUtils.createCopyOfFileFromURL(new URL(helmApiFilePath), "datarepo-api_ORIGINAL.yaml"); // modify the original/template YAML file and write the output to a new file File modifiedApiYamlFile = FileUtils.createNewFile(new File("datarepo-api_MODIFIED.yaml")); parseAndModifyApiYamlFile(originalApiYamlFile, modifiedApiYamlFile); // delete the existing API deployment // e.g. helm namespace delete mm-jade-datarepo-api --namespace mm ArrayList<String> deleteCmdArgs = new ArrayList<>(); deleteCmdArgs.add("namespace"); deleteCmdArgs.add("delete"); deleteCmdArgs.add(serverSpecification.namespace + "-jade-datarepo-api"); deleteCmdArgs.add("--namespace"); deleteCmdArgs.add(serverSpecification.namespace); Process helmDeleteProc = ProcessUtils.executeCommand("helm", deleteCmdArgs); List<String> cmdOutputLines = ProcessUtils.waitForTerminateAndReadStdout(helmDeleteProc); for (String cmdOutputLine : cmdOutputLines) { logger.debug(cmdOutputLine); } // list the available deployments (for debugging) // e.g. helm ls --namespace mm ArrayList<String> listCmdArgs = new ArrayList<>(); listCmdArgs.add("ls"); listCmdArgs.add("--namespace"); listCmdArgs.add(serverSpecification.namespace); Process helmListProc = ProcessUtils.executeCommand("helm", listCmdArgs); cmdOutputLines = ProcessUtils.waitForTerminateAndReadStdout(helmListProc); for (String cmdOutputLine : cmdOutputLines) { logger.debug(cmdOutputLine); } // install/upgrade the API deployment using the modified YAML file we just generated // e.g. helm namespace upgrade mm-jade-datarepo-api datarepo-helm/datarepo-api --install // --namespace mm -f datarepo-api_MODIFIED.yaml ArrayList<String> installCmdArgs = new ArrayList<>(); installCmdArgs.add("namespace"); installCmdArgs.add("upgrade"); installCmdArgs.add(serverSpecification.namespace + "-jade-datarepo-api"); installCmdArgs.add("datarepo-helm/datarepo-api"); installCmdArgs.add("--install"); installCmdArgs.add("--namespace"); installCmdArgs.add(serverSpecification.namespace); installCmdArgs.add("-f"); installCmdArgs.add(modifiedApiYamlFile.getAbsolutePath()); Process helmUpgradeProc = ProcessUtils.executeCommand("helm", installCmdArgs); cmdOutputLines = ProcessUtils.waitForTerminateAndReadStdout(helmUpgradeProc); for (String cmdOutputLine : cmdOutputLines) { logger.debug(cmdOutputLine); } // delete the two temp YAML files created above boolean originalYamlFileDeleted = originalApiYamlFile.delete(); if (!originalYamlFileDeleted) { throw new RuntimeException( "Error deleting the _ORIGINAL YAML file: " + originalApiYamlFile.getAbsolutePath()); } boolean modifiedYamlFileDeleted = modifiedApiYamlFile.delete(); if (!modifiedYamlFileDeleted) { throw new RuntimeException( "Error deleting the _MODIFIED YAML file: " + modifiedApiYamlFile.getAbsolutePath()); } } /** * 1. Poll the deployment status with Helm until it reports that the datarepo-api is "deployed". * 2. Poll the unauthenticated status endpoint until it returns success. * * <p>Waiting for the deployment to be ready to respond to API requests, often takes a long time * (~5-15 minutes) because we deleted the deployment before re-installing it. This restarts the * oidc-proxy which is what's holding things up. If we skip the delete deployment and just * re-install, then this method usually returns much quicker (~1-5 minutes). We need to do the * delete in order for the databases (Stairway and Data Repo) to be wiped because of how they * decide which pod will do the database migration. */ public void waitForDeployToFinish() throws Exception { int pollCtr = Math.floorDiv(maximumSecondsToWaitForDeploy, secondsIntervalToPollForDeploy); // first wait for the datarepo-api deployment to report "deployed" by helm ls logger.debug("Waiting for Helm to report datarepo-api as deployed"); boolean foundHelmStatusDeployed = false; while (pollCtr >= 0) { // list the available deployments // e.g. helm ls --namespace mm ArrayList<String> listCmdArgs = new ArrayList<>(); listCmdArgs.add("ls"); listCmdArgs.add("--namespace"); listCmdArgs.add(serverSpecification.namespace); Process helmListProc = ProcessUtils.executeCommand("helm", listCmdArgs); List<String> cmdOutputLines = ProcessUtils.waitForTerminateAndReadStdout(helmListProc); for (String cmdOutputLine : cmdOutputLines) { logger.debug(cmdOutputLine); } for (String cmdOutputLine : cmdOutputLines) { if (cmdOutputLine.startsWith(serverSpecification.namespace + "-jade-datarepo-api")) { if (cmdOutputLine.contains("deployed")) { foundHelmStatusDeployed = true; break; } } } if (foundHelmStatusDeployed) { break; } TimeUnit.SECONDS.sleep(secondsIntervalToPollForDeploy); pollCtr--; } // then wait for the datarepo-api deployment to respond successfully to a status request logger.debug("Waiting for the datarepo-api to respond successfully to a status request"); ApiClient apiClient = new ApiClient(); apiClient.setBasePath(serverSpecification.datarepoUri); UnauthenticatedApi unauthenticatedApi = new UnauthenticatedApi(apiClient); while (pollCtr >= 0) { // call the unauthenticated status endpoint try { unauthenticatedApi.serviceStatus(); int httpStatus = unauthenticatedApi.getApiClient().getStatusCode(); logger.debug("Service status: {}", httpStatus); if (HttpStatusCodes.isSuccess(httpStatus)) { break; } } catch (ApiException apiEx) { logger.debug("Exception caught while checking service status", apiEx); } TimeUnit.SECONDS.sleep(secondsIntervalToPollForDeploy); pollCtr--; } } /** * Parse the original datarepo-api YAML file and modify or add environment variables. Write the * result to the specified output file. * * @param inputFile the original datarepo-api YAML file * @param outputFile the modified datarepo-api YAML file */ private void parseAndModifyApiYamlFile(File inputFile, File outputFile) throws IOException { ObjectMapper objectMapper = new YAMLMapper(); JsonNode inputTree = objectMapper.readTree(inputFile); ObjectNode envSubTree = (ObjectNode) inputTree.get("env"); if (envSubTree == null) { throw new IllegalArgumentException("Error parsing datarepo-api YAML file"); } // confirm that the expected environment variables/application properties are set final List<String> environmentSpecificVariables = Arrays.asList( "DB_DATAREPO_USERNAME", "DB_STAIRWAY_USERNAME", "DB_DATAREPO_URI", "DB_STAIRWAY_URI", "SPRING_PROFILES_ACTIVE"); for (String var : environmentSpecificVariables) { JsonNode varValue = envSubTree.get(var); if (varValue == null) { throw new IllegalArgumentException( "Expected environment variable/application property not found in datarepo-api YAML file: " + var); } } // add the perftest profile to the SPRING_PROFILES_ACTIVE if it isn't already included String activeSpringProfiles = envSubTree.get("SPRING_PROFILES_ACTIVE").asText(); if (!activeSpringProfiles.contains("perftest")) { envSubTree.put("SPRING_PROFILES_ACTIVE", activeSpringProfiles + ",perftest"); } // always set the following testing-related environment variables envSubTree.put("DB_STAIRWAY_FORCECLEAN", "true"); envSubTree.put("GOOGLE_ALLOWREUSEEXISTINGBUCKETS", "true"); envSubTree.put("GOOGLE_ALLOWREUSEEXISTINGPROJECTS", "true"); // set the following environment variables from the application specification object // make sure the values are Strings so that they will be quoted in the Helm chart // otherwise, Helm may convert numbers to scientific notation, which breaks Spring's ability to // read them in as application properties envSubTree.put( "DB_MIGRATE_DROPALLONSTART", String.valueOf(serverSpecification.dbDropAllOnStart)); envSubTree.put( "DATAREPO_MAXSTAIRWAYTHREADS", String.valueOf(applicationSpecification.maxStairwayThreads)); envSubTree.put( "DATAREPO_MAXBULKFILELOAD", String.valueOf(applicationSpecification.maxBulkFileLoad)); envSubTree.put( "DATAREPO_MAXBULKFILELOADARRAY", String.valueOf(applicationSpecification.maxBulkFileLoadArray)); envSubTree.put( "DATAREPO_MAXDATASETINGEST", String.valueOf(applicationSpecification.maxDatasetIngest)); envSubTree.put( "DATAREPO_LOADCONCURRENTFILES", String.valueOf(applicationSpecification.loadConcurrentFiles)); envSubTree.put( "DATAREPO_LOADCONCURRENTINGESTS", String.valueOf(applicationSpecification.loadConcurrentIngests)); envSubTree.put( "DATAREPO_LOADDRIVERWAITSECONDS", String.valueOf(applicationSpecification.loadDriverWaitSeconds)); envSubTree.put( "DATAREPO_LOADHISTORYCOPYCHUNKSIZE", String.valueOf(applicationSpecification.loadHistoryCopyChunkSize)); envSubTree.put( "DATAREPO_LOADHISTORYWAITSECONDS", String.valueOf(applicationSpecification.loadHistoryWaitSeconds)); // write the modified tree out to disk objectMapper.writeValue(outputFile, inputTree); } }
datarepo-clienttests/src/main/java/scripts/deploymentscripts/ModularHelmChart.java
package scripts.deploymentscripts; import bio.terra.datarepo.api.UnauthenticatedApi; import bio.terra.datarepo.client.ApiClient; import bio.terra.datarepo.client.ApiException; import com.fasterxml.jackson.databind.JsonNode; import com.fasterxml.jackson.databind.ObjectMapper; import com.fasterxml.jackson.databind.node.ObjectNode; import com.fasterxml.jackson.dataformat.yaml.YAMLMapper; import com.google.api.client.http.HttpStatusCodes; import common.utils.FileUtils; import common.utils.ProcessUtils; import java.io.File; import java.io.IOException; import java.net.URL; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import java.util.concurrent.TimeUnit; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import runner.DeploymentScript; import runner.config.ApplicationSpecification; import runner.config.ServerSpecification; public class ModularHelmChart extends DeploymentScript { private static final Logger logger = LoggerFactory.getLogger(ModularHelmChart.class); private String helmApiFilePath; private ServerSpecification serverSpecification; private ApplicationSpecification applicationSpecification; private static int maximumSecondsToWaitForDeploy = 1000; private static int secondsIntervalToPollForDeploy = 15; /** Public constructor so that this class can be instantiated via reflection. */ public ModularHelmChart() { super(); } /** * Expects a single parameter: a URL to the Helm datarepo-api definition YAML. The URL may point * to a local (i.e. file://) or remote (e.g. https://) file. * * @param parameters list of string parameters supplied by the test configuration */ public void setParameters(List<String> parameters) throws Exception { if (parameters == null || parameters.size() < 1) { throw new IllegalArgumentException( "Must provide a file path for the Helm API definition YAML in the parameters list"); } else { helmApiFilePath = parameters.get(0); logger.debug("Helm API definition YAML: {}", helmApiFilePath); } } /** * 1. Copy the specified Helm datarepo-api definition YAML file to the current working directory. * 2. Modify the copied original YAML file to include the environment variables specified in the * application configuration. 3. Delete the existing API deployment using Helm. 4. Re-install the * API deployment using the modified datarepo-api definition YAML file. 5. Delete the two * temporary files created in the current working directory. * * @param server the server configuration supplied by the test configuration * @param app the application configuration supplied by the test configuration */ public void deploy(ServerSpecification server, ApplicationSpecification app) throws Exception { // store these on the instance to avoid passing them around to all the helper methods serverSpecification = server; applicationSpecification = app; // get file handle to original/template API deployment Helm YAML file File originalApiYamlFile = FileUtils.createCopyOfFileFromURL(new URL(helmApiFilePath), "datarepo-api_ORIGINAL.yaml"); // modify the original/template YAML file and write the output to a new file File modifiedApiYamlFile = FileUtils.createNewFile(new File("datarepo-api_MODIFIED.yaml")); parseAndModifyApiYamlFile(originalApiYamlFile, modifiedApiYamlFile); // delete the existing API deployment // e.g. helm namespace delete mm-jade-datarepo-api --namespace mm ArrayList<String> deleteCmdArgs = new ArrayList<>(); deleteCmdArgs.add("namespace"); deleteCmdArgs.add("delete"); deleteCmdArgs.add(serverSpecification.namespace + "-jade-datarepo-api"); deleteCmdArgs.add("--namespace"); deleteCmdArgs.add(serverSpecification.namespace); Process helmDeleteProc = ProcessUtils.executeCommand("helm", deleteCmdArgs); List<String> cmdOutputLines = ProcessUtils.waitForTerminateAndReadStdout(helmDeleteProc); for (String cmdOutputLine : cmdOutputLines) { logger.debug(cmdOutputLine); } // list the available deployments (for debugging) // e.g. helm ls --namespace mm ArrayList<String> listCmdArgs = new ArrayList<>(); listCmdArgs.add("ls"); listCmdArgs.add("--namespace"); listCmdArgs.add(serverSpecification.namespace); Process helmListProc = ProcessUtils.executeCommand("helm", listCmdArgs); cmdOutputLines = ProcessUtils.waitForTerminateAndReadStdout(helmListProc); for (String cmdOutputLine : cmdOutputLines) { logger.debug(cmdOutputLine); } // install/upgrade the API deployment using the modified YAML file we just generated // e.g. helm namespace upgrade mm-jade-datarepo-api datarepo-helm/datarepo-api --install // --namespace mm -f datarepo-api_MODIFIED.yaml ArrayList<String> installCmdArgs = new ArrayList<>(); installCmdArgs.add("namespace"); installCmdArgs.add("upgrade"); installCmdArgs.add(serverSpecification.namespace + "-jade-datarepo-api"); installCmdArgs.add("datarepo-helm/datarepo-api"); installCmdArgs.add("--install"); installCmdArgs.add("--namespace"); installCmdArgs.add(serverSpecification.namespace); installCmdArgs.add("-f"); installCmdArgs.add(modifiedApiYamlFile.getAbsolutePath()); Process helmUpgradeProc = ProcessUtils.executeCommand("helm", installCmdArgs); cmdOutputLines = ProcessUtils.waitForTerminateAndReadStdout(helmUpgradeProc); for (String cmdOutputLine : cmdOutputLines) { logger.debug(cmdOutputLine); } // delete the two temp YAML files created above boolean originalYamlFileDeleted = originalApiYamlFile.delete(); if (!originalYamlFileDeleted) { throw new RuntimeException( "Error deleting the _ORIGINAL YAML file: " + originalApiYamlFile.getAbsolutePath()); } boolean modifiedYamlFileDeleted = modifiedApiYamlFile.delete(); if (!modifiedYamlFileDeleted) { throw new RuntimeException( "Error deleting the _MODIFIED YAML file: " + modifiedApiYamlFile.getAbsolutePath()); } } /** * 1. Poll the deployment status with Helm until it reports that the datarepo-api is "deployed". * 2. Poll the unauthenticated status endpoint until it returns success. * * <p>Waiting for the deployment to be ready to respond to API requests, often takes a long time * (~5-15 minutes) because we deleted the deployment before re-installing it. This restarts the * oidc-proxy which is what's holding things up. If we skip the delete deployment and just * re-install, then this method usually returns much quicker (~1-5 minutes). We need to do the * delete in order for the databases (Stairway and Data Repo) to be wiped because of how they * decide which pod will do the database migration. */ public void waitForDeployToFinish() throws Exception { int pollCtr = Math.floorDiv(maximumSecondsToWaitForDeploy, secondsIntervalToPollForDeploy); // first wait for the datarepo-api deployment to report "deployed" by helm ls logger.debug("Waiting for Helm to report datarepo-api as deployed"); boolean foundHelmStatusDeployed = false; while (pollCtr >= 0) { // list the available deployments // e.g. helm ls --namespace mm ArrayList<String> listCmdArgs = new ArrayList<>(); listCmdArgs.add("ls"); listCmdArgs.add("--namespace"); listCmdArgs.add(serverSpecification.namespace); Process helmListProc = ProcessUtils.executeCommand("helm", listCmdArgs); List<String> cmdOutputLines = ProcessUtils.waitForTerminateAndReadStdout(helmListProc); for (String cmdOutputLine : cmdOutputLines) { logger.debug(cmdOutputLine); } for (String cmdOutputLine : cmdOutputLines) { if (cmdOutputLine.startsWith(serverSpecification.namespace + "-jade-datarepo-api")) { if (cmdOutputLine.contains("deployed")) { foundHelmStatusDeployed = true; break; } } } if (foundHelmStatusDeployed) { break; } TimeUnit.SECONDS.sleep(secondsIntervalToPollForDeploy); pollCtr--; } // then wait for the datarepo-api deployment to respond successfully to a status request logger.debug("Waiting for the datarepo-api to respond successfully to a status request"); ApiClient apiClient = new ApiClient(); apiClient.setBasePath(serverSpecification.datarepoUri); UnauthenticatedApi unauthenticatedApi = new UnauthenticatedApi(apiClient); while (pollCtr >= 0) { // call the unauthenticated status endpoint try { unauthenticatedApi.serviceStatus(); int httpStatus = unauthenticatedApi.getApiClient().getStatusCode(); logger.debug("Service status: {}", httpStatus); if (HttpStatusCodes.isSuccess(httpStatus)) { break; } } catch (ApiException apiEx) { logger.debug("Exception caught while checking service status", apiEx); } TimeUnit.SECONDS.sleep(secondsIntervalToPollForDeploy); pollCtr--; } } /** * Parse the original datarepo-api YAML file and modify or add environment variables. Write the * result to the specified output file. * * @param inputFile the original datarepo-api YAML file * @param outputFile the modified datarepo-api YAML file */ private void parseAndModifyApiYamlFile(File inputFile, File outputFile) throws IOException { ObjectMapper objectMapper = new YAMLMapper(); JsonNode inputTree = objectMapper.readTree(inputFile); ObjectNode envSubTree = (ObjectNode) inputTree.get("env"); if (envSubTree == null) { throw new IllegalArgumentException("Error parsing datarepo-api YAML file"); } // confirm that the expected environment variables/application properties are set final List<String> environmentSpecificVariables = Arrays.asList( "GOOGLE_PROJECTID", "GOOGLE_SINGLEDATAPROJECTID", "DB_DATAREPO_USERNAME", "DB_STAIRWAY_USERNAME", "DB_DATAREPO_URI", "DB_STAIRWAY_URI", "SPRING_PROFILES_ACTIVE"); for (String var : environmentSpecificVariables) { JsonNode varValue = envSubTree.get(var); if (varValue == null) { throw new IllegalArgumentException( "Expected environment variable/application property not found in datarepo-api YAML file: " + var); } } // add the perftest profile to the SPRING_PROFILES_ACTIVE if it isn't already included String activeSpringProfiles = envSubTree.get("SPRING_PROFILES_ACTIVE").asText(); if (!activeSpringProfiles.contains("perftest")) { envSubTree.put("SPRING_PROFILES_ACTIVE", activeSpringProfiles + ",perftest"); } // always set the following testing-related environment variables envSubTree.put("DB_STAIRWAY_FORCECLEAN", "true"); envSubTree.put("GOOGLE_ALLOWREUSEEXISTINGBUCKETS", "true"); envSubTree.put("GOOGLE_ALLOWREUSEEXISTINGPROJECTS", "true"); // set the following environment variables from the application specification object // make sure the values are Strings so that they will be quoted in the Helm chart // otherwise, Helm may convert numbers to scientific notation, which breaks Spring's ability to // read them in as application properties envSubTree.put( "DB_MIGRATE_DROPALLONSTART", String.valueOf(serverSpecification.dbDropAllOnStart)); envSubTree.put( "DATAREPO_MAXSTAIRWAYTHREADS", String.valueOf(applicationSpecification.maxStairwayThreads)); envSubTree.put( "DATAREPO_MAXBULKFILELOAD", String.valueOf(applicationSpecification.maxBulkFileLoad)); envSubTree.put( "DATAREPO_MAXBULKFILELOADARRAY", String.valueOf(applicationSpecification.maxBulkFileLoadArray)); envSubTree.put( "DATAREPO_MAXDATASETINGEST", String.valueOf(applicationSpecification.maxDatasetIngest)); envSubTree.put( "DATAREPO_LOADCONCURRENTFILES", String.valueOf(applicationSpecification.loadConcurrentFiles)); envSubTree.put( "DATAREPO_LOADCONCURRENTINGESTS", String.valueOf(applicationSpecification.loadConcurrentIngests)); envSubTree.put( "DATAREPO_LOADDRIVERWAITSECONDS", String.valueOf(applicationSpecification.loadDriverWaitSeconds)); envSubTree.put( "DATAREPO_LOADHISTORYCOPYCHUNKSIZE", String.valueOf(applicationSpecification.loadHistoryCopyChunkSize)); envSubTree.put( "DATAREPO_LOADHISTORYWAITSECONDS", String.valueOf(applicationSpecification.loadHistoryWaitSeconds)); // write the modified tree out to disk objectMapper.writeValue(outputFile, inputTree); } }
Don't check for existence of unused properties (#1143)
datarepo-clienttests/src/main/java/scripts/deploymentscripts/ModularHelmChart.java
Don't check for existence of unused properties (#1143)
<ide><path>atarepo-clienttests/src/main/java/scripts/deploymentscripts/ModularHelmChart.java <ide> // confirm that the expected environment variables/application properties are set <ide> final List<String> environmentSpecificVariables = <ide> Arrays.asList( <del> "GOOGLE_PROJECTID", <del> "GOOGLE_SINGLEDATAPROJECTID", <ide> "DB_DATAREPO_USERNAME", <ide> "DB_STAIRWAY_USERNAME", <ide> "DB_DATAREPO_URI",
Java
apache-2.0
e776e2996b1ce36201bdeb7b509ae89a7583279f
0
yukezhu/LifeGameSim,yukezhu/LifeGameSim,yukezhu/LifeGameSim,yukezhu/LifeGameSim
package ca.sfu.server; import java.io.IOException; import java.util.ArrayList; import ca.sfu.cmpt431.facility.Board; import ca.sfu.cmpt431.facility.BoardOperation; import ca.sfu.cmpt431.facility.Comrade; import ca.sfu.cmpt431.facility.Outfits; import ca.sfu.cmpt431.message.Message; import ca.sfu.cmpt431.message.MessageCodeDictionary; import ca.sfu.cmpt431.message.join.JoinOutfitsMsg; import ca.sfu.cmpt431.message.join.JoinRequestMsg; import ca.sfu.cmpt431.message.join.JoinSplitMsg; import ca.sfu.cmpt431.message.merge.MergeLastMsg; import ca.sfu.cmpt431.message.regular.RegularBoardReturnMsg; import ca.sfu.cmpt431.message.regular.RegularNextClockMsg; import ca.sfu.network.MessageReceiver; import ca.sfu.network.MessageSender; import ca.sfu.network.SynchronizedMsgQueue.MessageWithIp; public class Server{ protected static final int LISTEN_PORT = 6560; private MessageReceiver Receiver; private MessageSender Sender1; private MessageSender Sender2; private String client1_ip; private String client2_ip; private ArrayList<MessageSender> newClientSender = new ArrayList<MessageSender>(); private ArrayList<Comrade> regedClientSender = new ArrayList<Comrade>(); private ArrayList<Integer> toLeave = new ArrayList<Integer>(); private int waiting4confirm = 0; private int nextClock = 0; private int status; /* UI widgets */ MainFrame frame = null; InformationPanel infoPanel = null; public Server() throws IOException { Receiver = new MessageReceiver(LISTEN_PORT); status = 0; } protected void startServer() throws IOException, ClassNotFoundException, InterruptedException { // UI Board b = BoardOperation.LoadFile("Patterns/HerschelLoop2.lg"); System.out.println("UI"); frame = new MainFrame(b, 800, 800); infoPanel = new InformationPanel(); MessageWithIp m; while(true) { if(!Receiver.isEmpty()) { m = Receiver.getNextMessageWithIp(); infoPanel.setCellNum(frame.automataPanel.getCell()); infoPanel.setLifeNum(frame.automataPanel.getAlive()); infoPanel.setCycleNum(frame.automataPanel.getCycle()); infoPanel.setClientNum(regedClientSender.size()); infoPanel.setTargetNum("localhost"); switch(status) { //waiting for first client case 0: handleNewAddingLeaving(m,1); handlePending(); //send it the outfit regedClientSender.get(0).sender.sendMsg(new JoinOutfitsMsg(-1, -1, new Outfits(0,nextClock,0,0,b))); waiting4confirm++; status = 2; break; //wait for the confirm //start a cycle case 2: if(handleNewAddingLeaving(m,2)) break; handleConfirm(m,3); //expect only one message responding for JoinOutfitsMsg if(waiting4confirm == 0){ //send you a start for (Comrade var : regedClientSender) { var.sender.sendMsg(new RegularNextClockMsg(nextClock)); waiting4confirm++; } status = 3; } break; //waiting for the client to send the result back //handle new adding or //restart next cycle case 3: if(handleNewAddingLeaving(m,3)) break; handleNewBoardInfo(m,b,3); if(waiting4confirm!=0){ break; } // Thread.sleep(50); frame.repaint(); // BoardOperation.Print(b); // System.out.println("repaint"); //handle adding if(handlePending()){ status = 2; break; } //start if(waiting4confirm==0){ for (Comrade var : regedClientSender) { // System.out.println("sending start"); var.sender.sendMsg(new RegularNextClockMsg(nextClock)); waiting4confirm++; } } break; //new addings (not the first client) case 4: if(handleNewAddingLeaving(m,4)) break; handleConfirm(m,-1); if(waiting4confirm!=0) //still need waiting for confirmation break; //deal with add if(newClientSender.size()!=0){ handlePending(); status = 5; break; } //start if(waiting4confirm==0){ for (Comrade var : regedClientSender) { var.sender.sendMsg(new RegularNextClockMsg(nextClock)); waiting4confirm++; } } status = 3; break; case -1: client1_ip = m.getIp(); Sender1 = new MessageSender(client1_ip, LISTEN_PORT); System.out.println(client1_ip + "connected!!!"); status = 1; break; case -2: client2_ip = m.getIp(); Sender2 = new MessageSender(client2_ip, LISTEN_PORT); System.out.println(client2_ip + "connected!!!"); Sender1.sendMsg(client2_ip); status = 2; break; case -3: if(!m.getIp().equals(client1_ip)) System.out.println("Error!"); Sender2.sendMsg(client1_ip); status = 3; break; case -4: if(!m.getIp().equals(client2_ip)) System.out.println("Error!"); System.out.println("before"); //Sender1.sendMsg(auto.left()); // Sender1.sendMsg(auto); // Sender1.sendMsg(new AutomataMsg(3, 4)); // Sender1.sendMsg("left"); System.out.println("after"); status = 4; break; case -5: if(!m.getIp().equals(client1_ip)) System.out.println("Error!"); //Sender2.sendMsg(auto.right()); status = 5; break; case -6: if(!m.getIp().equals(client2_ip)) System.out.println("Error!"); Sender1.sendMsg("left"); status = 6; break; case 6: if(!m.getIp().equals(client1_ip)) System.out.println("Error!"); Sender2.sendMsg("right"); status = 7; break; case 7: if(!m.getIp().equals(client2_ip)) System.out.println("Error!"); Sender1.sendMsg("start"); status = 8; break; case 8: if(!m.getIp().equals(client1_ip)) System.out.println("Error!"); Sender2.sendMsg("start"); status = 9; break; case 9: if(!m.getIp().equals(client2_ip)) System.out.println("Error!"); status = 10; break; case 10: // if(m == null) System.out.println("null"); if(m.getIp().equals(client1_ip)){ //auto.mergeLeft((AutomataMsg)m.extracMessage()); //Sender1.sendMsg("OK"); } else{ //auto.mergeRight((AutomataMsg)m.extracMessage()); //Sender2.sendMsg("OK"); } status = 11; break; case 11: if(m.getIp().equals(client1_ip)){ //auto.mergeLeft((AutomataMsg)m.extracMessage()); //Sender1.sendMsg("OK"); } else{ //auto.mergeRight((AutomataMsg)m.extracMessage()); //Sender2.sendMsg("OK"); } frame.repaint(); Sender1.sendMsg("start"); status = 8; break; default: break; } } } } //store all the adding request into an array protected boolean handleNewAddingLeaving(MessageWithIp m, int nextStatus) throws IOException{ //check if m is a new adding request message Message msg = (Message) m.extracMessage(); if(msg.getMessageCode()==MessageCodeDictionary.JOIN_REQUEST){ JoinRequestMsg join = (JoinRequestMsg)m.extracMessage(); newClientSender.add(new MessageSender(m.getIp(), join.clientPort)); System.out.println("adding a new client to pending list"); //if it is a new adding request, we need to go to nextStatus //most time it should be the same status status = nextStatus; return true; } else if(msg.getMessageCode()==MessageCodeDictionary.LEAVE_REQUEST){ //TODO toLeave.add(msg.getClientId()); System.out.println("a client want to leave, pending now"); return true; } return false; } protected int handleLeaving() throws IOException{ int cid = toLeave.get(0); if(newClientSender.size()!=0){ //ask a new client to replace it immediately } else if(regedClientSender.size()==1){ //there is only one client and no adding //ask him to leave directly } else if(isLastPair(cid)!=-1){ //it is the last node, or the pair of last node //ask the last pair merge int s = regedClientSender.size(); int pair_id =(s%2==0)?((s-4)>=0?regedClientSender.get(s-4).id:-1):regedClientSender.get(0).id; if(isLastPair(pair_id)!=-1) pair_id = -1; //you pair can not be your neighbour, occurs when there is 2 clients regedClientSender.get(regedClientSender.size()-1-isLastPair(cid)).sender.sendMsg(new MergeLastMsg(pair_id)); //wait for a confirm return isLastPair(cid)+1; //1 if last or 2 if second last } else{ //ask the last node merge first,give it a new pair id //ask the last node to replace int s = regedClientSender.size(); int pair_id =(s%2==0)?((s-4)>=0?regedClientSender.get(s-4).id:-1):regedClientSender.get(0).id; if(isLastPair(pair_id)!=-1) pair_id = -1; //you pair can not be your neighbour regedClientSender.get(regedClientSender.size()-1).sender.sendMsg(new MergeLastMsg(pair_id)); //wait for a confirm return 3; } return -1; } private int isLastPair(int cid){ int s = regedClientSender.size(); if(regedClientSender.get(s-1).id == cid) return 0; else if(regedClientSender.get(s-2).id == cid) return 1; else return -1; } //deal with the pending adding request //manage the heap protected boolean handlePending() throws IOException{ //you can add at most N new clients in a cycle, N is the number of all clients existing before int count = 0; int n = regedClientSender.size(); while(!newClientSender.isEmpty()){ int cid = regedClientSender.size(); count++; if(count>n) return true; //manage the heap if(cid!=0){ //not the first client Comrade c = regedClientSender.get(0); //get it down one level //c is the pair int mode; if((((int)(Math.log(2*cid+1)/Math.log(2)))%2)!=0) mode = MessageCodeDictionary.SPLIT_MODE_HORIZONTAL; else mode = MessageCodeDictionary.SPLIT_MODE_VERTICAL; // System.out.println(cid); // System.out.println((Math.log(2*cid+1)/Math.log(2))%2); // System.out.println("mode"+mode); System.out.println("Sending a split command to "+ c.id+", new client id: "+cid+", split mode: "+(mode==0?"vertical":"horizontal")); // System.out.println("send JoinSplitMsg"); // System.out.println(newClientSender.get(0).hostIp); c.sender.sendMsg(new JoinSplitMsg(cid, newClientSender.get(0).hostListenningPort, newClientSender.get(0).hostIp, mode)); regedClientSender.remove(0); regedClientSender.add(c); regedClientSender.add(new Comrade(cid, newClientSender.get(0).hostListenningPort, newClientSender.get(0).hostIp, newClientSender.get(0))); waiting4confirm++; } else{ regedClientSender.add(new Comrade(cid, newClientSender.get(0).hostListenningPort, newClientSender.get(0).hostIp, newClientSender.get(0))); //regedClientSender.get(cid).sender.sendMsg(new RegularConfirmMsg(-1)); } //remove the pending one newClientSender.remove(0); System.out.println("register a new client"); return true; } return false; } protected void handleNewBoardInfo(MessageWithIp m, Board b, int nextStatus){ waiting4confirm--; // System.out.println("getting a result"); if(waiting4confirm==0) status = nextStatus; RegularBoardReturnMsg r = (RegularBoardReturnMsg)m.extracMessage(); BoardOperation.Merge(b, r.board, r.top, r.left); // b = (Board)m.extracMessage(); } //getting a new confirm message, if there is no waiting confirm, go to nextStatus protected void handleConfirm(MessageWithIp m, int nextStatus){ waiting4confirm--; // System.out.println("getting a confirm"); if(waiting4confirm==0) status = nextStatus; } }
GameOfLifeServer/src/ca/sfu/server/Server.java
package ca.sfu.server; import java.io.IOException; import java.util.ArrayList; import ca.sfu.cmpt431.facility.Board; import ca.sfu.cmpt431.facility.BoardOperation; import ca.sfu.cmpt431.facility.Comrade; import ca.sfu.cmpt431.facility.Outfits; import ca.sfu.cmpt431.message.Message; import ca.sfu.cmpt431.message.MessageCodeDictionary; import ca.sfu.cmpt431.message.join.JoinOutfitsMsg; import ca.sfu.cmpt431.message.join.JoinRequestMsg; import ca.sfu.cmpt431.message.join.JoinSplitMsg; import ca.sfu.cmpt431.message.regular.RegularBoardReturnMsg; import ca.sfu.cmpt431.message.regular.RegularNextClockMsg; import ca.sfu.network.MessageReceiver; import ca.sfu.network.MessageSender; import ca.sfu.network.SynchronizedMsgQueue.MessageWithIp; public class Server{ protected static final int LISTEN_PORT = 6560; private MessageReceiver Receiver; private MessageSender Sender1; private MessageSender Sender2; private String client1_ip; private String client2_ip; private ArrayList<MessageSender> newClientSender = new ArrayList<MessageSender>(); private ArrayList<Comrade> regedClientSender = new ArrayList<Comrade>(); private ArrayList<Integer> toLeave = new ArrayList<Integer>(); private int waiting4confirm = 0; private int nextClock = 0; private int status; /* UI widgets */ MainFrame frame = null; InformationPanel infoPanel = null; public Server() throws IOException { Receiver = new MessageReceiver(LISTEN_PORT); status = 0; } protected void startServer() throws IOException, ClassNotFoundException, InterruptedException { // UI Board b = BoardOperation.LoadFile("Patterns/HerschelLoop2.lg"); System.out.println("UI"); frame = new MainFrame(b, 800, 800); infoPanel = new InformationPanel(); MessageWithIp m; while(true) { if(!Receiver.isEmpty()) { m = Receiver.getNextMessageWithIp(); infoPanel.setCellNum(frame.automataPanel.getCell()); infoPanel.setLifeNum(frame.automataPanel.getAlive()); infoPanel.setCycleNum(frame.automataPanel.getCycle()); infoPanel.setClientNum(regedClientSender.size()); infoPanel.setTargetNum("localhost"); switch(status) { //waiting for first client case 0: handleNewAddingLeaving(m,1); handlePending(); //send it the outfit regedClientSender.get(0).sender.sendMsg(new JoinOutfitsMsg(-1, -1, new Outfits(0,nextClock,0,0,b))); waiting4confirm++; status = 2; break; //wait for the confirm //start a cycle case 2: if(handleNewAddingLeaving(m,2)) break; handleConfirm(m,3); //expect only one message responding for JoinOutfitsMsg if(waiting4confirm == 0){ //send you a start for (Comrade var : regedClientSender) { var.sender.sendMsg(new RegularNextClockMsg(nextClock)); waiting4confirm++; } status = 3; } break; //waiting for the client to send the result back //handle new adding or //restart next cycle case 3: if(handleNewAddingLeaving(m,3)) break; handleNewBoardInfo(m,b,3); if(waiting4confirm!=0){ break; } // Thread.sleep(50); frame.repaint(); // BoardOperation.Print(b); // System.out.println("repaint"); //handle adding if(handlePending()){ status = 2; break; } //start if(waiting4confirm==0){ for (Comrade var : regedClientSender) { // System.out.println("sending start"); var.sender.sendMsg(new RegularNextClockMsg(nextClock)); waiting4confirm++; } } break; //new addings (not the first client) case 4: if(handleNewAddingLeaving(m,4)) break; handleConfirm(m,-1); if(waiting4confirm!=0) //still need waiting for confirmation break; //deal with add if(newClientSender.size()!=0){ handlePending(); status = 5; break; } //start if(waiting4confirm==0){ for (Comrade var : regedClientSender) { var.sender.sendMsg(new RegularNextClockMsg(nextClock)); waiting4confirm++; } } status = 3; break; case -1: client1_ip = m.getIp(); Sender1 = new MessageSender(client1_ip, LISTEN_PORT); System.out.println(client1_ip + "connected!!!"); status = 1; break; case -2: client2_ip = m.getIp(); Sender2 = new MessageSender(client2_ip, LISTEN_PORT); System.out.println(client2_ip + "connected!!!"); Sender1.sendMsg(client2_ip); status = 2; break; case -3: if(!m.getIp().equals(client1_ip)) System.out.println("Error!"); Sender2.sendMsg(client1_ip); status = 3; break; case -4: if(!m.getIp().equals(client2_ip)) System.out.println("Error!"); System.out.println("before"); //Sender1.sendMsg(auto.left()); // Sender1.sendMsg(auto); // Sender1.sendMsg(new AutomataMsg(3, 4)); // Sender1.sendMsg("left"); System.out.println("after"); status = 4; break; case -5: if(!m.getIp().equals(client1_ip)) System.out.println("Error!"); //Sender2.sendMsg(auto.right()); status = 5; break; case -6: if(!m.getIp().equals(client2_ip)) System.out.println("Error!"); Sender1.sendMsg("left"); status = 6; break; case 6: if(!m.getIp().equals(client1_ip)) System.out.println("Error!"); Sender2.sendMsg("right"); status = 7; break; case 7: if(!m.getIp().equals(client2_ip)) System.out.println("Error!"); Sender1.sendMsg("start"); status = 8; break; case 8: if(!m.getIp().equals(client1_ip)) System.out.println("Error!"); Sender2.sendMsg("start"); status = 9; break; case 9: if(!m.getIp().equals(client2_ip)) System.out.println("Error!"); status = 10; break; case 10: // if(m == null) System.out.println("null"); if(m.getIp().equals(client1_ip)){ //auto.mergeLeft((AutomataMsg)m.extracMessage()); //Sender1.sendMsg("OK"); } else{ //auto.mergeRight((AutomataMsg)m.extracMessage()); //Sender2.sendMsg("OK"); } status = 11; break; case 11: if(m.getIp().equals(client1_ip)){ //auto.mergeLeft((AutomataMsg)m.extracMessage()); //Sender1.sendMsg("OK"); } else{ //auto.mergeRight((AutomataMsg)m.extracMessage()); //Sender2.sendMsg("OK"); } frame.repaint(); Sender1.sendMsg("start"); status = 8; break; default: break; } } } } //store all the adding request into an array protected boolean handleNewAddingLeaving(MessageWithIp m, int nextStatus) throws IOException{ //check if m is a new adding request message Message msg = (Message) m.extracMessage(); if(msg.getMessageCode()==MessageCodeDictionary.JOIN_REQUEST){ JoinRequestMsg join = (JoinRequestMsg)m.extracMessage(); newClientSender.add(new MessageSender(m.getIp(), join.clientPort)); System.out.println("adding a new client to pending list"); //if it is a new adding request, we need to go to nextStatus //most time it should be the same status status = nextStatus; return true; } else if(msg.getMessageCode()==0){ //TODO } return false; } protected boolean handleLeaving(){ if() } //deal with the pending adding request //manage the heap protected boolean handlePending() throws IOException{ //you can add at most N new clients in a cycle, N is the number of all clients existing before int count = 0; int n = regedClientSender.size(); while(!newClientSender.isEmpty()){ int cid = regedClientSender.size(); count++; if(count>n) return true; //manage the heap if(cid!=0){ //not the first client Comrade c = regedClientSender.get(0); //get it down one level //c is the pair int mode; if((((int)(Math.log(2*cid+1)/Math.log(2)))%2)!=0) mode = MessageCodeDictionary.SPLIT_MODE_HORIZONTAL; else mode = MessageCodeDictionary.SPLIT_MODE_VERTICAL; // System.out.println(cid); // System.out.println((Math.log(2*cid+1)/Math.log(2))%2); // System.out.println("mode"+mode); System.out.println("Sending a split command to "+ c.id+", new client id: "+cid+", split mode: "+(mode==0?"vertical":"horizontal")); // System.out.println("send JoinSplitMsg"); // System.out.println(newClientSender.get(0).hostIp); c.sender.sendMsg(new JoinSplitMsg(cid, newClientSender.get(0).hostListenningPort, newClientSender.get(0).hostIp, mode)); regedClientSender.remove(0); regedClientSender.add(c); regedClientSender.add(new Comrade(cid, newClientSender.get(0).hostListenningPort, newClientSender.get(0).hostIp, newClientSender.get(0))); waiting4confirm++; } else{ regedClientSender.add(new Comrade(cid, newClientSender.get(0).hostListenningPort, newClientSender.get(0).hostIp, newClientSender.get(0))); //regedClientSender.get(cid).sender.sendMsg(new RegularConfirmMsg(-1)); } //remove the pending one newClientSender.remove(0); System.out.println("register a new client"); return true; } return false; } protected void handleNewBoardInfo(MessageWithIp m, Board b, int nextStatus){ waiting4confirm--; // System.out.println("getting a result"); if(waiting4confirm==0) status = nextStatus; RegularBoardReturnMsg r = (RegularBoardReturnMsg)m.extracMessage(); BoardOperation.Merge(b, r.board, r.top, r.left); // b = (Board)m.extracMessage(); } //getting a new confirm message, if there is no waiting confirm, go to nextStatus protected void handleConfirm(MessageWithIp m, int nextStatus){ waiting4confirm--; // System.out.println("getting a confirm"); if(waiting4confirm==0) status = nextStatus; } }
server1:28
GameOfLifeServer/src/ca/sfu/server/Server.java
server1:28
<ide><path>ameOfLifeServer/src/ca/sfu/server/Server.java <ide> import ca.sfu.cmpt431.message.join.JoinOutfitsMsg; <ide> import ca.sfu.cmpt431.message.join.JoinRequestMsg; <ide> import ca.sfu.cmpt431.message.join.JoinSplitMsg; <add>import ca.sfu.cmpt431.message.merge.MergeLastMsg; <ide> import ca.sfu.cmpt431.message.regular.RegularBoardReturnMsg; <ide> import ca.sfu.cmpt431.message.regular.RegularNextClockMsg; <ide> import ca.sfu.network.MessageReceiver; <ide> status = nextStatus; <ide> return true; <ide> } <del> else if(msg.getMessageCode()==0){ <add> else if(msg.getMessageCode()==MessageCodeDictionary.LEAVE_REQUEST){ <ide> //TODO <add> toLeave.add(msg.getClientId()); <add> System.out.println("a client want to leave, pending now"); <add> return true; <ide> } <ide> return false; <ide> } <ide> <del> protected boolean handleLeaving(){ <del> if() <add> protected int handleLeaving() throws IOException{ <add> int cid = toLeave.get(0); <add> if(newClientSender.size()!=0){ <add> //ask a new client to replace it immediately <add> } <add> else if(regedClientSender.size()==1){ <add> //there is only one client and no adding <add> //ask him to leave directly <add> <add> } <add> else if(isLastPair(cid)!=-1){ <add> //it is the last node, or the pair of last node <add> //ask the last pair merge <add> int s = regedClientSender.size(); <add> int pair_id =(s%2==0)?((s-4)>=0?regedClientSender.get(s-4).id:-1):regedClientSender.get(0).id; <add> if(isLastPair(pair_id)!=-1) <add> pair_id = -1; //you pair can not be your neighbour, occurs when there is 2 clients <add> regedClientSender.get(regedClientSender.size()-1-isLastPair(cid)).sender.sendMsg(new MergeLastMsg(pair_id)); <add> //wait for a confirm <add> return isLastPair(cid)+1; //1 if last or 2 if second last <add> } <add> else{ <add> //ask the last node merge first,give it a new pair id <add> //ask the last node to replace <add> int s = regedClientSender.size(); <add> int pair_id =(s%2==0)?((s-4)>=0?regedClientSender.get(s-4).id:-1):regedClientSender.get(0).id; <add> if(isLastPair(pair_id)!=-1) <add> pair_id = -1; //you pair can not be your neighbour <add> regedClientSender.get(regedClientSender.size()-1).sender.sendMsg(new MergeLastMsg(pair_id)); <add> //wait for a confirm <add> return 3; <add> } <add> return -1; <add> } <add> <add> private int isLastPair(int cid){ <add> int s = regedClientSender.size(); <add> if(regedClientSender.get(s-1).id == cid) <add> return 0; <add> else if(regedClientSender.get(s-2).id == cid) <add> return 1; <add> else <add> return -1; <ide> } <ide> <ide> //deal with the pending adding request
Java
apache-2.0
7e26b7aa0716d61a70e8037f4a5dd0be6083bd29
0
mixpanel/mixpanel-android,mixpanel/mixpanel-android,mixpanel/mixpanel-android
package com.mixpanel.android.mpmetrics; import android.annotation.TargetApi; import android.app.Activity; import android.app.Application; import android.app.FragmentTransaction; import android.content.BroadcastReceiver; import android.content.Context; import android.content.Intent; import android.content.IntentFilter; import android.content.SharedPreferences; import android.content.pm.PackageInfo; import android.content.pm.PackageManager; import android.os.Build; import android.os.Bundle; import com.mixpanel.android.R; import com.mixpanel.android.takeoverinapp.TakeoverInAppActivity; import com.mixpanel.android.util.ActivityImageUtils; import com.mixpanel.android.util.MPLog; import com.mixpanel.android.viewcrawler.TrackingDebug; import com.mixpanel.android.viewcrawler.UpdatesFromMixpanel; import com.mixpanel.android.viewcrawler.ViewCrawler; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; import java.text.DateFormat; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.Date; import java.util.HashMap; import java.util.Iterator; import java.util.List; import java.util.Locale; import java.util.Map; import java.util.Map.Entry; import java.util.Set; import java.util.TimeZone; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.Executor; import java.util.concurrent.Executors; import java.util.concurrent.Future; import java.util.concurrent.locks.ReentrantLock; /** * Core class for interacting with Mixpanel Analytics. * * <p>Call {@link #getInstance(Context, String)} with * your main application activity and your Mixpanel API token as arguments * an to get an instance you can use to report how users are using your * application. * * <p>Once you have an instance, you can send events to Mixpanel * using {@link #track(String, JSONObject)}, and update People Analytics * records with {@link #getPeople()} * * <p>The Mixpanel library will periodically send information to * Mixpanel servers, so your application will need to have * <tt>android.permission.INTERNET</tt>. In addition, to preserve * battery life, messages to Mixpanel servers may not be sent immediately * when you call <tt>track</tt> or {@link People#set(String, Object)}. * The library will send messages periodically throughout the lifetime * of your application, but you will need to call {@link #flush()} * before your application is completely shutdown to ensure all of your * events are sent. * * <p>A typical use-case for the library might look like this: * * <pre> * {@code * public class MainActivity extends Activity { * MixpanelAPI mMixpanel; * * public void onCreate(Bundle saved) { * mMixpanel = MixpanelAPI.getInstance(this, "YOUR MIXPANEL API TOKEN"); * ... * } * * public void whenSomethingInterestingHappens(int flavor) { * JSONObject properties = new JSONObject(); * properties.put("flavor", flavor); * mMixpanel.track("Something Interesting Happened", properties); * ... * } * * public void onDestroy() { * mMixpanel.flush(); * super.onDestroy(); * } * } * } * </pre> * * <p>In addition to this documentation, you may wish to take a look at * <a href="https://github.com/mixpanel/sample-android-mixpanel-integration">the Mixpanel sample Android application</a>. * It demonstrates a variety of techniques, including * updating People Analytics records with {@link People} and others. * * <p>There are also <a href="https://mixpanel.com/docs/">step-by-step getting started documents</a> * available at mixpanel.com * * @see <a href="https://mixpanel.com/docs/integration-libraries/android">getting started documentation for tracking events</a> * @see <a href="https://mixpanel.com/docs/people-analytics/android">getting started documentation for People Analytics</a> * @see <a href="https://mixpanel.com/docs/people-analytics/android-push">getting started with push notifications for Android</a> * @see <a href="https://github.com/mixpanel/sample-android-mixpanel-integration">The Mixpanel Android sample application</a> */ public class MixpanelAPI { /** * String version of the library. */ public static final String VERSION = MPConfig.VERSION; /** * Declare a string-valued tweak, and return a reference you can use to read the value of the tweak. * Tweaks can be changed in Mixpanel A/B tests, and can allow you to alter your customers' experience * in your app without re-deploying your application through the app store. */ public static Tweak<String> stringTweak(String tweakName, String defaultValue) { return sSharedTweaks.stringTweak(tweakName, defaultValue); } /** * Declare a boolean-valued tweak, and return a reference you can use to read the value of the tweak. * Tweaks can be changed in Mixpanel A/B tests, and can allow you to alter your customers' experience * in your app without re-deploying your application through the app store. */ public static Tweak<Boolean> booleanTweak(String tweakName, boolean defaultValue) { return sSharedTweaks.booleanTweak(tweakName, defaultValue); } /** * Declare a double-valued tweak, and return a reference you can use to read the value of the tweak. * Tweaks can be changed in Mixpanel A/B tests, and can allow you to alter your customers' experience * in your app without re-deploying your application through the app store. */ public static Tweak<Double> doubleTweak(String tweakName, double defaultValue) { return sSharedTweaks.doubleTweak(tweakName, defaultValue); } /** * Declare a double-valued tweak, and return a reference you can use to read the value of the tweak. * Tweaks can be changed in Mixpanel A/B tests, and can allow you to alter your customers' experience * in your app without re-deploying your application through the app store. */ public static Tweak<Double> doubleTweak(String tweakName, double defaultValue, double minimumValue, double maximumValue) { return sSharedTweaks.doubleTweak(tweakName, defaultValue, minimumValue, maximumValue); } /** * Declare a float-valued tweak, and return a reference you can use to read the value of the tweak. * Tweaks can be changed in Mixpanel A/B tests, and can allow you to alter your customers' experience * in your app without re-deploying your application through the app store. */ public static Tweak<Float> floatTweak(String tweakName, float defaultValue) { return sSharedTweaks.floatTweak(tweakName, defaultValue); } /** * Declare a float-valued tweak, and return a reference you can use to read the value of the tweak. * Tweaks can be changed in Mixpanel A/B tests, and can allow you to alter your customers' experience * in your app without re-deploying your application through the app store. */ public static Tweak<Float> floatTweak(String tweakName, float defaultValue, float minimumValue, float maximumValue) { return sSharedTweaks.floatTweak(tweakName, defaultValue, minimumValue, maximumValue); } /** * Declare a long-valued tweak, and return a reference you can use to read the value of the tweak. * Tweaks can be changed in Mixpanel A/B tests, and can allow you to alter your customers' experience * in your app without re-deploying your application through the app store. */ public static Tweak<Long> longTweak(String tweakName, long defaultValue) { return sSharedTweaks.longTweak(tweakName, defaultValue); } /** * Declare a long-valued tweak, and return a reference you can use to read the value of the tweak. * Tweaks can be changed in Mixpanel A/B tests, and can allow you to alter your customers' experience * in your app without re-deploying your application through the app store. */ public static Tweak<Long> longTweak(String tweakName, long defaultValue, long minimumValue, long maximumValue) { return sSharedTweaks.longTweak(tweakName, defaultValue, minimumValue, maximumValue); } /** * Declare an int-valued tweak, and return a reference you can use to read the value of the tweak. * Tweaks can be changed in Mixpanel A/B tests, and can allow you to alter your customers' experience * in your app without re-deploying your application through the app store. */ public static Tweak<Integer> intTweak(String tweakName, int defaultValue) { return sSharedTweaks.intTweak(tweakName, defaultValue); } /** * Declare an int-valued tweak, and return a reference you can use to read the value of the tweak. * Tweaks can be changed in Mixpanel A/B tests, and can allow you to alter your customers' experience * in your app without re-deploying your application through the app store. */ public static Tweak<Integer> intTweak(String tweakName, int defaultValue, int minimumValue, int maximumValue) { return sSharedTweaks.intTweak(tweakName, defaultValue, minimumValue, maximumValue); } /** * Declare short-valued tweak, and return a reference you can use to read the value of the tweak. * Tweaks can be changed in Mixpanel A/B tests, and can allow you to alter your customers' experience * in your app without re-deploying your application through the app store. */ public static Tweak<Short> shortTweak(String tweakName, short defaultValue) { return sSharedTweaks.shortTweak(tweakName, defaultValue); } /** * Declare byte-valued tweak, and return a reference you can use to read the value of the tweak. * Tweaks can be changed in Mixpanel A/B tests, and can allow you to alter your customers' experience * in your app without re-deploying your application through the app store. */ public static Tweak<Byte> byteTweak(String tweakName, byte defaultValue) { return sSharedTweaks.byteTweak(tweakName, defaultValue); } /** * You shouldn't instantiate MixpanelAPI objects directly. * Use MixpanelAPI.getInstance to get an instance. */ MixpanelAPI(Context context, Future<SharedPreferences> referrerPreferences, String token, boolean optOutTrackingDefault, JSONObject superProperties) { this(context, referrerPreferences, token, MPConfig.getInstance(context), optOutTrackingDefault, superProperties); } /** * You shouldn't instantiate MixpanelAPI objects directly. * Use MixpanelAPI.getInstance to get an instance. */ MixpanelAPI(Context context, Future<SharedPreferences> referrerPreferences, String token, MPConfig config, boolean optOutTrackingDefault, JSONObject superProperties) { mContext = context; mToken = token; mPeople = new PeopleImpl(); mGroups = new HashMap<String, GroupImpl>(); mConfig = config; final Map<String, String> deviceInfo = new HashMap<String, String>(); deviceInfo.put("$android_lib_version", MPConfig.VERSION); deviceInfo.put("$android_os", "Android"); deviceInfo.put("$android_os_version", Build.VERSION.RELEASE == null ? "UNKNOWN" : Build.VERSION.RELEASE); deviceInfo.put("$android_manufacturer", Build.MANUFACTURER == null ? "UNKNOWN" : Build.MANUFACTURER); deviceInfo.put("$android_brand", Build.BRAND == null ? "UNKNOWN" : Build.BRAND); deviceInfo.put("$android_model", Build.MODEL == null ? "UNKNOWN" : Build.MODEL); try { final PackageManager manager = mContext.getPackageManager(); final PackageInfo info = manager.getPackageInfo(mContext.getPackageName(), 0); deviceInfo.put("$android_app_version", info.versionName); deviceInfo.put("$android_app_version_code", Integer.toString(info.versionCode)); } catch (final PackageManager.NameNotFoundException e) { MPLog.e(LOGTAG, "Exception getting app version name", e); } mDeviceInfo = Collections.unmodifiableMap(deviceInfo); mSessionMetadata = new SessionMetadata(); mUpdatesFromMixpanel = constructUpdatesFromMixpanel(context, token); mTrackingDebug = constructTrackingDebug(); mMessages = getAnalyticsMessages(); mPersistentIdentity = getPersistentIdentity(context, referrerPreferences, token); mEventTimings = mPersistentIdentity.getTimeEvents(); if (optOutTrackingDefault && (hasOptedOutTracking() || !mPersistentIdentity.hasOptOutFlag(token))) { optOutTracking(); } if (superProperties != null) { registerSuperProperties(superProperties); } mUpdatesListener = constructUpdatesListener(); mDecideMessages = constructDecideUpdates(token, mUpdatesListener, mUpdatesFromMixpanel); mConnectIntegrations = new ConnectIntegrations(this, mContext); // TODO reading persistent identify immediately forces the lazy load of the preferences, and defeats the // purpose of PersistentIdentity's laziness. String decideId = mPersistentIdentity.getPeopleDistinctId(); if (null == decideId) { decideId = mPersistentIdentity.getEventsDistinctId(); } mDecideMessages.setDistinctId(decideId); final boolean dbExists = MPDbAdapter.getInstance(mContext).getDatabaseFile().exists(); registerMixpanelActivityLifecycleCallbacks(); if (mPersistentIdentity.isFirstLaunch(dbExists)) { track(AutomaticEvents.FIRST_OPEN, null, true); mPersistentIdentity.setHasLaunched(); } if (!mConfig.getDisableDecideChecker()) { mMessages.installDecideCheck(mDecideMessages); } if (sendAppOpen()) { track("$app_open", null); } if (!mPersistentIdentity.isFirstIntegration(mToken)) { try { final JSONObject messageProps = new JSONObject(); messageProps.put("mp_lib", "Android"); messageProps.put("lib", "Android"); messageProps.put("distinct_id", token); messageProps.put("$lib_version", MPConfig.VERSION); messageProps.put("$user_id", token); final AnalyticsMessages.EventDescription eventDescription = new AnalyticsMessages.EventDescription( "Integration", messageProps, "85053bf24bba75239b16a601d9387e17"); mMessages.eventsMessage(eventDescription); mMessages.postToServer(new AnalyticsMessages.FlushDescription("85053bf24bba75239b16a601d9387e17", false)); mPersistentIdentity.setIsIntegrated(mToken); } catch (JSONException e) { } } if (mPersistentIdentity.isNewVersion(deviceInfo.get("$android_app_version_code"))) { try { final JSONObject messageProps = new JSONObject(); messageProps.put(AutomaticEvents.VERSION_UPDATED, deviceInfo.get("$android_app_version")); track(AutomaticEvents.APP_UPDATED, messageProps, true); } catch (JSONException e) {} } mUpdatesFromMixpanel.startUpdates(); if (!mConfig.getDisableExceptionHandler()) { ExceptionHandler.init(); } } /** * Get the instance of MixpanelAPI associated with your Mixpanel project token. * * <p>Use getInstance to get a reference to a shared * instance of MixpanelAPI you can use to send events * and People Analytics updates to Mixpanel.</p> * <p>getInstance is thread safe, but the returned instance is not, * and may be shared with other callers of getInstance. * The best practice is to call getInstance, and use the returned MixpanelAPI, * object from a single thread (probably the main UI thread of your application).</p> * <p>If you do choose to track events from multiple threads in your application, * you should synchronize your calls on the instance itself, like so:</p> * <pre> * {@code * MixpanelAPI instance = MixpanelAPI.getInstance(context, token); * synchronized(instance) { // Only necessary if the instance will be used in multiple threads. * instance.track(...) * } * } * </pre> * * @param context The application context you are tracking * @param token Your Mixpanel project token. You can get your project token on the Mixpanel web site, * in the settings dialog. * @return an instance of MixpanelAPI associated with your project */ public static MixpanelAPI getInstance(Context context, String token) { return getInstance(context, token, false, null); } /** * Get the instance of MixpanelAPI associated with your Mixpanel project token. * * <p>Use getInstance to get a reference to a shared * instance of MixpanelAPI you can use to send events * and People Analytics updates to Mixpanel.</p> * <p>getInstance is thread safe, but the returned instance is not, * and may be shared with other callers of getInstance. * The best practice is to call getInstance, and use the returned MixpanelAPI, * object from a single thread (probably the main UI thread of your application).</p> * <p>If you do choose to track events from multiple threads in your application, * you should synchronize your calls on the instance itself, like so:</p> * <pre> * {@code * MixpanelAPI instance = MixpanelAPI.getInstance(context, token); * synchronized(instance) { // Only necessary if the instance will be used in multiple threads. * instance.track(...) * } * } * </pre> * * @param context The application context you are tracking * @param token Your Mixpanel project token. You can get your project token on the Mixpanel web site, * in the settings dialog. * @param optOutTrackingDefault Whether or not Mixpanel can start tracking by default. See * {@link #optOutTracking()}. * @return an instance of MixpanelAPI associated with your project */ public static MixpanelAPI getInstance(Context context, String token, boolean optOutTrackingDefault) { return getInstance(context, token, optOutTrackingDefault, null); } /** * Get the instance of MixpanelAPI associated with your Mixpanel project token. * * <p>Use getInstance to get a reference to a shared * instance of MixpanelAPI you can use to send events * and People Analytics updates to Mixpanel.</p> * <p>getInstance is thread safe, but the returned instance is not, * and may be shared with other callers of getInstance. * The best practice is to call getInstance, and use the returned MixpanelAPI, * object from a single thread (probably the main UI thread of your application).</p> * <p>If you do choose to track events from multiple threads in your application, * you should synchronize your calls on the instance itself, like so:</p> * <pre> * {@code * MixpanelAPI instance = MixpanelAPI.getInstance(context, token); * synchronized(instance) { // Only necessary if the instance will be used in multiple threads. * instance.track(...) * } * } * </pre> * * @param context The application context you are tracking * @param token Your Mixpanel project token. You can get your project token on the Mixpanel web site, * in the settings dialog. * @param superProperties A JSONObject containing super properties to register. * @return an instance of MixpanelAPI associated with your project */ public static MixpanelAPI getInstance(Context context, String token, JSONObject superProperties) { return getInstance(context, token, false, superProperties); } /** * Get the instance of MixpanelAPI associated with your Mixpanel project token. * * <p>Use getInstance to get a reference to a shared * instance of MixpanelAPI you can use to send events * and People Analytics updates to Mixpanel.</p> * <p>getInstance is thread safe, but the returned instance is not, * and may be shared with other callers of getInstance. * The best practice is to call getInstance, and use the returned MixpanelAPI, * object from a single thread (probably the main UI thread of your application).</p> * <p>If you do choose to track events from multiple threads in your application, * you should synchronize your calls on the instance itself, like so:</p> * <pre> * {@code * MixpanelAPI instance = MixpanelAPI.getInstance(context, token); * synchronized(instance) { // Only necessary if the instance will be used in multiple threads. * instance.track(...) * } * } * </pre> * * @param context The application context you are tracking * @param token Your Mixpanel project token. You can get your project token on the Mixpanel web site, * in the settings dialog. * @param optOutTrackingDefault Whether or not Mixpanel can start tracking by default. See * {@link #optOutTracking()}. * @param superProperties A JSONObject containing super properties to register. * @return an instance of MixpanelAPI associated with your project */ public static MixpanelAPI getInstance(Context context, String token, boolean optOutTrackingDefault, JSONObject superProperties) { if (null == token || null == context) { return null; } synchronized (sInstanceMap) { final Context appContext = context.getApplicationContext(); if (null == sReferrerPrefs) { sReferrerPrefs = sPrefsLoader.loadPreferences(context, MPConfig.REFERRER_PREFS_NAME, null); } Map <Context, MixpanelAPI> instances = sInstanceMap.get(token); if (null == instances) { instances = new HashMap<Context, MixpanelAPI>(); sInstanceMap.put(token, instances); } MixpanelAPI instance = instances.get(appContext); if (null == instance && ConfigurationChecker.checkBasicConfiguration(appContext)) { instance = new MixpanelAPI(appContext, sReferrerPrefs, token, optOutTrackingDefault, superProperties); registerAppLinksListeners(context, instance); instances.put(appContext, instance); if (ConfigurationChecker.checkPushNotificationConfiguration(appContext)) { try { MixpanelFCMMessagingService.init(); } catch (Exception e) { MPLog.e(LOGTAG, "Push notification could not be initialized", e); } } } checkIntentForInboundAppLink(context); return instance; } } /** * This function creates a distinct_id alias from alias to original. If original is null, then it will create an alias * to the current events distinct_id, which may be the distinct_id randomly generated by the Mixpanel library * before {@link #identify(String)} is called. * * <p>This call does not identify the user after. You must still call both {@link #identify(String)} and * {@link People#identify(String)} if you wish the new alias to be used for Events and People. * * @param alias the new distinct_id that should represent original. * @param original the old distinct_id that alias will be mapped to. */ public void alias(String alias, String original) { if (hasOptedOutTracking()) return; if (original == null) { original = getDistinctId(); } if (alias.equals(original)) { MPLog.w(LOGTAG, "Attempted to alias identical distinct_ids " + alias + ". Alias message will not be sent."); return; } try { final JSONObject j = new JSONObject(); j.put("alias", alias); j.put("original", original); track("$create_alias", j); } catch (final JSONException e) { MPLog.e(LOGTAG, "Failed to alias", e); } flush(); } /** * Associate all future calls to {@link #track(String, JSONObject)} with the user identified by * the given distinct id. * * <p>This call does not identify the user for People Analytics; * to do that, see {@link People#identify(String)}. Mixpanel recommends using * the same distinct_id for both calls, and using a distinct_id that is easy * to associate with the given user, for example, a server-side account identifier. * * <p>Calls to {@link #track(String, JSONObject)} made before corresponding calls to * identify will use an internally generated distinct id, which means it is best * to call identify early to ensure that your Mixpanel funnels and retention * analytics can continue to track the user throughout their lifetime. We recommend * calling identify as early as you can. * * <p>Once identify is called, the given distinct id persists across restarts of your * application. * * @param distinctId a string uniquely identifying this user. Events sent to * Mixpanel using the same disinct_id will be considered associated with the * same visitor/customer for retention and funnel reporting, so be sure that the given * value is globally unique for each individual user you intend to track. * * @see People#identify(String) */ public void identify(String distinctId) { identify(distinctId, true); } private void identify(String distinctId, boolean markAsUserId) { if (hasOptedOutTracking()) return; synchronized (mPersistentIdentity) { String currentEventsDistinctId = mPersistentIdentity.getEventsDistinctId(); mPersistentIdentity.setAnonymousIdIfAbsent(currentEventsDistinctId); mPersistentIdentity.setEventsDistinctId(distinctId); if(markAsUserId) { mPersistentIdentity.markEventsUserIdPresent(); } String decideId = mPersistentIdentity.getPeopleDistinctId(); if (null == decideId) { decideId = mPersistentIdentity.getEventsDistinctId(); } mDecideMessages.setDistinctId(decideId); if (!distinctId.equals(currentEventsDistinctId)) { try { JSONObject identifyPayload = new JSONObject(); identifyPayload.put("$anon_distinct_id", currentEventsDistinctId); track("$identify", identifyPayload); } catch (JSONException e) { MPLog.e(LOGTAG, "Could not track $identify event"); } } } } /** * Begin timing of an event. Calling timeEvent("Thing") will not send an event, but * when you eventually call track("Thing"), your tracked event will be sent with a "$duration" * property, representing the number of seconds between your calls. * * @param eventName the name of the event to track with timing. */ public void timeEvent(final String eventName) { if (hasOptedOutTracking()) return; final long writeTime = System.currentTimeMillis(); synchronized (mEventTimings) { mEventTimings.put(eventName, writeTime); mPersistentIdentity.addTimeEvent(eventName, writeTime); } } /** * Retrieves the time elapsed for the named event since timeEvent() was called. * * @param eventName the name of the event to be tracked that was previously called with timeEvent() */ public double eventElapsedTime(final String eventName) { final long currentTime = System.currentTimeMillis(); Long startTime; synchronized (mEventTimings) { startTime = mEventTimings.get(eventName); } return startTime == null ? 0 : (double)((currentTime - startTime) / 1000); } /** * Track an event. * * <p>Every call to track eventually results in a data point sent to Mixpanel. These data points * are what are measured, counted, and broken down to create your Mixpanel reports. Events * have a string name, and an optional set of name/value pairs that describe the properties of * that event. * * @param eventName The name of the event to send * @param properties A Map containing the key value pairs of the properties to include in this event. * Pass null if no extra properties exist. * * See also {@link #track(String, org.json.JSONObject)} */ public void trackMap(String eventName, Map<String, Object> properties) { if (hasOptedOutTracking()) return; if (null == properties) { track(eventName, null); } else { try { track(eventName, new JSONObject(properties)); } catch (NullPointerException e) { MPLog.w(LOGTAG, "Can't have null keys in the properties of trackMap!"); } } } /** * Track an event with specific groups. * * <p>Every call to track eventually results in a data point sent to Mixpanel. These data points * are what are measured, counted, and broken down to create your Mixpanel reports. Events * have a string name, and an optional set of name/value pairs that describe the properties of * that event. Group key/value pairs are upserted into the property map before tracking. * * @param eventName The name of the event to send * @param properties A Map containing the key value pairs of the properties to include in this event. * Pass null if no extra properties exist. * @param groups A Map containing the group key value pairs for this event. * * See also {@link #track(String, org.json.JSONObject)}, {@link #trackMap(String, Map)} */ public void trackWithGroups(String eventName, Map<String, Object> properties, Map<String, Object> groups) { if (hasOptedOutTracking()) return; if (null == groups) { trackMap(eventName, properties); } else if (null == properties) { trackMap(eventName, groups); } else { for (Entry<String, Object> e : groups.entrySet()) { if (e.getValue() != null) { properties.put(e.getKey(), e.getValue()); } } trackMap(eventName, properties); } } /** * Track an event. * * <p>Every call to track eventually results in a data point sent to Mixpanel. These data points * are what are measured, counted, and broken down to create your Mixpanel reports. Events * have a string name, and an optional set of name/value pairs that describe the properties of * that event. * * @param eventName The name of the event to send * @param properties A JSONObject containing the key value pairs of the properties to include in this event. * Pass null if no extra properties exist. */ // DO NOT DOCUMENT, but track() must be thread safe since it is used to track events in // notifications from the UI thread, which might not be our MixpanelAPI "home" thread. // This MAY CHANGE IN FUTURE RELEASES, so minimize code that assumes thread safety // (and perhaps document that code here). public void track(String eventName, JSONObject properties) { if (hasOptedOutTracking()) return; track(eventName, properties, false); } /** * Equivalent to {@link #track(String, JSONObject)} with a null argument for properties. * Consider adding properties to your tracking to get the best insights and experience from Mixpanel. * @param eventName the name of the event to send */ public void track(String eventName) { if (hasOptedOutTracking()) return; track(eventName, null); } /** * Push all queued Mixpanel events and People Analytics changes to Mixpanel servers. * * <p>Events and People messages are pushed gradually throughout * the lifetime of your application. This means that to ensure that all messages * are sent to Mixpanel when your application is shut down, you will * need to call flush() to let the Mixpanel library know it should * send all remaining messages to the server. We strongly recommend * placing a call to flush() in the onDestroy() method of * your main application activity. */ public void flush() { if (hasOptedOutTracking()) return; mMessages.postToServer(new AnalyticsMessages.FlushDescription(mToken)); } /** * Returns a json object of the user's current super properties * *<p>SuperProperties are a collection of properties that will be sent with every event to Mixpanel, * and persist beyond the lifetime of your application. */ public JSONObject getSuperProperties() { JSONObject ret = new JSONObject(); mPersistentIdentity.addSuperPropertiesToObject(ret); return ret; } /** * Returns the string id currently being used to uniquely identify the user associated * with events sent using {@link #track(String, JSONObject)}. Before any calls to * {@link #identify(String)}, this will be an id automatically generated by the library. * * <p>The id returned by getDistinctId is independent of the distinct id used to identify * any People Analytics properties in Mixpanel. To read and write that identifier, * use {@link People#identify(String)} and {@link People#getDistinctId()}. * * @return The distinct id associated with event tracking * * @see #identify(String) * @see People#getDistinctId() */ public String getDistinctId() { return mPersistentIdentity.getEventsDistinctId(); } /** * Returns the anonymoous id currently being used to uniquely identify the device and all * with events sent using {@link #track(String, JSONObject)} will have this id as a device * id * * @return The device id associated with event tracking */ protected String getAnonymousId() { return mPersistentIdentity.getAnonymousId(); } /** * Returns the user id with which identify is called and all the with events sent using * {@link #track(String, JSONObject)} will have this id as a user id * * @return The user id associated with event tracking */ protected String getUserId() { return mPersistentIdentity.getEventsUserId(); } /** * Register properties that will be sent with every subsequent call to {@link #track(String, JSONObject)}. * * <p>SuperProperties are a collection of properties that will be sent with every event to Mixpanel, * and persist beyond the lifetime of your application. * * <p>Setting a superProperty with registerSuperProperties will store a new superProperty, * possibly overwriting any existing superProperty with the same name (to set a * superProperty only if it is currently unset, use {@link #registerSuperPropertiesOnce(JSONObject)}) * * <p>SuperProperties will persist even if your application is taken completely out of memory. * to remove a superProperty, call {@link #unregisterSuperProperty(String)} or {@link #clearSuperProperties()} * * @param superProperties A Map containing super properties to register * * See also {@link #registerSuperProperties(org.json.JSONObject)} */ public void registerSuperPropertiesMap(Map<String, Object> superProperties) { if (hasOptedOutTracking()) return; if (null == superProperties) { MPLog.e(LOGTAG, "registerSuperPropertiesMap does not accept null properties"); return; } try { registerSuperProperties(new JSONObject(superProperties)); } catch (NullPointerException e) { MPLog.w(LOGTAG, "Can't have null keys in the properties of registerSuperPropertiesMap"); } } /** * Register properties that will be sent with every subsequent call to {@link #track(String, JSONObject)}. * * <p>SuperProperties are a collection of properties that will be sent with every event to Mixpanel, * and persist beyond the lifetime of your application. * * <p>Setting a superProperty with registerSuperProperties will store a new superProperty, * possibly overwriting any existing superProperty with the same name (to set a * superProperty only if it is currently unset, use {@link #registerSuperPropertiesOnce(JSONObject)}) * * <p>SuperProperties will persist even if your application is taken completely out of memory. * to remove a superProperty, call {@link #unregisterSuperProperty(String)} or {@link #clearSuperProperties()} * * @param superProperties A JSONObject containing super properties to register * @see #registerSuperPropertiesOnce(JSONObject) * @see #unregisterSuperProperty(String) * @see #clearSuperProperties() */ public void registerSuperProperties(JSONObject superProperties) { if (hasOptedOutTracking()) return; mPersistentIdentity.registerSuperProperties(superProperties); } /** * Remove a single superProperty, so that it will not be sent with future calls to {@link #track(String, JSONObject)}. * * <p>If there is a superProperty registered with the given name, it will be permanently * removed from the existing superProperties. * To clear all superProperties, use {@link #clearSuperProperties()} * * @param superPropertyName name of the property to unregister * @see #registerSuperProperties(JSONObject) */ public void unregisterSuperProperty(String superPropertyName) { if (hasOptedOutTracking()) return; mPersistentIdentity.unregisterSuperProperty(superPropertyName); } /** * Register super properties for events, only if no other super property with the * same names has already been registered. * * <p>Calling registerSuperPropertiesOnce will never overwrite existing properties. * * @param superProperties A Map containing the super properties to register. * * See also {@link #registerSuperPropertiesOnce(org.json.JSONObject)} */ public void registerSuperPropertiesOnceMap(Map<String, Object> superProperties) { if (hasOptedOutTracking()) return; if (null == superProperties) { MPLog.e(LOGTAG, "registerSuperPropertiesOnceMap does not accept null properties"); return; } try { registerSuperPropertiesOnce(new JSONObject(superProperties)); } catch (NullPointerException e) { MPLog.w(LOGTAG, "Can't have null keys in the properties of registerSuperPropertiesOnce!"); } } /** * Register super properties for events, only if no other super property with the * same names has already been registered. * * <p>Calling registerSuperPropertiesOnce will never overwrite existing properties. * * @param superProperties A JSONObject containing the super properties to register. * @see #registerSuperProperties(JSONObject) */ public void registerSuperPropertiesOnce(JSONObject superProperties) { if (hasOptedOutTracking()) return; mPersistentIdentity.registerSuperPropertiesOnce(superProperties); } /** * Erase all currently registered superProperties. * * <p>Future tracking calls to Mixpanel will not contain the specific * superProperties registered before the clearSuperProperties method was called. * * <p>To remove a single superProperty, use {@link #unregisterSuperProperty(String)} * * @see #registerSuperProperties(JSONObject) */ public void clearSuperProperties() { mPersistentIdentity.clearSuperProperties(); } /** * Updates super properties in place. Given a SuperPropertyUpdate object, will * pass the current values of SuperProperties to that update and replace all * results with the return value of the update. Updates are synchronized on * the underlying super properties store, so they are guaranteed to be thread safe * (but long running updates may slow down your tracking.) * * @param update A function from one set of super properties to another. The update should not return null. */ public void updateSuperProperties(SuperPropertyUpdate update) { if (hasOptedOutTracking()) return; mPersistentIdentity.updateSuperProperties(update); } /** * Set the group this user belongs to. * * @param groupKey The property name associated with this group type (must already have been set up). * @param groupID The group the user belongs to. */ public void setGroup(String groupKey, Object groupID) { if (hasOptedOutTracking()) return; List<Object> groupIDs = new ArrayList<>(1); groupIDs.add(groupID); setGroup(groupKey, groupIDs); } /** * Set the groups this user belongs to. * * @param groupKey The property name associated with this group type (must already have been set up). * @param groupIDs The list of groups the user belongs to. */ public void setGroup(String groupKey, List<Object> groupIDs) { if (hasOptedOutTracking()) return; JSONArray vals = new JSONArray(); for (Object s : groupIDs) { if (s == null) { MPLog.w(LOGTAG, "groupID must be non-null"); } else { vals.put(s); } } try { registerSuperProperties((new JSONObject()).put(groupKey, vals)); mPeople.set(groupKey, vals); } catch (JSONException e) { MPLog.w(LOGTAG, "groupKey must be non-null"); } } /** * Add a group to this user's membership for a particular group key * * @param groupKey The property name associated with this group type (must already have been set up). * @param groupID The new group the user belongs to. */ public void addGroup(final String groupKey, final Object groupID) { if (hasOptedOutTracking()) return; updateSuperProperties(new SuperPropertyUpdate() { public JSONObject update(JSONObject in) { try { in.accumulate(groupKey, groupID); } catch (JSONException e) { MPLog.e(LOGTAG, "Failed to add groups superProperty", e); } return in; } }); // This is a best effort--if the people property is not already a list, this call does nothing. mPeople.union(groupKey, (new JSONArray()).put(groupID)); } /** * Remove a group from this user's membership for a particular group key * * @param groupKey The property name associated with this group type (must already have been set up). * @param groupID The group value to remove. */ public void removeGroup(final String groupKey, final Object groupID) { if (hasOptedOutTracking()) return; updateSuperProperties(new SuperPropertyUpdate() { public JSONObject update(JSONObject in) { try { JSONArray vals = in.getJSONArray(groupKey); JSONArray newVals = new JSONArray(); if (vals.length() <= 1) { in.remove(groupKey); // This is a best effort--we can't guarantee people and super properties match mPeople.unset(groupKey); } else { for (int i = 0; i < vals.length(); i++) { if (!vals.get(i).equals(groupID)) { newVals.put(vals.get(i)); } } in.put(groupKey, newVals); // This is a best effort--we can't guarantee people and super properties match // If people property is not a list, this call does nothing. mPeople.remove(groupKey, groupID); } } catch (JSONException e) { in.remove(groupKey); // This is a best effort--we can't guarantee people and super properties match mPeople.unset(groupKey); } return in; } }); } /** * Returns a Mixpanel.People object that can be used to set and increment * People Analytics properties. * * @return an instance of {@link People} that you can use to update * records in Mixpanel People Analytics and manage Mixpanel Firebase Cloud Messaging notifications. */ public People getPeople() { return mPeople; } /** * Returns a Mixpanel.Group object that can be used to set and increment * Group Analytics properties. * * @param groupKey String identifying the type of group (must be already in use as a group key) * @param groupID Object identifying the specific group * @return an instance of {@link Group} that you can use to update * records in Mixpanel Group Analytics */ public Group getGroup(String groupKey, Object groupID) { String mapKey = makeMapKey(groupKey, groupID); GroupImpl group = mGroups.get(mapKey); if (group == null) { group = new GroupImpl(groupKey, groupID); mGroups.put(mapKey, group); } if (!(group.mGroupKey.equals(groupKey) && group.mGroupID.equals(groupID))) { // we hit a map key collision, return a new group with the correct key and ID MPLog.i(LOGTAG, "groups map key collision " + mapKey); group = new GroupImpl(groupKey, groupID); mGroups.put(mapKey, group); } return group; } private String makeMapKey(String groupKey, Object groupID) { return groupKey + '_' + groupID; } /** * Clears tweaks and all distinct_ids, superProperties, and push registrations from persistent storage. * Will not clear referrer information. */ public void reset() { // Will clear distinct_ids, superProperties, notifications, experiments, // and waiting People Analytics properties. Will have no effect // on messages already queued to send with AnalyticsMessages. mPersistentIdentity.clearPreferences(); getAnalyticsMessages().clearAnonymousUpdatesMessage(new AnalyticsMessages.MixpanelDescription(mToken)); identify(getDistinctId(), false); mConnectIntegrations.reset(); mUpdatesFromMixpanel.storeVariants(new JSONArray()); mUpdatesFromMixpanel.applyPersistedUpdates(); flush(); } /** * Returns an unmodifiable map that contains the device description properties * that will be sent to Mixpanel. These are not all of the default properties, * but are a subset that are dependant on the user's device or installed version * of the host application, and are guaranteed not to change while the app is running. */ public Map<String, String> getDeviceInfo() { return mDeviceInfo; } /** * Use this method to opt-out a user from tracking. Events and people updates that haven't been * flushed yet will be deleted. Use {@link #flush()} before calling this method if you want * to send all the queues to Mixpanel before. * * This method will also remove any user-related information from the device. */ public void optOutTracking() { getAnalyticsMessages().emptyTrackingQueues(new AnalyticsMessages.MixpanelDescription(mToken)); if (getPeople().isIdentified()) { getPeople().deleteUser(); getPeople().clearCharges(); } mPersistentIdentity.clearPreferences(); synchronized (mEventTimings) { mEventTimings.clear(); mPersistentIdentity.clearTimeEvents(); } mPersistentIdentity.clearReferrerProperties(); mPersistentIdentity.setOptOutTracking(true, mToken); } /** * Use this method to opt-in an already opted-out user from tracking. People updates and track * calls will be sent to Mixpanel after using this method. * This method will internally track an opt-in event to your project. If you want to identify * the opt-in event and/or pass properties to the event, see {@link #optInTracking(String)} and * {@link #optInTracking(String, JSONObject)} * * See also {@link #optOutTracking()}. */ public void optInTracking() { optInTracking(null, null); } /** * Use this method to opt-in an already opted-out user from tracking. People updates and track * calls will be sent to Mixpanel after using this method. * This method will internally track an opt-in event to your project. * * @param distinctId Optional string to use as the distinct ID for events. * This will call {@link #identify(String)}. * If you use people profiles make sure you manually call * {@link People#identify(String)} after this method. * * See also {@link #optInTracking(String)}, {@link #optInTracking(String, JSONObject)} and * {@link #optOutTracking()}. */ public void optInTracking(String distinctId) { optInTracking(distinctId, null); } /** * Use this method to opt-in an already opted-out user from tracking. People updates and track * calls will be sent to Mixpanel after using this method. * This method will internally track an opt-in event to your project. * * @param distinctId Optional string to use as the distinct ID for events. * This will call {@link #identify(String)}. * If you use people profiles make sure you manually call * {@link People#identify(String)} after this method. * @param properties Optional JSONObject that could be passed to add properties to the * opt-in event that is sent to Mixpanel. * * See also {@link #optInTracking()} and {@link #optOutTracking()}. */ public void optInTracking(String distinctId, JSONObject properties) { mPersistentIdentity.setOptOutTracking(false, mToken); if (distinctId != null) { identify(distinctId); } track("$opt_in", properties); } /** * Will return true if the user has opted out from tracking. See {@link #optOutTracking()} and * {@link MixpanelAPI#getInstance(Context, String, boolean, JSONObject)} for more information. * * @return true if user has opted out from tracking. Defaults to false. */ public boolean hasOptedOutTracking() { return mPersistentIdentity.getOptOutTracking(mToken); } /** * Core interface for using Mixpanel People Analytics features. * You can get an instance by calling {@link MixpanelAPI#getPeople()} * * <p>The People object is used to update properties in a user's People Analytics record, * and to manage the receipt of push notifications sent via Mixpanel Engage. * For this reason, it's important to call {@link #identify(String)} on the People * object before you work with it. Once you call identify, the user identity will * persist across stops and starts of your application, until you make another * call to identify using a different id. * * A typical use case for the People object might look like this: * * <pre> * {@code * * public class MainActivity extends Activity { * MixpanelAPI mMixpanel; * * public void onCreate(Bundle saved) { * mMixpanel = MixpanelAPI.getInstance(this, "YOUR MIXPANEL API TOKEN"); * mMixpanel.getPeople().identify("A UNIQUE ID FOR THIS USER"); * ... * } * * public void userUpdatedJobTitle(String newTitle) { * mMixpanel.getPeople().set("Job Title", newTitle); * ... * } * * public void onDestroy() { * mMixpanel.flush(); * super.onDestroy(); * } * } * * } * </pre> * * @see MixpanelAPI */ public interface People { /** * Associate future calls to {@link #set(JSONObject)}, {@link #increment(Map)}, * {@link #append(String, Object)}, etc... with a particular People Analytics user. * * <p>All future calls to the People object will rely on this value to assign * and increment properties. The user identification will persist across * restarts of your application. We recommend calling * People.identify as soon as you know the distinct id of the user. * * @param distinctId a String that uniquely identifies the user. Users identified with * the same distinct id will be considered to be the same user in Mixpanel, * across all platforms and devices. We recommend choosing a distinct id * that is meaningful to your other systems (for example, a server-side account * identifier), and using the same distinct id for both calls to People.identify * and {@link MixpanelAPI#identify(String)} * * @see MixpanelAPI#identify(String) */ public void identify(String distinctId); /** * Sets a single property with the given name and value for this user. * The given name and value will be assigned to the user in Mixpanel People Analytics, * possibly overwriting an existing property with the same name. * * @param propertyName The name of the Mixpanel property. This must be a String, for example "Zip Code" * @param value The value of the Mixpanel property. For "Zip Code", this value might be the String "90210" */ public void set(String propertyName, Object value); /** * Set a collection of properties on the identified user all at once. * * @param properties a Map containing the collection of properties you wish to apply * to the identified user. Each key in the Map will be associated with * a property name, and the value of that key will be assigned to the property. * * See also {@link #set(org.json.JSONObject)} */ public void setMap(Map<String, Object> properties); /** * Set a collection of properties on the identified user all at once. * * @param properties a JSONObject containing the collection of properties you wish to apply * to the identified user. Each key in the JSONObject will be associated with * a property name, and the value of that key will be assigned to the property. */ public void set(JSONObject properties); /** * Works just like {@link People#set(String, Object)}, except it will not overwrite existing property values. This is useful for properties like "First login date". * * @param propertyName The name of the Mixpanel property. This must be a String, for example "Zip Code" * @param value The value of the Mixpanel property. For "Zip Code", this value might be the String "90210" */ public void setOnce(String propertyName, Object value); /** * Like {@link People#set(String, Object)}, but will not set properties that already exist on a record. * * @param properties a Map containing the collection of properties you wish to apply * to the identified user. Each key in the Map will be associated with * a property name, and the value of that key will be assigned to the property. * * See also {@link #setOnce(org.json.JSONObject)} */ public void setOnceMap(Map<String, Object> properties); /** * Like {@link People#set(String, Object)}, but will not set properties that already exist on a record. * * @param properties a JSONObject containing the collection of properties you wish to apply * to the identified user. Each key in the JSONObject will be associated with * a property name, and the value of that key will be assigned to the property. */ public void setOnce(JSONObject properties); /** * Add the given amount to an existing property on the identified user. If the user does not already * have the associated property, the amount will be added to zero. To reduce a property, * provide a negative number for the value. * * @param name the People Analytics property that should have its value changed * @param increment the amount to be added to the current value of the named property * * @see #increment(Map) */ public void increment(String name, double increment); /** * Merge a given JSONObject into the object-valued property named name. If the user does not * already have the associated property, an new property will be created with the value of * the given updates. If the user already has a value for the given property, the updates will * be merged into the existing value, with key/value pairs in updates taking precedence over * existing key/value pairs where the keys are the same. * * @param name the People Analytics property that should have the update merged into it * @param updates a JSONObject with keys and values that will be merged into the property */ public void merge(String name, JSONObject updates); /** * Change the existing values of multiple People Analytics properties at once. * * <p>If the user does not already have the associated property, the amount will * be added to zero. To reduce a property, provide a negative number for the value. * * @param properties A map of String properties names to Long amounts. Each * property associated with a name in the map will have its value changed by the given amount * * @see #increment(String, double) */ public void increment(Map<String, ? extends Number> properties); /** * Appends a value to a list-valued property. If the property does not currently exist, * it will be created as a list of one element. If the property does exist and doesn't * currently have a list value, the append will be ignored. * @param name the People Analytics property that should have it's value appended to * @param value the new value that will appear at the end of the property's list */ public void append(String name, Object value); /** * Adds values to a list-valued property only if they are not already present in the list. * If the property does not currently exist, it will be created with the given list as it's value. * If the property exists and is not list-valued, the union will be ignored. * * @param name name of the list-valued property to set or modify * @param value an array of values to add to the property value if not already present */ void union(String name, JSONArray value); /** * Remove value from a list-valued property only if they are already present in the list. * If the property does not currently exist, the remove will be ignored. * If the property exists and is not list-valued, the remove will be ignored. * @param name the People Analytics property that should have it's value removed from * @param value the value that will be removed from the property's list */ public void remove(String name, Object value); /** * permanently removes the property with the given name from the user's profile * @param name name of a property to unset */ void unset(String name); /** * Track a revenue transaction for the identified people profile. * * @param amount the amount of money exchanged. Positive amounts represent purchases or income from the customer, negative amounts represent refunds or payments to the customer. * @param properties an optional collection of properties to associate with this transaction. */ public void trackCharge(double amount, JSONObject properties); /** * Permanently clear the whole transaction history for the identified people profile. */ public void clearCharges(); /** * Permanently deletes the identified user's record from People Analytics. * * <p>Calling deleteUser deletes an entire record completely. Any future calls * to People Analytics using the same distinct id will create and store new values. */ public void deleteUser(); /** * Checks if the people profile is identified or not. * * @return Whether the current user is identified or not. */ public boolean isIdentified(); /** * This is a no-op, and will be removed in future versions of the library. * * @deprecated in 5.5.0. Google Cloud Messaging (GCM) is now deprecated by Google. * To enable end-to-end Firebase Cloud Messaging (FCM) from Mixpanel you only need to add * the following to your application manifest XML file: * * <pre> * {@code * <service * android:name="com.mixpanel.android.mpmetrics.MixpanelFCMMessagingService" * android:enabled="true" * android:exported="false"> * <intent-filter> * <action android:name="com.google.firebase.MESSAGING_EVENT"/> * </intent-filter> * </service> * } * </pre> * * Make sure you have a valid google-services.json file in your project and firebase * messaging is included as a dependency. Example: * * <pre> * {@code * buildscript { * ... * dependencies { * classpath 'com.google.gms:google-services:4.1.0' * ... * } * } * * dependencies { * implementation 'com.google.firebase:firebase-messaging:17.3.4' * implementation 'com.mixpanel.android:mixpanel-android:5.5.0' * } * * apply plugin: 'com.google.gms.google-services' * } * </pre> * * We recommend you update your Server Key on mixpanel.com from your Firebase console. Legacy * server keys are still supported. * * @see <a href="https://mixpanel.com/docs/people-analytics/android-push">Getting Started with Android Push Notifications</a> */ @Deprecated public void initPushHandling(String senderID); /** * Retrieves current Firebase Cloud Messaging token. * * <p>{@link People#getPushRegistrationId} should only be called after {@link #identify(String)} has been called. * * @return FCM push token or null if the user has not been registered in FCM. * * @see #setPushRegistrationId(String) * @see #clearPushRegistrationId */ public String getPushRegistrationId(); /** * Manually send a Firebase Cloud Messaging token to Mixpanel. * * <p>If you are handling Firebase Cloud Messages in your own application, but would like to * allow Mixpanel to handle messages originating from Mixpanel campaigns, you should * call setPushRegistrationId with the FCM token. * * <p>setPushRegistrationId should only be called after {@link #identify(String)} has been called. * * Optionally, applications that call setPushRegistrationId should also call * {@link #clearPushRegistrationId()} when they unregister the device id. * * @param token Firebase Cloud Messaging token * * @see #clearPushRegistrationId() */ public void setPushRegistrationId(String token); /** * Manually clear all current Firebase Cloud Messaging tokens from Mixpanel. * * <p>{@link People#clearPushRegistrationId} should only be called after {@link #identify(String)} has been called. * * <p>In general, all applications that call {@link #setPushRegistrationId(String)} should include a call to * clearPushRegistrationId. */ public void clearPushRegistrationId(); /** * Manually clear a single Firebase Cloud Messaging token from Mixpanel. * * <p>{@link People#clearPushRegistrationId} should only be called after {@link #identify(String)} has been called. * * <p>In general, all applications that call {@link #setPushRegistrationId(String)} should include a call to * clearPushRegistrationId. */ public void clearPushRegistrationId(String registrationId); /** * Returns the string id currently being used to uniquely identify the user associated * with events sent using {@link People#set(String, Object)} and {@link People#increment(String, double)}. * If no calls to {@link People#identify(String)} have been made, this method will return null. * * <p>The id returned by getDistinctId is independent of the distinct id used to identify * any events sent with {@link MixpanelAPI#track(String, JSONObject)}. To read and write that identifier, * use {@link MixpanelAPI#identify(String)} and {@link MixpanelAPI#getDistinctId()}. * * @return The distinct id associated with updates to People Analytics * * @see People#identify(String) * @see MixpanelAPI#getDistinctId() */ public String getDistinctId(); /** * Shows an in-app notification to the user if one is available. If the notification * is a mini notification, this method will attach and remove a Fragment to parent. * The lifecycle of the Fragment will be handled entirely by the Mixpanel library. * * <p>If the notification is a takeover notification, a TakeoverInAppActivity will be launched to * display the Takeover notification. * * <p>It is safe to call this method any time you want to potentially display an in-app notification. * This method will be a no-op if there is already an in-app notification being displayed. * * <p>This method is a no-op in environments with * Android API before JellyBean/API level 16. * * @param parent the Activity that the mini notification will be displayed in, or the Activity * that will be used to launch TakeoverInAppActivity for the takeover notification. */ public void showNotificationIfAvailable(Activity parent); /** * Applies A/B test changes, if they are present. By default, your application will attempt * to join available experiments any time an activity is resumed, but you can disable this * automatic behavior by adding the following tag to the &lt;application&gt; tag in your AndroidManifest.xml * {@code * <meta-data android:name="com.mixpanel.android.MPConfig.AutoShowMixpanelUpdates" * android:value="false" /> * } * * If you disable AutoShowMixpanelUpdates, you'll need to call joinExperimentIfAvailable to * join or clear existing experiments. If you want to display a loading screen or otherwise * wait for experiments to load from the server before you apply them, you can use * {@link #addOnMixpanelUpdatesReceivedListener(OnMixpanelUpdatesReceivedListener)} to * be informed that new experiments are ready. */ public void joinExperimentIfAvailable(); /** * Shows the given in-app notification to the user. Display will occur just as if the * notification was shown via showNotificationIfAvailable. In most cases, it is * easier and more efficient to use showNotificationIfAvailable. * * @param notif the {@link com.mixpanel.android.mpmetrics.InAppNotification} to show * * @param parent the Activity that the mini notification will be displayed in, or the Activity * that will be used to launch TakeoverInAppActivity for the takeover notification. */ public void showGivenNotification(InAppNotification notif, Activity parent); /** * Sends an event to Mixpanel that includes the automatic properties associated * with the given notification. In most cases this is not required, unless you're * not showing notifications using the library-provided in views and activities. * * @param eventName the name to use when the event is tracked. * * @param notif the {@link com.mixpanel.android.mpmetrics.InAppNotification} associated with the event you'd like to track. * * @param properties additional properties to be tracked with the event. */ public void trackNotification(String eventName, InAppNotification notif, JSONObject properties); /** * Returns an InAppNotification object if one is available and being held by the library, or null if * no notification is currently available. Callers who want to display in-app notifications should call this * method periodically. A given InAppNotification will be returned only once from this method, so callers * should be ready to consume any non-null return value. * * <p>This function will return quickly, and will not cause any communication with * Mixpanel's servers, so it is safe to call this from the UI thread. * * Note: you must call call {@link People#trackNotificationSeen(InAppNotification)} or you will * receive the same {@link com.mixpanel.android.mpmetrics.InAppNotification} again the * next time notifications are refreshed from Mixpanel's servers (on identify, or when * your app is destroyed and re-created) * * @return an InAppNotification object if one is available, null otherwise. */ public InAppNotification getNotificationIfAvailable(); /** * Tells MixPanel that you have handled an {@link com.mixpanel.android.mpmetrics.InAppNotification} * in the case where you are manually dealing with your notifications ({@link People#getNotificationIfAvailable()}). * * Note: if you do not acknowledge the notification you will receive it again each time * you call {@link People#identify(String)} and then call {@link People#getNotificationIfAvailable()} * * @param notif the notification to track (no-op on null) */ void trackNotificationSeen(InAppNotification notif); /** * Shows an in-app notification identified by id. The behavior of this is otherwise identical to * {@link People#showNotificationIfAvailable(Activity)}. * * @param id the id of the InAppNotification you wish to show. * @param parent the Activity that the mini notification will be displayed in, or the Activity * that will be used to launch TakeoverInAppActivity for the takeover notification. */ public void showNotificationById(int id, final Activity parent); /** * Return an instance of Mixpanel people with a temporary distinct id. * Instances returned by withIdentity will not check decide with the given distinctId. */ public People withIdentity(String distinctId); /** * Adds a new listener that will receive a callback when new updates from Mixpanel * (like in-app notifications or A/B test experiments) are discovered. Most users of the library * will not need this method since in-app notifications and experiments are * applied automatically to your application by default. * * <p>The given listener will be called when a new batch of updates is detected. Handlers * should be prepared to handle the callback on an arbitrary thread. * * <p>The listener will be called when new in-app notifications or experiments * are detected as available. That means you wait to call * {@link People#showNotificationIfAvailable(Activity)}, and {@link People#joinExperimentIfAvailable()} * to show content and updates that have been delivered to your app. (You can also call these * functions whenever else you would like, they're inexpensive and will do nothing if no * content is available.) * * @param listener the listener to add */ public void addOnMixpanelUpdatesReceivedListener(OnMixpanelUpdatesReceivedListener listener); /** * Removes a listener previously registered with addOnMixpanelUpdatesReceivedListener. * * @param listener the listener to add */ public void removeOnMixpanelUpdatesReceivedListener(OnMixpanelUpdatesReceivedListener listener); /** * Sets the listener that will receive a callback when new Tweaks from Mixpanel are discovered. Most * users of the library will not need this method, since Tweaks are applied automatically to your * application by default. * * <p>The given listener will be called when a new batch of Tweaks is applied. Handlers * should be prepared to handle the callback on an arbitrary thread. * * <p>The listener will be called when new Tweaks are detected as available. That means the listener * will get called once {@link People#joinExperimentIfAvailable()} has successfully applied the changes. * * @param listener the listener to set */ public void addOnMixpanelTweaksUpdatedListener(OnMixpanelTweaksUpdatedListener listener); /** * Removes the listener previously registered with addOnMixpanelTweaksUpdatedListener. * */ public void removeOnMixpanelTweaksUpdatedListener(OnMixpanelTweaksUpdatedListener listener); } /** * Core interface for using Mixpanel Group Analytics features. * You can get an instance by calling {@link MixpanelAPI#getGroup(String, Object)} * * <p>The Group object is used to update properties in a group's Group Analytics record. * * A typical use case for the Group object might look like this: * * <pre> * {@code * * public class MainActivity extends Activity { * MixpanelAPI mMixpanel; * * public void onCreate(Bundle saved) { * mMixpanel = MixpanelAPI.getInstance(this, "YOUR MIXPANEL API TOKEN"); * ... * } * * public void companyPlanTypeChanged(string company, String newPlan) { * mMixpanel.getGroup("Company", company).set("Plan Type", newPlan); * ... * } * * public void onDestroy() { * mMixpanel.flush(); * super.onDestroy(); * } * } * * } * </pre> * * @see MixpanelAPI */ public interface Group { /** * Sets a single property with the given name and value for this group. * The given name and value will be assigned to the user in Mixpanel Group Analytics, * possibly overwriting an existing property with the same name. * * @param propertyName The name of the Mixpanel property. This must be a String, for example "Zip Code" * @param value The value of the Mixpanel property. For "Zip Code", this value might be the String "90210" */ public void set(String propertyName, Object value); /** * Set a collection of properties on the identified group all at once. * * @param properties a Map containing the collection of properties you wish to apply * to the identified group. Each key in the Map will be associated with * a property name, and the value of that key will be assigned to the property. * * See also {@link #set(org.json.JSONObject)} */ public void setMap(Map<String, Object> properties); /** * Set a collection of properties on the identified group all at once. * * @param properties a JSONObject containing the collection of properties you wish to apply * to the identified group. Each key in the JSONObject will be associated with * a property name, and the value of that key will be assigned to the property. */ public void set(JSONObject properties); /** * Works just like {@link Group#set(String, Object)}, except it will not overwrite existing property values. This is useful for properties like "First login date". * * @param propertyName The name of the Mixpanel property. This must be a String, for example "Zip Code" * @param value The value of the Mixpanel property. For "Zip Code", this value might be the String "90210" */ public void setOnce(String propertyName, Object value); /** * Like {@link Group#set(String, Object)}, but will not set properties that already exist on a record. * * @param properties a Map containing the collection of properties you wish to apply * to the identified group. Each key in the Map will be associated with * a property name, and the value of that key will be assigned to the property. * * See also {@link #setOnce(org.json.JSONObject)} */ public void setOnceMap(Map<String, Object> properties); /** * Like {@link Group#set(String, Object)}, but will not set properties that already exist on a record. * * @param properties a JSONObject containing the collection of properties you wish to apply * to this group. Each key in the JSONObject will be associated with * a property name, and the value of that key will be assigned to the property. */ public void setOnce(JSONObject properties); /** * Adds values to a list-valued property only if they are not already present in the list. * If the property does not currently exist, it will be created with the given list as its value. * If the property exists and is not list-valued, the union will be ignored. * * @param name name of the list-valued property to set or modify * @param value an array of values to add to the property value if not already present */ void union(String name, JSONArray value); /** * Remove value from a list-valued property only if it is already present in the list. * If the property does not currently exist, the remove will be ignored. * If the property exists and is not list-valued, the remove will be ignored. * * @param name the Group Analytics list-valued property that should have a value removed * @param value the value that will be removed from the list */ public void remove(String name, Object value); /** * Permanently removes the property with the given name from the group's profile * @param name name of a property to unset */ void unset(String name); /** * Permanently deletes this group's record from Group Analytics. * * <p>Calling deleteGroup deletes an entire record completely. Any future calls * to Group Analytics using the same group value will create and store new values. */ public void deleteGroup(); } /** * This method is a no-op, kept for compatibility purposes. * * To enable verbose logging about communication with Mixpanel, add * {@code * <meta-data android:name="com.mixpanel.android.MPConfig.EnableDebugLogging" /> * } * * To the {@code <application>} tag of your AndroidManifest.xml file. * * @deprecated in 4.1.0, use Manifest meta-data instead */ @Deprecated public void logPosts() { MPLog.i( LOGTAG, "MixpanelAPI.logPosts() is deprecated.\n" + " To get verbose debug level logging, add\n" + " <meta-data android:name=\"com.mixpanel.android.MPConfig.EnableDebugLogging\" value=\"true\" />\n" + " to the <application> section of your AndroidManifest.xml." ); } /** * Attempt to register MixpanelActivityLifecycleCallbacks to the application's event lifecycle. * Once registered, we can automatically check for and show in-app notifications * when any Activity is opened. * * This is only available if the android version is >= 16. You can disable livecycle callbacks by setting * com.mixpanel.android.MPConfig.AutoShowMixpanelUpdates to false in your AndroidManifest.xml * * This function is automatically called when the library is initialized unless you explicitly * set com.mixpanel.android.MPConfig.AutoShowMixpanelUpdates to false in your AndroidManifest.xml */ @TargetApi(Build.VERSION_CODES.ICE_CREAM_SANDWICH) /* package */ void registerMixpanelActivityLifecycleCallbacks() { if (android.os.Build.VERSION.SDK_INT >= Build.VERSION_CODES.ICE_CREAM_SANDWICH) { if (mContext.getApplicationContext() instanceof Application) { final Application app = (Application) mContext.getApplicationContext(); mMixpanelActivityLifecycleCallbacks = new MixpanelActivityLifecycleCallbacks(this, mConfig); app.registerActivityLifecycleCallbacks(mMixpanelActivityLifecycleCallbacks); } else { MPLog.i(LOGTAG, "Context is not an Application, Mixpanel will not automatically show in-app notifications or A/B test experiments. We won't be able to automatically flush on an app background."); } } } /** * Based on the application's event lifecycle this method will determine whether the app * is running in the foreground or not. * * If your build version is below 14 this method will always return false. * * @return True if the app is running in the foreground. */ public boolean isAppInForeground() { if (android.os.Build.VERSION.SDK_INT >= Build.VERSION_CODES.ICE_CREAM_SANDWICH) { if (mMixpanelActivityLifecycleCallbacks != null) { return mMixpanelActivityLifecycleCallbacks.isInForeground(); } } else { MPLog.e(LOGTAG, "Your build version is below 14. This method will always return false."); } return false; } /* package */ void onBackground() { flush(); mUpdatesFromMixpanel.applyPersistedUpdates(); } /* package */ void onForeground() { mSessionMetadata.initSession(); } // Package-level access. Used (at least) by MixpanelFCMMessagingService // when OS-level events occur. /* package */ interface InstanceProcessor { public void process(MixpanelAPI m); } /* package */ static void allInstances(InstanceProcessor processor) { synchronized (sInstanceMap) { for (final Map<Context, MixpanelAPI> contextInstances : sInstanceMap.values()) { for (final MixpanelAPI instance : contextInstances.values()) { processor.process(instance); } } } } //////////////////////////////////////////////////////////////////// // Conveniences for testing. These methods should not be called by // non-test client code. /* package */ AnalyticsMessages getAnalyticsMessages() { return AnalyticsMessages.getInstance(mContext); } /* package */ DecideMessages getDecideMessages() { return mDecideMessages; } /* package */ PersistentIdentity getPersistentIdentity(final Context context, Future<SharedPreferences> referrerPreferences, final String token) { final SharedPreferencesLoader.OnPrefsLoadedListener listener = new SharedPreferencesLoader.OnPrefsLoadedListener() { @Override public void onPrefsLoaded(SharedPreferences preferences) { final String distinctId = PersistentIdentity.getPeopleDistinctId(preferences); if (null != distinctId) { pushWaitingPeopleRecord(distinctId); } } }; final String prefsName = "com.mixpanel.android.mpmetrics.MixpanelAPI_" + token; final Future<SharedPreferences> storedPreferences = sPrefsLoader.loadPreferences(context, prefsName, listener); final String timeEventsPrefsName = "com.mixpanel.android.mpmetrics.MixpanelAPI.TimeEvents_" + token; final Future<SharedPreferences> timeEventsPrefs = sPrefsLoader.loadPreferences(context, timeEventsPrefsName, null); final String mixpanelPrefsName = "com.mixpanel.android.mpmetrics.Mixpanel"; final Future<SharedPreferences> mixpanelPrefs = sPrefsLoader.loadPreferences(context, mixpanelPrefsName, null); return new PersistentIdentity(referrerPreferences, storedPreferences, timeEventsPrefs, mixpanelPrefs); } /* package */ DecideMessages constructDecideUpdates(final String token, final DecideMessages.OnNewResultsListener listener, UpdatesFromMixpanel updatesFromMixpanel) { return new DecideMessages(mContext, token, listener, updatesFromMixpanel, mPersistentIdentity.getSeenCampaignIds()); } /* package */ UpdatesListener constructUpdatesListener() { if (Build.VERSION.SDK_INT < MPConfig.UI_FEATURES_MIN_API) { MPLog.i(LOGTAG, "Notifications are not supported on this Android OS Version"); return new UnsupportedUpdatesListener(); } else { return new SupportedUpdatesListener(); } } /* package */ UpdatesFromMixpanel constructUpdatesFromMixpanel(final Context context, final String token) { if (Build.VERSION.SDK_INT < MPConfig.UI_FEATURES_MIN_API) { MPLog.i(LOGTAG, "SDK version is lower than " + MPConfig.UI_FEATURES_MIN_API + ". Web Configuration, A/B Testing, and Dynamic Tweaks are disabled."); return new NoOpUpdatesFromMixpanel(sSharedTweaks); } else if (mConfig.getDisableViewCrawler() || Arrays.asList(mConfig.getDisableViewCrawlerForProjects()).contains(token)) { MPLog.i(LOGTAG, "DisableViewCrawler is set to true. Web Configuration, A/B Testing, and Dynamic Tweaks are disabled."); return new NoOpUpdatesFromMixpanel(sSharedTweaks); } else { return new ViewCrawler(mContext, mToken, this, sSharedTweaks); } } /* package */ TrackingDebug constructTrackingDebug() { if (mUpdatesFromMixpanel instanceof ViewCrawler) { return (TrackingDebug) mUpdatesFromMixpanel; } return null; } /* package */ boolean sendAppOpen() { return !mConfig.getDisableAppOpenEvent(); } /////////////////////// private class PeopleImpl implements People { @Override public void identify(String distinctId) { if (hasOptedOutTracking()) return; synchronized (mPersistentIdentity) { mPersistentIdentity.setPeopleDistinctId(distinctId); mDecideMessages.setDistinctId(distinctId); } pushWaitingPeopleRecord(distinctId); } @Override public void setMap(Map<String, Object> properties) { if (hasOptedOutTracking()) return; if (null == properties) { MPLog.e(LOGTAG, "setMap does not accept null properties"); return; } try { set(new JSONObject(properties)); } catch (NullPointerException e) { MPLog.w(LOGTAG, "Can't have null keys in the properties of setMap!"); } } @Override public void set(JSONObject properties) { if (hasOptedOutTracking()) return; try { final JSONObject sendProperties = new JSONObject(mDeviceInfo); for (final Iterator<?> iter = properties.keys(); iter.hasNext();) { final String key = (String) iter.next(); sendProperties.put(key, properties.get(key)); } final JSONObject message = stdPeopleMessage("$set", sendProperties); recordPeopleMessage(message); } catch (final JSONException e) { MPLog.e(LOGTAG, "Exception setting people properties", e); } } @Override public void set(String property, Object value) { if (hasOptedOutTracking()) return; try { set(new JSONObject().put(property, value)); } catch (final JSONException e) { MPLog.e(LOGTAG, "set", e); } } @Override public void setOnceMap(Map<String, Object> properties) { if (hasOptedOutTracking()) return; if (null == properties) { MPLog.e(LOGTAG, "setOnceMap does not accept null properties"); return; } try { setOnce(new JSONObject(properties)); } catch (NullPointerException e) { MPLog.w(LOGTAG, "Can't have null keys in the properties setOnceMap!"); } } @Override public void setOnce(JSONObject properties) { if (hasOptedOutTracking()) return; try { final JSONObject message = stdPeopleMessage("$set_once", properties); recordPeopleMessage(message); } catch (final JSONException e) { MPLog.e(LOGTAG, "Exception setting people properties"); } } @Override public void setOnce(String property, Object value) { if (hasOptedOutTracking()) return; try { setOnce(new JSONObject().put(property, value)); } catch (final JSONException e) { MPLog.e(LOGTAG, "set", e); } } @Override public void increment(Map<String, ? extends Number> properties) { if (hasOptedOutTracking()) return; final JSONObject json = new JSONObject(properties); try { final JSONObject message = stdPeopleMessage("$add", json); recordPeopleMessage(message); } catch (final JSONException e) { MPLog.e(LOGTAG, "Exception incrementing properties", e); } } @Override // Must be thread safe public void merge(String property, JSONObject updates) { if (hasOptedOutTracking()) return; final JSONObject mergeMessage = new JSONObject(); try { mergeMessage.put(property, updates); final JSONObject message = stdPeopleMessage("$merge", mergeMessage); recordPeopleMessage(message); } catch (final JSONException e) { MPLog.e(LOGTAG, "Exception merging a property", e); } } @Override public void increment(String property, double value) { if (hasOptedOutTracking()) return; final Map<String, Double> map = new HashMap<String, Double>(); map.put(property, value); increment(map); } @Override public void append(String name, Object value) { if (hasOptedOutTracking()) return; try { final JSONObject properties = new JSONObject(); properties.put(name, value); final JSONObject message = stdPeopleMessage("$append", properties); recordPeopleMessage(message); } catch (final JSONException e) { MPLog.e(LOGTAG, "Exception appending a property", e); } } @Override public void union(String name, JSONArray value) { if (hasOptedOutTracking()) return; try { final JSONObject properties = new JSONObject(); properties.put(name, value); final JSONObject message = stdPeopleMessage("$union", properties); recordPeopleMessage(message); } catch (final JSONException e) { MPLog.e(LOGTAG, "Exception unioning a property"); } } @Override public void remove(String name, Object value) { if (hasOptedOutTracking()) return; try { final JSONObject properties = new JSONObject(); properties.put(name, value); final JSONObject message = stdPeopleMessage("$remove", properties); recordPeopleMessage(message); } catch (final JSONException e) { MPLog.e(LOGTAG, "Exception appending a property", e); } } @Override public void unset(String name) { if (hasOptedOutTracking()) return; try { final JSONArray names = new JSONArray(); names.put(name); final JSONObject message = stdPeopleMessage("$unset", names); recordPeopleMessage(message); } catch (final JSONException e) { MPLog.e(LOGTAG, "Exception unsetting a property", e); } } @Override public InAppNotification getNotificationIfAvailable() { return mDecideMessages.getNotification(mConfig.getTestMode()); } @Override public void trackNotificationSeen(InAppNotification notif) { if (notif == null) return; mPersistentIdentity.saveCampaignAsSeen(notif.getId()); if (hasOptedOutTracking()) return; trackNotification("$campaign_delivery", notif, null); final MixpanelAPI.People people = getPeople().withIdentity(getDistinctId()); if (people != null) { final DateFormat dateFormat = new SimpleDateFormat(ENGAGE_DATE_FORMAT_STRING, Locale.US); final JSONObject notifProperties = notif.getCampaignProperties(); try { notifProperties.put("$time", dateFormat.format(new Date())); } catch (final JSONException e) { MPLog.e(LOGTAG, "Exception trying to track an in-app notification seen", e); } people.append("$campaigns", notif.getId()); people.append("$notifications", notifProperties); } else { MPLog.e(LOGTAG, "No identity found. Make sure to call getPeople().identify() before showing in-app notifications."); } } @Override public void showNotificationIfAvailable(final Activity parent) { if (Build.VERSION.SDK_INT < MPConfig.UI_FEATURES_MIN_API) { return; } showGivenOrAvailableNotification(null, parent); } @Override public void showNotificationById(int id, final Activity parent) { final InAppNotification notif = mDecideMessages.getNotification(id, mConfig.getTestMode()); showGivenNotification(notif, parent); } @Override public void showGivenNotification(final InAppNotification notif, final Activity parent) { if (notif != null) { showGivenOrAvailableNotification(notif, parent); } } @Override public void trackNotification(final String eventName, final InAppNotification notif, final JSONObject properties) { if (hasOptedOutTracking()) return; JSONObject notificationProperties = notif.getCampaignProperties(); if (properties != null) { try { Iterator<String> keyIterator = properties.keys(); while (keyIterator.hasNext()) { String key = keyIterator.next(); notificationProperties.put(key, properties.get(key)); } } catch (final JSONException e) { MPLog.e(LOGTAG, "Exception merging provided properties with notification properties", e); } } track(eventName, notificationProperties); } @Override public void joinExperimentIfAvailable() { final JSONArray variants = mDecideMessages.getVariants(); mUpdatesFromMixpanel.setVariants(variants); } @Override public void trackCharge(double amount, JSONObject properties) { if (hasOptedOutTracking()) return; final Date now = new Date(); final DateFormat dateFormat = new SimpleDateFormat(ENGAGE_DATE_FORMAT_STRING, Locale.US); dateFormat.setTimeZone(TimeZone.getTimeZone("UTC")); try { final JSONObject transactionValue = new JSONObject(); transactionValue.put("$amount", amount); transactionValue.put("$time", dateFormat.format(now)); if (null != properties) { for (final Iterator<?> iter = properties.keys(); iter.hasNext();) { final String key = (String) iter.next(); transactionValue.put(key, properties.get(key)); } } this.append("$transactions", transactionValue); } catch (final JSONException e) { MPLog.e(LOGTAG, "Exception creating new charge", e); } } /** * Permanently clear the whole transaction history for the identified people profile. */ @Override public void clearCharges() { this.unset("$transactions"); } @Override public void deleteUser() { try { final JSONObject message = stdPeopleMessage("$delete", JSONObject.NULL); recordPeopleMessage(message); } catch (final JSONException e) { MPLog.e(LOGTAG, "Exception deleting a user"); } } @Override public String getPushRegistrationId() { return mPersistentIdentity.getPushId(); } @Override public void setPushRegistrationId(String registrationId) { String existingRegistrationId = getPushRegistrationId(); if (existingRegistrationId != null && existingRegistrationId.equals(registrationId)) { return; } // Must be thread safe, will be called from a lot of different threads. synchronized (mPersistentIdentity) { MPLog.d(LOGTAG, "Setting new push token on people profile: " + registrationId); mPersistentIdentity.storePushId(registrationId); final JSONArray ids = new JSONArray(); ids.put(registrationId); union("$android_devices", ids); } } @Override public void clearPushRegistrationId() { mPersistentIdentity.clearPushId(); set("$android_devices", new JSONArray()); } @Override public void clearPushRegistrationId(String registrationId) { if (registrationId == null) { return; } if (registrationId.equals(mPersistentIdentity.getPushId())) { mPersistentIdentity.clearPushId(); } remove("$android_devices", registrationId); } @Override public void initPushHandling(String senderID) { MPLog.w( LOGTAG, "MixpanelAPI.initPushHandling is deprecated. This is a no-op.\n" + " Mixpanel now uses Firebase Cloud Messaging. You need to remove your old Mixpanel" + " GCM Receiver from your AndroidManifest.xml and add the following:\n" + " <service\n" + " android:name=\"com.mixpanel.android.mpmetrics.MixpanelFCMMessagingService\"\n" + " android:enabled=\"true\"\n" + " android:exported=\"false\">\n" + " <intent-filter>\n" + " <action android:name=\"com.google.firebase.MESSAGING_EVENT\"/>\n" + " </intent-filter>\n" + " </service>\n\n" + "Make sure to add firebase messaging as a dependency on your gradle file:\n" + "buildscript {\n" + " ...\n" + " dependencies {\n" + " classpath 'com.google.gms:google-services:4.1.0'\n" + " ...\n" + " }\n" + "}\n" + "dependencies {\n" + " implementation 'com.google.firebase:firebase-messaging:17.3.4'\n" + " implementation 'com.mixpanel.android:mixpanel-android:5.5.0'\n" + "}\n" + "apply plugin: 'com.google.gms.google-services'" ); } @Override public String getDistinctId() { return mPersistentIdentity.getPeopleDistinctId(); } @Override public People withIdentity(final String distinctId) { if (null == distinctId) { return null; } return new PeopleImpl() { @Override public String getDistinctId() { return distinctId; } @Override public void identify(String distinctId) { throw new RuntimeException("This MixpanelPeople object has a fixed, constant distinctId"); } }; } @Override public void addOnMixpanelUpdatesReceivedListener(final OnMixpanelUpdatesReceivedListener listener) { mUpdatesListener.addOnMixpanelUpdatesReceivedListener(listener); } @Override public void removeOnMixpanelUpdatesReceivedListener(final OnMixpanelUpdatesReceivedListener listener) { mUpdatesListener.removeOnMixpanelUpdatesReceivedListener(listener); } @Override public void addOnMixpanelTweaksUpdatedListener(OnMixpanelTweaksUpdatedListener listener) { if (null == listener) { throw new NullPointerException("Listener cannot be null"); } mUpdatesFromMixpanel.addOnMixpanelTweaksUpdatedListener(listener); } @Override public void removeOnMixpanelTweaksUpdatedListener(OnMixpanelTweaksUpdatedListener listener) { mUpdatesFromMixpanel.removeOnMixpanelTweaksUpdatedListener(listener); } private JSONObject stdPeopleMessage(String actionType, Object properties) throws JSONException { final JSONObject dataObj = new JSONObject(); final String distinctId = getDistinctId(); // TODO ensure getDistinctId is thread safe final String anonymousId = getAnonymousId(); dataObj.put(actionType, properties); dataObj.put("$token", mToken); dataObj.put("$time", System.currentTimeMillis()); dataObj.put("$had_persisted_distinct_id", mPersistentIdentity.getHadPersistedDistinctId()); if (null != anonymousId) { dataObj.put("$device_id", anonymousId); } if (null != distinctId) { dataObj.put("$distinct_id", distinctId); dataObj.put("$user_id", distinctId); } dataObj.put("$mp_metadata", mSessionMetadata.getMetadataForPeople()); return dataObj; } private void showGivenOrAvailableNotification(final InAppNotification notifOrNull, final Activity parent) { if (Build.VERSION.SDK_INT < MPConfig.UI_FEATURES_MIN_API) { MPLog.v(LOGTAG, "Will not show notifications, os version is too low."); return; } parent.runOnUiThread(new Runnable() { @Override @TargetApi(MPConfig.UI_FEATURES_MIN_API) public void run() { final ReentrantLock lock = UpdateDisplayState.getLockObject(); lock.lock(); try { if (UpdateDisplayState.hasCurrentProposal()) { MPLog.v(LOGTAG, "DisplayState is locked, will not show notifications."); return; // Already being used. } InAppNotification toShow = notifOrNull; if (null == toShow) { toShow = getNotificationIfAvailable(); } if (null == toShow) { MPLog.v(LOGTAG, "No notification available, will not show."); return; // Nothing to show } final InAppNotification.Type inAppType = toShow.getType(); if (inAppType == InAppNotification.Type.TAKEOVER && !ConfigurationChecker.checkTakeoverInAppActivityAvailable(parent.getApplicationContext())) { MPLog.v(LOGTAG, "Application is not configured to show takeover notifications, none will be shown."); return; // Can't show due to config. } final int highlightColor = ActivityImageUtils.getHighlightColorFromBackground(parent); final UpdateDisplayState.DisplayState.InAppNotificationState proposal = new UpdateDisplayState.DisplayState.InAppNotificationState(toShow, highlightColor); final int intentId = UpdateDisplayState.proposeDisplay(proposal, getDistinctId(), mToken); if (intentId <= 0) { MPLog.e(LOGTAG, "DisplayState Lock in inconsistent state! Please report this issue to Mixpanel"); return; } switch (inAppType) { case MINI: { final UpdateDisplayState claimed = UpdateDisplayState.claimDisplayState(intentId); if (null == claimed) { MPLog.v(LOGTAG, "Notification's display proposal was already consumed, no notification will be shown."); return; // Can't claim the display state } final InAppFragment inapp = new InAppFragment(); inapp.setDisplayState( MixpanelAPI.this, intentId, (UpdateDisplayState.DisplayState.InAppNotificationState) claimed.getDisplayState() ); inapp.setRetainInstance(true); MPLog.v(LOGTAG, "Attempting to show mini notification."); final FragmentTransaction transaction = parent.getFragmentManager().beginTransaction(); transaction.setCustomAnimations(0, R.animator.com_mixpanel_android_slide_down); transaction.add(android.R.id.content, inapp); try { transaction.commit(); } catch (IllegalStateException e) { // if the app is in the background or the current activity gets killed, rendering the // notifiction will lead to a crash MPLog.v(LOGTAG, "Unable to show notification."); mDecideMessages.markNotificationAsUnseen(toShow); } } break; case TAKEOVER: { MPLog.v(LOGTAG, "Sending intent for takeover notification."); final Intent intent = new Intent(parent.getApplicationContext(), TakeoverInAppActivity.class); intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK); intent.addFlags(Intent.FLAG_ACTIVITY_REORDER_TO_FRONT); intent.putExtra(TakeoverInAppActivity.INTENT_ID_KEY, intentId); parent.startActivity(intent); } break; default: MPLog.e(LOGTAG, "Unrecognized notification type " + inAppType + " can't be shown"); } if (!mConfig.getTestMode()) { trackNotificationSeen(toShow); } } finally { lock.unlock(); } } // run() }); } @Override public boolean isIdentified() { return getDistinctId() != null; } }// PeopleImpl private interface UpdatesListener extends DecideMessages.OnNewResultsListener { public void addOnMixpanelUpdatesReceivedListener(OnMixpanelUpdatesReceivedListener listener); public void removeOnMixpanelUpdatesReceivedListener(OnMixpanelUpdatesReceivedListener listener); } private class UnsupportedUpdatesListener implements UpdatesListener { @Override public void onNewResults() { // Do nothing, these features aren't supported in older versions of the library } @Override public void addOnMixpanelUpdatesReceivedListener(OnMixpanelUpdatesReceivedListener listener) { // Do nothing, not supported } @Override public void removeOnMixpanelUpdatesReceivedListener(OnMixpanelUpdatesReceivedListener listener) { // Do nothing, not supported } } private class GroupImpl implements Group { private String mGroupKey; private Object mGroupID; public GroupImpl(String groupKey, Object groupID) { mGroupKey = groupKey; mGroupID = groupID; } @Override public void setMap(Map<String, Object> properties) { if (hasOptedOutTracking()) return; if (null == properties) { MPLog.e(LOGTAG, "setMap does not accept null properties"); return; } set(new JSONObject(properties)); } @Override public void set(JSONObject properties) { if (hasOptedOutTracking()) return; try { final JSONObject sendProperties = new JSONObject(); for (final Iterator<?> iter = properties.keys(); iter.hasNext();) { final String key = (String) iter.next(); sendProperties.put(key, properties.get(key)); } final JSONObject message = stdGroupMessage("$set", sendProperties); recordGroupMessage(message); } catch (final JSONException e) { MPLog.e(LOGTAG, "Exception setting group properties", e); } } @Override public void set(String property, Object value) { if (hasOptedOutTracking()) return; try { set(new JSONObject().put(property, value)); } catch (final JSONException e) { MPLog.e(LOGTAG, "set", e); } } @Override public void setOnceMap(Map<String, Object> properties) { if (hasOptedOutTracking()) return; if (null == properties) { MPLog.e(LOGTAG, "setOnceMap does not accept null properties"); return; } try { setOnce(new JSONObject(properties)); } catch (NullPointerException e) { MPLog.w(LOGTAG, "Can't have null keys in the properties for setOnceMap!"); } } @Override public void setOnce(JSONObject properties) { if (hasOptedOutTracking()) return; try { final JSONObject message = stdGroupMessage("$set_once", properties); recordGroupMessage(message); } catch (final JSONException e) { MPLog.e(LOGTAG, "Exception setting group properties"); } } @Override public void setOnce(String property, Object value) { if (hasOptedOutTracking()) return; try { setOnce(new JSONObject().put(property, value)); } catch (final JSONException e) { MPLog.e(LOGTAG, "Property name cannot be null", e); } } @Override public void union(String name, JSONArray value) { if (hasOptedOutTracking()) return; try { final JSONObject properties = new JSONObject(); properties.put(name, value); final JSONObject message = stdGroupMessage("$union", properties); recordGroupMessage(message); } catch (final JSONException e) { MPLog.e(LOGTAG, "Exception unioning a property", e); } } @Override public void remove(String name, Object value) { if (hasOptedOutTracking()) return; try { final JSONObject properties = new JSONObject(); properties.put(name, value); final JSONObject message = stdGroupMessage("$remove", properties); recordGroupMessage(message); } catch (final JSONException e) { MPLog.e(LOGTAG, "Exception removing a property", e); } } @Override public void unset(String name) { if (hasOptedOutTracking()) return; try { final JSONArray names = new JSONArray(); names.put(name); final JSONObject message = stdGroupMessage("$unset", names); recordGroupMessage(message); } catch (final JSONException e) { MPLog.e(LOGTAG, "Exception unsetting a property", e); } } @Override public void deleteGroup() { try { final JSONObject message = stdGroupMessage("$delete", JSONObject.NULL); recordGroupMessage(message); mGroups.remove(makeMapKey(mGroupKey, mGroupID)); } catch (final JSONException e) { MPLog.e(LOGTAG, "Exception deleting a group", e); } } private JSONObject stdGroupMessage(String actionType, Object properties) throws JSONException { final JSONObject dataObj = new JSONObject(); dataObj.put(actionType, properties); dataObj.put("$token", mToken); dataObj.put("$time", System.currentTimeMillis()); dataObj.put("$group_key", mGroupKey); dataObj.put("$group_id", mGroupID); dataObj.put("$mp_metadata", mSessionMetadata.getMetadataForPeople()); return dataObj; } }// GroupImpl private class SupportedUpdatesListener implements UpdatesListener, Runnable { @Override public void onNewResults() { mExecutor.execute(this); } @Override public void addOnMixpanelUpdatesReceivedListener(OnMixpanelUpdatesReceivedListener listener) { mListeners.add(listener); if (mDecideMessages.hasUpdatesAvailable()) { onNewResults(); } } @Override public void removeOnMixpanelUpdatesReceivedListener(OnMixpanelUpdatesReceivedListener listener) { mListeners.remove(listener); } @Override public void run() { // It's possible that by the time this has run the updates we detected are no longer // present, which is ok. for (final OnMixpanelUpdatesReceivedListener listener : mListeners) { listener.onMixpanelUpdatesReceived(); } mConnectIntegrations.setupIntegrations(mDecideMessages.getIntegrations()); } private final Set<OnMixpanelUpdatesReceivedListener> mListeners = Collections.newSetFromMap(new ConcurrentHashMap<OnMixpanelUpdatesReceivedListener, Boolean>()); private final Executor mExecutor = Executors.newSingleThreadExecutor(); } /* package */ class NoOpUpdatesFromMixpanel implements UpdatesFromMixpanel { public NoOpUpdatesFromMixpanel(Tweaks tweaks) { mTweaks = tweaks; } @Override public void startUpdates() { // No op } @Override public void storeVariants(JSONArray variants) { // No op } @Override public void applyPersistedUpdates() { // No op } @Override public void setEventBindings(JSONArray bindings) { // No op } @Override public void setVariants(JSONArray variants) { // No op } @Override public Tweaks getTweaks() { return mTweaks; } @Override public void addOnMixpanelTweaksUpdatedListener(OnMixpanelTweaksUpdatedListener listener) { // No op } @Override public void removeOnMixpanelTweaksUpdatedListener(OnMixpanelTweaksUpdatedListener listener) { // No op } private final Tweaks mTweaks; } //////////////////////////////////////////////////// protected void flushNoDecideCheck() { if (hasOptedOutTracking()) return; mMessages.postToServer(new AnalyticsMessages.FlushDescription(mToken, false)); } protected void track(String eventName, JSONObject properties, boolean isAutomaticEvent) { if (hasOptedOutTracking() || (isAutomaticEvent && !mDecideMessages.shouldTrackAutomaticEvent())) { return; } final Long eventBegin; synchronized (mEventTimings) { eventBegin = mEventTimings.get(eventName); mEventTimings.remove(eventName); mPersistentIdentity.removeTimeEvent(eventName); } try { final JSONObject messageProps = new JSONObject(); final Map<String, String> referrerProperties = mPersistentIdentity.getReferrerProperties(); for (final Map.Entry<String, String> entry : referrerProperties.entrySet()) { final String key = entry.getKey(); final String value = entry.getValue(); messageProps.put(key, value); } mPersistentIdentity.addSuperPropertiesToObject(messageProps); // Don't allow super properties or referral properties to override these fields, // but DO allow the caller to override them in their given properties. final double timeSecondsDouble = (System.currentTimeMillis()) / 1000.0; final long timeSeconds = (long) timeSecondsDouble; final String distinctId = getDistinctId(); final String anonymousId = getAnonymousId(); final String userId = getUserId(); messageProps.put("time", timeSeconds); messageProps.put("distinct_id", distinctId); messageProps.put("$had_persisted_distinct_id", mPersistentIdentity.getHadPersistedDistinctId()); if(anonymousId != null) { messageProps.put("$device_id", anonymousId); } if(userId != null) { messageProps.put("$user_id", userId); } if (null != eventBegin) { final double eventBeginDouble = ((double) eventBegin) / 1000.0; final double secondsElapsed = timeSecondsDouble - eventBeginDouble; messageProps.put("$duration", secondsElapsed); } if (null != properties) { final Iterator<?> propIter = properties.keys(); while (propIter.hasNext()) { final String key = (String) propIter.next(); if (!properties.isNull(key)) { messageProps.put(key, properties.get(key)); } } } final AnalyticsMessages.EventDescription eventDescription = new AnalyticsMessages.EventDescription(eventName, messageProps, mToken, isAutomaticEvent, mSessionMetadata.getMetadataForEvent()); mMessages.eventsMessage(eventDescription); if (mMixpanelActivityLifecycleCallbacks.getCurrentActivity() != null) { getPeople().showGivenNotification(mDecideMessages.getNotification(eventDescription, mConfig.getTestMode()), mMixpanelActivityLifecycleCallbacks.getCurrentActivity()); } if (null != mTrackingDebug) { mTrackingDebug.reportTrack(eventName); } } catch (final JSONException e) { MPLog.e(LOGTAG, "Exception tracking event " + eventName, e); } } private void recordPeopleMessage(JSONObject message) { if (hasOptedOutTracking()) return; mMessages.peopleMessage(new AnalyticsMessages.PeopleDescription(message, mToken)); } private void recordGroupMessage(JSONObject message) { if (hasOptedOutTracking()) return; if (message.has("$group_key") && message.has("$group_id")) { mMessages.groupMessage(new AnalyticsMessages.GroupDescription(message, mToken)); } else { MPLog.e(LOGTAG, "Attempt to update group without key and value--this should not happen."); } } private void pushWaitingPeopleRecord(String distinctId) { mMessages.pushAnonymousPeopleMessage(new AnalyticsMessages.PushAnonymousPeopleDescription(distinctId, mToken)); } private static void registerAppLinksListeners(Context context, final MixpanelAPI mixpanel) { // Register a BroadcastReceiver to receive com.parse.bolts.measurement_event and track a call to mixpanel try { final Class<?> clazz = Class.forName("android.support.v4.content.LocalBroadcastManager"); final Method methodGetInstance = clazz.getMethod("getInstance", Context.class); final Method methodRegisterReceiver = clazz.getMethod("registerReceiver", BroadcastReceiver.class, IntentFilter.class); final Object localBroadcastManager = methodGetInstance.invoke(null, context); methodRegisterReceiver.invoke(localBroadcastManager, new BroadcastReceiver() { @Override public void onReceive(Context context, Intent intent) { final JSONObject properties = new JSONObject(); final Bundle args = intent.getBundleExtra("event_args"); if (args != null) { for (final String key : args.keySet()) { try { properties.put(key, args.get(key)); } catch (final JSONException e) { MPLog.e(APP_LINKS_LOGTAG, "failed to add key \"" + key + "\" to properties for tracking bolts event", e); } } } mixpanel.track("$" + intent.getStringExtra("event_name"), properties); } }, new IntentFilter("com.parse.bolts.measurement_event")); } catch (final InvocationTargetException e) { MPLog.d(APP_LINKS_LOGTAG, "Failed to invoke LocalBroadcastManager.registerReceiver() -- App Links tracking will not be enabled due to this exception", e); } catch (final ClassNotFoundException e) { MPLog.d(APP_LINKS_LOGTAG, "To enable App Links tracking android.support.v4 must be installed: " + e.getMessage()); } catch (final NoSuchMethodException e) { MPLog.d(APP_LINKS_LOGTAG, "To enable App Links tracking android.support.v4 must be installed: " + e.getMessage()); } catch (final IllegalAccessException e) { MPLog.d(APP_LINKS_LOGTAG, "App Links tracking will not be enabled due to this exception: " + e.getMessage()); } } private static void checkIntentForInboundAppLink(Context context) { // call the Bolts getTargetUrlFromInboundIntent method simply for a side effect // if the intent is the result of an App Link, it'll trigger al_nav_in // https://github.com/BoltsFramework/Bolts-Android/blob/1.1.2/Bolts/src/bolts/AppLinks.java#L86 if (context instanceof Activity) { try { final Class<?> clazz = Class.forName("bolts.AppLinks"); final Intent intent = ((Activity) context).getIntent(); final Method getTargetUrlFromInboundIntent = clazz.getMethod("getTargetUrlFromInboundIntent", Context.class, Intent.class); getTargetUrlFromInboundIntent.invoke(null, context, intent); } catch (final InvocationTargetException e) { MPLog.d(APP_LINKS_LOGTAG, "Failed to invoke bolts.AppLinks.getTargetUrlFromInboundIntent() -- Unable to detect inbound App Links", e); } catch (final ClassNotFoundException e) { MPLog.d(APP_LINKS_LOGTAG, "Please install the Bolts library >= 1.1.2 to track App Links: " + e.getMessage()); } catch (final NoSuchMethodException e) { MPLog.d(APP_LINKS_LOGTAG, "Please install the Bolts library >= 1.1.2 to track App Links: " + e.getMessage()); } catch (final IllegalAccessException e) { MPLog.d(APP_LINKS_LOGTAG, "Unable to detect inbound App Links: " + e.getMessage()); } } else { MPLog.d(APP_LINKS_LOGTAG, "Context is not an instance of Activity. To detect inbound App Links, pass an instance of an Activity to getInstance."); } } private final Context mContext; private final AnalyticsMessages mMessages; private final MPConfig mConfig; private final String mToken; private final PeopleImpl mPeople; private final Map<String, GroupImpl> mGroups; private final UpdatesFromMixpanel mUpdatesFromMixpanel; private final PersistentIdentity mPersistentIdentity; private final UpdatesListener mUpdatesListener; private final TrackingDebug mTrackingDebug; private final ConnectIntegrations mConnectIntegrations; private final DecideMessages mDecideMessages; private final Map<String, String> mDeviceInfo; private final Map<String, Long> mEventTimings; private MixpanelActivityLifecycleCallbacks mMixpanelActivityLifecycleCallbacks; private final SessionMetadata mSessionMetadata; // Maps each token to a singleton MixpanelAPI instance private static final Map<String, Map<Context, MixpanelAPI>> sInstanceMap = new HashMap<String, Map<Context, MixpanelAPI>>(); private static final SharedPreferencesLoader sPrefsLoader = new SharedPreferencesLoader(); private static final Tweaks sSharedTweaks = new Tweaks(); private static Future<SharedPreferences> sReferrerPrefs; private static final String LOGTAG = "MixpanelAPI.API"; private static final String APP_LINKS_LOGTAG = "MixpanelAPI.AL"; private static final String ENGAGE_DATE_FORMAT_STRING = "yyyy-MM-dd'T'HH:mm:ss"; }
src/main/java/com/mixpanel/android/mpmetrics/MixpanelAPI.java
package com.mixpanel.android.mpmetrics; import android.annotation.TargetApi; import android.app.Activity; import android.app.Application; import android.app.FragmentTransaction; import android.content.BroadcastReceiver; import android.content.Context; import android.content.Intent; import android.content.IntentFilter; import android.content.SharedPreferences; import android.content.pm.PackageInfo; import android.content.pm.PackageManager; import android.os.Build; import android.os.Bundle; import com.mixpanel.android.R; import com.mixpanel.android.takeoverinapp.TakeoverInAppActivity; import com.mixpanel.android.util.ActivityImageUtils; import com.mixpanel.android.util.MPLog; import com.mixpanel.android.viewcrawler.TrackingDebug; import com.mixpanel.android.viewcrawler.UpdatesFromMixpanel; import com.mixpanel.android.viewcrawler.ViewCrawler; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; import java.text.DateFormat; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.Date; import java.util.HashMap; import java.util.Iterator; import java.util.List; import java.util.Locale; import java.util.Map; import java.util.Map.Entry; import java.util.Set; import java.util.TimeZone; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.Executor; import java.util.concurrent.Executors; import java.util.concurrent.Future; import java.util.concurrent.locks.ReentrantLock; /** * Core class for interacting with Mixpanel Analytics. * * <p>Call {@link #getInstance(Context, String)} with * your main application activity and your Mixpanel API token as arguments * an to get an instance you can use to report how users are using your * application. * * <p>Once you have an instance, you can send events to Mixpanel * using {@link #track(String, JSONObject)}, and update People Analytics * records with {@link #getPeople()} * * <p>The Mixpanel library will periodically send information to * Mixpanel servers, so your application will need to have * <tt>android.permission.INTERNET</tt>. In addition, to preserve * battery life, messages to Mixpanel servers may not be sent immediately * when you call <tt>track</tt> or {@link People#set(String, Object)}. * The library will send messages periodically throughout the lifetime * of your application, but you will need to call {@link #flush()} * before your application is completely shutdown to ensure all of your * events are sent. * * <p>A typical use-case for the library might look like this: * * <pre> * {@code * public class MainActivity extends Activity { * MixpanelAPI mMixpanel; * * public void onCreate(Bundle saved) { * mMixpanel = MixpanelAPI.getInstance(this, "YOUR MIXPANEL API TOKEN"); * ... * } * * public void whenSomethingInterestingHappens(int flavor) { * JSONObject properties = new JSONObject(); * properties.put("flavor", flavor); * mMixpanel.track("Something Interesting Happened", properties); * ... * } * * public void onDestroy() { * mMixpanel.flush(); * super.onDestroy(); * } * } * } * </pre> * * <p>In addition to this documentation, you may wish to take a look at * <a href="https://github.com/mixpanel/sample-android-mixpanel-integration">the Mixpanel sample Android application</a>. * It demonstrates a variety of techniques, including * updating People Analytics records with {@link People} and others. * * <p>There are also <a href="https://mixpanel.com/docs/">step-by-step getting started documents</a> * available at mixpanel.com * * @see <a href="https://mixpanel.com/docs/integration-libraries/android">getting started documentation for tracking events</a> * @see <a href="https://mixpanel.com/docs/people-analytics/android">getting started documentation for People Analytics</a> * @see <a href="https://mixpanel.com/docs/people-analytics/android-push">getting started with push notifications for Android</a> * @see <a href="https://github.com/mixpanel/sample-android-mixpanel-integration">The Mixpanel Android sample application</a> */ public class MixpanelAPI { /** * String version of the library. */ public static final String VERSION = MPConfig.VERSION; /** * Declare a string-valued tweak, and return a reference you can use to read the value of the tweak. * Tweaks can be changed in Mixpanel A/B tests, and can allow you to alter your customers' experience * in your app without re-deploying your application through the app store. */ public static Tweak<String> stringTweak(String tweakName, String defaultValue) { return sSharedTweaks.stringTweak(tweakName, defaultValue); } /** * Declare a boolean-valued tweak, and return a reference you can use to read the value of the tweak. * Tweaks can be changed in Mixpanel A/B tests, and can allow you to alter your customers' experience * in your app without re-deploying your application through the app store. */ public static Tweak<Boolean> booleanTweak(String tweakName, boolean defaultValue) { return sSharedTweaks.booleanTweak(tweakName, defaultValue); } /** * Declare a double-valued tweak, and return a reference you can use to read the value of the tweak. * Tweaks can be changed in Mixpanel A/B tests, and can allow you to alter your customers' experience * in your app without re-deploying your application through the app store. */ public static Tweak<Double> doubleTweak(String tweakName, double defaultValue) { return sSharedTweaks.doubleTweak(tweakName, defaultValue); } /** * Declare a double-valued tweak, and return a reference you can use to read the value of the tweak. * Tweaks can be changed in Mixpanel A/B tests, and can allow you to alter your customers' experience * in your app without re-deploying your application through the app store. */ public static Tweak<Double> doubleTweak(String tweakName, double defaultValue, double minimumValue, double maximumValue) { return sSharedTweaks.doubleTweak(tweakName, defaultValue, minimumValue, maximumValue); } /** * Declare a float-valued tweak, and return a reference you can use to read the value of the tweak. * Tweaks can be changed in Mixpanel A/B tests, and can allow you to alter your customers' experience * in your app without re-deploying your application through the app store. */ public static Tweak<Float> floatTweak(String tweakName, float defaultValue) { return sSharedTweaks.floatTweak(tweakName, defaultValue); } /** * Declare a float-valued tweak, and return a reference you can use to read the value of the tweak. * Tweaks can be changed in Mixpanel A/B tests, and can allow you to alter your customers' experience * in your app without re-deploying your application through the app store. */ public static Tweak<Float> floatTweak(String tweakName, float defaultValue, float minimumValue, float maximumValue) { return sSharedTweaks.floatTweak(tweakName, defaultValue, minimumValue, maximumValue); } /** * Declare a long-valued tweak, and return a reference you can use to read the value of the tweak. * Tweaks can be changed in Mixpanel A/B tests, and can allow you to alter your customers' experience * in your app without re-deploying your application through the app store. */ public static Tweak<Long> longTweak(String tweakName, long defaultValue) { return sSharedTweaks.longTweak(tweakName, defaultValue); } /** * Declare a long-valued tweak, and return a reference you can use to read the value of the tweak. * Tweaks can be changed in Mixpanel A/B tests, and can allow you to alter your customers' experience * in your app without re-deploying your application through the app store. */ public static Tweak<Long> longTweak(String tweakName, long defaultValue, long minimumValue, long maximumValue) { return sSharedTweaks.longTweak(tweakName, defaultValue, minimumValue, maximumValue); } /** * Declare an int-valued tweak, and return a reference you can use to read the value of the tweak. * Tweaks can be changed in Mixpanel A/B tests, and can allow you to alter your customers' experience * in your app without re-deploying your application through the app store. */ public static Tweak<Integer> intTweak(String tweakName, int defaultValue) { return sSharedTweaks.intTweak(tweakName, defaultValue); } /** * Declare an int-valued tweak, and return a reference you can use to read the value of the tweak. * Tweaks can be changed in Mixpanel A/B tests, and can allow you to alter your customers' experience * in your app without re-deploying your application through the app store. */ public static Tweak<Integer> intTweak(String tweakName, int defaultValue, int minimumValue, int maximumValue) { return sSharedTweaks.intTweak(tweakName, defaultValue, minimumValue, maximumValue); } /** * Declare short-valued tweak, and return a reference you can use to read the value of the tweak. * Tweaks can be changed in Mixpanel A/B tests, and can allow you to alter your customers' experience * in your app without re-deploying your application through the app store. */ public static Tweak<Short> shortTweak(String tweakName, short defaultValue) { return sSharedTweaks.shortTweak(tweakName, defaultValue); } /** * Declare byte-valued tweak, and return a reference you can use to read the value of the tweak. * Tweaks can be changed in Mixpanel A/B tests, and can allow you to alter your customers' experience * in your app without re-deploying your application through the app store. */ public static Tweak<Byte> byteTweak(String tweakName, byte defaultValue) { return sSharedTweaks.byteTweak(tweakName, defaultValue); } /** * You shouldn't instantiate MixpanelAPI objects directly. * Use MixpanelAPI.getInstance to get an instance. */ MixpanelAPI(Context context, Future<SharedPreferences> referrerPreferences, String token, boolean optOutTrackingDefault, JSONObject superProperties) { this(context, referrerPreferences, token, MPConfig.getInstance(context), optOutTrackingDefault, superProperties); } /** * You shouldn't instantiate MixpanelAPI objects directly. * Use MixpanelAPI.getInstance to get an instance. */ MixpanelAPI(Context context, Future<SharedPreferences> referrerPreferences, String token, MPConfig config, boolean optOutTrackingDefault, JSONObject superProperties) { mContext = context; mToken = token; mPeople = new PeopleImpl(); mGroups = new HashMap<String, GroupImpl>(); mConfig = config; final Map<String, String> deviceInfo = new HashMap<String, String>(); deviceInfo.put("$android_lib_version", MPConfig.VERSION); deviceInfo.put("$android_os", "Android"); deviceInfo.put("$android_os_version", Build.VERSION.RELEASE == null ? "UNKNOWN" : Build.VERSION.RELEASE); deviceInfo.put("$android_manufacturer", Build.MANUFACTURER == null ? "UNKNOWN" : Build.MANUFACTURER); deviceInfo.put("$android_brand", Build.BRAND == null ? "UNKNOWN" : Build.BRAND); deviceInfo.put("$android_model", Build.MODEL == null ? "UNKNOWN" : Build.MODEL); try { final PackageManager manager = mContext.getPackageManager(); final PackageInfo info = manager.getPackageInfo(mContext.getPackageName(), 0); deviceInfo.put("$android_app_version", info.versionName); deviceInfo.put("$android_app_version_code", Integer.toString(info.versionCode)); } catch (final PackageManager.NameNotFoundException e) { MPLog.e(LOGTAG, "Exception getting app version name", e); } mDeviceInfo = Collections.unmodifiableMap(deviceInfo); mSessionMetadata = new SessionMetadata(); mUpdatesFromMixpanel = constructUpdatesFromMixpanel(context, token); mTrackingDebug = constructTrackingDebug(); mMessages = getAnalyticsMessages(); mPersistentIdentity = getPersistentIdentity(context, referrerPreferences, token); mEventTimings = mPersistentIdentity.getTimeEvents(); if (optOutTrackingDefault && (hasOptedOutTracking() || !mPersistentIdentity.hasOptOutFlag(token))) { optOutTracking(); } if (superProperties != null) { registerSuperProperties(superProperties); } mUpdatesListener = constructUpdatesListener(); mDecideMessages = constructDecideUpdates(token, mUpdatesListener, mUpdatesFromMixpanel); mConnectIntegrations = new ConnectIntegrations(this, mContext); // TODO reading persistent identify immediately forces the lazy load of the preferences, and defeats the // purpose of PersistentIdentity's laziness. String decideId = mPersistentIdentity.getPeopleDistinctId(); if (null == decideId) { decideId = mPersistentIdentity.getEventsDistinctId(); } mDecideMessages.setDistinctId(decideId); final boolean dbExists = MPDbAdapter.getInstance(mContext).getDatabaseFile().exists(); registerMixpanelActivityLifecycleCallbacks(); if (mPersistentIdentity.isFirstLaunch(dbExists)) { track(AutomaticEvents.FIRST_OPEN, null, true); mPersistentIdentity.setHasLaunched(); } if (!mConfig.getDisableDecideChecker()) { mMessages.installDecideCheck(mDecideMessages); } if (sendAppOpen()) { track("$app_open", null); } if (!mPersistentIdentity.isFirstIntegration(mToken)) { try { final JSONObject messageProps = new JSONObject(); messageProps.put("mp_lib", "Android"); messageProps.put("lib", "Android"); messageProps.put("distinct_id", token); messageProps.put("$lib_version", MPConfig.VERSION); messageProps.put("$user_id", token); final AnalyticsMessages.EventDescription eventDescription = new AnalyticsMessages.EventDescription( "Integration", messageProps, "85053bf24bba75239b16a601d9387e17"); mMessages.eventsMessage(eventDescription); mMessages.postToServer(new AnalyticsMessages.FlushDescription("85053bf24bba75239b16a601d9387e17", false)); mPersistentIdentity.setIsIntegrated(mToken); } catch (JSONException e) { } } if (mPersistentIdentity.isNewVersion(deviceInfo.get("$android_app_version_code"))) { try { final JSONObject messageProps = new JSONObject(); messageProps.put(AutomaticEvents.VERSION_UPDATED, deviceInfo.get("$android_app_version")); track(AutomaticEvents.APP_UPDATED, messageProps, true); } catch (JSONException e) {} } mUpdatesFromMixpanel.startUpdates(); if (!mConfig.getDisableExceptionHandler()) { ExceptionHandler.init(); } } /** * Get the instance of MixpanelAPI associated with your Mixpanel project token. * * <p>Use getInstance to get a reference to a shared * instance of MixpanelAPI you can use to send events * and People Analytics updates to Mixpanel.</p> * <p>getInstance is thread safe, but the returned instance is not, * and may be shared with other callers of getInstance. * The best practice is to call getInstance, and use the returned MixpanelAPI, * object from a single thread (probably the main UI thread of your application).</p> * <p>If you do choose to track events from multiple threads in your application, * you should synchronize your calls on the instance itself, like so:</p> * <pre> * {@code * MixpanelAPI instance = MixpanelAPI.getInstance(context, token); * synchronized(instance) { // Only necessary if the instance will be used in multiple threads. * instance.track(...) * } * } * </pre> * * @param context The application context you are tracking * @param token Your Mixpanel project token. You can get your project token on the Mixpanel web site, * in the settings dialog. * @return an instance of MixpanelAPI associated with your project */ public static MixpanelAPI getInstance(Context context, String token) { return getInstance(context, token, false, null); } /** * Get the instance of MixpanelAPI associated with your Mixpanel project token. * * <p>Use getInstance to get a reference to a shared * instance of MixpanelAPI you can use to send events * and People Analytics updates to Mixpanel.</p> * <p>getInstance is thread safe, but the returned instance is not, * and may be shared with other callers of getInstance. * The best practice is to call getInstance, and use the returned MixpanelAPI, * object from a single thread (probably the main UI thread of your application).</p> * <p>If you do choose to track events from multiple threads in your application, * you should synchronize your calls on the instance itself, like so:</p> * <pre> * {@code * MixpanelAPI instance = MixpanelAPI.getInstance(context, token); * synchronized(instance) { // Only necessary if the instance will be used in multiple threads. * instance.track(...) * } * } * </pre> * * @param context The application context you are tracking * @param token Your Mixpanel project token. You can get your project token on the Mixpanel web site, * in the settings dialog. * @param superProperties A JSONObject containing super properties to register. * @return an instance of MixpanelAPI associated with your project */ public static MixpanelAPI getInstance(Context context, String token, JSONObject superProperties) { return getInstance(context, token, false, superProperties); } /** * Get the instance of MixpanelAPI associated with your Mixpanel project token. * * <p>Use getInstance to get a reference to a shared * instance of MixpanelAPI you can use to send events * and People Analytics updates to Mixpanel.</p> * <p>getInstance is thread safe, but the returned instance is not, * and may be shared with other callers of getInstance. * The best practice is to call getInstance, and use the returned MixpanelAPI, * object from a single thread (probably the main UI thread of your application).</p> * <p>If you do choose to track events from multiple threads in your application, * you should synchronize your calls on the instance itself, like so:</p> * <pre> * {@code * MixpanelAPI instance = MixpanelAPI.getInstance(context, token); * synchronized(instance) { // Only necessary if the instance will be used in multiple threads. * instance.track(...) * } * } * </pre> * * @param context The application context you are tracking * @param token Your Mixpanel project token. You can get your project token on the Mixpanel web site, * in the settings dialog. * @param optOutTrackingDefault Whether or not Mixpanel can start tracking by default. See * {@link #optOutTracking()}. * @param superProperties A JSONObject containing super properties to register. * @return an instance of MixpanelAPI associated with your project */ public static MixpanelAPI getInstance(Context context, String token, boolean optOutTrackingDefault, JSONObject superProperties) { if (null == token || null == context) { return null; } synchronized (sInstanceMap) { final Context appContext = context.getApplicationContext(); if (null == sReferrerPrefs) { sReferrerPrefs = sPrefsLoader.loadPreferences(context, MPConfig.REFERRER_PREFS_NAME, null); } Map <Context, MixpanelAPI> instances = sInstanceMap.get(token); if (null == instances) { instances = new HashMap<Context, MixpanelAPI>(); sInstanceMap.put(token, instances); } MixpanelAPI instance = instances.get(appContext); if (null == instance && ConfigurationChecker.checkBasicConfiguration(appContext)) { instance = new MixpanelAPI(appContext, sReferrerPrefs, token, optOutTrackingDefault, superProperties); registerAppLinksListeners(context, instance); instances.put(appContext, instance); if (ConfigurationChecker.checkPushNotificationConfiguration(appContext)) { try { MixpanelFCMMessagingService.init(); } catch (Exception e) { MPLog.e(LOGTAG, "Push notification could not be initialized", e); } } } checkIntentForInboundAppLink(context); return instance; } } /** * This function creates a distinct_id alias from alias to original. If original is null, then it will create an alias * to the current events distinct_id, which may be the distinct_id randomly generated by the Mixpanel library * before {@link #identify(String)} is called. * * <p>This call does not identify the user after. You must still call both {@link #identify(String)} and * {@link People#identify(String)} if you wish the new alias to be used for Events and People. * * @param alias the new distinct_id that should represent original. * @param original the old distinct_id that alias will be mapped to. */ public void alias(String alias, String original) { if (hasOptedOutTracking()) return; if (original == null) { original = getDistinctId(); } if (alias.equals(original)) { MPLog.w(LOGTAG, "Attempted to alias identical distinct_ids " + alias + ". Alias message will not be sent."); return; } try { final JSONObject j = new JSONObject(); j.put("alias", alias); j.put("original", original); track("$create_alias", j); } catch (final JSONException e) { MPLog.e(LOGTAG, "Failed to alias", e); } flush(); } /** * Associate all future calls to {@link #track(String, JSONObject)} with the user identified by * the given distinct id. * * <p>This call does not identify the user for People Analytics; * to do that, see {@link People#identify(String)}. Mixpanel recommends using * the same distinct_id for both calls, and using a distinct_id that is easy * to associate with the given user, for example, a server-side account identifier. * * <p>Calls to {@link #track(String, JSONObject)} made before corresponding calls to * identify will use an internally generated distinct id, which means it is best * to call identify early to ensure that your Mixpanel funnels and retention * analytics can continue to track the user throughout their lifetime. We recommend * calling identify as early as you can. * * <p>Once identify is called, the given distinct id persists across restarts of your * application. * * @param distinctId a string uniquely identifying this user. Events sent to * Mixpanel using the same disinct_id will be considered associated with the * same visitor/customer for retention and funnel reporting, so be sure that the given * value is globally unique for each individual user you intend to track. * * @see People#identify(String) */ public void identify(String distinctId) { identify(distinctId, true); } private void identify(String distinctId, boolean markAsUserId) { if (hasOptedOutTracking()) return; synchronized (mPersistentIdentity) { String currentEventsDistinctId = mPersistentIdentity.getEventsDistinctId(); mPersistentIdentity.setAnonymousIdIfAbsent(currentEventsDistinctId); mPersistentIdentity.setEventsDistinctId(distinctId); if(markAsUserId) { mPersistentIdentity.markEventsUserIdPresent(); } String decideId = mPersistentIdentity.getPeopleDistinctId(); if (null == decideId) { decideId = mPersistentIdentity.getEventsDistinctId(); } mDecideMessages.setDistinctId(decideId); if (!distinctId.equals(currentEventsDistinctId)) { try { JSONObject identifyPayload = new JSONObject(); identifyPayload.put("$anon_distinct_id", currentEventsDistinctId); track("$identify", identifyPayload); } catch (JSONException e) { MPLog.e(LOGTAG, "Could not track $identify event"); } } } } /** * Begin timing of an event. Calling timeEvent("Thing") will not send an event, but * when you eventually call track("Thing"), your tracked event will be sent with a "$duration" * property, representing the number of seconds between your calls. * * @param eventName the name of the event to track with timing. */ public void timeEvent(final String eventName) { if (hasOptedOutTracking()) return; final long writeTime = System.currentTimeMillis(); synchronized (mEventTimings) { mEventTimings.put(eventName, writeTime); mPersistentIdentity.addTimeEvent(eventName, writeTime); } } /** * Retrieves the time elapsed for the named event since timeEvent() was called. * * @param eventName the name of the event to be tracked that was previously called with timeEvent() */ public double eventElapsedTime(final String eventName) { final long currentTime = System.currentTimeMillis(); Long startTime; synchronized (mEventTimings) { startTime = mEventTimings.get(eventName); } return startTime == null ? 0 : (double)((currentTime - startTime) / 1000); } /** * Track an event. * * <p>Every call to track eventually results in a data point sent to Mixpanel. These data points * are what are measured, counted, and broken down to create your Mixpanel reports. Events * have a string name, and an optional set of name/value pairs that describe the properties of * that event. * * @param eventName The name of the event to send * @param properties A Map containing the key value pairs of the properties to include in this event. * Pass null if no extra properties exist. * * See also {@link #track(String, org.json.JSONObject)} */ public void trackMap(String eventName, Map<String, Object> properties) { if (hasOptedOutTracking()) return; if (null == properties) { track(eventName, null); } else { try { track(eventName, new JSONObject(properties)); } catch (NullPointerException e) { MPLog.w(LOGTAG, "Can't have null keys in the properties of trackMap!"); } } } /** * Track an event with specific groups. * * <p>Every call to track eventually results in a data point sent to Mixpanel. These data points * are what are measured, counted, and broken down to create your Mixpanel reports. Events * have a string name, and an optional set of name/value pairs that describe the properties of * that event. Group key/value pairs are upserted into the property map before tracking. * * @param eventName The name of the event to send * @param properties A Map containing the key value pairs of the properties to include in this event. * Pass null if no extra properties exist. * @param groups A Map containing the group key value pairs for this event. * * See also {@link #track(String, org.json.JSONObject)}, {@link #trackMap(String, Map)} */ public void trackWithGroups(String eventName, Map<String, Object> properties, Map<String, Object> groups) { if (hasOptedOutTracking()) return; if (null == groups) { trackMap(eventName, properties); } else if (null == properties) { trackMap(eventName, groups); } else { for (Entry<String, Object> e : groups.entrySet()) { if (e.getValue() != null) { properties.put(e.getKey(), e.getValue()); } } trackMap(eventName, properties); } } /** * Track an event. * * <p>Every call to track eventually results in a data point sent to Mixpanel. These data points * are what are measured, counted, and broken down to create your Mixpanel reports. Events * have a string name, and an optional set of name/value pairs that describe the properties of * that event. * * @param eventName The name of the event to send * @param properties A JSONObject containing the key value pairs of the properties to include in this event. * Pass null if no extra properties exist. */ // DO NOT DOCUMENT, but track() must be thread safe since it is used to track events in // notifications from the UI thread, which might not be our MixpanelAPI "home" thread. // This MAY CHANGE IN FUTURE RELEASES, so minimize code that assumes thread safety // (and perhaps document that code here). public void track(String eventName, JSONObject properties) { if (hasOptedOutTracking()) return; track(eventName, properties, false); } /** * Equivalent to {@link #track(String, JSONObject)} with a null argument for properties. * Consider adding properties to your tracking to get the best insights and experience from Mixpanel. * @param eventName the name of the event to send */ public void track(String eventName) { if (hasOptedOutTracking()) return; track(eventName, null); } /** * Push all queued Mixpanel events and People Analytics changes to Mixpanel servers. * * <p>Events and People messages are pushed gradually throughout * the lifetime of your application. This means that to ensure that all messages * are sent to Mixpanel when your application is shut down, you will * need to call flush() to let the Mixpanel library know it should * send all remaining messages to the server. We strongly recommend * placing a call to flush() in the onDestroy() method of * your main application activity. */ public void flush() { if (hasOptedOutTracking()) return; mMessages.postToServer(new AnalyticsMessages.FlushDescription(mToken)); } /** * Returns a json object of the user's current super properties * *<p>SuperProperties are a collection of properties that will be sent with every event to Mixpanel, * and persist beyond the lifetime of your application. */ public JSONObject getSuperProperties() { JSONObject ret = new JSONObject(); mPersistentIdentity.addSuperPropertiesToObject(ret); return ret; } /** * Returns the string id currently being used to uniquely identify the user associated * with events sent using {@link #track(String, JSONObject)}. Before any calls to * {@link #identify(String)}, this will be an id automatically generated by the library. * * <p>The id returned by getDistinctId is independent of the distinct id used to identify * any People Analytics properties in Mixpanel. To read and write that identifier, * use {@link People#identify(String)} and {@link People#getDistinctId()}. * * @return The distinct id associated with event tracking * * @see #identify(String) * @see People#getDistinctId() */ public String getDistinctId() { return mPersistentIdentity.getEventsDistinctId(); } /** * Returns the anonymoous id currently being used to uniquely identify the device and all * with events sent using {@link #track(String, JSONObject)} will have this id as a device * id * * @return The device id associated with event tracking */ protected String getAnonymousId() { return mPersistentIdentity.getAnonymousId(); } /** * Returns the user id with which identify is called and all the with events sent using * {@link #track(String, JSONObject)} will have this id as a user id * * @return The user id associated with event tracking */ protected String getUserId() { return mPersistentIdentity.getEventsUserId(); } /** * Register properties that will be sent with every subsequent call to {@link #track(String, JSONObject)}. * * <p>SuperProperties are a collection of properties that will be sent with every event to Mixpanel, * and persist beyond the lifetime of your application. * * <p>Setting a superProperty with registerSuperProperties will store a new superProperty, * possibly overwriting any existing superProperty with the same name (to set a * superProperty only if it is currently unset, use {@link #registerSuperPropertiesOnce(JSONObject)}) * * <p>SuperProperties will persist even if your application is taken completely out of memory. * to remove a superProperty, call {@link #unregisterSuperProperty(String)} or {@link #clearSuperProperties()} * * @param superProperties A Map containing super properties to register * * See also {@link #registerSuperProperties(org.json.JSONObject)} */ public void registerSuperPropertiesMap(Map<String, Object> superProperties) { if (hasOptedOutTracking()) return; if (null == superProperties) { MPLog.e(LOGTAG, "registerSuperPropertiesMap does not accept null properties"); return; } try { registerSuperProperties(new JSONObject(superProperties)); } catch (NullPointerException e) { MPLog.w(LOGTAG, "Can't have null keys in the properties of registerSuperPropertiesMap"); } } /** * Register properties that will be sent with every subsequent call to {@link #track(String, JSONObject)}. * * <p>SuperProperties are a collection of properties that will be sent with every event to Mixpanel, * and persist beyond the lifetime of your application. * * <p>Setting a superProperty with registerSuperProperties will store a new superProperty, * possibly overwriting any existing superProperty with the same name (to set a * superProperty only if it is currently unset, use {@link #registerSuperPropertiesOnce(JSONObject)}) * * <p>SuperProperties will persist even if your application is taken completely out of memory. * to remove a superProperty, call {@link #unregisterSuperProperty(String)} or {@link #clearSuperProperties()} * * @param superProperties A JSONObject containing super properties to register * @see #registerSuperPropertiesOnce(JSONObject) * @see #unregisterSuperProperty(String) * @see #clearSuperProperties() */ public void registerSuperProperties(JSONObject superProperties) { if (hasOptedOutTracking()) return; mPersistentIdentity.registerSuperProperties(superProperties); } /** * Remove a single superProperty, so that it will not be sent with future calls to {@link #track(String, JSONObject)}. * * <p>If there is a superProperty registered with the given name, it will be permanently * removed from the existing superProperties. * To clear all superProperties, use {@link #clearSuperProperties()} * * @param superPropertyName name of the property to unregister * @see #registerSuperProperties(JSONObject) */ public void unregisterSuperProperty(String superPropertyName) { if (hasOptedOutTracking()) return; mPersistentIdentity.unregisterSuperProperty(superPropertyName); } /** * Register super properties for events, only if no other super property with the * same names has already been registered. * * <p>Calling registerSuperPropertiesOnce will never overwrite existing properties. * * @param superProperties A Map containing the super properties to register. * * See also {@link #registerSuperPropertiesOnce(org.json.JSONObject)} */ public void registerSuperPropertiesOnceMap(Map<String, Object> superProperties) { if (hasOptedOutTracking()) return; if (null == superProperties) { MPLog.e(LOGTAG, "registerSuperPropertiesOnceMap does not accept null properties"); return; } try { registerSuperPropertiesOnce(new JSONObject(superProperties)); } catch (NullPointerException e) { MPLog.w(LOGTAG, "Can't have null keys in the properties of registerSuperPropertiesOnce!"); } } /** * Register super properties for events, only if no other super property with the * same names has already been registered. * * <p>Calling registerSuperPropertiesOnce will never overwrite existing properties. * * @param superProperties A JSONObject containing the super properties to register. * @see #registerSuperProperties(JSONObject) */ public void registerSuperPropertiesOnce(JSONObject superProperties) { if (hasOptedOutTracking()) return; mPersistentIdentity.registerSuperPropertiesOnce(superProperties); } /** * Erase all currently registered superProperties. * * <p>Future tracking calls to Mixpanel will not contain the specific * superProperties registered before the clearSuperProperties method was called. * * <p>To remove a single superProperty, use {@link #unregisterSuperProperty(String)} * * @see #registerSuperProperties(JSONObject) */ public void clearSuperProperties() { mPersistentIdentity.clearSuperProperties(); } /** * Updates super properties in place. Given a SuperPropertyUpdate object, will * pass the current values of SuperProperties to that update and replace all * results with the return value of the update. Updates are synchronized on * the underlying super properties store, so they are guaranteed to be thread safe * (but long running updates may slow down your tracking.) * * @param update A function from one set of super properties to another. The update should not return null. */ public void updateSuperProperties(SuperPropertyUpdate update) { if (hasOptedOutTracking()) return; mPersistentIdentity.updateSuperProperties(update); } /** * Set the group this user belongs to. * * @param groupKey The property name associated with this group type (must already have been set up). * @param groupID The group the user belongs to. */ public void setGroup(String groupKey, Object groupID) { if (hasOptedOutTracking()) return; List<Object> groupIDs = new ArrayList<>(1); groupIDs.add(groupID); setGroup(groupKey, groupIDs); } /** * Set the groups this user belongs to. * * @param groupKey The property name associated with this group type (must already have been set up). * @param groupIDs The list of groups the user belongs to. */ public void setGroup(String groupKey, List<Object> groupIDs) { if (hasOptedOutTracking()) return; JSONArray vals = new JSONArray(); for (Object s : groupIDs) { if (s == null) { MPLog.w(LOGTAG, "groupID must be non-null"); } else { vals.put(s); } } try { registerSuperProperties((new JSONObject()).put(groupKey, vals)); mPeople.set(groupKey, vals); } catch (JSONException e) { MPLog.w(LOGTAG, "groupKey must be non-null"); } } /** * Add a group to this user's membership for a particular group key * * @param groupKey The property name associated with this group type (must already have been set up). * @param groupID The new group the user belongs to. */ public void addGroup(final String groupKey, final Object groupID) { if (hasOptedOutTracking()) return; updateSuperProperties(new SuperPropertyUpdate() { public JSONObject update(JSONObject in) { try { in.accumulate(groupKey, groupID); } catch (JSONException e) { MPLog.e(LOGTAG, "Failed to add groups superProperty", e); } return in; } }); // This is a best effort--if the people property is not already a list, this call does nothing. mPeople.union(groupKey, (new JSONArray()).put(groupID)); } /** * Remove a group from this user's membership for a particular group key * * @param groupKey The property name associated with this group type (must already have been set up). * @param groupID The group value to remove. */ public void removeGroup(final String groupKey, final Object groupID) { if (hasOptedOutTracking()) return; updateSuperProperties(new SuperPropertyUpdate() { public JSONObject update(JSONObject in) { try { JSONArray vals = in.getJSONArray(groupKey); JSONArray newVals = new JSONArray(); if (vals.length() <= 1) { in.remove(groupKey); // This is a best effort--we can't guarantee people and super properties match mPeople.unset(groupKey); } else { for (int i = 0; i < vals.length(); i++) { if (!vals.get(i).equals(groupID)) { newVals.put(vals.get(i)); } } in.put(groupKey, newVals); // This is a best effort--we can't guarantee people and super properties match // If people property is not a list, this call does nothing. mPeople.remove(groupKey, groupID); } } catch (JSONException e) { in.remove(groupKey); // This is a best effort--we can't guarantee people and super properties match mPeople.unset(groupKey); } return in; } }); } /** * Returns a Mixpanel.People object that can be used to set and increment * People Analytics properties. * * @return an instance of {@link People} that you can use to update * records in Mixpanel People Analytics and manage Mixpanel Firebase Cloud Messaging notifications. */ public People getPeople() { return mPeople; } /** * Returns a Mixpanel.Group object that can be used to set and increment * Group Analytics properties. * * @param groupKey String identifying the type of group (must be already in use as a group key) * @param groupID Object identifying the specific group * @return an instance of {@link Group} that you can use to update * records in Mixpanel Group Analytics */ public Group getGroup(String groupKey, Object groupID) { String mapKey = makeMapKey(groupKey, groupID); GroupImpl group = mGroups.get(mapKey); if (group == null) { group = new GroupImpl(groupKey, groupID); mGroups.put(mapKey, group); } if (!(group.mGroupKey.equals(groupKey) && group.mGroupID.equals(groupID))) { // we hit a map key collision, return a new group with the correct key and ID MPLog.i(LOGTAG, "groups map key collision " + mapKey); group = new GroupImpl(groupKey, groupID); mGroups.put(mapKey, group); } return group; } private String makeMapKey(String groupKey, Object groupID) { return groupKey + '_' + groupID; } /** * Clears tweaks and all distinct_ids, superProperties, and push registrations from persistent storage. * Will not clear referrer information. */ public void reset() { // Will clear distinct_ids, superProperties, notifications, experiments, // and waiting People Analytics properties. Will have no effect // on messages already queued to send with AnalyticsMessages. mPersistentIdentity.clearPreferences(); getAnalyticsMessages().clearAnonymousUpdatesMessage(new AnalyticsMessages.MixpanelDescription(mToken)); identify(getDistinctId(), false); mConnectIntegrations.reset(); mUpdatesFromMixpanel.storeVariants(new JSONArray()); mUpdatesFromMixpanel.applyPersistedUpdates(); flush(); } /** * Returns an unmodifiable map that contains the device description properties * that will be sent to Mixpanel. These are not all of the default properties, * but are a subset that are dependant on the user's device or installed version * of the host application, and are guaranteed not to change while the app is running. */ public Map<String, String> getDeviceInfo() { return mDeviceInfo; } /** * Use this method to opt-out a user from tracking. Events and people updates that haven't been * flushed yet will be deleted. Use {@link #flush()} before calling this method if you want * to send all the queues to Mixpanel before. * * This method will also remove any user-related information from the device. */ public void optOutTracking() { getAnalyticsMessages().emptyTrackingQueues(new AnalyticsMessages.MixpanelDescription(mToken)); if (getPeople().isIdentified()) { getPeople().deleteUser(); getPeople().clearCharges(); } mPersistentIdentity.clearPreferences(); synchronized (mEventTimings) { mEventTimings.clear(); mPersistentIdentity.clearTimeEvents(); } mPersistentIdentity.clearReferrerProperties(); mPersistentIdentity.setOptOutTracking(true, mToken); } /** * Use this method to opt-in an already opted-out user from tracking. People updates and track * calls will be sent to Mixpanel after using this method. * This method will internally track an opt-in event to your project. If you want to identify * the opt-in event and/or pass properties to the event, see {@link #optInTracking(String)} and * {@link #optInTracking(String, JSONObject)} * * See also {@link #optOutTracking()}. */ public void optInTracking() { optInTracking(null, null); } /** * Use this method to opt-in an already opted-out user from tracking. People updates and track * calls will be sent to Mixpanel after using this method. * This method will internally track an opt-in event to your project. * * @param distinctId Optional string to use as the distinct ID for events. * This will call {@link #identify(String)}. * If you use people profiles make sure you manually call * {@link People#identify(String)} after this method. * * See also {@link #optInTracking(String)}, {@link #optInTracking(String, JSONObject)} and * {@link #optOutTracking()}. */ public void optInTracking(String distinctId) { optInTracking(distinctId, null); } /** * Use this method to opt-in an already opted-out user from tracking. People updates and track * calls will be sent to Mixpanel after using this method. * This method will internally track an opt-in event to your project. * * @param distinctId Optional string to use as the distinct ID for events. * This will call {@link #identify(String)}. * If you use people profiles make sure you manually call * {@link People#identify(String)} after this method. * @param properties Optional JSONObject that could be passed to add properties to the * opt-in event that is sent to Mixpanel. * * See also {@link #optInTracking()} and {@link #optOutTracking()}. */ public void optInTracking(String distinctId, JSONObject properties) { mPersistentIdentity.setOptOutTracking(false, mToken); if (distinctId != null) { identify(distinctId); } track("$opt_in", properties); } /** * Will return true if the user has opted out from tracking. See {@link #optOutTracking()} and * {@link MixpanelAPI#getInstance(Context, String, boolean, JSONObject)} for more information. * * @return true if user has opted out from tracking. Defaults to false. */ public boolean hasOptedOutTracking() { return mPersistentIdentity.getOptOutTracking(mToken); } /** * Core interface for using Mixpanel People Analytics features. * You can get an instance by calling {@link MixpanelAPI#getPeople()} * * <p>The People object is used to update properties in a user's People Analytics record, * and to manage the receipt of push notifications sent via Mixpanel Engage. * For this reason, it's important to call {@link #identify(String)} on the People * object before you work with it. Once you call identify, the user identity will * persist across stops and starts of your application, until you make another * call to identify using a different id. * * A typical use case for the People object might look like this: * * <pre> * {@code * * public class MainActivity extends Activity { * MixpanelAPI mMixpanel; * * public void onCreate(Bundle saved) { * mMixpanel = MixpanelAPI.getInstance(this, "YOUR MIXPANEL API TOKEN"); * mMixpanel.getPeople().identify("A UNIQUE ID FOR THIS USER"); * ... * } * * public void userUpdatedJobTitle(String newTitle) { * mMixpanel.getPeople().set("Job Title", newTitle); * ... * } * * public void onDestroy() { * mMixpanel.flush(); * super.onDestroy(); * } * } * * } * </pre> * * @see MixpanelAPI */ public interface People { /** * Associate future calls to {@link #set(JSONObject)}, {@link #increment(Map)}, * {@link #append(String, Object)}, etc... with a particular People Analytics user. * * <p>All future calls to the People object will rely on this value to assign * and increment properties. The user identification will persist across * restarts of your application. We recommend calling * People.identify as soon as you know the distinct id of the user. * * @param distinctId a String that uniquely identifies the user. Users identified with * the same distinct id will be considered to be the same user in Mixpanel, * across all platforms and devices. We recommend choosing a distinct id * that is meaningful to your other systems (for example, a server-side account * identifier), and using the same distinct id for both calls to People.identify * and {@link MixpanelAPI#identify(String)} * * @see MixpanelAPI#identify(String) */ public void identify(String distinctId); /** * Sets a single property with the given name and value for this user. * The given name and value will be assigned to the user in Mixpanel People Analytics, * possibly overwriting an existing property with the same name. * * @param propertyName The name of the Mixpanel property. This must be a String, for example "Zip Code" * @param value The value of the Mixpanel property. For "Zip Code", this value might be the String "90210" */ public void set(String propertyName, Object value); /** * Set a collection of properties on the identified user all at once. * * @param properties a Map containing the collection of properties you wish to apply * to the identified user. Each key in the Map will be associated with * a property name, and the value of that key will be assigned to the property. * * See also {@link #set(org.json.JSONObject)} */ public void setMap(Map<String, Object> properties); /** * Set a collection of properties on the identified user all at once. * * @param properties a JSONObject containing the collection of properties you wish to apply * to the identified user. Each key in the JSONObject will be associated with * a property name, and the value of that key will be assigned to the property. */ public void set(JSONObject properties); /** * Works just like {@link People#set(String, Object)}, except it will not overwrite existing property values. This is useful for properties like "First login date". * * @param propertyName The name of the Mixpanel property. This must be a String, for example "Zip Code" * @param value The value of the Mixpanel property. For "Zip Code", this value might be the String "90210" */ public void setOnce(String propertyName, Object value); /** * Like {@link People#set(String, Object)}, but will not set properties that already exist on a record. * * @param properties a Map containing the collection of properties you wish to apply * to the identified user. Each key in the Map will be associated with * a property name, and the value of that key will be assigned to the property. * * See also {@link #setOnce(org.json.JSONObject)} */ public void setOnceMap(Map<String, Object> properties); /** * Like {@link People#set(String, Object)}, but will not set properties that already exist on a record. * * @param properties a JSONObject containing the collection of properties you wish to apply * to the identified user. Each key in the JSONObject will be associated with * a property name, and the value of that key will be assigned to the property. */ public void setOnce(JSONObject properties); /** * Add the given amount to an existing property on the identified user. If the user does not already * have the associated property, the amount will be added to zero. To reduce a property, * provide a negative number for the value. * * @param name the People Analytics property that should have its value changed * @param increment the amount to be added to the current value of the named property * * @see #increment(Map) */ public void increment(String name, double increment); /** * Merge a given JSONObject into the object-valued property named name. If the user does not * already have the associated property, an new property will be created with the value of * the given updates. If the user already has a value for the given property, the updates will * be merged into the existing value, with key/value pairs in updates taking precedence over * existing key/value pairs where the keys are the same. * * @param name the People Analytics property that should have the update merged into it * @param updates a JSONObject with keys and values that will be merged into the property */ public void merge(String name, JSONObject updates); /** * Change the existing values of multiple People Analytics properties at once. * * <p>If the user does not already have the associated property, the amount will * be added to zero. To reduce a property, provide a negative number for the value. * * @param properties A map of String properties names to Long amounts. Each * property associated with a name in the map will have its value changed by the given amount * * @see #increment(String, double) */ public void increment(Map<String, ? extends Number> properties); /** * Appends a value to a list-valued property. If the property does not currently exist, * it will be created as a list of one element. If the property does exist and doesn't * currently have a list value, the append will be ignored. * @param name the People Analytics property that should have it's value appended to * @param value the new value that will appear at the end of the property's list */ public void append(String name, Object value); /** * Adds values to a list-valued property only if they are not already present in the list. * If the property does not currently exist, it will be created with the given list as it's value. * If the property exists and is not list-valued, the union will be ignored. * * @param name name of the list-valued property to set or modify * @param value an array of values to add to the property value if not already present */ void union(String name, JSONArray value); /** * Remove value from a list-valued property only if they are already present in the list. * If the property does not currently exist, the remove will be ignored. * If the property exists and is not list-valued, the remove will be ignored. * @param name the People Analytics property that should have it's value removed from * @param value the value that will be removed from the property's list */ public void remove(String name, Object value); /** * permanently removes the property with the given name from the user's profile * @param name name of a property to unset */ void unset(String name); /** * Track a revenue transaction for the identified people profile. * * @param amount the amount of money exchanged. Positive amounts represent purchases or income from the customer, negative amounts represent refunds or payments to the customer. * @param properties an optional collection of properties to associate with this transaction. */ public void trackCharge(double amount, JSONObject properties); /** * Permanently clear the whole transaction history for the identified people profile. */ public void clearCharges(); /** * Permanently deletes the identified user's record from People Analytics. * * <p>Calling deleteUser deletes an entire record completely. Any future calls * to People Analytics using the same distinct id will create and store new values. */ public void deleteUser(); /** * Checks if the people profile is identified or not. * * @return Whether the current user is identified or not. */ public boolean isIdentified(); /** * This is a no-op, and will be removed in future versions of the library. * * @deprecated in 5.5.0. Google Cloud Messaging (GCM) is now deprecated by Google. * To enable end-to-end Firebase Cloud Messaging (FCM) from Mixpanel you only need to add * the following to your application manifest XML file: * * <pre> * {@code * <service * android:name="com.mixpanel.android.mpmetrics.MixpanelFCMMessagingService" * android:enabled="true" * android:exported="false"> * <intent-filter> * <action android:name="com.google.firebase.MESSAGING_EVENT"/> * </intent-filter> * </service> * } * </pre> * * Make sure you have a valid google-services.json file in your project and firebase * messaging is included as a dependency. Example: * * <pre> * {@code * buildscript { * ... * dependencies { * classpath 'com.google.gms:google-services:4.1.0' * ... * } * } * * dependencies { * implementation 'com.google.firebase:firebase-messaging:17.3.4' * implementation 'com.mixpanel.android:mixpanel-android:5.5.0' * } * * apply plugin: 'com.google.gms.google-services' * } * </pre> * * We recommend you update your Server Key on mixpanel.com from your Firebase console. Legacy * server keys are still supported. * * @see <a href="https://mixpanel.com/docs/people-analytics/android-push">Getting Started with Android Push Notifications</a> */ @Deprecated public void initPushHandling(String senderID); /** * Retrieves current Firebase Cloud Messaging token. * * <p>{@link People#getPushRegistrationId} should only be called after {@link #identify(String)} has been called. * * @return FCM push token or null if the user has not been registered in FCM. * * @see #setPushRegistrationId(String) * @see #clearPushRegistrationId */ public String getPushRegistrationId(); /** * Manually send a Firebase Cloud Messaging token to Mixpanel. * * <p>If you are handling Firebase Cloud Messages in your own application, but would like to * allow Mixpanel to handle messages originating from Mixpanel campaigns, you should * call setPushRegistrationId with the FCM token. * * <p>setPushRegistrationId should only be called after {@link #identify(String)} has been called. * * Optionally, applications that call setPushRegistrationId should also call * {@link #clearPushRegistrationId()} when they unregister the device id. * * @param token Firebase Cloud Messaging token * * @see #clearPushRegistrationId() */ public void setPushRegistrationId(String token); /** * Manually clear all current Firebase Cloud Messaging tokens from Mixpanel. * * <p>{@link People#clearPushRegistrationId} should only be called after {@link #identify(String)} has been called. * * <p>In general, all applications that call {@link #setPushRegistrationId(String)} should include a call to * clearPushRegistrationId. */ public void clearPushRegistrationId(); /** * Manually clear a single Firebase Cloud Messaging token from Mixpanel. * * <p>{@link People#clearPushRegistrationId} should only be called after {@link #identify(String)} has been called. * * <p>In general, all applications that call {@link #setPushRegistrationId(String)} should include a call to * clearPushRegistrationId. */ public void clearPushRegistrationId(String registrationId); /** * Returns the string id currently being used to uniquely identify the user associated * with events sent using {@link People#set(String, Object)} and {@link People#increment(String, double)}. * If no calls to {@link People#identify(String)} have been made, this method will return null. * * <p>The id returned by getDistinctId is independent of the distinct id used to identify * any events sent with {@link MixpanelAPI#track(String, JSONObject)}. To read and write that identifier, * use {@link MixpanelAPI#identify(String)} and {@link MixpanelAPI#getDistinctId()}. * * @return The distinct id associated with updates to People Analytics * * @see People#identify(String) * @see MixpanelAPI#getDistinctId() */ public String getDistinctId(); /** * Shows an in-app notification to the user if one is available. If the notification * is a mini notification, this method will attach and remove a Fragment to parent. * The lifecycle of the Fragment will be handled entirely by the Mixpanel library. * * <p>If the notification is a takeover notification, a TakeoverInAppActivity will be launched to * display the Takeover notification. * * <p>It is safe to call this method any time you want to potentially display an in-app notification. * This method will be a no-op if there is already an in-app notification being displayed. * * <p>This method is a no-op in environments with * Android API before JellyBean/API level 16. * * @param parent the Activity that the mini notification will be displayed in, or the Activity * that will be used to launch TakeoverInAppActivity for the takeover notification. */ public void showNotificationIfAvailable(Activity parent); /** * Applies A/B test changes, if they are present. By default, your application will attempt * to join available experiments any time an activity is resumed, but you can disable this * automatic behavior by adding the following tag to the &lt;application&gt; tag in your AndroidManifest.xml * {@code * <meta-data android:name="com.mixpanel.android.MPConfig.AutoShowMixpanelUpdates" * android:value="false" /> * } * * If you disable AutoShowMixpanelUpdates, you'll need to call joinExperimentIfAvailable to * join or clear existing experiments. If you want to display a loading screen or otherwise * wait for experiments to load from the server before you apply them, you can use * {@link #addOnMixpanelUpdatesReceivedListener(OnMixpanelUpdatesReceivedListener)} to * be informed that new experiments are ready. */ public void joinExperimentIfAvailable(); /** * Shows the given in-app notification to the user. Display will occur just as if the * notification was shown via showNotificationIfAvailable. In most cases, it is * easier and more efficient to use showNotificationIfAvailable. * * @param notif the {@link com.mixpanel.android.mpmetrics.InAppNotification} to show * * @param parent the Activity that the mini notification will be displayed in, or the Activity * that will be used to launch TakeoverInAppActivity for the takeover notification. */ public void showGivenNotification(InAppNotification notif, Activity parent); /** * Sends an event to Mixpanel that includes the automatic properties associated * with the given notification. In most cases this is not required, unless you're * not showing notifications using the library-provided in views and activities. * * @param eventName the name to use when the event is tracked. * * @param notif the {@link com.mixpanel.android.mpmetrics.InAppNotification} associated with the event you'd like to track. * * @param properties additional properties to be tracked with the event. */ public void trackNotification(String eventName, InAppNotification notif, JSONObject properties); /** * Returns an InAppNotification object if one is available and being held by the library, or null if * no notification is currently available. Callers who want to display in-app notifications should call this * method periodically. A given InAppNotification will be returned only once from this method, so callers * should be ready to consume any non-null return value. * * <p>This function will return quickly, and will not cause any communication with * Mixpanel's servers, so it is safe to call this from the UI thread. * * Note: you must call call {@link People#trackNotificationSeen(InAppNotification)} or you will * receive the same {@link com.mixpanel.android.mpmetrics.InAppNotification} again the * next time notifications are refreshed from Mixpanel's servers (on identify, or when * your app is destroyed and re-created) * * @return an InAppNotification object if one is available, null otherwise. */ public InAppNotification getNotificationIfAvailable(); /** * Tells MixPanel that you have handled an {@link com.mixpanel.android.mpmetrics.InAppNotification} * in the case where you are manually dealing with your notifications ({@link People#getNotificationIfAvailable()}). * * Note: if you do not acknowledge the notification you will receive it again each time * you call {@link People#identify(String)} and then call {@link People#getNotificationIfAvailable()} * * @param notif the notification to track (no-op on null) */ void trackNotificationSeen(InAppNotification notif); /** * Shows an in-app notification identified by id. The behavior of this is otherwise identical to * {@link People#showNotificationIfAvailable(Activity)}. * * @param id the id of the InAppNotification you wish to show. * @param parent the Activity that the mini notification will be displayed in, or the Activity * that will be used to launch TakeoverInAppActivity for the takeover notification. */ public void showNotificationById(int id, final Activity parent); /** * Return an instance of Mixpanel people with a temporary distinct id. * Instances returned by withIdentity will not check decide with the given distinctId. */ public People withIdentity(String distinctId); /** * Adds a new listener that will receive a callback when new updates from Mixpanel * (like in-app notifications or A/B test experiments) are discovered. Most users of the library * will not need this method since in-app notifications and experiments are * applied automatically to your application by default. * * <p>The given listener will be called when a new batch of updates is detected. Handlers * should be prepared to handle the callback on an arbitrary thread. * * <p>The listener will be called when new in-app notifications or experiments * are detected as available. That means you wait to call * {@link People#showNotificationIfAvailable(Activity)}, and {@link People#joinExperimentIfAvailable()} * to show content and updates that have been delivered to your app. (You can also call these * functions whenever else you would like, they're inexpensive and will do nothing if no * content is available.) * * @param listener the listener to add */ public void addOnMixpanelUpdatesReceivedListener(OnMixpanelUpdatesReceivedListener listener); /** * Removes a listener previously registered with addOnMixpanelUpdatesReceivedListener. * * @param listener the listener to add */ public void removeOnMixpanelUpdatesReceivedListener(OnMixpanelUpdatesReceivedListener listener); /** * Sets the listener that will receive a callback when new Tweaks from Mixpanel are discovered. Most * users of the library will not need this method, since Tweaks are applied automatically to your * application by default. * * <p>The given listener will be called when a new batch of Tweaks is applied. Handlers * should be prepared to handle the callback on an arbitrary thread. * * <p>The listener will be called when new Tweaks are detected as available. That means the listener * will get called once {@link People#joinExperimentIfAvailable()} has successfully applied the changes. * * @param listener the listener to set */ public void addOnMixpanelTweaksUpdatedListener(OnMixpanelTweaksUpdatedListener listener); /** * Removes the listener previously registered with addOnMixpanelTweaksUpdatedListener. * */ public void removeOnMixpanelTweaksUpdatedListener(OnMixpanelTweaksUpdatedListener listener); } /** * Core interface for using Mixpanel Group Analytics features. * You can get an instance by calling {@link MixpanelAPI#getGroup(String, Object)} * * <p>The Group object is used to update properties in a group's Group Analytics record. * * A typical use case for the Group object might look like this: * * <pre> * {@code * * public class MainActivity extends Activity { * MixpanelAPI mMixpanel; * * public void onCreate(Bundle saved) { * mMixpanel = MixpanelAPI.getInstance(this, "YOUR MIXPANEL API TOKEN"); * ... * } * * public void companyPlanTypeChanged(string company, String newPlan) { * mMixpanel.getGroup("Company", company).set("Plan Type", newPlan); * ... * } * * public void onDestroy() { * mMixpanel.flush(); * super.onDestroy(); * } * } * * } * </pre> * * @see MixpanelAPI */ public interface Group { /** * Sets a single property with the given name and value for this group. * The given name and value will be assigned to the user in Mixpanel Group Analytics, * possibly overwriting an existing property with the same name. * * @param propertyName The name of the Mixpanel property. This must be a String, for example "Zip Code" * @param value The value of the Mixpanel property. For "Zip Code", this value might be the String "90210" */ public void set(String propertyName, Object value); /** * Set a collection of properties on the identified group all at once. * * @param properties a Map containing the collection of properties you wish to apply * to the identified group. Each key in the Map will be associated with * a property name, and the value of that key will be assigned to the property. * * See also {@link #set(org.json.JSONObject)} */ public void setMap(Map<String, Object> properties); /** * Set a collection of properties on the identified group all at once. * * @param properties a JSONObject containing the collection of properties you wish to apply * to the identified group. Each key in the JSONObject will be associated with * a property name, and the value of that key will be assigned to the property. */ public void set(JSONObject properties); /** * Works just like {@link Group#set(String, Object)}, except it will not overwrite existing property values. This is useful for properties like "First login date". * * @param propertyName The name of the Mixpanel property. This must be a String, for example "Zip Code" * @param value The value of the Mixpanel property. For "Zip Code", this value might be the String "90210" */ public void setOnce(String propertyName, Object value); /** * Like {@link Group#set(String, Object)}, but will not set properties that already exist on a record. * * @param properties a Map containing the collection of properties you wish to apply * to the identified group. Each key in the Map will be associated with * a property name, and the value of that key will be assigned to the property. * * See also {@link #setOnce(org.json.JSONObject)} */ public void setOnceMap(Map<String, Object> properties); /** * Like {@link Group#set(String, Object)}, but will not set properties that already exist on a record. * * @param properties a JSONObject containing the collection of properties you wish to apply * to this group. Each key in the JSONObject will be associated with * a property name, and the value of that key will be assigned to the property. */ public void setOnce(JSONObject properties); /** * Adds values to a list-valued property only if they are not already present in the list. * If the property does not currently exist, it will be created with the given list as its value. * If the property exists and is not list-valued, the union will be ignored. * * @param name name of the list-valued property to set or modify * @param value an array of values to add to the property value if not already present */ void union(String name, JSONArray value); /** * Remove value from a list-valued property only if it is already present in the list. * If the property does not currently exist, the remove will be ignored. * If the property exists and is not list-valued, the remove will be ignored. * * @param name the Group Analytics list-valued property that should have a value removed * @param value the value that will be removed from the list */ public void remove(String name, Object value); /** * Permanently removes the property with the given name from the group's profile * @param name name of a property to unset */ void unset(String name); /** * Permanently deletes this group's record from Group Analytics. * * <p>Calling deleteGroup deletes an entire record completely. Any future calls * to Group Analytics using the same group value will create and store new values. */ public void deleteGroup(); } /** * This method is a no-op, kept for compatibility purposes. * * To enable verbose logging about communication with Mixpanel, add * {@code * <meta-data android:name="com.mixpanel.android.MPConfig.EnableDebugLogging" /> * } * * To the {@code <application>} tag of your AndroidManifest.xml file. * * @deprecated in 4.1.0, use Manifest meta-data instead */ @Deprecated public void logPosts() { MPLog.i( LOGTAG, "MixpanelAPI.logPosts() is deprecated.\n" + " To get verbose debug level logging, add\n" + " <meta-data android:name=\"com.mixpanel.android.MPConfig.EnableDebugLogging\" value=\"true\" />\n" + " to the <application> section of your AndroidManifest.xml." ); } /** * Attempt to register MixpanelActivityLifecycleCallbacks to the application's event lifecycle. * Once registered, we can automatically check for and show in-app notifications * when any Activity is opened. * * This is only available if the android version is >= 16. You can disable livecycle callbacks by setting * com.mixpanel.android.MPConfig.AutoShowMixpanelUpdates to false in your AndroidManifest.xml * * This function is automatically called when the library is initialized unless you explicitly * set com.mixpanel.android.MPConfig.AutoShowMixpanelUpdates to false in your AndroidManifest.xml */ @TargetApi(Build.VERSION_CODES.ICE_CREAM_SANDWICH) /* package */ void registerMixpanelActivityLifecycleCallbacks() { if (android.os.Build.VERSION.SDK_INT >= Build.VERSION_CODES.ICE_CREAM_SANDWICH) { if (mContext.getApplicationContext() instanceof Application) { final Application app = (Application) mContext.getApplicationContext(); mMixpanelActivityLifecycleCallbacks = new MixpanelActivityLifecycleCallbacks(this, mConfig); app.registerActivityLifecycleCallbacks(mMixpanelActivityLifecycleCallbacks); } else { MPLog.i(LOGTAG, "Context is not an Application, Mixpanel will not automatically show in-app notifications or A/B test experiments. We won't be able to automatically flush on an app background."); } } } /** * Based on the application's event lifecycle this method will determine whether the app * is running in the foreground or not. * * If your build version is below 14 this method will always return false. * * @return True if the app is running in the foreground. */ public boolean isAppInForeground() { if (android.os.Build.VERSION.SDK_INT >= Build.VERSION_CODES.ICE_CREAM_SANDWICH) { if (mMixpanelActivityLifecycleCallbacks != null) { return mMixpanelActivityLifecycleCallbacks.isInForeground(); } } else { MPLog.e(LOGTAG, "Your build version is below 14. This method will always return false."); } return false; } /* package */ void onBackground() { flush(); mUpdatesFromMixpanel.applyPersistedUpdates(); } /* package */ void onForeground() { mSessionMetadata.initSession(); } // Package-level access. Used (at least) by MixpanelFCMMessagingService // when OS-level events occur. /* package */ interface InstanceProcessor { public void process(MixpanelAPI m); } /* package */ static void allInstances(InstanceProcessor processor) { synchronized (sInstanceMap) { for (final Map<Context, MixpanelAPI> contextInstances : sInstanceMap.values()) { for (final MixpanelAPI instance : contextInstances.values()) { processor.process(instance); } } } } //////////////////////////////////////////////////////////////////// // Conveniences for testing. These methods should not be called by // non-test client code. /* package */ AnalyticsMessages getAnalyticsMessages() { return AnalyticsMessages.getInstance(mContext); } /* package */ DecideMessages getDecideMessages() { return mDecideMessages; } /* package */ PersistentIdentity getPersistentIdentity(final Context context, Future<SharedPreferences> referrerPreferences, final String token) { final SharedPreferencesLoader.OnPrefsLoadedListener listener = new SharedPreferencesLoader.OnPrefsLoadedListener() { @Override public void onPrefsLoaded(SharedPreferences preferences) { final String distinctId = PersistentIdentity.getPeopleDistinctId(preferences); if (null != distinctId) { pushWaitingPeopleRecord(distinctId); } } }; final String prefsName = "com.mixpanel.android.mpmetrics.MixpanelAPI_" + token; final Future<SharedPreferences> storedPreferences = sPrefsLoader.loadPreferences(context, prefsName, listener); final String timeEventsPrefsName = "com.mixpanel.android.mpmetrics.MixpanelAPI.TimeEvents_" + token; final Future<SharedPreferences> timeEventsPrefs = sPrefsLoader.loadPreferences(context, timeEventsPrefsName, null); final String mixpanelPrefsName = "com.mixpanel.android.mpmetrics.Mixpanel"; final Future<SharedPreferences> mixpanelPrefs = sPrefsLoader.loadPreferences(context, mixpanelPrefsName, null); return new PersistentIdentity(referrerPreferences, storedPreferences, timeEventsPrefs, mixpanelPrefs); } /* package */ DecideMessages constructDecideUpdates(final String token, final DecideMessages.OnNewResultsListener listener, UpdatesFromMixpanel updatesFromMixpanel) { return new DecideMessages(mContext, token, listener, updatesFromMixpanel, mPersistentIdentity.getSeenCampaignIds()); } /* package */ UpdatesListener constructUpdatesListener() { if (Build.VERSION.SDK_INT < MPConfig.UI_FEATURES_MIN_API) { MPLog.i(LOGTAG, "Notifications are not supported on this Android OS Version"); return new UnsupportedUpdatesListener(); } else { return new SupportedUpdatesListener(); } } /* package */ UpdatesFromMixpanel constructUpdatesFromMixpanel(final Context context, final String token) { if (Build.VERSION.SDK_INT < MPConfig.UI_FEATURES_MIN_API) { MPLog.i(LOGTAG, "SDK version is lower than " + MPConfig.UI_FEATURES_MIN_API + ". Web Configuration, A/B Testing, and Dynamic Tweaks are disabled."); return new NoOpUpdatesFromMixpanel(sSharedTweaks); } else if (mConfig.getDisableViewCrawler() || Arrays.asList(mConfig.getDisableViewCrawlerForProjects()).contains(token)) { MPLog.i(LOGTAG, "DisableViewCrawler is set to true. Web Configuration, A/B Testing, and Dynamic Tweaks are disabled."); return new NoOpUpdatesFromMixpanel(sSharedTweaks); } else { return new ViewCrawler(mContext, mToken, this, sSharedTweaks); } } /* package */ TrackingDebug constructTrackingDebug() { if (mUpdatesFromMixpanel instanceof ViewCrawler) { return (TrackingDebug) mUpdatesFromMixpanel; } return null; } /* package */ boolean sendAppOpen() { return !mConfig.getDisableAppOpenEvent(); } /////////////////////// private class PeopleImpl implements People { @Override public void identify(String distinctId) { if (hasOptedOutTracking()) return; synchronized (mPersistentIdentity) { mPersistentIdentity.setPeopleDistinctId(distinctId); mDecideMessages.setDistinctId(distinctId); } pushWaitingPeopleRecord(distinctId); } @Override public void setMap(Map<String, Object> properties) { if (hasOptedOutTracking()) return; if (null == properties) { MPLog.e(LOGTAG, "setMap does not accept null properties"); return; } try { set(new JSONObject(properties)); } catch (NullPointerException e) { MPLog.w(LOGTAG, "Can't have null keys in the properties of setMap!"); } } @Override public void set(JSONObject properties) { if (hasOptedOutTracking()) return; try { final JSONObject sendProperties = new JSONObject(mDeviceInfo); for (final Iterator<?> iter = properties.keys(); iter.hasNext();) { final String key = (String) iter.next(); sendProperties.put(key, properties.get(key)); } final JSONObject message = stdPeopleMessage("$set", sendProperties); recordPeopleMessage(message); } catch (final JSONException e) { MPLog.e(LOGTAG, "Exception setting people properties", e); } } @Override public void set(String property, Object value) { if (hasOptedOutTracking()) return; try { set(new JSONObject().put(property, value)); } catch (final JSONException e) { MPLog.e(LOGTAG, "set", e); } } @Override public void setOnceMap(Map<String, Object> properties) { if (hasOptedOutTracking()) return; if (null == properties) { MPLog.e(LOGTAG, "setOnceMap does not accept null properties"); return; } try { setOnce(new JSONObject(properties)); } catch (NullPointerException e) { MPLog.w(LOGTAG, "Can't have null keys in the properties setOnceMap!"); } } @Override public void setOnce(JSONObject properties) { if (hasOptedOutTracking()) return; try { final JSONObject message = stdPeopleMessage("$set_once", properties); recordPeopleMessage(message); } catch (final JSONException e) { MPLog.e(LOGTAG, "Exception setting people properties"); } } @Override public void setOnce(String property, Object value) { if (hasOptedOutTracking()) return; try { setOnce(new JSONObject().put(property, value)); } catch (final JSONException e) { MPLog.e(LOGTAG, "set", e); } } @Override public void increment(Map<String, ? extends Number> properties) { if (hasOptedOutTracking()) return; final JSONObject json = new JSONObject(properties); try { final JSONObject message = stdPeopleMessage("$add", json); recordPeopleMessage(message); } catch (final JSONException e) { MPLog.e(LOGTAG, "Exception incrementing properties", e); } } @Override // Must be thread safe public void merge(String property, JSONObject updates) { if (hasOptedOutTracking()) return; final JSONObject mergeMessage = new JSONObject(); try { mergeMessage.put(property, updates); final JSONObject message = stdPeopleMessage("$merge", mergeMessage); recordPeopleMessage(message); } catch (final JSONException e) { MPLog.e(LOGTAG, "Exception merging a property", e); } } @Override public void increment(String property, double value) { if (hasOptedOutTracking()) return; final Map<String, Double> map = new HashMap<String, Double>(); map.put(property, value); increment(map); } @Override public void append(String name, Object value) { if (hasOptedOutTracking()) return; try { final JSONObject properties = new JSONObject(); properties.put(name, value); final JSONObject message = stdPeopleMessage("$append", properties); recordPeopleMessage(message); } catch (final JSONException e) { MPLog.e(LOGTAG, "Exception appending a property", e); } } @Override public void union(String name, JSONArray value) { if (hasOptedOutTracking()) return; try { final JSONObject properties = new JSONObject(); properties.put(name, value); final JSONObject message = stdPeopleMessage("$union", properties); recordPeopleMessage(message); } catch (final JSONException e) { MPLog.e(LOGTAG, "Exception unioning a property"); } } @Override public void remove(String name, Object value) { if (hasOptedOutTracking()) return; try { final JSONObject properties = new JSONObject(); properties.put(name, value); final JSONObject message = stdPeopleMessage("$remove", properties); recordPeopleMessage(message); } catch (final JSONException e) { MPLog.e(LOGTAG, "Exception appending a property", e); } } @Override public void unset(String name) { if (hasOptedOutTracking()) return; try { final JSONArray names = new JSONArray(); names.put(name); final JSONObject message = stdPeopleMessage("$unset", names); recordPeopleMessage(message); } catch (final JSONException e) { MPLog.e(LOGTAG, "Exception unsetting a property", e); } } @Override public InAppNotification getNotificationIfAvailable() { return mDecideMessages.getNotification(mConfig.getTestMode()); } @Override public void trackNotificationSeen(InAppNotification notif) { if (notif == null) return; mPersistentIdentity.saveCampaignAsSeen(notif.getId()); if (hasOptedOutTracking()) return; trackNotification("$campaign_delivery", notif, null); final MixpanelAPI.People people = getPeople().withIdentity(getDistinctId()); if (people != null) { final DateFormat dateFormat = new SimpleDateFormat(ENGAGE_DATE_FORMAT_STRING, Locale.US); final JSONObject notifProperties = notif.getCampaignProperties(); try { notifProperties.put("$time", dateFormat.format(new Date())); } catch (final JSONException e) { MPLog.e(LOGTAG, "Exception trying to track an in-app notification seen", e); } people.append("$campaigns", notif.getId()); people.append("$notifications", notifProperties); } else { MPLog.e(LOGTAG, "No identity found. Make sure to call getPeople().identify() before showing in-app notifications."); } } @Override public void showNotificationIfAvailable(final Activity parent) { if (Build.VERSION.SDK_INT < MPConfig.UI_FEATURES_MIN_API) { return; } showGivenOrAvailableNotification(null, parent); } @Override public void showNotificationById(int id, final Activity parent) { final InAppNotification notif = mDecideMessages.getNotification(id, mConfig.getTestMode()); showGivenNotification(notif, parent); } @Override public void showGivenNotification(final InAppNotification notif, final Activity parent) { if (notif != null) { showGivenOrAvailableNotification(notif, parent); } } @Override public void trackNotification(final String eventName, final InAppNotification notif, final JSONObject properties) { if (hasOptedOutTracking()) return; JSONObject notificationProperties = notif.getCampaignProperties(); if (properties != null) { try { Iterator<String> keyIterator = properties.keys(); while (keyIterator.hasNext()) { String key = keyIterator.next(); notificationProperties.put(key, properties.get(key)); } } catch (final JSONException e) { MPLog.e(LOGTAG, "Exception merging provided properties with notification properties", e); } } track(eventName, notificationProperties); } @Override public void joinExperimentIfAvailable() { final JSONArray variants = mDecideMessages.getVariants(); mUpdatesFromMixpanel.setVariants(variants); } @Override public void trackCharge(double amount, JSONObject properties) { if (hasOptedOutTracking()) return; final Date now = new Date(); final DateFormat dateFormat = new SimpleDateFormat(ENGAGE_DATE_FORMAT_STRING, Locale.US); dateFormat.setTimeZone(TimeZone.getTimeZone("UTC")); try { final JSONObject transactionValue = new JSONObject(); transactionValue.put("$amount", amount); transactionValue.put("$time", dateFormat.format(now)); if (null != properties) { for (final Iterator<?> iter = properties.keys(); iter.hasNext();) { final String key = (String) iter.next(); transactionValue.put(key, properties.get(key)); } } this.append("$transactions", transactionValue); } catch (final JSONException e) { MPLog.e(LOGTAG, "Exception creating new charge", e); } } /** * Permanently clear the whole transaction history for the identified people profile. */ @Override public void clearCharges() { this.unset("$transactions"); } @Override public void deleteUser() { try { final JSONObject message = stdPeopleMessage("$delete", JSONObject.NULL); recordPeopleMessage(message); } catch (final JSONException e) { MPLog.e(LOGTAG, "Exception deleting a user"); } } @Override public String getPushRegistrationId() { return mPersistentIdentity.getPushId(); } @Override public void setPushRegistrationId(String registrationId) { String existingRegistrationId = getPushRegistrationId(); if (existingRegistrationId != null && existingRegistrationId.equals(registrationId)) { return; } // Must be thread safe, will be called from a lot of different threads. synchronized (mPersistentIdentity) { MPLog.d(LOGTAG, "Setting new push token on people profile: " + registrationId); mPersistentIdentity.storePushId(registrationId); final JSONArray ids = new JSONArray(); ids.put(registrationId); union("$android_devices", ids); } } @Override public void clearPushRegistrationId() { mPersistentIdentity.clearPushId(); set("$android_devices", new JSONArray()); } @Override public void clearPushRegistrationId(String registrationId) { if (registrationId == null) { return; } if (registrationId.equals(mPersistentIdentity.getPushId())) { mPersistentIdentity.clearPushId(); } remove("$android_devices", registrationId); } @Override public void initPushHandling(String senderID) { MPLog.w( LOGTAG, "MixpanelAPI.initPushHandling is deprecated. This is a no-op.\n" + " Mixpanel now uses Firebase Cloud Messaging. You need to remove your old Mixpanel" + " GCM Receiver from your AndroidManifest.xml and add the following:\n" + " <service\n" + " android:name=\"com.mixpanel.android.mpmetrics.MixpanelFCMMessagingService\"\n" + " android:enabled=\"true\"\n" + " android:exported=\"false\">\n" + " <intent-filter>\n" + " <action android:name=\"com.google.firebase.MESSAGING_EVENT\"/>\n" + " </intent-filter>\n" + " </service>\n\n" + "Make sure to add firebase messaging as a dependency on your gradle file:\n" + "buildscript {\n" + " ...\n" + " dependencies {\n" + " classpath 'com.google.gms:google-services:4.1.0'\n" + " ...\n" + " }\n" + "}\n" + "dependencies {\n" + " implementation 'com.google.firebase:firebase-messaging:17.3.4'\n" + " implementation 'com.mixpanel.android:mixpanel-android:5.5.0'\n" + "}\n" + "apply plugin: 'com.google.gms.google-services'" ); } @Override public String getDistinctId() { return mPersistentIdentity.getPeopleDistinctId(); } @Override public People withIdentity(final String distinctId) { if (null == distinctId) { return null; } return new PeopleImpl() { @Override public String getDistinctId() { return distinctId; } @Override public void identify(String distinctId) { throw new RuntimeException("This MixpanelPeople object has a fixed, constant distinctId"); } }; } @Override public void addOnMixpanelUpdatesReceivedListener(final OnMixpanelUpdatesReceivedListener listener) { mUpdatesListener.addOnMixpanelUpdatesReceivedListener(listener); } @Override public void removeOnMixpanelUpdatesReceivedListener(final OnMixpanelUpdatesReceivedListener listener) { mUpdatesListener.removeOnMixpanelUpdatesReceivedListener(listener); } @Override public void addOnMixpanelTweaksUpdatedListener(OnMixpanelTweaksUpdatedListener listener) { if (null == listener) { throw new NullPointerException("Listener cannot be null"); } mUpdatesFromMixpanel.addOnMixpanelTweaksUpdatedListener(listener); } @Override public void removeOnMixpanelTweaksUpdatedListener(OnMixpanelTweaksUpdatedListener listener) { mUpdatesFromMixpanel.removeOnMixpanelTweaksUpdatedListener(listener); } private JSONObject stdPeopleMessage(String actionType, Object properties) throws JSONException { final JSONObject dataObj = new JSONObject(); final String distinctId = getDistinctId(); // TODO ensure getDistinctId is thread safe final String anonymousId = getAnonymousId(); dataObj.put(actionType, properties); dataObj.put("$token", mToken); dataObj.put("$time", System.currentTimeMillis()); dataObj.put("$had_persisted_distinct_id", mPersistentIdentity.getHadPersistedDistinctId()); if (null != anonymousId) { dataObj.put("$device_id", anonymousId); } if (null != distinctId) { dataObj.put("$distinct_id", distinctId); dataObj.put("$user_id", distinctId); } dataObj.put("$mp_metadata", mSessionMetadata.getMetadataForPeople()); return dataObj; } private void showGivenOrAvailableNotification(final InAppNotification notifOrNull, final Activity parent) { if (Build.VERSION.SDK_INT < MPConfig.UI_FEATURES_MIN_API) { MPLog.v(LOGTAG, "Will not show notifications, os version is too low."); return; } parent.runOnUiThread(new Runnable() { @Override @TargetApi(MPConfig.UI_FEATURES_MIN_API) public void run() { final ReentrantLock lock = UpdateDisplayState.getLockObject(); lock.lock(); try { if (UpdateDisplayState.hasCurrentProposal()) { MPLog.v(LOGTAG, "DisplayState is locked, will not show notifications."); return; // Already being used. } InAppNotification toShow = notifOrNull; if (null == toShow) { toShow = getNotificationIfAvailable(); } if (null == toShow) { MPLog.v(LOGTAG, "No notification available, will not show."); return; // Nothing to show } final InAppNotification.Type inAppType = toShow.getType(); if (inAppType == InAppNotification.Type.TAKEOVER && !ConfigurationChecker.checkTakeoverInAppActivityAvailable(parent.getApplicationContext())) { MPLog.v(LOGTAG, "Application is not configured to show takeover notifications, none will be shown."); return; // Can't show due to config. } final int highlightColor = ActivityImageUtils.getHighlightColorFromBackground(parent); final UpdateDisplayState.DisplayState.InAppNotificationState proposal = new UpdateDisplayState.DisplayState.InAppNotificationState(toShow, highlightColor); final int intentId = UpdateDisplayState.proposeDisplay(proposal, getDistinctId(), mToken); if (intentId <= 0) { MPLog.e(LOGTAG, "DisplayState Lock in inconsistent state! Please report this issue to Mixpanel"); return; } switch (inAppType) { case MINI: { final UpdateDisplayState claimed = UpdateDisplayState.claimDisplayState(intentId); if (null == claimed) { MPLog.v(LOGTAG, "Notification's display proposal was already consumed, no notification will be shown."); return; // Can't claim the display state } final InAppFragment inapp = new InAppFragment(); inapp.setDisplayState( MixpanelAPI.this, intentId, (UpdateDisplayState.DisplayState.InAppNotificationState) claimed.getDisplayState() ); inapp.setRetainInstance(true); MPLog.v(LOGTAG, "Attempting to show mini notification."); final FragmentTransaction transaction = parent.getFragmentManager().beginTransaction(); transaction.setCustomAnimations(0, R.animator.com_mixpanel_android_slide_down); transaction.add(android.R.id.content, inapp); try { transaction.commit(); } catch (IllegalStateException e) { // if the app is in the background or the current activity gets killed, rendering the // notifiction will lead to a crash MPLog.v(LOGTAG, "Unable to show notification."); mDecideMessages.markNotificationAsUnseen(toShow); } } break; case TAKEOVER: { MPLog.v(LOGTAG, "Sending intent for takeover notification."); final Intent intent = new Intent(parent.getApplicationContext(), TakeoverInAppActivity.class); intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK); intent.addFlags(Intent.FLAG_ACTIVITY_REORDER_TO_FRONT); intent.putExtra(TakeoverInAppActivity.INTENT_ID_KEY, intentId); parent.startActivity(intent); } break; default: MPLog.e(LOGTAG, "Unrecognized notification type " + inAppType + " can't be shown"); } if (!mConfig.getTestMode()) { trackNotificationSeen(toShow); } } finally { lock.unlock(); } } // run() }); } @Override public boolean isIdentified() { return getDistinctId() != null; } }// PeopleImpl private interface UpdatesListener extends DecideMessages.OnNewResultsListener { public void addOnMixpanelUpdatesReceivedListener(OnMixpanelUpdatesReceivedListener listener); public void removeOnMixpanelUpdatesReceivedListener(OnMixpanelUpdatesReceivedListener listener); } private class UnsupportedUpdatesListener implements UpdatesListener { @Override public void onNewResults() { // Do nothing, these features aren't supported in older versions of the library } @Override public void addOnMixpanelUpdatesReceivedListener(OnMixpanelUpdatesReceivedListener listener) { // Do nothing, not supported } @Override public void removeOnMixpanelUpdatesReceivedListener(OnMixpanelUpdatesReceivedListener listener) { // Do nothing, not supported } } private class GroupImpl implements Group { private String mGroupKey; private Object mGroupID; public GroupImpl(String groupKey, Object groupID) { mGroupKey = groupKey; mGroupID = groupID; } @Override public void setMap(Map<String, Object> properties) { if (hasOptedOutTracking()) return; if (null == properties) { MPLog.e(LOGTAG, "setMap does not accept null properties"); return; } set(new JSONObject(properties)); } @Override public void set(JSONObject properties) { if (hasOptedOutTracking()) return; try { final JSONObject sendProperties = new JSONObject(); for (final Iterator<?> iter = properties.keys(); iter.hasNext();) { final String key = (String) iter.next(); sendProperties.put(key, properties.get(key)); } final JSONObject message = stdGroupMessage("$set", sendProperties); recordGroupMessage(message); } catch (final JSONException e) { MPLog.e(LOGTAG, "Exception setting group properties", e); } } @Override public void set(String property, Object value) { if (hasOptedOutTracking()) return; try { set(new JSONObject().put(property, value)); } catch (final JSONException e) { MPLog.e(LOGTAG, "set", e); } } @Override public void setOnceMap(Map<String, Object> properties) { if (hasOptedOutTracking()) return; if (null == properties) { MPLog.e(LOGTAG, "setOnceMap does not accept null properties"); return; } try { setOnce(new JSONObject(properties)); } catch (NullPointerException e) { MPLog.w(LOGTAG, "Can't have null keys in the properties for setOnceMap!"); } } @Override public void setOnce(JSONObject properties) { if (hasOptedOutTracking()) return; try { final JSONObject message = stdGroupMessage("$set_once", properties); recordGroupMessage(message); } catch (final JSONException e) { MPLog.e(LOGTAG, "Exception setting group properties"); } } @Override public void setOnce(String property, Object value) { if (hasOptedOutTracking()) return; try { setOnce(new JSONObject().put(property, value)); } catch (final JSONException e) { MPLog.e(LOGTAG, "Property name cannot be null", e); } } @Override public void union(String name, JSONArray value) { if (hasOptedOutTracking()) return; try { final JSONObject properties = new JSONObject(); properties.put(name, value); final JSONObject message = stdGroupMessage("$union", properties); recordGroupMessage(message); } catch (final JSONException e) { MPLog.e(LOGTAG, "Exception unioning a property", e); } } @Override public void remove(String name, Object value) { if (hasOptedOutTracking()) return; try { final JSONObject properties = new JSONObject(); properties.put(name, value); final JSONObject message = stdGroupMessage("$remove", properties); recordGroupMessage(message); } catch (final JSONException e) { MPLog.e(LOGTAG, "Exception removing a property", e); } } @Override public void unset(String name) { if (hasOptedOutTracking()) return; try { final JSONArray names = new JSONArray(); names.put(name); final JSONObject message = stdGroupMessage("$unset", names); recordGroupMessage(message); } catch (final JSONException e) { MPLog.e(LOGTAG, "Exception unsetting a property", e); } } @Override public void deleteGroup() { try { final JSONObject message = stdGroupMessage("$delete", JSONObject.NULL); recordGroupMessage(message); mGroups.remove(makeMapKey(mGroupKey, mGroupID)); } catch (final JSONException e) { MPLog.e(LOGTAG, "Exception deleting a group", e); } } private JSONObject stdGroupMessage(String actionType, Object properties) throws JSONException { final JSONObject dataObj = new JSONObject(); dataObj.put(actionType, properties); dataObj.put("$token", mToken); dataObj.put("$time", System.currentTimeMillis()); dataObj.put("$group_key", mGroupKey); dataObj.put("$group_id", mGroupID); dataObj.put("$mp_metadata", mSessionMetadata.getMetadataForPeople()); return dataObj; } }// GroupImpl private class SupportedUpdatesListener implements UpdatesListener, Runnable { @Override public void onNewResults() { mExecutor.execute(this); } @Override public void addOnMixpanelUpdatesReceivedListener(OnMixpanelUpdatesReceivedListener listener) { mListeners.add(listener); if (mDecideMessages.hasUpdatesAvailable()) { onNewResults(); } } @Override public void removeOnMixpanelUpdatesReceivedListener(OnMixpanelUpdatesReceivedListener listener) { mListeners.remove(listener); } @Override public void run() { // It's possible that by the time this has run the updates we detected are no longer // present, which is ok. for (final OnMixpanelUpdatesReceivedListener listener : mListeners) { listener.onMixpanelUpdatesReceived(); } mConnectIntegrations.setupIntegrations(mDecideMessages.getIntegrations()); } private final Set<OnMixpanelUpdatesReceivedListener> mListeners = Collections.newSetFromMap(new ConcurrentHashMap<OnMixpanelUpdatesReceivedListener, Boolean>()); private final Executor mExecutor = Executors.newSingleThreadExecutor(); } /* package */ class NoOpUpdatesFromMixpanel implements UpdatesFromMixpanel { public NoOpUpdatesFromMixpanel(Tweaks tweaks) { mTweaks = tweaks; } @Override public void startUpdates() { // No op } @Override public void storeVariants(JSONArray variants) { // No op } @Override public void applyPersistedUpdates() { // No op } @Override public void setEventBindings(JSONArray bindings) { // No op } @Override public void setVariants(JSONArray variants) { // No op } @Override public Tweaks getTweaks() { return mTweaks; } @Override public void addOnMixpanelTweaksUpdatedListener(OnMixpanelTweaksUpdatedListener listener) { // No op } @Override public void removeOnMixpanelTweaksUpdatedListener(OnMixpanelTweaksUpdatedListener listener) { // No op } private final Tweaks mTweaks; } //////////////////////////////////////////////////// protected void flushNoDecideCheck() { if (hasOptedOutTracking()) return; mMessages.postToServer(new AnalyticsMessages.FlushDescription(mToken, false)); } protected void track(String eventName, JSONObject properties, boolean isAutomaticEvent) { if (hasOptedOutTracking() || (isAutomaticEvent && !mDecideMessages.shouldTrackAutomaticEvent())) { return; } final Long eventBegin; synchronized (mEventTimings) { eventBegin = mEventTimings.get(eventName); mEventTimings.remove(eventName); mPersistentIdentity.removeTimeEvent(eventName); } try { final JSONObject messageProps = new JSONObject(); final Map<String, String> referrerProperties = mPersistentIdentity.getReferrerProperties(); for (final Map.Entry<String, String> entry : referrerProperties.entrySet()) { final String key = entry.getKey(); final String value = entry.getValue(); messageProps.put(key, value); } mPersistentIdentity.addSuperPropertiesToObject(messageProps); // Don't allow super properties or referral properties to override these fields, // but DO allow the caller to override them in their given properties. final double timeSecondsDouble = (System.currentTimeMillis()) / 1000.0; final long timeSeconds = (long) timeSecondsDouble; final String distinctId = getDistinctId(); final String anonymousId = getAnonymousId(); final String userId = getUserId(); messageProps.put("time", timeSeconds); messageProps.put("distinct_id", distinctId); messageProps.put("$had_persisted_distinct_id", mPersistentIdentity.getHadPersistedDistinctId()); if(anonymousId != null) { messageProps.put("$device_id", anonymousId); } if(userId != null) { messageProps.put("$user_id", userId); } if (null != eventBegin) { final double eventBeginDouble = ((double) eventBegin) / 1000.0; final double secondsElapsed = timeSecondsDouble - eventBeginDouble; messageProps.put("$duration", secondsElapsed); } if (null != properties) { final Iterator<?> propIter = properties.keys(); while (propIter.hasNext()) { final String key = (String) propIter.next(); if (!properties.isNull(key)) { messageProps.put(key, properties.get(key)); } } } final AnalyticsMessages.EventDescription eventDescription = new AnalyticsMessages.EventDescription(eventName, messageProps, mToken, isAutomaticEvent, mSessionMetadata.getMetadataForEvent()); mMessages.eventsMessage(eventDescription); if (mMixpanelActivityLifecycleCallbacks.getCurrentActivity() != null) { getPeople().showGivenNotification(mDecideMessages.getNotification(eventDescription, mConfig.getTestMode()), mMixpanelActivityLifecycleCallbacks.getCurrentActivity()); } if (null != mTrackingDebug) { mTrackingDebug.reportTrack(eventName); } } catch (final JSONException e) { MPLog.e(LOGTAG, "Exception tracking event " + eventName, e); } } private void recordPeopleMessage(JSONObject message) { if (hasOptedOutTracking()) return; mMessages.peopleMessage(new AnalyticsMessages.PeopleDescription(message, mToken)); } private void recordGroupMessage(JSONObject message) { if (hasOptedOutTracking()) return; if (message.has("$group_key") && message.has("$group_id")) { mMessages.groupMessage(new AnalyticsMessages.GroupDescription(message, mToken)); } else { MPLog.e(LOGTAG, "Attempt to update group without key and value--this should not happen."); } } private void pushWaitingPeopleRecord(String distinctId) { mMessages.pushAnonymousPeopleMessage(new AnalyticsMessages.PushAnonymousPeopleDescription(distinctId, mToken)); } private static void registerAppLinksListeners(Context context, final MixpanelAPI mixpanel) { // Register a BroadcastReceiver to receive com.parse.bolts.measurement_event and track a call to mixpanel try { final Class<?> clazz = Class.forName("android.support.v4.content.LocalBroadcastManager"); final Method methodGetInstance = clazz.getMethod("getInstance", Context.class); final Method methodRegisterReceiver = clazz.getMethod("registerReceiver", BroadcastReceiver.class, IntentFilter.class); final Object localBroadcastManager = methodGetInstance.invoke(null, context); methodRegisterReceiver.invoke(localBroadcastManager, new BroadcastReceiver() { @Override public void onReceive(Context context, Intent intent) { final JSONObject properties = new JSONObject(); final Bundle args = intent.getBundleExtra("event_args"); if (args != null) { for (final String key : args.keySet()) { try { properties.put(key, args.get(key)); } catch (final JSONException e) { MPLog.e(APP_LINKS_LOGTAG, "failed to add key \"" + key + "\" to properties for tracking bolts event", e); } } } mixpanel.track("$" + intent.getStringExtra("event_name"), properties); } }, new IntentFilter("com.parse.bolts.measurement_event")); } catch (final InvocationTargetException e) { MPLog.d(APP_LINKS_LOGTAG, "Failed to invoke LocalBroadcastManager.registerReceiver() -- App Links tracking will not be enabled due to this exception", e); } catch (final ClassNotFoundException e) { MPLog.d(APP_LINKS_LOGTAG, "To enable App Links tracking android.support.v4 must be installed: " + e.getMessage()); } catch (final NoSuchMethodException e) { MPLog.d(APP_LINKS_LOGTAG, "To enable App Links tracking android.support.v4 must be installed: " + e.getMessage()); } catch (final IllegalAccessException e) { MPLog.d(APP_LINKS_LOGTAG, "App Links tracking will not be enabled due to this exception: " + e.getMessage()); } } private static void checkIntentForInboundAppLink(Context context) { // call the Bolts getTargetUrlFromInboundIntent method simply for a side effect // if the intent is the result of an App Link, it'll trigger al_nav_in // https://github.com/BoltsFramework/Bolts-Android/blob/1.1.2/Bolts/src/bolts/AppLinks.java#L86 if (context instanceof Activity) { try { final Class<?> clazz = Class.forName("bolts.AppLinks"); final Intent intent = ((Activity) context).getIntent(); final Method getTargetUrlFromInboundIntent = clazz.getMethod("getTargetUrlFromInboundIntent", Context.class, Intent.class); getTargetUrlFromInboundIntent.invoke(null, context, intent); } catch (final InvocationTargetException e) { MPLog.d(APP_LINKS_LOGTAG, "Failed to invoke bolts.AppLinks.getTargetUrlFromInboundIntent() -- Unable to detect inbound App Links", e); } catch (final ClassNotFoundException e) { MPLog.d(APP_LINKS_LOGTAG, "Please install the Bolts library >= 1.1.2 to track App Links: " + e.getMessage()); } catch (final NoSuchMethodException e) { MPLog.d(APP_LINKS_LOGTAG, "Please install the Bolts library >= 1.1.2 to track App Links: " + e.getMessage()); } catch (final IllegalAccessException e) { MPLog.d(APP_LINKS_LOGTAG, "Unable to detect inbound App Links: " + e.getMessage()); } } else { MPLog.d(APP_LINKS_LOGTAG, "Context is not an instance of Activity. To detect inbound App Links, pass an instance of an Activity to getInstance."); } } private final Context mContext; private final AnalyticsMessages mMessages; private final MPConfig mConfig; private final String mToken; private final PeopleImpl mPeople; private final Map<String, GroupImpl> mGroups; private final UpdatesFromMixpanel mUpdatesFromMixpanel; private final PersistentIdentity mPersistentIdentity; private final UpdatesListener mUpdatesListener; private final TrackingDebug mTrackingDebug; private final ConnectIntegrations mConnectIntegrations; private final DecideMessages mDecideMessages; private final Map<String, String> mDeviceInfo; private final Map<String, Long> mEventTimings; private MixpanelActivityLifecycleCallbacks mMixpanelActivityLifecycleCallbacks; private final SessionMetadata mSessionMetadata; // Maps each token to a singleton MixpanelAPI instance private static final Map<String, Map<Context, MixpanelAPI>> sInstanceMap = new HashMap<String, Map<Context, MixpanelAPI>>(); private static final SharedPreferencesLoader sPrefsLoader = new SharedPreferencesLoader(); private static final Tweaks sSharedTweaks = new Tweaks(); private static Future<SharedPreferences> sReferrerPrefs; private static final String LOGTAG = "MixpanelAPI.API"; private static final String APP_LINKS_LOGTAG = "MixpanelAPI.AL"; private static final String ENGAGE_DATE_FORMAT_STRING = "yyyy-MM-dd'T'HH:mm:ss"; }
Add optOutTrackingDefault as only extra param in getInstance()
src/main/java/com/mixpanel/android/mpmetrics/MixpanelAPI.java
Add optOutTrackingDefault as only extra param in getInstance()
<ide><path>rc/main/java/com/mixpanel/android/mpmetrics/MixpanelAPI.java <ide> * @param context The application context you are tracking <ide> * @param token Your Mixpanel project token. You can get your project token on the Mixpanel web site, <ide> * in the settings dialog. <add> * @param optOutTrackingDefault Whether or not Mixpanel can start tracking by default. See <add> * {@link #optOutTracking()}. <add> * @return an instance of MixpanelAPI associated with your project <add> */ <add> public static MixpanelAPI getInstance(Context context, String token, boolean optOutTrackingDefault) { <add> return getInstance(context, token, optOutTrackingDefault, null); <add> } <add> <add> /** <add> * Get the instance of MixpanelAPI associated with your Mixpanel project token. <add> * <add> * <p>Use getInstance to get a reference to a shared <add> * instance of MixpanelAPI you can use to send events <add> * and People Analytics updates to Mixpanel.</p> <add> * <p>getInstance is thread safe, but the returned instance is not, <add> * and may be shared with other callers of getInstance. <add> * The best practice is to call getInstance, and use the returned MixpanelAPI, <add> * object from a single thread (probably the main UI thread of your application).</p> <add> * <p>If you do choose to track events from multiple threads in your application, <add> * you should synchronize your calls on the instance itself, like so:</p> <add> * <pre> <add> * {@code <add> * MixpanelAPI instance = MixpanelAPI.getInstance(context, token); <add> * synchronized(instance) { // Only necessary if the instance will be used in multiple threads. <add> * instance.track(...) <add> * } <add> * } <add> * </pre> <add> * <add> * @param context The application context you are tracking <add> * @param token Your Mixpanel project token. You can get your project token on the Mixpanel web site, <add> * in the settings dialog. <ide> * @param superProperties A JSONObject containing super properties to register. <ide> * @return an instance of MixpanelAPI associated with your project <ide> */
JavaScript
apache-2.0
8e1f18981b13d813af0b702e79dde688b3b7973e
0
phakhruddin/krani
var args = arguments[0] || {}; exports.openMainWindow = function(_tab) { _tab.open($.enterjobdetail_window); Ti.API.info("This is child widow checking _tab on : " +JSON.stringify(_tab)); Ti.API.info(" input details after tab enterjobdetail : "+JSON.stringify(args)); // $.labor_table.search = $.search_history; }; var GoogleAuth = require('googleAuth'); var googleAuthSheet = new GoogleAuth({ clientId : '306793301753-8ej6duert04ksb3abjutpie916l8hcc7.apps.googleusercontent.com', clientSecret : 'fjrsVudiK3ClrOKWxO5QvXYL', propertyName : 'googleToken', scope : scope, quiet: false }); Alloy.Collections.joblog.fetch(); function transformFunction(model) { var currentaddr; var transform = model.toJSON(); console.log("enterjobdetail.js::transform is ::" +JSON.stringify(transform)); transform.title = transform.col1+":"+transform.col2+":"+transform.col5+":"+transform.col6+":"+transform.col7+":" +transform.col8+":"+transform.col9+":"+transform.col10+":"+transform.col11+":"+transform.col12+":"+transform.col13 +":"+transform.col14+":"+transform.col15+":"+transform.col16; transform.date = "Date: "+transform.col1; transform.notes = "Notes: "+transform.col2; transform.img = (transform.col4)?transform.col4:"none"; lat1=transform.col8; lon1=transform.col9; transform.address = "Lat: "+transform.col8+" , Lon:"+transform.col9; var newRow = Ti.UI.createTableViewRow({}); var newImageView = Ti.UI.createImageView({ image : transform.img, height: 200, width: 200 }); var imageRow = newRow.add(newImageView); //$.labor_table.setData($.joblog_row); return transform; } var joblog = Alloy.Collections.instance('joblog'); var content = joblog.toJSON(); console.log("enterjobdetail.js::JSON stringify joblog: "+JSON.stringify(content)); function jobDetailAddRow (date,notesbody,imageurl) { var jobrow = Ti.UI.createTableViewRow ({ backgroundColor: "#ECE6E6", opacity:"0", color:"transparent", width: Ti.UI.FILL, height: "150" }); var datelabel = Ti.UI.createLabel ({ color : "orange", left : "20", textAlign : "Ti.UI.TEXT_ALIGNMENT_LEFT", top : "10", text : date }); var noteslabel = Ti.UI.createLabel ({ color : "#888", left : "20", textAlign : "Ti.UI.TEXT_ALIGNMENT_LEFT", font: { fontSize: "12" }, text : notesbody }); var imagelabel = Ti.UI.createImageView ({ image : imageurl, height : "200", width : "200" }); var innerview = Ti.UI.createView({ width:"90%", height:"80%", backgroundColor:"white", borderRadius:"10", borderWidth:"0.1", borderColor:"white" }); innerview.add(datelabel); if ( notesbody != "none" ) { innerview.add(noteslabel); noteslabel.top = 50; } else { //imagelabel.height = 200; imagelabel.height = Ti.UI.SIZE; imagelabel.width = 200; }; if (imageurl != "none") { innerview.add(imagelabel); var jobrow = Ti.UI.createTableViewRow ({ backgroundColor: "#ECE6E6", opacity:"0", color:"transparent", width: Ti.UI.FILL, height: Ti.UI.SIZE }); }; if ( notesbody != "none" && imageurl != "none") { imagelabel.top = 50; noteslabel.top = 220; }; jobrow.add(innerview); var jobtable = Ti.UI.createTableView({ backgroundColor: "white", separatorStyle :"Titanium.UI.iPhone.TableViewSeparatorStyle.NONE" }); jobtable.add(jobrow); $.labor_table.appendRow(jobrow); }; var sid = args.sid; console.log("enterjobdetail.js::sid right before key in contents value: "+sid); console.log("enterjobdetail.js::content.length: "+content.length); for (i=0;i<content.length;i++){ if ( content[i].col10 == sid ){ var notesbody = content[i].col2; var imageurl = content[i].col4; var date = content[i].col1; jobDetailAddRow (date,notesbody,imageurl); } } function closeWin(e) { console.log("enterjobdetail.js::e is: "+JSON.stringify(e)); } function UploadPhotoToServer(imagemedia){ console.log("enterjobdetail.js::UploadPhotoToServer:: Upload photo to the server."); var imageView = Titanium.UI.createImageView({ image:imagemedia, width:200, height:200 }); var image = imageView.toImage(); console.log("enterjobdetail.js::beginning to upload to the cloud."); var imagedatabase64 = Ti.Utils.base64encode(image); var date = new Date(); var imagefilename = filename+"_"+date.toString().replace(/ /g,'_');; // uploadPictoGoogle(image,"uploadphoto3.jpeg"); uploadPictoGoogle(image,imagefilename); //console.log("enterjobdetail.js::UploadPhotoToServer::image sid is : " +imagesid); } function uploadFile(e){ console.log("enterjobdetail.js::JSON stringify e uploadFile : " +JSON.stringify(e)); Titanium.Media.openPhotoGallery({ success:function(event) { Ti.API.debug('Our type was: '+event.mediaType); if(event.mediaType == Ti.Media.MEDIA_TYPE_PHOTO) { UploadPhotoToServer(event.media); } }, cancel:function() { }, error:function(err) { Ti.API.error(err); }, mediaTypes:[Ti.Media.MEDIA_TYPE_PHOTO] }); } var win = Titanium.UI.createWindow({ title:"Media", backgroundColor: "black" }); function takePic(e){ console.log("enterjobdetail.js::JSON stringify e takePic:" +JSON.stringify(e)); Titanium.Media.showCamera({ success:function(e){ if(e.mediaType === Titanium.Media.MEDIA_TYPE_PHOTO){ /* var ImageView = Titanium.UI.createImageView({ image:e.media, width:288, height:215, top:12, zIndex:1 }); win.add(ImageView);*/ var imageView = Titanium.UI.createImageView({ image:e.media, width:200, height:200 }); var image = imageView.toImage(); console.log("enterjobdetail.js::beginning to upload to the cloud."); //var imagedatabase64 = Ti.Utils.base64encode(image); uploadPictoGoogle(image,"testimage1.jpg"); } else if (e.mediaType === Titanium.Media.MEDIA_TYPE_VIDEO){ var w = Titanium.UI.createWindow({ title:"Job Video", backgroundColor: "black" }); var videoPlayer = Titanium.Media.createVideoPlayer({ media: e.media }); w.add(videoPlayer); videoPlayer.addEventListener("complete",function(e){ w.remove(videoPlayer); videoPlayer = null ; w.close(); }); } }, error:function(e){ alert("unable to load the camera"); }, cancel:function(e){ alert("unable to load the camera"); }, allowEditing:true, saveToPhotoGallery:true, mediaTypes:[Titanium.Media.MEDIA_TYPE_PHOTO,Titanium.Media.MEDIA_TYPE_VIDEO], videoQuality:Titanium.Media.QUALITY_HIGH }); //win.open(); } var win = Ti.UI.createWindow({ backgroundColor: 'white' }); var send = Titanium.UI.createButton({ title : 'Send', style : Titanium.UI.iPhone.SystemButtonStyle.DONE, }); var camera = Titanium.UI.createButton({ systemButton : Titanium.UI.iPhone.SystemButton.CAMERA, }); var cancel = Titanium.UI.createButton({ systemButton : Titanium.UI.iPhone.SystemButton.CANCEL }); var flexSpace = Titanium.UI.createButton({ systemButton : Titanium.UI.iPhone.SystemButton.FLEXIBLE_SPACE }); var textfield = Titanium.UI.createTextField({ borderStyle : Titanium.UI.INPUT_BORDERSTYLE_BEZEL, hintText : 'Focus to see keyboard with toolbar', keyboardToolbar : [cancel, flexSpace, camera, flexSpace, send], keyboardToolbarColor : '#999', backgroundColor : "white", keyboardToolbarHeight : 40, top : 10, width : Ti.UI.SIZE, height : Ti.UI.SIZE }); var sid = args.sid; console.log("enterjobdetail.js::before notes_textarea hintText: JSON.stringify(args): "+JSON.stringify(args)+" sid:"+sid); $.notes_textarea._hintText = sid; $.notes_textarea.addEventListener("blur",function(e){ console.log("enterjobdetail.js::JSON.stringify(e) :" +JSON.stringify(e)); e.source.keyboardToolbar.items = null; enterNotes(e); e.source.value = ""; //$.ktb_textarea.hide(); }); function enterNotes(e,imgurl) { console.log("enterjobdetail.js::JSON.stringify(e) enterNotes :" +JSON.stringify(e)); //$.enterjobdetail_window.show($.notes_textarea); //$.enterjobdetail_window.add(textfield); var date = new Date(); var notesbody = e.value; var sourcesid = e.source._hintText; var imageurl = imgurl?imgurl:"none"; var dataModel = Alloy.createModel("joblog",{ col1 : date || "none", col2 : notesbody || "none", col3 : imageurl, col4 : "none", col5:"none", col6:"none", col7:"none", col8:"none", col9:"none", col10: sourcesid, col11:"none", col12:"none", col13:"none", col14:"none", col15:"none", col16:"none" }); dataModel.save(); Alloy.Collections.joblog.fetch(); var joblog = Alloy.Collections.instance('joblog'); var content = joblog.toJSON(); console.log("enterjobdetail.js::JSON stringify joblog after write: "+JSON.stringify(content)); var thedate = date.toString().replace(".","").split(' ',4).toString().replace(/,/g,' ')+' '+Alloy.Globals.formatAMPM(date); //console.log("enterjobdetail.js::thedate is: " +thedate); jobDetailAddRow (thedate,notesbody,imageurl); //add to the local db submit(thedate,notesbody,imageurl); //submit to the cloud }; function submit(thedate,notesbody,imageurl) { var thenone = "none"; var sid = args.sid; var imageurl = imageurl.replace('&','&amp;'); //var imageurl = 'https://docs.google.com/uc?id=0B3XMbMJnSVEGS0lBXzVaLUFlZHM&amp;export=download'; var xmldatastring = ['<entry xmlns=\'http://www.w3.org/2005/Atom\' xmlns:gsx=\'http://schemas.google.com/spreadsheets/2006/extended\'>' +'<gsx:col1>'+thedate+'</gsx:col1><gsx:col2>'+notesbody+'</gsx:col2><gsx:col3>' +thenone+'</gsx:col3><gsx:col4>'+imageurl+'</gsx:col4><gsx:col5>' +thenone+'</gsx:col5><gsx:col6>'+thenone+'</gsx:col6><gsx:col7>'+thenone+'</gsx:col7><gsx:col8>'+thenone+'</gsx:col8><gsx:col9>'+thenone +'</gsx:col9><gsx:col10>'+sid+'</gsx:col10><gsx:col11>'+thenone+'</gsx:col11><gsx:col12>NA</gsx:col12><gsx:col13>NA</gsx:col13><gsx:col14>NA</gsx:col14><gsx:col15>NA</gsx:col15><gsx:col16>NA</gsx:col16></entry>'].join(''); Ti.API.info('xmldatastring to POST: '+xmldatastring); var xhr = Titanium.Network.createHTTPClient({ onload: function() { try { Ti.API.info(this.responseText); } catch(e){ Ti.API.info("enterjobdetail.js::submit::cathing e: "+JSON.stringify(e)); } }, onerror: function(e) { Ti.API.info("enterjobdetail.js::submit::error e: "+JSON.stringify(e)); alert("Unable to communicate to the cloud. Please try again"); } }); //var sid = Titanium.App.Properties.getString('joblog'); //var sid = Titanium.App.Properties.getString('sid'); //sid need to correct//sid need to correct xhr.open("POST", 'https://spreadsheets.google.com/feeds/list/'+sid+'/od6/private/full'); xhr.setRequestHeader("Content-type", "application/atom+xml"); xhr.setRequestHeader("Authorization", 'Bearer '+ googleAuthSheet.getAccessToken()); xhr.send(xmldatastring); Ti.API.info('done POSTed'); } var scope = ['https://spreadsheets.google.com/feeds', 'https://docs.google.com/feeds','https://www.googleapis.com/auth/calendar','https://www.googleapis.com/auth/calendar.readonly','https://www.googleapis.com/auth/drive']; scope.push ("https://www.googleapis.com/auth/drive.appdata"); scope.push ("https://www.googleapis.com/auth/drive.apps.readonly"); scope.push ("https://www.googleapis.com/auth/drive.file"); //scope.push ("https://www.googleapis.com/auth/plus.login"); //var jsonargs = JSON.stringify(args); console.log("enterjobdetail.js::jsonargs : "+JSON.stringify(args)); var projectid = args.title.title.split(':')[15]; var firstname = args.title.title.split(':')[1]; var lastname = args.title.title.split(':')[2]; var filename = 'project_'+projectid+'_'+firstname+'_'+lastname; Titanium.App.Properties.setString('filename',filename); console.log("enterjobdetail.js::value derived from args: projectid: "+projectid+" firstname: "+firstname+" lastname: "+lastname); //var filename = "project"+jsonargs.title.split(':')[15]; function getParentFolder(args) { var sid = Titanium.App.Properties.getString('joblog'); var xhr = Ti.Network.createHTTPClient({ onload: function(e) { try { var json = JSON.parse(this.responseText); Ti.API.info("response is: "+JSON.stringify(json)); var parentid = json.items[0].id; Titanium.App.Properties.setString('parentid',parentid); console.log("enterjobdetail.js::args inside getParentFolder: "+JSON.stringify(args)); //var filename = 'test03'; //createSpreadsheet(filename,parentid); } catch(e){ Ti.API.info("cathing e: "+JSON.stringify(e)); } return parentid; } }); xhr.onerror = function(e){ alert("Unable to connect to the cloud."); }; xhr.open("GET", 'https://www.googleapis.com/drive/v2/files/'+sid+'/parents'); xhr.setRequestHeader("Content-type", "application/json"); xhr.setRequestHeader("Authorization", 'Bearer '+ googleAuthSheet.getAccessToken()); xhr.send(); }; function createSpreadsheet(filename,parentid) { console.log("enterjobdetail.js::create ss with filename: "+filename+" and parentid: "+parentid); var jsonpost = '{' +'\"title\": \"'+filename+'\",' +'\"shared\": \"true\",' +'\"parents\": [' +'{' +'\"id\": \"0AHXMbMJnSVEGUk9PVA\"' +' }' +'],' +'\"mimeType\": \"application/vnd.google-apps.spreadsheet\"' +'}'; var xhr = Ti.Network.createHTTPClient({ onload: function(e) { try { Ti.API.info("response is: "+this.responseText); var json = JSON.parse(this.responseText); var sid = json.id; console.log("enterjobdetail.js::sid : "+sid); populatejoblogSIDtoDB(filename,sid); } catch(e){ Ti.API.info("cathing e: "+JSON.stringify(e)); } } }); xhr.onerror = function(e){ alert("Unable to connect to the cloud."); }; xhr.open("POST", 'https://www.googleapis.com/drive/v2/files'); xhr.setRequestHeader("Content-type", "application/json"); xhr.setRequestHeader("Authorization", 'Bearer '+ googleAuthSheet.getAccessToken()); console.log("enterjobdetail.js::json post: "+jsonpost); xhr.send(jsonpost); } var jsonlist = " "; function fileExist(){ var jsonlist = " "; var xhr = Ti.Network.createHTTPClient({ onload: function(e) { try { var jsonlist = JSON.parse(this.responseText); Ti.API.info("response of jsonlist is: "+JSON.stringify(jsonlist)); } catch(e){ Ti.API.info("cathing e: "+JSON.stringify(e)); } console.log("enterjobdetail.js::jsonlist.items.length: "+jsonlist.items.length); var filename = Titanium.App.Properties.getString('filename'); filelist = []; if (jsonlist.items.length == "0" ){ console.log("enterjobdetail.js::File DOES NOT EXIST"); var fileexist = "false"; createSpreadsheet(filename,parentid); // create file when does not exists } else { var fileexist = "true"; console.log("enterjobdetail.js::enterjobdetail.js::fileExist:: File exist. sid is: "+jsonlist.items[0].id+" Skipped."); populatejoblogSIDtoDB(filename,sid); }; } }); xhr.onerror = function(e){ alert("Unable to connect to the cloud."); }; //xhr.open("GET", 'https://www.googleapis.com/drive/v2/files'); var rawquerystring = '?q=title+%3D+\''+filename+'\'+and+mimeType+%3D+\'application%2Fvnd.google-apps.spreadsheet\'+and+trashed+%3D+false&fields=items(id%2CmimeType%2Clabels%2Ctitle)'; //xhr.open("GET", 'https://www.googleapis.com/drive/v2/files?q=title+%3D+\'project_1_Phakhruddin_Abdullah\'&fields=items(mimeType%2Clabels%2Ctitle)'); xhr.open("GET", 'https://www.googleapis.com/drive/v2/files'+rawquerystring); xhr.setRequestHeader("Content-type", "application/json"); xhr.setRequestHeader("Authorization", 'Bearer '+ googleAuthSheet.getAccessToken()); xhr.send(); } //fileExist(); var parentid = Titanium.App.Properties.getString('parentid'); //console.log("enterjobdetail.js::create spreadsheet with filename: "+filename+" and parentid: "+parentid); //createSpreadsheet(filename,parentid); var file = Ti.Filesystem.getFile( Ti.Filesystem.tempDirectory, "joblogsid.txt" ); var joblogsidfile = file.read().text; //var joblogsidfilejson = JSON.parse(joblogsidfile); console.log("enterjobdetail.js::joblogsidfile" +joblogsidfile); //console.log("enterjobdetail.js::JSON.stringify(joblogsidfilejson)" +joblogsidfilejson); function populatejoblogSIDtoDB(filename,sid) { var dataModel = Alloy.createModel("joblogsid",{ col1 : filename || "none", col2 : sid || "none", col3 : "none",col4:"none", col5:"none", col6:"none", col7:"none", col8:"none", col9:"none", col10:"none", col11:"none", col12:"none", col13:"none", col14:"none", col15:"none", col16:"none" }); dataModel.save(); var thejoblogsid = Alloy.Collections.instance('joblogsid'); thejoblogsid.fetch(); Ti.API.info(" enterjobdetail.js::populatejoblogSIDtoDB:: thejoblogsid : "+JSON.stringify(thejoblogsid)); } //Retrieve cloud data again var sid = args.sid; Ti.API.info("sid for joblog in enterjobdetail.js : "+sid); Alloy.Globals.getPrivateData(sid,"joblog"); function uploadPictoGoogle(image,filename){ console.log("enterjobdetail.js::uploadPictoGoogle::create ss with filename: "+filename); var base64Data = Ti.Utils.base64encode(image); var parts = []; var bound = 287032396531387; var meta = '\{' + '\"title\": \"'+filename+'\"' + '\}'; var parts = []; parts.push('--' + bound); parts.push('Content-Type: application/json'); parts.push(''); parts.push(meta); parts.push('--' + bound); parts.push('Content-Type: image/jpeg'); parts.push('Content-Transfer-Encoding: base64'); parts.push(''); parts.push(base64Data); parts.push('--' + bound + '--'); var url = "https://www.googleapis.com/upload/drive/v2/files?uploadType=multipart"; var xhr = Titanium.Network.createHTTPClient({ onload: function() { try { var json = JSON.parse(this.responseText); Ti.API.info("enterjobdetail.js::uploadPictoGoogle::response is: "+JSON.stringify(json)); var id = json.id; var webcontentlink = json.webContentLink; Ti.API.info("enterjobdetail.js::uploadPictoGoogle::id is: "+id+" webcontentlink: "+webcontentlink); shareAnyonePermission(id); var e = {"value":"none","source":{"_hintText":id}}; console.log("enterjobdetail.js::uploadPictoGoogle::entering urlimage with info below e: "+JSON.stringify(e)); enterNotes(e,webcontentlink); } catch(e){ Ti.API.info("enterjobdetail.js::uploadPictoGoogle::cathing e: "+JSON.stringify(e)); } return id; }, onerror: function(e) { Ti.API.info("enterjobdetail.js::uploadPictoGoogle::error e: "+JSON.stringify(e)); alert("unable to talk to the cloud, will try later"); } }); xhr.open("POST", url); xhr.setRequestHeader("Content-type", "multipart/mixed; boundary=" + bound); xhr.setRequestHeader("Authorization", 'Bearer '+googleAuthSheet.getAccessToken()); //xhr.setRequestHeader("Content-Length", "2000000"); xhr.send(parts.join("\r\n")); Ti.API.info('done POSTed'); //Ti.API.info("enterjobdetail.js::uploadPictoGoogle::sid outside is: "+id); } function shareAnyonePermission(sid){ console.log("enterjobdetail.js::shareAnyonePermission::sid: "+sid); var jsonpost = '{' +'\"role\": \"reader\",' +'\"type\": \"anyone\"' +'}'; var xhr = Ti.Network.createHTTPClient({ onload: function(e) { try { Ti.API.info("enterjobdetail.js::shareAnyonePermission::response is: "+this.responseText); } catch(e){ Ti.API.info("cathing e: "+JSON.stringify(e)); } } }); xhr.onerror = function(e){ alert("Unable to connect to the cloud."); }; xhr.open("POST", 'https://www.googleapis.com/drive/v2/files/'+sid+'/permissions'); xhr.setRequestHeader("Content-type", "application/json"); xhr.setRequestHeader("Authorization", 'Bearer '+ googleAuthSheet.getAccessToken()); console.log("enterjobdetail.js::shareAnyonePermission::json post: "+jsonpost); xhr.send(jsonpost); } /* $.jobdetailtf.addEventListener("focus", function(e){ console.log("enterjobdetail.js::JSON.stringify(e) :" +JSON.stringify(e)); });*/ /* function largeTF(e){ console.log("enterjobdetail.js::JSON.stringify(e) largeTF :" +JSON.stringify(e)); //$.itemjobdetail.add(textfield); } */
app/controllers/enterjobdetail.js
var args = arguments[0] || {}; exports.openMainWindow = function(_tab) { _tab.open($.enterjobdetail_window); Ti.API.info("This is child widow checking _tab on : " +JSON.stringify(_tab)); Ti.API.info(" input details after tab enterjobdetail : "+JSON.stringify(args)); // $.labor_table.search = $.search_history; }; var GoogleAuth = require('googleAuth'); var googleAuthSheet = new GoogleAuth({ clientId : '306793301753-8ej6duert04ksb3abjutpie916l8hcc7.apps.googleusercontent.com', clientSecret : 'fjrsVudiK3ClrOKWxO5QvXYL', propertyName : 'googleToken', scope : scope, quiet: false }); Alloy.Collections.joblog.fetch(); function transformFunction(model) { var currentaddr; var transform = model.toJSON(); console.log("enterjobdetail.js::transform is ::" +JSON.stringify(transform)); transform.title = transform.col1+":"+transform.col2+":"+transform.col5+":"+transform.col6+":"+transform.col7+":" +transform.col8+":"+transform.col9+":"+transform.col10+":"+transform.col11+":"+transform.col12+":"+transform.col13 +":"+transform.col14+":"+transform.col15+":"+transform.col16; transform.date = "Date: "+transform.col1; transform.notes = "Notes: "+transform.col2; transform.img = (transform.col4)?transform.col4:"none"; lat1=transform.col8; lon1=transform.col9; transform.address = "Lat: "+transform.col8+" , Lon:"+transform.col9; var newRow = Ti.UI.createTableViewRow({}); var newImageView = Ti.UI.createImageView({ image : transform.img, height: 200, width: 200 }); var imageRow = newRow.add(newImageView); //$.labor_table.setData($.joblog_row); return transform; } var joblog = Alloy.Collections.instance('joblog'); var content = joblog.toJSON(); console.log("enterjobdetail.js::JSON stringify joblog: "+JSON.stringify(content)); function jobDetailAddRow (date,notesbody,imageurl) { var datelabel = Ti.UI.createLabel ({ color : "orange", left : "20", textAlign : "Ti.UI.TEXT_ALIGNMENT_LEFT", top : "10", text : date }); var noteslabel = Ti.UI.createLabel ({ color : "#888", left : "20", textAlign : "Ti.UI.TEXT_ALIGNMENT_LEFT", font: { fontSize: "12" }, text : notesbody }); var imagelabel = Ti.UI.createImageView ({ image : imageurl, height : "200", width : "200" }); var innerview = Ti.UI.createView({ width:"90%", height:"80%", backgroundColor:"white", borderRadius:"10", borderWidth:"0.1", borderColor:"white" }); innerview.add(datelabel); if ( notesbody != "none" ) { innerview.add(noteslabel); noteslabel.top = 50; } else { imagelabel.height = 200; imagelabel.width = 200; }; if (imageurl != "none") {innerview.add(imagelabel);}; if ( notesbody != "none" && imageurl != "none") { imagelabel.top = 50; noteslabel.top = 220; }; var jobrow = Ti.UI.createTableViewRow ({ backgroundColor: "#ECE6E6", opacity:"0", color:"transparent", width: Ti.UI.FILL, height: "200" ///height: Ti.UI.SIZE //title:"{title}" }); jobrow.add(innerview); var jobtable = Ti.UI.createTableView({ backgroundColor: "white", separatorStyle :"Titanium.UI.iPhone.TableViewSeparatorStyle.NONE" }); jobtable.add(jobrow); $.labor_table.appendRow(jobrow); }; var sid = args.sid; console.log("enterjobdetail.js::sid right before key in contents value: "+sid); console.log("enterjobdetail.js::content.length: "+content.length); for (i=0;i<content.length;i++){ if ( content[i].col10 == sid ){ var notesbody = content[i].col2; var imageurl = content[i].col4; var date = content[i].col1; jobDetailAddRow (date,notesbody,imageurl); } } function closeWin(e) { console.log("enterjobdetail.js::e is: "+JSON.stringify(e)); } function UploadPhotoToServer(imagemedia){ console.log("enterjobdetail.js::UploadPhotoToServer:: Upload photo to the server."); var imageView = Titanium.UI.createImageView({ image:imagemedia, width:200, height:200 }); var image = imageView.toImage(); console.log("enterjobdetail.js::beginning to upload to the cloud."); var imagedatabase64 = Ti.Utils.base64encode(image); var date = new Date(); var imagefilename = filename+"_"+date.toString().replace(/ /g,'_');; // uploadPictoGoogle(image,"uploadphoto3.jpeg"); uploadPictoGoogle(image,imagefilename); //console.log("enterjobdetail.js::UploadPhotoToServer::image sid is : " +imagesid); } function uploadFile(e){ console.log("enterjobdetail.js::JSON stringify e uploadFile : " +JSON.stringify(e)); Titanium.Media.openPhotoGallery({ success:function(event) { Ti.API.debug('Our type was: '+event.mediaType); if(event.mediaType == Ti.Media.MEDIA_TYPE_PHOTO) { UploadPhotoToServer(event.media); } }, cancel:function() { }, error:function(err) { Ti.API.error(err); }, mediaTypes:[Ti.Media.MEDIA_TYPE_PHOTO] }); } var win = Titanium.UI.createWindow({ title:"Media", backgroundColor: "black" }); function takePic(e){ console.log("enterjobdetail.js::JSON stringify e takePic:" +JSON.stringify(e)); Titanium.Media.showCamera({ success:function(e){ if(e.mediaType === Titanium.Media.MEDIA_TYPE_PHOTO){ /* var ImageView = Titanium.UI.createImageView({ image:e.media, width:288, height:215, top:12, zIndex:1 }); win.add(ImageView);*/ var imageView = Titanium.UI.createImageView({ image:e.media, width:200, height:200 }); var image = imageView.toImage(); console.log("enterjobdetail.js::beginning to upload to the cloud."); //var imagedatabase64 = Ti.Utils.base64encode(image); uploadPictoGoogle(image,"testimage1.jpg"); } else if (e.mediaType === Titanium.Media.MEDIA_TYPE_VIDEO){ var w = Titanium.UI.createWindow({ title:"Job Video", backgroundColor: "black" }); var videoPlayer = Titanium.Media.createVideoPlayer({ media: e.media }); w.add(videoPlayer); videoPlayer.addEventListener("complete",function(e){ w.remove(videoPlayer); videoPlayer = null ; w.close(); }); } }, error:function(e){ alert("unable to load the camera"); }, cancel:function(e){ alert("unable to load the camera"); }, allowEditing:true, saveToPhotoGallery:true, mediaTypes:[Titanium.Media.MEDIA_TYPE_PHOTO,Titanium.Media.MEDIA_TYPE_VIDEO], videoQuality:Titanium.Media.QUALITY_HIGH }); //win.open(); } var win = Ti.UI.createWindow({ backgroundColor: 'white' }); var send = Titanium.UI.createButton({ title : 'Send', style : Titanium.UI.iPhone.SystemButtonStyle.DONE, }); var camera = Titanium.UI.createButton({ systemButton : Titanium.UI.iPhone.SystemButton.CAMERA, }); var cancel = Titanium.UI.createButton({ systemButton : Titanium.UI.iPhone.SystemButton.CANCEL }); var flexSpace = Titanium.UI.createButton({ systemButton : Titanium.UI.iPhone.SystemButton.FLEXIBLE_SPACE }); var textfield = Titanium.UI.createTextField({ borderStyle : Titanium.UI.INPUT_BORDERSTYLE_BEZEL, hintText : 'Focus to see keyboard with toolbar', keyboardToolbar : [cancel, flexSpace, camera, flexSpace, send], keyboardToolbarColor : '#999', backgroundColor : "white", keyboardToolbarHeight : 40, top : 10, width : Ti.UI.SIZE, height : Ti.UI.SIZE }); var sid = args.sid; console.log("enterjobdetail.js::before notes_textarea hintText: JSON.stringify(args): "+JSON.stringify(args)+" sid:"+sid); $.notes_textarea._hintText = sid; $.notes_textarea.addEventListener("blur",function(e){ console.log("enterjobdetail.js::JSON.stringify(e) :" +JSON.stringify(e)); e.source.keyboardToolbar.items = null; enterNotes(e); e.source.value = ""; //$.ktb_textarea.hide(); }); function enterNotes(e,imgurl) { console.log("enterjobdetail.js::JSON.stringify(e) enterNotes :" +JSON.stringify(e)); //$.enterjobdetail_window.show($.notes_textarea); //$.enterjobdetail_window.add(textfield); var date = new Date(); var notesbody = e.value; var sourcesid = e.source._hintText; var imageurl = imgurl?imgurl:"none"; var dataModel = Alloy.createModel("joblog",{ col1 : date || "none", col2 : notesbody || "none", col3 : imageurl, col4 : "none", col5:"none", col6:"none", col7:"none", col8:"none", col9:"none", col10: sourcesid, col11:"none", col12:"none", col13:"none", col14:"none", col15:"none", col16:"none" }); dataModel.save(); Alloy.Collections.joblog.fetch(); var joblog = Alloy.Collections.instance('joblog'); var content = joblog.toJSON(); console.log("enterjobdetail.js::JSON stringify joblog after write: "+JSON.stringify(content)); var thedate = date.toString().replace(".","").split(' ',4).toString().replace(/,/g,' ')+' '+Alloy.Globals.formatAMPM(date); //console.log("enterjobdetail.js::thedate is: " +thedate); jobDetailAddRow (thedate,notesbody,imageurl); //add to the local db submit(thedate,notesbody,imageurl); //submit to the cloud }; function submit(thedate,notesbody,imageurl) { var thenone = "none"; var sid = args.sid; var imageurl = imageurl.replace('&','&amp;'); //var imageurl = 'https://docs.google.com/uc?id=0B3XMbMJnSVEGS0lBXzVaLUFlZHM&amp;export=download'; var xmldatastring = ['<entry xmlns=\'http://www.w3.org/2005/Atom\' xmlns:gsx=\'http://schemas.google.com/spreadsheets/2006/extended\'>' +'<gsx:col1>'+thedate+'</gsx:col1><gsx:col2>'+notesbody+'</gsx:col2><gsx:col3>' +thenone+'</gsx:col3><gsx:col4>'+imageurl+'</gsx:col4><gsx:col5>' +thenone+'</gsx:col5><gsx:col6>'+thenone+'</gsx:col6><gsx:col7>'+thenone+'</gsx:col7><gsx:col8>'+thenone+'</gsx:col8><gsx:col9>'+thenone +'</gsx:col9><gsx:col10>'+sid+'</gsx:col10><gsx:col11>'+thenone+'</gsx:col11><gsx:col12>NA</gsx:col12><gsx:col13>NA</gsx:col13><gsx:col14>NA</gsx:col14><gsx:col15>NA</gsx:col15><gsx:col16>NA</gsx:col16></entry>'].join(''); Ti.API.info('xmldatastring to POST: '+xmldatastring); var xhr = Titanium.Network.createHTTPClient({ onload: function() { try { Ti.API.info(this.responseText); } catch(e){ Ti.API.info("enterjobdetail.js::submit::cathing e: "+JSON.stringify(e)); } }, onerror: function(e) { Ti.API.info("enterjobdetail.js::submit::error e: "+JSON.stringify(e)); alert("Unable to communicate to the cloud. Please try again"); } }); //var sid = Titanium.App.Properties.getString('joblog'); //var sid = Titanium.App.Properties.getString('sid'); //sid need to correct//sid need to correct xhr.open("POST", 'https://spreadsheets.google.com/feeds/list/'+sid+'/od6/private/full'); xhr.setRequestHeader("Content-type", "application/atom+xml"); xhr.setRequestHeader("Authorization", 'Bearer '+ googleAuthSheet.getAccessToken()); xhr.send(xmldatastring); Ti.API.info('done POSTed'); } var scope = ['https://spreadsheets.google.com/feeds', 'https://docs.google.com/feeds','https://www.googleapis.com/auth/calendar','https://www.googleapis.com/auth/calendar.readonly','https://www.googleapis.com/auth/drive']; scope.push ("https://www.googleapis.com/auth/drive.appdata"); scope.push ("https://www.googleapis.com/auth/drive.apps.readonly"); scope.push ("https://www.googleapis.com/auth/drive.file"); //scope.push ("https://www.googleapis.com/auth/plus.login"); //var jsonargs = JSON.stringify(args); console.log("enterjobdetail.js::jsonargs : "+JSON.stringify(args)); var projectid = args.title.title.split(':')[15]; var firstname = args.title.title.split(':')[1]; var lastname = args.title.title.split(':')[2]; var filename = 'project_'+projectid+'_'+firstname+'_'+lastname; Titanium.App.Properties.setString('filename',filename); console.log("enterjobdetail.js::value derived from args: projectid: "+projectid+" firstname: "+firstname+" lastname: "+lastname); //var filename = "project"+jsonargs.title.split(':')[15]; function getParentFolder(args) { var sid = Titanium.App.Properties.getString('joblog'); var xhr = Ti.Network.createHTTPClient({ onload: function(e) { try { var json = JSON.parse(this.responseText); Ti.API.info("response is: "+JSON.stringify(json)); var parentid = json.items[0].id; Titanium.App.Properties.setString('parentid',parentid); console.log("enterjobdetail.js::args inside getParentFolder: "+JSON.stringify(args)); //var filename = 'test03'; //createSpreadsheet(filename,parentid); } catch(e){ Ti.API.info("cathing e: "+JSON.stringify(e)); } return parentid; } }); xhr.onerror = function(e){ alert("Unable to connect to the cloud."); }; xhr.open("GET", 'https://www.googleapis.com/drive/v2/files/'+sid+'/parents'); xhr.setRequestHeader("Content-type", "application/json"); xhr.setRequestHeader("Authorization", 'Bearer '+ googleAuthSheet.getAccessToken()); xhr.send(); }; function createSpreadsheet(filename,parentid) { console.log("enterjobdetail.js::create ss with filename: "+filename+" and parentid: "+parentid); var jsonpost = '{' +'\"title\": \"'+filename+'\",' +'\"shared\": \"true\",' +'\"parents\": [' +'{' +'\"id\": \"0AHXMbMJnSVEGUk9PVA\"' +' }' +'],' +'\"mimeType\": \"application/vnd.google-apps.spreadsheet\"' +'}'; var xhr = Ti.Network.createHTTPClient({ onload: function(e) { try { Ti.API.info("response is: "+this.responseText); var json = JSON.parse(this.responseText); var sid = json.id; console.log("enterjobdetail.js::sid : "+sid); populatejoblogSIDtoDB(filename,sid); } catch(e){ Ti.API.info("cathing e: "+JSON.stringify(e)); } } }); xhr.onerror = function(e){ alert("Unable to connect to the cloud."); }; xhr.open("POST", 'https://www.googleapis.com/drive/v2/files'); xhr.setRequestHeader("Content-type", "application/json"); xhr.setRequestHeader("Authorization", 'Bearer '+ googleAuthSheet.getAccessToken()); console.log("enterjobdetail.js::json post: "+jsonpost); xhr.send(jsonpost); } var jsonlist = " "; function fileExist(){ var jsonlist = " "; var xhr = Ti.Network.createHTTPClient({ onload: function(e) { try { var jsonlist = JSON.parse(this.responseText); Ti.API.info("response of jsonlist is: "+JSON.stringify(jsonlist)); } catch(e){ Ti.API.info("cathing e: "+JSON.stringify(e)); } console.log("enterjobdetail.js::jsonlist.items.length: "+jsonlist.items.length); var filename = Titanium.App.Properties.getString('filename'); filelist = []; if (jsonlist.items.length == "0" ){ console.log("enterjobdetail.js::File DOES NOT EXIST"); var fileexist = "false"; createSpreadsheet(filename,parentid); // create file when does not exists } else { var fileexist = "true"; console.log("enterjobdetail.js::enterjobdetail.js::fileExist:: File exist. sid is: "+jsonlist.items[0].id+" Skipped."); populatejoblogSIDtoDB(filename,sid); }; } }); xhr.onerror = function(e){ alert("Unable to connect to the cloud."); }; //xhr.open("GET", 'https://www.googleapis.com/drive/v2/files'); var rawquerystring = '?q=title+%3D+\''+filename+'\'+and+mimeType+%3D+\'application%2Fvnd.google-apps.spreadsheet\'+and+trashed+%3D+false&fields=items(id%2CmimeType%2Clabels%2Ctitle)'; //xhr.open("GET", 'https://www.googleapis.com/drive/v2/files?q=title+%3D+\'project_1_Phakhruddin_Abdullah\'&fields=items(mimeType%2Clabels%2Ctitle)'); xhr.open("GET", 'https://www.googleapis.com/drive/v2/files'+rawquerystring); xhr.setRequestHeader("Content-type", "application/json"); xhr.setRequestHeader("Authorization", 'Bearer '+ googleAuthSheet.getAccessToken()); xhr.send(); } //fileExist(); var parentid = Titanium.App.Properties.getString('parentid'); //console.log("enterjobdetail.js::create spreadsheet with filename: "+filename+" and parentid: "+parentid); //createSpreadsheet(filename,parentid); var file = Ti.Filesystem.getFile( Ti.Filesystem.tempDirectory, "joblogsid.txt" ); var joblogsidfile = file.read().text; //var joblogsidfilejson = JSON.parse(joblogsidfile); console.log("enterjobdetail.js::joblogsidfile" +joblogsidfile); //console.log("enterjobdetail.js::JSON.stringify(joblogsidfilejson)" +joblogsidfilejson); function populatejoblogSIDtoDB(filename,sid) { var dataModel = Alloy.createModel("joblogsid",{ col1 : filename || "none", col2 : sid || "none", col3 : "none",col4:"none", col5:"none", col6:"none", col7:"none", col8:"none", col9:"none", col10:"none", col11:"none", col12:"none", col13:"none", col14:"none", col15:"none", col16:"none" }); dataModel.save(); var thejoblogsid = Alloy.Collections.instance('joblogsid'); thejoblogsid.fetch(); Ti.API.info(" enterjobdetail.js::populatejoblogSIDtoDB:: thejoblogsid : "+JSON.stringify(thejoblogsid)); } //Retrieve cloud data again var sid = args.sid; Ti.API.info("sid for joblog in enterjobdetail.js : "+sid); Alloy.Globals.getPrivateData(sid,"joblog"); function uploadPictoGoogle(image,filename){ console.log("enterjobdetail.js::uploadPictoGoogle::create ss with filename: "+filename); var base64Data = Ti.Utils.base64encode(image); var parts = []; var bound = 287032396531387; var meta = '\{' + '\"title\": \"'+filename+'\"' + '\}'; var parts = []; parts.push('--' + bound); parts.push('Content-Type: application/json'); parts.push(''); parts.push(meta); parts.push('--' + bound); parts.push('Content-Type: image/jpeg'); parts.push('Content-Transfer-Encoding: base64'); parts.push(''); parts.push(base64Data); parts.push('--' + bound + '--'); var url = "https://www.googleapis.com/upload/drive/v2/files?uploadType=multipart"; var xhr = Titanium.Network.createHTTPClient({ onload: function() { try { var json = JSON.parse(this.responseText); Ti.API.info("enterjobdetail.js::uploadPictoGoogle::response is: "+JSON.stringify(json)); var id = json.id; var webcontentlink = json.webContentLink; Ti.API.info("enterjobdetail.js::uploadPictoGoogle::id is: "+id+" webcontentlink: "+webcontentlink); shareAnyonePermission(id); var e = {"value":"Please refer to pic above","source":{"_hintText":id}}; console.log("enterjobdetail.js::uploadPictoGoogle::entering urlimage with info below e: "+JSON.stringify(e)); enterNotes(e,webcontentlink); } catch(e){ Ti.API.info("enterjobdetail.js::uploadPictoGoogle::cathing e: "+JSON.stringify(e)); } return id; }, onerror: function(e) { Ti.API.info("enterjobdetail.js::uploadPictoGoogle::error e: "+JSON.stringify(e)); alert("unable to talk to the cloud, will try later"); } }); xhr.open("POST", url); xhr.setRequestHeader("Content-type", "multipart/mixed; boundary=" + bound); xhr.setRequestHeader("Authorization", 'Bearer '+googleAuthSheet.getAccessToken()); //xhr.setRequestHeader("Content-Length", "2000000"); xhr.send(parts.join("\r\n")); Ti.API.info('done POSTed'); //Ti.API.info("enterjobdetail.js::uploadPictoGoogle::sid outside is: "+id); } function shareAnyonePermission(sid){ console.log("enterjobdetail.js::shareAnyonePermission::sid: "+sid); var jsonpost = '{' +'\"role\": \"reader\",' +'\"type\": \"anyone\"' +'}'; var xhr = Ti.Network.createHTTPClient({ onload: function(e) { try { Ti.API.info("enterjobdetail.js::shareAnyonePermission::response is: "+this.responseText); } catch(e){ Ti.API.info("cathing e: "+JSON.stringify(e)); } } }); xhr.onerror = function(e){ alert("Unable to connect to the cloud."); }; xhr.open("POST", 'https://www.googleapis.com/drive/v2/files/'+sid+'/permissions'); xhr.setRequestHeader("Content-type", "application/json"); xhr.setRequestHeader("Authorization", 'Bearer '+ googleAuthSheet.getAccessToken()); console.log("enterjobdetail.js::shareAnyonePermission::json post: "+jsonpost); xhr.send(jsonpost); } /* $.jobdetailtf.addEventListener("focus", function(e){ console.log("enterjobdetail.js::JSON.stringify(e) :" +JSON.stringify(e)); });*/ /* function largeTF(e){ console.log("enterjobdetail.js::JSON.stringify(e) largeTF :" +JSON.stringify(e)); //$.itemjobdetail.add(textfield); } */
fix alignment
app/controllers/enterjobdetail.js
fix alignment
<ide><path>pp/controllers/enterjobdetail.js <ide> console.log("enterjobdetail.js::JSON stringify joblog: "+JSON.stringify(content)); <ide> <ide> function jobDetailAddRow (date,notesbody,imageurl) { <add> var jobrow = Ti.UI.createTableViewRow ({ <add> backgroundColor: "#ECE6E6", <add> opacity:"0", <add> color:"transparent", <add> width: Ti.UI.FILL, <add> height: "150" <add> }); <ide> var datelabel = Ti.UI.createLabel ({ <ide> color : "orange", <ide> left : "20", <ide> innerview.add(noteslabel); <ide> noteslabel.top = 50; <ide> } else { <del> imagelabel.height = 200; <add> //imagelabel.height = 200; <add> imagelabel.height = Ti.UI.SIZE; <ide> imagelabel.width = 200; <ide> }; <del> if (imageurl != "none") {innerview.add(imagelabel);}; <add> if (imageurl != "none") { <add> innerview.add(imagelabel); <add> var jobrow = Ti.UI.createTableViewRow ({ <add> backgroundColor: "#ECE6E6", <add> opacity:"0", <add> color:"transparent", <add> width: Ti.UI.FILL, <add> height: Ti.UI.SIZE <add> }); <add> }; <ide> if ( notesbody != "none" && imageurl != "none") { <ide> imagelabel.top = 50; <ide> noteslabel.top = 220; <ide> }; <del> var jobrow = Ti.UI.createTableViewRow ({ <del> backgroundColor: "#ECE6E6", <del> opacity:"0", <del> color:"transparent", <del> width: Ti.UI.FILL, <del> height: "200" <del> ///height: Ti.UI.SIZE <del> //title:"{title}" <del> }); <ide> jobrow.add(innerview); <ide> <ide> var jobtable = Ti.UI.createTableView({ <ide> var webcontentlink = json.webContentLink; <ide> Ti.API.info("enterjobdetail.js::uploadPictoGoogle::id is: "+id+" webcontentlink: "+webcontentlink); <ide> shareAnyonePermission(id); <del> var e = {"value":"Please refer to pic above","source":{"_hintText":id}}; <add> var e = {"value":"none","source":{"_hintText":id}}; <ide> console.log("enterjobdetail.js::uploadPictoGoogle::entering urlimage with info below e: "+JSON.stringify(e)); <ide> enterNotes(e,webcontentlink); <ide> } catch(e){
Java
apache-2.0
8cc33c414a85146f575c87663024dc765a959bfe
0
formalin14/titanium_mobile,jvkops/titanium_mobile,emilyvon/titanium_mobile,ashcoding/titanium_mobile,prop/titanium_mobile,shopmium/titanium_mobile,AngelkPetkov/titanium_mobile,taoger/titanium_mobile,taoger/titanium_mobile,openbaoz/titanium_mobile,cheekiatng/titanium_mobile,kopiro/titanium_mobile,mvitr/titanium_mobile,jvkops/titanium_mobile,pec1985/titanium_mobile,perdona/titanium_mobile,KangaCoders/titanium_mobile,indera/titanium_mobile,csg-coder/titanium_mobile,prop/titanium_mobile,sriks/titanium_mobile,pinnamur/titanium_mobile,emilyvon/titanium_mobile,KoketsoMabuela92/titanium_mobile,peymanmortazavi/titanium_mobile,bhatfield/titanium_mobile,ashcoding/titanium_mobile,pinnamur/titanium_mobile,sriks/titanium_mobile,linearhub/titanium_mobile,perdona/titanium_mobile,kopiro/titanium_mobile,indera/titanium_mobile,jhaynie/titanium_mobile,AngelkPetkov/titanium_mobile,KoketsoMabuela92/titanium_mobile,benbahrenburg/titanium_mobile,falkolab/titanium_mobile,falkolab/titanium_mobile,sriks/titanium_mobile,AngelkPetkov/titanium_mobile,shopmium/titanium_mobile,smit1625/titanium_mobile,mano-mykingdom/titanium_mobile,shopmium/titanium_mobile,pinnamur/titanium_mobile,prop/titanium_mobile,pec1985/titanium_mobile,taoger/titanium_mobile,jhaynie/titanium_mobile,pinnamur/titanium_mobile,jhaynie/titanium_mobile,mvitr/titanium_mobile,FokkeZB/titanium_mobile,shopmium/titanium_mobile,jvkops/titanium_mobile,formalin14/titanium_mobile,falkolab/titanium_mobile,rblalock/titanium_mobile,cheekiatng/titanium_mobile,kopiro/titanium_mobile,benbahrenburg/titanium_mobile,perdona/titanium_mobile,smit1625/titanium_mobile,smit1625/titanium_mobile,sriks/titanium_mobile,taoger/titanium_mobile,peymanmortazavi/titanium_mobile,jhaynie/titanium_mobile,ashcoding/titanium_mobile,AngelkPetkov/titanium_mobile,formalin14/titanium_mobile,rblalock/titanium_mobile,cheekiatng/titanium_mobile,linearhub/titanium_mobile,mvitr/titanium_mobile,AngelkPetkov/titanium_mobile,prop/titanium_mobile,emilyvon/titanium_mobile,emilyvon/titanium_mobile,peymanmortazavi/titanium_mobile,pec1985/titanium_mobile,benbahrenburg/titanium_mobile,peymanmortazavi/titanium_mobile,csg-coder/titanium_mobile,ashcoding/titanium_mobile,falkolab/titanium_mobile,emilyvon/titanium_mobile,bright-sparks/titanium_mobile,collinprice/titanium_mobile,bright-sparks/titanium_mobile,shopmium/titanium_mobile,openbaoz/titanium_mobile,collinprice/titanium_mobile,pinnamur/titanium_mobile,taoger/titanium_mobile,pec1985/titanium_mobile,collinprice/titanium_mobile,csg-coder/titanium_mobile,falkolab/titanium_mobile,smit1625/titanium_mobile,KangaCoders/titanium_mobile,bhatfield/titanium_mobile,benbahrenburg/titanium_mobile,perdona/titanium_mobile,openbaoz/titanium_mobile,emilyvon/titanium_mobile,mano-mykingdom/titanium_mobile,pec1985/titanium_mobile,smit1625/titanium_mobile,KangaCoders/titanium_mobile,bhatfield/titanium_mobile,indera/titanium_mobile,csg-coder/titanium_mobile,sriks/titanium_mobile,prop/titanium_mobile,pinnamur/titanium_mobile,linearhub/titanium_mobile,linearhub/titanium_mobile,FokkeZB/titanium_mobile,openbaoz/titanium_mobile,jhaynie/titanium_mobile,KoketsoMabuela92/titanium_mobile,indera/titanium_mobile,prop/titanium_mobile,collinprice/titanium_mobile,falkolab/titanium_mobile,rblalock/titanium_mobile,bright-sparks/titanium_mobile,peymanmortazavi/titanium_mobile,mano-mykingdom/titanium_mobile,sriks/titanium_mobile,jvkops/titanium_mobile,pinnamur/titanium_mobile,rblalock/titanium_mobile,FokkeZB/titanium_mobile,linearhub/titanium_mobile,pinnamur/titanium_mobile,shopmium/titanium_mobile,rblalock/titanium_mobile,bright-sparks/titanium_mobile,kopiro/titanium_mobile,KangaCoders/titanium_mobile,taoger/titanium_mobile,sriks/titanium_mobile,csg-coder/titanium_mobile,KoketsoMabuela92/titanium_mobile,jhaynie/titanium_mobile,collinprice/titanium_mobile,peymanmortazavi/titanium_mobile,KangaCoders/titanium_mobile,mvitr/titanium_mobile,shopmium/titanium_mobile,prop/titanium_mobile,formalin14/titanium_mobile,csg-coder/titanium_mobile,openbaoz/titanium_mobile,shopmium/titanium_mobile,mano-mykingdom/titanium_mobile,kopiro/titanium_mobile,collinprice/titanium_mobile,mvitr/titanium_mobile,taoger/titanium_mobile,pinnamur/titanium_mobile,AngelkPetkov/titanium_mobile,ashcoding/titanium_mobile,bright-sparks/titanium_mobile,perdona/titanium_mobile,rblalock/titanium_mobile,benbahrenburg/titanium_mobile,rblalock/titanium_mobile,jhaynie/titanium_mobile,openbaoz/titanium_mobile,formalin14/titanium_mobile,prop/titanium_mobile,KoketsoMabuela92/titanium_mobile,sriks/titanium_mobile,bright-sparks/titanium_mobile,falkolab/titanium_mobile,benbahrenburg/titanium_mobile,jvkops/titanium_mobile,KangaCoders/titanium_mobile,jvkops/titanium_mobile,smit1625/titanium_mobile,kopiro/titanium_mobile,mano-mykingdom/titanium_mobile,indera/titanium_mobile,AngelkPetkov/titanium_mobile,KangaCoders/titanium_mobile,bhatfield/titanium_mobile,collinprice/titanium_mobile,KangaCoders/titanium_mobile,taoger/titanium_mobile,mano-mykingdom/titanium_mobile,mano-mykingdom/titanium_mobile,perdona/titanium_mobile,csg-coder/titanium_mobile,emilyvon/titanium_mobile,KoketsoMabuela92/titanium_mobile,cheekiatng/titanium_mobile,cheekiatng/titanium_mobile,smit1625/titanium_mobile,indera/titanium_mobile,collinprice/titanium_mobile,bhatfield/titanium_mobile,KoketsoMabuela92/titanium_mobile,benbahrenburg/titanium_mobile,mano-mykingdom/titanium_mobile,AngelkPetkov/titanium_mobile,bhatfield/titanium_mobile,pec1985/titanium_mobile,jvkops/titanium_mobile,FokkeZB/titanium_mobile,pec1985/titanium_mobile,FokkeZB/titanium_mobile,pec1985/titanium_mobile,peymanmortazavi/titanium_mobile,ashcoding/titanium_mobile,cheekiatng/titanium_mobile,linearhub/titanium_mobile,perdona/titanium_mobile,kopiro/titanium_mobile,perdona/titanium_mobile,openbaoz/titanium_mobile,ashcoding/titanium_mobile,KoketsoMabuela92/titanium_mobile,FokkeZB/titanium_mobile,indera/titanium_mobile,falkolab/titanium_mobile,cheekiatng/titanium_mobile,peymanmortazavi/titanium_mobile,linearhub/titanium_mobile,jvkops/titanium_mobile,mvitr/titanium_mobile,emilyvon/titanium_mobile,bright-sparks/titanium_mobile,kopiro/titanium_mobile,pec1985/titanium_mobile,rblalock/titanium_mobile,formalin14/titanium_mobile,formalin14/titanium_mobile,bhatfield/titanium_mobile,bhatfield/titanium_mobile,openbaoz/titanium_mobile,benbahrenburg/titanium_mobile,jhaynie/titanium_mobile,FokkeZB/titanium_mobile,bright-sparks/titanium_mobile,indera/titanium_mobile,cheekiatng/titanium_mobile,FokkeZB/titanium_mobile,csg-coder/titanium_mobile,mvitr/titanium_mobile,linearhub/titanium_mobile,formalin14/titanium_mobile,ashcoding/titanium_mobile,mvitr/titanium_mobile,smit1625/titanium_mobile
/** * Appcelerator Titanium Mobile * Copyright (c) 2009-2012 by Appcelerator, Inc. All Rights Reserved. * Licensed under the terms of the Apache Public License * Please see the LICENSE included with this distribution for details. */ package ti.modules.titanium.ui.widget; import java.util.HashMap; import org.appcelerator.kroll.KrollDict; import org.appcelerator.kroll.KrollProxy; import org.appcelerator.kroll.common.Log; import org.appcelerator.titanium.TiC; import org.appcelerator.titanium.proxy.TiViewProxy; import org.appcelerator.titanium.util.TiConvert; import org.appcelerator.titanium.util.TiUIHelper; import org.appcelerator.titanium.view.TiUIView; import android.content.Context; import android.graphics.Rect; import android.text.Editable; import android.text.InputType; import android.text.TextUtils.TruncateAt; import android.text.TextWatcher; import android.text.method.DialerKeyListener; import android.text.method.DigitsKeyListener; import android.text.method.NumberKeyListener; import android.text.method.PasswordTransformationMethod; import android.view.Gravity; import android.view.KeyEvent; import android.view.View; import android.view.View.OnFocusChangeListener; import android.view.inputmethod.EditorInfo; import android.widget.EditText; import android.widget.TextView; import android.widget.TextView.OnEditorActionListener; public class TiUIText extends TiUIView implements TextWatcher, OnEditorActionListener, OnFocusChangeListener { private static final String TAG = "TiUIText"; public static final int RETURNKEY_GO = 0; public static final int RETURNKEY_GOOGLE = 1; public static final int RETURNKEY_JOIN = 2; public static final int RETURNKEY_NEXT = 3; public static final int RETURNKEY_ROUTE = 4; public static final int RETURNKEY_SEARCH = 5; public static final int RETURNKEY_YAHOO = 6; public static final int RETURNKEY_DONE = 7; public static final int RETURNKEY_EMERGENCY_CALL = 8; public static final int RETURNKEY_DEFAULT = 9; public static final int RETURNKEY_SEND = 10; private static final int KEYBOARD_ASCII = 0; private static final int KEYBOARD_NUMBERS_PUNCTUATION = 1; private static final int KEYBOARD_URL = 2; private static final int KEYBOARD_NUMBER_PAD = 3; private static final int KEYBOARD_PHONE_PAD = 4; private static final int KEYBOARD_EMAIL_ADDRESS = 5; @SuppressWarnings("unused") private static final int KEYBOARD_NAMEPHONE_PAD = 6; private static final int KEYBOARD_DEFAULT = 7; private static final int KEYBOARD_DECIMAL_PAD = 8; // UIModule also has these as values - there's a chance they won't stay in sync if somebody changes one without changing these private static final int TEXT_AUTOCAPITALIZATION_NONE = 0; private static final int TEXT_AUTOCAPITALIZATION_SENTENCES = 1; private static final int TEXT_AUTOCAPITALIZATION_WORDS = 2; private static final int TEXT_AUTOCAPITALIZATION_ALL = 3; private boolean field; private int maxLength = -1; private boolean isTruncatingText = false; private boolean disableChangeEvent = false; protected TiEditText tv; public class TiEditText extends EditText { public TiEditText(Context context) { super(context); } /** * Check whether the called view is a text editor, in which case it would make sense to * automatically display a soft input window for it. */ @Override public boolean onCheckIsTextEditor () { if (proxy.hasProperty(TiC.PROPERTY_SOFT_KEYBOARD_ON_FOCUS) && TiConvert.toInt(proxy.getProperty(TiC.PROPERTY_SOFT_KEYBOARD_ON_FOCUS)) == TiUIView.SOFT_KEYBOARD_HIDE_ON_FOCUS) { return false; } if (proxy.hasProperty(TiC.PROPERTY_EDITABLE) && !(TiConvert.toBoolean(proxy.getProperty(TiC.PROPERTY_EDITABLE)))) { return false; } return true; } @Override protected void onLayout(boolean changed, int left, int top, int right, int bottom) { super.onLayout(changed, left, top, right, bottom); TiUIHelper.firePostLayoutEvent(proxy); } } public TiUIText(TiViewProxy proxy, boolean field) { super(proxy); Log.d(TAG, "Creating a text field", Log.DEBUG_MODE); this.field = field; tv = new TiEditText(getProxy().getActivity()); if (field) { tv.setSingleLine(); tv.setMaxLines(1); } tv.addTextChangedListener(this); tv.setOnEditorActionListener(this); tv.setOnFocusChangeListener(this); // TODO refactor to TiUIView? tv.setIncludeFontPadding(true); if (field) { tv.setGravity(Gravity.CENTER_VERTICAL | Gravity.LEFT); } else { tv.setGravity(Gravity.TOP | Gravity.LEFT); } setNativeView(tv); } @Override public void processProperties(KrollDict d) { super.processProperties(d); if (d.containsKey(TiC.PROPERTY_ENABLED)) { tv.setEnabled(TiConvert.toBoolean(d, TiC.PROPERTY_ENABLED, true)); } if (d.containsKey(TiC.PROPERTY_MAX_LENGTH) && field) { maxLength = TiConvert.toInt(d.get(TiC.PROPERTY_MAX_LENGTH), -1); } // Disable change event temporarily as we are setting the default value disableChangeEvent = true; if (d.containsKey(TiC.PROPERTY_VALUE)) { tv.setText(d.getString(TiC.PROPERTY_VALUE)); } else { tv.setText(""); } disableChangeEvent = false; if (d.containsKey(TiC.PROPERTY_COLOR)) { tv.setTextColor(TiConvert.toColor(d, TiC.PROPERTY_COLOR)); } if (d.containsKey(TiC.PROPERTY_HINT_TEXT)) { tv.setHint(d.getString(TiC.PROPERTY_HINT_TEXT)); } if (d.containsKey(TiC.PROPERTY_ELLIPSIZE)) { if (TiConvert.toBoolean(d, TiC.PROPERTY_ELLIPSIZE)) { tv.setEllipsize(TruncateAt.END); } else { tv.setEllipsize(null); } } if (d.containsKey(TiC.PROPERTY_FONT)) { TiUIHelper.styleText(tv, d.getKrollDict(TiC.PROPERTY_FONT)); } if (d.containsKey(TiC.PROPERTY_TEXT_ALIGN) || d.containsKey(TiC.PROPERTY_VERTICAL_ALIGN)) { String textAlign = null; String verticalAlign = null; if (d.containsKey(TiC.PROPERTY_TEXT_ALIGN)) { textAlign = d.getString(TiC.PROPERTY_TEXT_ALIGN); } if (d.containsKey(TiC.PROPERTY_VERTICAL_ALIGN)) { verticalAlign = d.getString(TiC.PROPERTY_VERTICAL_ALIGN); } handleTextAlign(textAlign, verticalAlign); } if (d.containsKey(TiC.PROPERTY_RETURN_KEY_TYPE)) { handleReturnKeyType(TiConvert.toInt(d.get(TiC.PROPERTY_RETURN_KEY_TYPE), RETURNKEY_DEFAULT)); } if (d.containsKey(TiC.PROPERTY_KEYBOARD_TYPE) || d.containsKey(TiC.PROPERTY_AUTOCORRECT) || d.containsKey(TiC.PROPERTY_PASSWORD_MASK) || d.containsKey(TiC.PROPERTY_AUTOCAPITALIZATION) || d.containsKey(TiC.PROPERTY_EDITABLE)) { handleKeyboard(d); } if (d.containsKey(TiC.PROPERTY_AUTO_LINK)) { TiUIHelper.linkifyIfEnabled(tv, d.get(TiC.PROPERTY_AUTO_LINK)); } } @Override public void propertyChanged(String key, Object oldValue, Object newValue, KrollProxy proxy) { if (Log.isDebugModeEnabled()) { Log.d(TAG, "Property: " + key + " old: " + oldValue + " new: " + newValue, Log.DEBUG_MODE); } if (key.equals(TiC.PROPERTY_ENABLED)) { tv.setEnabled(TiConvert.toBoolean(newValue)); } else if (key.equals(TiC.PROPERTY_VALUE)) { tv.setText(TiConvert.toString(newValue)); } else if (key.equals(TiC.PROPERTY_MAX_LENGTH)) { maxLength = TiConvert.toInt(newValue); //truncate if current text exceeds max length Editable currentText = tv.getText(); if (maxLength >= 0 && currentText.length() > maxLength) { CharSequence truncateText = currentText.subSequence(0, maxLength); int cursor = tv.getSelectionStart() - 1; if (cursor > maxLength) { cursor = maxLength; } tv.setText(truncateText); tv.setSelection(cursor); } } else if (key.equals(TiC.PROPERTY_COLOR)) { tv.setTextColor(TiConvert.toColor((String) newValue)); } else if (key.equals(TiC.PROPERTY_HINT_TEXT)) { tv.setHint((String) newValue); } else if (key.equals(TiC.PROPERTY_ELLIPSIZE)) { if (TiConvert.toBoolean(newValue)) { tv.setEllipsize(TruncateAt.END); } else { tv.setEllipsize(null); } } else if (key.equals(TiC.PROPERTY_TEXT_ALIGN) || key.equals(TiC.PROPERTY_VERTICAL_ALIGN)) { String textAlign = null; String verticalAlign = null; if (key.equals(TiC.PROPERTY_TEXT_ALIGN)) { textAlign = TiConvert.toString(newValue); } else if (proxy.hasProperty(TiC.PROPERTY_TEXT_ALIGN)){ textAlign = TiConvert.toString(proxy.getProperty(TiC.PROPERTY_TEXT_ALIGN)); } if (key.equals(TiC.PROPERTY_VERTICAL_ALIGN)) { verticalAlign = TiConvert.toString(newValue); } else if (proxy.hasProperty(TiC.PROPERTY_VERTICAL_ALIGN)){ verticalAlign = TiConvert.toString(proxy.getProperty(TiC.PROPERTY_VERTICAL_ALIGN)); } handleTextAlign(textAlign, verticalAlign); } else if (key.equals(TiC.PROPERTY_KEYBOARD_TYPE) || (key.equals(TiC.PROPERTY_AUTOCORRECT) || key.equals(TiC.PROPERTY_AUTOCAPITALIZATION) || key.equals(TiC.PROPERTY_PASSWORD_MASK) || key.equals(TiC.PROPERTY_EDITABLE))) { KrollDict d = proxy.getProperties(); handleKeyboard(d); } else if (key.equals(TiC.PROPERTY_RETURN_KEY_TYPE)) { handleReturnKeyType(TiConvert.toInt(newValue)); } else if (key.equals(TiC.PROPERTY_FONT)) { TiUIHelper.styleText(tv, (HashMap) newValue); } else if (key.equals(TiC.PROPERTY_AUTO_LINK)) { TiUIHelper.linkifyIfEnabled(tv, newValue); } else { super.propertyChanged(key, oldValue, newValue, proxy); } } @Override public void afterTextChanged(Editable editable) { if (maxLength >= 0 && editable.length() > maxLength) { // The input characters are more than maxLength. We need to truncate the text and reset text. isTruncatingText = true; String newText = editable.subSequence(0, maxLength).toString(); int cursor = tv.getSelectionStart(); if (cursor > maxLength) { cursor = maxLength; } tv.setText(newText); // This method will invoke onTextChanged() and afterTextChanged(). tv.setSelection(cursor); } else { isTruncatingText = false; } } @Override public void beforeTextChanged(CharSequence s, int start, int before, int count) { } @Override public void onTextChanged(CharSequence s, int start, int before, int count) { /** * There is an Android bug regarding setting filter on EditText that impacts auto completion. * Therefore we can't use filters to implement "maxLength" property. Instead we manipulate * the text to achieve perfect parity with other platforms. * Android bug url for reference: http://code.google.com/p/android/issues/detail?id=35757 */ if (maxLength >= 0 && s.length() > maxLength) { // Can only set truncated text in afterTextChanged. Otherwise, it will crash. return; } String newText = tv.getText().toString(); if (!disableChangeEvent && (!isTruncatingText || (isTruncatingText && proxy.shouldFireChange(proxy.getProperty(TiC.PROPERTY_VALUE), newText)))) { KrollDict data = new KrollDict(); data.put(TiC.PROPERTY_VALUE, newText); proxy.setProperty(TiC.PROPERTY_VALUE, newText); fireEvent(TiC.EVENT_CHANGE, data); } } @Override public void focus() { super.focus(); if (nativeView != null) { if (proxy.hasProperty(TiC.PROPERTY_EDITABLE) && !(TiConvert.toBoolean(proxy.getProperty(TiC.PROPERTY_EDITABLE)))) { TiUIHelper.showSoftKeyboard(nativeView, false); } else { TiUIHelper.requestSoftInputChange(proxy, nativeView); } } } @Override public void onFocusChange(View v, boolean hasFocus) { if (hasFocus) { Boolean clearOnEdit = (Boolean) proxy.getProperty(TiC.PROPERTY_CLEAR_ON_EDIT); if (clearOnEdit != null && clearOnEdit) { ((EditText) nativeView).setText(""); } Rect r = new Rect(); nativeView.getFocusedRect(r); nativeView.requestRectangleOnScreen(r); } super.onFocusChange(v, hasFocus); } @Override protected KrollDict getFocusEventObject(boolean hasFocus) { KrollDict event = new KrollDict(); event.put(TiC.PROPERTY_VALUE, tv.getText().toString()); return event; } @Override public boolean onEditorAction(TextView v, int actionId, KeyEvent keyEvent) { String value = tv.getText().toString(); KrollDict data = new KrollDict(); data.put(TiC.PROPERTY_VALUE, value); proxy.setProperty(TiC.PROPERTY_VALUE, value); Log.d(TAG, "ActionID: " + actionId + " KeyEvent: " + (keyEvent != null ? keyEvent.getKeyCode() : null), Log.DEBUG_MODE); //This is to prevent 'return' event from being fired twice when return key is hit. In other words, when return key is clicked, //this callback is triggered twice (except for keys that are mapped to EditorInfo.IME_ACTION_NEXT or EditorInfo.IME_ACTION_DONE). The first check is to deal with those keys - filter out //one of the two callbacks, and the next checks deal with 'Next' and 'Done' callbacks, respectively. //Refer to TiUIText.handleReturnKeyType(int) for a list of return keys that are mapped to EditorInfo.IME_ACTION_NEXT and EditorInfo.IME_ACTION_DONE. if ((actionId == EditorInfo.IME_NULL && keyEvent != null) || actionId == EditorInfo.IME_ACTION_NEXT || actionId == EditorInfo.IME_ACTION_DONE ) { fireEvent("return", data); } Boolean enableReturnKey = (Boolean) proxy.getProperty(TiC.PROPERTY_ENABLE_RETURN_KEY); if (enableReturnKey != null && enableReturnKey && v.getText().length() == 0) { return true; } return false; } public void handleTextAlign(String textAlign, String verticalAlign) { if (verticalAlign == null) { verticalAlign = field ? "middle" : "top"; } if (textAlign == null) { textAlign = "left"; } TiUIHelper.setAlignment(tv, textAlign, verticalAlign); } public void handleKeyboard(KrollDict d) { int type = KEYBOARD_ASCII; boolean passwordMask = false; boolean editable = true; int autocorrect = InputType.TYPE_TEXT_FLAG_AUTO_CORRECT; int autoCapValue = 0; if (d.containsKey(TiC.PROPERTY_AUTOCORRECT) && !TiConvert.toBoolean(d, TiC.PROPERTY_AUTOCORRECT, true)) { autocorrect = InputType.TYPE_TEXT_FLAG_NO_SUGGESTIONS; } if (d.containsKey(TiC.PROPERTY_EDITABLE)) { editable = TiConvert.toBoolean(d, TiC.PROPERTY_EDITABLE, true); } if (d.containsKey(TiC.PROPERTY_AUTOCAPITALIZATION)) { switch (TiConvert.toInt(d.get(TiC.PROPERTY_AUTOCAPITALIZATION), TEXT_AUTOCAPITALIZATION_NONE)) { case TEXT_AUTOCAPITALIZATION_NONE: autoCapValue = 0; break; case TEXT_AUTOCAPITALIZATION_ALL: autoCapValue = InputType.TYPE_TEXT_FLAG_CAP_CHARACTERS | InputType.TYPE_TEXT_FLAG_CAP_SENTENCES | InputType.TYPE_TEXT_FLAG_CAP_WORDS ; break; case TEXT_AUTOCAPITALIZATION_SENTENCES: autoCapValue = InputType.TYPE_TEXT_FLAG_CAP_SENTENCES; break; case TEXT_AUTOCAPITALIZATION_WORDS: autoCapValue = InputType.TYPE_TEXT_FLAG_CAP_WORDS; break; default: Log.w(TAG, "Unknown AutoCapitalization Value ["+d.getString(TiC.PROPERTY_AUTOCAPITALIZATION)+"]"); break; } } if (d.containsKey(TiC.PROPERTY_PASSWORD_MASK)) { passwordMask = TiConvert.toBoolean(d, TiC.PROPERTY_PASSWORD_MASK, false); } if (d.containsKey(TiC.PROPERTY_KEYBOARD_TYPE)) { type = TiConvert.toInt(d.get(TiC.PROPERTY_KEYBOARD_TYPE), KEYBOARD_DEFAULT); } int typeModifiers = autocorrect | autoCapValue; int textTypeAndClass = typeModifiers; // For some reason you can't set both TYPE_CLASS_TEXT and TYPE_TEXT_FLAG_NO_SUGGESTIONS together. // Also, we need TYPE_CLASS_TEXT for passwords. if (autocorrect != InputType.TYPE_TEXT_FLAG_NO_SUGGESTIONS || passwordMask) { textTypeAndClass = textTypeAndClass | InputType.TYPE_CLASS_TEXT; } if (!field) { tv.setSingleLine(false); } tv.setCursorVisible(true); switch(type) { case KEYBOARD_DEFAULT: case KEYBOARD_ASCII: // Don't need a key listener, inputType handles that. break; case KEYBOARD_NUMBERS_PUNCTUATION: textTypeAndClass |= InputType.TYPE_CLASS_NUMBER; tv.setKeyListener(new NumberKeyListener() { @Override public int getInputType() { return InputType.TYPE_CLASS_NUMBER; } @Override protected char[] getAcceptedChars() { return new char[] { '0', '1', '2','3','4','5','6','7','8','9', '.','-','+','_','*','-','!','@', '#', '$', '%', '^', '&', '*', '(', ')', '=', '{', '}', '[', ']', '|', '\\', '<', '>', ',', '?', '/', ':', ';', '\'', '"', '~' }; } }); break; case KEYBOARD_URL: Log.d(TAG, "Setting keyboard type URL-3", Log.DEBUG_MODE); tv.setImeOptions(EditorInfo.IME_ACTION_GO); textTypeAndClass |= InputType.TYPE_TEXT_VARIATION_URI; break; case KEYBOARD_DECIMAL_PAD: textTypeAndClass |= (InputType.TYPE_NUMBER_FLAG_DECIMAL | InputType.TYPE_NUMBER_FLAG_SIGNED); case KEYBOARD_NUMBER_PAD: tv.setKeyListener(DigitsKeyListener.getInstance(true,true)); textTypeAndClass |= InputType.TYPE_CLASS_NUMBER; break; case KEYBOARD_PHONE_PAD: tv.setKeyListener(DialerKeyListener.getInstance()); textTypeAndClass |= InputType.TYPE_CLASS_PHONE; break; case KEYBOARD_EMAIL_ADDRESS: textTypeAndClass |= InputType.TYPE_TEXT_VARIATION_EMAIL_ADDRESS; break; } if (passwordMask) { textTypeAndClass |= InputType.TYPE_TEXT_VARIATION_PASSWORD; // Sometimes password transformation does not work properly when the input type is set after the transformation method. // This issue has been filed at http://code.google.com/p/android/issues/detail?id=7092 tv.setInputType(tv.getInputType() | textTypeAndClass); tv.setTransformationMethod(PasswordTransformationMethod.getInstance()); //turn off text UI in landscape mode b/c Android numeric passwords are not masked correctly in landscape mode. if (type == KEYBOARD_NUMBERS_PUNCTUATION || type == KEYBOARD_DECIMAL_PAD || type == KEYBOARD_NUMBER_PAD) { tv.setImeOptions(EditorInfo.IME_FLAG_NO_EXTRACT_UI); } } else { tv.setInputType(tv.getInputType() | textTypeAndClass); if (tv.getTransformationMethod() instanceof PasswordTransformationMethod) { tv.setTransformationMethod(null); } } if (!editable) { tv.setKeyListener(null); tv.setCursorVisible(false); } } public void setSelection(int start, int end) { int textLength = tv.length(); if (start < 0 || start > textLength || end < 0 || end > textLength) { Log.w(TAG, "Invalid range for text selection. Ignoring."); return; } tv.setSelection(start, end); } public void handleReturnKeyType(int type) { if (!field) { tv.setInputType(InputType.TYPE_TEXT_FLAG_IME_MULTI_LINE); } switch(type) { case RETURNKEY_GO: tv.setImeOptions(EditorInfo.IME_ACTION_GO); break; case RETURNKEY_GOOGLE: tv.setImeOptions(EditorInfo.IME_ACTION_GO); break; case RETURNKEY_JOIN: tv.setImeOptions(EditorInfo.IME_ACTION_DONE); break; case RETURNKEY_NEXT: tv.setImeOptions(EditorInfo.IME_ACTION_NEXT); break; case RETURNKEY_ROUTE: tv.setImeOptions(EditorInfo.IME_ACTION_DONE); break; case RETURNKEY_SEARCH: tv.setImeOptions(EditorInfo.IME_ACTION_SEARCH); break; case RETURNKEY_YAHOO: tv.setImeOptions(EditorInfo.IME_ACTION_GO); break; case RETURNKEY_DONE: tv.setImeOptions(EditorInfo.IME_ACTION_DONE); break; case RETURNKEY_EMERGENCY_CALL: tv.setImeOptions(EditorInfo.IME_ACTION_GO); break; case RETURNKEY_DEFAULT: tv.setImeOptions(EditorInfo.IME_ACTION_UNSPECIFIED); break; case RETURNKEY_SEND: tv.setImeOptions(EditorInfo.IME_ACTION_SEND); break; } } }
android/modules/ui/src/java/ti/modules/titanium/ui/widget/TiUIText.java
/** * Appcelerator Titanium Mobile * Copyright (c) 2009-2012 by Appcelerator, Inc. All Rights Reserved. * Licensed under the terms of the Apache Public License * Please see the LICENSE included with this distribution for details. */ package ti.modules.titanium.ui.widget; import java.util.HashMap; import org.appcelerator.kroll.KrollDict; import org.appcelerator.kroll.KrollProxy; import org.appcelerator.kroll.common.Log; import org.appcelerator.titanium.TiC; import org.appcelerator.titanium.proxy.TiViewProxy; import org.appcelerator.titanium.util.TiConvert; import org.appcelerator.titanium.util.TiUIHelper; import org.appcelerator.titanium.view.TiUIView; import android.content.Context; import android.graphics.Rect; import android.text.Editable; import android.text.InputType; import android.text.TextUtils.TruncateAt; import android.text.TextWatcher; import android.text.method.DialerKeyListener; import android.text.method.DigitsKeyListener; import android.text.method.NumberKeyListener; import android.text.method.PasswordTransformationMethod; import android.view.Gravity; import android.view.KeyEvent; import android.view.View; import android.view.View.OnFocusChangeListener; import android.view.inputmethod.EditorInfo; import android.widget.EditText; import android.widget.TextView; import android.widget.TextView.OnEditorActionListener; public class TiUIText extends TiUIView implements TextWatcher, OnEditorActionListener, OnFocusChangeListener { private static final String TAG = "TiUIText"; public static final int RETURNKEY_GO = 0; public static final int RETURNKEY_GOOGLE = 1; public static final int RETURNKEY_JOIN = 2; public static final int RETURNKEY_NEXT = 3; public static final int RETURNKEY_ROUTE = 4; public static final int RETURNKEY_SEARCH = 5; public static final int RETURNKEY_YAHOO = 6; public static final int RETURNKEY_DONE = 7; public static final int RETURNKEY_EMERGENCY_CALL = 8; public static final int RETURNKEY_DEFAULT = 9; public static final int RETURNKEY_SEND = 10; private static final int KEYBOARD_ASCII = 0; private static final int KEYBOARD_NUMBERS_PUNCTUATION = 1; private static final int KEYBOARD_URL = 2; private static final int KEYBOARD_NUMBER_PAD = 3; private static final int KEYBOARD_PHONE_PAD = 4; private static final int KEYBOARD_EMAIL_ADDRESS = 5; @SuppressWarnings("unused") private static final int KEYBOARD_NAMEPHONE_PAD = 6; private static final int KEYBOARD_DEFAULT = 7; private static final int KEYBOARD_DECIMAL_PAD = 8; // UIModule also has these as values - there's a chance they won't stay in sync if somebody changes one without changing these private static final int TEXT_AUTOCAPITALIZATION_NONE = 0; private static final int TEXT_AUTOCAPITALIZATION_SENTENCES = 1; private static final int TEXT_AUTOCAPITALIZATION_WORDS = 2; private static final int TEXT_AUTOCAPITALIZATION_ALL = 3; private boolean field; private int maxLength = -1; private boolean isTruncatingText = false; private boolean disableChangeEvent = false; protected TiEditText tv; public class TiEditText extends EditText { public TiEditText(Context context) { super(context); } /** * Check whether the called view is a text editor, in which case it would make sense to * automatically display a soft input window for it. */ @Override public boolean onCheckIsTextEditor () { if (proxy.hasProperty(TiC.PROPERTY_SOFT_KEYBOARD_ON_FOCUS) && TiConvert.toInt(proxy.getProperty(TiC.PROPERTY_SOFT_KEYBOARD_ON_FOCUS)) == TiUIView.SOFT_KEYBOARD_HIDE_ON_FOCUS) { return false; } if (proxy.hasProperty(TiC.PROPERTY_EDITABLE) && !(TiConvert.toBoolean(proxy.getProperty(TiC.PROPERTY_EDITABLE)))) { return false; } return true; } @Override protected void onLayout(boolean changed, int left, int top, int right, int bottom) { super.onLayout(changed, left, top, right, bottom); TiUIHelper.firePostLayoutEvent(proxy); } } public TiUIText(TiViewProxy proxy, boolean field) { super(proxy); Log.d(TAG, "Creating a text field", Log.DEBUG_MODE); this.field = field; tv = new TiEditText(getProxy().getActivity()); if (field) { tv.setSingleLine(); tv.setMaxLines(1); } tv.addTextChangedListener(this); tv.setOnEditorActionListener(this); tv.setOnFocusChangeListener(this); // TODO refactor to TiUIView? tv.setIncludeFontPadding(true); if (field) { tv.setGravity(Gravity.CENTER_VERTICAL | Gravity.LEFT); } else { tv.setGravity(Gravity.TOP | Gravity.LEFT); } setNativeView(tv); } @Override public void processProperties(KrollDict d) { super.processProperties(d); if (d.containsKey(TiC.PROPERTY_ENABLED)) { tv.setEnabled(TiConvert.toBoolean(d, TiC.PROPERTY_ENABLED, true)); } if (d.containsKey(TiC.PROPERTY_MAX_LENGTH) && field) { maxLength = TiConvert.toInt(d.get(TiC.PROPERTY_MAX_LENGTH), -1); } // Disable change event temporarily as we are setting the default value disableChangeEvent = true; if (d.containsKey(TiC.PROPERTY_VALUE)) { tv.setText(d.getString(TiC.PROPERTY_VALUE)); } else { tv.setText(""); } disableChangeEvent = false; if (d.containsKey(TiC.PROPERTY_COLOR)) { tv.setTextColor(TiConvert.toColor(d, TiC.PROPERTY_COLOR)); } if (d.containsKey(TiC.PROPERTY_HINT_TEXT)) { tv.setHint(d.getString(TiC.PROPERTY_HINT_TEXT)); } if (d.containsKey(TiC.PROPERTY_ELLIPSIZE)) { if (TiConvert.toBoolean(d, TiC.PROPERTY_ELLIPSIZE)) { tv.setEllipsize(TruncateAt.END); } else { tv.setEllipsize(null); } } if (d.containsKey(TiC.PROPERTY_FONT)) { TiUIHelper.styleText(tv, d.getKrollDict(TiC.PROPERTY_FONT)); } if (d.containsKey(TiC.PROPERTY_TEXT_ALIGN) || d.containsKey(TiC.PROPERTY_VERTICAL_ALIGN)) { String textAlign = null; String verticalAlign = null; if (d.containsKey(TiC.PROPERTY_TEXT_ALIGN)) { textAlign = d.getString(TiC.PROPERTY_TEXT_ALIGN); } if (d.containsKey(TiC.PROPERTY_VERTICAL_ALIGN)) { verticalAlign = d.getString(TiC.PROPERTY_VERTICAL_ALIGN); } handleTextAlign(textAlign, verticalAlign); } if (d.containsKey(TiC.PROPERTY_RETURN_KEY_TYPE)) { handleReturnKeyType(TiConvert.toInt(d.get(TiC.PROPERTY_RETURN_KEY_TYPE), RETURNKEY_DEFAULT)); } if (d.containsKey(TiC.PROPERTY_KEYBOARD_TYPE) || d.containsKey(TiC.PROPERTY_AUTOCORRECT) || d.containsKey(TiC.PROPERTY_PASSWORD_MASK) || d.containsKey(TiC.PROPERTY_AUTOCAPITALIZATION) || d.containsKey(TiC.PROPERTY_EDITABLE)) { handleKeyboard(d); } else if (!field) { tv.setInputType(InputType.TYPE_TEXT_FLAG_IME_MULTI_LINE); } if (d.containsKey(TiC.PROPERTY_AUTO_LINK)) { TiUIHelper.linkifyIfEnabled(tv, d.get(TiC.PROPERTY_AUTO_LINK)); } } @Override public void propertyChanged(String key, Object oldValue, Object newValue, KrollProxy proxy) { if (Log.isDebugModeEnabled()) { Log.d(TAG, "Property: " + key + " old: " + oldValue + " new: " + newValue, Log.DEBUG_MODE); } if (key.equals(TiC.PROPERTY_ENABLED)) { tv.setEnabled(TiConvert.toBoolean(newValue)); } else if (key.equals(TiC.PROPERTY_VALUE)) { tv.setText(TiConvert.toString(newValue)); } else if (key.equals(TiC.PROPERTY_MAX_LENGTH)) { maxLength = TiConvert.toInt(newValue); //truncate if current text exceeds max length Editable currentText = tv.getText(); if (maxLength >= 0 && currentText.length() > maxLength) { CharSequence truncateText = currentText.subSequence(0, maxLength); int cursor = tv.getSelectionStart() - 1; if (cursor > maxLength) { cursor = maxLength; } tv.setText(truncateText); tv.setSelection(cursor); } } else if (key.equals(TiC.PROPERTY_COLOR)) { tv.setTextColor(TiConvert.toColor((String) newValue)); } else if (key.equals(TiC.PROPERTY_HINT_TEXT)) { tv.setHint((String) newValue); } else if (key.equals(TiC.PROPERTY_ELLIPSIZE)) { if (TiConvert.toBoolean(newValue)) { tv.setEllipsize(TruncateAt.END); } else { tv.setEllipsize(null); } } else if (key.equals(TiC.PROPERTY_TEXT_ALIGN) || key.equals(TiC.PROPERTY_VERTICAL_ALIGN)) { String textAlign = null; String verticalAlign = null; if (key.equals(TiC.PROPERTY_TEXT_ALIGN)) { textAlign = TiConvert.toString(newValue); } else if (proxy.hasProperty(TiC.PROPERTY_TEXT_ALIGN)){ textAlign = TiConvert.toString(proxy.getProperty(TiC.PROPERTY_TEXT_ALIGN)); } if (key.equals(TiC.PROPERTY_VERTICAL_ALIGN)) { verticalAlign = TiConvert.toString(newValue); } else if (proxy.hasProperty(TiC.PROPERTY_VERTICAL_ALIGN)){ verticalAlign = TiConvert.toString(proxy.getProperty(TiC.PROPERTY_VERTICAL_ALIGN)); } handleTextAlign(textAlign, verticalAlign); } else if (key.equals(TiC.PROPERTY_KEYBOARD_TYPE) || (key.equals(TiC.PROPERTY_AUTOCORRECT) || key.equals(TiC.PROPERTY_AUTOCAPITALIZATION) || key.equals(TiC.PROPERTY_PASSWORD_MASK) || key.equals(TiC.PROPERTY_EDITABLE))) { KrollDict d = proxy.getProperties(); handleKeyboard(d); } else if (key.equals(TiC.PROPERTY_RETURN_KEY_TYPE)) { handleReturnKeyType(TiConvert.toInt(newValue)); } else if (key.equals(TiC.PROPERTY_FONT)) { TiUIHelper.styleText(tv, (HashMap) newValue); } else if (key.equals(TiC.PROPERTY_AUTO_LINK)) { TiUIHelper.linkifyIfEnabled(tv, newValue); } else { super.propertyChanged(key, oldValue, newValue, proxy); } } @Override public void afterTextChanged(Editable editable) { if (maxLength >= 0 && editable.length() > maxLength) { // The input characters are more than maxLength. We need to truncate the text and reset text. isTruncatingText = true; String newText = editable.subSequence(0, maxLength).toString(); int cursor = tv.getSelectionStart(); if (cursor > maxLength) { cursor = maxLength; } tv.setText(newText); // This method will invoke onTextChanged() and afterTextChanged(). tv.setSelection(cursor); } else { isTruncatingText = false; } } @Override public void beforeTextChanged(CharSequence s, int start, int before, int count) { } @Override public void onTextChanged(CharSequence s, int start, int before, int count) { /** * There is an Android bug regarding setting filter on EditText that impacts auto completion. * Therefore we can't use filters to implement "maxLength" property. Instead we manipulate * the text to achieve perfect parity with other platforms. * Android bug url for reference: http://code.google.com/p/android/issues/detail?id=35757 */ if (maxLength >= 0 && s.length() > maxLength) { // Can only set truncated text in afterTextChanged. Otherwise, it will crash. return; } String newText = tv.getText().toString(); if (!disableChangeEvent && (!isTruncatingText || (isTruncatingText && proxy.shouldFireChange(proxy.getProperty(TiC.PROPERTY_VALUE), newText)))) { KrollDict data = new KrollDict(); data.put(TiC.PROPERTY_VALUE, newText); proxy.setProperty(TiC.PROPERTY_VALUE, newText); fireEvent(TiC.EVENT_CHANGE, data); } } @Override public void focus() { super.focus(); if (nativeView != null) { if (proxy.hasProperty(TiC.PROPERTY_EDITABLE) && !(TiConvert.toBoolean(proxy.getProperty(TiC.PROPERTY_EDITABLE)))) { TiUIHelper.showSoftKeyboard(nativeView, false); } else { TiUIHelper.requestSoftInputChange(proxy, nativeView); } } } @Override public void onFocusChange(View v, boolean hasFocus) { if (hasFocus) { Boolean clearOnEdit = (Boolean) proxy.getProperty(TiC.PROPERTY_CLEAR_ON_EDIT); if (clearOnEdit != null && clearOnEdit) { ((EditText) nativeView).setText(""); } Rect r = new Rect(); nativeView.getFocusedRect(r); nativeView.requestRectangleOnScreen(r); } super.onFocusChange(v, hasFocus); } @Override protected KrollDict getFocusEventObject(boolean hasFocus) { KrollDict event = new KrollDict(); event.put(TiC.PROPERTY_VALUE, tv.getText().toString()); return event; } @Override public boolean onEditorAction(TextView v, int actionId, KeyEvent keyEvent) { String value = tv.getText().toString(); KrollDict data = new KrollDict(); data.put(TiC.PROPERTY_VALUE, value); proxy.setProperty(TiC.PROPERTY_VALUE, value); Log.d(TAG, "ActionID: " + actionId + " KeyEvent: " + (keyEvent != null ? keyEvent.getKeyCode() : null), Log.DEBUG_MODE); //This is to prevent 'return' event from being fired twice when return key is hit. In other words, when return key is clicked, //this callback is triggered twice (except for keys that are mapped to EditorInfo.IME_ACTION_NEXT or EditorInfo.IME_ACTION_DONE). The first check is to deal with those keys - filter out //one of the two callbacks, and the next checks deal with 'Next' and 'Done' callbacks, respectively. //Refer to TiUIText.handleReturnKeyType(int) for a list of return keys that are mapped to EditorInfo.IME_ACTION_NEXT and EditorInfo.IME_ACTION_DONE. if ((actionId == EditorInfo.IME_NULL && keyEvent != null) || actionId == EditorInfo.IME_ACTION_NEXT || actionId == EditorInfo.IME_ACTION_DONE ) { fireEvent("return", data); } Boolean enableReturnKey = (Boolean) proxy.getProperty(TiC.PROPERTY_ENABLE_RETURN_KEY); if (enableReturnKey != null && enableReturnKey && v.getText().length() == 0) { return true; } return false; } public void handleTextAlign(String textAlign, String verticalAlign) { if (verticalAlign == null) { verticalAlign = field ? "middle" : "top"; } if (textAlign == null) { textAlign = "left"; } TiUIHelper.setAlignment(tv, textAlign, verticalAlign); } public void handleKeyboard(KrollDict d) { int type = KEYBOARD_ASCII; boolean passwordMask = false; boolean editable = true; int autocorrect = InputType.TYPE_TEXT_FLAG_AUTO_CORRECT; int autoCapValue = 0; if (d.containsKey(TiC.PROPERTY_AUTOCORRECT) && !TiConvert.toBoolean(d, TiC.PROPERTY_AUTOCORRECT, true)) { autocorrect = InputType.TYPE_TEXT_FLAG_NO_SUGGESTIONS; } if (d.containsKey(TiC.PROPERTY_EDITABLE)) { editable = TiConvert.toBoolean(d, TiC.PROPERTY_EDITABLE, true); } if (d.containsKey(TiC.PROPERTY_AUTOCAPITALIZATION)) { switch (TiConvert.toInt(d.get(TiC.PROPERTY_AUTOCAPITALIZATION), TEXT_AUTOCAPITALIZATION_NONE)) { case TEXT_AUTOCAPITALIZATION_NONE: autoCapValue = 0; break; case TEXT_AUTOCAPITALIZATION_ALL: autoCapValue = InputType.TYPE_TEXT_FLAG_CAP_CHARACTERS | InputType.TYPE_TEXT_FLAG_CAP_SENTENCES | InputType.TYPE_TEXT_FLAG_CAP_WORDS ; break; case TEXT_AUTOCAPITALIZATION_SENTENCES: autoCapValue = InputType.TYPE_TEXT_FLAG_CAP_SENTENCES; break; case TEXT_AUTOCAPITALIZATION_WORDS: autoCapValue = InputType.TYPE_TEXT_FLAG_CAP_WORDS; break; default: Log.w(TAG, "Unknown AutoCapitalization Value ["+d.getString(TiC.PROPERTY_AUTOCAPITALIZATION)+"]"); break; } } if (d.containsKey(TiC.PROPERTY_PASSWORD_MASK)) { passwordMask = TiConvert.toBoolean(d, TiC.PROPERTY_PASSWORD_MASK, false); } if (d.containsKey(TiC.PROPERTY_KEYBOARD_TYPE)) { type = TiConvert.toInt(d.get(TiC.PROPERTY_KEYBOARD_TYPE), KEYBOARD_DEFAULT); } int typeModifiers = autocorrect | autoCapValue; int textTypeAndClass = typeModifiers; // For some reason you can't set both TYPE_CLASS_TEXT and TYPE_TEXT_FLAG_NO_SUGGESTIONS together. // Also, we need TYPE_CLASS_TEXT for passwords. if (autocorrect != InputType.TYPE_TEXT_FLAG_NO_SUGGESTIONS || passwordMask) { textTypeAndClass = textTypeAndClass | InputType.TYPE_CLASS_TEXT; } if (!field) { tv.setSingleLine(false); } tv.setCursorVisible(true); switch(type) { case KEYBOARD_DEFAULT: case KEYBOARD_ASCII: // Don't need a key listener, inputType handles that. break; case KEYBOARD_NUMBERS_PUNCTUATION: textTypeAndClass |= InputType.TYPE_CLASS_NUMBER; tv.setKeyListener(new NumberKeyListener() { @Override public int getInputType() { return InputType.TYPE_CLASS_NUMBER; } @Override protected char[] getAcceptedChars() { return new char[] { '0', '1', '2','3','4','5','6','7','8','9', '.','-','+','_','*','-','!','@', '#', '$', '%', '^', '&', '*', '(', ')', '=', '{', '}', '[', ']', '|', '\\', '<', '>', ',', '?', '/', ':', ';', '\'', '"', '~' }; } }); break; case KEYBOARD_URL: Log.d(TAG, "Setting keyboard type URL-3", Log.DEBUG_MODE); tv.setImeOptions(EditorInfo.IME_ACTION_GO); textTypeAndClass |= InputType.TYPE_TEXT_VARIATION_URI; break; case KEYBOARD_DECIMAL_PAD: textTypeAndClass |= (InputType.TYPE_NUMBER_FLAG_DECIMAL | InputType.TYPE_NUMBER_FLAG_SIGNED); case KEYBOARD_NUMBER_PAD: tv.setKeyListener(DigitsKeyListener.getInstance(true,true)); textTypeAndClass |= InputType.TYPE_CLASS_NUMBER; break; case KEYBOARD_PHONE_PAD: tv.setKeyListener(DialerKeyListener.getInstance()); textTypeAndClass |= InputType.TYPE_CLASS_PHONE; break; case KEYBOARD_EMAIL_ADDRESS: textTypeAndClass |= InputType.TYPE_TEXT_VARIATION_EMAIL_ADDRESS; break; } if (passwordMask) { textTypeAndClass |= InputType.TYPE_TEXT_VARIATION_PASSWORD; // Sometimes password transformation does not work properly when the input type is set after the transformation method. // This issue has been filed at http://code.google.com/p/android/issues/detail?id=7092 tv.setInputType(textTypeAndClass); tv.setTransformationMethod(PasswordTransformationMethod.getInstance()); //turn off text UI in landscape mode b/c Android numeric passwords are not masked correctly in landscape mode. if (type == KEYBOARD_NUMBERS_PUNCTUATION || type == KEYBOARD_DECIMAL_PAD || type == KEYBOARD_NUMBER_PAD) { tv.setImeOptions(EditorInfo.IME_FLAG_NO_EXTRACT_UI); } } else { tv.setInputType(textTypeAndClass); if (tv.getTransformationMethod() instanceof PasswordTransformationMethod) { tv.setTransformationMethod(null); } } if (!editable) { tv.setKeyListener(null); tv.setCursorVisible(false); } } public void setSelection(int start, int end) { int textLength = tv.length(); if (start < 0 || start > textLength || end < 0 || end > textLength) { Log.w(TAG, "Invalid range for text selection. Ignoring."); return; } tv.setSelection(start, end); } public void handleReturnKeyType(int type) { if (!field) { tv.setInputType(InputType.TYPE_TEXT_FLAG_IME_MULTI_LINE); } switch(type) { case RETURNKEY_GO: tv.setImeOptions(EditorInfo.IME_ACTION_GO); break; case RETURNKEY_GOOGLE: tv.setImeOptions(EditorInfo.IME_ACTION_GO); break; case RETURNKEY_JOIN: tv.setImeOptions(EditorInfo.IME_ACTION_DONE); break; case RETURNKEY_NEXT: tv.setImeOptions(EditorInfo.IME_ACTION_NEXT); break; case RETURNKEY_ROUTE: tv.setImeOptions(EditorInfo.IME_ACTION_DONE); break; case RETURNKEY_SEARCH: tv.setImeOptions(EditorInfo.IME_ACTION_SEARCH); break; case RETURNKEY_YAHOO: tv.setImeOptions(EditorInfo.IME_ACTION_GO); break; case RETURNKEY_DONE: tv.setImeOptions(EditorInfo.IME_ACTION_DONE); break; case RETURNKEY_EMERGENCY_CALL: tv.setImeOptions(EditorInfo.IME_ACTION_GO); break; case RETURNKEY_DEFAULT: tv.setImeOptions(EditorInfo.IME_ACTION_UNSPECIFIED); break; case RETURNKEY_SEND: tv.setImeOptions(EditorInfo.IME_ACTION_SEND); break; } } }
TIMOB-15535: Don't default to setting textareas to InputType.TYPE_TEXT_FLAG_IME_MULTI_LINE.
android/modules/ui/src/java/ti/modules/titanium/ui/widget/TiUIText.java
TIMOB-15535: Don't default to setting textareas to InputType.TYPE_TEXT_FLAG_IME_MULTI_LINE.
<ide><path>ndroid/modules/ui/src/java/ti/modules/titanium/ui/widget/TiUIText.java <ide> if (d.containsKey(TiC.PROPERTY_RETURN_KEY_TYPE)) { <ide> handleReturnKeyType(TiConvert.toInt(d.get(TiC.PROPERTY_RETURN_KEY_TYPE), RETURNKEY_DEFAULT)); <ide> } <del> <del> if (d.containsKey(TiC.PROPERTY_KEYBOARD_TYPE) || d.containsKey(TiC.PROPERTY_AUTOCORRECT) || d.containsKey(TiC.PROPERTY_PASSWORD_MASK) || d.containsKey(TiC.PROPERTY_AUTOCAPITALIZATION) || d.containsKey(TiC.PROPERTY_EDITABLE)) { <add> <add> if (d.containsKey(TiC.PROPERTY_KEYBOARD_TYPE) || d.containsKey(TiC.PROPERTY_AUTOCORRECT) <add> || d.containsKey(TiC.PROPERTY_PASSWORD_MASK) || d.containsKey(TiC.PROPERTY_AUTOCAPITALIZATION) <add> || d.containsKey(TiC.PROPERTY_EDITABLE)) { <ide> handleKeyboard(d); <del> } else if (!field) { <del> tv.setInputType(InputType.TYPE_TEXT_FLAG_IME_MULTI_LINE); <del> } <del> <add> } <add> <ide> if (d.containsKey(TiC.PROPERTY_AUTO_LINK)) { <ide> TiUIHelper.linkifyIfEnabled(tv, d.get(TiC.PROPERTY_AUTO_LINK)); <ide> } <ide> textTypeAndClass |= InputType.TYPE_TEXT_VARIATION_PASSWORD; <ide> // Sometimes password transformation does not work properly when the input type is set after the transformation method. <ide> // This issue has been filed at http://code.google.com/p/android/issues/detail?id=7092 <del> tv.setInputType(textTypeAndClass); <add> tv.setInputType(tv.getInputType() | textTypeAndClass); <ide> tv.setTransformationMethod(PasswordTransformationMethod.getInstance()); <ide> <ide> //turn off text UI in landscape mode b/c Android numeric passwords are not masked correctly in landscape mode. <ide> } <ide> <ide> } else { <del> tv.setInputType(textTypeAndClass); <add> tv.setInputType(tv.getInputType() | textTypeAndClass); <ide> if (tv.getTransformationMethod() instanceof PasswordTransformationMethod) { <ide> tv.setTransformationMethod(null); <ide> }
Java
agpl-3.0
f1e620245bf8edc6a8f094d76b7941469737a4a6
0
telefonicaid/fiware-cygnus,Fiware/data.Cygnus,telefonicaid/fiware-cygnus,Fiware/context.Cygnus,Fiware/context.Cygnus,Fiware/data.Cygnus,Fiware/data.Cygnus,Fiware/context.Cygnus,Fiware/context.Cygnus,telefonicaid/fiware-cygnus,telefonicaid/fiware-cygnus
/** * Copyright 2015 Telefonica Investigación y Desarrollo, S.A.U * * This file is part of fiware-cygnus (FI-WARE project). * * fiware-cygnus is free software: you can redistribute it and/or modify it under the terms of the GNU Affero * General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your * option) any later version. * fiware-cygnus is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the * implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License * for more details. * * You should have received a copy of the GNU Affero General Public License along with fiware-cygnus. If not, see * http://www.gnu.org/licenses/. * * For those usages not covered by the GNU Affero General Public License please contact with iot_support at tid dot es */ package com.telefonica.iot.cygnus.sinks; import com.telefonica.iot.cygnus.backends.hdfs.HDFSBackend; import com.telefonica.iot.cygnus.backends.hdfs.HDFSBackend.FileFormat; import static com.telefonica.iot.cygnus.backends.hdfs.HDFSBackend.FileFormat.CSVCOLUMN; import static com.telefonica.iot.cygnus.backends.hdfs.HDFSBackend.FileFormat.CSVROW; import static com.telefonica.iot.cygnus.backends.hdfs.HDFSBackend.FileFormat.JSONCOLUMN; import static com.telefonica.iot.cygnus.backends.hdfs.HDFSBackend.FileFormat.JSONROW; import com.telefonica.iot.cygnus.backends.hdfs.HDFSBackendImplBinary; import com.telefonica.iot.cygnus.backends.hdfs.HDFSBackendImplREST; import com.telefonica.iot.cygnus.containers.NotifyContextRequest; import com.telefonica.iot.cygnus.containers.NotifyContextRequest.ContextAttribute; import com.telefonica.iot.cygnus.containers.NotifyContextRequest.ContextElement; import com.telefonica.iot.cygnus.errors.CygnusBadConfiguration; import com.telefonica.iot.cygnus.log.CygnusLogger; import com.telefonica.iot.cygnus.utils.Constants; import com.telefonica.iot.cygnus.utils.Utils; import java.util.ArrayList; import java.util.Arrays; import java.util.HashMap; import java.util.Map; import java.util.Set; import org.apache.flume.Context; import org.json.simple.JSONArray; import org.json.simple.JSONObject; import org.json.simple.parser.JSONParser; /** * * @author frb * * Detailed documentation can be found at: * https://github.com/telefonicaid/fiware-cygnus/blob/master/doc/design/OrionHDFSSink.md */ public class OrionHDFSSink extends OrionSink { /** * Available backend implementation. */ public enum BackendImpl { BINARY, REST } private static final CygnusLogger LOGGER = new CygnusLogger(OrionHDFSSink.class); private String[] host; private String port; private String username; private String password; private FileFormat fileFormat; private String oauth2Token; private String hiveServerVersion; private String hiveHost; private String hivePort; private boolean krb5; private String krb5User; private String krb5Password; private String krb5LoginConfFile; private String krb5ConfFile; private boolean serviceAsNamespace; private BackendImpl backendImpl; private HDFSBackend persistenceBackend; /** * Constructor. */ public OrionHDFSSink() { super(); } // OrionHDFSSink /** * Gets the Cosmos host. It is protected due to it is only required for testing purposes. * @return The Cosmos host */ protected String[] getHDFSHosts() { return host; } // getHDFSHosts /** * Gets the Cosmos port. It is protected due to it is only required for testing purposes. * @return The Cosmos port */ protected String getHDFSPort() { return port; } // getHDFSPort /** * Gets the default Cosmos username. It is protected due to it is only required for testing purposes. * @return The default Cosmos username */ protected String getHDFSUsername() { return username; } // getHDFSUsername /** * Gets the password for the default Cosmos username. It is protected due to it is only required for testing * purposes. * @return The password for the default Cosmos username */ protected String getHDFSPassword() { return password; } // getHDFSPassword /** * Gets the OAuth2 token used for authentication and authorization. It is protected due to it is only required * for testing purposes. * @return The Cosmos oauth2Token for the detault Cosmos username */ protected String getOAuth2Token() { return oauth2Token; } // getOAuth2Token /** * Returns if the service is used as HDFS namespace. It is protected due to it is only required for testing * purposes. * @return "true" if the service is used as HDFS namespace, "false" otherwise. */ protected String getServiceAsNamespace() { return (serviceAsNamespace ? "true" : "false"); } // getServiceAsNamespace /** * Gets the file format. It is protected due to it is only required for testing purposes. * @return The file format */ protected String getFileFormat() { switch (fileFormat) { case JSONROW: return "json-row"; case JSONCOLUMN: return "json-column"; case CSVROW: return "csv-row"; case CSVCOLUMN: return "csv-column"; default: return ""; } // switch; } // getFileFormat /** * Gets the Hive server version. It is protected due to it is only required for testing purposes. * @return The Hive server version */ protected String getHiveServerVersion() { return hiveServerVersion; } // getHiveServerVersion /** * Gets the Hive host. It is protected due to it is only required for testing purposes. * @return The Hive port */ protected String getHiveHost() { return hiveHost; } // getHiveHost /** * Gets the Hive port. It is protected due to it is only required for testing purposes. * @return The Hive port */ protected String getHivePort() { return hivePort; } // getHivePort /** * Returns if Kerberos is being used for authenticacion. It is protected due to it is only required for testing * purposes. * @return "true" if Kerberos is being used for authentication, otherwise "false" */ protected String getKrb5Auth() { return (krb5 ? "true" : "false"); } // getKrb5Auth /** * Returns the persistence backend. It is protected due to it is only required for testing purposes. * @return The persistence backend */ protected HDFSBackend getPersistenceBackend() { return persistenceBackend; } // getPersistenceBackend /** * Sets the persistence backend. It is protected due to it is only required for testing purposes. * @param persistenceBackend */ protected void setPersistenceBackend(HDFSBackendImplREST persistenceBackend) { this.persistenceBackend = persistenceBackend; } // setPersistenceBackend @Override public void configure(Context context) { String cosmosHost = context.getString("cosmos_host"); String hdfsHost = context.getString("hdfs_host"); if (hdfsHost != null && hdfsHost.length() > 0) { host = hdfsHost.split(","); LOGGER.debug("[" + this.getName() + "] Reading configuration (hdfs_host=" + Arrays.toString(host) + ")"); } else if (cosmosHost != null && cosmosHost.length() > 0) { host = cosmosHost.split(","); LOGGER.debug("[" + this.getName() + "] Reading configuration (cosmos_host=" + Arrays.toString(host) + ")" + " -- DEPRECATED, use hdfs_host instead"); } else { host = new String[]{"localhost"}; LOGGER.debug("[" + this.getName() + "] Defaulting to hdfs_host=localhost"); } // if else String cosmosPort = context.getString("cosmos_port"); String hdfsPort = context.getString("hdfs_port"); if (hdfsPort != null && hdfsPort.length() > 0) { port = hdfsPort; LOGGER.debug("[" + this.getName() + "] Reading configuration (hdfs_port=" + port + ")"); } else if (cosmosPort != null && cosmosPort.length() > 0) { port = cosmosPort; LOGGER.debug("[" + this.getName() + "] Reading configuration (cosmos_port=" + port + ")" + " -- DEPRECATED, use hdfs_port instead"); } else { port = "14000"; LOGGER.debug("[" + this.getName() + "] Defaulting to hdfs_port=14000"); } String cosmosDefaultUsername = context.getString("cosmos_default_username"); String hdfsUsername = context.getString("hdfs_username"); if (hdfsUsername != null && hdfsUsername.length() > 0) { username = hdfsUsername; LOGGER.debug("[" + this.getName() + "] Reading configuration (hdfs_username=" + username + ")"); } else if (cosmosDefaultUsername != null && cosmosDefaultUsername.length() > 0) { username = cosmosDefaultUsername; LOGGER.debug("[" + this.getName() + "] Reading configuration (cosmos_default_username=" + username + ")" + " -- DEPRECATED, use hdfs_username instead"); } else { LOGGER.error("[" + this.getName() + "] No username provided. Cygnus can continue, but HDFS sink will not " + "properly work!"); } // if else oauth2Token = context.getString("oauth2_token"); if (oauth2Token != null && oauth2Token.length() > 0) { LOGGER.debug("[" + this.getName() + "] Reading configuration (oauth2_token=" + this.oauth2Token + ")"); } else { LOGGER.error("[" + this.getName() + "] No OAuth2 token provided. Cygnus can continue, but HDFS sink may " + "not properly work if WebHDFS service is protected with such an authentication and " + "authorization mechanism!"); } // if else password = context.getString("hdfs_password"); LOGGER.debug("[" + this.getName() + "] Reading configuration (hdfs_password=" + password + ")"); boolean rowAttrPersistenceConfigured = context.getParameters().containsKey("attr_persistence"); boolean fileFormatConfigured = context.getParameters().containsKey("file_format"); if (fileFormatConfigured) { fileFormat = FileFormat.valueOf(context.getString("file_format").replaceAll("-", "").toUpperCase()); LOGGER.debug("[" + this.getName() + "] Reading configuration (file_format=" + fileFormat + ")"); } else if (rowAttrPersistenceConfigured) { boolean rowAttrPersistence = context.getString("attr_persistence").equals("row"); LOGGER.debug("[" + this.getName() + "] Reading configuration (attr_persistence=" + (rowAttrPersistence ? "row" : "column") + ") -- DEPRECATED, converting to file_format=" + (rowAttrPersistence ? "json-row" : "json-column")); fileFormat = (rowAttrPersistence ? FileFormat.JSONROW : FileFormat.JSONCOLUMN); } else { fileFormat = FileFormat.JSONROW; LOGGER.debug("[" + this.getName() + "] Defaulting to file_format=json-row"); } // if else if hiveServerVersion = context.getString("hive_server_version", "2"); LOGGER.debug("[" + this.getName() + "] Reading configuration (hive_server_version=" + hiveServerVersion + ")"); hiveHost = context.getString("hive_host", "localhost"); LOGGER.debug("[" + this.getName() + "] Reading configuration (hive_host=" + hiveHost + ")"); hivePort = context.getString("hive_port", "10000"); LOGGER.debug("[" + this.getName() + "] Reading configuration (hive_port=" + hivePort + ")"); krb5 = context.getBoolean("krb5_auth", false); LOGGER.debug("[" + this.getName() + "] Reading configuration (krb5_auth=" + (krb5 ? "true" : "false") + ")"); krb5User = context.getString("krb5_auth.krb5_user", ""); LOGGER.debug("[" + this.getName() + "] Reading configuration (krb5_user=" + krb5User + ")"); krb5Password = context.getString("krb5_auth.krb5_password", ""); LOGGER.debug("[" + this.getName() + "] Reading configuration (krb5_password=" + krb5Password + ")"); krb5LoginConfFile = context.getString("krb5_auth.krb5_login_conf_file", ""); LOGGER.debug("[" + this.getName() + "] Reading configuration (krb5_login_conf_file=" + krb5LoginConfFile + ")"); krb5ConfFile = context.getString("krb5_auth.krb5_conf_file", ""); LOGGER.debug("[" + this.getName() + "] Reading configuration (krb5_conf_file=" + krb5ConfFile + ")"); serviceAsNamespace = context.getBoolean("service_as_namespace", false); LOGGER.debug("[" + this.getName() + "] Reading configuration (service_as_namespace=" + serviceAsNamespace + ")"); String backendImplStr = context.getString("backend_impl", "rest"); backendImpl = BackendImpl.valueOf(backendImplStr.toUpperCase()); LOGGER.debug("[" + this.getName() + "] Reading configuration (backend_impl=" + backendImplStr + ")"); super.configure(context); } // configure @Override public void start() { try { // create the persistence backend if (backendImpl == BackendImpl.BINARY) { persistenceBackend = new HDFSBackendImplBinary(host, port, username, password, oauth2Token, hiveServerVersion, hiveHost, hivePort, krb5, krb5User, krb5Password, krb5LoginConfFile, krb5ConfFile, serviceAsNamespace); } else if (backendImpl == BackendImpl.REST) { persistenceBackend = new HDFSBackendImplREST(host, port, username, password, oauth2Token, hiveServerVersion, hiveHost, hivePort, krb5, krb5User, krb5Password, krb5LoginConfFile, krb5ConfFile, serviceAsNamespace); } else { LOGGER.fatal("The configured backend implementation does not exist, Cygnus will exit. Details=" + backendImpl.toString()); System.exit(-1); } // if else LOGGER.debug("[" + this.getName() + "] HDFS persistence backend created"); } catch (Exception e) { LOGGER.error(e.getMessage()); } // try catch // try catch super.start(); LOGGER.info("[" + this.getName() + "] Startup completed"); } // start // TBD: to be removed once all the sinks have been migrated to persistBatch method @Override void persistOne(Map<String, String> eventHeaders, NotifyContextRequest notification) throws Exception { throw new Exception("Not yet supoported. You should be using persistBatch method."); } // persistOne @Override void persistBatch(Batch defaultBatch, Batch groupedBatch) throws Exception { // select batch depending on the enable grouping parameter Batch batch = (enableGrouping ? groupedBatch : defaultBatch); if (batch == null) { LOGGER.debug("[" + this.getName() + "] Null batch, nothing to do"); return; } // if // iterate on the destinations, for each one a single create / append will be performed for (String destination : batch.getDestinations()) { LOGGER.debug("[" + this.getName() + "] Processing sub-batch regarding the " + destination + " destination"); // get the sub-batch for this destination ArrayList<CygnusEvent> subBatch = batch.getEvents(destination); // get an aggregator for this destination and initialize it HDFSAggregator aggregator = getAggregator(fileFormat); aggregator.initialize(subBatch.get(0)); for (CygnusEvent cygnusEvent : subBatch) { aggregator.aggregate(cygnusEvent); } // for // persist the aggregation persistAggregation(aggregator); batch.setPersisted(destination); // persist the metadata aggregations only in CSV-like file formats if (fileFormat == FileFormat.CSVROW || fileFormat == FileFormat.CSVCOLUMN) { persistMDAggregations(aggregator); } // if // create the Hive table createHiveTable(aggregator); } // for } // persistBatch /** * Class for aggregating aggregation. */ private abstract class HDFSAggregator { // string containing the data aggregation protected String aggregation; // map containing the HDFS files holding the attribute metadata, one per attribute protected Map<String, String> mdAggregations; protected String service; protected String servicePath; protected String destination; protected String firstLevel; protected String secondLevel; protected String thirdLevel; protected String hdfsFolder; protected String hdfsFile; protected String hiveFields; public HDFSAggregator() { aggregation = ""; mdAggregations = new HashMap<String, String>(); } // HDFSAggregator public String getAggregation() { return aggregation; } // getAggregation public Set<String> getAggregatedAttrMDFiles() { return mdAggregations.keySet(); } // getAggregatedAttrMDFiles public String getMDAggregation(String attrMDFile) { return mdAggregations.get(attrMDFile); } // getMDAggregation public String getFolder() { return hdfsFolder; } // getFolder public String getFile() { return hdfsFile; } // getFile public String getHiveFields() { return hiveFields; } // getHiveFields public void initialize(CygnusEvent cygnusEvent) throws Exception { service = cygnusEvent.getService(); servicePath = cygnusEvent.getServicePath(); destination = cygnusEvent.getDestination(); firstLevel = buildFirstLevel(service); secondLevel = buildSecondLevel(servicePath); thirdLevel = buildThirdLevel(destination); hdfsFolder = firstLevel + "/" + secondLevel + "/" + thirdLevel; hdfsFile = hdfsFolder + "/" + thirdLevel + ".txt"; } // initialize public abstract void aggregate(CygnusEvent cygnusEvent) throws Exception; } // HDFSAggregator /** * Class for aggregating batches in JSON row mode. */ private class JSONRowAggregator extends HDFSAggregator { @Override public void initialize(CygnusEvent cygnusEvent) throws Exception { super.initialize(cygnusEvent); hiveFields = Constants.RECV_TIME_TS + " bigint, " + Constants.RECV_TIME + " string, " + Constants.ENTITY_ID + " string, " + Constants.ENTITY_TYPE + " string, " + Constants.ATTR_NAME + " string, " + Constants.ATTR_TYPE + " string, " + Constants.ATTR_VALUE + " string, " + Constants.ATTR_MD + " array<struct<name:string,type:string,value:string>>"; } // initialize @Override public void aggregate(CygnusEvent cygnusEvent) throws Exception { // get the event headers long recvTimeTs = cygnusEvent.getRecvTimeTs(); String recvTime = Utils.getHumanReadable(recvTimeTs, true); // get the event body ContextElement contextElement = cygnusEvent.getContextElement(); String entityId = contextElement.getId(); String entityType = contextElement.getType(); LOGGER.debug("[" + getName() + "] Processing context element (id=" + entityId + ", type=" + entityType + ")"); // iterate on all this context element attributes, if there are attributes ArrayList<ContextAttribute> contextAttributes = contextElement.getAttributes(); if (contextAttributes == null || contextAttributes.isEmpty()) { LOGGER.warn("No attributes within the notified entity, nothing is done (id=" + entityId + ", type=" + entityType + ")"); return; } // if for (ContextAttribute contextAttribute : contextAttributes) { String attrName = contextAttribute.getName(); String attrType = contextAttribute.getType(); String attrValue = contextAttribute.getContextValue(true); String attrMetadata = contextAttribute.getContextMetadata(); LOGGER.debug("[" + getName() + "] Processing context attribute (name=" + attrName + ", type=" + attrType + ")"); // create a line and aggregate it String line = "{" + "\"" + Constants.RECV_TIME_TS + "\":\"" + recvTimeTs / 1000 + "\"," + "\"" + Constants.RECV_TIME + "\":\"" + recvTime + "\"," + "\"" + Constants.ENTITY_ID + "\":\"" + entityId + "\"," + "\"" + Constants.ENTITY_TYPE + "\":\"" + entityType + "\"," + "\"" + Constants.ATTR_NAME + "\":\"" + attrName + "\"," + "\"" + Constants.ATTR_TYPE + "\":\"" + attrType + "\"," + "\"" + Constants.ATTR_VALUE + "\":" + attrValue + "," + "\"" + Constants.ATTR_MD + "\":" + attrMetadata + "}"; if (aggregation.isEmpty()) { aggregation = line; } else { aggregation += "\n" + line; } // if else } // for } // aggregate } // JSONRowAggregator /** * Class for aggregating batches in JSON column mode. */ private class JSONColumnAggregator extends HDFSAggregator { @Override public void initialize(CygnusEvent cygnusEvent) throws Exception { super.initialize(cygnusEvent); // particular initialization hiveFields = Constants.RECV_TIME + " string"; // iterate on all this context element attributes, if there are attributes ArrayList<ContextAttribute> contextAttributes = cygnusEvent.getContextElement().getAttributes(); if (contextAttributes == null || contextAttributes.isEmpty()) { return; } // if for (ContextAttribute contextAttribute : contextAttributes) { String attrName = contextAttribute.getName(); hiveFields += "," + attrName + " string," + attrName + "_md array<struct<name:string,type:string,value:string>>"; } // for } // initialize @Override public void aggregate(CygnusEvent cygnusEvent) throws Exception { // get the event headers long recvTimeTs = cygnusEvent.getRecvTimeTs(); String recvTime = Utils.getHumanReadable(recvTimeTs, true); // get the event body ContextElement contextElement = cygnusEvent.getContextElement(); String entityId = contextElement.getId(); String entityType = contextElement.getType(); LOGGER.debug("[" + getName() + "] Processing context element (id=" + entityId + ", type=" + entityType + ")"); // iterate on all this context element attributes, if there are attributes ArrayList<ContextAttribute> contextAttributes = contextElement.getAttributes(); if (contextAttributes == null || contextAttributes.isEmpty()) { LOGGER.warn("No attributes within the notified entity, nothing is done (id=" + entityId + ", type=" + entityType + ")"); return; } // if String line = "{\"" + Constants.RECV_TIME + "\":\"" + recvTime + "\""; for (ContextAttribute contextAttribute : contextAttributes) { String attrName = contextAttribute.getName(); String attrType = contextAttribute.getType(); String attrValue = contextAttribute.getContextValue(true); String attrMetadata = contextAttribute.getContextMetadata(); LOGGER.debug("[" + getName() + "] Processing context attribute (name=" + attrName + ", type=" + attrType + ")"); // create part of the line with the current attribute (a.k.a. a column) line += ", \"" + attrName + "\":" + attrValue + ", \"" + attrName + "_md\":" + attrMetadata; } // for // now, aggregate the line if (aggregation.isEmpty()) { aggregation = line + "}"; } else { aggregation += "\n" + line + "}"; } // if else } // aggregate } // JSONColumnAggregator /** * Class for aggregating batches in CSV row mode. */ private class CSVRowAggregator extends HDFSAggregator { @Override public void initialize(CygnusEvent cygnusEvent) throws Exception { super.initialize(cygnusEvent); hiveFields = Constants.RECV_TIME_TS + " bigint, " + Constants.RECV_TIME + " string, " + Constants.ENTITY_ID + " string, " + Constants.ENTITY_TYPE + " string, " + Constants.ATTR_NAME + " string, " + Constants.ATTR_TYPE + " string, " + Constants.ATTR_VALUE + " string, " + Constants.ATTR_MD_FILE + " string"; } // initialize @Override public void aggregate(CygnusEvent cygnusEvent) throws Exception { // get the event headers long recvTimeTs = cygnusEvent.getRecvTimeTs(); String recvTime = Utils.getHumanReadable(recvTimeTs, true); // get the event body ContextElement contextElement = cygnusEvent.getContextElement(); String entityId = contextElement.getId(); String entityType = contextElement.getType(); LOGGER.debug("[" + getName() + "] Processing context element (id=" + entityId + ", type=" + entityType + ")"); // iterate on all this context element attributes, if there are attributes ArrayList<ContextAttribute> contextAttributes = contextElement.getAttributes(); if (contextAttributes == null || contextAttributes.isEmpty()) { LOGGER.warn("No attributes within the notified entity, nothing is done (id=" + entityId + ", type=" + entityType + ")"); return; } // if for (ContextAttribute contextAttribute : contextAttributes) { String attrName = contextAttribute.getName(); String attrType = contextAttribute.getType(); String attrValue = contextAttribute.getContextValue(true); String attrMetadata = contextAttribute.getContextMetadata(); LOGGER.debug("[" + getName() + "] Processing context attribute (name=" + attrName + ", type=" + attrType + ")"); // this has to be done notification by notification and not at initialization since in row mode not all // the notifications contain all the attributes String thirdLevelMd = buildThirdLevelMd(destination, attrName, attrType); String attrMdFolder = firstLevel + "/" + secondLevel + "/" + thirdLevelMd; String attrMdFileName = attrMdFolder + "/" + thirdLevelMd + ".txt"; String printableAttrMdFileName = "hdfs:///user/" + username + "/" + attrMdFileName; String mdAggregation = mdAggregations.get(attrMdFileName); if (mdAggregation == null) { mdAggregation = new String(); } // if // aggregate the metadata String concatMdAggregation; if (mdAggregation.isEmpty()) { concatMdAggregation = getCSVMetadata(attrMetadata, recvTimeTs); } else { concatMdAggregation = mdAggregation.concat("\n" + getCSVMetadata(attrMetadata, recvTimeTs)); } // if else mdAggregations.put(attrMdFileName, concatMdAggregation); // aggreagate the data String line = recvTimeTs / 1000 + "," + recvTime + "," + entityId + "," + entityType + "," + attrName + "," + attrType + "," + attrValue.replaceAll("\"", "") + "," + printableAttrMdFileName; if (aggregation.isEmpty()) { aggregation = line; } else { aggregation += "\n" + line; } // if else } // for } // aggregate private String getCSVMetadata(String attrMetadata, long recvTimeTs) throws Exception { String csvMd = ""; // metadata is in JSON format, decode it JSONParser jsonParser = new JSONParser(); JSONArray attrMetadataJSON = (JSONArray) jsonParser.parse(attrMetadata); // iterate on the metadata for (Object mdObject : attrMetadataJSON) { JSONObject mdJSONObject = (JSONObject) mdObject; String line = recvTimeTs + "," + mdJSONObject.get("name") + "," + mdJSONObject.get("type") + "," + mdJSONObject.get("value"); if (csvMd.isEmpty()) { csvMd = line; } else { csvMd += "\n" + line; } // if else } // for return csvMd; } // getCSVMetadata } // CSVRowAggregator /** * Class for aggregating aggregation in CSV column mode. */ private class CSVColumnAggregator extends HDFSAggregator { @Override public void initialize(CygnusEvent cygnusEvent) throws Exception { super.initialize(cygnusEvent); // particular initialization hiveFields = Constants.RECV_TIME + " string"; // iterate on all this context element attributes; it is supposed all the entity's attributes are notified ArrayList<ContextAttribute> contextAttributes = cygnusEvent.getContextElement().getAttributes(); if (contextAttributes == null || contextAttributes.isEmpty()) { return; } // if for (ContextAttribute contextAttribute : contextAttributes) { String attrName = contextAttribute.getName(); String attrType = contextAttribute.getType(); String thirdLevelMd = buildThirdLevelMd(destination, attrName, attrType); String attrMdFolder = firstLevel + "/" + secondLevel + "/" + thirdLevelMd; String attrMdFileName = attrMdFolder + "/" + thirdLevelMd + ".txt"; mdAggregations.put(attrMdFileName, new String()); hiveFields += "," + attrName + " string," + attrName + "_md_file string"; } // for } // initialize @Override public void aggregate(CygnusEvent cygnusEvent) throws Exception { // get the event headers long recvTimeTs = cygnusEvent.getRecvTimeTs(); String recvTime = Utils.getHumanReadable(recvTimeTs, true); // get the event body ContextElement contextElement = cygnusEvent.getContextElement(); String entityId = contextElement.getId(); String entityType = contextElement.getType(); LOGGER.debug("[" + getName() + "] Processing context element (id=" + entityId + ", type=" + entityType + ")"); // iterate on all this context element attributes, if there are attributes ArrayList<ContextAttribute> contextAttributes = contextElement.getAttributes(); if (contextAttributes == null || contextAttributes.isEmpty()) { LOGGER.warn("No attributes within the notified entity, nothing is done (id=" + entityId + ", type=" + entityType + ")"); return; } // if String line = recvTime; for (ContextAttribute contextAttribute : contextAttributes) { String attrName = contextAttribute.getName(); String attrType = contextAttribute.getType(); String attrValue = contextAttribute.getContextValue(true); String attrMetadata = contextAttribute.getContextMetadata(); LOGGER.debug("[" + getName() + "] Processing context attribute (name=" + attrName + ", type=" + attrType + ")"); // this has to be done notification by notification and not at initialization since in row mode not all // the notifications contain all the attributes String thirdLevelMd = buildThirdLevelMd(destination, attrName, attrType); String attrMdFolder = firstLevel + "/" + secondLevel + "/" + thirdLevelMd; String attrMdFileName = attrMdFolder + "/" + thirdLevelMd + ".txt"; String printableAttrMdFileName = "hdfs:///user/" + username + "/" + attrMdFileName; String mdAggregation = mdAggregations.get(attrMdFileName); if (mdAggregation == null) { mdAggregation = new String(); } // if // agregate the metadata String concatMdAggregation; if (mdAggregation.isEmpty()) { concatMdAggregation = getCSVMetadata(attrMetadata, recvTimeTs); } else { concatMdAggregation = mdAggregation.concat("\n" + getCSVMetadata(attrMetadata, recvTimeTs)); } // if else mdAggregations.put(attrMdFileName, concatMdAggregation); // create part of the line with the current attribute (a.k.a. a column) line += "," + attrValue.replaceAll("\"", "") + "," + printableAttrMdFileName; } // for // now, aggregate the line if (aggregation.isEmpty()) { aggregation = line; } else { aggregation += "\n" + line; } // if else } // aggregate private String getCSVMetadata(String attrMetadata, long recvTimeTs) throws Exception { String csvMd = ""; // metadata is in JSON format, decode it JSONParser jsonParser = new JSONParser(); JSONArray attrMetadataJSON = (JSONArray) jsonParser.parse(attrMetadata); // iterate on the metadata for (Object mdObject : attrMetadataJSON) { JSONObject mdJSONObject = (JSONObject) mdObject; String line = recvTimeTs + "," + mdJSONObject.get("name") + "," + mdJSONObject.get("type") + "," + mdJSONObject.get("value"); if (csvMd.isEmpty()) { csvMd = line; } else { csvMd += "\n" + line; } // if else } // for return csvMd; } // getCSVMetadata } // CSVColumnAggregator private HDFSAggregator getAggregator(FileFormat fileFormat) { switch (fileFormat) { case JSONROW: return new JSONRowAggregator(); case JSONCOLUMN: return new JSONColumnAggregator(); case CSVROW: return new CSVRowAggregator(); case CSVCOLUMN: return new CSVColumnAggregator(); default: return null; } // switch } // getAggregator private void persistAggregation(HDFSAggregator aggregator) throws Exception { String aggregation = aggregator.getAggregation(); String hdfsFolder = aggregator.getFolder(); String hdfsFile = aggregator.getFile(); LOGGER.info("[" + this.getName() + "] Persisting data at OrionHDFSSink. HDFS file (" + hdfsFile + "), Data (" + aggregation + ")"); if (persistenceBackend.exists(hdfsFile)) { persistenceBackend.append(hdfsFile, aggregation); } else { persistenceBackend.createDir(hdfsFolder); persistenceBackend.createFile(hdfsFile, aggregation); } // if else } // persistAggregation private void persistMDAggregations(HDFSAggregator aggregator) throws Exception { Set<String> attrMDFiles = aggregator.getAggregatedAttrMDFiles(); for (String hdfsMDFile : attrMDFiles) { String hdfsMdFolder = hdfsMDFile.substring(0, hdfsMDFile.lastIndexOf("/")); String mdAggregation = aggregator.getMDAggregation(hdfsMDFile); LOGGER.info("[" + this.getName() + "] Persisting metadata at OrionHDFSSink. HDFS file (" + hdfsMDFile + "), Data (" + mdAggregation + ")"); if (persistenceBackend.exists(hdfsMDFile)) { persistenceBackend.append(hdfsMDFile, mdAggregation); } else { persistenceBackend.createDir(hdfsMdFolder); persistenceBackend.createFile(hdfsMDFile, mdAggregation); } // if else } // for } // persistMDAggregations private void createHiveTable(HDFSAggregator aggregator) throws Exception { persistenceBackend.provisionHiveTable(fileFormat, aggregator.getFolder(), aggregator.getHiveFields()); } // createHiveTable /** * Builds the first level of a HDFS path given a fiwareService. It throws an exception if the naming conventions are * violated. * @param fiwareService * @return * @throws Exception */ private String buildFirstLevel(String fiwareService) throws Exception { String firstLevel = fiwareService; if (firstLevel.length() > Constants.MAX_NAME_LEN) { throw new CygnusBadConfiguration("Building firstLevel=fiwareService (fiwareService=" + fiwareService + ") " + "and its length is greater than " + Constants.MAX_NAME_LEN); } // if return firstLevel; } // buildFirstLevel /** * Builds the second level of a HDFS path given given a fiwareService and a destination. It throws an exception if * the naming conventions are violated. * @param fiwareService * @param destination * @return * @throws Exception */ private String buildSecondLevel(String fiwareServicePath) throws Exception { String secondLevel = fiwareServicePath; if (secondLevel.length() > Constants.MAX_NAME_LEN) { throw new CygnusBadConfiguration("Building secondLevel=fiwareServicePath (" + fiwareServicePath + ") and " + "its length is greater than " + Constants.MAX_NAME_LEN); } // if return secondLevel; } // buildSecondLevel /** * Builds the third level of a HDFS path given a destination. It throws an exception if the naming conventions are * violated. * @param destination * @return * @throws Exception */ private String buildThirdLevel(String destination) throws Exception { String thirdLevel = destination; if (thirdLevel.length() > Constants.MAX_NAME_LEN) { throw new CygnusBadConfiguration("Building thirdLevel=destination (" + destination + ") and its length is " + "greater than " + Constants.MAX_NAME_LEN); } // if return thirdLevel; } // buildThirdLevel /** * Builds the third level of a HDFS path given a destination. It throws an exception if the naming conventions are * violated. * @param destination * @return * @throws Exception */ private String buildThirdLevelMd(String destination, String attrName, String attrType) throws Exception { String thirdLevelMd = destination + "_" + attrName + "_" + attrType; if (thirdLevelMd.length() > Constants.MAX_NAME_LEN) { throw new CygnusBadConfiguration("Building thirdLevelMd=" + thirdLevelMd + " and its length is " + "greater than " + Constants.MAX_NAME_LEN); } // if return thirdLevelMd; } // buildThirdLevelMd } // OrionHDFSSink
src/main/java/com/telefonica/iot/cygnus/sinks/OrionHDFSSink.java
/** * Copyright 2015 Telefonica Investigación y Desarrollo, S.A.U * * This file is part of fiware-cygnus (FI-WARE project). * * fiware-cygnus is free software: you can redistribute it and/or modify it under the terms of the GNU Affero * General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your * option) any later version. * fiware-cygnus is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the * implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License * for more details. * * You should have received a copy of the GNU Affero General Public License along with fiware-cygnus. If not, see * http://www.gnu.org/licenses/. * * For those usages not covered by the GNU Affero General Public License please contact with iot_support at tid dot es */ package com.telefonica.iot.cygnus.sinks; import com.telefonica.iot.cygnus.backends.hdfs.HDFSBackend; import com.telefonica.iot.cygnus.backends.hdfs.HDFSBackend.FileFormat; import static com.telefonica.iot.cygnus.backends.hdfs.HDFSBackend.FileFormat.CSVCOLUMN; import static com.telefonica.iot.cygnus.backends.hdfs.HDFSBackend.FileFormat.CSVROW; import static com.telefonica.iot.cygnus.backends.hdfs.HDFSBackend.FileFormat.JSONCOLUMN; import static com.telefonica.iot.cygnus.backends.hdfs.HDFSBackend.FileFormat.JSONROW; import com.telefonica.iot.cygnus.backends.hdfs.HDFSBackendImplBinary; import com.telefonica.iot.cygnus.backends.hdfs.HDFSBackendImplREST; import com.telefonica.iot.cygnus.containers.NotifyContextRequest; import com.telefonica.iot.cygnus.containers.NotifyContextRequest.ContextAttribute; import com.telefonica.iot.cygnus.containers.NotifyContextRequest.ContextElement; import com.telefonica.iot.cygnus.errors.CygnusBadConfiguration; import com.telefonica.iot.cygnus.log.CygnusLogger; import com.telefonica.iot.cygnus.utils.Constants; import com.telefonica.iot.cygnus.utils.Utils; import java.util.ArrayList; import java.util.Arrays; import java.util.HashMap; import java.util.Map; import java.util.Set; import org.apache.flume.Context; import org.json.simple.JSONArray; import org.json.simple.JSONObject; import org.json.simple.parser.JSONParser; /** * * @author frb * * Detailed documentation can be found at: * https://github.com/telefonicaid/fiware-cygnus/blob/master/doc/design/OrionHDFSSink.md */ public class OrionHDFSSink extends OrionSink { /** * Available backend implementation. */ public enum BackendImpl { BINARY, REST } private static final CygnusLogger LOGGER = new CygnusLogger(OrionHDFSSink.class); private String[] host; private String port; private String username; private String password; private FileFormat fileFormat; private String oauth2Token; private String hiveServerVersion; private String hiveHost; private String hivePort; private boolean krb5; private String krb5User; private String krb5Password; private String krb5LoginConfFile; private String krb5ConfFile; private boolean serviceAsNamespace; private BackendImpl backendImpl; private HDFSBackend persistenceBackend; /** * Constructor. */ public OrionHDFSSink() { super(); } // OrionHDFSSink /** * Gets the Cosmos host. It is protected due to it is only required for testing purposes. * @return The Cosmos host */ protected String[] getHDFSHosts() { return host; } // getHDFSHosts /** * Gets the Cosmos port. It is protected due to it is only required for testing purposes. * @return The Cosmos port */ protected String getHDFSPort() { return port; } // getHDFSPort /** * Gets the default Cosmos username. It is protected due to it is only required for testing purposes. * @return The default Cosmos username */ protected String getHDFSUsername() { return username; } // getHDFSUsername /** * Gets the password for the default Cosmos username. It is protected due to it is only required for testing * purposes. * @return The password for the default Cosmos username */ protected String getHDFSPassword() { return password; } // getHDFSPassword /** * Gets the OAuth2 token used for authentication and authorization. It is protected due to it is only required * for testing purposes. * @return The Cosmos oauth2Token for the detault Cosmos username */ protected String getOAuth2Token() { return oauth2Token; } // getOAuth2Token /** * Returns if the service is used as HDFS namespace. It is protected due to it is only required for testing * purposes. * @return "true" if the service is used as HDFS namespace, "false" otherwise. */ protected String getServiceAsNamespace() { return (serviceAsNamespace ? "true" : "false"); } // getServiceAsNamespace /** * Gets the file format. It is protected due to it is only required for testing purposes. * @return The file format */ protected String getFileFormat() { switch (fileFormat) { case JSONROW: return "json-row"; case JSONCOLUMN: return "json-column"; case CSVROW: return "csv-row"; case CSVCOLUMN: return "csv-column"; default: return ""; } // switch; } // getFileFormat /** * Gets the Hive server version. It is protected due to it is only required for testing purposes. * @return The Hive server version */ protected String getHiveServerVersion() { return hiveServerVersion; } // getHiveServerVersion /** * Gets the Hive host. It is protected due to it is only required for testing purposes. * @return The Hive port */ protected String getHiveHost() { return hiveHost; } // getHiveHost /** * Gets the Hive port. It is protected due to it is only required for testing purposes. * @return The Hive port */ protected String getHivePort() { return hivePort; } // getHivePort /** * Returns if Kerberos is being used for authenticacion. It is protected due to it is only required for testing * purposes. * @return "true" if Kerberos is being used for authentication, otherwise "false" */ protected String getKrb5Auth() { return (krb5 ? "true" : "false"); } // getKrb5Auth /** * Returns the persistence backend. It is protected due to it is only required for testing purposes. * @return The persistence backend */ protected HDFSBackend getPersistenceBackend() { return persistenceBackend; } // getPersistenceBackend /** * Sets the persistence backend. It is protected due to it is only required for testing purposes. * @param persistenceBackend */ protected void setPersistenceBackend(HDFSBackendImplREST persistenceBackend) { this.persistenceBackend = persistenceBackend; } // setPersistenceBackend @Override public void configure(Context context) { String cosmosHost = context.getString("cosmos_host"); String hdfsHost = context.getString("hdfs_host"); if (hdfsHost != null && hdfsHost.length() > 0) { host = hdfsHost.split(","); LOGGER.debug("[" + this.getName() + "] Reading configuration (hdfs_host=" + Arrays.toString(host) + ")"); } else if (cosmosHost != null && cosmosHost.length() > 0) { host = cosmosHost.split(","); LOGGER.debug("[" + this.getName() + "] Reading configuration (cosmos_host=" + Arrays.toString(host) + ")" + " -- DEPRECATED, use hdfs_host instead"); } else { host = new String[]{"localhost"}; LOGGER.debug("[" + this.getName() + "] Defaulting to hdfs_host=localhost"); } // if else String cosmosPort = context.getString("cosmos_port"); String hdfsPort = context.getString("hdfs_port"); if (hdfsPort != null && hdfsPort.length() > 0) { port = hdfsPort; LOGGER.debug("[" + this.getName() + "] Reading configuration (hdfs_port=" + port + ")"); } else if (cosmosPort != null && cosmosPort.length() > 0) { port = cosmosPort; LOGGER.debug("[" + this.getName() + "] Reading configuration (cosmos_port=" + port + ")" + " -- DEPRECATED, use hdfs_port instead"); } else { port = "14000"; LOGGER.debug("[" + this.getName() + "] Defaulting to hdfs_port=14000"); } String cosmosDefaultUsername = context.getString("cosmos_default_username"); String hdfsUsername = context.getString("hdfs_username"); if (hdfsUsername != null && hdfsUsername.length() > 0) { username = hdfsUsername; LOGGER.debug("[" + this.getName() + "] Reading configuration (hdfs_username=" + username + ")"); } else if (cosmosDefaultUsername != null && cosmosDefaultUsername.length() > 0) { username = cosmosDefaultUsername; LOGGER.debug("[" + this.getName() + "] Reading configuration (cosmos_default_username=" + username + ")" + " -- DEPRECATED, use hdfs_username instead"); } else { LOGGER.error("[" + this.getName() + "] No username provided. Cygnus can continue, but HDFS sink will not " + "properly work!"); } // if else oauth2Token = context.getString("oauth2_token"); if (oauth2Token != null && oauth2Token.length() > 0) { LOGGER.debug("[" + this.getName() + "] Reading configuration (oauth2_token=" + this.oauth2Token + ")"); } else { LOGGER.error("[" + this.getName() + "] No OAuth2 token provided. Cygnus can continue, but HDFS sink may " + "not properly work if WebHDFS service is protected with such an authentication and " + "authorization mechanism!"); } // if else password = context.getString("hdfs_password"); LOGGER.debug("[" + this.getName() + "] Reading configuration (hdfs_password=" + password + ")"); boolean rowAttrPersistenceConfigured = context.getParameters().containsKey("attr_persistence"); boolean fileFormatConfigured = context.getParameters().containsKey("file_format"); if (fileFormatConfigured) { fileFormat = FileFormat.valueOf(context.getString("file_format").replaceAll("-", "").toUpperCase()); LOGGER.debug("[" + this.getName() + "] Reading configuration (file_format=" + fileFormat + ")"); } else if (rowAttrPersistenceConfigured) { boolean rowAttrPersistence = context.getString("attr_persistence").equals("row"); LOGGER.debug("[" + this.getName() + "] Reading configuration (attr_persistence=" + (rowAttrPersistence ? "row" : "column") + ") -- DEPRECATED, converting to file_format=" + (rowAttrPersistence ? "json-row" : "json-column")); fileFormat = (rowAttrPersistence ? FileFormat.JSONROW : FileFormat.JSONCOLUMN); } else { fileFormat = FileFormat.JSONROW; LOGGER.debug("[" + this.getName() + "] Defaulting to file_format=json-row"); } // if else if hiveServerVersion = context.getString("hive_server_version", "2"); LOGGER.debug("[" + this.getName() + "] Reading configuration (hive_server_version=" + hiveServerVersion + ")"); hiveHost = context.getString("hive_host", "localhost"); LOGGER.debug("[" + this.getName() + "] Reading configuration (hive_host=" + hiveHost + ")"); hivePort = context.getString("hive_port", "10000"); LOGGER.debug("[" + this.getName() + "] Reading configuration (hive_port=" + hivePort + ")"); krb5 = context.getBoolean("krb5_auth", false); LOGGER.debug("[" + this.getName() + "] Reading configuration (krb5_auth=" + (krb5 ? "true" : "false") + ")"); krb5User = context.getString("krb5_auth.krb5_user", ""); LOGGER.debug("[" + this.getName() + "] Reading configuration (krb5_user=" + krb5User + ")"); krb5Password = context.getString("krb5_auth.krb5_password", ""); LOGGER.debug("[" + this.getName() + "] Reading configuration (krb5_password=" + krb5Password + ")"); krb5LoginConfFile = context.getString("krb5_auth.krb5_login_conf_file", ""); LOGGER.debug("[" + this.getName() + "] Reading configuration (krb5_login_conf_file=" + krb5LoginConfFile + ")"); krb5ConfFile = context.getString("krb5_auth.krb5_conf_file", ""); LOGGER.debug("[" + this.getName() + "] Reading configuration (krb5_conf_file=" + krb5ConfFile + ")"); serviceAsNamespace = context.getBoolean("service_as_namespace", false); LOGGER.debug("[" + this.getName() + "] Reading configuration (service_as_namespace=" + serviceAsNamespace + ")"); String backendImplStr = context.getString("backend_impl", "rest"); backendImpl = BackendImpl.valueOf(backendImplStr.toUpperCase()); LOGGER.debug("[" + this.getName() + "] Reading configuration (backend_impl=" + backendImplStr + ")"); super.configure(context); } // configure @Override public void start() { try { // create the persistence backend if (backendImpl == BackendImpl.BINARY) { persistenceBackend = new HDFSBackendImplBinary(host, port, username, password, oauth2Token, hiveServerVersion, hiveHost, hivePort, krb5, krb5User, krb5Password, krb5LoginConfFile, krb5ConfFile, serviceAsNamespace); } else if (backendImpl == BackendImpl.REST) { persistenceBackend = new HDFSBackendImplREST(host, port, username, password, oauth2Token, hiveServerVersion, hiveHost, hivePort, krb5, krb5User, krb5Password, krb5LoginConfFile, krb5ConfFile, serviceAsNamespace); } else { LOGGER.fatal("The configured backend implementation does not exist, Cygnus will exit. Details=" + backendImpl.toString()); System.exit(-1); } // if else LOGGER.debug("[" + this.getName() + "] HDFS persistence backend created"); } catch (Exception e) { LOGGER.error(e.getMessage()); } // try catch // try catch super.start(); LOGGER.info("[" + this.getName() + "] Startup completed"); } // start // TBD: to be removed once all the sinks have been migrated to persistBatch method @Override void persistOne(Map<String, String> eventHeaders, NotifyContextRequest notification) throws Exception { throw new Exception("Not yet supoported. You should be using persistBatch method."); } // persistOne @Override void persistBatch(Batch defaultBatch, Batch groupedBatch) throws Exception { // select batch depending on the enable grouping parameter Batch batch = (enableGrouping ? groupedBatch : defaultBatch); if (batch == null) { LOGGER.debug("[" + this.getName() + "] Null batch, nothing to do"); return; } // if // iterate on the destinations, for each one a single create / append will be performed for (String destination : batch.getDestinations()) { LOGGER.debug("[" + this.getName() + "] Processing sub-batch regarding the " + destination + " destination"); // get the sub-batch for this destination ArrayList<CygnusEvent> subBatch = batch.getEvents(destination); // get an aggregator for this destination and initialize it HDFSAggregator aggregator = getAggregator(fileFormat); aggregator.initialize(subBatch.get(0)); for (CygnusEvent cygnusEvent : subBatch) { aggregator.aggregate(cygnusEvent); } // for // persist the aggregation persistAggregation(aggregator); batch.setPersisted(destination); // persist the metadata aggregations only in CSV-like file formats if (fileFormat == FileFormat.CSVROW || fileFormat == FileFormat.CSVCOLUMN) { persistMDAggregations(aggregator); } // if // create the Hive table createHiveTable(aggregator); } // for } // persistBatch /** * Class for aggregating aggregation. */ private abstract class HDFSAggregator { // string containing the data aggregation protected String aggregation; // map containing the HDFS files holding the attribute metadata, one per attribute protected Map<String, String> mdAggregations; protected String service; protected String servicePath; protected String destination; protected String firstLevel; protected String secondLevel; protected String thirdLevel; protected String hdfsFolder; protected String hdfsFile; protected String hiveFields; public HDFSAggregator() { aggregation = ""; mdAggregations = new HashMap<String, String>(); } // HDFSAggregator public String getAggregation() { return aggregation; } // getAggregation public Set<String> getAggregatedAttrMDFiles() { return mdAggregations.keySet(); } // getAggregatedAttrMDFiles public String getMDAggregation(String attrMDFile) { return mdAggregations.get(attrMDFile); } // getMDAggregation public String getFolder() { return hdfsFolder; } // getFolder public String getFile() { return hdfsFile; } // getFile public String getHiveFields() { return hiveFields; } // getHiveFields public void initialize(CygnusEvent cygnusEvent) throws Exception { service = cygnusEvent.getService(); servicePath = cygnusEvent.getServicePath(); destination = cygnusEvent.getDestination(); firstLevel = buildFirstLevel(service); secondLevel = buildSecondLevel(servicePath); thirdLevel = buildThirdLevel(destination); hdfsFolder = firstLevel + "/" + secondLevel + "/" + thirdLevel; hdfsFile = hdfsFolder + "/" + thirdLevel + ".txt"; } // initialize public abstract void aggregate(CygnusEvent cygnusEvent) throws Exception; } // HDFSAggregator /** * Class for aggregating batches in JSON row mode. */ private class JSONRowAggregator extends HDFSAggregator { @Override public void initialize(CygnusEvent cygnusEvent) throws Exception { super.initialize(cygnusEvent); hiveFields = Constants.RECV_TIME_TS + " bigint, " + Constants.RECV_TIME + " string, " + Constants.ENTITY_ID + " string, " + Constants.ENTITY_TYPE + " string, " + Constants.ATTR_NAME + " string, " + Constants.ATTR_TYPE + " string, " + Constants.ATTR_VALUE + " string, " + Constants.ATTR_MD + " array<struct<name:string,type:string,value:string>>"; } // initialize @Override public void aggregate(CygnusEvent cygnusEvent) throws Exception { // get the event headers long recvTimeTs = cygnusEvent.getRecvTimeTs(); String recvTime = Utils.getHumanReadable(recvTimeTs, true); // get the event body ContextElement contextElement = cygnusEvent.getContextElement(); String entityId = contextElement.getId(); String entityType = contextElement.getType(); LOGGER.debug("[" + getName() + "] Processing context element (id=" + entityId + ", type=" + entityType + ")"); // iterate on all this context element attributes, if there are attributes ArrayList<ContextAttribute> contextAttributes = contextElement.getAttributes(); if (contextAttributes == null || contextAttributes.isEmpty()) { LOGGER.warn("No attributes within the notified entity, nothing is done (id=" + entityId + ", type=" + entityType + ")"); return; } // if for (ContextAttribute contextAttribute : contextAttributes) { String attrName = contextAttribute.getName(); String attrType = contextAttribute.getType(); String attrValue = contextAttribute.getContextValue(true); String attrMetadata = contextAttribute.getContextMetadata(); LOGGER.debug("[" + getName() + "] Processing context attribute (name=" + attrName + ", type=" + attrType + ")"); // create a line and aggregate it String line = "{" + "\"" + Constants.RECV_TIME_TS + "\":\"" + recvTimeTs / 1000 + "\"," + "\"" + Constants.RECV_TIME + "\":\"" + recvTime + "\"," + "\"" + Constants.ENTITY_ID + "\":\"" + entityId + "\"," + "\"" + Constants.ENTITY_TYPE + "\":\"" + entityType + "\"," + "\"" + Constants.ATTR_NAME + "\":\"" + attrName + "\"," + "\"" + Constants.ATTR_TYPE + "\":\"" + attrType + "\"," + "\"" + Constants.ATTR_VALUE + "\":" + attrValue + "," + "\"" + Constants.ATTR_MD + "\":" + attrMetadata + "}"; if (aggregation.isEmpty()) { aggregation = line; } else { aggregation += "\n" + line; } // if else } // for } // aggregate } // JSONRowAggregator /** * Class for aggregating batches in JSON column mode. */ private class JSONColumnAggregator extends HDFSAggregator { @Override public void initialize(CygnusEvent cygnusEvent) throws Exception { super.initialize(cygnusEvent); // particular initialization hiveFields = Constants.RECV_TIME + " string"; // iterate on all this context element attributes, if there are attributes ArrayList<ContextAttribute> contextAttributes = cygnusEvent.getContextElement().getAttributes(); if (contextAttributes == null || contextAttributes.isEmpty()) { return; } // if for (ContextAttribute contextAttribute : contextAttributes) { String attrName = contextAttribute.getName(); hiveFields += "," + attrName + " string," + attrName + "_md array<struct<name:string,type:string,value:string>>"; } // for } // initialize @Override public void aggregate(CygnusEvent cygnusEvent) throws Exception { // get the event headers long recvTimeTs = cygnusEvent.getRecvTimeTs(); String recvTime = Utils.getHumanReadable(recvTimeTs, true); // get the event body ContextElement contextElement = cygnusEvent.getContextElement(); String entityId = contextElement.getId(); String entityType = contextElement.getType(); LOGGER.debug("[" + getName() + "] Processing context element (id=" + entityId + ", type=" + entityType + ")"); // iterate on all this context element attributes, if there are attributes ArrayList<ContextAttribute> contextAttributes = contextElement.getAttributes(); if (contextAttributes == null || contextAttributes.isEmpty()) { LOGGER.warn("No attributes within the notified entity, nothing is done (id=" + entityId + ", type=" + entityType + ")"); return; } // if String line = "{\"" + Constants.RECV_TIME + "\":\"" + recvTime + "\""; for (ContextAttribute contextAttribute : contextAttributes) { String attrName = contextAttribute.getName(); String attrType = contextAttribute.getType(); String attrValue = contextAttribute.getContextValue(true); String attrMetadata = contextAttribute.getContextMetadata(); LOGGER.debug("[" + getName() + "] Processing context attribute (name=" + attrName + ", type=" + attrType + ")"); // create part of the line with the current attribute (a.k.a. a column) line += ", \"" + attrName + "\":" + attrValue + ", \"" + attrName + "_md\":" + attrMetadata; } // for // now, aggregate the line if (aggregation.isEmpty()) { aggregation = line + "}"; } else { aggregation += "\n" + line + "}"; } // if else } // aggregate } // JSONColumnAggregator /** * Class for aggregating batches in CSV row mode. */ private class CSVRowAggregator extends HDFSAggregator { @Override public void initialize(CygnusEvent cygnusEvent) throws Exception { super.initialize(cygnusEvent); hiveFields = Constants.RECV_TIME_TS + " bigint, " + Constants.RECV_TIME + " string, " + Constants.ENTITY_ID + " string, " + Constants.ENTITY_TYPE + " string, " + Constants.ATTR_NAME + " string, " + Constants.ATTR_TYPE + " string, " + Constants.ATTR_VALUE + " string, " + Constants.ATTR_MD_FILE + " string"; } // initialize @Override public void aggregate(CygnusEvent cygnusEvent) throws Exception { // get the event headers long recvTimeTs = cygnusEvent.getRecvTimeTs(); String recvTime = Utils.getHumanReadable(recvTimeTs, true); // get the event body ContextElement contextElement = cygnusEvent.getContextElement(); String entityId = contextElement.getId(); String entityType = contextElement.getType(); LOGGER.debug("[" + getName() + "] Processing context element (id=" + entityId + ", type=" + entityType + ")"); // iterate on all this context element attributes, if there are attributes ArrayList<ContextAttribute> contextAttributes = contextElement.getAttributes(); if (contextAttributes == null || contextAttributes.isEmpty()) { LOGGER.warn("No attributes within the notified entity, nothing is done (id=" + entityId + ", type=" + entityType + ")"); return; } // if for (ContextAttribute contextAttribute : contextAttributes) { String attrName = contextAttribute.getName(); String attrType = contextAttribute.getType(); String attrValue = contextAttribute.getContextValue(true); String attrMetadata = contextAttribute.getContextMetadata(); LOGGER.debug("[" + getName() + "] Processing context attribute (name=" + attrName + ", type=" + attrType + ")"); // this has to be done notification by notification and not at initialization since in row mode not all // the notifications contain all the attributes String thirdLevelMd = buildThirdLevelMd(destination, attrName, attrType); String attrMdFolder = firstLevel + "/" + secondLevel + "/" + thirdLevelMd; String attrMdFileName = attrMdFolder + "/" + thirdLevelMd + ".txt"; String printableAttrMdFileName = "hdfs:///user/" + username + "/" + attrMdFileName; String mdAggregation = mdAggregations.get(attrMdFileName); if (mdAggregation == null) { mdAggregation = new String(); } // if // aggregate the metadata String concatMdAggregation = mdAggregation.concat(getCSVMetadata(attrMetadata, recvTimeTs)); mdAggregations.put(attrMdFileName, concatMdAggregation); // aggreagate the data String line = recvTimeTs / 1000 + "," + recvTime + "," + entityId + "," + entityType + "," + attrName + "," + attrType + "," + attrValue.replaceAll("\"", "") + "," + printableAttrMdFileName; if (aggregation.isEmpty()) { aggregation = line; } else { aggregation += "\n" + line; } // if else } // for } // aggregate private String getCSVMetadata(String attrMetadata, long recvTimeTs) throws Exception { String csvMd = ""; // metadata is in JSON format, decode it JSONParser jsonParser = new JSONParser(); JSONArray attrMetadataJSON = (JSONArray) jsonParser.parse(attrMetadata); // iterate on the metadata for (Object mdObject : attrMetadataJSON) { JSONObject mdJSONObject = (JSONObject) mdObject; csvMd += recvTimeTs + "," + mdJSONObject.get("name") + "," + mdJSONObject.get("type") + "," + mdJSONObject.get("value"); } // for return csvMd; } // getCSVMetadata } // CSVRowAggregator /** * Class for aggregating aggregation in CSV column mode. */ private class CSVColumnAggregator extends HDFSAggregator { @Override public void initialize(CygnusEvent cygnusEvent) throws Exception { super.initialize(cygnusEvent); // particular initialization hiveFields = Constants.RECV_TIME + " string"; // iterate on all this context element attributes; it is supposed all the entity's attributes are notified ArrayList<ContextAttribute> contextAttributes = cygnusEvent.getContextElement().getAttributes(); if (contextAttributes == null || contextAttributes.isEmpty()) { return; } // if for (ContextAttribute contextAttribute : contextAttributes) { String attrName = contextAttribute.getName(); String attrType = contextAttribute.getType(); String thirdLevelMd = buildThirdLevelMd(destination, attrName, attrType); String attrMdFolder = firstLevel + "/" + secondLevel + "/" + thirdLevelMd; String attrMdFileName = attrMdFolder + "/" + thirdLevelMd + ".txt"; mdAggregations.put(attrMdFileName, new String()); hiveFields += "," + attrName + " string," + attrName + "_md_file string"; } // for } // initialize @Override public void aggregate(CygnusEvent cygnusEvent) throws Exception { // get the event headers long recvTimeTs = cygnusEvent.getRecvTimeTs(); String recvTime = Utils.getHumanReadable(recvTimeTs, true); // get the event body ContextElement contextElement = cygnusEvent.getContextElement(); String entityId = contextElement.getId(); String entityType = contextElement.getType(); LOGGER.debug("[" + getName() + "] Processing context element (id=" + entityId + ", type=" + entityType + ")"); // iterate on all this context element attributes, if there are attributes ArrayList<ContextAttribute> contextAttributes = contextElement.getAttributes(); if (contextAttributes == null || contextAttributes.isEmpty()) { LOGGER.warn("No attributes within the notified entity, nothing is done (id=" + entityId + ", type=" + entityType + ")"); return; } // if String line = recvTime; for (ContextAttribute contextAttribute : contextAttributes) { String attrName = contextAttribute.getName(); String attrType = contextAttribute.getType(); String attrValue = contextAttribute.getContextValue(true); String attrMetadata = contextAttribute.getContextMetadata(); LOGGER.debug("[" + getName() + "] Processing context attribute (name=" + attrName + ", type=" + attrType + ")"); // this has to be done notification by notification and not at initialization since in row mode not all // the notifications contain all the attributes String thirdLevelMd = buildThirdLevelMd(destination, attrName, attrType); String attrMdFolder = firstLevel + "/" + secondLevel + "/" + thirdLevelMd; String attrMdFileName = attrMdFolder + "/" + thirdLevelMd + ".txt"; String printableAttrMdFileName = "hdfs:///user/" + username + "/" + attrMdFileName; String mdAggregation = mdAggregations.get(attrMdFileName); if (mdAggregation == null) { mdAggregation = new String(); } // if // agregate the metadata String concatMdAggregation = mdAggregation.concat(getCSVMetadata(attrMetadata, recvTimeTs)); mdAggregations.put(attrMdFileName, concatMdAggregation); // create part of the line with the current attribute (a.k.a. a column) line += "," + attrValue.replaceAll("\"", "") + "," + printableAttrMdFileName; } // for // now, aggregate the line if (aggregation.isEmpty()) { aggregation = line; } else { aggregation += "\n" + line; } // if else } // aggregate private String getCSVMetadata(String attrMetadata, long recvTimeTs) throws Exception { String csvMd = ""; // metadata is in JSON format, decode it JSONParser jsonParser = new JSONParser(); JSONArray attrMetadataJSON = (JSONArray) jsonParser.parse(attrMetadata); // iterate on the metadata for (Object mdObject : attrMetadataJSON) { JSONObject mdJSONObject = (JSONObject) mdObject; csvMd += recvTimeTs + "," + mdJSONObject.get("name") + "," + mdJSONObject.get("type") + "," + mdJSONObject.get("value"); } // for return csvMd; } // getCSVMetadata } // CSVColumnAggregator private HDFSAggregator getAggregator(FileFormat fileFormat) { switch (fileFormat) { case JSONROW: return new JSONRowAggregator(); case JSONCOLUMN: return new JSONColumnAggregator(); case CSVROW: return new CSVRowAggregator(); case CSVCOLUMN: return new CSVColumnAggregator(); default: return null; } // switch } // getAggregator private void persistAggregation(HDFSAggregator aggregator) throws Exception { String aggregation = aggregator.getAggregation(); String hdfsFolder = aggregator.getFolder(); String hdfsFile = aggregator.getFile(); LOGGER.info("[" + this.getName() + "] Persisting data at OrionHDFSSink. HDFS file (" + hdfsFile + "), Data (" + aggregation + ")"); if (persistenceBackend.exists(hdfsFile)) { persistenceBackend.append(hdfsFile, aggregation); } else { persistenceBackend.createDir(hdfsFolder); persistenceBackend.createFile(hdfsFile, aggregation); } // if else } // persistAggregation private void persistMDAggregations(HDFSAggregator aggregator) throws Exception { Set<String> attrMDFiles = aggregator.getAggregatedAttrMDFiles(); for (String hdfsMDFile : attrMDFiles) { String hdfsMdFolder = hdfsMDFile.substring(0, hdfsMDFile.lastIndexOf("/")); String mdAggregation = aggregator.getMDAggregation(hdfsMDFile); LOGGER.info("[" + this.getName() + "] Persisting metadata at OrionHDFSSink. HDFS file (" + hdfsMDFile + "), Data (" + mdAggregation + ")"); if (persistenceBackend.exists(hdfsMDFile)) { persistenceBackend.append(hdfsMDFile, mdAggregation); } else { persistenceBackend.createDir(hdfsMdFolder); persistenceBackend.createFile(hdfsMDFile, mdAggregation); } // if else } // for } // persistMDAggregations private void createHiveTable(HDFSAggregator aggregator) throws Exception { persistenceBackend.provisionHiveTable(fileFormat, aggregator.getFolder(), aggregator.getHiveFields()); } // createHiveTable /** * Builds the first level of a HDFS path given a fiwareService. It throws an exception if the naming conventions are * violated. * @param fiwareService * @return * @throws Exception */ private String buildFirstLevel(String fiwareService) throws Exception { String firstLevel = fiwareService; if (firstLevel.length() > Constants.MAX_NAME_LEN) { throw new CygnusBadConfiguration("Building firstLevel=fiwareService (fiwareService=" + fiwareService + ") " + "and its length is greater than " + Constants.MAX_NAME_LEN); } // if return firstLevel; } // buildFirstLevel /** * Builds the second level of a HDFS path given given a fiwareService and a destination. It throws an exception if * the naming conventions are violated. * @param fiwareService * @param destination * @return * @throws Exception */ private String buildSecondLevel(String fiwareServicePath) throws Exception { String secondLevel = fiwareServicePath; if (secondLevel.length() > Constants.MAX_NAME_LEN) { throw new CygnusBadConfiguration("Building secondLevel=fiwareServicePath (" + fiwareServicePath + ") and " + "its length is greater than " + Constants.MAX_NAME_LEN); } // if return secondLevel; } // buildSecondLevel /** * Builds the third level of a HDFS path given a destination. It throws an exception if the naming conventions are * violated. * @param destination * @return * @throws Exception */ private String buildThirdLevel(String destination) throws Exception { String thirdLevel = destination; if (thirdLevel.length() > Constants.MAX_NAME_LEN) { throw new CygnusBadConfiguration("Building thirdLevel=destination (" + destination + ") and its length is " + "greater than " + Constants.MAX_NAME_LEN); } // if return thirdLevel; } // buildThirdLevel /** * Builds the third level of a HDFS path given a destination. It throws an exception if the naming conventions are * violated. * @param destination * @return * @throws Exception */ private String buildThirdLevelMd(String destination, String attrName, String attrType) throws Exception { String thirdLevelMd = destination + "_" + attrName + "_" + attrType; if (thirdLevelMd.length() > Constants.MAX_NAME_LEN) { throw new CygnusBadConfiguration("Building thirdLevelMd=" + thirdLevelMd + " and its length is " + "greater than " + Constants.MAX_NAME_LEN); } // if return thirdLevelMd; } // buildThirdLevelMd } // OrionHDFSSink
FIX the metadata aggregation in CSV-like modes
src/main/java/com/telefonica/iot/cygnus/sinks/OrionHDFSSink.java
FIX the metadata aggregation in CSV-like modes
<ide><path>rc/main/java/com/telefonica/iot/cygnus/sinks/OrionHDFSSink.java <ide> } // if <ide> <ide> // aggregate the metadata <del> String concatMdAggregation = mdAggregation.concat(getCSVMetadata(attrMetadata, recvTimeTs)); <add> String concatMdAggregation; <add> <add> if (mdAggregation.isEmpty()) { <add> concatMdAggregation = getCSVMetadata(attrMetadata, recvTimeTs); <add> } else { <add> concatMdAggregation = mdAggregation.concat("\n" + getCSVMetadata(attrMetadata, recvTimeTs)); <add> } // if else <add> <ide> mdAggregations.put(attrMdFileName, concatMdAggregation); <ide> <ide> // aggreagate the data <ide> // iterate on the metadata <ide> for (Object mdObject : attrMetadataJSON) { <ide> JSONObject mdJSONObject = (JSONObject) mdObject; <del> csvMd += recvTimeTs + "," <add> String line = recvTimeTs + "," <ide> + mdJSONObject.get("name") + "," <ide> + mdJSONObject.get("type") + "," <ide> + mdJSONObject.get("value"); <add> <add> if (csvMd.isEmpty()) { <add> csvMd = line; <add> } else { <add> csvMd += "\n" + line; <add> } // if else <ide> } // for <ide> <ide> return csvMd; <ide> } // if <ide> <ide> // agregate the metadata <del> String concatMdAggregation = mdAggregation.concat(getCSVMetadata(attrMetadata, recvTimeTs)); <add> String concatMdAggregation; <add> <add> if (mdAggregation.isEmpty()) { <add> concatMdAggregation = getCSVMetadata(attrMetadata, recvTimeTs); <add> } else { <add> concatMdAggregation = mdAggregation.concat("\n" + getCSVMetadata(attrMetadata, recvTimeTs)); <add> } // if else <add> <ide> mdAggregations.put(attrMdFileName, concatMdAggregation); <ide> <ide> // create part of the line with the current attribute (a.k.a. a column) <ide> // iterate on the metadata <ide> for (Object mdObject : attrMetadataJSON) { <ide> JSONObject mdJSONObject = (JSONObject) mdObject; <del> csvMd += recvTimeTs + "," <add> String line = recvTimeTs + "," <ide> + mdJSONObject.get("name") + "," <ide> + mdJSONObject.get("type") + "," <ide> + mdJSONObject.get("value"); <add> <add> if (csvMd.isEmpty()) { <add> csvMd = line; <add> } else { <add> csvMd += "\n" + line; <add> } // if else <ide> } // for <ide> <ide> return csvMd;
Java
apache-2.0
11253c28b8f3fa86fc69920b91214005a2c56a0c
0
nordapp/rest
package org.i3xx.util.ctree.parser; import java.io.IOException; import java.util.Map; import java.util.regex.Pattern; import org.i3xx.util.ctree.IConfNode; import org.i3xx.util.ctree.core.IResolverFactory; import org.i3xx.util.ctree.impl.NodeParser; import org.slf4j.Logger; import org.slf4j.LoggerFactory; public class KeyValueRuleProcessLine extends AbstractKeyValueRule { private static final Logger logger = LoggerFactory.getLogger(KeyValueRuleProcessLine.class); // public static final Pattern separator = Pattern.compile("\\s*[\\s|=]\\s*"); protected IConfNode root; private NodeParser nParser; public KeyValueRuleProcessLine(IConfNode root, IResolverFactory factory) { super(); this.root = root; //The NodeParser does the resolving of the value of the configuration node. this.nParser = new NodeParser(factory); } @Override public void exec(String stmt, Map<String, String> params) throws IOException { String key = null; String param = null; String[] temp = separator.split(stmt, 2); if(temp.length==0) { return; }else if(temp.length==1) { key = temp[0].trim(); param = ""; }else{ key = temp[0].trim(); param = temp[1].trim(); } String prefix = params.get("prefix"); if(prefix!=null){ key = prefix + "." + key; } //Convert text/xml to text/plain logger.trace("Add to configuration key:{}, value:{}", key, param); //this happens 01.06.2016 if(key.equals("")) return; //Insert to confTree IConfNode node = root.create(key); node.value( param ); //Ensure to remove a former resolving to avoid malfunction. node.resolved(false); node.resolver(null); nParser.process(node); } @Override public boolean match(String stmt, Map<String, String> params) throws IOException { return super.match(stmt, params); } }
org.i3xx.util.ctree2/src/main/java/org/i3xx/util/ctree/parser/KeyValueRuleProcessLine.java
package org.i3xx.util.ctree.parser; import java.io.IOException; import java.util.Map; import java.util.regex.Pattern; import org.i3xx.util.ctree.IConfNode; import org.i3xx.util.ctree.core.IResolverFactory; import org.i3xx.util.ctree.impl.NodeParser; import org.slf4j.Logger; import org.slf4j.LoggerFactory; public class KeyValueRuleProcessLine extends AbstractKeyValueRule { private static final Logger logger = LoggerFactory.getLogger(KeyValueRuleProcessLine.class); // public static final Pattern separator = Pattern.compile("\\s*[\\s|=]\\s*"); protected IConfNode root; private NodeParser nParser; public KeyValueRuleProcessLine(IConfNode root, IResolverFactory factory) { super(); this.root = root; //The NodeParser does the resolving of the value of the configuration node. this.nParser = new NodeParser(factory); } @Override public void exec(String stmt, Map<String, String> params) throws IOException { String key = null; String param = null; String[] temp = separator.split(stmt, 2); if(temp.length==0) { return; }else if(temp.length==1) { key = temp[0].trim(); param = ""; }else{ key = temp[0].trim(); param = temp[1].trim(); } String prefix = params.get("prefix"); if(prefix!=null){ key = prefix + "." + key; } //Convert text/xml to text/plain logger.trace("Add to configuration key:{}, value:{}", key, param); //Insert to confTree IConfNode node = root.create(key); node.value( param ); //Ensure to remove a former resolving to avoid malfunction. node.resolved(false); node.resolver(null); nParser.process(node); } @Override public boolean match(String stmt, Map<String, String> params) throws IOException { return super.match(stmt, params); } }
Fix an invalid configuration entry that leads to a NullPointerException
org.i3xx.util.ctree2/src/main/java/org/i3xx/util/ctree/parser/KeyValueRuleProcessLine.java
Fix an invalid configuration entry that leads to a NullPointerException
<ide><path>rg.i3xx.util.ctree2/src/main/java/org/i3xx/util/ctree/parser/KeyValueRuleProcessLine.java <ide> //Convert text/xml to text/plain <ide> logger.trace("Add to configuration key:{}, value:{}", key, param); <ide> <add> //this happens 01.06.2016 <add> if(key.equals("")) <add> return; <add> <ide> //Insert to confTree <ide> IConfNode node = root.create(key); <ide> node.value( param );
Java
apache-2.0
8ad8be79d100df078e997eba45e710d9e0f01bf4
0
jerome-jacob/testng,bmlct/testng,smaudet/testng,s2oBCN/testng,JeshRJ/myRepRJ,tobecrazy/testng,VladRassokhin/testng,krmahadevan/testng,AJ-72/testng,6ft-invsbl-rbbt/testng,bmlct/testng,aledsage/testng,jerome-jacob/testng,juherr/testng,JeshRJ/myRepRJ,scr/testng,emopers/testng,krmahadevan/testng,missedone/testng,akozlova/testng,tobecrazy/testng,smaudet/testng,AJ-72/testng,gjuillot/testng,jaypal/testng,bmlct/testng,tremes/testng,raindev/testng,rschmitt/testng,s2oBCN/testng,6ft-invsbl-rbbt/testng,aledsage/testng,jaypal/testng,6ft-invsbl-rbbt/testng,juherr/testng,cbeust/testng,msebire/testng,cbeust/testng,scr/testng,tremes/testng,tremes/testng,VikingDen/testng,cbeust/testng,VikingDen/testng,raindev/testng,scr/testng,aledsage/testng,msebire/testng,emopers/testng,raindev/testng,AJ-72/testng,JeshRJ/myRepRJ,aledsage/testng,s2oBCN/testng,missedone/testng,raindev/testng,VladRassokhin/testng,meeroslaph/testng,juherr/testng,meeroslaph/testng,emopers/testng,emopers/testng,aledsage/testng,akozlova/testng,AJ-72/testng,VladRassokhin/testng,VladRassokhin/testng,gjuillot/testng,AJ-72/testng,bmlct/testng,VladRassokhin/testng,jerome-jacob/testng,rschmitt/testng,gjuillot/testng,bmlct/testng,missedone/testng,jaypal/testng,krmahadevan/testng,meeroslaph/testng,smaudet/testng,smaudet/testng,missedone/testng,emopers/testng,missedone/testng,cbeust/testng,JeshRJ/myRepRJ,akozlova/testng,VikingDen/testng,6ft-invsbl-rbbt/testng,krmahadevan/testng,6ft-invsbl-rbbt/testng,jaypal/testng,msebire/testng,meeroslaph/testng,smaudet/testng,gjuillot/testng,tobecrazy/testng,gjuillot/testng,VladRassokhin/testng,rschmitt/testng,scr/testng,akozlova/testng,rschmitt/testng,juherr/testng,VikingDen/testng,tremes/testng,krmahadevan/testng,jaypal/testng,AJ-72/testng,meeroslaph/testng,msebire/testng,JeshRJ/myRepRJ,cbeust/testng,VikingDen/testng,akozlova/testng,raindev/testng,tobecrazy/testng,jerome-jacob/testng,s2oBCN/testng,s2oBCN/testng,msebire/testng,tremes/testng,scr/testng,juherr/testng,jerome-jacob/testng,aledsage/testng,rschmitt/testng,raindev/testng,tobecrazy/testng
package org.testng.internal.annotations; import java.io.File; import java.io.FileNotFoundException; import java.io.FileReader; import java.lang.reflect.Constructor; import java.lang.reflect.Method; import java.util.ArrayList; import java.util.Collections; import java.util.HashMap; import java.util.Hashtable; import java.util.List; import java.util.Map; import org.testng.TestRunner; import org.testng.internal.Utils; import org.testng.log4testng.Logger; import com.thoughtworks.qdox.JavaDocBuilder; import com.thoughtworks.qdox.directorywalker.DirectoryScanner; import com.thoughtworks.qdox.directorywalker.FileVisitor; import com.thoughtworks.qdox.directorywalker.SuffixFilter; import com.thoughtworks.qdox.model.AbstractInheritableJavaEntity; import com.thoughtworks.qdox.model.JavaClass; import com.thoughtworks.qdox.model.JavaMethod; /** * This class implements IAnnotationFinder with QDox for JDK 1.4 * * TODO: this class needs some synchronization, because at this moment it can sometimes * try to parse some files twice. * * @author <a href="mailto:[email protected]">Cedric Beust</a> * @author <a href='mailto:the_mindstorm[at]evolva[dot]ro'>Alexandru Popescu</a> */ public class JDK14AnnotationFinder implements IAnnotationFinder { /** This class' loge4testng Logger. */ private static final Logger LOGGER = Logger.getLogger(JDK14AnnotationFinder.class); private Map<String, List<File>> m_sourceFiles= new HashMap<String, List<File>>(); private Map<String, String> m_parsedClasses= new HashMap<String, String>(); private Map<String, String> m_parsedFiles= new HashMap<String, String>(); private JDK14TagFactory m_tagFactory = new JDK14TagFactory(); private JavaDocBuilder m_docBuilder; private String[] m_dirPaths; private IAnnotationTransformer m_transformer; public JDK14AnnotationFinder(IAnnotationTransformer transformer) { m_docBuilder = new JavaDocBuilder(); m_transformer = transformer; } public void addSourceDirs(String[] dirPaths) { if(dirPaths == null) { Utils.log(getClass().getName(), 1, "[WARNING] Array of source directory paths is null"); return; } m_dirPaths = dirPaths; for (int i = 0; i < m_dirPaths.length; i++) { File dir = new File(m_dirPaths[i]); DirectoryScanner scanner = new DirectoryScanner(dir); scanner.addFilter(new SuffixFilter(".java")); scanner.scan(new FileVisitor() { public void visitFile(File currentFile) { registerSourceFile(currentFile); } }); } } /** * Record in an internal map the existence of a source file. * @param sourcefile the source file */ private void registerSourceFile(File sourcefile) { List<File> files= m_sourceFiles.get(sourcefile.getName()); if(null == files) { files= new ArrayList<File>(); m_sourceFiles.put(sourcefile.getName(), files); } files.add(sourcefile); } //private void addSources(String[] filePaths) { //if(filePaths == null) { // Utils.log(getClass().getName(), 1, "[WARNING] Array of source paths is null"); // // return; //} //for(int i = 0; i < filePaths.length; i++) { // addSource(filePaths[i]); //} //} /** * Must be synch to be assured that a file is not parsed twice */ private synchronized boolean addSource(String filePath) { if(m_parsedFiles.containsKey(filePath)) { return true; } try { m_docBuilder.addSource(new FileReader(filePath)); m_parsedFiles.put(filePath, filePath); return true; } catch(FileNotFoundException fnfe) { Utils.log(getClass().getName(), 1, "[WARNING] source file not found: " + filePath + "\n " + fnfe.getMessage()); } catch(Throwable t) { Utils.log(getClass().getName(), 1, "[WARNING] cannot parse source: " + filePath + "\n " + t.getMessage()); } return false; } private JavaClass getClassByName(Class clazz) { if(m_parsedClasses.containsKey(clazz.getName())) { JavaClass jc= m_docBuilder.getClassByName(clazz.getName()); return jc; } else { parseSource(clazz); return getClassByName(clazz); } } private void parseSource(Class clazz) { final String className= clazz.getName(); int innerSignPos= className.indexOf('$'); final String fileName = innerSignPos == -1 ? className.substring(className.lastIndexOf('.') + 1) : clazz.getName().substring(className.lastIndexOf('.') + 1, innerSignPos); List<File> sourcefiles= m_sourceFiles.get(fileName + ".java"); if(null != sourcefiles) { for(File f: sourcefiles) { addSource(f.getAbsolutePath()); } } m_parsedClasses.put(className, className); Class superClass= clazz.getSuperclass(); if(null != superClass && !Object.class.equals(superClass)) { parseSource(superClass); } } public IAnnotation findAnnotation(Class cls, Class annotationClass) { if(Object.class.equals(cls)) { return null; } IAnnotation result = m_tagFactory.createTag(annotationClass, getClassByName(cls), m_transformer); transform(result, cls, null, null); return result; } public IAnnotation findAnnotation(Method m, Class annotationClass) { IAnnotation result = findMethodAnnotation(m.getName(), m.getParameterTypes(), m.getDeclaringClass(), annotationClass, m_transformer); transform(result, null, null, m); return result; } public IAnnotation findAnnotation(Constructor m, Class annotationClass) { String name = stripPackage(m.getName()); IAnnotation result = findMethodAnnotation(name, m.getParameterTypes(), m.getDeclaringClass(), annotationClass, m_transformer); transform(result, null, m, null); return result; } private void transform (IAnnotation a, Class testClass, Constructor testConstructor, Method testMethod) { if (a instanceof ITest) { m_transformer.transform((ITest) a, testClass, testConstructor, testMethod); } } private String stripPackage(String name) { return name.substring(name.lastIndexOf('.')); // String result = name; // int index = result.lastIndexOf("."); // if (index > 0) { // result = result.substring(index + 1); // } // // return result; } private IAnnotation findMethodAnnotation(String methodName, Class[] parameterTypes, Class methodClass, Class annotationClass, IAnnotationTransformer transformer) { if(Object.class.equals(methodClass)) { return null; } IAnnotation result = null; JavaClass jc = getClassByName(methodClass); if (jc != null) { List<JavaMethod> methods = new ArrayList<JavaMethod>(); JavaMethod[] allMethods = jc.getMethods(); for (int i = 0; i < allMethods.length; i++) { JavaMethod jm = allMethods[i]; if (methodsAreEqual(jm, methodName, parameterTypes)) { methods.add(jm); } } JavaMethod method = null; // if (methods.size() > 1) { // ppp("WARNING: method " + methodName + " is overloaded, only considering the first one"); // } if (methods.size() > 0) { method = methods.get(0); result = findTag(annotationClass, result, method, transformer); } } else { Utils.log(getClass().getName(), 1, "[WARNING] cannot resolve class: " + methodClass.getName()); } return result; } private boolean methodsAreEqual(JavaMethod jm, String methodName, Class[] parameterTypes) { boolean result = jm.getName().equals(methodName) && jm.getParameters().length == parameterTypes.length; return result; } private IAnnotation findTag(Class annotationClass, IAnnotation result, AbstractInheritableJavaEntity entity, IAnnotationTransformer transformer) { return m_tagFactory.createTag(annotationClass, entity, transformer); } private static void ppp(String s) { System.out.println("[JDK14AnnotationFinder] " + s); } }
src/main/org/testng/internal/annotations/JDK14AnnotationFinder.java
package org.testng.internal.annotations; import java.io.File; import java.io.FileNotFoundException; import java.io.FileReader; import java.lang.reflect.Constructor; import java.lang.reflect.Method; import java.util.ArrayList; import java.util.List; import org.testng.TestRunner; import org.testng.internal.Utils; import org.testng.log4testng.Logger; import com.thoughtworks.qdox.JavaDocBuilder; import com.thoughtworks.qdox.directorywalker.DirectoryScanner; import com.thoughtworks.qdox.directorywalker.FileVisitor; import com.thoughtworks.qdox.directorywalker.SuffixFilter; import com.thoughtworks.qdox.model.AbstractInheritableJavaEntity; import com.thoughtworks.qdox.model.JavaClass; import com.thoughtworks.qdox.model.JavaMethod; /** * This class implements IAnnotationFinder with QDox for JDK 1.4 * * @author <a href="mailto:[email protected]">Cedric Beust</a> * @author <a href='mailto:the_mindstorm[at]evolva[dot]ro'>Alexandru Popescu</a> */ public class JDK14AnnotationFinder implements IAnnotationFinder { /** This class' loge4testng Logger. */ private static final Logger LOGGER = Logger.getLogger(JDK14AnnotationFinder.class); private JDK14TagFactory m_tagFactory = new JDK14TagFactory(); private JavaDocBuilder m_docBuilder; private String[] m_dirPaths; private IAnnotationTransformer m_transformer; public JDK14AnnotationFinder(IAnnotationTransformer transformer) { m_docBuilder = new JavaDocBuilder(); m_transformer = transformer; } void addSources(String[] filePaths) { if(filePaths == null) { if (TestRunner.getVerbose() > 1) { ppp("Array of source paths is null"); } return; } for(int i = 0; i < filePaths.length; i++) { try { m_docBuilder.addSource(new FileReader(filePaths[i])); } catch(FileNotFoundException fnfe) { LOGGER.warn("file or directory does not exist: " + filePaths[i]); ppp("File does not exist [" + filePaths[i] + "]"); } catch(Throwable t) { Utils.log(getClass().getName(), 1, "[WARNING] cannot parse source: " + filePaths[i] + "\n " + t.getMessage()); } } } public void addSourceDirs(String[] dirPaths) { if(dirPaths == null) { if (TestRunner.getVerbose() > 1) { ppp("Array of source directory paths is null"); } return; } m_dirPaths = dirPaths; for (int i = 0; i < m_dirPaths.length; i++) { File dir = new File(m_dirPaths[i]); DirectoryScanner scanner = new DirectoryScanner(dir); scanner.addFilter(new SuffixFilter(".java")); scanner.scan(new FileVisitor() { public void visitFile(File currentFile) { addSources(new String[] { currentFile.getAbsolutePath() }); } }); } } public IAnnotation findAnnotation(Class cls, Class annotationClass) { IAnnotation result = m_tagFactory.createTag(annotationClass, m_docBuilder.getClassByName(cls.getName()), m_transformer); transform(result, cls, null, null); return result; } public IAnnotation findAnnotation(Method m, Class annotationClass) { IAnnotation result = findMethodAnnotation(m.getName(), m.getParameterTypes(), m.getDeclaringClass(), annotationClass, m_transformer); transform(result, null, null, m); return result; } public IAnnotation findAnnotation(Constructor m, Class annotationClass) { String name = stripPackage(m.getName()); IAnnotation result = findMethodAnnotation(name, m.getParameterTypes(), m.getDeclaringClass(), annotationClass, m_transformer); transform(result, null, m, null); return result; } private void transform (IAnnotation a, Class testClass, Constructor testConstructor, Method testMethod) { if (a instanceof ITest) { m_transformer.transform((ITest) a, testClass, testConstructor, testMethod); } } private String stripPackage(String name) { String result = name; int index = result.lastIndexOf("."); if (index > 0) { result = result.substring(index + 1); } return result; } private IAnnotation findMethodAnnotation(String methodName, Class[] parameterTypes, Class methodClass, Class annotationClass, IAnnotationTransformer transformer) { IAnnotation result = null; JavaClass jc = m_docBuilder.getClassByName(methodClass.getName()); if (jc != null) { List methods = new ArrayList(); JavaMethod[] allMethods = jc.getMethods(); for (int i = 0; i < allMethods.length; i++) { JavaMethod jm = allMethods[i]; if (methodsAreEqual(jm, methodName, parameterTypes)) { methods.add(jm); } } JavaMethod method =null; // if (methods.size() > 1) { // ppp("WARNING: method " + methodName + " is overloaded, only considering the first one"); // } if (methods.size() > 0) { method = (JavaMethod) methods.get(0); result = findTag(annotationClass, result, method, transformer); } } else { ppp("COULDN'T RESOLVE CLASS " + methodClass.getName()); } return result; } private boolean methodsAreEqual(JavaMethod jm, String methodName, Class[] parameterTypes) { boolean result = jm.getName().equals(methodName) && jm.getParameters().length == parameterTypes.length; return result; } private IAnnotation findTag(Class annotationClass, IAnnotation result, AbstractInheritableJavaEntity entity, IAnnotationTransformer transformer) { return m_tagFactory.createTag(annotationClass, entity, transformer); } private static void ppp(String s) { System.out.println("[JDK14AnnotationFinder] " + s); } }
improved behavior in scanning sources: only the requested sources (and their super hierarchy) is scanned now
src/main/org/testng/internal/annotations/JDK14AnnotationFinder.java
improved behavior in scanning sources: only the requested sources (and their super hierarchy) is scanned now
<ide><path>rc/main/org/testng/internal/annotations/JDK14AnnotationFinder.java <ide> import java.lang.reflect.Constructor; <ide> import java.lang.reflect.Method; <ide> import java.util.ArrayList; <add>import java.util.Collections; <add>import java.util.HashMap; <add>import java.util.Hashtable; <ide> import java.util.List; <add>import java.util.Map; <ide> <ide> import org.testng.TestRunner; <ide> import org.testng.internal.Utils; <ide> /** <ide> * This class implements IAnnotationFinder with QDox for JDK 1.4 <ide> * <add> * TODO: this class needs some synchronization, because at this moment it can sometimes <add> * try to parse some files twice. <add> * <ide> * @author <a href="mailto:[email protected]">Cedric Beust</a> <ide> * @author <a href='mailto:the_mindstorm[at]evolva[dot]ro'>Alexandru Popescu</a> <ide> */ <ide> /** This class' loge4testng Logger. */ <ide> private static final Logger LOGGER = Logger.getLogger(JDK14AnnotationFinder.class); <ide> <add> private Map<String, List<File>> m_sourceFiles= new HashMap<String, List<File>>(); <add> private Map<String, String> m_parsedClasses= new HashMap<String, String>(); <add> <add> private Map<String, String> m_parsedFiles= new HashMap<String, String>(); <add> <ide> private JDK14TagFactory m_tagFactory = new JDK14TagFactory(); <ide> private JavaDocBuilder m_docBuilder; <ide> private String[] m_dirPaths; <ide> m_transformer = transformer; <ide> } <ide> <del> void addSources(String[] filePaths) { <del> if(filePaths == null) { <del> if (TestRunner.getVerbose() > 1) { <del> ppp("Array of source paths is null"); <del> } <del> <del> return; <del> } <del> for(int i = 0; i < filePaths.length; i++) { <del> try { <del> m_docBuilder.addSource(new FileReader(filePaths[i])); <del> } <del> catch(FileNotFoundException fnfe) { <del> LOGGER.warn("file or directory does not exist: " + filePaths[i]); <del> ppp("File does not exist [" + filePaths[i] + "]"); <del> } <del> catch(Throwable t) { <del> Utils.log(getClass().getName(), 1, "[WARNING] cannot parse source: " + filePaths[i] + "\n " + t.getMessage()); <del> } <del> } <del> } <del> <ide> public void addSourceDirs(String[] dirPaths) { <ide> if(dirPaths == null) { <del> if (TestRunner.getVerbose() > 1) { <del> ppp("Array of source directory paths is null"); <del> } <add> Utils.log(getClass().getName(), 1, "[WARNING] Array of source directory paths is null"); <ide> return; <ide> } <ide> <ide> scanner.addFilter(new SuffixFilter(".java")); <ide> scanner.scan(new FileVisitor() { <ide> public void visitFile(File currentFile) { <del> addSources(new String[] { currentFile.getAbsolutePath() }); <add> registerSourceFile(currentFile); <ide> } <ide> }); <ide> } <ide> } <ide> <del> public IAnnotation findAnnotation(Class cls, Class annotationClass) <del> { <del> IAnnotation result = m_tagFactory.createTag(annotationClass, <del> m_docBuilder.getClassByName(cls.getName()), <del> m_transformer); <del> <add> /** <add> * Record in an internal map the existence of a source file. <add> * @param sourcefile the source file <add> */ <add> private void registerSourceFile(File sourcefile) { <add> List<File> files= m_sourceFiles.get(sourcefile.getName()); <add> if(null == files) { <add> files= new ArrayList<File>(); <add> m_sourceFiles.put(sourcefile.getName(), files); <add> } <add> files.add(sourcefile); <add> } <add> <add>//private void addSources(String[] filePaths) { <add>//if(filePaths == null) { <add>// Utils.log(getClass().getName(), 1, "[WARNING] Array of source paths is null"); <add>// <add>// return; <add>//} <add>//for(int i = 0; i < filePaths.length; i++) { <add>// addSource(filePaths[i]); <add>//} <add>//} <add> <add> /** <add> * Must be synch to be assured that a file is not parsed twice <add> */ <add> private synchronized boolean addSource(String filePath) { <add> if(m_parsedFiles.containsKey(filePath)) { <add> return true; <add> } <add> <add> try { <add> m_docBuilder.addSource(new FileReader(filePath)); <add> m_parsedFiles.put(filePath, filePath); <add> <add> return true; <add> } <add> catch(FileNotFoundException fnfe) { <add> Utils.log(getClass().getName(), 1, "[WARNING] source file not found: " + filePath + "\n " + fnfe.getMessage()); <add> } <add> catch(Throwable t) { <add> Utils.log(getClass().getName(), 1, "[WARNING] cannot parse source: " + filePath + "\n " + t.getMessage()); <add> } <add> <add> return false; <add> } <add> <add> private JavaClass getClassByName(Class clazz) { <add> if(m_parsedClasses.containsKey(clazz.getName())) { <add> JavaClass jc= m_docBuilder.getClassByName(clazz.getName()); <add> return jc; <add> } <add> else { <add> parseSource(clazz); <add> <add> return getClassByName(clazz); <add> } <add> } <add> <add> private void parseSource(Class clazz) { <add> final String className= clazz.getName(); <add> int innerSignPos= className.indexOf('$'); <add> final String fileName = innerSignPos == -1 <add> ? className.substring(className.lastIndexOf('.') + 1) <add> : clazz.getName().substring(className.lastIndexOf('.') + 1, innerSignPos); <add> <add> List<File> sourcefiles= m_sourceFiles.get(fileName + ".java"); <add> if(null != sourcefiles) { <add> for(File f: sourcefiles) { <add> addSource(f.getAbsolutePath()); <add> } <add> } <add> <add> m_parsedClasses.put(className, className); <add> <add> Class superClass= clazz.getSuperclass(); <add> if(null != superClass && !Object.class.equals(superClass)) { <add> parseSource(superClass); <add> } <add> } <add> <add> public IAnnotation findAnnotation(Class cls, Class annotationClass) { <add> if(Object.class.equals(cls)) { <add> return null; <add> } <add> <add> IAnnotation result = m_tagFactory.createTag(annotationClass, getClassByName(cls), m_transformer); <add> <ide> transform(result, cls, null, null); <ide> <ide> return result; <ide> } <ide> <del> public IAnnotation findAnnotation(Method m, Class annotationClass) <del> { <add> public IAnnotation findAnnotation(Method m, Class annotationClass) { <ide> IAnnotation result = findMethodAnnotation(m.getName(), m.getParameterTypes(), <ide> m.getDeclaringClass(), annotationClass, m_transformer); <del> <add> <ide> transform(result, null, null, m); <ide> <ide> return result; <ide> } <ide> <del> public IAnnotation findAnnotation(Constructor m, Class annotationClass) <del> { <add> public IAnnotation findAnnotation(Constructor m, Class annotationClass) { <ide> String name = stripPackage(m.getName()); <del> IAnnotation result = <del> findMethodAnnotation(name, m.getParameterTypes(), m.getDeclaringClass(), <add> IAnnotation result = findMethodAnnotation(name, m.getParameterTypes(), m.getDeclaringClass(), <ide> annotationClass, m_transformer); <del> <add> <ide> transform(result, null, m, null); <ide> <ide> return result; <ide> } <ide> <del> private void transform (IAnnotation a, Class testClass, <del> Constructor testConstructor, Method testMethod) <del> { <add> private void transform (IAnnotation a, Class testClass, Constructor testConstructor, Method testMethod) { <ide> if (a instanceof ITest) { <del> m_transformer.transform((ITest) a, <del> testClass, testConstructor, testMethod); <add> m_transformer.transform((ITest) a, testClass, testConstructor, testMethod); <ide> } <ide> } <ide> <ide> private String stripPackage(String name) { <del> String result = name; <del> int index = result.lastIndexOf("."); <del> if (index > 0) { <del> result = result.substring(index + 1); <del> } <del> <del> return result; <add> return name.substring(name.lastIndexOf('.')); <add>// String result = name; <add>// int index = result.lastIndexOf("."); <add>// if (index > 0) { <add>// result = result.substring(index + 1); <add>// } <add>// <add>// return result; <ide> } <ide> <ide> private IAnnotation findMethodAnnotation(String methodName, Class[] parameterTypes, <ide> Class methodClass, Class annotationClass, IAnnotationTransformer transformer) <ide> { <add> if(Object.class.equals(methodClass)) { <add> return null; <add> } <add> <ide> IAnnotation result = null; <del> JavaClass jc = m_docBuilder.getClassByName(methodClass.getName()); <add> JavaClass jc = getClassByName(methodClass); <ide> if (jc != null) { <del> List methods = new ArrayList(); <add> List<JavaMethod> methods = new ArrayList<JavaMethod>(); <ide> JavaMethod[] allMethods = jc.getMethods(); <ide> for (int i = 0; i < allMethods.length; i++) { <ide> JavaMethod jm = allMethods[i]; <ide> } <ide> } <ide> <del> JavaMethod method =null; <add> JavaMethod method = null; <ide> // if (methods.size() > 1) { <ide> // ppp("WARNING: method " + methodName + " is overloaded, only considering the first one"); <ide> // } <ide> <ide> if (methods.size() > 0) { <del> method = (JavaMethod) methods.get(0); <add> method = methods.get(0); <ide> result = findTag(annotationClass, result, method, transformer); <ide> } <ide> <ide> } <ide> else { <del> ppp("COULDN'T RESOLVE CLASS " + methodClass.getName()); <add> Utils.log(getClass().getName(), 1, "[WARNING] cannot resolve class: " + methodClass.getName()); <ide> } <ide> <ide> return result;
Java
mit
error: pathspec 'java/LeetCode/132-pattern-456.java' did not match any file(s) known to git
8fdcf334aeb95f3c080b0b57edac99814b4c0a9d
1
vinnyoodles/algorithms,vinnyoodles/algorithms,vinnyoodles/algorithms
public class Solution { public boolean find132pattern(int[] nums) { // Keep track of the global minimum. // The global min will be the ai value. int min = Integer.MAX_VALUE; for (int j = 0; j < nums.length; j++) { min = Math.min(nums[j], min); // If the current value is the minimum, // then this is the ai value for this current iteration. if (min == nums[j]) continue; // Otherwise, it is not the minimum so let nums[j] be aj for (int k = nums.length - 1; k > j; k--) { // If there is a valid ak, after j then return true; if (min < nums[k] && nums[k] < nums[j]) return true; } } return false; } }
java/LeetCode/132-pattern-456.java
Add leetcode 456
java/LeetCode/132-pattern-456.java
Add leetcode 456
<ide><path>ava/LeetCode/132-pattern-456.java <add>public class Solution { <add> <add> public boolean find132pattern(int[] nums) { <add> // Keep track of the global minimum. <add> // The global min will be the ai value. <add> int min = Integer.MAX_VALUE; <add> for (int j = 0; j < nums.length; j++) { <add> min = Math.min(nums[j], min); <add> <add> // If the current value is the minimum, <add> // then this is the ai value for this current iteration. <add> if (min == nums[j]) continue; <add> <add> // Otherwise, it is not the minimum so let nums[j] be aj <add> for (int k = nums.length - 1; k > j; k--) { <add> <add> // If there is a valid ak, after j then return true; <add> if (min < nums[k] && nums[k] < nums[j]) return true; <add> } <add> } <add> <add> return false; <add> } <add>}
Java
apache-2.0
90c37596144a59b2a3ac253a0b6efe25588b25e2
0
pkleczko/CustomGauge
package pl.pawelkleczkowski.customgauge; import android.content.Context; import android.content.res.TypedArray; import android.graphics.Canvas; import android.graphics.LinearGradient; import android.graphics.Paint; import android.graphics.RectF; import android.graphics.Shader; import android.support.v4.content.ContextCompat; import android.text.TextUtils; import android.util.AttributeSet; import android.view.View; public class CustomGauge extends View { private static final int DEFAULT_LONG_POINTER_SIZE = 1; private Paint mPaint; private float mStrokeWidth; private int mStrokeColor; private RectF mRect; private String mStrokeCap; private int mStartAngel; private int mSweepAngel; private int mStartValue; private int mEndValue; private int mValue; private double mPointAngel; private int mPoint; private int mPointSize; private int mPointStartColor; private int mPointEndColor; private int mDividerColor; private int mDividerSize; private int mDividerStepAngel; private int mDividersCount; private boolean mDividerDrawFirst; private boolean mDividerDrawLast; public CustomGauge(Context context) { super(context); init(); } public CustomGauge(Context context, AttributeSet attrs) { super(context, attrs); TypedArray a = context.obtainStyledAttributes(attrs, R.styleable.CustomGauge, 0, 0); // stroke style setStrokeWidth(a.getDimension(R.styleable.CustomGauge_gaugeStrokeWidth, 10)); setStrokeColor(a.getColor(R.styleable.CustomGauge_gaugeStrokeColor, ContextCompat.getColor(context, android.R.color.darker_gray))); setStrokeCap(a.getString(R.styleable.CustomGauge_gaugeStrokeCap)); // angel start and sweep (opposite direction 0, 270, 180, 90) setStartAngel(a.getInt(R.styleable.CustomGauge_gaugeStartAngel, 0)); setSweepAngel(a.getInt(R.styleable.CustomGauge_gaugeSweepAngel, 360)); // scale (from mStartValue to mEndValue) setStartValue(a.getInt(R.styleable.CustomGauge_gaugeStartValue, 0)); setEndValue(a.getInt(R.styleable.CustomGauge_gaugeEndValue, 1000)); // pointer size and color setPointSize(a.getInt(R.styleable.CustomGauge_gaugePointSize, 0)); setPointStartColor(a.getColor(R.styleable.CustomGauge_gaugePointStartColor, ContextCompat.getColor(context, android.R.color.white))); setPointEndColor(a.getColor(R.styleable.CustomGauge_gaugePointEndColor, ContextCompat.getColor(context, android.R.color.white))); // divider options int dividerSize = a.getInt(R.styleable.CustomGauge_gaugeDividerSize, 0); setDividerColor(a.getColor(R.styleable.CustomGauge_gaugeDividerColor, ContextCompat.getColor(context, android.R.color.white))); int dividerStep = a.getInt(R.styleable.CustomGauge_gaugeDividerStep, 0); setDividerDrawFirst(a.getBoolean(R.styleable.CustomGauge_gaugeDividerDrawFirst, true)); setDividerDrawLast(a.getBoolean(R.styleable.CustomGauge_gaugeDividerDrawLast, true)); // calculating one point sweep mPointAngel = ((double) Math.abs(mSweepAngel) / (mEndValue - mStartValue)); // calculating divider step if (dividerSize > 0) { mDividerSize = mSweepAngel / (Math.abs(mEndValue - mStartValue) / dividerSize); mDividersCount = 100 / dividerStep; mDividerStepAngel = mSweepAngel / mDividersCount; } a.recycle(); init(); } private void init() { //main Paint mPaint = new Paint(); mPaint.setColor(mStrokeColor); mPaint.setStrokeWidth(mStrokeWidth); mPaint.setAntiAlias(true); if (!TextUtils.isEmpty(mStrokeCap)) { if (mStrokeCap.equals("BUTT")) mPaint.setStrokeCap(Paint.Cap.BUTT); else if (mStrokeCap.equals("ROUND")) mPaint.setStrokeCap(Paint.Cap.ROUND); } else mPaint.setStrokeCap(Paint.Cap.BUTT); mPaint.setStyle(Paint.Style.STROKE); mRect = new RectF(); mValue = mStartValue; mPoint = mStartAngel; } @Override protected void onDraw(Canvas canvas) { super.onDraw(canvas); float paddingLeft = getPaddingLeft(); float paddingRight= getPaddingRight(); float paddingTop = getPaddingTop(); float paddingBottom = getPaddingBottom(); float width = getWidth() - (paddingLeft+paddingRight); float height = getHeight() - (paddingTop+paddingBottom); float radius = (width > height ? width/2 : height/2); float rectLeft = width/2 - radius + paddingLeft; float rectTop = height/2 - radius + paddingTop; float rectRight = width/2 - radius + paddingLeft + width; float rectBottom = height/2 - radius + paddingTop + height; mRect.set(rectLeft, rectTop, rectRight, rectBottom); mPaint.setColor(mStrokeColor); mPaint.setShader(null); canvas.drawArc(mRect, mStartAngel, mSweepAngel, false, mPaint); mPaint.setColor(mPointStartColor); mPaint.setShader(new LinearGradient(getWidth(), getHeight(), 0, 0, mPointEndColor, mPointStartColor, Shader.TileMode.CLAMP)); if (mPointSize>0) {//if size of pointer is defined if (mPoint > mStartAngel + mPointSize/2) { canvas.drawArc(mRect, mPoint - mPointSize/2, mPointSize, false, mPaint); } else { //to avoid excedding start/zero point canvas.drawArc(mRect, mPoint, mPointSize, false, mPaint); } } else { //draw from start point to value point (long pointer) if (mValue==mStartValue) //use non-zero default value for start point (to avoid lack of pointer for start/zero value) canvas.drawArc(mRect, mStartAngel, DEFAULT_LONG_POINTER_SIZE, false, mPaint); else canvas.drawArc(mRect, mStartAngel, mPoint - mStartAngel, false, mPaint); } if (mDividerSize > 0) { mPaint.setColor(mDividerColor); mPaint.setShader(null); int i = mDividerDrawFirst ? 0 : 1; int max = mDividerDrawLast ? mDividersCount + 1 : mDividersCount; for (; i < max; i++) { canvas.drawArc(mRect, mStartAngel + i*mDividerStepAngel, mDividerSize, false, mPaint); } } } public void setValue(int value) { mValue = value; mPoint = (int) (mStartAngel + (mValue-mStartValue) * mPointAngel); invalidate(); } public int getValue() { return mValue; } @SuppressWarnings("unused") public float getStrokeWidth() { return mStrokeWidth; } public void setStrokeWidth(float strokeWidth) { mStrokeWidth = strokeWidth; } @SuppressWarnings("unused") public int getStrokeColor() { return mStrokeColor; } public void setStrokeColor(int strokeColor) { mStrokeColor = strokeColor; } @SuppressWarnings("unused") public String getStrokeCap() { return mStrokeCap; } public void setStrokeCap(String strokeCap) { mStrokeCap = strokeCap; } @SuppressWarnings("unused") public int getStartAngel() { return mStartAngel; } public void setStartAngel(int startAngel) { mStartAngel = startAngel; } @SuppressWarnings("unused") public int getSweepAngel() { return mSweepAngel; } public void setSweepAngel(int sweepAngel) { mSweepAngel = sweepAngel; } @SuppressWarnings("unused") public int getStartValue() { return mStartValue; } public void setStartValue(int startValue) { mStartValue = startValue; } @SuppressWarnings("unused") public int getEndValue() { return mEndValue; } public void setEndValue(int endValue) { mEndValue = endValue; } @SuppressWarnings("unused") public int getPointSize() { return mPointSize; } public void setPointSize(int pointSize) { mPointSize = pointSize; } @SuppressWarnings("unused") public int getPointStartColor() { return mPointStartColor; } public void setPointStartColor(int pointStartColor) { mPointStartColor = pointStartColor; } @SuppressWarnings("unused") public int getPointEndColor() { return mPointEndColor; } public void setPointEndColor(int pointEndColor) { mPointEndColor = pointEndColor; } @SuppressWarnings("unused") public int getDividerColor() { return mDividerColor; } public void setDividerColor(int dividerColor) { mDividerColor = dividerColor; } @SuppressWarnings("unused") public boolean isDividerDrawFirst() { return mDividerDrawFirst; } public void setDividerDrawFirst(boolean dividerDrawFirst) { mDividerDrawFirst = dividerDrawFirst; } @SuppressWarnings("unused") public boolean isDividerDrawLast() { return mDividerDrawLast; } public void setDividerDrawLast(boolean dividerDrawLast) { mDividerDrawLast = dividerDrawLast; } }
CustomGauge/src/main/java/pl/pawelkleczkowski/customgauge/CustomGauge.java
package pl.pawelkleczkowski.customgauge; import android.content.Context; import android.content.res.TypedArray; import android.graphics.Canvas; import android.graphics.LinearGradient; import android.graphics.Paint; import android.graphics.RectF; import android.graphics.Shader; import android.support.v4.content.ContextCompat; import android.text.TextUtils; import android.util.AttributeSet; import android.view.View; public class CustomGauge extends View { private static final int DEFAULT_LONG_POINTER_SIZE = 1; private Paint mPaint; private float mStrokeWidth; private int mStrokeColor; private RectF mRect; private String mStrokeCap; private int mStartAngel; private int mSweepAngel; private int mStartValue; private int mEndValue; private int mValue; private double mPointAngel; private float mRectLeft; private float mRectTop; private float mRectRight; private float mRectBottom; private int mPoint; private int mPointSize; private int mPointStartColor; private int mPointEndColor; private int mDividerColor; private int mDividerSize; private int mDividerStepAngel; private int mDividersCount; private boolean mDividerDrawFirst; private boolean mDividerDrawLast; public CustomGauge(Context context) { super(context); init(); } public CustomGauge(Context context, AttributeSet attrs) { super(context, attrs); TypedArray a = context.obtainStyledAttributes(attrs, R.styleable.CustomGauge, 0, 0); // stroke style mStrokeWidth = a.getDimension(R.styleable.CustomGauge_gaugeStrokeWidth, 10); mStrokeColor = a.getColor(R.styleable.CustomGauge_gaugeStrokeColor, ContextCompat.getColor(context, android.R.color.darker_gray)); mStrokeCap = a.getString(R.styleable.CustomGauge_gaugeStrokeCap); // angel start and sweep (opposite direction 0, 270, 180, 90) mStartAngel = a.getInt(R.styleable.CustomGauge_gaugeStartAngel, 0); mSweepAngel = a.getInt(R.styleable.CustomGauge_gaugeSweepAngel, 360); // scale (from mStartValue to mEndValue) mStartValue = a.getInt(R.styleable.CustomGauge_gaugeStartValue, 0); mEndValue = a.getInt(R.styleable.CustomGauge_gaugeEndValue, 1000); // pointer size and color mPointSize = a.getInt(R.styleable.CustomGauge_gaugePointSize, 0); mPointStartColor = a.getColor(R.styleable.CustomGauge_gaugePointStartColor, ContextCompat.getColor(context, android.R.color.white)); mPointEndColor = a.getColor(R.styleable.CustomGauge_gaugePointEndColor, ContextCompat.getColor(context, android.R.color.white)); // divider options int dividerSize = a.getInt(R.styleable.CustomGauge_gaugeDividerSize, 0); mDividerColor = a.getColor(R.styleable.CustomGauge_gaugeDividerColor, ContextCompat.getColor(context, android.R.color.white)); int dividerStep = a.getInt(R.styleable.CustomGauge_gaugeDividerStep, 0); mDividerDrawFirst = a.getBoolean(R.styleable.CustomGauge_gaugeDividerDrawFirst, true); mDividerDrawLast = a.getBoolean(R.styleable.CustomGauge_gaugeDividerDrawLast, true); // calculating one point sweep mPointAngel = ((double) Math.abs(mSweepAngel) / (mEndValue - mStartValue)); // calculating divider step if (dividerSize > 0) { mDividerSize = mSweepAngel / (Math.abs(mEndValue - mStartValue) / dividerSize); mDividersCount = 100 / dividerStep; mDividerStepAngel = mSweepAngel / mDividersCount; } a.recycle(); init(); } private void init() { //main Paint mPaint = new Paint(); mPaint.setColor(mStrokeColor); mPaint.setStrokeWidth(mStrokeWidth); mPaint.setAntiAlias(true); if (!TextUtils.isEmpty(mStrokeCap)) { if (mStrokeCap.equals("BUTT")) mPaint.setStrokeCap(Paint.Cap.BUTT); else if (mStrokeCap.equals("ROUND")) mPaint.setStrokeCap(Paint.Cap.ROUND); } else mPaint.setStrokeCap(Paint.Cap.BUTT); mPaint.setStyle(Paint.Style.STROKE); mRect = new RectF(); mValue = mStartValue; mPoint = mStartAngel; } @Override protected void onDraw(Canvas canvas) { super.onDraw(canvas); float paddingLeft = getPaddingLeft(); float paddingRight= getPaddingRight(); float paddingTop = getPaddingTop(); float paddingBottom = getPaddingBottom(); float width = getWidth() - (paddingLeft+paddingRight); float height = getHeight() - (paddingTop+paddingBottom); float radius = (width > height ? width/2 : height/2); mRectLeft = width/2 - radius + paddingLeft; mRectTop = height/2 - radius + paddingTop; mRectRight = width/2 - radius + paddingLeft + width; mRectBottom = height/2 - radius + paddingTop + height; mRect.set(mRectLeft, mRectTop, mRectRight, mRectBottom); mPaint.setColor(mStrokeColor); mPaint.setShader(null); canvas.drawArc(mRect, mStartAngel, mSweepAngel, false, mPaint); mPaint.setColor(mPointStartColor); mPaint.setShader(new LinearGradient(getWidth(), getHeight(), 0, 0, mPointEndColor, mPointStartColor, Shader.TileMode.CLAMP)); if (mPointSize>0) {//if size of pointer is defined if (mPoint > mStartAngel + mPointSize/2) { canvas.drawArc(mRect, mPoint - mPointSize/2, mPointSize, false, mPaint); } else { //to avoid excedding start/zero point canvas.drawArc(mRect, mPoint, mPointSize, false, mPaint); } } else { //draw from start point to value point (long pointer) if (mValue==mStartValue) //use non-zero default value for start point (to avoid lack of pointer for start/zero value) canvas.drawArc(mRect, mStartAngel, DEFAULT_LONG_POINTER_SIZE, false, mPaint); else canvas.drawArc(mRect, mStartAngel, mPoint - mStartAngel, false, mPaint); } if (mDividerSize > 0) { mPaint.setColor(mDividerColor); mPaint.setShader(null); int i = mDividerDrawFirst ? 0 : 1; int max = mDividerDrawLast ? mDividersCount + 1 : mDividersCount; for (; i < max; i++) { canvas.drawArc(mRect, mStartAngel + i*mDividerStepAngel, mDividerSize, false, mPaint); } } } public void setValue(int value) { mValue = value; mPoint = (int) (mStartAngel + (mValue-mStartValue) * mPointAngel); invalidate(); } public int getValue() { return mValue; } }
Added setters and getters.
CustomGauge/src/main/java/pl/pawelkleczkowski/customgauge/CustomGauge.java
Added setters and getters.
<ide><path>ustomGauge/src/main/java/pl/pawelkleczkowski/customgauge/CustomGauge.java <ide> private int mEndValue; <ide> private int mValue; <ide> private double mPointAngel; <del> private float mRectLeft; <del> private float mRectTop; <del> private float mRectRight; <del> private float mRectBottom; <ide> private int mPoint; <ide> private int mPointSize; <ide> private int mPointStartColor; <ide> TypedArray a = context.obtainStyledAttributes(attrs, R.styleable.CustomGauge, 0, 0); <ide> <ide> // stroke style <del> mStrokeWidth = a.getDimension(R.styleable.CustomGauge_gaugeStrokeWidth, 10); <del> mStrokeColor = a.getColor(R.styleable.CustomGauge_gaugeStrokeColor, ContextCompat.getColor(context, android.R.color.darker_gray)); <del> mStrokeCap = a.getString(R.styleable.CustomGauge_gaugeStrokeCap); <add> setStrokeWidth(a.getDimension(R.styleable.CustomGauge_gaugeStrokeWidth, 10)); <add> setStrokeColor(a.getColor(R.styleable.CustomGauge_gaugeStrokeColor, ContextCompat.getColor(context, android.R.color.darker_gray))); <add> setStrokeCap(a.getString(R.styleable.CustomGauge_gaugeStrokeCap)); <ide> <ide> // angel start and sweep (opposite direction 0, 270, 180, 90) <del> mStartAngel = a.getInt(R.styleable.CustomGauge_gaugeStartAngel, 0); <del> mSweepAngel = a.getInt(R.styleable.CustomGauge_gaugeSweepAngel, 360); <add> setStartAngel(a.getInt(R.styleable.CustomGauge_gaugeStartAngel, 0)); <add> setSweepAngel(a.getInt(R.styleable.CustomGauge_gaugeSweepAngel, 360)); <ide> <ide> // scale (from mStartValue to mEndValue) <del> mStartValue = a.getInt(R.styleable.CustomGauge_gaugeStartValue, 0); <del> mEndValue = a.getInt(R.styleable.CustomGauge_gaugeEndValue, 1000); <add> setStartValue(a.getInt(R.styleable.CustomGauge_gaugeStartValue, 0)); <add> setEndValue(a.getInt(R.styleable.CustomGauge_gaugeEndValue, 1000)); <ide> <ide> // pointer size and color <del> mPointSize = a.getInt(R.styleable.CustomGauge_gaugePointSize, 0); <del> mPointStartColor = a.getColor(R.styleable.CustomGauge_gaugePointStartColor, ContextCompat.getColor(context, android.R.color.white)); <del> mPointEndColor = a.getColor(R.styleable.CustomGauge_gaugePointEndColor, ContextCompat.getColor(context, android.R.color.white)); <add> setPointSize(a.getInt(R.styleable.CustomGauge_gaugePointSize, 0)); <add> setPointStartColor(a.getColor(R.styleable.CustomGauge_gaugePointStartColor, ContextCompat.getColor(context, android.R.color.white))); <add> setPointEndColor(a.getColor(R.styleable.CustomGauge_gaugePointEndColor, ContextCompat.getColor(context, android.R.color.white))); <ide> <ide> // divider options <ide> int dividerSize = a.getInt(R.styleable.CustomGauge_gaugeDividerSize, 0); <del> mDividerColor = a.getColor(R.styleable.CustomGauge_gaugeDividerColor, ContextCompat.getColor(context, android.R.color.white)); <add> setDividerColor(a.getColor(R.styleable.CustomGauge_gaugeDividerColor, ContextCompat.getColor(context, android.R.color.white))); <ide> int dividerStep = a.getInt(R.styleable.CustomGauge_gaugeDividerStep, 0); <del> mDividerDrawFirst = a.getBoolean(R.styleable.CustomGauge_gaugeDividerDrawFirst, true); <del> mDividerDrawLast = a.getBoolean(R.styleable.CustomGauge_gaugeDividerDrawLast, true); <add> setDividerDrawFirst(a.getBoolean(R.styleable.CustomGauge_gaugeDividerDrawFirst, true)); <add> setDividerDrawLast(a.getBoolean(R.styleable.CustomGauge_gaugeDividerDrawLast, true)); <ide> <ide> // calculating one point sweep <ide> mPointAngel = ((double) Math.abs(mSweepAngel) / (mEndValue - mStartValue)); <ide> float height = getHeight() - (paddingTop+paddingBottom); <ide> float radius = (width > height ? width/2 : height/2); <ide> <del> mRectLeft = width/2 - radius + paddingLeft; <del> mRectTop = height/2 - radius + paddingTop; <del> mRectRight = width/2 - radius + paddingLeft + width; <del> mRectBottom = height/2 - radius + paddingTop + height; <del> <del> mRect.set(mRectLeft, mRectTop, mRectRight, mRectBottom); <add> float rectLeft = width/2 - radius + paddingLeft; <add> float rectTop = height/2 - radius + paddingTop; <add> float rectRight = width/2 - radius + paddingLeft + width; <add> float rectBottom = height/2 - radius + paddingTop + height; <add> <add> mRect.set(rectLeft, rectTop, rectRight, rectBottom); <ide> <ide> mPaint.setColor(mStrokeColor); <ide> mPaint.setShader(null); <ide> public int getValue() { <ide> return mValue; <ide> } <add> <add> @SuppressWarnings("unused") <add> public float getStrokeWidth() { <add> return mStrokeWidth; <add> } <add> <add> public void setStrokeWidth(float strokeWidth) { <add> mStrokeWidth = strokeWidth; <add> } <add> <add> @SuppressWarnings("unused") <add> public int getStrokeColor() { <add> return mStrokeColor; <add> } <add> <add> public void setStrokeColor(int strokeColor) { <add> mStrokeColor = strokeColor; <add> } <add> <add> @SuppressWarnings("unused") <add> public String getStrokeCap() { <add> return mStrokeCap; <add> } <add> <add> public void setStrokeCap(String strokeCap) { <add> mStrokeCap = strokeCap; <add> } <add> <add> @SuppressWarnings("unused") <add> public int getStartAngel() { <add> return mStartAngel; <add> } <add> <add> public void setStartAngel(int startAngel) { <add> mStartAngel = startAngel; <add> } <add> <add> @SuppressWarnings("unused") <add> public int getSweepAngel() { <add> return mSweepAngel; <add> } <add> <add> public void setSweepAngel(int sweepAngel) { <add> mSweepAngel = sweepAngel; <add> } <add> <add> @SuppressWarnings("unused") <add> public int getStartValue() { <add> return mStartValue; <add> } <add> <add> public void setStartValue(int startValue) { <add> mStartValue = startValue; <add> } <add> <add> @SuppressWarnings("unused") <add> public int getEndValue() { <add> return mEndValue; <add> } <add> <add> public void setEndValue(int endValue) { <add> mEndValue = endValue; <add> } <add> <add> @SuppressWarnings("unused") <add> public int getPointSize() { <add> return mPointSize; <add> } <add> <add> public void setPointSize(int pointSize) { <add> mPointSize = pointSize; <add> } <add> <add> @SuppressWarnings("unused") <add> public int getPointStartColor() { <add> return mPointStartColor; <add> } <add> <add> public void setPointStartColor(int pointStartColor) { <add> mPointStartColor = pointStartColor; <add> } <add> <add> @SuppressWarnings("unused") <add> public int getPointEndColor() { <add> return mPointEndColor; <add> } <add> <add> public void setPointEndColor(int pointEndColor) { <add> mPointEndColor = pointEndColor; <add> } <add> <add> @SuppressWarnings("unused") <add> public int getDividerColor() { <add> return mDividerColor; <add> } <add> <add> public void setDividerColor(int dividerColor) { <add> mDividerColor = dividerColor; <add> } <add> <add> @SuppressWarnings("unused") <add> public boolean isDividerDrawFirst() { <add> return mDividerDrawFirst; <add> } <add> <add> public void setDividerDrawFirst(boolean dividerDrawFirst) { <add> mDividerDrawFirst = dividerDrawFirst; <add> } <add> <add> @SuppressWarnings("unused") <add> public boolean isDividerDrawLast() { <add> return mDividerDrawLast; <add> } <add> <add> public void setDividerDrawLast(boolean dividerDrawLast) { <add> mDividerDrawLast = dividerDrawLast; <add> } <add> <ide> }
Java
apache-2.0
bae543d1f93585ecc6f7b27ae639ac21e7195ba3
0
Nickname0806/Test_Q4,apache/tomcat,apache/tomcat,apache/tomcat,Nickname0806/Test_Q4,Nickname0806/Test_Q4,Nickname0806/Test_Q4,apache/tomcat,apache/tomcat
/* * 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.catalina.storeconfig; import java.io.PrintWriter; import org.apache.catalina.Context; import org.apache.catalina.Host; import org.apache.catalina.Server; import org.apache.catalina.Service; public interface IStoreConfig { /** * Get Configuration Registry * * @return aRegistry that handle the store operations */ StoreRegistry getRegistry(); /** * Set Configuration Registry * * @param aRegistry * aregistry that handle the store operations */ void setRegistry(StoreRegistry aRegistry); /** * Get associated server * * @return aServer the associated server */ Server getServer(); /** * Set associated server * * @param aServer the associated server */ void setServer(Server aServer); /** * Store the current StoreFactory Server. */ void storeConfig(); /** * Store the specified Server properties. * * @param aServer * Object to be stored */ boolean store(Server aServer); /** * Store the specified Server properties. * * @param aWriter * PrintWriter to which we are storing * @param indent * Number of spaces to indent this element * @param aServer * Object to be stored */ void store(PrintWriter aWriter, int indent, Server aServer) throws Exception; /** * Store the specified Service properties. * * @param aWriter * PrintWriter to which we are storing * @param indent * Number of spaces to indent this element * @param aService * Object to be stored */ void store(PrintWriter aWriter, int indent, Service aService) throws Exception; /** * Store the specified Host properties. * * @param aWriter * PrintWriter to which we are storing * @param indent * Number of spaces to indent this element * @param aHost * Object to be stored */ void store(PrintWriter aWriter, int indent, Host aHost) throws Exception; /** * Store the specified Context properties. * * @param aContext * Object to be stored */ boolean store(Context aContext); /** * Store the specified Context properties. * * @param aWriter * PrintWriter to which we are storing * @param indent * Number of spaces to indent this element * @param aContext * Object to be stored */ void store(PrintWriter aWriter, int indent, Context aContext) throws Exception; }
java/org/apache/catalina/storeconfig/IStoreConfig.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.catalina.storeconfig; import java.io.PrintWriter; import org.apache.catalina.Context; import org.apache.catalina.Host; import org.apache.catalina.Server; import org.apache.catalina.Service; public interface IStoreConfig { /** * Get Configuration Registry * * @return aRegistry that handle the store operations */ StoreRegistry getRegistry(); /** * Set Configuration Registry * * @param aRegistry * aregistry that handle the store operations */ void setRegistry(StoreRegistry aRegistry); /** * Get associated server * * @return aServer the associated server */ Server getServer(); /** * Set associated server * * @param aServer the associated server */ void setServer(Server aServer); /** * Store the current StoreFactory Server. * * @exception Exception * if an exception occurs while storing */ void storeConfig(); /** * Store the specified Server properties. * * @param aServer * Object to be stored * * @exception Exception * if an exception occurs while storing */ boolean store(Server aServer); /** * Store the specified Server properties. * * @param aWriter * PrintWriter to which we are storing * @param indent * Number of spaces to indent this element * @param aServer * Object to be stored */ void store(PrintWriter aWriter, int indent, Server aServer) throws Exception; /** * Store the specified Service properties. * * @param aWriter * PrintWriter to which we are storing * @param indent * Number of spaces to indent this element * @param aService * Object to be stored */ void store(PrintWriter aWriter, int indent, Service aService) throws Exception; /** * Store the specified Host properties. * * @param aWriter * PrintWriter to which we are storing * @param indent * Number of spaces to indent this element * @param aHost * Object to be stored */ void store(PrintWriter aWriter, int indent, Host aHost) throws Exception; /** * Store the specified Context properties. * * @param aContext * Object to be stored */ boolean store(Context aContext); /** * Store the specified Context properties. * * @param aWriter * PrintWriter to which we are storing * @param indent * Number of spaces to indent this element * @param aContext * Object to be stored */ void store(PrintWriter aWriter, int indent, Context aContext) throws Exception; }
Fix Javadoc nags git-svn-id: 79cef5a5a257cc9dbe40a45ac190115b4780e2d0@1607807 13f79535-47bb-0310-9956-ffa450edef68
java/org/apache/catalina/storeconfig/IStoreConfig.java
Fix Javadoc nags
<ide><path>ava/org/apache/catalina/storeconfig/IStoreConfig.java <ide> <ide> /** <ide> * Store the current StoreFactory Server. <del> * <del> * @exception Exception <del> * if an exception occurs while storing <ide> */ <ide> void storeConfig(); <ide> <ide> * <ide> * @param aServer <ide> * Object to be stored <del> * <del> * @exception Exception <del> * if an exception occurs while storing <ide> */ <ide> boolean store(Server aServer); <ide>
Java
mit
0691acd599ec45871ff66464802fe8ac3977a5d1
0
Rudolfking/TreatLookaheadMatcher
package hu.bme.mit.inf.treatengine; import java.util.ArrayList; import java.util.Arrays; import java.util.HashMap; import java.util.List; import java.util.Map.Entry; import org.eclipse.incquery.runtime.base.api.NavigationHelper; import org.eclipse.incquery.runtime.matchers.psystem.PVariable; import hu.bme.mit.inf.lookaheadmatcher.IConstraintEnumerator; import hu.bme.mit.inf.lookaheadmatcher.IDelta; import hu.bme.mit.inf.lookaheadmatcher.impl.AxisConstraint; import hu.bme.mit.inf.lookaheadmatcher.impl.FindConstraint; import hu.bme.mit.inf.lookaheadmatcher.impl.LookaheadMatching; import hu.bme.mit.inf.lookaheadmatcher.impl.RelationConstraint; import hu.bme.mit.inf.lookaheadmatcher.impl.SimpleConstraintEnumerator; import hu.bme.mit.inf.lookaheadmatcher.impl.TypeConstraint; public class TreatConstraintEnumerator implements IConstraintEnumerator { // a simple inner searcher used by easy mode SimpleConstraintEnumerator simpleInner; public TreatConstraintEnumerator(NavigationHelper navHelper) { simpleInner = new SimpleConstraintEnumerator(navHelper); } @Override public int getCost(AxisConstraint constraint, HashMap<PVariable, Object> matchingVariables) { // should use deltas!! TODO big TODO if (!constraint.hasMailboxContent()) return simpleInner.getCost(constraint, matchingVariables); else { if (!(constraint instanceof FindConstraint)) throw new AssertionError("Not findconstraint mailbox content is not supported!"); else { // get and return: this will filter by content return enumerateConstraint(constraint, matchingVariables).size(); } } // return 0; // something went bad } @Override public List<Object[]> enumerateConstraint(AxisConstraint constraint, HashMap<PVariable, Object> matchingVariables) { // tricking view ("rollback delta" for one time) view!! List<Object[]> candidates = simpleInner.enumerateConstraint(constraint, matchingVariables); List<Object[]> ret = null; // filter ret... (this can be really resource consuming!) if (constraint.hasMailboxContent()) { // filter by deltas List<IDelta> deltas = constraint.getMailboxContent(); // modifications: List<Integer> deleteIndexes = new ArrayList<Integer>(); ArrayList<Object> additions = new ArrayList<Object>(); // check all delta: for (IDelta deltai : deltas) { Delta delta = (Delta)deltai; if (constraint instanceof FindConstraint) { for (Entry<LookaheadMatching, Boolean> change : delta.getChangeset().entries()) { for (int cd = 0; cd < candidates.size(); cd++) { boolean equal = true; // add or remove from changeset! for (int vizs = 0; vizs < change.getKey().getParameterMatchValuesOnlyAsArray().length; vizs++) { if (change.getKey().getParameterMatchValuesOnlyAsArray()[vizs].equals(candidates.get(cd)[vizs]) == false) equal = false; } if (equal) { if (change.getValue() == false) deleteIndexes.add(cd); else additions.addAll(Arrays.asList(change.getKey().getParameterMatchValuesOnlyAsArray())); } } } } else if (constraint instanceof TypeConstraint) { // hope should not even implement throw new AssertionError("Not implemented!"); } else if (constraint instanceof RelationConstraint) { throw new AssertionError("Not implemented!"); } else { throw new AssertionError("Unknown constraint, which should be filtered!"); } } ret = new ArrayList<Object[]>(); // then delete the indexes, (candidate), so full for (int i=0;i<candidates.size();i++) { if (deleteIndexes.contains(Integer.valueOf(i))) continue; // leave out deleteds ret.add(candidates.get(i)); } } // if had delta, ret changed but okay if (ret == null) return candidates; // no mailbox return ret; // mailbox, processed } }
hu.bme.mit.inf.TreatEngine/src/hu/bme/mit/inf/treatengine/TreatConstraintEnumerator.java
package hu.bme.mit.inf.treatengine; import java.util.ArrayList; import java.util.Arrays; import java.util.HashMap; import java.util.List; import java.util.Map.Entry; import org.eclipse.incquery.runtime.base.api.NavigationHelper; import org.eclipse.incquery.runtime.matchers.psystem.PVariable; import hu.bme.mit.inf.lookaheadmatcher.IConstraintEnumerator; import hu.bme.mit.inf.lookaheadmatcher.IDelta; import hu.bme.mit.inf.lookaheadmatcher.impl.AxisConstraint; import hu.bme.mit.inf.lookaheadmatcher.impl.FindConstraint; import hu.bme.mit.inf.lookaheadmatcher.impl.LookaheadMatching; import hu.bme.mit.inf.lookaheadmatcher.impl.RelationConstraint; import hu.bme.mit.inf.lookaheadmatcher.impl.SimpleConstraintEnumerator; import hu.bme.mit.inf.lookaheadmatcher.impl.TypeConstraint; public class TreatConstraintEnumerator implements IConstraintEnumerator { // a simple inner searcher used by easy mode SimpleConstraintEnumerator simpleInner; public TreatConstraintEnumerator(NavigationHelper navHelper) { simpleInner = new SimpleConstraintEnumerator(navHelper); } @Override public int getCost(AxisConstraint constraint, HashMap<PVariable, Object> matchingVariables) { // should use deltas!! TODO big TODO if (!(constraint instanceof FindConstraint)) return simpleInner.getCost(constraint, matchingVariables); else { // get and return } return 0; // something went bad } @Override public List<Object[]> enumerateConstraint(AxisConstraint constraint, HashMap<PVariable, Object> matchingVariables) { // tricking view ("rollback delta" for one time) view!! List<Object[]> candidates = simpleInner.enumerateConstraint(constraint, matchingVariables); List<Object[]> ret = null; // filter ret... if (constraint.hasMailboxContent()) { // int itemSize; // if (candidates.size() > 0) // itemSize = candidates.get(0).length; // else // itemSize = ((Delta)constraint.getMailboxContent().get(0)).getPattern().getParameters().size(); // fallback... // for (int i=0;i<candidates.length;i++) // { // candidates[i] = new ArrayList<Object>(); // for (int j=0;j<itemSize;j++) // candidates[i].add(ret.get(i * itemSize + j)); // } // filter by deltas List<IDelta> deltas = constraint.getMailboxContent(); // modifications: List<Integer> deleteIndexes = new ArrayList<Integer>(); ArrayList<Object> additions = new ArrayList<Object>(); // check all delta: for (IDelta deltai : deltas) { Delta delta = (Delta)deltai; if (constraint instanceof FindConstraint) { for (Entry<LookaheadMatching, Boolean> change : delta.getChangeset().entries()) { for (int cd = 0; cd < candidates.size(); cd++) { boolean equal = true; // add or remove from changeset! for (int vizs = 0; vizs < change.getKey().getParameterMatchValuesOnlyAsArray().length; vizs++) { if (change.getKey().getParameterMatchValuesOnlyAsArray()[vizs].equals(candidates.get(cd)[vizs]) == false) equal = false; } if (equal) { if (change.getValue() == false) deleteIndexes.add(cd); else additions.addAll(Arrays.asList(change.getKey().getParameterMatchValuesOnlyAsArray())); } } } } else if (constraint instanceof TypeConstraint) { // hope should not even implement throw new AssertionError("Not implemented!"); } else if (constraint instanceof RelationConstraint) { throw new AssertionError("Not implemented!"); } else { throw new AssertionError("Unknown constraint, which should be filtered!"); } } ret = new ArrayList<Object[]>(); // then delete the indexes, (candidate), so full for (int i=0;i<candidates.size();i++) { if (deleteIndexes.contains(Integer.valueOf(i))) continue; // leave out deleteds ret.add(candidates.get(i)); } } // if had delta, ret changed but okay if (ret == null) return candidates; // no mailbox return ret; // mailbox, processed } }
Treat enumerator getSize works as expected (maybe)
hu.bme.mit.inf.TreatEngine/src/hu/bme/mit/inf/treatengine/TreatConstraintEnumerator.java
Treat enumerator getSize works as expected (maybe)
<ide><path>u.bme.mit.inf.TreatEngine/src/hu/bme/mit/inf/treatengine/TreatConstraintEnumerator.java <ide> public int getCost(AxisConstraint constraint, HashMap<PVariable, Object> matchingVariables) <ide> { <ide> // should use deltas!! TODO big TODO <del> if (!(constraint instanceof FindConstraint)) <add> if (!constraint.hasMailboxContent()) <ide> return simpleInner.getCost(constraint, matchingVariables); <ide> else <ide> { <del> // get and return <del> <add> if (!(constraint instanceof FindConstraint)) <add> throw new AssertionError("Not findconstraint mailbox content is not supported!"); <add> else <add> { <add> // get and return: this will filter by content <add> return enumerateConstraint(constraint, matchingVariables).size(); <add> } <ide> } <del> return 0; // something went bad <add> // return 0; // something went bad <ide> } <ide> <ide> @Override <ide> <ide> List<Object[]> ret = null; <ide> <del> // filter ret... <add> // filter ret... (this can be really resource consuming!) <ide> if (constraint.hasMailboxContent()) <del> { <del>// int itemSize; <del>// if (candidates.size() > 0) <del>// itemSize = candidates.get(0).length; <del>// else <del>// itemSize = ((Delta)constraint.getMailboxContent().get(0)).getPattern().getParameters().size(); // fallback... <del>// for (int i=0;i<candidates.length;i++) <del>// { <del>// candidates[i] = new ArrayList<Object>(); <del>// for (int j=0;j<itemSize;j++) <del>// candidates[i].add(ret.get(i * itemSize + j)); <del>// } <del> <add> { <ide> // filter by deltas <ide> List<IDelta> deltas = constraint.getMailboxContent(); <ide> // modifications:
Java
apache-2.0
060aa608339be08d91036c766347aff9713e1623
0
ppavlidis/Gemma,ppavlidis/Gemma,ppavlidis/Gemma,ppavlidis/Gemma,ppavlidis/Gemma,ppavlidis/Gemma,ppavlidis/Gemma
gemma-web/src/main/java/ubic/gemma/web/controller/diff/DifferentialExpressionMetaValueObject.java
/* * The Gemma project * * Copyright (c) 2008 University of British Columbia * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package ubic.gemma.web.controller.diff; import java.util.List; import ubic.gemma.analysis.expression.diff.DifferentialExpressionValueObject; /** * @author keshav * @version $Id$ */ public class DifferentialExpressionMetaValueObject { List<DifferentialExpressionValueObject> differentialExpressionValueObjects = null; public DifferentialExpressionMetaValueObject( List<DifferentialExpressionValueObject> differentialExpressionValueObjects ) { super(); this.differentialExpressionValueObjects = differentialExpressionValueObjects; } /* * (non-Javadoc) * * @see java.lang.Object#toString() */ @Override public String toString() { StringBuilder buf = new StringBuilder(); for ( DifferentialExpressionValueObject devo : differentialExpressionValueObjects ) { buf.append( devo.toString() ); buf.append( "\n" ); } return buf.toString(); } }
removed unused value object
gemma-web/src/main/java/ubic/gemma/web/controller/diff/DifferentialExpressionMetaValueObject.java
removed unused value object
<ide><path>emma-web/src/main/java/ubic/gemma/web/controller/diff/DifferentialExpressionMetaValueObject.java <del>/* <del> * The Gemma project <del> * <del> * Copyright (c) 2008 University of British Columbia <del> * <del> * Licensed under the Apache License, Version 2.0 (the "License"); <del> * you may not use this file except in compliance with the License. <del> * You may obtain a copy of the License at <del> * <del> * http://www.apache.org/licenses/LICENSE-2.0 <del> * <del> * Unless required by applicable law or agreed to in writing, software <del> * distributed under the License is distributed on an "AS IS" BASIS, <del> * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. <del> * See the License for the specific language governing permissions and <del> * limitations under the License. <del> * <del> */ <del>package ubic.gemma.web.controller.diff; <del> <del>import java.util.List; <del> <del>import ubic.gemma.analysis.expression.diff.DifferentialExpressionValueObject; <del> <del> <del>/** <del> * @author keshav <del> * @version $Id$ <del> */ <del>public class DifferentialExpressionMetaValueObject { <del> <del> List<DifferentialExpressionValueObject> differentialExpressionValueObjects = null; <del> <del> public DifferentialExpressionMetaValueObject( <del> List<DifferentialExpressionValueObject> differentialExpressionValueObjects ) { <del> super(); <del> this.differentialExpressionValueObjects = differentialExpressionValueObjects; <del> } <del> <del> /* <del> * (non-Javadoc) <del> * <del> * @see java.lang.Object#toString() <del> */ <del> @Override <del> public String toString() { <del> StringBuilder buf = new StringBuilder(); <del> for ( DifferentialExpressionValueObject devo : differentialExpressionValueObjects ) { <del> buf.append( devo.toString() ); <del> buf.append( "\n" ); <del> } <del> return buf.toString(); <del> } <del> <del>}
Java
apache-2.0
7f307dfe8ee85cf62ef409bb64e8c1edb4fac4fb
0
akosyakov/intellij-community,kdwink/intellij-community,vladmm/intellij-community,nicolargo/intellij-community,ahb0327/intellij-community,signed/intellij-community,suncycheng/intellij-community,Distrotech/intellij-community,mglukhikh/intellij-community,holmes/intellij-community,clumsy/intellij-community,gnuhub/intellij-community,idea4bsd/idea4bsd,apixandru/intellij-community,ibinti/intellij-community,apixandru/intellij-community,ryano144/intellij-community,ahb0327/intellij-community,allotria/intellij-community,ryano144/intellij-community,blademainer/intellij-community,fnouama/intellij-community,supersven/intellij-community,semonte/intellij-community,vladmm/intellij-community,akosyakov/intellij-community,fitermay/intellij-community,michaelgallacher/intellij-community,Lekanich/intellij-community,Lekanich/intellij-community,fitermay/intellij-community,alphafoobar/intellij-community,tmpgit/intellij-community,alphafoobar/intellij-community,Distrotech/intellij-community,da1z/intellij-community,Distrotech/intellij-community,fnouama/intellij-community,lucafavatella/intellij-community,adedayo/intellij-community,vladmm/intellij-community,alphafoobar/intellij-community,robovm/robovm-studio,akosyakov/intellij-community,wreckJ/intellij-community,ivan-fedorov/intellij-community,samthor/intellij-community,youdonghai/intellij-community,hurricup/intellij-community,adedayo/intellij-community,MER-GROUP/intellij-community,youdonghai/intellij-community,kdwink/intellij-community,ivan-fedorov/intellij-community,Distrotech/intellij-community,adedayo/intellij-community,MichaelNedzelsky/intellij-community,fnouama/intellij-community,michaelgallacher/intellij-community,ftomassetti/intellij-community,muntasirsyed/intellij-community,dslomov/intellij-community,fitermay/intellij-community,fengbaicanhe/intellij-community,youdonghai/intellij-community,samthor/intellij-community,TangHao1987/intellij-community,pwoodworth/intellij-community,vladmm/intellij-community,ThiagoGarciaAlves/intellij-community,alphafoobar/intellij-community,apixandru/intellij-community,youdonghai/intellij-community,mglukhikh/intellij-community,salguarnieri/intellij-community,robovm/robovm-studio,ibinti/intellij-community,ibinti/intellij-community,holmes/intellij-community,izonder/intellij-community,xfournet/intellij-community,izonder/intellij-community,blademainer/intellij-community,fnouama/intellij-community,vvv1559/intellij-community,supersven/intellij-community,semonte/intellij-community,Lekanich/intellij-community,jagguli/intellij-community,youdonghai/intellij-community,orekyuu/intellij-community,muntasirsyed/intellij-community,allotria/intellij-community,FHannes/intellij-community,retomerz/intellij-community,gnuhub/intellij-community,lucafavatella/intellij-community,dslomov/intellij-community,akosyakov/intellij-community,tmpgit/intellij-community,FHannes/intellij-community,semonte/intellij-community,mglukhikh/intellij-community,clumsy/intellij-community,robovm/robovm-studio,vvv1559/intellij-community,izonder/intellij-community,pwoodworth/intellij-community,samthor/intellij-community,robovm/robovm-studio,izonder/intellij-community,blademainer/intellij-community,salguarnieri/intellij-community,hurricup/intellij-community,da1z/intellij-community,fengbaicanhe/intellij-community,ivan-fedorov/intellij-community,fnouama/intellij-community,apixandru/intellij-community,ibinti/intellij-community,adedayo/intellij-community,ryano144/intellij-community,kool79/intellij-community,asedunov/intellij-community,allotria/intellij-community,jagguli/intellij-community,signed/intellij-community,ol-loginov/intellij-community,amith01994/intellij-community,amith01994/intellij-community,kool79/intellij-community,supersven/intellij-community,holmes/intellij-community,holmes/intellij-community,petteyg/intellij-community,MER-GROUP/intellij-community,orekyuu/intellij-community,youdonghai/intellij-community,apixandru/intellij-community,muntasirsyed/intellij-community,signed/intellij-community,youdonghai/intellij-community,kool79/intellij-community,suncycheng/intellij-community,tmpgit/intellij-community,tmpgit/intellij-community,holmes/intellij-community,ivan-fedorov/intellij-community,suncycheng/intellij-community,orekyuu/intellij-community,mglukhikh/intellij-community,retomerz/intellij-community,wreckJ/intellij-community,SerCeMan/intellij-community,izonder/intellij-community,supersven/intellij-community,kool79/intellij-community,da1z/intellij-community,samthor/intellij-community,nicolargo/intellij-community,lucafavatella/intellij-community,salguarnieri/intellij-community,Lekanich/intellij-community,idea4bsd/idea4bsd,slisson/intellij-community,fitermay/intellij-community,MichaelNedzelsky/intellij-community,da1z/intellij-community,allotria/intellij-community,ibinti/intellij-community,supersven/intellij-community,hurricup/intellij-community,SerCeMan/intellij-community,ryano144/intellij-community,jagguli/intellij-community,samthor/intellij-community,fengbaicanhe/intellij-community,pwoodworth/intellij-community,izonder/intellij-community,FHannes/intellij-community,salguarnieri/intellij-community,kool79/intellij-community,michaelgallacher/intellij-community,semonte/intellij-community,TangHao1987/intellij-community,ryano144/intellij-community,pwoodworth/intellij-community,dslomov/intellij-community,ThiagoGarciaAlves/intellij-community,retomerz/intellij-community,amith01994/intellij-community,muntasirsyed/intellij-community,FHannes/intellij-community,michaelgallacher/intellij-community,MER-GROUP/intellij-community,idea4bsd/idea4bsd,ThiagoGarciaAlves/intellij-community,apixandru/intellij-community,kool79/intellij-community,mglukhikh/intellij-community,idea4bsd/idea4bsd,blademainer/intellij-community,apixandru/intellij-community,fnouama/intellij-community,caot/intellij-community,retomerz/intellij-community,ftomassetti/intellij-community,asedunov/intellij-community,pwoodworth/intellij-community,clumsy/intellij-community,alphafoobar/intellij-community,diorcety/intellij-community,Lekanich/intellij-community,jagguli/intellij-community,asedunov/intellij-community,muntasirsyed/intellij-community,amith01994/intellij-community,TangHao1987/intellij-community,MER-GROUP/intellij-community,fengbaicanhe/intellij-community,lucafavatella/intellij-community,ftomassetti/intellij-community,semonte/intellij-community,vvv1559/intellij-community,MER-GROUP/intellij-community,tmpgit/intellij-community,ivan-fedorov/intellij-community,petteyg/intellij-community,supersven/intellij-community,fitermay/intellij-community,suncycheng/intellij-community,diorcety/intellij-community,xfournet/intellij-community,SerCeMan/intellij-community,signed/intellij-community,idea4bsd/idea4bsd,ahb0327/intellij-community,supersven/intellij-community,mglukhikh/intellij-community,muntasirsyed/intellij-community,FHannes/intellij-community,youdonghai/intellij-community,wreckJ/intellij-community,signed/intellij-community,da1z/intellij-community,robovm/robovm-studio,vladmm/intellij-community,fengbaicanhe/intellij-community,pwoodworth/intellij-community,caot/intellij-community,diorcety/intellij-community,izonder/intellij-community,alphafoobar/intellij-community,petteyg/intellij-community,muntasirsyed/intellij-community,vladmm/intellij-community,semonte/intellij-community,orekyuu/intellij-community,fengbaicanhe/intellij-community,apixandru/intellij-community,lucafavatella/intellij-community,ThiagoGarciaAlves/intellij-community,mglukhikh/intellij-community,TangHao1987/intellij-community,semonte/intellij-community,xfournet/intellij-community,signed/intellij-community,MichaelNedzelsky/intellij-community,allotria/intellij-community,adedayo/intellij-community,jagguli/intellij-community,fnouama/intellij-community,suncycheng/intellij-community,wreckJ/intellij-community,pwoodworth/intellij-community,Distrotech/intellij-community,allotria/intellij-community,adedayo/intellij-community,tmpgit/intellij-community,hurricup/intellij-community,ftomassetti/intellij-community,michaelgallacher/intellij-community,allotria/intellij-community,clumsy/intellij-community,MichaelNedzelsky/intellij-community,fitermay/intellij-community,fitermay/intellij-community,clumsy/intellij-community,idea4bsd/idea4bsd,robovm/robovm-studio,ryano144/intellij-community,ryano144/intellij-community,xfournet/intellij-community,izonder/intellij-community,semonte/intellij-community,tmpgit/intellij-community,caot/intellij-community,vladmm/intellij-community,dslomov/intellij-community,diorcety/intellij-community,petteyg/intellij-community,signed/intellij-community,asedunov/intellij-community,ivan-fedorov/intellij-community,akosyakov/intellij-community,dslomov/intellij-community,salguarnieri/intellij-community,MER-GROUP/intellij-community,da1z/intellij-community,akosyakov/intellij-community,vvv1559/intellij-community,adedayo/intellij-community,suncycheng/intellij-community,ahb0327/intellij-community,ThiagoGarciaAlves/intellij-community,mglukhikh/intellij-community,Distrotech/intellij-community,jagguli/intellij-community,MichaelNedzelsky/intellij-community,apixandru/intellij-community,vvv1559/intellij-community,nicolargo/intellij-community,xfournet/intellij-community,muntasirsyed/intellij-community,nicolargo/intellij-community,fitermay/intellij-community,jagguli/intellij-community,asedunov/intellij-community,idea4bsd/idea4bsd,ThiagoGarciaAlves/intellij-community,vvv1559/intellij-community,allotria/intellij-community,fitermay/intellij-community,diorcety/intellij-community,kool79/intellij-community,diorcety/intellij-community,wreckJ/intellij-community,kool79/intellij-community,allotria/intellij-community,fengbaicanhe/intellij-community,samthor/intellij-community,TangHao1987/intellij-community,diorcety/intellij-community,akosyakov/intellij-community,SerCeMan/intellij-community,petteyg/intellij-community,slisson/intellij-community,hurricup/intellij-community,slisson/intellij-community,diorcety/intellij-community,ThiagoGarciaAlves/intellij-community,da1z/intellij-community,hurricup/intellij-community,da1z/intellij-community,holmes/intellij-community,nicolargo/intellij-community,kdwink/intellij-community,michaelgallacher/intellij-community,caot/intellij-community,kdwink/intellij-community,holmes/intellij-community,vvv1559/intellij-community,blademainer/intellij-community,clumsy/intellij-community,supersven/intellij-community,Distrotech/intellij-community,alphafoobar/intellij-community,hurricup/intellij-community,MER-GROUP/intellij-community,akosyakov/intellij-community,mglukhikh/intellij-community,asedunov/intellij-community,pwoodworth/intellij-community,kool79/intellij-community,apixandru/intellij-community,ahb0327/intellij-community,asedunov/intellij-community,slisson/intellij-community,slisson/intellij-community,orekyuu/intellij-community,gnuhub/intellij-community,caot/intellij-community,MER-GROUP/intellij-community,MichaelNedzelsky/intellij-community,blademainer/intellij-community,ryano144/intellij-community,SerCeMan/intellij-community,diorcety/intellij-community,holmes/intellij-community,tmpgit/intellij-community,allotria/intellij-community,dslomov/intellij-community,ThiagoGarciaAlves/intellij-community,gnuhub/intellij-community,TangHao1987/intellij-community,FHannes/intellij-community,Lekanich/intellij-community,robovm/robovm-studio,petteyg/intellij-community,retomerz/intellij-community,retomerz/intellij-community,orekyuu/intellij-community,wreckJ/intellij-community,youdonghai/intellij-community,gnuhub/intellij-community,adedayo/intellij-community,apixandru/intellij-community,robovm/robovm-studio,semonte/intellij-community,amith01994/intellij-community,Lekanich/intellij-community,MichaelNedzelsky/intellij-community,pwoodworth/intellij-community,robovm/robovm-studio,kdwink/intellij-community,muntasirsyed/intellij-community,dslomov/intellij-community,suncycheng/intellij-community,wreckJ/intellij-community,Lekanich/intellij-community,FHannes/intellij-community,ahb0327/intellij-community,youdonghai/intellij-community,wreckJ/intellij-community,diorcety/intellij-community,apixandru/intellij-community,slisson/intellij-community,ftomassetti/intellij-community,MichaelNedzelsky/intellij-community,retomerz/intellij-community,caot/intellij-community,suncycheng/intellij-community,amith01994/intellij-community,ftomassetti/intellij-community,amith01994/intellij-community,petteyg/intellij-community,blademainer/intellij-community,wreckJ/intellij-community,kdwink/intellij-community,samthor/intellij-community,hurricup/intellij-community,hurricup/intellij-community,allotria/intellij-community,adedayo/intellij-community,vladmm/intellij-community,salguarnieri/intellij-community,alphafoobar/intellij-community,youdonghai/intellij-community,vladmm/intellij-community,retomerz/intellij-community,wreckJ/intellij-community,fnouama/intellij-community,hurricup/intellij-community,gnuhub/intellij-community,xfournet/intellij-community,amith01994/intellij-community,xfournet/intellij-community,michaelgallacher/intellij-community,lucafavatella/intellij-community,kool79/intellij-community,xfournet/intellij-community,fitermay/intellij-community,ivan-fedorov/intellij-community,wreckJ/intellij-community,samthor/intellij-community,suncycheng/intellij-community,clumsy/intellij-community,TangHao1987/intellij-community,caot/intellij-community,Lekanich/intellij-community,salguarnieri/intellij-community,ftomassetti/intellij-community,blademainer/intellij-community,ivan-fedorov/intellij-community,supersven/intellij-community,vvv1559/intellij-community,da1z/intellij-community,samthor/intellij-community,retomerz/intellij-community,ol-loginov/intellij-community,clumsy/intellij-community,nicolargo/intellij-community,gnuhub/intellij-community,diorcety/intellij-community,vvv1559/intellij-community,ibinti/intellij-community,kdwink/intellij-community,samthor/intellij-community,allotria/intellij-community,vladmm/intellij-community,Distrotech/intellij-community,izonder/intellij-community,supersven/intellij-community,fnouama/intellij-community,salguarnieri/intellij-community,da1z/intellij-community,TangHao1987/intellij-community,TangHao1987/intellij-community,wreckJ/intellij-community,pwoodworth/intellij-community,ol-loginov/intellij-community,michaelgallacher/intellij-community,xfournet/intellij-community,semonte/intellij-community,Distrotech/intellij-community,fengbaicanhe/intellij-community,SerCeMan/intellij-community,FHannes/intellij-community,fengbaicanhe/intellij-community,ahb0327/intellij-community,ftomassetti/intellij-community,akosyakov/intellij-community,ol-loginov/intellij-community,akosyakov/intellij-community,ivan-fedorov/intellij-community,vladmm/intellij-community,signed/intellij-community,ThiagoGarciaAlves/intellij-community,izonder/intellij-community,alphafoobar/intellij-community,ahb0327/intellij-community,robovm/robovm-studio,MER-GROUP/intellij-community,lucafavatella/intellij-community,xfournet/intellij-community,ryano144/intellij-community,caot/intellij-community,fengbaicanhe/intellij-community,pwoodworth/intellij-community,Distrotech/intellij-community,ftomassetti/intellij-community,MichaelNedzelsky/intellij-community,michaelgallacher/intellij-community,alphafoobar/intellij-community,vvv1559/intellij-community,muntasirsyed/intellij-community,asedunov/intellij-community,da1z/intellij-community,lucafavatella/intellij-community,akosyakov/intellij-community,orekyuu/intellij-community,FHannes/intellij-community,nicolargo/intellij-community,SerCeMan/intellij-community,Distrotech/intellij-community,ibinti/intellij-community,kdwink/intellij-community,caot/intellij-community,lucafavatella/intellij-community,retomerz/intellij-community,caot/intellij-community,jagguli/intellij-community,dslomov/intellij-community,fnouama/intellij-community,allotria/intellij-community,mglukhikh/intellij-community,ol-loginov/intellij-community,suncycheng/intellij-community,vvv1559/intellij-community,fnouama/intellij-community,ivan-fedorov/intellij-community,FHannes/intellij-community,caot/intellij-community,supersven/intellij-community,FHannes/intellij-community,michaelgallacher/intellij-community,MichaelNedzelsky/intellij-community,blademainer/intellij-community,apixandru/intellij-community,ol-loginov/intellij-community,clumsy/intellij-community,xfournet/intellij-community,MER-GROUP/intellij-community,salguarnieri/intellij-community,alphafoobar/intellij-community,semonte/intellij-community,tmpgit/intellij-community,signed/intellij-community,fitermay/intellij-community,salguarnieri/intellij-community,mglukhikh/intellij-community,alphafoobar/intellij-community,holmes/intellij-community,ftomassetti/intellij-community,lucafavatella/intellij-community,ibinti/intellij-community,idea4bsd/idea4bsd,slisson/intellij-community,signed/intellij-community,kdwink/intellij-community,michaelgallacher/intellij-community,slisson/intellij-community,signed/intellij-community,MER-GROUP/intellij-community,slisson/intellij-community,semonte/intellij-community,samthor/intellij-community,orekyuu/intellij-community,SerCeMan/intellij-community,idea4bsd/idea4bsd,diorcety/intellij-community,asedunov/intellij-community,gnuhub/intellij-community,nicolargo/intellij-community,semonte/intellij-community,fitermay/intellij-community,hurricup/intellij-community,SerCeMan/intellij-community,amith01994/intellij-community,lucafavatella/intellij-community,salguarnieri/intellij-community,ftomassetti/intellij-community,da1z/intellij-community,lucafavatella/intellij-community,asedunov/intellij-community,apixandru/intellij-community,ol-loginov/intellij-community,ol-loginov/intellij-community,blademainer/intellij-community,clumsy/intellij-community,ol-loginov/intellij-community,ibinti/intellij-community,robovm/robovm-studio,ahb0327/intellij-community,kool79/intellij-community,holmes/intellij-community,ahb0327/intellij-community,izonder/intellij-community,nicolargo/intellij-community,retomerz/intellij-community,xfournet/intellij-community,adedayo/intellij-community,supersven/intellij-community,jagguli/intellij-community,pwoodworth/intellij-community,vladmm/intellij-community,orekyuu/intellij-community,idea4bsd/idea4bsd,asedunov/intellij-community,orekyuu/intellij-community,ol-loginov/intellij-community,Lekanich/intellij-community,TangHao1987/intellij-community,TangHao1987/intellij-community,vvv1559/intellij-community,mglukhikh/intellij-community,tmpgit/intellij-community,hurricup/intellij-community,ol-loginov/intellij-community,holmes/intellij-community,petteyg/intellij-community,dslomov/intellij-community,kdwink/intellij-community,orekyuu/intellij-community,tmpgit/intellij-community,gnuhub/intellij-community,gnuhub/intellij-community,slisson/intellij-community,jagguli/intellij-community,FHannes/intellij-community,ryano144/intellij-community,tmpgit/intellij-community,dslomov/intellij-community,kool79/intellij-community,ibinti/intellij-community,ahb0327/intellij-community,retomerz/intellij-community,holmes/intellij-community,ol-loginov/intellij-community,idea4bsd/idea4bsd,fitermay/intellij-community,idea4bsd/idea4bsd,ibinti/intellij-community,salguarnieri/intellij-community,gnuhub/intellij-community,FHannes/intellij-community,izonder/intellij-community,signed/intellij-community,robovm/robovm-studio,slisson/intellij-community,TangHao1987/intellij-community,Lekanich/intellij-community,lucafavatella/intellij-community,clumsy/intellij-community,dslomov/intellij-community,clumsy/intellij-community,orekyuu/intellij-community,petteyg/intellij-community,muntasirsyed/intellij-community,blademainer/intellij-community,SerCeMan/intellij-community,akosyakov/intellij-community,ahb0327/intellij-community,ibinti/intellij-community,MichaelNedzelsky/intellij-community,fengbaicanhe/intellij-community,muntasirsyed/intellij-community,amith01994/intellij-community,nicolargo/intellij-community,amith01994/intellij-community,ibinti/intellij-community,youdonghai/intellij-community,ivan-fedorov/intellij-community,hurricup/intellij-community,caot/intellij-community,petteyg/intellij-community,michaelgallacher/intellij-community,jagguli/intellij-community,mglukhikh/intellij-community,youdonghai/intellij-community,xfournet/intellij-community,ftomassetti/intellij-community,MichaelNedzelsky/intellij-community,idea4bsd/idea4bsd,MER-GROUP/intellij-community,retomerz/intellij-community,ivan-fedorov/intellij-community,kdwink/intellij-community,ryano144/intellij-community,adedayo/intellij-community,asedunov/intellij-community,nicolargo/intellij-community,petteyg/intellij-community,vvv1559/intellij-community,blademainer/intellij-community,amith01994/intellij-community,gnuhub/intellij-community,ryano144/intellij-community,ThiagoGarciaAlves/intellij-community,SerCeMan/intellij-community,Lekanich/intellij-community,jagguli/intellij-community,kdwink/intellij-community,suncycheng/intellij-community,dslomov/intellij-community,adedayo/intellij-community,nicolargo/intellij-community,fnouama/intellij-community,signed/intellij-community,petteyg/intellij-community,SerCeMan/intellij-community,samthor/intellij-community,slisson/intellij-community,suncycheng/intellij-community,Distrotech/intellij-community,ThiagoGarciaAlves/intellij-community,fengbaicanhe/intellij-community,asedunov/intellij-community,ThiagoGarciaAlves/intellij-community,da1z/intellij-community
package com.intellij.structuralsearch.impl.matcher.compiler; import com.intellij.codeInsight.template.Template; import com.intellij.codeInsight.template.TemplateManager; import com.intellij.dupLocator.iterators.ArrayBackedNodeIterator; import com.intellij.dupLocator.util.NodeFilter; import com.intellij.lang.Language; import com.intellij.openapi.application.ApplicationManager; import com.intellij.openapi.fileTypes.FileType; import com.intellij.openapi.fileTypes.LanguageFileType; import com.intellij.openapi.project.Project; import com.intellij.openapi.util.text.StringUtil; import com.intellij.psi.PsiElement; import com.intellij.psi.PsiErrorElement; import com.intellij.psi.PsiFile; import com.intellij.psi.PsiRecursiveElementWalkingVisitor; import com.intellij.psi.impl.source.PsiFileImpl; import com.intellij.psi.impl.source.tree.LeafElement; import com.intellij.psi.search.GlobalSearchScope; import com.intellij.psi.search.LocalSearchScope; import com.intellij.psi.util.PsiUtilCore; import com.intellij.structuralsearch.*; import com.intellij.structuralsearch.impl.matcher.CompiledPattern; import com.intellij.structuralsearch.impl.matcher.MatcherImplUtil; import com.intellij.structuralsearch.impl.matcher.PatternTreeContext; import com.intellij.structuralsearch.impl.matcher.filters.LexicalNodesFilter; import com.intellij.structuralsearch.impl.matcher.handlers.MatchPredicate; import com.intellij.structuralsearch.impl.matcher.handlers.SubstitutionHandler; import com.intellij.structuralsearch.impl.matcher.predicates.*; import com.intellij.structuralsearch.plugin.ui.Configuration; import com.intellij.util.IncorrectOperationException; import gnu.trove.TIntArrayList; import gnu.trove.TIntHashSet; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import java.util.*; import java.util.regex.Matcher; import java.util.regex.Pattern; /** * Compiles the handlers for usability */ public class PatternCompiler { private static CompileContext lastTestingContext; public static void transformOldPattern(MatchOptions options) { StringToConstraintsTransformer.transformOldPattern(options); } public static CompiledPattern compilePattern(final Project project, final MatchOptions options) throws MalformedPatternException, UnsupportedOperationException { FileType fileType = options.getFileType(); assert fileType instanceof LanguageFileType; Language language = ((LanguageFileType)fileType).getLanguage(); StructuralSearchProfile profile = StructuralSearchUtil.getProfileByLanguage(language); assert profile != null; CompiledPattern result = profile.createCompiledPattern(); final String[] prefixes = result.getTypedVarPrefixes(); assert prefixes.length > 0; final CompileContext context = new CompileContext(); if (ApplicationManager.getApplication().isUnitTestMode()) lastTestingContext = context; /*CompiledPattern result = options.getFileType() == StdFileTypes.JAVA ? new JavaCompiledPattern() : new XmlCompiledPattern();*/ try { context.init(result, options, project, options.getScope() instanceof GlobalSearchScope); List<PsiElement> elements = compileByAllPrefixes(project, options, result, context, prefixes); context.getPattern().setNodes(elements); if (context.getSearchHelper().doOptimizing() && context.getSearchHelper().isScannedSomething()) { final Set<PsiFile> set = context.getSearchHelper().getFilesSetToScan(); final List<PsiFile> filesToScan = new ArrayList<PsiFile>(set.size()); final GlobalSearchScope scope = (GlobalSearchScope)options.getScope(); for (final PsiFile file : set) { if (!scope.contains(file.getVirtualFile())) { continue; } if (file instanceof PsiFileImpl) { ((PsiFileImpl)file).clearCaches(); } filesToScan.add(file); } if (filesToScan.size() == 0) { throw new MalformedPatternException(SSRBundle.message("ssr.will.not.find.anything")); } result.setScope( new LocalSearchScope(PsiUtilCore.toPsiElementArray(filesToScan)) ); } } finally { context.clear(); } return result; } public static String getLastFindPlan() { return ((TestModeOptimizingSearchHelper)lastTestingContext.getSearchHelper()).getSearchPlan(); } @NotNull private static List<PsiElement> compileByAllPrefixes(Project project, MatchOptions options, CompiledPattern pattern, CompileContext context, String[] applicablePrefixes) { if (applicablePrefixes.length == 0) { return Collections.emptyList(); } List<PsiElement> elements = doCompile(project, options, pattern, new ConstantPrefixProvider(applicablePrefixes[0]), context); if (elements.isEmpty()) { return elements; } final PsiFile file = elements.get(0).getContainingFile(); if (file == null) { return elements; } final PsiElement last = elements.get(elements.size() - 1); final Pattern[] patterns = new Pattern[applicablePrefixes.length]; for (int i = 0; i < applicablePrefixes.length; i++) { String s = StructuralSearchUtil.shieldSpecialChars(applicablePrefixes[i]); patterns[i] = Pattern.compile(s + "\\w+\\b"); } final int[] varEndOffsets = findAllTypedVarOffsets(file, patterns); final int patternEndOffset = last.getTextRange().getEndOffset(); if (elements.size() == 0 || checkErrorElements(file, patternEndOffset, patternEndOffset, varEndOffsets, true) != Boolean.TRUE) { return elements; } final int varCount = varEndOffsets.length; final String[] prefixSequence = new String[varCount]; for (int i = 0; i < varCount; i++) { prefixSequence[i] = applicablePrefixes[0]; } final List<PsiElement> finalElements = compileByPrefixes(project, options, pattern, context, applicablePrefixes, patterns, prefixSequence, 0); return finalElements != null ? finalElements : doCompile(project, options, pattern, new ConstantPrefixProvider(applicablePrefixes[0]), context); } @Nullable private static List<PsiElement> compileByPrefixes(Project project, MatchOptions options, CompiledPattern pattern, CompileContext context, String[] applicablePrefixes, Pattern[] substitutionPatterns, String[] prefixSequence, int index) { if (index >= prefixSequence.length) { final List<PsiElement> elements = doCompile(project, options, pattern, new ArrayPrefixProvider(prefixSequence), context); if (elements.isEmpty()) { return elements; } final PsiElement parent = elements.get(0).getParent(); final PsiElement last = elements.get(elements.size() - 1); final int[] varEndOffsets = findAllTypedVarOffsets(parent.getContainingFile(), substitutionPatterns); final int patternEndOffset = last.getTextRange().getEndOffset(); return checkErrorElements(parent, patternEndOffset, patternEndOffset, varEndOffsets, false) != Boolean.TRUE ? elements : null; } String[] alternativeVariant = null; for (String applicablePrefix : applicablePrefixes) { prefixSequence[index] = applicablePrefix; List<PsiElement> elements = doCompile(project, options, pattern, new ArrayPrefixProvider(prefixSequence), context); if (elements.isEmpty()) { return elements; } final PsiFile file = elements.get(0).getContainingFile(); if (file == null) { return elements; } final int[] varEndOffsets = findAllTypedVarOffsets(file, substitutionPatterns); final int offset = varEndOffsets[index]; final int patternEndOffset = elements.get(elements.size() - 1).getTextRange().getEndOffset(); final Boolean result = checkErrorElements(file, offset, patternEndOffset, varEndOffsets, false); if (result == Boolean.TRUE) { continue; } if (result == Boolean.FALSE || (result == null && alternativeVariant == null)) { final List<PsiElement> finalElements = compileByPrefixes(project, options, pattern, context, applicablePrefixes, substitutionPatterns, prefixSequence, index + 1); if (finalElements != null) { if (result == Boolean.FALSE) { return finalElements; } alternativeVariant = new String[prefixSequence.length]; System.arraycopy(prefixSequence, 0, alternativeVariant, 0, prefixSequence.length); } } } return alternativeVariant != null ? compileByPrefixes(project, options, pattern, context, applicablePrefixes, substitutionPatterns, alternativeVariant, index + 1) : null; } @NotNull private static int[] findAllTypedVarOffsets(final PsiFile file, final Pattern[] substitutionPatterns) { final TIntHashSet result = new TIntHashSet(); file.accept(new PsiRecursiveElementWalkingVisitor() { @Override public void visitElement(PsiElement element) { super.visitElement(element); if (element instanceof LeafElement) { final String text = element.getText(); for (Pattern pattern : substitutionPatterns) { final Matcher matcher = pattern.matcher(text); while (matcher.find()) { result.add(element.getTextRange().getStartOffset() + matcher.end()); } } } } }); final int[] resultArray = result.toArray(); Arrays.sort(resultArray); return resultArray; } /** * False: there are no error elements before offset, except patternEndOffset * Null: there are only error elements located exactly after template variables or at the end of the pattern * True: otherwise */ @Nullable private static Boolean checkErrorElements(PsiElement element, final int offset, final int patternEndOffset, final int[] varEndOffsets, final boolean strict) { final TIntArrayList errorOffsets = new TIntArrayList(); final boolean[] containsErrorTail = {false}; final TIntHashSet varEndOffsetsSet = new TIntHashSet(varEndOffsets); element.accept(new PsiRecursiveElementWalkingVisitor() { @Override public void visitElement(PsiElement element) { super.visitElement(element); if (!(element instanceof PsiErrorElement)) { return; } final int startOffset = element.getTextRange().getStartOffset(); if ((strict || !varEndOffsetsSet.contains(startOffset)) && startOffset != patternEndOffset) { errorOffsets.add(startOffset); } if (startOffset == offset) { containsErrorTail[0] = true; } } }); for (int i = 0; i < errorOffsets.size(); i++) { final int errorOffset = errorOffsets.get(i); if (errorOffset <= offset) { return true; } } return containsErrorTail[0] ? null : false; } private interface PrefixProvider { String getPrefix(int varIndex); } private static class ConstantPrefixProvider implements PrefixProvider { private final String myPrefix; private ConstantPrefixProvider(String prefix) { myPrefix = prefix; } @Override public String getPrefix(int varIndex) { return myPrefix; } } private static class ArrayPrefixProvider implements PrefixProvider { private final String[] myPrefixes; private ArrayPrefixProvider(String[] prefixes) { myPrefixes = prefixes; } @Override public String getPrefix(int varIndex) { try { return myPrefixes[varIndex]; } catch (ArrayIndexOutOfBoundsException e) { return null; } } } private static List<PsiElement> doCompile(Project project, MatchOptions options, CompiledPattern result, PrefixProvider prefixProvider, CompileContext context) { result.clearHandlers(); context.init(result, options, project, options.getScope() instanceof GlobalSearchScope); final StringBuilder buf = new StringBuilder(); Template template = TemplateManager.getInstance(project).createTemplate("","",options.getSearchPattern()); int segmentsCount = template.getSegmentsCount(); String text = template.getTemplateText(); buf.setLength(0); int prevOffset = 0; for(int i=0;i<segmentsCount;++i) { final int offset = template.getSegmentOffset(i); final String name = template.getSegmentName(i); final String prefix = prefixProvider.getPrefix(i); if (prefix == null) { throw new MalformedPatternException(); } buf.append(text.substring(prevOffset,offset)); buf.append(prefix); buf.append(name); MatchVariableConstraint constraint = options.getVariableConstraint(name); if (constraint==null) { // we do not edited the constraints constraint = new MatchVariableConstraint(); constraint.setName( name ); options.addVariableConstraint(constraint); } SubstitutionHandler handler = result.createSubstitutionHandler( name, prefix + name, constraint.isPartOfSearchResults(), constraint.getMinCount(), constraint.getMaxCount(), constraint.isGreedy() ); if(constraint.isWithinHierarchy()) { handler.setSubtype(true); } if(constraint.isStrictlyWithinHierarchy()) { handler.setStrictSubtype(true); } MatchPredicate predicate; if (constraint.getRegExp()!=null && constraint.getRegExp().length() > 0) { predicate = new RegExpPredicate( constraint.getRegExp(), options.isCaseSensitiveMatch(), name, constraint.isWholeWordsOnly(), constraint.isPartOfSearchResults() ); if (constraint.isInvertRegExp()) { predicate = new NotPredicate(predicate); } addPredicate(handler,predicate); } if (constraint.isReadAccess()) { predicate = new ReadPredicate(); if (constraint.isInvertReadAccess()) { predicate = new NotPredicate(predicate); } addPredicate(handler,predicate); } if (constraint.isWriteAccess()) { predicate = new WritePredicate(); if (constraint.isInvertWriteAccess()) { predicate = new NotPredicate(predicate); } addPredicate(handler,predicate); } if (constraint.isReference()) { predicate = new ReferencePredicate( constraint.getNameOfReferenceVar() ); if (constraint.isInvertReference()) { predicate = new NotPredicate(predicate); } addPredicate(handler,predicate); } if (constraint.getNameOfExprType()!=null && constraint.getNameOfExprType().length() > 0 ) { predicate = new ExprTypePredicate( constraint.getNameOfExprType(), name, constraint.isExprTypeWithinHierarchy(), options.isCaseSensitiveMatch(), constraint.isPartOfSearchResults() ); if (constraint.isInvertExprType()) { predicate = new NotPredicate(predicate); } addPredicate(handler,predicate); } if (constraint.getNameOfFormalArgType()!=null && constraint.getNameOfFormalArgType().length() > 0) { predicate = new FormalArgTypePredicate( constraint.getNameOfFormalArgType(), name, constraint.isFormalArgTypeWithinHierarchy(), options.isCaseSensitiveMatch(), constraint.isPartOfSearchResults() ); if (constraint.isInvertFormalType()) { predicate = new NotPredicate(predicate); } addPredicate(handler,predicate); } addScriptConstraint(name, constraint, handler); if (constraint.getContainsConstraint() != null && constraint.getContainsConstraint().length() > 0) { predicate = new ContainsPredicate(name, constraint.getContainsConstraint()); if (constraint.isInvertContainsConstraint()) { predicate = new NotPredicate(predicate); } addPredicate(handler,predicate); } if (constraint.getWithinConstraint() != null && constraint.getWithinConstraint().length() > 0) { assert false; } prevOffset = offset; } MatchVariableConstraint constraint = options.getVariableConstraint(Configuration.CONTEXT_VAR_NAME); if (constraint != null) { SubstitutionHandler handler = result.createSubstitutionHandler( Configuration.CONTEXT_VAR_NAME, Configuration.CONTEXT_VAR_NAME, constraint.isPartOfSearchResults(), constraint.getMinCount(), constraint.getMaxCount(), constraint.isGreedy() ); if (constraint.getWithinConstraint() != null && constraint.getWithinConstraint().length() > 0) { MatchPredicate predicate = new WithinPredicate(Configuration.CONTEXT_VAR_NAME, constraint.getWithinConstraint(), project); if (constraint.isInvertWithinConstraint()) { predicate = new NotPredicate(predicate); } addPredicate(handler,predicate); } addScriptConstraint(Configuration.CONTEXT_VAR_NAME, constraint, handler); } buf.append(text.substring(prevOffset,text.length())); PsiElement[] matchStatements; try { final String pattern = buf.toString(); matchStatements = MatcherImplUtil.createTreeFromText(pattern, PatternTreeContext.Block, options.getFileType(), options.getDialect(), options.getPatternContext(), project, false); if (matchStatements.length==0) throw new MalformedPatternException(pattern); } catch (IncorrectOperationException e) { throw new MalformedPatternException(e.getMessage()); } NodeFilter filter = LexicalNodesFilter.getInstance(); GlobalCompilingVisitor compilingVisitor = new GlobalCompilingVisitor(); compilingVisitor.compile(matchStatements,context); ArrayList<PsiElement> elements = new ArrayList<PsiElement>(); for (PsiElement matchStatement : matchStatements) { if (!filter.accepts(matchStatement)) { elements.add(matchStatement); } } new DeleteNodesAction(compilingVisitor.getLexicalNodes()).run(); return elements; } private static void addScriptConstraint(String name, MatchVariableConstraint constraint, SubstitutionHandler handler) { MatchPredicate predicate; if (constraint.getScriptCodeConstraint()!= null && constraint.getScriptCodeConstraint().length() > 2) { final String script = StringUtil.stripQuotesAroundValue(constraint.getScriptCodeConstraint()); final String s = ScriptSupport.checkValidScript(script); if (s != null) throw new MalformedPatternException("Script constraint for " + constraint.getName() + " has problem "+s); predicate = new ScriptPredicate(name, script); addPredicate(handler,predicate); } } static void addPredicate(SubstitutionHandler handler, MatchPredicate predicate) { if (handler.getPredicate()==null) { handler.setPredicate(predicate); } else { handler.setPredicate( new BinaryPredicate( handler.getPredicate(), predicate, false ) ); } } }
plugins/structuralsearch/source/com/intellij/structuralsearch/impl/matcher/compiler/PatternCompiler.java
package com.intellij.structuralsearch.impl.matcher.compiler; import com.intellij.codeInsight.template.Template; import com.intellij.codeInsight.template.TemplateManager; import com.intellij.dupLocator.iterators.ArrayBackedNodeIterator; import com.intellij.dupLocator.util.NodeFilter; import com.intellij.lang.Language; import com.intellij.openapi.application.ApplicationManager; import com.intellij.openapi.fileTypes.FileType; import com.intellij.openapi.fileTypes.LanguageFileType; import com.intellij.openapi.project.Project; import com.intellij.openapi.util.text.StringUtil; import com.intellij.psi.PsiElement; import com.intellij.psi.PsiErrorElement; import com.intellij.psi.PsiFile; import com.intellij.psi.PsiRecursiveElementWalkingVisitor; import com.intellij.psi.impl.source.PsiFileImpl; import com.intellij.psi.impl.source.tree.LeafElement; import com.intellij.psi.search.GlobalSearchScope; import com.intellij.psi.search.LocalSearchScope; import com.intellij.psi.util.PsiUtilCore; import com.intellij.structuralsearch.*; import com.intellij.structuralsearch.impl.matcher.CompiledPattern; import com.intellij.structuralsearch.impl.matcher.MatcherImplUtil; import com.intellij.structuralsearch.impl.matcher.PatternTreeContext; import com.intellij.structuralsearch.impl.matcher.filters.LexicalNodesFilter; import com.intellij.structuralsearch.impl.matcher.handlers.MatchPredicate; import com.intellij.structuralsearch.impl.matcher.handlers.SubstitutionHandler; import com.intellij.structuralsearch.impl.matcher.predicates.*; import com.intellij.structuralsearch.plugin.ui.Configuration; import com.intellij.util.IncorrectOperationException; import gnu.trove.TIntArrayList; import gnu.trove.TIntHashSet; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import java.util.*; import java.util.regex.Matcher; import java.util.regex.Pattern; /** * Compiles the handlers for usability */ public class PatternCompiler { private static CompileContext lastTestingContext; public static void transformOldPattern(MatchOptions options) { StringToConstraintsTransformer.transformOldPattern(options); } public static CompiledPattern compilePattern(final Project project, final MatchOptions options) throws MalformedPatternException, UnsupportedOperationException { FileType fileType = options.getFileType(); assert fileType instanceof LanguageFileType; Language language = ((LanguageFileType)fileType).getLanguage(); StructuralSearchProfile profile = StructuralSearchUtil.getProfileByLanguage(language); assert profile != null; CompiledPattern result = profile.createCompiledPattern(); final String[] prefixes = result.getTypedVarPrefixes(); assert prefixes.length > 0; final CompileContext context = new CompileContext(); if (ApplicationManager.getApplication().isUnitTestMode()) lastTestingContext = context; /*CompiledPattern result = options.getFileType() == StdFileTypes.JAVA ? new JavaCompiledPattern() : new XmlCompiledPattern();*/ try { context.init(result, options, project, options.getScope() instanceof GlobalSearchScope); List<PsiElement> elements = compileByAllPrefixes(project, options, result, context, prefixes); context.getPattern().setNodes(elements); if (context.getSearchHelper().doOptimizing() && context.getSearchHelper().isScannedSomething()) { final Set<PsiFile> set = context.getSearchHelper().getFilesSetToScan(); final List<PsiFile> filesToScan = new ArrayList<PsiFile>(set.size()); final GlobalSearchScope scope = (GlobalSearchScope)options.getScope(); for (final PsiFile file : set) { if (!scope.contains(file.getVirtualFile())) { continue; } if (file instanceof PsiFileImpl) { ((PsiFileImpl)file).clearCaches(); } filesToScan.add(file); } if (filesToScan.size() == 0) { throw new MalformedPatternException(SSRBundle.message("ssr.will.not.find.anything")); } result.setScope( new LocalSearchScope(PsiUtilCore.toPsiElementArray(filesToScan)) ); } } finally { context.clear(); } return result; } public static String getLastFindPlan() { return ((TestModeOptimizingSearchHelper)lastTestingContext.getSearchHelper()).getSearchPlan(); } @NotNull private static List<PsiElement> compileByAllPrefixes(Project project, MatchOptions options, CompiledPattern pattern, CompileContext context, String[] applicablePrefixes) { if (applicablePrefixes.length == 0) { return Collections.emptyList(); } List<PsiElement> elements = doCompile(project, options, pattern, new ConstantPrefixProvider(applicablePrefixes[0]), context); if (elements.isEmpty()) { return elements; } final PsiFile file = elements.get(0).getContainingFile(); if (file == null) { return elements; } final PsiElement last = elements.get(elements.size() - 1); final Pattern[] patterns = new Pattern[applicablePrefixes.length]; for (int i = 0; i < applicablePrefixes.length; i++) { String s = StructuralSearchUtil.shieldSpecialChars(applicablePrefixes[i]); patterns[i] = Pattern.compile(s + "\\w+\\b"); } final int[] varEndOffsets = findAllTypedVarOffsets(file, patterns); final int patternEndOffset = last.getTextRange().getEndOffset(); if (elements.size() == 0 || checkErrorElements(file, patternEndOffset, patternEndOffset, varEndOffsets, true) != Boolean.TRUE) { return elements; } final int varCount = varEndOffsets.length; final String[] prefixSequence = new String[varCount]; for (int i = 0; i < varCount; i++) { prefixSequence[i] = applicablePrefixes[0]; } final List<PsiElement> finalElements = compileByPrefixes(project, options, pattern, context, applicablePrefixes, patterns, prefixSequence, 0); return finalElements != null ? finalElements : doCompile(project, options, pattern, new ConstantPrefixProvider(applicablePrefixes[0]), context); } @Nullable private static List<PsiElement> compileByPrefixes(Project project, MatchOptions options, CompiledPattern pattern, CompileContext context, String[] applicablePrefixes, Pattern[] substitutionPatterns, String[] prefixSequence, int index) { if (index >= prefixSequence.length) { final List<PsiElement> elements = doCompile(project, options, pattern, new ArrayPrefixProvider(prefixSequence), context); if (elements.isEmpty()) { return elements; } final PsiElement parent = elements.get(0).getParent(); final PsiElement last = elements.get(elements.size() - 1); final int[] varEndOffsets = findAllTypedVarOffsets(parent.getContainingFile(), substitutionPatterns); final int patternEndOffset = last.getTextRange().getEndOffset(); return checkErrorElements(parent, patternEndOffset, patternEndOffset, varEndOffsets, false) != Boolean.TRUE ? elements : null; } String[] alternativeVariant = null; for (String applicablePrefix : applicablePrefixes) { prefixSequence[index] = applicablePrefix; List<PsiElement> elements = doCompile(project, options, pattern, new ArrayPrefixProvider(prefixSequence), context); if (elements.isEmpty()) { return elements; } final PsiFile file = elements.get(0).getContainingFile(); if (file == null) { return elements; } final int[] varEndOffsets = findAllTypedVarOffsets(file, substitutionPatterns); final int offset = varEndOffsets[index]; final int patternEndOffset = elements.get(elements.size() - 1).getTextRange().getEndOffset(); final Boolean result = checkErrorElements(file, offset, patternEndOffset, varEndOffsets, false); if (result == Boolean.TRUE) { continue; } if (result == Boolean.FALSE || (result == null && alternativeVariant == null)) { final List<PsiElement> finalElements = compileByPrefixes(project, options, pattern, context, applicablePrefixes, substitutionPatterns, prefixSequence, index + 1); if (finalElements != null) { if (result == Boolean.FALSE) { return finalElements; } alternativeVariant = new String[prefixSequence.length]; System.arraycopy(prefixSequence, 0, alternativeVariant, 0, prefixSequence.length); } } } return alternativeVariant != null ? compileByPrefixes(project, options, pattern, context, applicablePrefixes, substitutionPatterns, alternativeVariant, index + 1) : null; } @NotNull private static int[] findAllTypedVarOffsets(final PsiFile file, final Pattern[] substitutionPatterns) { final TIntHashSet result = new TIntHashSet(); file.accept(new PsiRecursiveElementWalkingVisitor() { @Override public void visitElement(PsiElement element) { super.visitElement(element); if (element instanceof LeafElement) { final String text = element.getText(); for (Pattern pattern : substitutionPatterns) { final Matcher matcher = pattern.matcher(text); while (matcher.find()) { result.add(element.getTextRange().getStartOffset() + matcher.end()); } } } } }); final int[] resultArray = result.toArray(); Arrays.sort(resultArray); return resultArray; } /** * False: there are no error elements before offset, except patternEndOffset * Null: there are only error elements located exactly after template variables or at the end of the pattern * True: otherwise */ @Nullable private static Boolean checkErrorElements(PsiElement element, final int offset, final int patternEndOffset, final int[] varEndOffsets, final boolean strict) { final TIntArrayList errorOffsets = new TIntArrayList(); final boolean[] containsErrorTail = {false}; final TIntHashSet varEndOffsetsSet = new TIntHashSet(varEndOffsets); element.accept(new PsiRecursiveElementWalkingVisitor() { @Override public void visitElement(PsiElement element) { super.visitElement(element); if (!(element instanceof PsiErrorElement)) { return; } final int startOffset = element.getTextRange().getStartOffset(); if ((strict || !varEndOffsetsSet.contains(startOffset)) && startOffset != patternEndOffset) { errorOffsets.add(startOffset); } if (startOffset == offset) { containsErrorTail[0] = true; } } }); for (int i = 0; i < errorOffsets.size(); i++) { final int errorOffset = errorOffsets.get(i); if (errorOffset <= offset) { return true; } } return containsErrorTail[0] ? null : false; } private interface PrefixProvider { String getPrefix(int varIndex); } private static class ConstantPrefixProvider implements PrefixProvider { private final String myPrefix; private ConstantPrefixProvider(String prefix) { myPrefix = prefix; } @Override public String getPrefix(int varIndex) { return myPrefix; } } private static class ArrayPrefixProvider implements PrefixProvider { private final String[] myPrefixes; private ArrayPrefixProvider(String[] prefixes) { myPrefixes = prefixes; } @Override public String getPrefix(int varIndex) { return myPrefixes[varIndex]; } } private static List<PsiElement> doCompile(Project project, MatchOptions options, CompiledPattern result, PrefixProvider prefixProvider, CompileContext context) { result.clearHandlers(); context.init(result, options, project, options.getScope() instanceof GlobalSearchScope); final StringBuilder buf = new StringBuilder(); Template template = TemplateManager.getInstance(project).createTemplate("","",options.getSearchPattern()); int segmentsCount = template.getSegmentsCount(); String text = template.getTemplateText(); buf.setLength(0); int prevOffset = 0; for(int i=0;i<segmentsCount;++i) { final int offset = template.getSegmentOffset(i); final String name = template.getSegmentName(i); final String prefix = prefixProvider.getPrefix(i); buf.append(text.substring(prevOffset,offset)); buf.append(prefix); buf.append(name); MatchVariableConstraint constraint = options.getVariableConstraint(name); if (constraint==null) { // we do not edited the constraints constraint = new MatchVariableConstraint(); constraint.setName( name ); options.addVariableConstraint(constraint); } SubstitutionHandler handler = result.createSubstitutionHandler( name, prefix + name, constraint.isPartOfSearchResults(), constraint.getMinCount(), constraint.getMaxCount(), constraint.isGreedy() ); if(constraint.isWithinHierarchy()) { handler.setSubtype(true); } if(constraint.isStrictlyWithinHierarchy()) { handler.setStrictSubtype(true); } MatchPredicate predicate; if (constraint.getRegExp()!=null && constraint.getRegExp().length() > 0) { predicate = new RegExpPredicate( constraint.getRegExp(), options.isCaseSensitiveMatch(), name, constraint.isWholeWordsOnly(), constraint.isPartOfSearchResults() ); if (constraint.isInvertRegExp()) { predicate = new NotPredicate(predicate); } addPredicate(handler,predicate); } if (constraint.isReadAccess()) { predicate = new ReadPredicate(); if (constraint.isInvertReadAccess()) { predicate = new NotPredicate(predicate); } addPredicate(handler,predicate); } if (constraint.isWriteAccess()) { predicate = new WritePredicate(); if (constraint.isInvertWriteAccess()) { predicate = new NotPredicate(predicate); } addPredicate(handler,predicate); } if (constraint.isReference()) { predicate = new ReferencePredicate( constraint.getNameOfReferenceVar() ); if (constraint.isInvertReference()) { predicate = new NotPredicate(predicate); } addPredicate(handler,predicate); } if (constraint.getNameOfExprType()!=null && constraint.getNameOfExprType().length() > 0 ) { predicate = new ExprTypePredicate( constraint.getNameOfExprType(), name, constraint.isExprTypeWithinHierarchy(), options.isCaseSensitiveMatch(), constraint.isPartOfSearchResults() ); if (constraint.isInvertExprType()) { predicate = new NotPredicate(predicate); } addPredicate(handler,predicate); } if (constraint.getNameOfFormalArgType()!=null && constraint.getNameOfFormalArgType().length() > 0) { predicate = new FormalArgTypePredicate( constraint.getNameOfFormalArgType(), name, constraint.isFormalArgTypeWithinHierarchy(), options.isCaseSensitiveMatch(), constraint.isPartOfSearchResults() ); if (constraint.isInvertFormalType()) { predicate = new NotPredicate(predicate); } addPredicate(handler,predicate); } addScriptConstraint(name, constraint, handler); if (constraint.getContainsConstraint() != null && constraint.getContainsConstraint().length() > 0) { predicate = new ContainsPredicate(name, constraint.getContainsConstraint()); if (constraint.isInvertContainsConstraint()) { predicate = new NotPredicate(predicate); } addPredicate(handler,predicate); } if (constraint.getWithinConstraint() != null && constraint.getWithinConstraint().length() > 0) { assert false; } prevOffset = offset; } MatchVariableConstraint constraint = options.getVariableConstraint(Configuration.CONTEXT_VAR_NAME); if (constraint != null) { SubstitutionHandler handler = result.createSubstitutionHandler( Configuration.CONTEXT_VAR_NAME, Configuration.CONTEXT_VAR_NAME, constraint.isPartOfSearchResults(), constraint.getMinCount(), constraint.getMaxCount(), constraint.isGreedy() ); if (constraint.getWithinConstraint() != null && constraint.getWithinConstraint().length() > 0) { MatchPredicate predicate = new WithinPredicate(Configuration.CONTEXT_VAR_NAME, constraint.getWithinConstraint(), project); if (constraint.isInvertWithinConstraint()) { predicate = new NotPredicate(predicate); } addPredicate(handler,predicate); } addScriptConstraint(Configuration.CONTEXT_VAR_NAME, constraint, handler); } buf.append(text.substring(prevOffset,text.length())); PsiElement[] matchStatements; try { final String pattern = buf.toString(); matchStatements = MatcherImplUtil.createTreeFromText(pattern, PatternTreeContext.Block, options.getFileType(), options.getDialect(), options.getPatternContext(), project, false); if (matchStatements.length==0) throw new MalformedPatternException(pattern); } catch (IncorrectOperationException e) { throw new MalformedPatternException(e.getMessage()); } NodeFilter filter = LexicalNodesFilter.getInstance(); GlobalCompilingVisitor compilingVisitor = new GlobalCompilingVisitor(); compilingVisitor.compile(matchStatements,context); ArrayList<PsiElement> elements = new ArrayList<PsiElement>(); for (PsiElement matchStatement : matchStatements) { if (!filter.accepts(matchStatement)) { elements.add(matchStatement); } } new DeleteNodesAction(compilingVisitor.getLexicalNodes()).run(); return elements; } private static void addScriptConstraint(String name, MatchVariableConstraint constraint, SubstitutionHandler handler) { MatchPredicate predicate; if (constraint.getScriptCodeConstraint()!= null && constraint.getScriptCodeConstraint().length() > 2) { final String script = StringUtil.stripQuotesAroundValue(constraint.getScriptCodeConstraint()); final String s = ScriptSupport.checkValidScript(script); if (s != null) throw new MalformedPatternException("Script constraint for " + constraint.getName() + " has problem "+s); predicate = new ScriptPredicate(name, script); addPredicate(handler,predicate); } } static void addPredicate(SubstitutionHandler handler, MatchPredicate predicate) { if (handler.getPredicate()==null) { handler.setPredicate(predicate); } else { handler.setPredicate( new BinaryPredicate( handler.getPredicate(), predicate, false ) ); } } }
EA-57372 & IDEA-126616 (Structural Search: throwable at com.intellij.structuralsearch.plugin.ui.SearchDialog$2.run)
plugins/structuralsearch/source/com/intellij/structuralsearch/impl/matcher/compiler/PatternCompiler.java
EA-57372 & IDEA-126616 (Structural Search: throwable at com.intellij.structuralsearch.plugin.ui.SearchDialog$2.run)
<ide><path>lugins/structuralsearch/source/com/intellij/structuralsearch/impl/matcher/compiler/PatternCompiler.java <ide> <ide> @Override <ide> public String getPrefix(int varIndex) { <del> return myPrefixes[varIndex]; <add> try { <add> return myPrefixes[varIndex]; <add> } catch (ArrayIndexOutOfBoundsException e) { <add> return null; <add> } <ide> } <ide> } <ide> <ide> final String name = template.getSegmentName(i); <ide> <ide> final String prefix = prefixProvider.getPrefix(i); <add> if (prefix == null) { <add> throw new MalformedPatternException(); <add> } <ide> <ide> buf.append(text.substring(prevOffset,offset)); <ide> buf.append(prefix);
Java
mit
35b8ea2171fa7687c32f272dc143f5691bb558da
0
fiveham/Sudoku_Solver
package sudoku.technique; import common.Pair; import common.Sets; import common.graph.Graph; import common.graph.Wrap; import common.graph.BasicGraph; import common.graph.WrapVertex; import java.util.ArrayList; import java.util.Arrays; import java.util.Collection; import java.util.HashSet; import java.util.Iterator; import java.util.List; import java.util.NoSuchElementException; import java.util.Optional; import java.util.Set; import java.util.function.Consumer; import java.util.function.Function; import java.util.function.Predicate; import java.util.function.Supplier; import java.util.stream.Collectors; import sudoku.Claim; import sudoku.Fact; import sudoku.Sudoku; import sudoku.time.TechniqueEvent; /** * <p>The color-chain technique exploits the fact that a Rule with * only two connected Claims is analogous to a {@code xor} operation. * A collection of interconnected two-Claim Rules, regardless of * the size and shape of such a network, has only two possible * solution-states.</p> * * @author fiveham * */ public class ColorChain extends AbstractTechnique { /** * <p>Constructs a ColorChain that works to solve the * specified {@code target}.</p> * @param target the Puzzle that this Technique works * to solve. */ public ColorChain(Sudoku puzzle) { super(puzzle); } /** * <p>Isolates those Rules in the target that have two Claims, makes * a Graph of their Claims, where two Claims share an edge if they * share a Rule as an element, and returns a collection of that Graph's * connected components, each of which is a xor-chain with two possible * solution-states.</p> * * @return a collection of the xor-chains that exist in the target * at the time when this method is called */ private static Collection<Graph<ColorClaim>> generateChains(Sudoku target, ColorSource colorSource){ List<Fact> xorRules = target.factStream() .filter(Fact::isXor) .collect(Collectors.toList()); return new BasicGraph<ColorClaim>(Wrap.wrap(xorRules,ColorClaim::new)) .addGrowthListenerFactory(colorSource) .connectedComponents(); } private final ColorSource colorSource = new ColorSource(); /** * <p>A generator and manager of ints to be used as colors for Claims * in xor-chains.</p> * * <p>Use {@code get()} to get the current color with the current sign, * use {@code nextColor()} when beginning to color a new xor-chain, and * use {@code invertColor()} to change the sign of the colors returned * by subsequent calls to {@code get()}.</p> * @author fiveham * */ private static class ColorSource implements Supplier<Consumer<Set<ColorClaim>>>{ public static final int INIT_COLOR = 1; private int color; ColorSource(){ this.color = INIT_COLOR; } @Override public Consumer<Set<ColorClaim>> get() { return new Colorizer(color++); } class Colorizer implements Consumer<Set<ColorClaim>>{ private final int col; private boolean positive; Colorizer(int col){ this.col = col; this.positive = true; } @Override public void accept(Set<ColorClaim> cuttingEdge) { cuttingEdge.stream().forEach((e)->e.setColor(getColor())); invertColor(); } /** * <p>Changes this Colorizer's color sign so that * subsequent calls to {@code getColor()} return a color * with the sign opposite of the sign returned by * previous calls to {@code getColor()}.</p> */ private void invertColor(){ positive = !positive; } /** * <p>Returns the current color with the current sign.</p> * @return the current color with the current sign */ private int getColor(){ return positive ? col : -col; } } } /* * TODO incorporate use of subsumedFacts via its method into xyChain's analysis * and incorporate xyChain and subsumedFacts into implicationIntersection. * * Currently, SubsumedFacts analysis (in the form of checks for fully localized * Facts, not including partially localized facts) is implicitly incorporated into * xyChain analysis. I'd like to incorporate it in an explicit, formal manner, * in order to add the partial-overlap functionality and also to avoid code duplication. * * Additionally, I'd like to incorporate subsumedFacts and xyChain into * implicationIntersection in order to begin unifying ColorChain and Sledgehammer. */ private static final List<Function<ColorChain,TechniqueEvent>> SUBTECHNIQUES = Arrays.asList( ColorChain::subsumedFacts, ColorChain::xyChain, ColorChain::implicationIntersection); @Override public TechniqueEvent process(){ try{ return SUBTECHNIQUES.stream() .map((st) -> st.apply(this)) .filter((result) -> result != null) .findFirst().get(); } catch(NoSuchElementException e){ return null; } } private static final int MIN_IMPLICATION_INTERSECTION_SIZE = 3; /** * <p>Explores the consequences of each individual Claim of a * given Rule (for each Rule of each size greater than 2) being * true and falsifies those Claims that would have to be false * regardless of which Claim of the Rule currently in focus is * true.</p> * @return */ private TechniqueEvent implicationIntersection(){ for(int size = MIN_IMPLICATION_INTERSECTION_SIZE; size <= target.sideLength(); ++size){ Collection<Fact> rules; { final int size2 = size; rules = target.factStream() .filter((f) -> f.size() == size2) .collect(Collectors.toList()); } for(Fact rule : rules){ Set<Claim> externalFalseIntersection = getFalseIntersection(rule, size); if(!externalFalseIntersection.isEmpty()){ return new SolveEventImplicationIntersection( externalFalseIntersection, rule) .falsifyClaims(); } } } return null; } public static class SolveEventImplicationIntersection extends TechniqueEvent{ private final Fact rule; SolveEventImplicationIntersection(Set<Claim> falsifiedClaims, Fact rule){ super(falsifiedClaims); this.rule = rule; } @Override protected String toStringStart() { return "An intersection of the Claims that would be falsified by the verification of any of the Claims of "+rule; } } private static Set<Claim> getFalseIntersection(Fact rule, int size){ Iterator<Claim> claimAsserter = rule.iterator(); if(!claimAsserter.hasNext()){ StringBuilder sb = new StringBuilder("This Iterator doesn't have a first element. "); sb.append("Size: ").append(rule.size()); sb.append("Intended size: ").append(size); throw new IllegalStateException(sb.toString()); } Set<Claim> falseIntersection = getFalsifiedClaims(claimAsserter.next()); while(claimAsserter.hasNext() && !rule.containsAll(falseIntersection)){ falseIntersection.retainAll( getFalsifiedClaims( claimAsserter.next())); } falseIntersection.removeAll(rule); return falseIntersection; } private TechniqueEvent xyChain(){ for(Graph<ColorClaim> chain : generateChains(target, colorSource)){ Set<Claim> falseIntersection = ColorClaim.COLOR_SIGNS.stream() .map((test) -> chain.nodeStream() .filter(test) .map(ColorClaim::wrapped) .collect(Collectors.toSet())) .map(ColorChain::getFalsifiedClaims) .collect(Sets.massIntersectionCollector()); if(!falseIntersection.isEmpty()){ List<Fact> xorChain = chain.nodeStream() .map(ColorClaim::wrapped) .collect(Sets.massUnionCollector()) .stream() .filter(Fact::isXor) .collect(Collectors.toList()); return new SolveEventColorChain(falseIntersection, xorChain) .falsifyClaims(); } } return null; } private static Set<Claim> getFalsifiedClaims(Claim... initialTrue){ return getFalsifiedClaims( Arrays.stream(initialTrue) .collect(Collectors.toSet())); } private static Set<Claim> getFalsifiedClaims(Set<Claim> initialTrue){ Set<Claim> trueClaims = new HashSet<>(); Set<Claim> falseClaims = new HashSet<>(); Set<Claim> newTrue = new HashSet<>(initialTrue); while(!newTrue.isEmpty()){ Set<Claim> newFalse = newFalse(newTrue, falseClaims); trueClaims.addAll(newTrue); falseClaims.addAll(newFalse); newTrue = newTrue(falseClaims, trueClaims, newFalse); } return falseClaims; } /** * <p.Determines which Claims, in addition to those already known to * be conditionally false, must be conditionally false.</p> * <p>A Claim is conditionally false if it would have to be false * given that the Claim currently {@code assertedTrue} in * {@code getFalsifiedClaims} is asserted to be true.</p> * @param newTrue * @param f * @return */ private static Set<Claim> newFalse(Set<Claim> newTrue, Set<Claim> f){ Set<Claim> result = new HashSet<>(); for(Claim newlyVerified : newTrue){ result.addAll(newlyVerified.visible()); } result.removeAll(f); return result; } /** * <p>Returns a set of the Claims that must be true because all other Claims of some * Rule have already been determined to be false.</p> * @param newFalse * @return */ private static Set<Claim> newTrue(Set<Claim> falseClaims, Set<Claim> trueClaims, Set<Claim> newFalse){ Set<Fact> visibleRules = visibleRules(newFalse); Set<Claim> result = new HashSet<>(visibleRules.size()); for(Fact rvisibleRule : visibleRules){ Set<Claim> copyOfVisibleRule = new HashSet<>(rvisibleRule); copyOfVisibleRule.removeAll(falseClaims); if(copyOfVisibleRule.size() == Fact.SIZE_WHEN_SOLVED){ result.add(rvisibleRule.iterator().next()); } } result.removeAll(trueClaims); return result; } /** * <p>Returns a set of the Facts visible (adjacent) to at least one of * the Claims in {@code newFalse}.</p> * @param newFalse * @return */ private static Set<Fact> visibleRules(Set<Claim> newFalse){ return Sets.massUnion(newFalse); } public class SolveEventColorChain extends TechniqueEvent{ private final Collection<Fact> xorEntity; public SolveEventColorChain(Set<Claim> falsified, Collection<Fact> xorEntity) { super(falsified); this.xorEntity = xorEntity; } @Override protected String toStringStart() { return "Either-solution propagation from the "+xorEntity.size()+"-Rule xor-chain "+xorEntity.toString(); } } /** * <p>Wraps a Claim and decorates it with an int color.</p> * @author fiveham * */ private static class ColorClaim implements WrapVertex<Claim,ColorClaim>{ public static final List<Predicate<ColorClaim>> COLOR_SIGNS; static{ COLOR_SIGNS = new ArrayList<>(2); //MAGIC COLOR_SIGNS.add((colorClaim) -> colorClaim.color > 0); COLOR_SIGNS.add((colorClaim) -> colorClaim.color < 0); } private int color = 0; private final Claim claim; private final List<ColorClaim> neighbors; ColorClaim(Claim claim){ this.claim = claim; this.neighbors = new ArrayList<>(); } @Override public Claim wrapped(){ return claim; } @Override public List<ColorClaim> neighbors(){ return neighbors; } /** * <p>Sets the color to {@code color{@code .</p> * @param color the new color */ void setColor(int color){ if(this.color == 0){ this.color = color; } else{ throw new IllegalStateException("Cannot change color to "+color+" because color has already been set to "+this.color); } } @Override public boolean equals(Object o){ if(o instanceof ColorClaim){ ColorClaim cc = (ColorClaim) o; return cc.color == this.color && cc.claim == this.claim; } return false; } @Override public int hashCode(){ return claim.hashCode(); } @Override public String toString(){ return "ColorClaim pairing " + color + " with " + claim; } } @Override public ColorChain apply(Sudoku sudoku){ return new ColorChain(sudoku); } /** * <p>Finds a unary Fact in {@code target} and sets that Fact's * one Claim neighbor true.</p> * @return an Initialization describing the verification of * an Init's sole Claim neighbor and any and all resulting * automatic resolution events, or null if no Init is found */ private TechniqueEvent subsumedFacts(){ Optional<Pair<Fact,Set<Fact>>> i = target.factStream() .map((fact) -> new Pair<Fact,Set<Fact>>( fact, fact.visible().stream() .filter((vis) -> vis.containsAll(fact)) .collect(Collectors.toSet()))) .filter((pair) -> !pair.getB().isEmpty()) .findFirst(); if(i.isPresent()){ Pair<Fact,Set<Fact>> p = i.get(); return new SubsumedFact(p.getA(), p.getB()).falsifyClaims(); } return null; } /** * <p>Describes the verification of a Claim known to be true * because one or more of its Fact neighbors contains only that * Claim as an element..</p> * @author fiveham * */ public static class SubsumedFact extends TechniqueEvent{ private final Fact src; private final Set<Fact> supersets; private SubsumedFact(Fact solved, Set<Fact> supersets){ super(solved.iterator().next().visible()); this.src = solved; this.supersets = supersets; } @Override public boolean equals(Object o){ if(o instanceof SubsumedFact){ SubsumedFact se = (SubsumedFact) o; return super.equals(se) && (src == null ? se.src == null : src.equals(se.src)); } return false; } @Override protected String toStringStart(){ return src+"is subsumed by "+supersets.stream() .map(Object::toString) .collect(Collectors.joining(", ")); } } }
src/sudoku/technique/ColorChain.java
package sudoku.technique; import common.Pair; import common.Sets; import common.graph.Graph; import common.graph.Wrap; import common.graph.BasicGraph; import common.graph.WrapVertex; import java.util.ArrayList; import java.util.Arrays; import java.util.Collection; import java.util.HashSet; import java.util.Iterator; import java.util.List; import java.util.NoSuchElementException; import java.util.Optional; import java.util.Set; import java.util.function.Consumer; import java.util.function.Function; import java.util.function.Predicate; import java.util.function.Supplier; import java.util.stream.Collectors; import sudoku.Claim; import sudoku.Fact; import sudoku.Sudoku; import sudoku.time.TechniqueEvent; /** * <p>The color-chain technique exploits the fact that a Rule with * only two connected Claims is analogous to a {@code xor} operation. * A collection of interconnected two-Claim Rules, regardless of * the size and shape of such a network, has only two possible * solution-states.</p> * * @author fiveham * */ public class ColorChain extends AbstractTechnique { /** * <p>Constructs a ColorChain that works to solve the * specified {@code target}.</p> * @param target the Puzzle that this Technique works * to solve. */ public ColorChain(Sudoku puzzle) { super(puzzle); } /** * <p>Isolates those Rules in the target that have two Claims, makes * a Graph of their Claims, where two Claims share an edge if they * share a Rule as an element, and returns a collection of that Graph's * connected components, each of which is a xor-chain with two possible * solution-states.</p> * * @return a collection of the xor-chains that exist in the target * at the time when this method is called */ private static Collection<Graph<ColorClaim>> generateChains(Sudoku target, ColorSource colorSource){ List<Fact> xorRules = target.factStream() .filter(Fact::isXor) .collect(Collectors.toList()); return new BasicGraph<ColorClaim>(Wrap.wrap(xorRules,ColorClaim::new)) .addGrowthListenerFactory(colorSource) .connectedComponents(); } private final ColorSource colorSource = new ColorSource(); /** * <p>A generator and manager of ints to be used as colors for Claims * in xor-chains.</p> * * <p>Use {@code get()} to get the current color with the current sign, * use {@code nextColor()} when beginning to color a new xor-chain, and * use {@code invertColor()} to change the sign of the colors returned * by subsequent calls to {@code get()}.</p> * @author fiveham * */ private static class ColorSource implements Supplier<Consumer<Set<ColorClaim>>>{ public static final int INIT_COLOR = 1; private int color; ColorSource(){ this.color = INIT_COLOR; } @Override public Consumer<Set<ColorClaim>> get() { return new Colorizer(color++); } class Colorizer implements Consumer<Set<ColorClaim>>{ private final int col; private boolean positive; Colorizer(int col){ this.col = col; this.positive = true; } @Override public void accept(Set<ColorClaim> cuttingEdge) { cuttingEdge.stream().forEach((e)->e.setColor(getColor())); invertColor(); } /** * <p>Changes this Colorizer's color sign so that * subsequent calls to {@code getColor()} return a color * with the sign opposite of the sign returned by * previous calls to {@code getColor()}.</p> */ private void invertColor(){ positive = !positive; } /** * <p>Returns the current color with the current sign.</p> * @return the current color with the current sign */ private int getColor(){ return positive ? col : -col; } } } private static final List<Function<ColorChain,TechniqueEvent>> SUBTECHNIQUES = Arrays.asList( ColorChain::subsumedFacts, ColorChain::xyChain, ColorChain::implicationIntersection); @Override public TechniqueEvent process(){ try{ return SUBTECHNIQUES.stream() .map((st) -> st.apply(this)) .filter((result) -> result != null) .findFirst().get(); } catch(NoSuchElementException e){ return null; } } private static final int MIN_IMPLICATION_INTERSECTION_SIZE = 3; /** * <p>Explores the consequences of each individual Claim of a * given Rule (for each Rule of each size greater than 2) being * true and falsifies those Claims that would have to be false * regardless of which Claim of the Rule currently in focus is * true.</p> * @return */ private TechniqueEvent implicationIntersection(){ for(int size = MIN_IMPLICATION_INTERSECTION_SIZE; size <= target.sideLength(); ++size){ Collection<Fact> rules; { final int size2 = size; rules = target.factStream() .filter((f) -> f.size() == size2) .collect(Collectors.toList()); } for(Fact rule : rules){ Set<Claim> externalFalseIntersection = getFalseIntersection(rule, size); if(!externalFalseIntersection.isEmpty()){ return new SolveEventImplicationIntersection( externalFalseIntersection, rule) .falsifyClaims(); } } } return null; } public static class SolveEventImplicationIntersection extends TechniqueEvent{ private final Fact rule; SolveEventImplicationIntersection(Set<Claim> falsifiedClaims, Fact rule){ super(falsifiedClaims); this.rule = rule; } @Override protected String toStringStart() { return "An intersection of the Claims that would be falsified by the verification of any of the Claims of "+rule; } } private static Set<Claim> getFalseIntersection(Fact rule, int size){ Iterator<Claim> claimAsserter = rule.iterator(); if(!claimAsserter.hasNext()){ StringBuilder sb = new StringBuilder("This Iterator doesn't have a first element. "); sb.append("Size: ").append(rule.size()); sb.append("Intended size: ").append(size); throw new IllegalStateException(sb.toString()); } Set<Claim> falseIntersection = getFalsifiedClaims(claimAsserter.next()); while(claimAsserter.hasNext() && !rule.containsAll(falseIntersection)){ falseIntersection.retainAll( getFalsifiedClaims( claimAsserter.next())); } falseIntersection.removeAll(rule); return falseIntersection; } private TechniqueEvent xyChain(){ for(Graph<ColorClaim> chain : generateChains(target, colorSource)){ Set<Claim> falseIntersection = ColorClaim.COLOR_SIGNS.stream() .map((test) -> chain.nodeStream() .filter(test) .map(ColorClaim::wrapped) .collect(Collectors.toSet())) .map(ColorChain::getFalsifiedClaims) .collect(Sets.massIntersectionCollector()); if(!falseIntersection.isEmpty()){ List<Fact> xorChain = chain.nodeStream() .map(ColorClaim::wrapped) .collect(Sets.massUnionCollector()) .stream() .filter(Fact::isXor) .collect(Collectors.toList()); return new SolveEventColorChain(falseIntersection, xorChain) .falsifyClaims(); } } return null; } private static Set<Claim> getFalsifiedClaims(Claim... initialTrue){ return getFalsifiedClaims( Arrays.stream(initialTrue) .collect(Collectors.toSet())); } private static Set<Claim> getFalsifiedClaims(Set<Claim> initialTrue){ Set<Claim> trueClaims = new HashSet<>(); Set<Claim> falseClaims = new HashSet<>(); Set<Claim> newTrue = new HashSet<>(initialTrue); while(!newTrue.isEmpty()){ Set<Claim> newFalse = newFalse(newTrue, falseClaims); trueClaims.addAll(newTrue); falseClaims.addAll(newFalse); newTrue = newTrue(falseClaims, trueClaims, newFalse); } return falseClaims; } /** * <p.Determines which Claims, in addition to those already known to * be conditionally false, must be conditionally false.</p> * <p>A Claim is conditionally false if it would have to be false * given that the Claim currently {@code assertedTrue} in * {@code getFalsifiedClaims} is asserted to be true.</p> * @param newTrue * @param f * @return */ private static Set<Claim> newFalse(Set<Claim> newTrue, Set<Claim> f){ Set<Claim> result = new HashSet<>(); for(Claim newlyVerified : newTrue){ result.addAll(newlyVerified.visible()); } result.removeAll(f); return result; } /** * <p>Returns a set of the Claims that must be true because all other Claims of some * Rule have already been determined to be false.</p> * @param newFalse * @return */ private static Set<Claim> newTrue(Set<Claim> falseClaims, Set<Claim> trueClaims, Set<Claim> newFalse){ Set<Fact> visibleRules = visibleRules(newFalse); Set<Claim> result = new HashSet<>(visibleRules.size()); for(Fact rvisibleRule : visibleRules){ Set<Claim> copyOfVisibleRule = new HashSet<>(rvisibleRule); copyOfVisibleRule.removeAll(falseClaims); if(copyOfVisibleRule.size() == Fact.SIZE_WHEN_SOLVED){ result.add(rvisibleRule.iterator().next()); } } result.removeAll(trueClaims); return result; } /** * <p>Returns a set of the Facts visible (adjacent) to at least one of * the Claims in {@code newFalse}.</p> * @param newFalse * @return */ private static Set<Fact> visibleRules(Set<Claim> newFalse){ return Sets.massUnion(newFalse); } public class SolveEventColorChain extends TechniqueEvent{ private final Collection<Fact> xorEntity; public SolveEventColorChain(Set<Claim> falsified, Collection<Fact> xorEntity) { super(falsified); this.xorEntity = xorEntity; } @Override protected String toStringStart() { return "Either-solution propagation from the "+xorEntity.size()+"-Rule xor-chain "+xorEntity.toString(); } } /** * <p>Wraps a Claim and decorates it with an int color.</p> * @author fiveham * */ private static class ColorClaim implements WrapVertex<Claim,ColorClaim>{ public static final List<Predicate<ColorClaim>> COLOR_SIGNS; static{ COLOR_SIGNS = new ArrayList<>(2); //MAGIC COLOR_SIGNS.add((colorClaim) -> colorClaim.color > 0); COLOR_SIGNS.add((colorClaim) -> colorClaim.color < 0); } private int color = 0; private final Claim claim; private final List<ColorClaim> neighbors; ColorClaim(Claim claim){ this.claim = claim; this.neighbors = new ArrayList<>(); } @Override public Claim wrapped(){ return claim; } @Override public List<ColorClaim> neighbors(){ return neighbors; } /** * <p>Sets the color to {@code color{@code .</p> * @param color the new color */ void setColor(int color){ if(this.color == 0){ this.color = color; } else{ throw new IllegalStateException("Cannot change color to "+color+" because color has already been set to "+this.color); } } @Override public boolean equals(Object o){ if(o instanceof ColorClaim){ ColorClaim cc = (ColorClaim) o; return cc.color == this.color && cc.claim == this.claim; } return false; } @Override public int hashCode(){ return claim.hashCode(); } @Override public String toString(){ return "ColorClaim pairing " + color + " with " + claim; } } @Override public ColorChain apply(Sudoku sudoku){ return new ColorChain(sudoku); } /** * <p>Finds a unary Fact in {@code target} and sets that Fact's * one Claim neighbor true.</p> * @return an Initialization describing the verification of * an Init's sole Claim neighbor and any and all resulting * automatic resolution events, or null if no Init is found */ private TechniqueEvent subsumedFacts(){ Optional<Pair<Fact,Set<Fact>>> i = target.factStream() .map((fact) -> new Pair<Fact,Set<Fact>>( fact, fact.visible().stream() .filter((vis) -> vis.containsAll(fact)) .collect(Collectors.toSet()))) .filter((pair) -> !pair.getB().isEmpty()) .findFirst(); if(i.isPresent()){ Pair<Fact,Set<Fact>> p = i.get(); return new SubsumedFact(p.getA(), p.getB()).falsifyClaims(); } return null; } /** * <p>Describes the verification of a Claim known to be true * because one or more of its Fact neighbors contains only that * Claim as an element..</p> * @author fiveham * */ public static class SubsumedFact extends TechniqueEvent{ private final Fact src; private final Set<Fact> supersets; private SubsumedFact(Fact solved, Set<Fact> supersets){ super(solved.iterator().next().visible()); this.src = solved; this.supersets = supersets; } @Override public boolean equals(Object o){ if(o instanceof SubsumedFact){ SubsumedFact se = (SubsumedFact) o; return super.equals(se) && (src == null ? se.src == null : src.equals(se.src)); } return false; } @Override protected String toStringStart(){ return src+"is subsumed by "+supersets.stream() .map(Object::toString) .collect(Collectors.joining(", ")); } } }
note in comments
src/sudoku/technique/ColorChain.java
note in comments
<ide><path>rc/sudoku/technique/ColorChain.java <ide> } <ide> } <ide> <add> /* <add> * TODO incorporate use of subsumedFacts via its method into xyChain's analysis <add> * and incorporate xyChain and subsumedFacts into implicationIntersection. <add> * <add> * Currently, SubsumedFacts analysis (in the form of checks for fully localized <add> * Facts, not including partially localized facts) is implicitly incorporated into <add> * xyChain analysis. I'd like to incorporate it in an explicit, formal manner, <add> * in order to add the partial-overlap functionality and also to avoid code duplication. <add> * <add> * Additionally, I'd like to incorporate subsumedFacts and xyChain into <add> * implicationIntersection in order to begin unifying ColorChain and Sledgehammer. <add> */ <ide> private static final List<Function<ColorChain,TechniqueEvent>> SUBTECHNIQUES = Arrays.asList( <ide> ColorChain::subsumedFacts, <ide> ColorChain::xyChain,
Java
bsd-3-clause
5f707982cfff22072ab5b800fc860453acb5b0cd
0
amihaiemil/charles,amihaiemil/charles,opencharles/charles,opencharles/charles
/* Copyright (c) 2016, Mihai Emil Andronache All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. * Neither the name of charles nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ package com.amihaiemil.charles; import static org.junit.Assert.assertTrue; import java.util.Set; import org.junit.After; import org.junit.Before; import org.junit.Test; import org.openqa.selenium.WebDriver; import org.openqa.selenium.phantomjs.PhantomJSDriver; import org.openqa.selenium.phantomjs.PhantomJSDriverService; import org.openqa.selenium.remote.DesiredCapabilities; /** * Integration tests for {@link LiveWebPage} * @author Mihai Andronache ([email protected]) * */ public class LiveWebPageITCase { private WebDriver driver; /** * {@link LiveWebPage} can fetch all the links from a web page when it has a CNAME url defined. */ @Test public void retrievesLinksFromPageCname() { String address = "http://amihaiemil.github.io/"; LiveWebPage livePage = new LiveWebPage(this.driver, address); Set<Link> links = livePage.getLinks(); assertTrue(links.size() > 0); assertTrue("Expected link not on web page!", links.contains( new Link("What is HATEOAS?", "http://www.amihaiemil.com/rest/2016/05/07/what-is-hateoas.html") ) ); } /** * {@link LiveWebPage} can fetch all the links from a web page. */ @Test public void retrievesLinksFromPage() { String address = "http://www.amihaiemil.com/"; LiveWebPage livePage = new LiveWebPage(this.driver, address); Set<Link> links = livePage.getLinks(); assertTrue(links.size() > 0); assertTrue("Expected link not on web page!", links.contains( new Link("What is HATEOAS?", "http://www.amihaiemil.com/rest/2016/05/07/what-is-hateoas.html") ) ); for(Link l : links) { assertTrue(l.getHref().startsWith(address)); } } /** * {@link LiveWebPage} can fetch its category. */ @Test public void retrievesPageCategory() { String address = "http://www.amihaiemil.com/"; LiveWebPage livePage = new LiveWebPage(this.driver, address); assertTrue(livePage.getCategory().equals("page")); } /** * {@link LiveWebPage} can return the visible text from the page. */ @Test public void retrievesTextFromPage() { LiveWebPage livePage = new LiveWebPage(this.driver, "http://www.amihaiemil.com/rest/2016/05/07/what-is-hateoas.html"); String textContent = livePage.getTextContent(); assertTrue(textContent.contains("In his book Burke also describes HATEOAS")); assertTrue(textContent.contains("\"lastmodified\": \"15/03/2016\"")); assertTrue(textContent.contains("JS client to work with it")); } /** * {@link LiveWebpage} can return a snapshot WebPage. */ @Test public void snapshotsSelf() { LiveWebPage livePage = new LiveWebPage(this.driver, "http://www.amihaiemil.com"); WebPage snapshot = livePage.snapshot(); assertTrue(snapshot.getTitle().equals("amihaiemil.com | Programming blog")); assertTrue(snapshot.getLinks().size() > 0); assertTrue("Expected link not on web page!", snapshot.getLinks().contains( new Link("What is HATEOAS?", "http://www.amihaiemil.com/rest/2016/05/07/what-is-hateoas.html") ) ); } @Before public void initDriver() { this.driver = this.phantomJsDriver(); } @After public void quitDriver() { this.driver.quit(); } private WebDriver phantomJsDriver() { String phantomJsExecPath = System.getProperty("phantomjsExec"); if("".equals(phantomJsExecPath)) { phantomJsExecPath = "/usr/local/bin/phantomjs"; } DesiredCapabilities dc = new DesiredCapabilities(); dc.setJavascriptEnabled(true); dc.setCapability( PhantomJSDriverService.PHANTOMJS_EXECUTABLE_PATH_PROPERTY, phantomJsExecPath ); return new PhantomJSDriver(dc); } }
src/test/java/com/amihaiemil/charles/LiveWebPageITCase.java
/* Copyright (c) 2016, Mihai Emil Andronache All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. * Neither the name of charles nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ package com.amihaiemil.charles; import static org.junit.Assert.assertTrue; import java.util.Set; import org.junit.After; import org.junit.Before; import org.junit.Test; import org.openqa.selenium.WebDriver; import org.openqa.selenium.firefox.FirefoxDriver; import org.openqa.selenium.phantomjs.PhantomJSDriver; import org.openqa.selenium.phantomjs.PhantomJSDriverService; import org.openqa.selenium.remote.DesiredCapabilities; /** * Integration tests for {@link LiveWebPage} * @author Mihai Andronache ([email protected]) * */ public class LiveWebPageITCase { private WebDriver driver; /** * {@link LiveWebPage} can fetch all the links from a web page when it has a CNAME url defined. */ @Test public void retrievesLinksFromPageCname() { String address = "http://amihaiemil.github.io/"; LiveWebPage livePage = new LiveWebPage(this.driver, address); Set<Link> links = livePage.getLinks(); assertTrue(links.size() > 0); assertTrue("Expected link not on web page!", links.contains( new Link("What is HATEOAS?", "http://www.amihaiemil.com/rest/2016/05/07/what-is-hateoas.html") ) ); } /** * {@link LiveWebPage} can fetch all the links from a web page. */ @Test public void retrievesLinksFromPage() { String address = "http://www.amihaiemil.com/"; LiveWebPage livePage = new LiveWebPage(this.driver, address); Set<Link> links = livePage.getLinks(); assertTrue(links.size() > 0); assertTrue("Expected link not on web page!", links.contains( new Link("What is HATEOAS?", "http://www.amihaiemil.com/rest/2016/05/07/what-is-hateoas.html") ) ); for(Link l : links) { assertTrue(l.getHref().startsWith(address)); } } /** * {@link LiveWebPage} can fetch its category. */ @Test public void retrievesPageCategory() { String address = "http://www.amihaiemil.com/"; LiveWebPage livePage = new LiveWebPage(this.driver, address); assertTrue(livePage.getCategory().equals("page")); } /** * {@link LiveWebPage} can return the visible text from the page. */ @Test public void retrievesTextFromPage() { LiveWebPage livePage = new LiveWebPage(this.driver, "http://www.amihaiemil.com/rest/2016/05/07/what-is-hateoas.html"); String textContent = livePage.getTextContent(); assertTrue(textContent.contains("In his book Burke also describes HATEOAS")); assertTrue(textContent.contains("\"lastmodified\": \"15/03/2016\"")); assertTrue(textContent.contains("JS client to work with it")); } /** * {@link LiveWebpage} can return a snapshot WebPage. */ @Test public void snapshotsSelf() { LiveWebPage livePage = new LiveWebPage(this.driver, "http://www.amihaiemil.com"); WebPage snapshot = livePage.snapshot(); assertTrue(snapshot.getTitle().equals("amihaiemil.com | Programming blog")); assertTrue(snapshot.getLinks().size() > 0); assertTrue("Expected link not on web page!", snapshot.getLinks().contains( new Link("What is HATEOAS?", "http://www.amihaiemil.com/rest/2016/05/07/what-is-hateoas.html") ) ); } @Before public void initDriver() { this.driver = this.phantomJsDriver(); } @After public void quitDriver() { this.driver.quit(); } private WebDriver phantomJsDriver() { // String phantomJsExecPath = System.getProperty("phantomjsExec"); // if("".equals(phantomJsExecPath)) { // phantomJsExecPath = "/usr/local/bin/phantomjs"; // } // // DesiredCapabilities dc = new DesiredCapabilities(); // dc.setJavascriptEnabled(true); // dc.setCapability( // PhantomJSDriverService.PHANTOMJS_EXECUTABLE_PATH_PROPERTY, // phantomJsExecPath // ); // return new PhantomJSDriver(dc); System.setProperty("webdriver.firefox.bin", "C:\\Program Files\\Mozilla Firefox\\firefox.exe"); return new FirefoxDriver(); } }
back to phantomjs
src/test/java/com/amihaiemil/charles/LiveWebPageITCase.java
back to phantomjs
<ide><path>rc/test/java/com/amihaiemil/charles/LiveWebPageITCase.java <ide> import org.junit.Before; <ide> import org.junit.Test; <ide> import org.openqa.selenium.WebDriver; <del>import org.openqa.selenium.firefox.FirefoxDriver; <ide> import org.openqa.selenium.phantomjs.PhantomJSDriver; <ide> import org.openqa.selenium.phantomjs.PhantomJSDriverService; <ide> import org.openqa.selenium.remote.DesiredCapabilities; <ide> } <ide> <ide> private WebDriver phantomJsDriver() { <del>// String phantomJsExecPath = System.getProperty("phantomjsExec"); <del>// if("".equals(phantomJsExecPath)) { <del>// phantomJsExecPath = "/usr/local/bin/phantomjs"; <del>// } <del>// <del>// DesiredCapabilities dc = new DesiredCapabilities(); <del>// dc.setJavascriptEnabled(true); <del>// dc.setCapability( <del>// PhantomJSDriverService.PHANTOMJS_EXECUTABLE_PATH_PROPERTY, <del>// phantomJsExecPath <del>// ); <del>// return new PhantomJSDriver(dc); <del> System.setProperty("webdriver.firefox.bin", "C:\\Program Files\\Mozilla Firefox\\firefox.exe"); <del> return new FirefoxDriver(); <add> String phantomJsExecPath = System.getProperty("phantomjsExec"); <add> if("".equals(phantomJsExecPath)) { <add> phantomJsExecPath = "/usr/local/bin/phantomjs"; <add> } <add> <add> DesiredCapabilities dc = new DesiredCapabilities(); <add> dc.setJavascriptEnabled(true); <add> dc.setCapability( <add> PhantomJSDriverService.PHANTOMJS_EXECUTABLE_PATH_PROPERTY, <add> phantomJsExecPath <add> ); <add> return new PhantomJSDriver(dc); <ide> } <ide> <ide> }
Java
apache-2.0
252ec48a44e2c42e21136a52ce7a9915e9fe4ff2
0
NationalSecurityAgency/ghidra,NationalSecurityAgency/ghidra,NationalSecurityAgency/ghidra,NationalSecurityAgency/ghidra,NationalSecurityAgency/ghidra,NationalSecurityAgency/ghidra,NationalSecurityAgency/ghidra
/* ### * IP: GHIDRA * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package ghidra.app.plugin.core.disassembler; import docking.action.DockingAction; import ghidra.app.CorePluginPackage; import ghidra.app.cmd.disassemble.*; import ghidra.app.context.ListingActionContext; import ghidra.app.events.ProgramActivatedPluginEvent; import ghidra.app.plugin.PluginCategoryNames; import ghidra.app.plugin.core.codebrowser.CodeViewerActionContext; import ghidra.framework.options.Options; import ghidra.framework.plugintool.*; import ghidra.framework.plugintool.util.PluginStatus; import ghidra.program.disassemble.Disassembler; import ghidra.program.model.address.*; import ghidra.program.model.lang.Register; import ghidra.program.model.listing.*; import ghidra.program.model.mem.MemoryAccessException; import ghidra.program.util.ProgramLocation; import ghidra.program.util.ProgramSelection; /** * <CODE>DisassemblerPlugin</CODE> provides functionality for dynamic disassembly, * static disassembly.<BR> * In dynamic disassembly disassembling begins from the * selected addresses or if there is no selection then at the address of the * current cursor location and attempts to continue disassembling * through fallthroughs and along all flows from a disassembled instruction. * For instance, if a jump instruction is disassembled then the address being * jumped to will be disassembled. The dynamic disassembly will also follow * data pointers to addresses containing undefined data, which is then * disassembled.<BR> * In static disassembly a range or set of ranges * is given and disassembly is attempted on each range. Any defined code in the * ranges before the static disassembly are first removed.<BR> * <P> * <CODE>DisassemblerPlugin</CODE> provides access to its functions as a service * that another plugin may use and through the popup menu to the user. */ //@formatter:off @PluginInfo( status = PluginStatus.RELEASED, packageName = CorePluginPackage.NAME, category = PluginCategoryNames.ANALYSIS, shortDescription = "Disassembler", description = "This plugin provides functionality for dynamic disassembly, " + "static disassembly. In dynamic disassembly, disassembling begins from the " + "selected addresses or if there is no selection then at the address of the " + "current cursor location and attempts to continue disassembling " + "through fallthroughs and along all flows from a disassembled instruction. " + "For instance, if a jump instruction is disassembled then the address being " + "jumped to will be disassembled. The dynamic disassembly will also follow " + "data pointers to addresses containing undefined data, which is then " + "disassembled. In static disassembly a range or set of ranges " + "is given and disassembly is attempted on each range. Any defined code in the " + "ranges before the static disassembly are first removed.", eventsConsumed = { ProgramActivatedPluginEvent.class } ) //@formatter:on public class DisassemblerPlugin extends Plugin { // action info final static String GROUP_NAME = "Disassembly"; // actions private DockingAction disassembleRestrictedAction; private DockingAction disassembleAction; private DockingAction disassembleStaticAction; private DockingAction contextAction; private DockingAction armDisassembleAction; private DockingAction armThumbDisassembleAction; private DockingAction hcs12DisassembleAction; private DockingAction xgateDisassembleAction; private DockingAction mipsDisassembleAction; private DockingAction mips16DisassembleAction; private DockingAction ppcDisassembleAction; private DockingAction ppcVleDisassembleAction; private DockingAction setFlowOverrideAction; /** Dialog for obtaining the processor state to be used for disassembling. */ // private ProcessorStateDialog processorStateDialog; ////////////////////////////////////////////////////////////////////// // // // static class methods // // // ////////////////////////////////////////////////////////////////////// /** * Get the description of this plugin. */ public static String getDescription() { return "Provides disassembler services for all supplied machine language modules."; } /** * Get the descriptive name. */ public static String getDescriptiveName() { return "Disassembler"; } /** * Get the category. */ public static String getCategory() { return "Disassemblers"; } ////////////////////////////////////////////////////////////////////// // // // Constructor // // // ////////////////////////////////////////////////////////////////////// /** * Creates a new instance of the plugin giving it the tool that * it will work in. */ public DisassemblerPlugin(PluginTool tool) { super(tool); createActions(); } @Override public void processEvent(PluginEvent event) { if (event instanceof ProgramActivatedPluginEvent) { ProgramActivatedPluginEvent ev = (ProgramActivatedPluginEvent) event; programActivated(ev.getActiveProgram()); } } protected void programActivated(Program program) { if (program == null) { return; } Options options = program.getOptions(Program.DISASSEMBLER_PROPERTIES); options.registerOption(Disassembler.MARK_BAD_INSTRUCTION_PROPERTY, true, null, "Place ERROR Bookmark at locations where disassembly could not be perfomed."); options.registerOption( Disassembler.MARK_UNIMPL_PCODE_PROPERTY, true, null, "Place WARNING Bookmark at locations where a disassembled instruction has unimplemented pcode."); options.registerOption(Disassembler.RESTRICT_DISASSEMBLY_TO_EXECUTE_MEMORY_PROPERTY, false, null, "Restrict disassembly to executable memory blocks."); } ////////////////////////////////////////////////////////////////////// // private methods // ////////////////////////////////////////////////////////////////////// /** * Creates actions for the plugin. */ private void createActions() { disassembleAction = new DisassembleAction(this, GROUP_NAME); disassembleRestrictedAction = new RestrictedDisassembleAction(this, GROUP_NAME); disassembleStaticAction = new StaticDisassembleAction(this, GROUP_NAME); contextAction = new ContextAction(this, GROUP_NAME); armDisassembleAction = new ArmDisassembleAction(this, GROUP_NAME, false); armThumbDisassembleAction = new ArmDisassembleAction(this, GROUP_NAME, true); hcs12DisassembleAction = new Hcs12DisassembleAction(this, GROUP_NAME, false); xgateDisassembleAction = new Hcs12DisassembleAction(this, GROUP_NAME, true); mipsDisassembleAction = new MipsDisassembleAction(this, GROUP_NAME, false); mips16DisassembleAction = new MipsDisassembleAction(this, GROUP_NAME, true); ppcDisassembleAction = new PowerPCDisassembleAction(this, GROUP_NAME, false); ppcVleDisassembleAction= new PowerPCDisassembleAction(this, GROUP_NAME, true); setFlowOverrideAction = new SetFlowOverrideAction(this, GROUP_NAME); tool.addAction(disassembleAction); tool.addAction(disassembleRestrictedAction); tool.addAction(disassembleStaticAction); tool.addAction(armDisassembleAction); tool.addAction(armThumbDisassembleAction); tool.addAction(hcs12DisassembleAction); tool.addAction(xgateDisassembleAction); tool.addAction(mipsDisassembleAction); tool.addAction(mips16DisassembleAction); tool.addAction(ppcDisassembleAction); tool.addAction(ppcVleDisassembleAction); tool.addAction(contextAction); tool.addAction(setFlowOverrideAction); } void disassembleRestrictedCallback(ListingActionContext context) { ProgramSelection currentSelection = context.getSelection(); ProgramLocation currentLocation = context.getLocation(); Program currentProgram = context.getProgram(); DisassembleCommand cmd = null; if ((currentSelection != null) && (!currentSelection.isEmpty())) { cmd = new DisassembleCommand(currentSelection, currentSelection, true); } else { Address addr = currentLocation.getAddress(); cmd = new DisassembleCommand(addr, new AddressSet(addr, addr), true); } tool.executeBackgroundCommand(cmd, currentProgram); } void disassembleStaticCallback(ListingActionContext context) { ProgramSelection currentSelection = context.getSelection(); ProgramLocation currentLocation = context.getLocation(); Program currentProgram = context.getProgram(); DisassembleCommand cmd = null; if ((currentSelection != null) && (!currentSelection.isEmpty())) { cmd = new DisassembleCommand(currentSelection, currentSelection, false); } else { Address addr = currentLocation.getAddress(); cmd = new DisassembleCommand(addr, new AddressSet(addr, addr), false); } tool.executeBackgroundCommand(cmd, currentProgram); } void disassembleCallback(ListingActionContext context) { ProgramSelection currentSelection = context.getSelection(); ProgramLocation currentLocation = context.getLocation(); Program currentProgram = context.getProgram(); DisassembleCommand cmd = null; boolean isDynamicListing = (context instanceof CodeViewerActionContext && ((CodeViewerActionContext) context).isDyanmicListing()); if ((currentSelection != null) && (!currentSelection.isEmpty())) { cmd = new DisassembleCommand(currentSelection, null, true); } else { Address addr = currentLocation.getAddress(); try { currentProgram.getMemory().getByte(addr); AddressSetView restrictedSet = null; if (isDynamicListing) { // TODO: should we have option to control restricted range? Address min, max; try { min = addr.subtractNoWrap(1000); } catch (AddressOverflowException e) { min = addr.getAddressSpace().getMinAddress(); } try { max = addr.addNoWrap(1000); } catch (AddressOverflowException e) { max = addr.getAddressSpace().getMaxAddress(); } restrictedSet = new AddressSet(min, max); } cmd = new DisassembleCommand(addr, restrictedSet, true); } catch (MemoryAccessException e) { tool.setStatusInfo("Can't disassemble unitialized memory!", true); } } if (cmd != null) { cmd.enableCodeAnalysis(!isDynamicListing); // do not analyze debugger listing tool.executeBackgroundCommand(cmd, currentProgram); } } boolean checkDisassemblyEnabled(ListingActionContext context, Address address, boolean followPtr) { ProgramSelection currentSelection = context.getSelection(); Program currentProgram = context.getProgram(); if ((currentSelection != null) && (!currentSelection.isEmpty())) { return true; } Listing listing = currentProgram.getListing(); if (listing.getInstructionContaining(address) != null) { return false; } Data data = listing.getDefinedDataContaining(address); if (data != null) { if (followPtr && data.isPointer()) { Address ptrAddr = data.getAddress(0); if (ptrAddr != null) { return checkDisassemblyEnabled(context, ptrAddr, false); } } return false; } return currentProgram.getMemory().contains(address); } public void setDefaultContext(ListingActionContext context) { Program contextProgram = context.getProgram(); Register baseContextReg = contextProgram.getLanguage().getContextBaseRegister(); if (baseContextReg != null && baseContextReg.hasChildren()) { tool.showDialog(new ProcessorStateDialog(contextProgram.getProgramContext()), context.getComponentProvider()); } } public boolean hasContextRegisters(Program currentProgram) { Register baseContextReg = currentProgram.getLanguage().getContextBaseRegister(); return baseContextReg != null && baseContextReg.hasChildren(); } public void disassembleArmCallback(ListingActionContext context, boolean thumbMode) { ProgramSelection currentSelection = context.getSelection(); ProgramLocation currentLocation = context.getLocation(); Program currentProgram = context.getProgram(); ArmDisassembleCommand cmd = null; if ((currentSelection != null) && (!currentSelection.isEmpty())) { cmd = new ArmDisassembleCommand(currentSelection, null, thumbMode); } else { Address addr = currentLocation.getAddress(); try { currentProgram.getMemory().getByte(addr); cmd = new ArmDisassembleCommand(addr, null, thumbMode); } catch (MemoryAccessException e) { tool.setStatusInfo("Can't disassemble unitialized memory!", true); } } if (cmd != null) { tool.executeBackgroundCommand(cmd, currentProgram); } } public void disassembleHcs12Callback(ListingActionContext context, boolean xgMode) { ProgramSelection currentSelection = context.getSelection(); ProgramLocation currentLocation = context.getLocation(); Program currentProgram = context.getProgram(); Hcs12DisassembleCommand cmd = null; if ((currentSelection != null) && (!currentSelection.isEmpty())) { cmd = new Hcs12DisassembleCommand(currentSelection, null, xgMode); } else { Address addr = currentLocation.getAddress(); try { currentProgram.getMemory().getByte(addr); cmd = new Hcs12DisassembleCommand(addr, null, xgMode); } catch (MemoryAccessException e) { tool.setStatusInfo("Can't disassemble unitialized memory!", true); } } if (cmd != null) { tool.executeBackgroundCommand(cmd, currentProgram); } } public void disassembleMipsCallback(ListingActionContext context, boolean mips16) { ProgramSelection currentSelection = context.getSelection(); ProgramLocation currentLocation = context.getLocation(); Program currentProgram = context.getProgram(); MipsDisassembleCommand cmd = null; if ((currentSelection != null) && (!currentSelection.isEmpty())) { cmd = new MipsDisassembleCommand(currentSelection, null, mips16); } else { Address addr = currentLocation.getAddress(); try { currentProgram.getMemory().getByte(addr); cmd = new MipsDisassembleCommand(addr, null, mips16); } catch (MemoryAccessException e) { tool.setStatusInfo("Can't disassemble unitialized memory!", true); } } if (cmd != null) { tool.executeBackgroundCommand(cmd, currentProgram); } } public void disassemblePPCCallback(ListingActionContext context, boolean vle) { ProgramSelection currentSelection = context.getSelection(); ProgramLocation currentLocation = context.getLocation(); Program currentProgram = context.getProgram(); PowerPCDisassembleCommand cmd = null; if ((currentSelection != null) && (!currentSelection.isEmpty())) { cmd = new PowerPCDisassembleCommand(currentSelection, null, vle); } else { Address addr = currentLocation.getAddress(); try { currentProgram.getMemory().getByte(addr); cmd = new PowerPCDisassembleCommand(addr, null, vle); } catch (MemoryAccessException e) { tool.setStatusInfo("Can't disassemble unitialized memory!", true); } } if (cmd != null) { tool.executeBackgroundCommand(cmd, currentProgram); } } }
Ghidra/Features/Base/src/main/java/ghidra/app/plugin/core/disassembler/DisassemblerPlugin.java
/* ### * IP: GHIDRA * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package ghidra.app.plugin.core.disassembler; import docking.action.DockingAction; import ghidra.app.CorePluginPackage; import ghidra.app.cmd.disassemble.*; import ghidra.app.context.ListingActionContext; import ghidra.app.events.ProgramActivatedPluginEvent; import ghidra.app.plugin.PluginCategoryNames; import ghidra.app.plugin.core.codebrowser.CodeViewerActionContext; import ghidra.framework.options.Options; import ghidra.framework.plugintool.*; import ghidra.framework.plugintool.util.PluginStatus; import ghidra.program.disassemble.Disassembler; import ghidra.program.model.address.*; import ghidra.program.model.lang.Register; import ghidra.program.model.listing.*; import ghidra.program.model.mem.MemoryAccessException; import ghidra.program.util.ProgramLocation; import ghidra.program.util.ProgramSelection; /** * <CODE>DisassemblerPlugin</CODE> provides functionality for dynamic disassembly, * static disassembly.<BR> * In dynamic disassembly disassembling begins from the * selected addresses or if there is no selection then at the address of the * current cursor location and attempts to continue disassembling * through fallthroughs and along all flows from a disassembled instruction. * For instance, if a jump instruction is disassembled then the address being * jumped to will be disassembled. The dynamic disassembly will also follow * data pointers to addresses containing undefined data, which is then * disassembled.<BR> * In static disassembly a range or set of ranges * is given and disassembly is attempted on each range. Any defined code in the * ranges before the static disassembly are first removed.<BR> * <P> * <CODE>DisassemblerPlugin</CODE> provides access to its functions as a service * that another plugin may use and through the popup menu to the user. */ //@formatter:off @PluginInfo( status = PluginStatus.RELEASED, packageName = CorePluginPackage.NAME, category = PluginCategoryNames.ANALYSIS, shortDescription = "Disassembler", description = "This plugin provides functionality for dynamic disassembly, " + "static disassembly. In dynamic disassembly, disassembling begins from the " + "selected addresses or if there is no selection then at the address of the " + "current cursor location and attempts to continue disassembling " + "through fallthroughs and along all flows from a disassembled instruction. " + "For instance, if a jump instruction is disassembled then the address being " + "jumped to will be disassembled. The dynamic disassembly will also follow " + "data pointers to addresses containing undefined data, which is then " + "disassembled. In static disassembly a range or set of ranges " + "is given and disassembly is attempted on each range. Any defined code in the " + "ranges before the static disassembly are first removed.", eventsConsumed = { ProgramActivatedPluginEvent.class } ) //@formatter:on public class DisassemblerPlugin extends Plugin { // action info final static String GROUP_NAME = "Disassembly"; // actions private DockingAction disassembleRestrictedAction; private DockingAction disassembleAction; private DockingAction disassembleStaticAction; private DockingAction contextAction; private DockingAction armDisassembleAction; private DockingAction armThumbDisassembleAction; private DockingAction hcs12DisassembleAction; private DockingAction xgateDisassembleAction; private DockingAction mipsDisassembleAction; private DockingAction mips16DisassembleAction; private DockingAction ppcDisassembleAction; private DockingAction ppcVleDisassembleAction; private DockingAction setFlowOverrideAction; /** Dialog for obtaining the processor state to be used for disassembling. */ // private ProcessorStateDialog processorStateDialog; ////////////////////////////////////////////////////////////////////// // // // static class methods // // // ////////////////////////////////////////////////////////////////////// /** * Get the description of this plugin. */ public static String getDescription() { return "Provides disassembler services for all supplied machine language modules."; } /** * Get the descriptive name. */ public static String getDescriptiveName() { return "Disassembler"; } /** * Get the category. */ public static String getCategory() { return "Disassemblers"; } ////////////////////////////////////////////////////////////////////// // // // Constructor // // // ////////////////////////////////////////////////////////////////////// /** * Creates a new instance of the plugin giving it the tool that * it will work in. */ public DisassemblerPlugin(PluginTool tool) { super(tool); createActions(); } @Override public void processEvent(PluginEvent event) { if (event instanceof ProgramActivatedPluginEvent) { ProgramActivatedPluginEvent ev = (ProgramActivatedPluginEvent) event; programActivated(ev.getActiveProgram()); } } protected void programActivated(Program program) { if (program == null) { return; } Options options = program.getOptions(Program.DISASSEMBLER_PROPERTIES); options.registerOption(Disassembler.MARK_BAD_INSTRUCTION_PROPERTY, true, null, "Place ERROR Bookmark at locations where disassembly could not be perfomed."); options.registerOption( Disassembler.MARK_UNIMPL_PCODE_PROPERTY, true, null, "Place WARNING Bookmark at locations where a disassembled instruction has unimplemented pcode."); options.registerOption(Disassembler.RESTRICT_DISASSEMBLY_TO_EXECUTE_MEMORY_PROPERTY, false, null, "Restrict disassembly to executable memory blocks."); } ////////////////////////////////////////////////////////////////////// // private methods // ////////////////////////////////////////////////////////////////////// /** * Creates actions for the plugin. */ private void createActions() { disassembleAction = new DisassembleAction(this, GROUP_NAME); disassembleRestrictedAction = new RestrictedDisassembleAction(this, GROUP_NAME); disassembleStaticAction = new StaticDisassembleAction(this, GROUP_NAME); contextAction = new ContextAction(this, GROUP_NAME); armDisassembleAction = new ArmDisassembleAction(this, GROUP_NAME, false); armThumbDisassembleAction = new ArmDisassembleAction(this, GROUP_NAME, true); hcs12DisassembleAction = new Hcs12DisassembleAction(this, GROUP_NAME, false); xgateDisassembleAction = new Hcs12DisassembleAction(this, GROUP_NAME, true); mipsDisassembleAction = new MipsDisassembleAction(this, GROUP_NAME, false); mips16DisassembleAction = new MipsDisassembleAction(this, GROUP_NAME, true); ppcDisassembleAction = new PowerPCDisassembleAction(this, GROUP_NAME, false); ppcVleDisassembleAction= new PowerPCDisassembleAction(this, GROUP_NAME, true); setFlowOverrideAction = new SetFlowOverrideAction(this, GROUP_NAME); tool.addAction(disassembleAction); tool.addAction(disassembleRestrictedAction); tool.addAction(disassembleStaticAction); tool.addAction(armDisassembleAction); tool.addAction(armThumbDisassembleAction); tool.addAction(hcs12DisassembleAction); tool.addAction(xgateDisassembleAction); tool.addAction(mipsDisassembleAction); tool.addAction(mips16DisassembleAction); tool.addAction(ppcDisassembleAction); tool.addAction(ppcVleDisassembleAction); tool.addAction(contextAction); tool.addAction(setFlowOverrideAction); } void disassembleRestrictedCallback(ListingActionContext context) { ProgramSelection currentSelection = context.getSelection(); ProgramLocation currentLocation = context.getLocation(); Program currentProgram = context.getProgram(); DisassembleCommand cmd = null; if ((currentSelection != null) && (!currentSelection.isEmpty())) { cmd = new DisassembleCommand(currentSelection, currentSelection, true); } else { Address addr = currentLocation.getAddress(); cmd = new DisassembleCommand(addr, new AddressSet(addr, addr), true); } tool.executeBackgroundCommand(cmd, currentProgram); } void disassembleStaticCallback(ListingActionContext context) { ProgramSelection currentSelection = context.getSelection(); ProgramLocation currentLocation = context.getLocation(); Program currentProgram = context.getProgram(); DisassembleCommand cmd = null; if ((currentSelection != null) && (!currentSelection.isEmpty())) { cmd = new DisassembleCommand(currentSelection, currentSelection, false); } else { Address addr = currentLocation.getAddress(); cmd = new DisassembleCommand(addr, new AddressSet(addr, addr), false); } tool.executeBackgroundCommand(cmd, currentProgram); } void disassembleCallback(ListingActionContext context) { ProgramSelection currentSelection = context.getSelection(); ProgramLocation currentLocation = context.getLocation(); Program currentProgram = context.getProgram(); DisassembleCommand cmd = null; boolean isDynamicListing = (context instanceof CodeViewerActionContext && ((CodeViewerActionContext) context).isDyanmicListing()); if ((currentSelection != null) && (!currentSelection.isEmpty())) { cmd = new DisassembleCommand(currentSelection, null, true); } else { Address addr = currentLocation.getAddress(); try { currentProgram.getMemory().getByte(addr); AddressSetView restrictedSet = null; if (isDynamicListing) { // TODO: should we have option to control restricted range? Address min, max; try { min = addr.subtractNoWrap(1000); } catch (AddressOverflowException e) { min = addr.getAddressSpace().getMinAddress(); } try { max = addr.addNoWrap(1000); } catch (AddressOverflowException e) { max = addr.getAddressSpace().getMaxAddress(); } restrictedSet = new AddressSet(min, max); } cmd = new DisassembleCommand(addr, restrictedSet, true); } catch (MemoryAccessException e) { tool.setStatusInfo("Can't disassemble unitialized memory!", true); } } if (cmd != null) { cmd.enableCodeAnalysis(!isDynamicListing); // do not analyze debugger listing tool.executeBackgroundCommand(cmd, currentProgram); } } boolean checkDisassemblyEnabled(ListingActionContext context, Address address, boolean followPtr) { ProgramSelection currentSelection = context.getSelection(); Program currentProgram = context.getProgram(); if ((currentSelection != null) && (!currentSelection.isEmpty())) { return true; } Listing listing = currentProgram.getListing(); if (listing.getInstructionContaining(address) != null) { return false; } Data data = listing.getDefinedDataContaining(address); if (data != null) { if (followPtr && data.isPointer()) { Address ptrAddr = data.getAddress(0); if (ptrAddr != null) { return checkDisassemblyEnabled(context, ptrAddr, false); } } return false; } return currentProgram.getMemory().contains(address); } public void setDefaultContext(ListingActionContext context) { Program contextProgram = context.getProgram(); Register baseContextReg = contextProgram.getLanguage().getContextBaseRegister(); if (baseContextReg != null && baseContextReg.hasChildren()) { return; } tool.showDialog(new ProcessorStateDialog(contextProgram.getProgramContext()), context.getComponentProvider()); } public boolean hasContextRegisters(Program currentProgram) { Register baseContextReg = currentProgram.getLanguage().getContextBaseRegister(); return baseContextReg != null && baseContextReg.hasChildren(); } public void disassembleArmCallback(ListingActionContext context, boolean thumbMode) { ProgramSelection currentSelection = context.getSelection(); ProgramLocation currentLocation = context.getLocation(); Program currentProgram = context.getProgram(); ArmDisassembleCommand cmd = null; if ((currentSelection != null) && (!currentSelection.isEmpty())) { cmd = new ArmDisassembleCommand(currentSelection, null, thumbMode); } else { Address addr = currentLocation.getAddress(); try { currentProgram.getMemory().getByte(addr); cmd = new ArmDisassembleCommand(addr, null, thumbMode); } catch (MemoryAccessException e) { tool.setStatusInfo("Can't disassemble unitialized memory!", true); } } if (cmd != null) { tool.executeBackgroundCommand(cmd, currentProgram); } } public void disassembleHcs12Callback(ListingActionContext context, boolean xgMode) { ProgramSelection currentSelection = context.getSelection(); ProgramLocation currentLocation = context.getLocation(); Program currentProgram = context.getProgram(); Hcs12DisassembleCommand cmd = null; if ((currentSelection != null) && (!currentSelection.isEmpty())) { cmd = new Hcs12DisassembleCommand(currentSelection, null, xgMode); } else { Address addr = currentLocation.getAddress(); try { currentProgram.getMemory().getByte(addr); cmd = new Hcs12DisassembleCommand(addr, null, xgMode); } catch (MemoryAccessException e) { tool.setStatusInfo("Can't disassemble unitialized memory!", true); } } if (cmd != null) { tool.executeBackgroundCommand(cmd, currentProgram); } } public void disassembleMipsCallback(ListingActionContext context, boolean mips16) { ProgramSelection currentSelection = context.getSelection(); ProgramLocation currentLocation = context.getLocation(); Program currentProgram = context.getProgram(); MipsDisassembleCommand cmd = null; if ((currentSelection != null) && (!currentSelection.isEmpty())) { cmd = new MipsDisassembleCommand(currentSelection, null, mips16); } else { Address addr = currentLocation.getAddress(); try { currentProgram.getMemory().getByte(addr); cmd = new MipsDisassembleCommand(addr, null, mips16); } catch (MemoryAccessException e) { tool.setStatusInfo("Can't disassemble unitialized memory!", true); } } if (cmd != null) { tool.executeBackgroundCommand(cmd, currentProgram); } } public void disassemblePPCCallback(ListingActionContext context, boolean vle) { ProgramSelection currentSelection = context.getSelection(); ProgramLocation currentLocation = context.getLocation(); Program currentProgram = context.getProgram(); PowerPCDisassembleCommand cmd = null; if ((currentSelection != null) && (!currentSelection.isEmpty())) { cmd = new PowerPCDisassembleCommand(currentSelection, null, vle); } else { Address addr = currentLocation.getAddress(); try { currentProgram.getMemory().getByte(addr); cmd = new PowerPCDisassembleCommand(addr, null, vle); } catch (MemoryAccessException e) { tool.setStatusInfo("Can't disassemble unitialized memory!", true); } } if (cmd != null) { tool.executeBackgroundCommand(cmd, currentProgram); } } }
GP-38 Corrected ContextAction failure to display dialog (Closes #2860)
Ghidra/Features/Base/src/main/java/ghidra/app/plugin/core/disassembler/DisassemblerPlugin.java
GP-38 Corrected ContextAction failure to display dialog (Closes #2860)
<ide><path>hidra/Features/Base/src/main/java/ghidra/app/plugin/core/disassembler/DisassemblerPlugin.java <ide> } <ide> <ide> public void setDefaultContext(ListingActionContext context) { <del> <ide> Program contextProgram = context.getProgram(); <ide> Register baseContextReg = contextProgram.getLanguage().getContextBaseRegister(); <ide> if (baseContextReg != null && baseContextReg.hasChildren()) { <del> return; <del> } <del> <del> tool.showDialog(new ProcessorStateDialog(contextProgram.getProgramContext()), <del> context.getComponentProvider()); <add> tool.showDialog(new ProcessorStateDialog(contextProgram.getProgramContext()), <add> context.getComponentProvider()); <add> } <ide> } <ide> <ide> public boolean hasContextRegisters(Program currentProgram) {
Java
apache-2.0
8141393299ceaa5051238ee9423e047da990de4e
0
yongtang/hadoop-xz
package io.sensesecure.hadoop.xz; import java.io.ByteArrayInputStream; import java.io.DataInputStream; import java.io.IOException; import java.io.InputStream; import org.apache.hadoop.fs.Seekable; import org.apache.hadoop.io.compress.SplitCompressionInputStream; import org.apache.hadoop.io.compress.SplittableCompressionCodec.READ_MODE; import org.tukaani.xz.SeekableXZInputStream; import org.tukaani.xz.XZ; import org.tukaani.xz.check.Check; import org.tukaani.xz.common.DecoderUtil; import org.tukaani.xz.common.StreamFlags; import static org.tukaani.xz.common.Util.BLOCK_HEADER_SIZE_MAX; import static org.tukaani.xz.common.Util.STREAM_HEADER_SIZE; /** * * @author yongtang */ public class XZSplitCompressionInputStream extends SplitCompressionInputStream { private final READ_MODE readMode; private final XZSeekableInputStream xzSeekableIn; private final SeekableXZInputStream seekableXZIn; private long adjustedStart; private long adjustedEnd; private long uncompressedStart; private long uncompressedEnd; public XZSplitCompressionInputStream(InputStream seekableIn, long start, long end, READ_MODE readMode) throws IOException { super(seekableIn, start, end); this.readMode = readMode; if (!(seekableIn instanceof Seekable)) { throw new IOException("seekableIn must be an instance of " + Seekable.class.getName()); } // There are two ways to find the stream footer: // 1. If each block includes the compressedSize, then the // stream footer could be located by skip through the // blocks until the index indicator is encountered. Since // compressedSize is an optional field in the block, this // method is not guaranteed. // 2. Alternatively the stream footer could be located by // scan though the stream until the footer magic is found DataInputStream inData = new DataInputStream(seekableIn); byte[] streamHeaderBuf = new byte[STREAM_HEADER_SIZE]; byte[] streamFooterBuf = new byte[STREAM_HEADER_SIZE]; byte[] buf = new byte[BLOCK_HEADER_SIZE_MAX]; long streamFinal = 0, offsetFinal = 0; ((Seekable) seekableIn).seek(0); int streamHeaderLen = inData.read(streamHeaderBuf, 0, STREAM_HEADER_SIZE); while (streamHeaderLen != -1) { if (streamHeaderLen != STREAM_HEADER_SIZE) { throw new IOException("XZ Stream Header is corrupt"); } StreamFlags streamFlags = DecoderUtil.decodeStreamHeader(streamHeaderBuf); int checkSize = Check.getInstance(streamFlags.checkType).getSize(); // Block Header or Index Indicator inData.readFully(buf, 0, 1); if (streamFinal != 0 && buf[0] != 0x00) { // We get the offsetFinal and stop offsetFinal = ((Seekable) seekableIn).getPos() - 1; break; } while (buf[0] != 0x00) { // Read the rest of the block header int headerSize = 4 * ((buf[0] & 0xFF) + 1); inData.readFully(buf, 1, headerSize - 1); // Validate the CRC32 if (!DecoderUtil.isCRC32Valid(buf, 0, headerSize - 4, headerSize - 4)) { throw new IOException("XZ Block Header is corrupt"); } // Check for reserved bits in Block Flags if ((buf[1] & 0x3C) != 0) { throw new IOException("Unsupported options in XZ Block Header"); } // Check compressed size if ((buf[1] & 0x40) == 0x00) { // No compressed size break; } ByteArrayInputStream bufStream = new ByteArrayInputStream(buf, 2, headerSize - 6); long compressedSize = DecoderUtil.decodeVLI(bufStream); if (compressedSize == 0 || compressedSize > ((DecoderUtil.VLI_MAX & ~(4 - 1)) - headerSize - checkSize)) { throw new IOException("Corrupted compressed size in XZ Block Header"); } // Skip compressed, padding, and crc32 long remaining = ((compressedSize + checkSize) + 4 - 1) & ~(4 - 1); if (inData.skip(remaining) != remaining) { throw new IOException("Incomplete data in XZ Block"); } inData.readFully(buf, 0, 1); } // No compressed size if (buf[0] != 0x00) { // Locate footer after end ((Seekable) seekableIn).seek((end & ~(4 - 1)) < STREAM_HEADER_SIZE ? 0 : ((end & ~(4 - 1)) - STREAM_HEADER_SIZE)); while (true) { inData.readFully(streamFooterBuf, 8, 4); if (streamFooterBuf[10] == XZ.FOOTER_MAGIC[0] && streamFooterBuf[11] == XZ.FOOTER_MAGIC[1]) { ((Seekable) seekableIn).seek(((Seekable) seekableIn).getPos() - STREAM_HEADER_SIZE); inData.readFully(streamFooterBuf); if (streamFooterBuf[10] == XZ.FOOTER_MAGIC[0] && streamFooterBuf[11] == XZ.FOOTER_MAGIC[1] && DecoderUtil.isCRC32Valid(streamFooterBuf, 4, 6, 0)) { break; } } } if (((Seekable) seekableIn).getPos() >= end) { offsetFinal = streamFinal = ((Seekable) seekableIn).getPos(); } // Stream header streamHeaderLen = inData.read(streamHeaderBuf, 0, STREAM_HEADER_SIZE); continue; } // Index Indicator long count = DecoderUtil.decodeVLI(inData); // If the Record count doesn't fit into an int, we cannot allocate the array to hold the record if (count > Integer.MAX_VALUE) { throw new IOException("XZ Index has over " + Integer.MAX_VALUE + " Records"); } // Decode the record for (int i = (int) count; i > 0; --i) { // Get the next Record long unpaddedSize = DecoderUtil.decodeVLI(inData); long uncompressedSize = DecoderUtil.decodeVLI(inData); } // Padding + CRC32 long off = ((Seekable) seekableIn).getPos(); long padding = ((off + 4 - 1) & ~(4 - 1)) - off; inData.skip(padding + 4); // Stream Footer inData.readFully(streamFooterBuf); if (streamFooterBuf[10] == XZ.FOOTER_MAGIC[0] && streamFooterBuf[11] == XZ.FOOTER_MAGIC[1] && DecoderUtil.isCRC32Valid(streamFooterBuf, 4, 6, 0)) { throw new IOException("XZ Stream Footer is corrupt"); } if (((Seekable) seekableIn).getPos() >= end) { offsetFinal = streamFinal = ((Seekable) seekableIn).getPos(); } // Stream Header streamHeaderLen = inData.read(streamHeaderBuf, 0, STREAM_HEADER_SIZE); } xzSeekableIn = new XZSeekableInputStream(in, streamFinal); seekableXZIn = new SeekableXZInputStream(xzSeekableIn); if (seekableXZIn.getBlockCount() == 0) { adjustedStart = 0; uncompressedStart = 0; if (start != 0) { adjustedStart = offsetFinal; uncompressedStart = seekableXZIn.length(); } adjustedEnd = 0; uncompressedEnd = 0; if (end != 0) { adjustedEnd = offsetFinal; uncompressedEnd = seekableXZIn.length(); } } else { adjustedStart = 0; uncompressedStart = 0; if (start != 0) { for (int i = 1; i < seekableXZIn.getBlockCount(); i++) { if (start <= seekableXZIn.getBlockCompPos(i)) { adjustedStart = seekableXZIn.getBlockCompPos(i); uncompressedStart = seekableXZIn.getBlockPos(i); break; } } if (adjustedStart == 0) { adjustedStart = offsetFinal; uncompressedStart = seekableXZIn.length(); } } adjustedEnd = 0; uncompressedEnd = 0; if (end != 0) { for (int i = 1; i < seekableXZIn.getBlockCount(); i++) { if (end <= seekableXZIn.getBlockCompPos(i)) { adjustedEnd = seekableXZIn.getBlockCompPos(i); uncompressedEnd = seekableXZIn.getBlockPos(i); break; } } if (adjustedEnd == 0) { adjustedEnd = offsetFinal; uncompressedEnd = seekableXZIn.length(); } } } seekableXZIn.seek(this.uncompressedStart); } @Override public void close() throws IOException { seekableXZIn.close(); } @Override public long getAdjustedStart() { return adjustedStart; } @Override public long getAdjustedEnd() { return adjustedEnd; } @Override public int read(byte[] b, int off, int len) throws IOException { if (seekableXZIn.position() < uncompressedEnd) { len = (int) ((seekableXZIn.position() + len < uncompressedEnd) ? len : uncompressedEnd - seekableXZIn.position()); return seekableXZIn.read(b, off, len); } return -1; } @Override public void resetState() throws IOException { throw new UnsupportedOperationException("readState() is not supported yet."); } @Override public int read() throws IOException { byte b[] = new byte[1]; int result = this.read(b, 0, 1); return (result < 0) ? result : (b[0] & 0xff); } @Override public long getPos() throws IOException { if (seekableXZIn.position() < uncompressedEnd) { return adjustedStart; } return adjustedEnd; } }
src/main/java/io/sensesecure/hadoop/xz/XZSplitCompressionInputStream.java
package io.sensesecure.hadoop.xz; import java.io.ByteArrayInputStream; import java.io.DataInputStream; import java.io.IOException; import java.io.InputStream; import org.apache.hadoop.fs.Seekable; import org.apache.hadoop.io.compress.SplitCompressionInputStream; import org.apache.hadoop.io.compress.SplittableCompressionCodec; import org.apache.hadoop.io.compress.SplittableCompressionCodec.READ_MODE; import org.tukaani.xz.SeekableXZInputStream; import org.tukaani.xz.XZ; import org.tukaani.xz.check.Check; import org.tukaani.xz.common.DecoderUtil; import org.tukaani.xz.common.StreamFlags; import static org.tukaani.xz.common.Util.BLOCK_HEADER_SIZE_MAX; import static org.tukaani.xz.common.Util.STREAM_HEADER_SIZE; /** * * @author yongtang */ public class XZSplitCompressionInputStream extends SplitCompressionInputStream { private final READ_MODE readMode; private final XZSeekableInputStream xzSeekableIn; private final SeekableXZInputStream seekableXZIn; private long adjustedStart; private long adjustedEnd; private long uncompressedStart; private long uncompressedEnd; public XZSplitCompressionInputStream(InputStream seekableIn, long start, long end, READ_MODE readMode) throws IOException { super(seekableIn, start, end); this.readMode = readMode; if (this.readMode != SplittableCompressionCodec.READ_MODE.BYBLOCK) { throw new UnsupportedOperationException("readMode " + readMode + " is not supported"); } if (!(seekableIn instanceof Seekable)) { throw new IOException("seekableIn must be an instance of " + Seekable.class.getName()); } // There are two ways to find the stream footer: // 1. If each block includes the compressedSize, then the // stream footer could be located by skip through the // blocks until the index indicator is encountered. Since // compressedSize is an optional field in the block, this // method is not guaranteed. // 2. Alternatively the stream footer could be located by // scan though the stream until the footer magic is found DataInputStream inData = new DataInputStream(seekableIn); byte[] streamHeaderBuf = new byte[STREAM_HEADER_SIZE]; byte[] streamFooterBuf = new byte[STREAM_HEADER_SIZE]; byte[] buf = new byte[BLOCK_HEADER_SIZE_MAX]; long streamFinal = 0, offsetFinal = 0; ((Seekable) seekableIn).seek(0); int streamHeaderLen = inData.read(streamHeaderBuf, 0, STREAM_HEADER_SIZE); while (streamHeaderLen != -1) { if (streamHeaderLen != STREAM_HEADER_SIZE) { throw new IOException("XZ Stream Header is corrupt"); } StreamFlags streamFlags = DecoderUtil.decodeStreamHeader(streamHeaderBuf); int checkSize = Check.getInstance(streamFlags.checkType).getSize(); // Block Header or Index Indicator inData.readFully(buf, 0, 1); if (streamFinal != 0 && buf[0] != 0x00) { // We get the offsetFinal and stop offsetFinal = ((Seekable) seekableIn).getPos() - 1; break; } while (buf[0] != 0x00) { // Read the rest of the block header int headerSize = 4 * ((buf[0] & 0xFF) + 1); inData.readFully(buf, 1, headerSize - 1); // Validate the CRC32 if (!DecoderUtil.isCRC32Valid(buf, 0, headerSize - 4, headerSize - 4)) { throw new IOException("XZ Block Header is corrupt"); } // Check for reserved bits in Block Flags if ((buf[1] & 0x3C) != 0) { throw new IOException("Unsupported options in XZ Block Header"); } // Check compressed size if ((buf[1] & 0x40) == 0x00) { // No compressed size break; } ByteArrayInputStream bufStream = new ByteArrayInputStream(buf, 2, headerSize - 6); long compressedSize = DecoderUtil.decodeVLI(bufStream); if (compressedSize == 0 || compressedSize > ((DecoderUtil.VLI_MAX & ~(4 - 1)) - headerSize - checkSize)) { throw new IOException("Corrupted compressed size in XZ Block Header"); } // Skip compressed, padding, and crc32 long remaining = ((compressedSize + checkSize) + 4 - 1) & ~(4 - 1); if (inData.skip(remaining) != remaining) { throw new IOException("Incomplete data in XZ Block"); } inData.readFully(buf, 0, 1); } // No compressed size if (buf[0] != 0x00) { // Locate footer after end ((Seekable) seekableIn).seek((end & ~(4 - 1)) < STREAM_HEADER_SIZE ? 0 : ((end & ~(4 - 1)) - STREAM_HEADER_SIZE)); while (true) { inData.readFully(streamFooterBuf, 8, 4); if (streamFooterBuf[10] == XZ.FOOTER_MAGIC[0] && streamFooterBuf[11] == XZ.FOOTER_MAGIC[1]) { ((Seekable) seekableIn).seek(((Seekable) seekableIn).getPos() - STREAM_HEADER_SIZE); inData.readFully(streamFooterBuf); if (streamFooterBuf[10] == XZ.FOOTER_MAGIC[0] && streamFooterBuf[11] == XZ.FOOTER_MAGIC[1] && DecoderUtil.isCRC32Valid(streamFooterBuf, 4, 6, 0)) { break; } } } if (((Seekable) seekableIn).getPos() >= end) { offsetFinal = streamFinal = ((Seekable) seekableIn).getPos(); } // Stream header streamHeaderLen = inData.read(streamHeaderBuf, 0, STREAM_HEADER_SIZE); continue; } // Index Indicator long count = DecoderUtil.decodeVLI(inData); // If the Record count doesn't fit into an int, we cannot allocate the array to hold the record if (count > Integer.MAX_VALUE) { throw new IOException("XZ Index has over " + Integer.MAX_VALUE + " Records"); } // Decode the record for (int i = (int) count; i > 0; --i) { // Get the next Record long unpaddedSize = DecoderUtil.decodeVLI(inData); long uncompressedSize = DecoderUtil.decodeVLI(inData); } // Padding + CRC32 long off = ((Seekable) seekableIn).getPos(); long padding = ((off + 4 - 1) & ~(4 - 1)) - off; inData.skip(padding + 4); // Stream Footer inData.readFully(streamFooterBuf); if (streamFooterBuf[10] == XZ.FOOTER_MAGIC[0] && streamFooterBuf[11] == XZ.FOOTER_MAGIC[1] && DecoderUtil.isCRC32Valid(streamFooterBuf, 4, 6, 0)) { throw new IOException("XZ Stream Footer is corrupt"); } if (((Seekable) seekableIn).getPos() >= end) { offsetFinal = streamFinal = ((Seekable) seekableIn).getPos(); } // Stream Header streamHeaderLen = inData.read(streamHeaderBuf, 0, STREAM_HEADER_SIZE); } xzSeekableIn = new XZSeekableInputStream(in, streamFinal); seekableXZIn = new SeekableXZInputStream(xzSeekableIn); if (seekableXZIn.getBlockCount() == 0) { adjustedStart = 0; uncompressedStart = 0; if (start != 0) { adjustedStart = offsetFinal; uncompressedStart = seekableXZIn.length(); } adjustedEnd = 0; uncompressedEnd = 0; if (end != 0) { adjustedEnd = offsetFinal; uncompressedEnd = seekableXZIn.length(); } } else { adjustedStart = 0; uncompressedStart = 0; if (start != 0) { for (int i = 1; i < seekableXZIn.getBlockCount(); i++) { if (start <= seekableXZIn.getBlockCompPos(i)) { adjustedStart = seekableXZIn.getBlockCompPos(i); uncompressedStart = seekableXZIn.getBlockPos(i); break; } } if (adjustedStart == 0) { adjustedStart = offsetFinal; uncompressedStart = seekableXZIn.length(); } } adjustedEnd = 0; uncompressedEnd = 0; if (end != 0) { for (int i = 1; i < seekableXZIn.getBlockCount(); i++) { if (end <= seekableXZIn.getBlockCompPos(i)) { adjustedEnd = seekableXZIn.getBlockCompPos(i); uncompressedEnd = seekableXZIn.getBlockPos(i); break; } } if (adjustedEnd == 0) { adjustedEnd = offsetFinal; uncompressedEnd = seekableXZIn.length(); } } } seekableXZIn.seek(this.uncompressedStart); } @Override public void close() throws IOException { seekableXZIn.close(); } @Override public long getAdjustedStart() { return adjustedStart; } @Override public long getAdjustedEnd() { return adjustedEnd; } @Override public int read(byte[] b, int off, int len) throws IOException { if (seekableXZIn.position() < uncompressedEnd) { len = (int) ((seekableXZIn.position() + len < uncompressedEnd) ? len : uncompressedEnd - seekableXZIn.position()); return seekableXZIn.read(b, off, len); } return -1; } @Override public void resetState() throws IOException { throw new UnsupportedOperationException("readState() is not supported yet."); } @Override public int read() throws IOException { if (seekableXZIn.position() < uncompressedEnd) { return seekableXZIn.read(); } return -1; } @Override public long getPos() throws IOException { if (seekableXZIn.position() < uncompressedEnd) { return adjustedStart; } return adjustedEnd; } }
Enable CONTINUOUS mode.
src/main/java/io/sensesecure/hadoop/xz/XZSplitCompressionInputStream.java
Enable CONTINUOUS mode.
<ide><path>rc/main/java/io/sensesecure/hadoop/xz/XZSplitCompressionInputStream.java <ide> import java.io.InputStream; <ide> import org.apache.hadoop.fs.Seekable; <ide> import org.apache.hadoop.io.compress.SplitCompressionInputStream; <del>import org.apache.hadoop.io.compress.SplittableCompressionCodec; <ide> import org.apache.hadoop.io.compress.SplittableCompressionCodec.READ_MODE; <ide> import org.tukaani.xz.SeekableXZInputStream; <ide> import org.tukaani.xz.XZ; <ide> <ide> this.readMode = readMode; <ide> <del> if (this.readMode != SplittableCompressionCodec.READ_MODE.BYBLOCK) { <del> throw new UnsupportedOperationException("readMode " + readMode + " is not supported"); <del> } <ide> if (!(seekableIn instanceof Seekable)) { <ide> throw new IOException("seekableIn must be an instance of " + Seekable.class.getName()); <ide> } <ide> <ide> @Override <ide> public int read() throws IOException { <del> if (seekableXZIn.position() < uncompressedEnd) { <del> return seekableXZIn.read(); <del> } <del> return -1; <add> byte b[] = new byte[1]; <add> int result = this.read(b, 0, 1); <add> return (result < 0) ? result : (b[0] & 0xff); <ide> } <ide> <ide> @Override
Java
apache-2.0
bc9641e6a3af172749cec992f70aac8ea8f60991
0
slapperwan/gh4a,edyesed/gh4a,slapperwan/gh4a,edyesed/gh4a
package com.gh4a.utils; import android.support.annotation.IntDef; import android.support.annotation.NonNull; import android.widget.EditText; public class MarkdownUtils { public static final int LIST_TYPE_BULLETS = 0; public static final int LIST_TYPE_NUMBERS = 1; public static final int LIST_TYPE_TASKS = 2; @IntDef({ LIST_TYPE_BULLETS, LIST_TYPE_NUMBERS, LIST_TYPE_TASKS }) public @interface ListType { } private MarkdownUtils() { } /** * Turns the current selection inside of the specified EditText into a markdown list. * * @param editText The EditText to which to add markdown list. * @param listType The type of the list. */ public static void addList(@NonNull EditText editText, @ListType int listType) { addList(editText, UiUtils.getSelectedText(editText), listType); } /** * Inserts a markdown list to the specified EditText at the currently selected position. * * @param editText The EditText to which to add markdown list. * @param text The text to turn into the list. Each new line will become a separate list * entry. * @param listType The type of the list. */ public static void addList(@NonNull EditText editText, @NonNull CharSequence text, @ListType int listType) { int tagCount = 1; String tag; if (listType == LIST_TYPE_NUMBERS) { tag = "1. "; } else if (listType == LIST_TYPE_TASKS) { tag = "- [ ] "; } else { tag = "- "; } if (text.length() == 0) { moveSelectionStartToStartOfLine(editText); text = UiUtils.getSelectedText(editText); } int selectionStart = editText.getSelectionStart(); StringBuilder stringBuilder = new StringBuilder(); String[] lines = text.toString().split("\n"); if (lines.length > 0) { for (String line : lines) { if (line.length() == 0 && stringBuilder.length() != 0) { stringBuilder.append("\n"); continue; } if (stringBuilder.length() > 0) { stringBuilder.append("\n"); } if (!line.trim().startsWith(tag)) { stringBuilder.append(tag).append(line); } else { stringBuilder.append(line); } if (listType == LIST_TYPE_NUMBERS) { tagCount += 1; tag = tagCount + ". "; } } } if (stringBuilder.length() == 0) { stringBuilder.append(tag); } int selectionEnd = editText.getSelectionEnd(); requireEmptyLineAbove(editText, stringBuilder, selectionStart); requireEmptyLineBelow(editText, stringBuilder, selectionEnd); editText.getText().replace(selectionStart, selectionEnd, stringBuilder); editText.setSelection(selectionStart + stringBuilder.length()); updateCursorPosition(editText, text.length() > 0); } /** * Turns the current selection inside of the specified EditText into a markdown header tag. * * @param editText The EditText to which to add markdown tag. * @param level The level of the header tag. */ public static void addHeader(@NonNull EditText editText, int level) { addHeader(editText, UiUtils.getSelectedText(editText), level); } /** * Inserts a markdown header tag to the specified EditText at the currently selected position. * * @param editText The EditText to which to add markdown header tag. * @param level The level of the header tag. * @param text The text of the header tag. */ public static void addHeader(@NonNull EditText editText, @NonNull CharSequence text, int level) { if (text.length() == 0) { moveSelectionStartToStartOfLine(editText); moveSelectionEndToEndOfLine(editText); text = UiUtils.getSelectedText(editText); } int selectionStart = editText.getSelectionStart(); StringBuilder result = new StringBuilder(); requireEmptyLineAbove(editText, result, selectionStart); for (int i = 0; i < level; i++) { result.append("#"); } result.append(" ").append(text); requireEmptyLineBelow(editText, result, editText.getSelectionEnd()); UiUtils.replaceSelectionText(editText, result); updateCursorPosition(editText, text.length() > 0); } /** * Turns the current selection inside of the specified EditText into a markdown bold tag. * * @param editText The EditText to which to add markdown bold tag. */ public static void addBold(@NonNull EditText editText) { addBold(editText, UiUtils.getSelectedText(editText)); } /** * Inserts a markdown bold to the specified EditText at the currently selected position. * * @param editText The EditText to which to add markdown bold tag. * @param text The text of the bold tag. */ public static void addBold(@NonNull EditText editText, @NonNull CharSequence text) { setSurroundText(editText, text, "**"); } /** * Turns the current selection inside of the specified EditText into a markdown italic tag. * * @param editText The EditText to which to add markdown italic tag. */ public static void addItalic(@NonNull EditText editText) { addItalic(editText, UiUtils.getSelectedText(editText)); } /** * Inserts a markdown italic to the specified EditText at the currently selected position. * * @param editText The EditText to which to add markdown italic tag. * @param text The text of the italic tag. */ public static void addItalic(@NonNull EditText editText, @NonNull CharSequence text) { setSurroundText(editText, text, "_"); } /** * Turns the current selection inside of the specified EditText into a markdown strike-through * tag. * * @param editText The EditText to which to add markdown strike-through tag. */ public static void addStrikeThrough(@NonNull EditText editText) { addStrikeThrough(editText, UiUtils.getSelectedText(editText)); } /** * Inserts a markdown strike-through to the specified EditText at the currently selected * position. * * @param editText The EditText to which to add markdown strike-through tag. * @param text The text of the strike-through tag. */ public static void addStrikeThrough(@NonNull EditText editText, @NonNull CharSequence text) { setSurroundText(editText, text, "~~"); } /** * Turns the current selection inside of the specified EditText into a markdown code block. * * @param editText The EditText to which to add code block. */ public static void addCode(@NonNull EditText editText) { addCode(editText, UiUtils.getSelectedText(editText)); } /** * Inserts a markdown code block to the specified EditText at the currently selected position. * * @param editText The EditText to which to add markdown code block. * @param text The text of the code block. */ public static void addCode(@NonNull EditText editText, @NonNull CharSequence text) { if (text.length() == 0) { selectWordAroundCursor(editText); text = UiUtils.getSelectedText(editText); } int selectionStart = editText.getSelectionStart(); String string = text.toString(); boolean isCodeBlock = string.contains("\n"); StringBuilder stringBuilder = new StringBuilder(); if (isCodeBlock) { requireEmptyLineAbove(editText, stringBuilder, selectionStart); stringBuilder.append("```\n").append(text).append("\n```"); requireEmptyLineBelow(editText, stringBuilder, editText.getSelectionEnd()); } else { stringBuilder.append("`").append(string.trim()).append("`"); } UiUtils.replaceSelectionText(editText, stringBuilder); if (isCodeBlock) { updateCursorPosition(editText, true); } else { editText.setSelection(editText.getSelectionEnd() - 1); } } /** * Turns the current selection inside of the specified EditText into a markdown quote block. * * @param editText The EditText to which to add quote block. */ public static void addQuote(@NonNull EditText editText) { addQuote(editText, UiUtils.getSelectedText(editText)); } /** * Inserts a markdown quote block to the specified EditText at the currently selected position. * * @param editText The EditText to which to add quote block. * @param text The text of the quote block. */ public static void addQuote(@NonNull EditText editText, @NonNull CharSequence text) { if (text.length() == 0) { moveSelectionStartToStartOfLine(editText); moveSelectionEndToEndOfLine(editText); text = UiUtils.getSelectedText(editText); } int selectionStart = editText.getSelectionStart(); StringBuilder stringBuilder = new StringBuilder(); requireEmptyLineAbove(editText, stringBuilder, selectionStart); stringBuilder.append("> "); if (text.length() > 0) { stringBuilder.append(text.toString().replace("\n", "\n> ")); } requireEmptyLineBelow(editText, stringBuilder, editText.getSelectionEnd()); UiUtils.replaceSelectionText(editText, stringBuilder); updateCursorPosition(editText, text.length() > 0); } /** * Inserts a markdown divider to the specified EditText at the currently selected position. * * @param editText The EditText to which to add divider. */ public static void addDivider(@NonNull EditText editText) { int selectionStart = editText.getSelectionStart(); StringBuilder stringBuilder = new StringBuilder(); requireEmptyLineAbove(editText, stringBuilder, selectionStart); stringBuilder.append("-------"); if (editText.getSelectionEnd() == editText.getText().length()) { stringBuilder.append("\n\n"); } else { requireEmptyLineBelow(editText, stringBuilder, editText.getSelectionEnd()); } UiUtils.replaceSelectionText(editText, stringBuilder); updateCursorPosition(editText, true); } /** * Turns the current selection inside of the specified EditText into a markdown image tag. * * @param editText The EditText to which to add image tag. */ public static void addImage(@NonNull EditText editText) { addImage(editText, UiUtils.getSelectedText(editText)); } /** * Inserts a markdown image tag to the specified EditText at the currently selected position. * * @param editText The EditText to which to add image tag. * @param text The title of the image. */ public static void addImage(@NonNull EditText editText, @NonNull CharSequence text) { if (text.length() == 0) { selectWordAroundCursor(editText); text = UiUtils.getSelectedText(editText); } int selectionStart = editText.getSelectionStart(); String result = "![" + text + "](url)"; UiUtils.replaceSelectionText(editText, result); if (text.length() == 0) { editText.setSelection(selectionStart + 2); } else { selectionStart = selectionStart + result.length() - 4; editText.setSelection(selectionStart, selectionStart + 3); } } /** * Turns the current selection inside of the specified EditText into a markdown link tag. * * @param editText The EditText to which to add link tag. */ public static void addLink(@NonNull EditText editText) { addLink(editText, UiUtils.getSelectedText(editText)); } /** * Inserts a markdown link tag to the specified EditText at the currently selected position. * * @param editText The EditText to which to add link tag. * @param text The title of the link. */ public static void addLink(@NonNull EditText editText, @NonNull CharSequence text) { if (text.length() == 0) { selectWordAroundCursor(editText); text = UiUtils.getSelectedText(editText); } int selectionStart = editText.getSelectionStart(); String result = "[" + text + "](url)"; UiUtils.replaceSelectionText(editText, result); if (text.length() == 0) { editText.setSelection(selectionStart + 1); } else { selectionStart = selectionStart + result.length() - 4; editText.setSelection(selectionStart, selectionStart + 3); } } private static void setSurroundText(@NonNull EditText editText, @NonNull CharSequence text, String surroundText) { if (text.length() == 0) { selectWordAroundCursor(editText); text = UiUtils.getSelectedText(editText); } CharSequence source = editText.getText(); int selectionStart = editText.getSelectionStart(); int selectionEnd = editText.getSelectionEnd(); text = text.toString().trim(); int charactersToGoBack = 0; if (text.length() == 0) { charactersToGoBack = surroundText.length(); } StringBuilder result = new StringBuilder(); if (selectionStart > 0 && !Character.isWhitespace(source.charAt(selectionStart - 1))) { result.append(" "); } result.append(surroundText).append(text).append(surroundText); if (selectionEnd < source.length() && !Character.isWhitespace(source.charAt(selectionEnd))) { result.append(" "); charactersToGoBack += 1; } UiUtils.replaceSelectionText(editText, result); editText.setSelection(selectionStart + result.length() - charactersToGoBack); } private static void selectWordAroundCursor(@NonNull EditText editText) { String source = editText.getText().toString(); int selectionStart = editText.getSelectionStart(); int selectionEnd = editText.getSelectionEnd(); if (selectionStart != selectionEnd) { return; } while (selectionStart > 0 && !Character.isWhitespace(source.charAt(selectionStart - 1))) { selectionStart -= 1; } while (selectionEnd < source.length() && !Character.isWhitespace(source.charAt(selectionEnd))) { selectionEnd += 1; } editText.setSelection(selectionStart, selectionEnd); } private static void requireEmptyLineAbove(@NonNull EditText editText, StringBuilder stringBuilder, int position) { CharSequence source = editText.getText(); if (position <= 0) { return; } if (source.charAt(position - 1) != '\n') { stringBuilder.insert(0, "\n\n"); } else if (position > 1 && source.charAt(position - 2) != '\n') { stringBuilder.insert(0, "\n"); } } private static void requireEmptyLineBelow(@NonNull EditText editText, StringBuilder stringBuilder, int position) { CharSequence source = editText.getText(); if (position > source.length() - 1) { return; } if (source.charAt(position) != '\n') { stringBuilder.append("\n\n"); } else if (position < source.length() - 2 && source.charAt(position + 1) != '\n') { stringBuilder.append("\n"); } } private static void moveSelectionStartToStartOfLine(@NonNull EditText editText) { int position = editText.getSelectionStart(); String substring = editText.getText().toString().substring(0, position); int selectionStart = substring.lastIndexOf('\n') + 1; editText.setSelection(selectionStart, editText.getSelectionEnd()); } private static void moveSelectionEndToEndOfLine(@NonNull EditText editText) { int position = editText.getSelectionEnd(); String source = editText.getText().toString(); String substring = source.substring(position); int selectionEnd = substring.indexOf('\n'); if (selectionEnd == -1) { selectionEnd = source.length(); } else { selectionEnd += position; } editText.setSelection(editText.getSelectionStart(), selectionEnd); } private static void updateCursorPosition(@NonNull EditText editText, boolean goToNewLine) { int selectionEnd = editText.getSelectionEnd(); String source = editText.getText().toString(); if (selectionEnd > source.length()) { return; } while (selectionEnd > 0 && source.charAt(selectionEnd - 1) == '\n') { selectionEnd -= 1; } if (goToNewLine && selectionEnd < source.length()) { selectionEnd += 1; } editText.setSelection(selectionEnd); } }
app/src/main/java/com/gh4a/utils/MarkdownUtils.java
package com.gh4a.utils; import android.support.annotation.IntDef; import android.support.annotation.NonNull; import android.widget.EditText; public class MarkdownUtils { public static final int LIST_TYPE_BULLETS = 0; public static final int LIST_TYPE_NUMBERS = 1; public static final int LIST_TYPE_TASKS = 2; @IntDef({ LIST_TYPE_BULLETS, LIST_TYPE_NUMBERS, LIST_TYPE_TASKS }) public @interface ListType { } private MarkdownUtils() { } /** * Turns the current selection inside of the specified EditText into a markdown list. * * @param editText The EditText to which to add markdown list. * @param listType The type of the list. */ public static void addList(@NonNull EditText editText, @ListType int listType) { addList(editText, UiUtils.getSelectedText(editText), listType); } /** * Inserts a markdown list to the specified EditText at the currently selected position. * * @param editText The EditText to which to add markdown list. * @param text The text to turn into the list. Each new line will become a separate list * entry. * @param listType The type of the list. */ public static void addList(@NonNull EditText editText, @NonNull CharSequence text, @ListType int listType) { int tagCount = 1; String tag; if (listType == LIST_TYPE_NUMBERS) { tag = "1. "; } else if (listType == LIST_TYPE_TASKS) { tag = "- [ ] "; } else { tag = "- "; } if (text.length() == 0) { moveSelectionStartToStartOfLine(editText); text = UiUtils.getSelectedText(editText); } int selectionStart = editText.getSelectionStart(); StringBuilder stringBuilder = new StringBuilder(); String[] lines = text.toString().split("\n"); if (lines.length > 0) { for (String line : lines) { if (line.length() == 0 && stringBuilder.length() != 0) { stringBuilder.append("\n"); continue; } if (stringBuilder.length() > 0) { stringBuilder.append("\n"); } if (!line.trim().startsWith(tag)) { stringBuilder.append(tag).append(line); } else { stringBuilder.append(line); } if (listType == LIST_TYPE_NUMBERS) { tagCount += 1; tag = tagCount + ". "; } } } if (stringBuilder.length() == 0) { stringBuilder.append(tag); } int selectionEnd = editText.getSelectionEnd(); requireEmptyLineAbove(editText, stringBuilder, selectionStart); requireEmptyLineBelow(editText, stringBuilder, selectionEnd); editText.getText().replace(selectionStart, selectionEnd, stringBuilder); editText.setSelection(selectionStart + stringBuilder.length()); } /** * Turns the current selection inside of the specified EditText into a markdown header tag. * * @param editText The EditText to which to add markdown tag. * @param level The level of the header tag. */ public static void addHeader(@NonNull EditText editText, int level) { addHeader(editText, UiUtils.getSelectedText(editText), level); } /** * Inserts a markdown header tag to the specified EditText at the currently selected position. * * @param editText The EditText to which to add markdown header tag. * @param level The level of the header tag. * @param text The text of the header tag. */ public static void addHeader(@NonNull EditText editText, @NonNull CharSequence text, int level) { if (text.length() == 0) { moveSelectionStartToStartOfLine(editText); moveSelectionEndToEndOfLine(editText); text = UiUtils.getSelectedText(editText); } int selectionStart = editText.getSelectionStart(); StringBuilder result = new StringBuilder(); requireEmptyLineAbove(editText, result, selectionStart); for (int i = 0; i < level; i++) { result.append("#"); } result.append(" ").append(text); requireEmptyLineBelow(editText, result, editText.getSelectionEnd()); UiUtils.replaceSelectionText(editText, result); editText.setSelection(selectionStart + result.length()); } /** * Turns the current selection inside of the specified EditText into a markdown bold tag. * * @param editText The EditText to which to add markdown bold tag. */ public static void addBold(@NonNull EditText editText) { addBold(editText, UiUtils.getSelectedText(editText)); } /** * Inserts a markdown bold to the specified EditText at the currently selected position. * * @param editText The EditText to which to add markdown bold tag. * @param text The text of the bold tag. */ public static void addBold(@NonNull EditText editText, @NonNull CharSequence text) { setSurroundText(editText, text, "**"); } /** * Turns the current selection inside of the specified EditText into a markdown italic tag. * * @param editText The EditText to which to add markdown italic tag. */ public static void addItalic(@NonNull EditText editText) { addItalic(editText, UiUtils.getSelectedText(editText)); } /** * Inserts a markdown italic to the specified EditText at the currently selected position. * * @param editText The EditText to which to add markdown italic tag. * @param text The text of the italic tag. */ public static void addItalic(@NonNull EditText editText, @NonNull CharSequence text) { setSurroundText(editText, text, "_"); } /** * Turns the current selection inside of the specified EditText into a markdown strike-through * tag. * * @param editText The EditText to which to add markdown strike-through tag. */ public static void addStrikeThrough(@NonNull EditText editText) { addStrikeThrough(editText, UiUtils.getSelectedText(editText)); } /** * Inserts a markdown strike-through to the specified EditText at the currently selected * position. * * @param editText The EditText to which to add markdown strike-through tag. * @param text The text of the strike-through tag. */ public static void addStrikeThrough(@NonNull EditText editText, @NonNull CharSequence text) { setSurroundText(editText, text, "~~"); } /** * Turns the current selection inside of the specified EditText into a markdown code block. * * @param editText The EditText to which to add code block. */ public static void addCode(@NonNull EditText editText) { addCode(editText, UiUtils.getSelectedText(editText)); } /** * Inserts a markdown code block to the specified EditText at the currently selected position. * * @param editText The EditText to which to add markdown code block. * @param text The text of the code block. */ public static void addCode(@NonNull EditText editText, @NonNull CharSequence text) { int selectionStart = editText.getSelectionStart(); String string = text.toString(); int charactersToGoBack = 1; StringBuilder stringBuilder = new StringBuilder(); if (string.contains("\n")) { requireEmptyLineAbove(editText, stringBuilder, selectionStart); stringBuilder.append("```\n").append(text).append("\n```"); requireEmptyLineBelow(editText, stringBuilder, editText.getSelectionEnd()); charactersToGoBack += 4; } else { stringBuilder.append("`").append(string.trim()).append("`"); } UiUtils.replaceSelectionText(editText, stringBuilder); editText.setSelection(selectionStart + stringBuilder.length() - charactersToGoBack); } /** * Turns the current selection inside of the specified EditText into a markdown quote block. * * @param editText The EditText to which to add quote block. */ public static void addQuote(@NonNull EditText editText) { addQuote(editText, UiUtils.getSelectedText(editText)); } /** * Inserts a markdown quote block to the specified EditText at the currently selected position. * * @param editText The EditText to which to add quote block. * @param text The text of the quote block. */ public static void addQuote(@NonNull EditText editText, @NonNull CharSequence text) { if (text.length() == 0) { moveSelectionStartToStartOfLine(editText); moveSelectionEndToEndOfLine(editText); text = UiUtils.getSelectedText(editText); } int selectionStart = editText.getSelectionStart(); StringBuilder stringBuilder = new StringBuilder(); requireEmptyLineAbove(editText, stringBuilder, selectionStart); stringBuilder.append("> "); if (text.length() > 0) { stringBuilder.append(text.toString().replace("\n", "\n> ")); } requireEmptyLineBelow(editText, stringBuilder, editText.getSelectionEnd()); UiUtils.replaceSelectionText(editText, stringBuilder); editText.setSelection(selectionStart + stringBuilder.length()); } /** * Inserts a markdown divider to the specified EditText at the currently selected position. * * @param editText The EditText to which to add divider. */ public static void addDivider(@NonNull EditText editText) { int selectionStart = editText.getSelectionStart(); StringBuilder stringBuilder = new StringBuilder(); requireEmptyLineAbove(editText, stringBuilder, selectionStart); stringBuilder.append("-------"); if (editText.getSelectionEnd() == editText.getText().length()) { stringBuilder.append("\n\n"); } else { requireEmptyLineBelow(editText, stringBuilder, editText.getSelectionEnd()); } UiUtils.replaceSelectionText(editText, stringBuilder); editText.setSelection(selectionStart + stringBuilder.length()); } /** * Turns the current selection inside of the specified EditText into a markdown image tag. * * @param editText The EditText to which to add image tag. */ public static void addImage(@NonNull EditText editText) { addImage(editText, UiUtils.getSelectedText(editText)); } /** * Inserts a markdown image tag to the specified EditText at the currently selected position. * * @param editText The EditText to which to add image tag. * @param text The title of the image. */ public static void addImage(@NonNull EditText editText, @NonNull CharSequence text) { if (text.length() == 0) { selectWordAroundCursor(editText); text = UiUtils.getSelectedText(editText); } int selectionStart = editText.getSelectionStart(); String result = "![" + text + "](url)"; UiUtils.replaceSelectionText(editText, result); if (text.length() == 0) { editText.setSelection(selectionStart + 2); } else { selectionStart = selectionStart + result.length() - 4; editText.setSelection(selectionStart, selectionStart + 3); } } /** * Turns the current selection inside of the specified EditText into a markdown link tag. * * @param editText The EditText to which to add link tag. */ public static void addLink(@NonNull EditText editText) { addLink(editText, UiUtils.getSelectedText(editText)); } /** * Inserts a markdown link tag to the specified EditText at the currently selected position. * * @param editText The EditText to which to add link tag. * @param text The title of the link. */ public static void addLink(@NonNull EditText editText, @NonNull CharSequence text) { if (text.length() == 0) { selectWordAroundCursor(editText); text = UiUtils.getSelectedText(editText); } int selectionStart = editText.getSelectionStart(); String result = "[" + text + "](url)"; UiUtils.replaceSelectionText(editText, result); if (text.length() == 0) { editText.setSelection(selectionStart + 1); } else { selectionStart = selectionStart + result.length() - 4; editText.setSelection(selectionStart, selectionStart + 3); } } private static void setSurroundText(@NonNull EditText editText, @NonNull CharSequence text, String surroundText) { if (text.length() == 0) { selectWordAroundCursor(editText); text = UiUtils.getSelectedText(editText); } CharSequence source = editText.getText(); int selectionStart = editText.getSelectionStart(); int selectionEnd = editText.getSelectionEnd(); text = text.toString().trim(); int charactersToGoBack = 0; if (text.length() == 0) { charactersToGoBack = surroundText.length(); } StringBuilder result = new StringBuilder(); if (selectionStart > 0 && !Character.isWhitespace(source.charAt(selectionStart - 1))) { result.append(" "); } result.append(surroundText).append(text).append(surroundText); if (selectionEnd < source.length() && !Character.isWhitespace(source.charAt(selectionEnd))) { result.append(" "); charactersToGoBack += 1; } UiUtils.replaceSelectionText(editText, result); editText.setSelection(selectionStart + result.length() - charactersToGoBack); } private static void selectWordAroundCursor(@NonNull EditText editText) { String source = editText.getText().toString(); int selectionStart = editText.getSelectionStart(); int selectionEnd = editText.getSelectionEnd(); if (selectionStart != selectionEnd) { return; } while (selectionStart > 0 && !Character.isWhitespace(source.charAt(selectionStart - 1))) { selectionStart -= 1; } while (selectionEnd < source.length() && !Character.isWhitespace(source.charAt(selectionEnd))) { selectionEnd += 1; } editText.setSelection(selectionStart, selectionEnd); } private static void requireEmptyLineAbove(@NonNull EditText editText, StringBuilder stringBuilder, int position) { CharSequence source = editText.getText(); if (position <= 0) { return; } if (source.charAt(position - 1) != '\n') { stringBuilder.insert(0, "\n\n"); } else if (position > 1 && source.charAt(position - 2) != '\n') { stringBuilder.insert(0, "\n"); } } private static void requireEmptyLineBelow(@NonNull EditText editText, StringBuilder stringBuilder, int position) { CharSequence source = editText.getText(); if (position > source.length() - 1) { return; } if (source.charAt(position) != '\n') { stringBuilder.append("\n\n"); } else if (position < source.length() - 2 && source.charAt(position + 1) != '\n') { stringBuilder.append("\n"); } } private static void moveSelectionStartToStartOfLine(@NonNull EditText editText) { int position = editText.getSelectionStart(); String substring = editText.getText().toString().substring(0, position); int selectionStart = substring.lastIndexOf('\n') + 1; editText.setSelection(selectionStart, editText.getSelectionEnd()); } private static void moveSelectionEndToEndOfLine(@NonNull EditText editText) { int position = editText.getSelectionEnd(); String source = editText.getText().toString(); String substring = source.substring(position); int selectionEnd = substring.indexOf('\n'); if (selectionEnd == -1) { selectionEnd = source.length(); } else { selectionEnd += position; } editText.setSelection(editText.getSelectionStart(), selectionEnd); } }
Add smart cursor positioning
app/src/main/java/com/gh4a/utils/MarkdownUtils.java
Add smart cursor positioning
<ide><path>pp/src/main/java/com/gh4a/utils/MarkdownUtils.java <ide> <ide> editText.getText().replace(selectionStart, selectionEnd, stringBuilder); <ide> editText.setSelection(selectionStart + stringBuilder.length()); <add> updateCursorPosition(editText, text.length() > 0); <ide> } <ide> <ide> /** <ide> moveSelectionEndToEndOfLine(editText); <ide> text = UiUtils.getSelectedText(editText); <ide> } <del> <add> <ide> int selectionStart = editText.getSelectionStart(); <ide> <ide> StringBuilder result = new StringBuilder(); <ide> requireEmptyLineBelow(editText, result, editText.getSelectionEnd()); <ide> <ide> UiUtils.replaceSelectionText(editText, result); <del> editText.setSelection(selectionStart + result.length()); <add> updateCursorPosition(editText, text.length() > 0); <ide> } <ide> <ide> /** <ide> * @param text The text of the code block. <ide> */ <ide> public static void addCode(@NonNull EditText editText, @NonNull CharSequence text) { <add> if (text.length() == 0) { <add> selectWordAroundCursor(editText); <add> text = UiUtils.getSelectedText(editText); <add> } <ide> int selectionStart = editText.getSelectionStart(); <ide> String string = text.toString(); <del> int charactersToGoBack = 1; <add> boolean isCodeBlock = string.contains("\n"); <ide> <ide> StringBuilder stringBuilder = new StringBuilder(); <del> if (string.contains("\n")) { <add> if (isCodeBlock) { <ide> requireEmptyLineAbove(editText, stringBuilder, selectionStart); <ide> stringBuilder.append("```\n").append(text).append("\n```"); <ide> requireEmptyLineBelow(editText, stringBuilder, editText.getSelectionEnd()); <del> <del> charactersToGoBack += 4; <ide> } else { <ide> stringBuilder.append("`").append(string.trim()).append("`"); <ide> } <ide> <del> <ide> UiUtils.replaceSelectionText(editText, stringBuilder); <del> editText.setSelection(selectionStart + stringBuilder.length() - charactersToGoBack); <add> if (isCodeBlock) { <add> updateCursorPosition(editText, true); <add> } else { <add> editText.setSelection(editText.getSelectionEnd() - 1); <add> } <ide> } <ide> <ide> /** <ide> requireEmptyLineBelow(editText, stringBuilder, editText.getSelectionEnd()); <ide> <ide> UiUtils.replaceSelectionText(editText, stringBuilder); <del> editText.setSelection(selectionStart + stringBuilder.length()); <add> updateCursorPosition(editText, text.length() > 0); <ide> } <ide> <ide> /** <ide> } <ide> <ide> UiUtils.replaceSelectionText(editText, stringBuilder); <del> editText.setSelection(selectionStart + stringBuilder.length()); <add> updateCursorPosition(editText, true); <ide> } <ide> <ide> /** <ide> } <ide> <ide> UiUtils.replaceSelectionText(editText, result); <del> <ide> editText.setSelection(selectionStart + result.length() - charactersToGoBack); <ide> } <ide> <ide> } <ide> editText.setSelection(editText.getSelectionStart(), selectionEnd); <ide> } <add> <add> private static void updateCursorPosition(@NonNull EditText editText, boolean goToNewLine) { <add> int selectionEnd = editText.getSelectionEnd(); <add> String source = editText.getText().toString(); <add> if (selectionEnd > source.length()) { <add> return; <add> } <add> <add> while (selectionEnd > 0 && source.charAt(selectionEnd - 1) == '\n') { <add> selectionEnd -= 1; <add> } <add> if (goToNewLine && selectionEnd < source.length()) { <add> selectionEnd += 1; <add> } <add> editText.setSelection(selectionEnd); <add> } <ide> }
Java
apache-2.0
788938fa2a4a500a971033cc75848fc1a1bae882
0
allotria/intellij-community,allotria/intellij-community,allotria/intellij-community,allotria/intellij-community,allotria/intellij-community,allotria/intellij-community,allotria/intellij-community,allotria/intellij-community,allotria/intellij-community,allotria/intellij-community,allotria/intellij-community,allotria/intellij-community,allotria/intellij-community
// Copyright 2000-2019 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package com.intellij.util.containers; import com.intellij.openapi.util.Comparing; import com.intellij.openapi.util.Condition; import com.intellij.openapi.util.Conditions; import com.intellij.openapi.util.TextRange; import com.intellij.openapi.util.text.StringUtil; import com.intellij.util.Function; import com.intellij.util.Functions; import com.intellij.util.PairFunction; import com.intellij.util.Processor; import junit.framework.TestCase; import org.jetbrains.annotations.NotNull; import java.lang.reflect.Modifier; import java.util.*; import java.util.concurrent.atomic.AtomicInteger; import static com.intellij.openapi.util.Conditions.not; import static com.intellij.util.containers.JBIterable.Split.*; /** * @author gregsh * * @noinspection ArraysAsListWithZeroOrOneArgument */ public class TreeTraverserTest extends TestCase { /** * <pre> * --- 5 * --- 2 --- 6 * / --- 7 * / * / --- 8 * 1 --- 3 --- 9 * \ --- 10 * \ * \ --- 11 * --- 4 --- 12 * --- 13 * </pre> */ private static Map<Integer, Collection<Integer>> numbers() { return ContainerUtil.<Integer, Collection<Integer>>immutableMapBuilder(). put(1, Arrays.asList(2, 3, 4)). put(2, Arrays.asList(5, 6, 7)). put(3, Arrays.asList(8, 9, 10)). put(4, Arrays.asList(11, 12, 13)). build(); } private static Map<Integer, Collection<Integer>> numbers2() { return ContainerUtil.<Integer, Collection<Integer>>immutableMapBuilder(). put(1, Arrays.asList(2, 3, 4)). put(2, Arrays.asList(5, 6, 7)). put(3, Arrays.asList(8, 9, 10)). put(4, Arrays.asList(11, 12, 13)). put(5, Arrays.asList(14, 15, 16)). put(6, Arrays.asList(17, 18, 19)). put(7, Arrays.asList(20, 21, 22)). put(8, Arrays.asList(23, 24, 25)). put(9, Arrays.asList(26, 27, 28)). put(10, Arrays.asList(29, 30, 31)). put(11, Arrays.asList(32, 33, 34)). put(12, Arrays.asList(35, 36, 37)). build(); } private static final Function<Integer, Integer> ASSERT_NUMBER = o -> { if (o instanceof Number) return o; throw new AssertionError(String.valueOf(o)); }; private static final Condition<Integer> IS_ODD = integer -> integer.intValue() % 2 == 1; private static final Condition<Integer> IS_POSITIVE = integer -> integer.intValue() > 0; private static Condition<Integer> inRange(int s, int e) { return integer -> s <= integer && integer <= e; } public static final Function<Integer, List<Integer>> WRAP_TO_LIST = integer -> ContainerUtil.newArrayList(integer); public static final Function<Integer, Integer> DIV_2 = k -> k / 2; private static final Function<Integer, Integer> INCREMENT = k -> k + 1; private static final Function<Integer, Integer> SQUARE = k -> k * k; private static final PairFunction<Integer, Integer, Integer> FIBONACCI = (k1, k2) -> k2 + k1; private static final Function<Integer, Integer> FIBONACCI2 = new JBIterable.SFun<Integer, Integer>() { int k0; @Override public Integer fun(Integer k) { int t = k0; k0 = k; return t + k; } }; @NotNull private static Condition<Integer> LESS_THAN(final int max) { return integer -> integer < max; } @NotNull private static Condition<Integer> LESS_THAN_MOD(final int max) { return integer -> integer % max < max / 2; } @NotNull private static <E> JBIterable.SCond<E> UP_TO(final E o) { return new JBIterable.SCond<E>() { boolean b; @Override public boolean value(E e) { if (b) return false; b = Comparing.equal(e, o); return true; } }; } // JBIterator ---------------------------------------------- public void testIteratorContracts() { Processor<Runnable> tryCatch = (r) -> { try { r.run(); return true; } catch (NoSuchElementException e) { return false; } }; JBIterator<Integer> it = JBIterator.from(Arrays.asList(1, 2, 3, 4).iterator()); assertFalse(tryCatch.process(it::current)); assertTrue(it.hasNext()); assertFalse(tryCatch.process(it::current)); assertTrue(it.advance()); // advance->1 assertEquals(new Integer(1), it.current()); assertTrue(it.hasNext()); assertTrue(it.hasNext()); assertEquals(new Integer(2), it.next()); // advance->2 assertEquals(new Integer(2), it.current()); assertEquals(new Integer(2), it.current()); assertTrue(it.advance()); // advance->3 assertEquals(new Integer(4), it.next()); // advance->4 assertFalse(it.hasNext()); assertFalse(it.hasNext()); assertFalse(it.advance()); assertFalse(tryCatch.process(it::current)); assertFalse(tryCatch.process(it::next)); assertFalse(it.hasNext()); } public void testIteratorContractsCurrent() { JBIterator<Integer> it = JBIterator.from(JBIterable.of(1).iterator()); assertTrue(it.advance()); assertEquals(new Integer(1), it.current()); assertFalse(it.hasNext()); assertEquals(new Integer(1), it.current()); } public void testCursorIterableContract() { List<Integer> list = new ArrayList<>(); JBIterable<Integer> orig = JBIterable.generate(1, INCREMENT).take(5); for (JBIterator<Integer> it : JBIterator.cursor(JBIterator.from(orig.iterator()))) { it.current(); it.hasNext(); list.add(it.current()); } assertEquals(orig.toList(), list); } public void testCursorIteratorContract() { JBIterable<Integer> orig = JBIterable.generate(1, INCREMENT).take(5); JBIterator<JBIterator<Integer>> it = JBIterator.from(JBIterator.cursor( JBIterator.from(orig.iterator())).iterator()); List<Integer> list = new ArrayList<>(); while (it.advance()) { it.hasNext(); list.add(it.current().current()); } assertEquals(orig.toList(), list); } public void testCursorTransform() { JBIterable<Integer> orig = JBIterable.generate(1, INCREMENT).take(5); List<Integer> expected = ContainerUtil.newArrayList(1, 2, 3, 4, 5); List<Integer> expectedOdd = ContainerUtil.newArrayList(1, 3, 5); assertEquals(expected, JBIterator.cursor(JBIterator.from(orig.iterator())).transform(o -> o.current()).toList()); assertEquals(expected.size(), JBIterator.cursor(JBIterator.from(orig.iterator())).last().current().intValue()); assertEquals(expectedOdd, JBIterator.cursor(JBIterator.from(orig.iterator())).transform(o -> o.current()).filter(IS_ODD).toList()); assertEquals(expectedOdd, JBIterator.cursor(JBIterator.from(orig.iterator())).filter(o -> IS_ODD.value(o.current())).transform(o -> o.current()).toList()); assertEquals(expected.subList(0, 4), JBIterator.cursor(JBIterator.from(orig.iterator())).filter(o -> o.hasNext()).transform(o -> o.current()).toList()); } public void testIteratorContractsSkipAndStop() { final AtomicInteger count = new AtomicInteger(0); JBIterator<Integer> it = new JBIterator<Integer>() { @Override protected Integer nextImpl() { return count.get() < 0 ? stop() : count.incrementAndGet() < 10 ? skip() : (Integer)count.addAndGet(-count.get() - 1); } }; assertEquals(JBIterable.of(-1).toList(), JBIterable.once(it).toList()); } // JBIterable ---------------------------------------------- public void testIterableOfNulls() { Object nil = null; assertEquals("[]", JBIterable.of(nil).toList().toString()); assertEquals("[null, null, null]", JBIterable.of(nil, nil, nil).toList().toString()); assertEquals("[null, null, null]", JBIterable.of(ContainerUtil.ar(nil, nil, nil)).toList().toString()); assertEquals("[null, null, null]", JBIterable.from(Arrays.asList(nil, nil, nil)).toList().toString()); assertEquals("[]", JBIterable.generate(null, x -> null).toList().toString()); assertEquals("[42]", JBIterable.generate(42, x -> null).toList().toString()); } public void testSingleElement() { JBIterable<String> it = JBIterable.of("42"); assertEquals(1, it.size()); assertEquals("42", it.first()); assertEquals("42", it.last()); assertEquals("42", it.single()); assertEquals("[42, 42]", it.append(it).toList().toString()); assertEquals("[42, 42]", it.repeat(2).toList().toString()); assertEquals("[42, 42, 48, 48]", it.append("42").append(Arrays.asList("48", "48")).toList().toString()); assertEquals("[42, 42, 48, 48, 49]", it.append("42").append(Arrays.asList("48", "48")).append("49").toList().toString()); assertEquals("[42, 42, 48, 48, 49]", it.append("42").append(JBIterable.of("48").append("48")).append("49").toList().toString()); } public void testFirstLastSingle() { assertNull(JBIterable.empty().first()); assertNull(JBIterable.empty().last()); assertNull(JBIterable.empty().single()); assertEquals("a", JBIterable.generate("a", o -> o + "a").first()); assertEquals("aaa", JBIterable.generate("a", o -> o + "a").take(3).last()); assertEquals("a", JBIterable.generate("a", o -> o + "a").take(1).single()); assertNull(JBIterable.generate("a", o -> o + "a").take(2).single()); assertEquals("a", JBIterable.from(Arrays.asList("a", "aa", "aaa")).first()); assertEquals("aaa", JBIterable.from(Arrays.asList("a", "aa", "aaa")).last()); assertEquals("a", JBIterable.of("a").single()); assertNull(JBIterable.of("a", "aa", "aaa").single()); } public void testOfAppendNulls() { Integer o = null; JBIterable<Integer> it = JBIterable.of(o).append(o).append(JBIterable.empty()); assertTrue(it.isEmpty()); assertSame(it, JBIterable.empty()); } public void testAppend() { JBIterable<Integer> it = JBIterable.of(1, 2, 3).append(JBIterable.of(4, 5, 6)).append(JBIterable.empty()).append(7); assertEquals(7, it.size()); assertEquals(Arrays.asList(1, 2, 3, 4, 5, 6, 7), it.toList()); assertTrue(it.contains(5)); } public void testGenerateRepeat() { JBIterable<Integer> it = JBIterable.generate(1, INCREMENT).take(3).repeat(3); assertEquals(9, it.size()); assertEquals(Arrays.asList(1, 2, 3, 1, 2, 3, 1, 2, 3), it.toList()); } public void testSkipTakeSize() { JBIterable<Integer> it = JBIterable.generate(1, INCREMENT).skip(10).take(10); assertEquals(10, it.size()); assertEquals(new Integer(11), it.first()); } public void testFlattenSkipTake() { assertEquals(1, JBIterable.of(1).flatMap(o -> JBIterable.of(o)).take(1).take(1).take(1).size()); assertEquals((Integer)1, JBIterable.of(1).flatMap(o -> JBIterable.of(o, o + 1)).take(2).take(1).get(0)); assertEquals((Integer)2, JBIterable.of(1).flatMap(o -> JBIterable.of(o, o + 1)).skip(1).take(1).get(0)); } public void testRangeWithSkipAndTake() { Condition<Integer> cond = i -> Math.abs(i - 10) <= 5; JBIterable<Integer> it = JBIterable.generate(1, INCREMENT).skipWhile(not(cond)).takeWhile(cond); assertEquals(11, it.size()); assertEquals(new Integer(5), it.first()); assertEquals(new Integer(15), it.last()); } public void testSkipWhile() { JBIterable<Integer> it = JBIterable.generate(1, INCREMENT).skipWhile(LESS_THAN_MOD(10)).take(10); assertEquals(Arrays.asList(5, 6, 7, 8, 9, 10, 11, 12, 13, 14), it.toList()); } public void testTakeWhile() { JBIterable<Integer> it = JBIterable.generate(1, INCREMENT).takeWhile(LESS_THAN_MOD(10)).take(10); assertEquals(Arrays.asList(1, 2, 3, 4), it.toList()); } public void testGetAt() { JBIterable<Integer> it = JBIterable.of(1, 2, 3, 4); assertEquals((Integer)4, it.get(3)); assertNull(it.get(4)); assertNull(it.get(5)); JBIterable<Integer> it2 = JBIterable.generate(1, INCREMENT).take(4); assertEquals((Integer)4, it2.get(3)); assertNull(it2.get(4)); assertNull(it2.get(5)); } public void testFilterTransformTakeWhile() { JBIterable<Integer> it = JBIterable.generate(1, INCREMENT).filter(IS_ODD).transform(SQUARE).takeWhile(LESS_THAN(100)); assertEquals(Arrays.asList(1, 9, 25, 49, 81), it.toList()); assertEquals(new Integer(1), it.first()); assertEquals(new Integer(81), it.last()); } public void testFilterTransformSkipWhile() { JBIterable<Integer> it = JBIterable.generate(1, INCREMENT).filter(IS_ODD).transform(SQUARE).skipWhile(LESS_THAN(100)).take(3); assertEquals(Arrays.asList(121, 169, 225), it.toList()); assertEquals(new Integer(121), it.first()); assertEquals(new Integer(225), it.last()); } public void testOnce() { JBIterable<Integer> it = JBIterable.once(JBIterable.generate(1, INCREMENT).take(3).iterator()); assertEquals(Arrays.asList(1, 2, 3), it.toList()); try { assertEquals(Arrays.asList(1, 2, 3), it.toList()); fail(); } catch (UnsupportedOperationException ignored) { } } public void testFlatten() { JBIterable<Integer> it = JBIterable.generate(1, INCREMENT).take(3).flatten(i -> i % 2 == 0 ? null : JBIterable.of(i - 1, i)); assertEquals(Arrays.asList(0, 1, 2, 3), it.toList()); } public void testStatefulFilter() { JBIterable<Integer> it = JBIterable.generate(1, INCREMENT).take(5).filter(new JBIterable.SCond<Integer>() { int prev; @Override public boolean value(Integer integer) { boolean b = integer > prev; if (b) prev = integer; return b; } }); assertEquals(Arrays.asList(1, 2, 3, 4, 5), it.toList()); assertEquals(Arrays.asList(1, 2, 3, 4, 5), it.toList()); } public void testStatefulGenerator() { JBIterable<Integer> it = JBIterable.generate(1, FIBONACCI2).take(8); assertEquals(Arrays.asList(1, 1, 2, 3, 5, 8, 13, 21), it.toList()); assertEquals(Arrays.asList(1, 1, 2, 3, 5, 8, 13, 21), it.toList()); } public void testFindIndexReduceMap() { JBIterable<Integer> it = JBIterable.of(1, 2, 3, 4, 5); assertEquals(15, (int)it.reduce(0, (Integer v, Integer o) -> v + o)); assertEquals(3, (int)it.find((o)-> o.intValue() == 3)); assertEquals(2, it.indexOf((o)-> o.intValue() == 3)); assertEquals(-1, it.indexOf((o)-> o.intValue() == 33)); assertEquals(Arrays.asList(1, 4, 9, 16, 25), it.map(o -> o * o).toList()); assertEquals(Arrays.asList(0, 1, 0, 2, 0, 3, 0, 4, 0, 5), it.flatMap(o -> Arrays.asList(0, o)).toList()); } public void testJoin() { assertNull(JBIterable.<String>of().join(", ").reduce((a, b) -> a + b)); assertEquals("", JBIterable.of().join(", ").reduce("", (a, b) -> a + b)); assertEquals("a", JBIterable.of("a").join(", ").reduce((a, b) -> a + b)); assertEquals("a, b, c", JBIterable.of("a", "b", "c").join(", ").reduce((a, b) -> a + b)); } public void testSplits1() { JBIterable<Integer> it = JBIterable.of(1, 2, 3, 4, 5); assertEquals(Arrays.asList(Arrays.asList(1, 2), Arrays.asList(3, 4)), it.split(2, true).toList()); assertEquals(Arrays.asList(Arrays.asList(1, 2), Arrays.asList(3, 4), Arrays.asList(5)), it.split(2, false).toList()); assertEquals("[[1, 2], [4, 5]]", it.split(OFF, o -> o % 3 == 0).map(o -> o.toList()).toList().toString()); assertEquals("[[1, 2], [3], [4, 5]]", it.split(AROUND, o -> o % 3 == 0).map(o -> o.toList()).toList().toString()); assertEquals("[[1, 2, 3], [4, 5]]", it.split(AFTER, o -> o % 3 == 0).map(o -> o.toList()).toList().toString()); assertEquals("[[1, 2], [3, 4, 5]]", it.split(BEFORE, o -> o % 3 == 0).map(o -> o.toList()).toList().toString()); assertEquals("[[1, 2, 3, 4], [5], []]", it.split(AROUND, o -> o == 5).map(o -> o.toList()).toList().toString()); assertEquals("[[], [1], [2, 3, 4, 5]]", it.split(AROUND, o -> o == 1).map(o -> o.toList()).toList().toString()); assertEquals("[[], [], [], [], [], []]", it.split(OFF, o -> true).map(o -> o.toList()).toList().toString()); assertEquals("[[1], [2], [3], [4], [5], []]", it.split(AFTER, o -> true).map(o -> o.toList()).toList().toString()); assertEquals("[[], [1], [2], [3], [4], [5]]", it.split(BEFORE, o -> true).map(o -> o.toList()).toList().toString()); assertEquals("[[], [1], [], [2], [], [3], [], [4], [], [5], []]", it.split(AROUND, o -> true).map(o -> o.toList()).toList().toString()); assertEquals("[[1, 2, 3, 4, 5]]", it.split(GROUP, o -> true).map(o -> o.toList()).toList().toString()); assertEquals("[[1, 2, 3, 4, 5]]", it.split(OFF, o -> false).map(o -> o.toList()).toList().toString()); assertEquals("[[1, 2, 3, 4, 5]]", it.split(AFTER, o -> false).map(o -> o.toList()).toList().toString()); assertEquals("[[1, 2, 3, 4, 5]]", it.split(BEFORE, o -> false).map(o -> o.toList()).toList().toString()); assertEquals("[[1, 2, 3, 4, 5]]", it.split(AROUND, o -> false).map(o -> o.toList()).toList().toString()); assertEquals("[[1, 2, 3, 4, 5]]", it.split(GROUP, o -> false).map(o -> o.toList()).toList().toString()); assertEquals(3, it.split(AROUND, o -> o % 3 == 0).size()); assertEquals(11, it.split(AROUND, o -> true).size()); assertEquals(it.split(2, false).toList(), it.split(AFTER, o -> o % 2 == 0).map(o -> o.toList()).toList()); JBIterable<JBIterable<Integer>> statePart = it.split(GROUP, new JBIterable.SCond<Integer>() { int i = 4; @Override public boolean value(Integer integer) { return (i = (i + 2) % 12) - 5 > 0; // 3 positive, 3 negative (+1 +3 +5 : -5 -3 -1) } }); assertEquals("[[1, 2, 3], [4, 5]]", statePart.map(o -> o.toList()).toList().toString()); assertEquals("[[1, 2, 3], [4, 5]]", statePart.map(o -> o.toList()).toList().toString()); } public void testSplits2() { JBIterable<Integer> it = JBIterable.empty(); assertEquals("[]", it.split(OFF, o -> o % 3 == 0).map(o -> o.toList()).toList().toString()); assertEquals("[]", it.split(AROUND, o -> o % 3 == 0).map(o -> o.toList()).toList().toString()); assertEquals("[]", it.split(AFTER, o -> o % 3 == 0).map(o -> o.toList()).toList().toString()); assertEquals("[]", it.split(BEFORE, o -> o % 3 == 0).map(o -> o.toList()).toList().toString()); assertEquals("[]", it.split(GROUP, o -> o % 3 == 0).map(o -> o.toList()).toList().toString()); it = JBIterable.of(3); assertEquals("[[], []]", it.split(OFF, o -> o % 3 == 0).map(o -> o.toList()).toList().toString()); assertEquals("[[], [3], []]", it.split(AROUND, o -> o % 3 == 0).map(o -> o.toList()).toList().toString()); assertEquals("[[3], []]", it.split(AFTER, o -> o % 3 == 0).map(o -> o.toList()).toList().toString()); assertEquals("[[], [3]]", it.split(BEFORE, o -> o % 3 == 0).map(o -> o.toList()).toList().toString()); assertEquals("[[3]]", it.split(GROUP, o -> o % 3 == 0).map(o -> o.toList()).toList().toString()); it = JBIterable.of(1, 2, 3, 3, 4, 5); assertEquals("[[1, 2], [], [4, 5]]", it.split(OFF, o -> o % 3 == 0).map(o -> o.toList()).toList().toString()); assertEquals("[[1, 2], [3], [], [3], [4, 5]]", it.split(AROUND, o -> o % 3 == 0).map(o -> o.toList()).toList().toString()); assertEquals("[[1, 2, 3], [3], [4, 5]]", it.split(AFTER, o -> o % 3 == 0).map(o -> o.toList()).toList().toString()); assertEquals("[[1, 2], [3], [3, 4, 5]]", it.split(BEFORE, o -> o % 3 == 0).map(o -> o.toList()).toList().toString()); assertEquals("[[1, 2], [3, 3], [4, 5]]", it.split(GROUP, o -> o % 3 == 0).map(o -> o.toList()).toList().toString()); it = JBIterable.of(3, 3, 1, 2, 3, 3); assertEquals("[[], [], [1, 2], [], []]", it.split(OFF, o -> o % 3 == 0).map(o -> o.toList()).toList().toString()); assertEquals("[[], [3], [], [3], [1, 2], [3], [], [3], []]", it.split(AROUND, o -> o % 3 == 0).map(o -> o.toList()).toList().toString()); assertEquals("[[3], [3], [1, 2, 3], [3], []]", it.split(AFTER, o -> o % 3 == 0).map(o -> o.toList()).toList().toString()); assertEquals("[[], [3], [3, 1, 2], [3], [3]]", it.split(BEFORE, o -> o % 3 == 0).map(o -> o.toList()).toList().toString()); assertEquals("[[3, 3], [1, 2], [3, 3]]", it.split(GROUP, o -> o % 3 == 0).map(o -> o.toList()).toList().toString()); Function<JBIterable<Integer>, JBIterable<JBIterator<Integer>>> cursor = param -> JBIterator.cursor(JBIterator.from(param.iterator())); assertEquals("[[], [], [1, 2], [], []]", cursor.fun(it).split(OFF, o -> o.current() % 3 == 0).map(o -> o.map(p -> p.current()).toList()).toList().toString()); assertEquals("[[], [3], [], [3], [1, 2], [3], [], [3], []]", cursor.fun(it).split(AROUND, o -> o.current() % 3 == 0).map(o -> o.map(p -> p.current()).toList()).toList().toString()); assertEquals("[[3], [3], [1, 2, 3], [3], []]", cursor.fun(it).split(AFTER, o -> o.current() % 3 == 0).map(o -> o.map(p -> p.current()).toList()).toList().toString()); assertEquals("[[], [3], [3, 1, 2], [3], [3]]", cursor.fun(it).split(BEFORE, o -> o.current() % 3 == 0).map(o -> o.map(p -> p.current()).toList()).toList().toString()); assertEquals("[[3, 3], [1, 2], [3, 3]]", cursor.fun(it).split(GROUP, o -> o.current() % 3 == 0).map(o -> o.map(p -> p.current()).toList()).toList().toString()); assertEquals("[[3, 3], [1, 2], [3, 3]]", it.split(2, true).toList().toString()); assertEquals("[[3, 3], [1, 2], [3, 3]]", it.split(2).map(o -> o.toList()).toList().toString()); assertEquals("[[3, 3], [1, 2], [3, 3]]", cursor.fun(it).split(2).map(o -> o.map(p -> p.current()).toList()).toList().toString()); assertEquals("[[3, 3, 1, 2], [3, 3]]", cursor.fun(it).split(4).map(o -> o.map(p -> p.current()).toList()).toList().toString()); } public void testIterateUnique() { JBIterable<Integer> it = JBIterable.generate(1, INCREMENT).take(30); assertEquals(it.toList(), it.unique().toList()); JBIterable<Integer> uniqueMod5 = it.unique((o) -> o % 5); assertEquals(Arrays.asList(1, 2, 3, 4, 5), uniqueMod5.toList()); assertEquals(Arrays.asList(1, 2, 3, 4, 5), uniqueMod5.toList()); // same results again } public void testSort() { JBIterable<Integer> it1 = JBIterable.generate(1, INCREMENT).take(30); JBIterable<Integer> it2 = JBIterable.generate(30, o -> o - 1).take(30).sort(Integer::compareTo); assertEquals(it1.toList(), it2.unique().toList()); } // TreeTraversal ---------------------------------------------- @NotNull private static JBTreeTraverser<Integer> numTraverser() { return new JBTreeTraverser<>(Functions.compose(ASSERT_NUMBER, Functions.fromMap(numbers()))).withRoot(1); } @NotNull private static JBTreeTraverser<Integer> num2Traverser() { return new JBTreeTraverser<>(Functions.compose(ASSERT_NUMBER, Functions.fromMap(numbers2()))).withRoot(1); } @NotNull private static JBIterable<TreeTraversal> allTraversals() { JBIterable<TreeTraversal> result = JBIterable.of(TreeTraversal.class.getDeclaredFields()) .filter(o -> Modifier.isStatic(o.getModifiers()) && Modifier.isPublic(o.getModifiers())) .map(o -> { try { return o.get(null); } catch (IllegalAccessException e) { throw new AssertionError(e); } }) .filter(TreeTraversal.class) .sort(Comparator.comparing(Object::toString)) .collect(); assertEquals("[BI_ORDER_DFS, INTERLEAVED_DFS, LEAVES_BFS, LEAVES_DFS," + " PLAIN_BFS, POST_ORDER_DFS, PRE_ORDER_DFS, TRACING_BFS]", result.toList().toString()); return result; } public void testTraverserOfNulls() { JBIterable<TreeTraversal> traversals = allTraversals(); Object nil = null; JBTreeTraverser<Object> t1 = JBTreeTraverser.from(o -> JBIterable.of(nil, nil)).withRoots(Arrays.asList(nil)); assertEquals("BI_ORDER_DFS [null, null]\n" + "INTERLEAVED_DFS [null]\n" + "LEAVES_BFS [null]\n" + "LEAVES_DFS [null]\n" + "PLAIN_BFS [null]\n" + "POST_ORDER_DFS [null]\n" + "PRE_ORDER_DFS [null]\n" + "TRACING_BFS [null]", StringUtil.join(traversals.map(o -> o + " " + t1.traverse(o).toList().toString()), "\n")); JBTreeTraverser<Object> t2 = JBTreeTraverser.from(o -> JBIterable.of(nil, nil)).withRoots(Arrays.asList(42)); assertEquals("BI_ORDER_DFS [42, null, null, null, null, 42]\n" + "INTERLEAVED_DFS [42, null, null]\n" + "LEAVES_BFS [null, null]\n" + "LEAVES_DFS [null, null]\n" + "PLAIN_BFS [42, null, null]\n" + "POST_ORDER_DFS [null, null, 42]\n" + "PRE_ORDER_DFS [42, null, null]\n" + "TRACING_BFS [42, null]", StringUtil.join(traversals.map(o -> o + " " + t2.traverse(o).toList().toString()), "\n")); } public void testSimplePreOrderDfs() { assertEquals(Arrays.asList(1, 2, 5, 6, 7, 3, 8, 9, 10, 4, 11, 12, 13), numTraverser().toList()); } public void testSimpleBiOrderDfs() { assertEquals(Arrays.asList(1, 2, 5, 5, 6, 6, 7, 7, 2, 3, 8, 8, 9, 9, 10, 10, 3, 4, 11, 11, 12, 12, 13, 13, 4, 1), numTraverser().withTraversal(TreeTraversal.BI_ORDER_DFS).toList()); } public void testSimpleBiOrderDfs2Roots() { assertEquals(Arrays.asList(2, 5, 5, 6, 6, 7, 7, 2, 3, 8, 8, 9, 9, 10, 10, 3, 4, 11, 11, 12, 12, 13, 13, 4), TreeTraversal.BI_ORDER_DFS.traversal(numbers().get(1), Functions.fromMap(numbers())).toList()); } public void testHarderBiOrderDfs() { StringBuilder sb = new StringBuilder(); TreeTraversal.TracingIt<Integer> it = numTraverser().withTraversal(TreeTraversal.BI_ORDER_DFS).traverse().typedIterator(); while (it.advance()) { if (sb.length() != 0) sb.append(", "); it.hasNext(); sb.append(it.current()).append(it.isDescending() ? "↓" : "↑"); } assertEquals("1↓, 2↓, 5↓, 5↑, 6↓, 6↑, 7↓, 7↑, 2↑, 3↓, 8↓, 8↑, 9↓, 9↑, 10↓, 10↑, 3↑, 4↓, 11↓, 11↑, 12↓, 12↑, 13↓, 13↑, 4↑, 1↑", sb.toString()); } public void testSimpleInterlacedDfs() { assertEquals(Arrays.asList(1, 2, 5, 3, 6, 4, 8, 7, 9, 11, 10, 12, 13), numTraverser().withTraversal(TreeTraversal.INTERLEAVED_DFS).toList()); } public void testCyclicInterlacedDfs() { Function<Integer, JBIterable<Integer>> traversal = TreeTraversal.INTERLEAVED_DFS.traversal(Functions.fromMap( ContainerUtil.<Integer, Collection<Integer>>immutableMapBuilder() .put(1, Arrays.asList(1, 2)) .put(2, Arrays.asList(1, 2, 3)) .put(3, Arrays.asList()).build())); assertEquals(Arrays.asList(1, 1, 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, 3), traversal.fun(1).takeWhile(UP_TO(3)).toList()); } public void testIndefiniteCyclicInterlacedDfs() { Function<Integer, JBIterable<Integer>> traversal = TreeTraversal.INTERLEAVED_DFS.traversal( integer -> { JBIterable<Integer> it = JBIterable.generate(1, INCREMENT).takeWhile(UP_TO(integer + 1)); // 1: no repeat return it; // 2: repeat indefinitely: all seq //return JBIterable.generate(it, Functions.id()).flatten(Functions.id()); // 3: repeat indefinitely: self-cycle //return it.append(JBIterable.generate(integer, Functions.id())); }); JBIterable<Integer> counts = JBIterable.generate(1, INCREMENT).transform(integer -> traversal.fun(1).takeWhile(UP_TO(integer)).size()); // 1: no repeat assertEquals(Arrays.asList(1, 4, 13, 39, 117, 359, 1134, 3686, 12276, 41708), counts.take(10).toList()); // 2: repeat all seq //assertEquals(Arrays.asList(1, 4, 19, 236), counts.take(4).toList()); // 2: repeat self-cycle //assertEquals(Arrays.asList(1, 4, 19, 236), counts.take(4).toList()); } public void testTreeBacktraceSimple() { JBIterable<Integer> dfs = num2Traverser().withTraversal(TreeTraversal.PRE_ORDER_DFS).traverse(); JBIterable<Integer> bfs = num2Traverser().withTraversal(TreeTraversal.TRACING_BFS).traverse(); JBIterable<Integer> postDfs = num2Traverser().withTraversal(TreeTraversal.POST_ORDER_DFS).traverse(); TreeTraversal.TracingIt<Integer> it1 = dfs.typedIterator(); assertEquals(new Integer(37), it1.skipWhile(Conditions.notEqualTo(37)).next()); TreeTraversal.TracingIt<Integer> it2 = bfs.typedIterator(); assertEquals(new Integer(37), it2.skipWhile(Conditions.notEqualTo(37)).next()); TreeTraversal.TracingIt<Integer> it3 = postDfs.typedIterator(); assertEquals(new Integer(37), it3.skipWhile(Conditions.notEqualTo(37)).next()); assertEquals(Arrays.asList(37, 12, 4, 1), it1.backtrace().toList()); assertEquals(Arrays.asList(37, 12, 4, 1), it2.backtrace().toList()); assertEquals(Arrays.asList(37, 12, 4, 1), it3.backtrace().toList()); assertTrue(it1.hasNext()); assertFalse(it2.hasNext()); assertTrue(it3.hasNext()); assertEquals(Arrays.asList(37, 12, 4, 1), it1.backtrace().toList()); assertEquals(Arrays.asList(37, 12, 4, 1), it2.backtrace().toList()); assertEquals(Arrays.asList(37, 12, 4, 1), it3.backtrace().toList()); assertEquals(new Integer(12), it1.parent()); assertEquals(new Integer(12), it2.parent()); assertEquals(new Integer(12), it3.parent()); } public void testTreeBacktraceSingle() { Integer root = 123; JBTreeTraverser<Integer> traverser = new JBTreeTraverser<Integer>(Functions.constant(null)).withRoot(root); JBIterable<Integer> dfs = traverser.traverse(TreeTraversal.PRE_ORDER_DFS); JBIterable<Integer> bfs = traverser.traverse(TreeTraversal.TRACING_BFS); JBIterable<Integer> postDfs = traverser.traverse(TreeTraversal.POST_ORDER_DFS); TreeTraversal.TracingIt<Integer> it1 = dfs.typedIterator(); assertEquals(root, it1.next()); TreeTraversal.TracingIt<Integer> it2 = bfs.typedIterator(); assertEquals(root, it2.next()); TreeTraversal.TracingIt<Integer> it3 = postDfs.typedIterator(); assertEquals(root, it3.next()); assertEquals(Arrays.asList(root), it1.backtrace().toList()); assertEquals(Arrays.asList(root), it2.backtrace().toList()); assertEquals(Arrays.asList(root), it3.backtrace().toList()); assertNull(it1.parent()); assertNull(it2.parent()); assertNull(it3.parent()); } public void testTreeBacktraceTransformed() { JBIterable<String> dfs = num2Traverser().withTraversal(TreeTraversal.PRE_ORDER_DFS).traverse().map(Functions.TO_STRING()); JBIterable<String> bfs = num2Traverser().withTraversal(TreeTraversal.TRACING_BFS).traverse().map(Functions.TO_STRING()); TreeTraversal.TracingIt<String> it1 = dfs.typedIterator(); it1.skipWhile(Conditions.notEqualTo("37")).next(); TreeTraversal.TracingIt<String> it2 = bfs.typedIterator(); it2.skipWhile(Conditions.notEqualTo("37")).next(); assertEquals(Arrays.asList("37", "12", "4", "1"), it1.backtrace().toList()); assertEquals(Arrays.asList("37", "12", "4", "1"), it2.backtrace().toList()); assertEquals("12", it1.parent()); assertEquals("12", it2.parent()); } public void testSimplePostOrderDfs() { assertEquals(Arrays.asList(5, 6, 7, 2, 8, 9, 10, 3, 11, 12, 13, 4, 1), numTraverser().withTraversal(TreeTraversal.POST_ORDER_DFS).toList()); } public void testSimpleBfs() { assertEquals(JBIterable.generate(1, INCREMENT).take(37).toList(), num2Traverser().withTraversal(TreeTraversal.PLAIN_BFS).toList()); } public void testSimpleBfsLaziness() { List<Integer> result = simpleTraverseExpand(TreeTraversal.PLAIN_BFS); assertEquals(JBIterable.of(1, 2, 2, 4, 4, 4, 4, 8, 8, 8, 8, 8, 8, 8, 8).toList(), result); } public void testSimplePreDfsLaziness() { List<Integer> result = simpleTraverseExpand(TreeTraversal.PRE_ORDER_DFS); assertEquals(JBIterable.of(1, 2, 4, 8, 8, 4, 8, 8, 2, 4, 8, 8, 4, 8, 8).toList(), result); } @NotNull public List<Integer> simpleTraverseExpand(TreeTraversal traversal) { List<Integer> result = new ArrayList<>(); JBIterable<List<Integer>> iter = traversal.traversal((Function<List<Integer>, Iterable<List<Integer>>>)integers -> JBIterable.from(integers).skip(1).transform(WRAP_TO_LIST)).fun(ContainerUtil.newArrayList(1)); for (List<Integer> integers : iter) { Integer cur = integers.get(0); result.add(cur); if (cur > 4) continue; integers.add(cur*2); integers.add(cur*2); } return result; } public void testTracingBfsLaziness() { List<Integer> result = new ArrayList<>(); TreeTraversal.TracingIt<List<Integer>> it = TreeTraversal.TRACING_BFS.traversal((Function<List<Integer>, Iterable<List<Integer>>>)integers -> JBIterable.from(integers).skip(1).transform(WRAP_TO_LIST)).fun(ContainerUtil.newArrayList(1)).typedIterator(); while (it.advance()) { Integer cur = it.current().get(0); result.add(cur); assertEquals(JBIterable.generate(cur, DIV_2).takeWhile(IS_POSITIVE).toList(), it.backtrace().transform(integers -> integers.get(0)) .toList()); if (cur > 4) continue; it.current().add(cur*2); it.current().add(cur*2); } assertEquals(JBIterable.of(1, 2, 2, 4, 4, 4, 4, 8, 8, 8, 8, 8, 8, 8, 8).toList(), result); } public void testTraverseUnique() { assertEquals(Arrays.asList(1, 2, 5, 6, 7, 3, 8, 9, 10, 4, 11, 12, 13), numTraverser().unique().toList()); JBIterable<Integer> t0 = numTraverser().unique(o -> o % 5).traverse(); assertEquals(Arrays.asList(1, 2, 5, 3, 9), t0.toList()); assertEquals(Arrays.asList(1, 2, 5, 3, 9), t0.toList()); // same results again JBIterable<Integer> t1 = numTraverser().unique(o -> o % 5).unique(o -> o % 7).traverse(); JBIterable<Integer> t2 = numTraverser().unique(o -> o % 7).unique(o -> o % 5).traverse(); assertEquals(Arrays.asList(1, 2, 5, 3, 4), t1.toList()); assertEquals(Arrays.asList(1, 2, 5, 3), t2.toList()); TreeTraversal preOrder = TreeTraversal.PRE_ORDER_DFS; assertEquals(t1.toList(), numTraverser().traverse(preOrder.unique(o -> ((int)o) % 5).unique(o -> ((int)o) % 7)).toList()); assertEquals(t2.toList(), numTraverser().traverse(preOrder.unique(o -> ((int)o) % 7).unique(o -> ((int)o) % 5)).toList()); assertEquals(JBIterable.generate(1, INCREMENT).take(37).toList(), num2Traverser().withTraversal(TreeTraversal.PLAIN_BFS.unique()).toList()); assertEquals(JBIterable.generate(1, INCREMENT).take(37).toList(), num2Traverser().withTraversal(TreeTraversal.PLAIN_BFS.unique().unique()).toList()); } public void testTraverseMap() { Condition<String> notEmpty = o -> !o.isEmpty(); Condition<String> isThirteen = o -> "13".equals(o); JBTreeTraverser<Integer> t = numTraverser().filter(IS_ODD).regard(IS_POSITIVE); JBTreeTraverser<String> mappedA = t.map(String::valueOf, Integer::parseInt); JBTreeTraverser<String> mappedB = t.map(String::valueOf); JBTreeTraverser<Integer> mapped2A = mappedA.map(Integer::parseInt); JBTreeTraverser<Integer> mapped2B = mappedB.map(Integer::parseInt); JBTreeTraverser<Integer> mapped3A = mappedA.expand(notEmpty).regard(notEmpty).forceDisregard(isThirteen).map(o -> Integer.parseInt(o)); JBTreeTraverser<Integer> mapped3B = mappedB.expand(notEmpty).regard(notEmpty).forceDisregard(isThirteen).map(o -> Integer.parseInt(o)); JBTreeTraverser<String> mapped4A = mapped3B.map(String::valueOf).map(Integer::parseInt).map(String::valueOf); JBTreeTraverser<String> mapped4B = mapped3B.map(String::valueOf).map(Integer::parseInt).map(String::valueOf); assertFalse(mappedA.children("1").isEmpty()); assertTrue(mappedB.children("1").isEmpty()); // not supported in irreversible mapped trees assertEquals(Arrays.asList("1", "5", "7", "3", "9", "11", "13"), mappedA.toList()); assertEquals(Arrays.asList("1", "5", "7", "3", "9", "11", "13"), mappedB.toList()); assertEquals(Arrays.asList(1, 5, 7, 3, 9, 11, 13), mapped2A.toList()); assertEquals(Arrays.asList(1, 5, 7, 3, 9, 11, 13), mapped2B.toList()); assertEquals(Arrays.asList(1, 5, 7, 3, 9, 11, 13), mapped2A.reset().toList()); assertEquals(Arrays.asList(1, 5, 7, 3, 9, 11, 13), mapped2B.reset().toList()); assertEquals(t.toList(), mapped2A.toList()); assertEquals(t.toList(), mapped2B.toList()); assertEquals(Arrays.asList(1, 5, 7, 3, 9, 11), mapped3A.toList()); assertEquals(Arrays.asList(1, 5, 7, 3, 9, 11), mapped3B.toList()); assertEquals(Arrays.asList("1", "5", "7", "3", "9", "11"), mapped4A.toList()); assertEquals(Arrays.asList("1", "5", "7", "3", "9", "11"), mapped4B.toList()); } public void testTraverseMapStateful() { JBTreeTraverser<Integer> t = numTraverser(); class F extends JBIterable.SFun<Integer, String> { int count; @Override public String fun(Integer o) { count++; return count + ":" + o; } } JBTreeTraverser<String> mappedA = t.map(new F(), o -> Integer.parseInt(o.substring(o.indexOf(":") + 1))); JBTreeTraverser<String> mappedB = t.map(new F()); assertEquals(Arrays.asList("1:1", "1:2", "1:5", "2:6", "3:7"), mappedA.traverse().take(5).toList()); // FIXME assertEquals(Arrays.asList("1:1", "1:2", "1:5", "2:6", "3:7"), mappedA.traverse().take(5).toList()); // FIXME assertEquals(Arrays.asList("1:1", "2:2", "3:5", "4:6", "5:7"), mappedB.traverse().take(5).toList()); assertEquals(Arrays.asList("1:1", "2:2", "3:5", "4:6", "5:7"), mappedB.traverse().take(5).toList()); } // GuidedTraversal ---------------------------------------------- @NotNull private static TreeTraversal.GuidedIt.Guide<Integer> newGuide(@NotNull final TreeTraversal traversal) { return it -> { if (traversal == TreeTraversal.PRE_ORDER_DFS) { it.queueNext(it.curChild).result(it.curChild); } else if (traversal == TreeTraversal.POST_ORDER_DFS) { it.queueNext(it.curChild).result(it.curChild == null ? it.curParent : null); } else if (traversal == TreeTraversal.PLAIN_BFS) { it.queueLast(it.curChild).result(it.curChild); } }; } public void testGuidedDfs() { verifyGuidedTraversal(TreeTraversal.PRE_ORDER_DFS); verifyGuidedTraversal(TreeTraversal.POST_ORDER_DFS); verifyGuidedTraversal(TreeTraversal.PLAIN_BFS); } private static void verifyGuidedTraversal(TreeTraversal traversal) { assertEquals(num2Traverser().withTraversal(TreeTraversal.GUIDED_TRAVERSAL(newGuide(traversal))).toList(), num2Traverser().withTraversal(traversal).toList()); } // FilteredTraverser ---------------------------------------------- @NotNull public JBTreeTraverser<TextRange> rangeTraverser() { return new JBTreeTraverser<>( r -> r.getLength() < 4 ? JBIterable.empty() : JBIterable.generate(r.getStartOffset(), i -> i += r.getLength() / 4) .takeWhile(i -> i < r.getEndOffset()) .map(i -> TextRange.from(i, r.getLength() / 4))); } public void testSimpleFilter() { assertEquals(Arrays.asList(1, 5, 7, 3, 9, 11, 13), numTraverser().filter(IS_ODD).toList()); } public void testSimpleExpand() { assertEquals(Arrays.asList(1, 2, 3, 8, 9, 10, 4), numTraverser().expand(IS_ODD).toList()); } public void testExpandFilter() { assertEquals(Arrays.asList(1, 3, 9), numTraverser().expand(IS_ODD).filter(IS_ODD).toList()); assertEquals(Arrays.asList(1, 3, 9), numTraverser().expandAndFilter(IS_ODD).toList()); } public void testSkipExpandedDfs() { assertEquals(Arrays.asList(2, 8, 9, 10, 4), numTraverser().expand(IS_ODD).traverse(TreeTraversal.LEAVES_DFS).toList()); } public void testOnRange() { assertEquals(13, numTraverser().onRange(o -> true).traverse().size()); JBTreeTraverser<TextRange> ranges = rangeTraverser(); assertEquals(5, ranges.withRoot(TextRange.from(0, 8)).traverse().size()); assertEquals(Arrays.asList("(0,64)", "(16,32)", "(28,32)", "(29,30)", "(30,31)", "(31,32)", "(32,48)", "(32,36)", "(32,33)", "(33,34)"), ranges.withRoot(TextRange.from(0, 64)) .onRange(r -> r.intersects(30, 33)) .preOrderDfsTraversal().map(Object::toString).toList()); } public void testRangeChildrenLeavesDfs() { assertEquals(Arrays.asList(5, 6, 3, 11, 12, 13), numTraverser().regard(not(inRange(7, 10))).traverse(TreeTraversal.LEAVES_DFS).toList()); } public void testRangeChildrenLeavesBfs() { assertEquals(Arrays.asList(5, 6, 3, 11, 12, 13), numTraverser().regard(not(inRange(7, 10))).traverse(TreeTraversal.LEAVES_DFS).toList()); } public void testHideOneNodeDfs() { assertEquals(Arrays.asList(1, 2, 5, 6, 7, 4, 11, 12, 13), numTraverser().expandAndFilter(x -> x != 3).traverse(TreeTraversal.PRE_ORDER_DFS).toList()); } public void testHideOneNodeCompletelyBfs() { assertEquals(Arrays.asList(1, 2, 4, 5, 6, 7, 11, 12, 13), numTraverser().expandAndFilter(x -> x != 3).traverse(TreeTraversal.PLAIN_BFS).toList()); } public void testSkipExpandedCompletelyBfs() { assertEquals(Arrays.asList(2, 4, 8, 9, 10), numTraverser().expand(IS_ODD).traverse(TreeTraversal.LEAVES_BFS).toList()); } public void testExpandSkipFilterReset() { assertEquals(Arrays.asList(1, 5, 7, 3, 9, 11, 13), numTraverser().expand(IS_ODD).withTraversal(TreeTraversal.LEAVES_DFS).reset().filter(IS_ODD).toList()); } public void testForceExcludeReset() { assertEquals(Arrays.asList(1, 2, 6, 4, 12), numTraverser().forceIgnore(IS_ODD).reset().toList()); } public void testForceSkipReset() { assertEquals(Arrays.asList(1, 2, 6, 8, 10, 4, 12), numTraverser().forceDisregard(IS_ODD).reset().toList()); } public void testForceSkipLeavesDfs() { assertEquals(Arrays.asList(6, 8, 10, 12), numTraverser().forceDisregard(IS_ODD).traverse(TreeTraversal.LEAVES_DFS).toList()); } public void testFilterChildren() { assertEquals(Arrays.asList(1, 5, 7, 3, 9, 11, 13), numTraverser().regard(IS_ODD).toList()); } public void testEndlessGraph() { JBTreeTraverser<Integer> t = new JBTreeTraverser<>(k -> JBIterable.generate(k, INCREMENT).map(SQUARE).take(3)); assertEquals(Arrays.asList(1, 1, 4, 9, 1, 4, 9, 16, 25, 36, 81), t.withRoot(1).bfsTraversal().take(11).toList()); } public void testEndlessGraphParents() { JBTreeTraverser<Integer> t = new JBTreeTraverser<>(k -> JBIterable.generate(1, k, FIBONACCI).skip(2).take(3)); TreeTraversal.TracingIt<Integer> it = t.withRoot(1).preOrderDfsTraversal().skip(20).typedIterator(); TreeTraversal.TracingIt<Integer> cursor = JBIterator.cursor(it).first(); assertNotNull(cursor); assertSame(cursor, it); assertEquals(Arrays.asList(21, 20, 19, 18, 17, 16, 15, 14, 13, 12, 11, 10, 9, 8, 7, 6, 5, 4, 3, 2, 1), cursor.backtrace().toList()); } public void testEdgeFilter() { JBTreeTraverser<Integer> t = numTraverser(); JBIterable<Integer> it = t.regard(new FilteredTraverserBase.EdgeFilter<Integer>() { @Override public boolean value(Integer integer) { return (integer / edgeSource) % 2 == 0; } }).traverse(); assertEquals(Arrays.asList(1, 2, 5, 8, 10, 4, 11), it.toList()); assertEquals(Arrays.asList(1, 2, 5, 8, 10, 4, 11), it.toList()); } public void testStatefulChildFilter() { JBTreeTraverser<Integer> t = numTraverser(); class F extends JBIterable.SCond<Integer> { int count; final boolean value; F(boolean initialVal) { value = initialVal; } @Override public boolean value(Integer integer) { return count ++ > 0 == value; } } JBIterable<Integer> it = t.regard(new F(true)).traverse(); assertEquals(Arrays.asList(1, 5, 6, 7, 3, 9, 10, 4, 12, 13), it.toList()); assertEquals(Arrays.asList(1, 5, 6, 7, 3, 9, 10, 4, 12, 13), it.toList()); assertEquals(it.toList(), t.forceDisregard(new F(false)).reset().toList()); } }
platform/platform-tests/testSrc/com/intellij/util/containers/TreeTraverserTest.java
// Copyright 2000-2019 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package com.intellij.util.containers; import com.intellij.openapi.util.Comparing; import com.intellij.openapi.util.Condition; import com.intellij.openapi.util.Conditions; import com.intellij.openapi.util.TextRange; import com.intellij.openapi.util.text.StringUtil; import com.intellij.util.Function; import com.intellij.util.Functions; import com.intellij.util.PairFunction; import com.intellij.util.Processor; import junit.framework.TestCase; import org.jetbrains.annotations.NotNull; import java.lang.reflect.Modifier; import java.util.*; import java.util.concurrent.atomic.AtomicInteger; import static com.intellij.openapi.util.Conditions.not; import static com.intellij.util.containers.JBIterable.Split.*; /** * @author gregsh * * @noinspection ArraysAsListWithZeroOrOneArgument */ public class TreeTraverserTest extends TestCase { /** * <pre> * --- 5 * --- 2 --- 6 * / --- 7 * / * / --- 8 * 1 --- 3 --- 9 * \ --- 10 * \ * \ --- 11 * --- 4 --- 12 * --- 13 * </pre> */ private static Map<Integer, Collection<Integer>> numbers() { return ContainerUtil.<Integer, Collection<Integer>>immutableMapBuilder(). put(1, Arrays.asList(2, 3, 4)). put(2, Arrays.asList(5, 6, 7)). put(3, Arrays.asList(8, 9, 10)). put(4, Arrays.asList(11, 12, 13)). build(); } private static Map<Integer, Collection<Integer>> numbers2() { return ContainerUtil.<Integer, Collection<Integer>>immutableMapBuilder(). put(1, Arrays.asList(2, 3, 4)). put(2, Arrays.asList(5, 6, 7)). put(3, Arrays.asList(8, 9, 10)). put(4, Arrays.asList(11, 12, 13)). put(5, Arrays.asList(14, 15, 16)). put(6, Arrays.asList(17, 18, 19)). put(7, Arrays.asList(20, 21, 22)). put(8, Arrays.asList(23, 24, 25)). put(9, Arrays.asList(26, 27, 28)). put(10, Arrays.asList(29, 30, 31)). put(11, Arrays.asList(32, 33, 34)). put(12, Arrays.asList(35, 36, 37)). build(); } private static final Function<Integer, Integer> ASSERT_NUMBER = o -> { if (o instanceof Number) return o; throw new AssertionError(String.valueOf(o)); }; private static final Condition<Integer> IS_ODD = integer -> integer.intValue() % 2 == 1; private static final Condition<Integer> IS_POSITIVE = integer -> integer.intValue() > 0; private static Condition<Integer> inRange(int s, int e) { return integer -> s <= integer && integer <= e; } public static final Function<Integer, List<Integer>> WRAP_TO_LIST = integer -> ContainerUtil.newArrayList(integer); public static final Function<Integer, Integer> DIV_2 = k -> k / 2; private static final Function<Integer, Integer> INCREMENT = k -> k + 1; private static final Function<Integer, Integer> SQUARE = k -> k * k; private static final PairFunction<Integer, Integer, Integer> FIBONACCI = (k1, k2) -> k2 + k1; private static final Function<Integer, Integer> FIBONACCI2 = new JBIterable.SFun<Integer, Integer>() { int k0; @Override public Integer fun(Integer k) { int t = k0; k0 = k; return t + k; } }; @NotNull private static Condition<Integer> LESS_THAN(final int max) { return integer -> integer < max; } @NotNull private static Condition<Integer> LESS_THAN_MOD(final int max) { return integer -> integer % max < max / 2; } @NotNull private static <E> JBIterable.SCond<E> UP_TO(final E o) { return new JBIterable.SCond<E>() { boolean b; @Override public boolean value(E e) { if (b) return false; b = Comparing.equal(e, o); return true; } }; } // JBIterator ---------------------------------------------- public void testIteratorContracts() { Processor<Runnable> tryCatch = (r) -> { try { r.run(); return true; } catch (NoSuchElementException e) { return false; } }; JBIterator<Integer> it = JBIterator.from(Arrays.asList(1, 2, 3, 4).iterator()); assertFalse(tryCatch.process(it::current)); assertTrue(it.hasNext()); assertFalse(tryCatch.process(it::current)); assertTrue(it.advance()); // advance->1 assertEquals(new Integer(1), it.current()); assertTrue(it.hasNext()); assertTrue(it.hasNext()); assertEquals(new Integer(2), it.next()); // advance->2 assertEquals(new Integer(2), it.current()); assertEquals(new Integer(2), it.current()); assertTrue(it.advance()); // advance->3 assertEquals(new Integer(4), it.next()); // advance->4 assertFalse(it.hasNext()); assertFalse(it.hasNext()); assertFalse(it.advance()); assertFalse(tryCatch.process(it::current)); assertFalse(tryCatch.process(it::next)); assertFalse(it.hasNext()); } public void testIteratorContractsCurrent() { JBIterator<Integer> it = JBIterator.from(JBIterable.of(1).iterator()); assertTrue(it.advance()); assertEquals(new Integer(1), it.current()); assertFalse(it.hasNext()); assertEquals(new Integer(1), it.current()); } public void testCursorIterableContract() { List<Integer> list = new ArrayList<>(); JBIterable<Integer> orig = JBIterable.generate(1, INCREMENT).take(5); for (JBIterator<Integer> it : JBIterator.cursor(JBIterator.from(orig.iterator()))) { it.current(); it.hasNext(); list.add(it.current()); } assertEquals(orig.toList(), list); } public void testCursorIteratorContract() { JBIterable<Integer> orig = JBIterable.generate(1, INCREMENT).take(5); JBIterator<JBIterator<Integer>> it = JBIterator.from(JBIterator.cursor( JBIterator.from(orig.iterator())).iterator()); List<Integer> list = new ArrayList<>(); while (it.advance()) { it.hasNext(); list.add(it.current().current()); } assertEquals(orig.toList(), list); } public void testCursorTransform() { JBIterable<Integer> orig = JBIterable.generate(1, INCREMENT).take(5); List<Integer> expected = ContainerUtil.newArrayList(1, 2, 3, 4, 5); List<Integer> expectedOdd = ContainerUtil.newArrayList(1, 3, 5); assertEquals(expected, JBIterator.cursor(JBIterator.from(orig.iterator())).transform(o -> o.current()).toList()); assertEquals(expected.size(), JBIterator.cursor(JBIterator.from(orig.iterator())).last().current().intValue()); assertEquals(expectedOdd, JBIterator.cursor(JBIterator.from(orig.iterator())).transform(o -> o.current()).filter(IS_ODD).toList()); assertEquals(expectedOdd, JBIterator.cursor(JBIterator.from(orig.iterator())).filter(o -> IS_ODD.value(o.current())).transform(o -> o.current()).toList()); assertEquals(expected.subList(0, 4), JBIterator.cursor(JBIterator.from(orig.iterator())).filter(o -> o.hasNext()).transform(o -> o.current()).toList()); } public void testIteratorContractsSkipAndStop() { final AtomicInteger count = new AtomicInteger(0); JBIterator<Integer> it = new JBIterator<Integer>() { @Override protected Integer nextImpl() { return count.get() < 0 ? stop() : count.incrementAndGet() < 10 ? skip() : (Integer)count.addAndGet(-count.get() - 1); } }; assertEquals(JBIterable.of(-1).toList(), JBIterable.once(it).toList()); } // JBIterable ---------------------------------------------- public void testIterableOfNulls() { Object nil = null; assertEquals("[]", JBIterable.of(nil).toList().toString()); assertEquals("[null, null, null]", JBIterable.of(nil, nil, nil).toList().toString()); assertEquals("[null, null, null]", JBIterable.of(ContainerUtil.ar(nil, nil, nil)).toList().toString()); assertEquals("[null, null, null]", JBIterable.from(Arrays.asList(nil, nil, nil)).toList().toString()); assertEquals("[]", JBIterable.generate(null, x -> null).toList().toString()); assertEquals("[42]", JBIterable.generate(42, x -> null).toList().toString()); } public void testSingleElement() { JBIterable<String> it = JBIterable.of("42"); assertEquals(1, it.size()); assertEquals("42", it.first()); assertEquals("42", it.last()); assertEquals("42", it.single()); assertEquals("[42, 42]", it.append(it).toList().toString()); assertEquals("[42, 42]", it.repeat(2).toList().toString()); assertEquals("[42, 42, 48, 48]", it.append("42").append(Arrays.asList("48", "48")).toList().toString()); assertEquals("[42, 42, 48, 48, 49]", it.append("42").append(Arrays.asList("48", "48")).append("49").toList().toString()); assertEquals("[42, 42, 48, 48, 49]", it.append("42").append(JBIterable.of("48").append("48")).append("49").toList().toString()); } public void testFirstLastSingle() { assertNull(JBIterable.empty().first()); assertNull(JBIterable.empty().last()); assertNull(JBIterable.empty().single()); assertEquals("a", JBIterable.generate("a", o -> o + "a").first()); assertEquals("aaa", JBIterable.generate("a", o -> o + "a").take(3).last()); assertEquals("a", JBIterable.generate("a", o -> o + "a").take(1).single()); assertNull(JBIterable.generate("a", o -> o + "a").take(2).single()); assertEquals("a", JBIterable.from(Arrays.asList("a", "aa", "aaa")).first()); assertEquals("aaa", JBIterable.from(Arrays.asList("a", "aa", "aaa")).last()); assertEquals("a", JBIterable.of("a").single()); assertNull(JBIterable.of("a", "aa", "aaa").single()); } public void testOfAppendNulls() { Integer o = null; JBIterable<Integer> it = JBIterable.of(o).append(o).append(JBIterable.empty()); assertTrue(it.isEmpty()); assertSame(it, JBIterable.empty()); } public void testAppend() { JBIterable<Integer> it = JBIterable.of(1, 2, 3).append(JBIterable.of(4, 5, 6)).append(JBIterable.empty()).append(7); assertEquals(7, it.size()); assertEquals(Arrays.asList(1, 2, 3, 4, 5, 6, 7), it.toList()); assertTrue(it.contains(5)); } public void testGenerateRepeat() { JBIterable<Integer> it = JBIterable.generate(1, INCREMENT).take(3).repeat(3); assertEquals(9, it.size()); assertEquals(Arrays.asList(1, 2, 3, 1, 2, 3, 1, 2, 3), it.toList()); } public void testSkipTakeSize() { JBIterable<Integer> it = JBIterable.generate(1, INCREMENT).skip(10).take(10); assertEquals(10, it.size()); assertEquals(new Integer(11), it.first()); } public void testFlattenSkipTake() { assertEquals(1, JBIterable.of(1).flatMap(o -> JBIterable.of(o)).take(1).take(1).take(1).size()); assertEquals((Integer)1, JBIterable.of(1).flatMap(o -> JBIterable.of(o, o + 1)).take(2).take(1).get(0)); assertEquals((Integer)2, JBIterable.of(1).flatMap(o -> JBIterable.of(o, o + 1)).skip(1).take(1).get(0)); } public void testRangeWithSkipAndTake() { Condition<Integer> cond = i -> Math.abs(i - 10) <= 5; JBIterable<Integer> it = JBIterable.generate(1, INCREMENT).skipWhile(not(cond)).takeWhile(cond); assertEquals(11, it.size()); assertEquals(new Integer(5), it.first()); assertEquals(new Integer(15), it.last()); } public void testSkipWhile() { JBIterable<Integer> it = JBIterable.generate(1, INCREMENT).skipWhile(LESS_THAN_MOD(10)).take(10); assertEquals(Arrays.asList(5, 6, 7, 8, 9, 10, 11, 12, 13, 14), it.toList()); } public void testTakeWhile() { JBIterable<Integer> it = JBIterable.generate(1, INCREMENT).takeWhile(LESS_THAN_MOD(10)).take(10); assertEquals(Arrays.asList(1, 2, 3, 4), it.toList()); } public void testGetAt() { JBIterable<Integer> it = JBIterable.of(1, 2, 3, 4); assertEquals((Integer)4, it.get(3)); assertNull(it.get(4)); assertNull(it.get(5)); JBIterable<Integer> it2 = JBIterable.generate(1, INCREMENT).take(4); assertEquals((Integer)4, it2.get(3)); assertNull(it2.get(4)); assertNull(it2.get(5)); } public void testFilterTransformTakeWhile() { JBIterable<Integer> it = JBIterable.generate(1, INCREMENT).filter(IS_ODD).transform(SQUARE).takeWhile(LESS_THAN(100)); assertEquals(Arrays.asList(1, 9, 25, 49, 81), it.toList()); assertEquals(new Integer(1), it.first()); assertEquals(new Integer(81), it.last()); } public void testFilterTransformSkipWhile() { JBIterable<Integer> it = JBIterable.generate(1, INCREMENT).filter(IS_ODD).transform(SQUARE).skipWhile(LESS_THAN(100)).take(3); assertEquals(Arrays.asList(121, 169, 225), it.toList()); assertEquals(new Integer(121), it.first()); assertEquals(new Integer(225), it.last()); } public void testOnce() { JBIterable<Integer> it = JBIterable.once(JBIterable.generate(1, INCREMENT).take(3).iterator()); assertEquals(Arrays.asList(1, 2, 3), it.toList()); try { assertEquals(Arrays.asList(1, 2, 3), it.toList()); fail(); } catch (UnsupportedOperationException ignored) { } } public void testFlatten() { JBIterable<Integer> it = JBIterable.generate(1, INCREMENT).take(3).flatten(i -> i % 2 == 0 ? null : JBIterable.of(i - 1, i)); assertEquals(Arrays.asList(0, 1, 2, 3), it.toList()); } public void testStatefulFilter() { JBIterable<Integer> it = JBIterable.generate(1, INCREMENT).take(5).filter(new JBIterable.SCond<Integer>() { int prev; @Override public boolean value(Integer integer) { boolean b = integer > prev; if (b) prev = integer; return b; } }); assertEquals(Arrays.asList(1, 2, 3, 4, 5), it.toList()); assertEquals(Arrays.asList(1, 2, 3, 4, 5), it.toList()); } public void testStatefulGenerator() { JBIterable<Integer> it = JBIterable.generate(1, FIBONACCI2).take(8); assertEquals(Arrays.asList(1, 1, 2, 3, 5, 8, 13, 21), it.toList()); assertEquals(Arrays.asList(1, 1, 2, 3, 5, 8, 13, 21), it.toList()); } public void testFindIndexReduceMap() { JBIterable<Integer> it = JBIterable.of(1, 2, 3, 4, 5); assertEquals(15, (int)it.reduce(0, (Integer v, Integer o) -> v + o)); assertEquals(3, (int)it.find((o)-> o.intValue() == 3)); assertEquals(2, it.indexOf((o)-> o.intValue() == 3)); assertEquals(-1, it.indexOf((o)-> o.intValue() == 33)); assertEquals(Arrays.asList(1, 4, 9, 16, 25), it.map(o -> o * o).toList()); assertEquals(Arrays.asList(0, 1, 0, 2, 0, 3, 0, 4, 0, 5), it.flatMap(o -> Arrays.asList(0, o)).toList()); } public void testJoin() { assertNull(JBIterable.<String>of().join(", ").reduce((a, b) -> a + b)); assertEquals("", JBIterable.of().join(", ").reduce("", (a, b) -> a + b)); assertEquals("a", JBIterable.of("a").join(", ").reduce((a, b) -> a + b)); assertEquals("a, b, c", JBIterable.of("a", "b", "c").join(", ").reduce((a, b) -> a + b)); } public void testSplits1() { JBIterable<Integer> it = JBIterable.of(1, 2, 3, 4, 5); assertEquals(Arrays.asList(Arrays.asList(1, 2), Arrays.asList(3, 4)), it.split(2, true).toList()); assertEquals(Arrays.asList(Arrays.asList(1, 2), Arrays.asList(3, 4), Arrays.asList(5)), it.split(2, false).toList()); assertEquals("[[1, 2], [4, 5]]", it.split(OFF, o -> o % 3 == 0).map(o -> o.toList()).toList().toString()); assertEquals("[[1, 2], [3], [4, 5]]", it.split(AROUND, o -> o % 3 == 0).map(o -> o.toList()).toList().toString()); assertEquals("[[1, 2, 3], [4, 5]]", it.split(AFTER, o -> o % 3 == 0).map(o -> o.toList()).toList().toString()); assertEquals("[[1, 2], [3, 4, 5]]", it.split(BEFORE, o -> o % 3 == 0).map(o -> o.toList()).toList().toString()); assertEquals("[[1, 2, 3, 4], [5], []]", it.split(AROUND, o -> o == 5).map(o -> o.toList()).toList().toString()); assertEquals("[[], [1], [2, 3, 4, 5]]", it.split(AROUND, o -> o == 1).map(o -> o.toList()).toList().toString()); assertEquals("[[], [], [], [], [], []]", it.split(OFF, o -> true).map(o -> o.toList()).toList().toString()); assertEquals("[[1], [2], [3], [4], [5], []]", it.split(AFTER, o -> true).map(o -> o.toList()).toList().toString()); assertEquals("[[], [1], [2], [3], [4], [5]]", it.split(BEFORE, o -> true).map(o -> o.toList()).toList().toString()); assertEquals("[[], [1], [], [2], [], [3], [], [4], [], [5], []]", it.split(AROUND, o -> true).map(o -> o.toList()).toList().toString()); assertEquals("[[1, 2, 3, 4, 5]]", it.split(GROUP, o -> true).map(o -> o.toList()).toList().toString()); assertEquals("[[1, 2, 3, 4, 5]]", it.split(OFF, o -> false).map(o -> o.toList()).toList().toString()); assertEquals("[[1, 2, 3, 4, 5]]", it.split(AFTER, o -> false).map(o -> o.toList()).toList().toString()); assertEquals("[[1, 2, 3, 4, 5]]", it.split(BEFORE, o -> false).map(o -> o.toList()).toList().toString()); assertEquals("[[1, 2, 3, 4, 5]]", it.split(AROUND, o -> false).map(o -> o.toList()).toList().toString()); assertEquals("[[1, 2, 3, 4, 5]]", it.split(GROUP, o -> false).map(o -> o.toList()).toList().toString()); assertEquals(3, it.split(AROUND, o -> o % 3 == 0).size()); assertEquals(11, it.split(AROUND, o -> true).size()); assertEquals(it.split(2, false).toList(), it.split(AFTER, o -> o % 2 == 0).map(o -> o.toList()).toList()); JBIterable<JBIterable<Integer>> statePart = it.split(GROUP, new JBIterable.SCond<Integer>() { int i = 4; @Override public boolean value(Integer integer) { return (i = (i + 2) % 12) - 5 > 0; // 3 positive, 3 negative (+1 +3 +5 : -5 -3 -1) } }); assertEquals("[[1, 2, 3], [4, 5]]", statePart.map(o -> o.toList()).toList().toString()); assertEquals("[[1, 2, 3], [4, 5]]", statePart.map(o -> o.toList()).toList().toString()); } public void testSplits2() { JBIterable<Integer> it = JBIterable.empty(); assertEquals("[]", it.split(OFF, o -> o % 3 == 0).map(o -> o.toList()).toList().toString()); assertEquals("[]", it.split(AROUND, o -> o % 3 == 0).map(o -> o.toList()).toList().toString()); assertEquals("[]", it.split(AFTER, o -> o % 3 == 0).map(o -> o.toList()).toList().toString()); assertEquals("[]", it.split(BEFORE, o -> o % 3 == 0).map(o -> o.toList()).toList().toString()); assertEquals("[]", it.split(GROUP, o -> o % 3 == 0).map(o -> o.toList()).toList().toString()); it = JBIterable.of(3); assertEquals("[[], []]", it.split(OFF, o -> o % 3 == 0).map(o -> o.toList()).toList().toString()); assertEquals("[[], [3], []]", it.split(AROUND, o -> o % 3 == 0).map(o -> o.toList()).toList().toString()); assertEquals("[[3], []]", it.split(AFTER, o -> o % 3 == 0).map(o -> o.toList()).toList().toString()); assertEquals("[[], [3]]", it.split(BEFORE, o -> o % 3 == 0).map(o -> o.toList()).toList().toString()); assertEquals("[[3]]", it.split(GROUP, o -> o % 3 == 0).map(o -> o.toList()).toList().toString()); it = JBIterable.of(1, 2, 3, 3, 4, 5); assertEquals("[[1, 2], [], [4, 5]]", it.split(OFF, o -> o % 3 == 0).map(o -> o.toList()).toList().toString()); assertEquals("[[1, 2], [3], [], [3], [4, 5]]", it.split(AROUND, o -> o % 3 == 0).map(o -> o.toList()).toList().toString()); assertEquals("[[1, 2, 3], [3], [4, 5]]", it.split(AFTER, o -> o % 3 == 0).map(o -> o.toList()).toList().toString()); assertEquals("[[1, 2], [3], [3, 4, 5]]", it.split(BEFORE, o -> o % 3 == 0).map(o -> o.toList()).toList().toString()); assertEquals("[[1, 2], [3, 3], [4, 5]]", it.split(GROUP, o -> o % 3 == 0).map(o -> o.toList()).toList().toString()); it = JBIterable.of(3, 3, 1, 2, 3, 3); assertEquals("[[], [], [1, 2], [], []]", it.split(OFF, o -> o % 3 == 0).map(o -> o.toList()).toList().toString()); assertEquals("[[], [3], [], [3], [1, 2], [3], [], [3], []]", it.split(AROUND, o -> o % 3 == 0).map(o -> o.toList()).toList().toString()); assertEquals("[[3], [3], [1, 2, 3], [3], []]", it.split(AFTER, o -> o % 3 == 0).map(o -> o.toList()).toList().toString()); assertEquals("[[], [3], [3, 1, 2], [3], [3]]", it.split(BEFORE, o -> o % 3 == 0).map(o -> o.toList()).toList().toString()); assertEquals("[[3, 3], [1, 2], [3, 3]]", it.split(GROUP, o -> o % 3 == 0).map(o -> o.toList()).toList().toString()); Function<JBIterable<Integer>, JBIterable<JBIterator<Integer>>> cursor = param -> JBIterator.cursor(JBIterator.from(param.iterator())); assertEquals("[[], [], [1, 2], [], []]", cursor.fun(it).split(OFF, o -> o.current() % 3 == 0).map(o -> o.map(p -> p.current()).toList()).toList().toString()); assertEquals("[[], [3], [], [3], [1, 2], [3], [], [3], []]", cursor.fun(it).split(AROUND, o -> o.current() % 3 == 0).map(o -> o.map(p -> p.current()).toList()).toList().toString()); assertEquals("[[3], [3], [1, 2, 3], [3], []]", cursor.fun(it).split(AFTER, o -> o.current() % 3 == 0).map(o -> o.map(p -> p.current()).toList()).toList().toString()); assertEquals("[[], [3], [3, 1, 2], [3], [3]]", cursor.fun(it).split(BEFORE, o -> o.current() % 3 == 0).map(o -> o.map(p -> p.current()).toList()).toList().toString()); assertEquals("[[3, 3], [1, 2], [3, 3]]", cursor.fun(it).split(GROUP, o -> o.current() % 3 == 0).map(o -> o.map(p -> p.current()).toList()).toList().toString()); assertEquals("[[3, 3], [1, 2], [3, 3]]", it.split(2, true).toList().toString()); assertEquals("[[3, 3], [1, 2], [3, 3]]", it.split(2).map(o -> o.toList()).toList().toString()); assertEquals("[[3, 3], [1, 2], [3, 3]]", cursor.fun(it).split(2).map(o -> o.map(p -> p.current()).toList()).toList().toString()); assertEquals("[[3, 3, 1, 2], [3, 3]]", cursor.fun(it).split(4).map(o -> o.map(p -> p.current()).toList()).toList().toString()); } public void testIterateUnique() { JBIterable<Integer> it = JBIterable.generate(1, INCREMENT).take(30); assertEquals(it.toList(), it.unique().toList()); JBIterable<Integer> uniqueMod5 = it.unique((o) -> o % 5); assertEquals(Arrays.asList(1, 2, 3, 4, 5), uniqueMod5.toList()); assertEquals(Arrays.asList(1, 2, 3, 4, 5), uniqueMod5.toList()); // same results again } public void testSort() { JBIterable<Integer> it1 = JBIterable.generate(1, INCREMENT).take(30); JBIterable<Integer> it2 = JBIterable.generate(30, o -> o - 1).take(30).sort(Integer::compareTo); assertEquals(it1.toList(), it2.unique().toList()); } // TreeTraversal ---------------------------------------------- @NotNull private static Function<Integer, JBIterable<Integer>> numTraverser(TreeTraversal t) { return t.traversal(Functions.compose(ASSERT_NUMBER, Functions.fromMap(numbers()))); } @NotNull private static Function<Integer, JBIterable<Integer>> numTraverser2(TreeTraversal t) { return t.traversal(Functions.compose(ASSERT_NUMBER, Functions.fromMap(numbers2()))); } @NotNull private static JBIterable<TreeTraversal> allTraversals() { JBIterable<TreeTraversal> result = JBIterable.of(TreeTraversal.class.getDeclaredFields()) .filter(o -> Modifier.isStatic(o.getModifiers()) && Modifier.isPublic(o.getModifiers())) .map(o -> { try { return o.get(null); } catch (IllegalAccessException e) { throw new AssertionError(e); } }) .filter(TreeTraversal.class) .sort(Comparator.comparing(Object::toString)) .collect(); assertEquals("[BI_ORDER_DFS, INTERLEAVED_DFS, LEAVES_BFS, LEAVES_DFS," + " PLAIN_BFS, POST_ORDER_DFS, PRE_ORDER_DFS, TRACING_BFS]", result.toList().toString()); return result; } public void testTraverserOfNulls() { JBIterable<TreeTraversal> traversals = allTraversals(); Object nil = null; JBTreeTraverser<Object> t1 = JBTreeTraverser.from(o -> JBIterable.of(nil, nil)).withRoots(Arrays.asList(nil)); assertEquals("BI_ORDER_DFS [null, null]\n" + "INTERLEAVED_DFS [null]\n" + "LEAVES_BFS [null]\n" + "LEAVES_DFS [null]\n" + "PLAIN_BFS [null]\n" + "POST_ORDER_DFS [null]\n" + "PRE_ORDER_DFS [null]\n" + "TRACING_BFS [null]", StringUtil.join(traversals.map(o -> o + " " + t1.traverse(o).toList().toString()), "\n")); JBTreeTraverser<Object> t2 = JBTreeTraverser.from(o -> JBIterable.of(nil, nil)).withRoots(Arrays.asList(42)); assertEquals("BI_ORDER_DFS [42, null, null, null, null, 42]\n" + "INTERLEAVED_DFS [42, null, null]\n" + "LEAVES_BFS [null, null]\n" + "LEAVES_DFS [null, null]\n" + "PLAIN_BFS [42, null, null]\n" + "POST_ORDER_DFS [null, null, 42]\n" + "PRE_ORDER_DFS [42, null, null]\n" + "TRACING_BFS [42, null]", StringUtil.join(traversals.map(o -> o + " " + t2.traverse(o).toList().toString()), "\n")); } public void testSimplePreOrderDfs() { assertEquals(Arrays.asList(1, 2, 5, 6, 7, 3, 8, 9, 10, 4, 11, 12, 13), numTraverser(TreeTraversal.PRE_ORDER_DFS).fun(1).toList()); } public void testSimpleBiOrderDfs() { assertEquals(Arrays.asList(1, 2, 5, 5, 6, 6, 7, 7, 2, 3, 8, 8, 9, 9, 10, 10, 3, 4, 11, 11, 12, 12, 13, 13, 4, 1), numTraverser(TreeTraversal.BI_ORDER_DFS).fun(1).toList()); } public void testSimpleBiOrderDfs2Roots() { assertEquals(Arrays.asList(2, 5, 5, 6, 6, 7, 7, 2, 3, 8, 8, 9, 9, 10, 10, 3, 4, 11, 11, 12, 12, 13, 13, 4), TreeTraversal.BI_ORDER_DFS.traversal(numbers().get(1), Functions.fromMap(numbers())).toList()); } public void testHarderBiOrderDfs() { StringBuilder sb = new StringBuilder(); TreeTraversal.TracingIt<Integer> it = numTraverser(TreeTraversal.BI_ORDER_DFS).fun(1).typedIterator(); while (it.advance()) { if (sb.length() != 0) sb.append(", "); it.hasNext(); sb.append(it.current()).append(it.isDescending() ? "↓" : "↑"); } assertEquals("1↓, 2↓, 5↓, 5↑, 6↓, 6↑, 7↓, 7↑, 2↑, 3↓, 8↓, 8↑, 9↓, 9↑, 10↓, 10↑, 3↑, 4↓, 11↓, 11↑, 12↓, 12↑, 13↓, 13↑, 4↑, 1↑", sb.toString()); } public void testSimpleInterlacedDfs() { assertEquals(Arrays.asList(1, 2, 5, 3, 6, 4, 8, 7, 9, 11, 10, 12, 13), numTraverser(TreeTraversal.INTERLEAVED_DFS).fun(1).toList()); } public void testCyclicInterlacedDfs() { Function<Integer, JBIterable<Integer>> traversal = TreeTraversal.INTERLEAVED_DFS.traversal(Functions.fromMap( ContainerUtil.<Integer, Collection<Integer>>immutableMapBuilder() .put(1, Arrays.asList(1, 2)) .put(2, Arrays.asList(1, 2, 3)) .put(3, Arrays.asList()).build())); assertEquals(Arrays.asList(1, 1, 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, 3), traversal.fun(1).takeWhile(UP_TO(3)).toList()); } public void testIndefiniteCyclicInterlacedDfs() { Function<Integer, JBIterable<Integer>> traversal = TreeTraversal.INTERLEAVED_DFS.traversal( integer -> { JBIterable<Integer> it = JBIterable.generate(1, INCREMENT).takeWhile(UP_TO(integer + 1)); // 1: no repeat return it; // 2: repeat indefinitely: all seq //return JBIterable.generate(it, Functions.id()).flatten(Functions.id()); // 3: repeat indefinitely: self-cycle //return it.append(JBIterable.generate(integer, Functions.id())); }); JBIterable<Integer> counts = JBIterable.generate(1, INCREMENT).transform(integer -> traversal.fun(1).takeWhile(UP_TO(integer)).size()); // 1: no repeat assertEquals(Arrays.asList(1, 4, 13, 39, 117, 359, 1134, 3686, 12276, 41708), counts.take(10).toList()); // 2: repeat all seq //assertEquals(Arrays.asList(1, 4, 19, 236), counts.take(4).toList()); // 2: repeat self-cycle //assertEquals(Arrays.asList(1, 4, 19, 236), counts.take(4).toList()); } public void testTreeBacktraceSimple() { JBIterable<Integer> dfs = numTraverser2(TreeTraversal.PRE_ORDER_DFS).fun(1); JBIterable<Integer> bfs = numTraverser2(TreeTraversal.TRACING_BFS).fun(1); JBIterable<Integer> postDfs = numTraverser2(TreeTraversal.POST_ORDER_DFS).fun(1); TreeTraversal.TracingIt<Integer> it1 = dfs.typedIterator(); assertEquals(new Integer(37), it1.skipWhile(Conditions.notEqualTo(37)).next()); TreeTraversal.TracingIt<Integer> it2 = bfs.typedIterator(); assertEquals(new Integer(37), it2.skipWhile(Conditions.notEqualTo(37)).next()); TreeTraversal.TracingIt<Integer> it3 = postDfs.typedIterator(); assertEquals(new Integer(37), it3.skipWhile(Conditions.notEqualTo(37)).next()); assertEquals(Arrays.asList(37, 12, 4, 1), it1.backtrace().toList()); assertEquals(Arrays.asList(37, 12, 4, 1), it2.backtrace().toList()); assertEquals(Arrays.asList(37, 12, 4, 1), it3.backtrace().toList()); assertTrue(it1.hasNext()); assertFalse(it2.hasNext()); assertTrue(it3.hasNext()); assertEquals(Arrays.asList(37, 12, 4, 1), it1.backtrace().toList()); assertEquals(Arrays.asList(37, 12, 4, 1), it2.backtrace().toList()); assertEquals(Arrays.asList(37, 12, 4, 1), it3.backtrace().toList()); assertEquals(new Integer(12), it1.parent()); assertEquals(new Integer(12), it2.parent()); assertEquals(new Integer(12), it3.parent()); } public void testTreeBacktraceSingle() { Integer root = 123; JBTreeTraverser<Integer> traverser = new JBTreeTraverser<Integer>(Functions.constant(null)).withRoot(root); JBIterable<Integer> dfs = traverser.traverse(TreeTraversal.PRE_ORDER_DFS); JBIterable<Integer> bfs = traverser.traverse(TreeTraversal.TRACING_BFS); JBIterable<Integer> postDfs = traverser.traverse(TreeTraversal.POST_ORDER_DFS); TreeTraversal.TracingIt<Integer> it1 = dfs.typedIterator(); assertEquals(root, it1.next()); TreeTraversal.TracingIt<Integer> it2 = bfs.typedIterator(); assertEquals(root, it2.next()); TreeTraversal.TracingIt<Integer> it3 = postDfs.typedIterator(); assertEquals(root, it3.next()); assertEquals(Arrays.asList(root), it1.backtrace().toList()); assertEquals(Arrays.asList(root), it2.backtrace().toList()); assertEquals(Arrays.asList(root), it3.backtrace().toList()); assertNull(it1.parent()); assertNull(it2.parent()); assertNull(it3.parent()); } public void testTreeBacktraceTransformed() { JBIterable<String> dfs = numTraverser2(TreeTraversal.PRE_ORDER_DFS).fun(1).transform(Functions.TO_STRING()); JBIterable<String> bfs = numTraverser2(TreeTraversal.TRACING_BFS).fun(1).transform(Functions.TO_STRING()); TreeTraversal.TracingIt<String> it1 = dfs.typedIterator(); it1.skipWhile(Conditions.notEqualTo("37")).next(); TreeTraversal.TracingIt<String> it2 = bfs.typedIterator(); it2.skipWhile(Conditions.notEqualTo("37")).next(); assertEquals(Arrays.asList("37", "12", "4", "1"), it1.backtrace().toList()); assertEquals(Arrays.asList("37", "12", "4", "1"), it2.backtrace().toList()); assertEquals("12", it1.parent()); assertEquals("12", it2.parent()); } public void testSimplePostOrderDfs() { assertEquals(Arrays.asList(5, 6, 7, 2, 8, 9, 10, 3, 11, 12, 13, 4, 1), numTraverser(TreeTraversal.POST_ORDER_DFS).fun(1).toList()); } public void testSimpleBfs() { assertEquals(JBIterable.generate(1, INCREMENT).take(37).toList(), numTraverser2(TreeTraversal.PLAIN_BFS).fun(1).toList()); } public void testSimpleBfsLaziness() { List<Integer> result = simpleTraverseExpand(TreeTraversal.PLAIN_BFS); assertEquals(JBIterable.of(1, 2, 2, 4, 4, 4, 4, 8, 8, 8, 8, 8, 8, 8, 8).toList(), result); } public void testSimplePreDfsLaziness() { List<Integer> result = simpleTraverseExpand(TreeTraversal.PRE_ORDER_DFS); assertEquals(JBIterable.of(1, 2, 4, 8, 8, 4, 8, 8, 2, 4, 8, 8, 4, 8, 8).toList(), result); } @NotNull public List<Integer> simpleTraverseExpand(TreeTraversal traversal) { List<Integer> result = new ArrayList<>(); JBIterable<List<Integer>> iter = traversal.traversal((Function<List<Integer>, Iterable<List<Integer>>>)integers -> JBIterable.from(integers).skip(1).transform(WRAP_TO_LIST)).fun(ContainerUtil.newArrayList(1)); for (List<Integer> integers : iter) { Integer cur = integers.get(0); result.add(cur); if (cur > 4) continue; integers.add(cur*2); integers.add(cur*2); } return result; } public void testTracingBfsLaziness() { List<Integer> result = new ArrayList<>(); TreeTraversal.TracingIt<List<Integer>> it = TreeTraversal.TRACING_BFS.traversal((Function<List<Integer>, Iterable<List<Integer>>>)integers -> JBIterable.from(integers).skip(1).transform(WRAP_TO_LIST)).fun(ContainerUtil.newArrayList(1)).typedIterator(); while (it.advance()) { Integer cur = it.current().get(0); result.add(cur); assertEquals(JBIterable.generate(cur, DIV_2).takeWhile(IS_POSITIVE).toList(), it.backtrace().transform(integers -> integers.get(0)) .toList()); if (cur > 4) continue; it.current().add(cur*2); it.current().add(cur*2); } assertEquals(JBIterable.of(1, 2, 2, 4, 4, 4, 4, 8, 8, 8, 8, 8, 8, 8, 8).toList(), result); } public void testTraverseUnique() { assertEquals(Arrays.asList(1, 2, 5, 6, 7, 3, 8, 9, 10, 4, 11, 12, 13), numTraverser(TreeTraversal.PRE_ORDER_DFS.unique()).fun(1).toList()); JBIterable<Integer> uniqueMod5 = numTraverser(TreeTraversal.PRE_ORDER_DFS.unique((Integer o) -> o % 5)).fun(1); assertEquals(Arrays.asList(1, 2, 5, 3, 9), uniqueMod5.toList()); assertEquals(Arrays.asList(1, 2, 5, 3, 9), uniqueMod5.toList()); // same results again JBIterable<Integer> uniqueMod57 = numTraverser(TreeTraversal.PRE_ORDER_DFS.unique((Integer o) -> o % 5).unique((Integer o) -> o % 7)).fun(1); JBIterable<Integer> uniqueMod75 = numTraverser(TreeTraversal.PRE_ORDER_DFS.unique((Integer o) -> o % 7).unique((Integer o) -> o % 5)).fun(1); assertEquals(Arrays.asList(1, 2, 5, 3, 4), uniqueMod57.toList()); assertEquals(Arrays.asList(1, 2, 5, 3), uniqueMod75.toList()); assertEquals(JBIterable.generate(1, INCREMENT).take(37).toList(), numTraverser2(TreeTraversal.PLAIN_BFS.unique()).fun(1).toList()); assertEquals(JBIterable.generate(1, INCREMENT).take(37).toList(), numTraverser2(TreeTraversal.PLAIN_BFS.unique().unique()).fun(1).toList()); } public void testTraverseMap() { Condition<String> notEmpty = o -> !o.isEmpty(); Condition<String> isThirteen = o -> "13".equals(o); JBTreeTraverser<Integer> t = numberTraverser().withRoot(1).filter(IS_ODD).regard(IS_POSITIVE); JBTreeTraverser<String> mappedA = t.map(String::valueOf, Integer::parseInt); JBTreeTraverser<String> mappedB = t.map(String::valueOf); JBTreeTraverser<Integer> mapped2A = mappedA.map(Integer::parseInt); JBTreeTraverser<Integer> mapped2B = mappedB.map(Integer::parseInt); JBTreeTraverser<Integer> mapped3A = mappedA.expand(notEmpty).regard(notEmpty).forceDisregard(isThirteen).map(o -> Integer.parseInt(o)); JBTreeTraverser<Integer> mapped3B = mappedB.expand(notEmpty).regard(notEmpty).forceDisregard(isThirteen).map(o -> Integer.parseInt(o)); JBTreeTraverser<String> mapped4A = mapped3B.map(String::valueOf).map(Integer::parseInt).map(String::valueOf); JBTreeTraverser<String> mapped4B = mapped3B.map(String::valueOf).map(Integer::parseInt).map(String::valueOf); assertFalse(mappedA.children("1").isEmpty()); assertTrue(mappedB.children("1").isEmpty()); // not supported in irreversible mapped trees assertEquals(Arrays.asList("1", "5", "7", "3", "9", "11", "13"), mappedA.toList()); assertEquals(Arrays.asList("1", "5", "7", "3", "9", "11", "13"), mappedB.toList()); assertEquals(Arrays.asList(1, 5, 7, 3, 9, 11, 13), mapped2A.toList()); assertEquals(Arrays.asList(1, 5, 7, 3, 9, 11, 13), mapped2B.toList()); assertEquals(Arrays.asList(1, 5, 7, 3, 9, 11, 13), mapped2A.reset().toList()); assertEquals(Arrays.asList(1, 5, 7, 3, 9, 11, 13), mapped2B.reset().toList()); assertEquals(t.toList(), mapped2A.toList()); assertEquals(t.toList(), mapped2B.toList()); assertEquals(Arrays.asList(1, 5, 7, 3, 9, 11), mapped3A.toList()); assertEquals(Arrays.asList(1, 5, 7, 3, 9, 11), mapped3B.toList()); assertEquals(Arrays.asList("1", "5", "7", "3", "9", "11"), mapped4A.toList()); assertEquals(Arrays.asList("1", "5", "7", "3", "9", "11"), mapped4B.toList()); } public void testTraverseMapStateful() { JBTreeTraverser<Integer> t = numberTraverser().withRoot(1); class F extends JBIterable.SFun<Integer, String> { int count; @Override public String fun(Integer o) { count++; return count + ":" + o; } } JBTreeTraverser<String> mappedA = t.map(new F(), o -> Integer.parseInt(o.substring(o.indexOf(":") + 1))); JBTreeTraverser<String> mappedB = t.map(new F()); assertEquals(Arrays.asList("1:1", "1:2", "1:5", "2:6", "3:7"), mappedA.traverse().take(5).toList()); // FIXME assertEquals(Arrays.asList("1:1", "1:2", "1:5", "2:6", "3:7"), mappedA.traverse().take(5).toList()); // FIXME assertEquals(Arrays.asList("1:1", "2:2", "3:5", "4:6", "5:7"), mappedB.traverse().take(5).toList()); assertEquals(Arrays.asList("1:1", "2:2", "3:5", "4:6", "5:7"), mappedB.traverse().take(5).toList()); } // GuidedTraversal ---------------------------------------------- @NotNull private static TreeTraversal.GuidedIt.Guide<Integer> newGuide(@NotNull final TreeTraversal traversal) { return it -> { if (traversal == TreeTraversal.PRE_ORDER_DFS) { it.queueNext(it.curChild).result(it.curChild); } else if (traversal == TreeTraversal.POST_ORDER_DFS) { it.queueNext(it.curChild).result(it.curChild == null ? it.curParent : null); } else if (traversal == TreeTraversal.PLAIN_BFS) { it.queueLast(it.curChild).result(it.curChild); } }; } public void testGuidedDfs() { verifyGuidedTraversal(TreeTraversal.PRE_ORDER_DFS); verifyGuidedTraversal(TreeTraversal.POST_ORDER_DFS); verifyGuidedTraversal(TreeTraversal.PLAIN_BFS); } private static void verifyGuidedTraversal(TreeTraversal traversal) { assertEquals(numTraverser2(TreeTraversal.GUIDED_TRAVERSAL(newGuide(traversal))).fun(1).toList(), numTraverser2(traversal).fun(1).toList()); } // FilteredTraverser ---------------------------------------------- @NotNull private static JBTreeTraverser<Integer> numberTraverser() { return new JBTreeTraverser<>(Functions.compose(ASSERT_NUMBER, Functions.fromMap(numbers()))); } @NotNull public JBTreeTraverser<TextRange> rangeTraverser() { return new JBTreeTraverser<>( r -> r.getLength() < 4 ? JBIterable.empty() : JBIterable.generate(r.getStartOffset(), i -> i += r.getLength() / 4) .takeWhile(i -> i < r.getEndOffset()) .map(i -> TextRange.from(i, r.getLength() / 4))); } public void testSimpleFilter() { JBTreeTraverser<Integer> t = numberTraverser(); assertEquals(Arrays.asList(1, 5, 7, 3, 9, 11, 13), t.withRoot(1).filter(IS_ODD).toList()); } public void testSimpleExpand() { JBTreeTraverser<Integer> t = numberTraverser(); assertEquals(Arrays.asList(1, 2, 3, 8, 9, 10, 4), t.withRoot(1).expand(IS_ODD).toList()); } public void testExpandFilter() { JBTreeTraverser<Integer> t = numberTraverser(); assertEquals(Arrays.asList(1, 3, 9), t.withRoot(1).expand(IS_ODD).filter(IS_ODD).toList()); assertEquals(Arrays.asList(1, 3, 9), t.withRoot(1).expandAndFilter(IS_ODD).toList()); } public void testSkipExpandedDfs() { JBTreeTraverser<Integer> t = numberTraverser(); assertEquals(Arrays.asList(2, 8, 9, 10, 4), t.withRoot(1).expand(IS_ODD).traverse(TreeTraversal.LEAVES_DFS).toList()); } public void testOnRange() { assertEquals(13, numberTraverser().withRoot(1).onRange(o -> true).traverse().size()); JBTreeTraverser<TextRange> ranges = rangeTraverser(); assertEquals(5, ranges.withRoot(TextRange.from(0, 8)).traverse().size()); assertEquals(Arrays.asList("(0,64)", "(16,32)", "(28,32)", "(29,30)", "(30,31)", "(31,32)", "(32,48)", "(32,36)", "(32,33)", "(33,34)"), ranges.withRoot(TextRange.from(0, 64)) .onRange(r -> r.intersects(30, 33)) .preOrderDfsTraversal().map(Object::toString).toList()); } public void testRangeChildrenLeavesDfs() { JBTreeTraverser<Integer> t = numberTraverser(); assertEquals(Arrays.asList(5, 6, 3, 11, 12, 13), t.withRoot(1).regard(not(inRange(7, 10))).traverse(TreeTraversal.LEAVES_DFS).toList()); } public void testRangeChildrenLeavesBfs() { JBTreeTraverser<Integer> t = numberTraverser(); assertEquals(Arrays.asList(5, 6, 3, 11, 12, 13), t.withRoot(1).regard(not(inRange(7, 10))).traverse(TreeTraversal.LEAVES_DFS).toList()); } public void testHideOneNodeDfs() { JBTreeTraverser<Integer> t = numberTraverser(); assertEquals(Arrays.asList(1, 2, 5, 6, 7, 4, 11, 12, 13), t.withRoot(1).expandAndFilter(x -> x != 3).traverse(TreeTraversal.PRE_ORDER_DFS).toList()); } public void testHideOneNodeCompletelyBfs() { JBTreeTraverser<Integer> t = numberTraverser(); assertEquals(Arrays.asList(1, 2, 4, 5, 6, 7, 11, 12, 13), t.withRoot(1).expandAndFilter(x -> x != 3).traverse(TreeTraversal.PLAIN_BFS).toList()); } public void testSkipExpandedCompletelyBfs() { JBTreeTraverser<Integer> t = numberTraverser(); assertEquals(Arrays.asList(2, 4, 8, 9, 10), t.withRoot(1).expand(IS_ODD).traverse(TreeTraversal.LEAVES_BFS).toList()); } public void testExpandSkipFilterReset() { JBTreeTraverser<Integer> t = numberTraverser(); assertEquals(Arrays.asList(1, 5, 7, 3, 9, 11, 13), t.withRoot(1).expand(IS_ODD). withTraversal(TreeTraversal.LEAVES_DFS).reset().filter(IS_ODD).toList()); } public void testForceExlcudeReset() { JBTreeTraverser<Integer> t = numberTraverser(); assertEquals(Arrays.asList(1, 2, 6, 4, 12), t.withRoot(1).forceIgnore(IS_ODD).reset().toList()); } public void testForceSkipReset() { JBTreeTraverser<Integer> t = numberTraverser(); assertEquals(Arrays.asList(1, 2, 6, 8, 10, 4, 12), t.withRoot(1).forceDisregard(IS_ODD).reset().toList()); } public void testForceSkipLeavesDfs() { JBTreeTraverser<Integer> t = numberTraverser(); assertEquals(Arrays.asList(6, 8, 10, 12), t.withRoot(1).forceDisregard(IS_ODD).traverse(TreeTraversal.LEAVES_DFS).toList()); } public void testFilterChildren() { JBTreeTraverser<Integer> t = numberTraverser(); assertEquals(Arrays.asList(1, 5, 7, 3, 9, 11, 13), t.withRoot(1).regard(IS_ODD).toList()); } public void testEndlessGraph() { JBTreeTraverser<Integer> t = new JBTreeTraverser<>(k -> JBIterable.generate(k, INCREMENT).transform(SQUARE).take(3)); assertEquals(Arrays.asList(1, 1, 4, 9, 1, 4, 9, 16, 25, 36, 81), t.withRoot(1).bfsTraversal().take(11).toList()); } public void testEndlessGraphParents() { JBTreeTraverser<Integer> t = new JBTreeTraverser<>(k -> JBIterable.generate(1, k, FIBONACCI).skip(2).take(3)); TreeTraversal.TracingIt<Integer> it = t.withRoot(1).preOrderDfsTraversal().skip(20).typedIterator(); TreeTraversal.TracingIt<Integer> cursor = JBIterator.cursor(it).first(); assertNotNull(cursor); assertSame(cursor, it); assertEquals(Arrays.asList(21, 20, 19, 18, 17, 16, 15, 14, 13, 12, 11, 10, 9, 8, 7, 6, 5, 4, 3, 2, 1), cursor.backtrace().toList()); } public void testEdgeFilter() { JBTreeTraverser<Integer> t = numberTraverser(); JBIterable<Integer> it = t.regard(new FilteredTraverserBase.EdgeFilter<Integer>() { @Override public boolean value(Integer integer) { return (integer / edgeSource) % 2 == 0; } }).withRoot(1).traverse(); assertEquals(Arrays.asList(1, 2, 5, 8, 10, 4, 11), it.toList()); assertEquals(Arrays.asList(1, 2, 5, 8, 10, 4, 11), it.toList()); } public void testStatefulChildFilter() { JBTreeTraverser<Integer> t = numberTraverser(); class F extends JBIterable.SCond<Integer> { int count; boolean value; F(boolean initialVal) { value = initialVal; } @Override public boolean value(Integer integer) { return count ++ > 0 == value; } } JBIterable<Integer> it = t.regard(new F(true)).withRoot(1).traverse(); assertEquals(Arrays.asList(1, 5, 6, 7, 3, 9, 10, 4, 12, 13), it.toList()); assertEquals(Arrays.asList(1, 5, 6, 7, 3, 9, 10, 4, 12, 13), it.toList()); assertEquals(it.toList(), t.forceDisregard(new F(false)).withRoot(1).reset().traverse().toList()); } }
cleanup: use traversers GitOrigin-RevId: 2c699a4182006bd325194a146eaea38000f22334
platform/platform-tests/testSrc/com/intellij/util/containers/TreeTraverserTest.java
cleanup: use traversers
<ide><path>latform/platform-tests/testSrc/com/intellij/util/containers/TreeTraverserTest.java <ide> // TreeTraversal ---------------------------------------------- <ide> <ide> @NotNull <del> private static Function<Integer, JBIterable<Integer>> numTraverser(TreeTraversal t) { <del> return t.traversal(Functions.compose(ASSERT_NUMBER, Functions.fromMap(numbers()))); <add> private static JBTreeTraverser<Integer> numTraverser() { <add> return new JBTreeTraverser<>(Functions.compose(ASSERT_NUMBER, Functions.fromMap(numbers()))).withRoot(1); <ide> } <ide> <ide> @NotNull <del> private static Function<Integer, JBIterable<Integer>> numTraverser2(TreeTraversal t) { <del> return t.traversal(Functions.compose(ASSERT_NUMBER, Functions.fromMap(numbers2()))); <del> } <add> private static JBTreeTraverser<Integer> num2Traverser() { <add> return new JBTreeTraverser<>(Functions.compose(ASSERT_NUMBER, Functions.fromMap(numbers2()))).withRoot(1); <add> } <add> <ide> <ide> @NotNull <ide> private static JBIterable<TreeTraversal> allTraversals() { <ide> } <ide> <ide> public void testSimplePreOrderDfs() { <del> assertEquals(Arrays.asList(1, 2, 5, 6, 7, 3, 8, 9, 10, 4, 11, 12, 13), numTraverser(TreeTraversal.PRE_ORDER_DFS).fun(1).toList()); <add> assertEquals(Arrays.asList(1, 2, 5, 6, 7, 3, 8, 9, 10, 4, 11, 12, 13), numTraverser().toList()); <ide> } <ide> <ide> public void testSimpleBiOrderDfs() { <del> assertEquals(Arrays.asList(1, 2, 5, 5, 6, 6, 7, 7, 2, 3, 8, 8, 9, 9, 10, 10, 3, 4, 11, 11, 12, 12, 13, 13, 4, 1), numTraverser(TreeTraversal.BI_ORDER_DFS).fun(1).toList()); <add> assertEquals(Arrays.asList(1, 2, 5, 5, 6, 6, 7, 7, 2, 3, 8, 8, 9, 9, 10, 10, 3, 4, 11, 11, 12, 12, 13, 13, 4, 1), <add> numTraverser().withTraversal(TreeTraversal.BI_ORDER_DFS).toList()); <ide> } <ide> <ide> public void testSimpleBiOrderDfs2Roots() { <ide> <ide> public void testHarderBiOrderDfs() { <ide> StringBuilder sb = new StringBuilder(); <del> TreeTraversal.TracingIt<Integer> it = numTraverser(TreeTraversal.BI_ORDER_DFS).fun(1).typedIterator(); <add> TreeTraversal.TracingIt<Integer> it = numTraverser().withTraversal(TreeTraversal.BI_ORDER_DFS).traverse().typedIterator(); <ide> while (it.advance()) { <ide> if (sb.length() != 0) sb.append(", "); <ide> it.hasNext(); <ide> } <ide> <ide> public void testSimpleInterlacedDfs() { <del> assertEquals(Arrays.asList(1, 2, 5, 3, 6, 4, 8, 7, 9, 11, 10, 12, 13), numTraverser(TreeTraversal.INTERLEAVED_DFS).fun(1).toList()); <add> assertEquals(Arrays.asList(1, 2, 5, 3, 6, 4, 8, 7, 9, 11, 10, 12, 13), <add> numTraverser().withTraversal(TreeTraversal.INTERLEAVED_DFS).toList()); <ide> } <ide> <ide> public void testCyclicInterlacedDfs() { <ide> } <ide> <ide> public void testTreeBacktraceSimple() { <del> JBIterable<Integer> dfs = numTraverser2(TreeTraversal.PRE_ORDER_DFS).fun(1); <del> JBIterable<Integer> bfs = numTraverser2(TreeTraversal.TRACING_BFS).fun(1); <del> JBIterable<Integer> postDfs = numTraverser2(TreeTraversal.POST_ORDER_DFS).fun(1); <add> JBIterable<Integer> dfs = num2Traverser().withTraversal(TreeTraversal.PRE_ORDER_DFS).traverse(); <add> JBIterable<Integer> bfs = num2Traverser().withTraversal(TreeTraversal.TRACING_BFS).traverse(); <add> JBIterable<Integer> postDfs = num2Traverser().withTraversal(TreeTraversal.POST_ORDER_DFS).traverse(); <ide> <ide> TreeTraversal.TracingIt<Integer> it1 = dfs.typedIterator(); <ide> assertEquals(new Integer(37), it1.skipWhile(Conditions.notEqualTo(37)).next()); <ide> } <ide> <ide> public void testTreeBacktraceTransformed() { <del> JBIterable<String> dfs = numTraverser2(TreeTraversal.PRE_ORDER_DFS).fun(1).transform(Functions.TO_STRING()); <del> JBIterable<String> bfs = numTraverser2(TreeTraversal.TRACING_BFS).fun(1).transform(Functions.TO_STRING()); <add> JBIterable<String> dfs = num2Traverser().withTraversal(TreeTraversal.PRE_ORDER_DFS).traverse().map(Functions.TO_STRING()); <add> JBIterable<String> bfs = num2Traverser().withTraversal(TreeTraversal.TRACING_BFS).traverse().map(Functions.TO_STRING()); <ide> <ide> TreeTraversal.TracingIt<String> it1 = dfs.typedIterator(); <ide> it1.skipWhile(Conditions.notEqualTo("37")).next(); <ide> } <ide> <ide> public void testSimplePostOrderDfs() { <del> assertEquals(Arrays.asList(5, 6, 7, 2, 8, 9, 10, 3, 11, 12, 13, 4, 1), numTraverser(TreeTraversal.POST_ORDER_DFS).fun(1).toList()); <add> assertEquals(Arrays.asList(5, 6, 7, 2, 8, 9, 10, 3, 11, 12, 13, 4, 1), <add> numTraverser().withTraversal(TreeTraversal.POST_ORDER_DFS).toList()); <ide> } <ide> <ide> public void testSimpleBfs() { <del> assertEquals(JBIterable.generate(1, INCREMENT).take(37).toList(), numTraverser2(TreeTraversal.PLAIN_BFS).fun(1).toList()); <add> assertEquals(JBIterable.generate(1, INCREMENT).take(37).toList(), <add> num2Traverser().withTraversal(TreeTraversal.PLAIN_BFS).toList()); <ide> } <ide> <ide> public void testSimpleBfsLaziness() { <ide> } <ide> <ide> public void testTraverseUnique() { <del> assertEquals(Arrays.asList(1, 2, 5, 6, 7, 3, 8, 9, 10, 4, 11, 12, 13), numTraverser(TreeTraversal.PRE_ORDER_DFS.unique()).fun(1).toList()); <del> JBIterable<Integer> uniqueMod5 = numTraverser(TreeTraversal.PRE_ORDER_DFS.unique((Integer o) -> o % 5)).fun(1); <del> assertEquals(Arrays.asList(1, 2, 5, 3, 9), uniqueMod5.toList()); <del> assertEquals(Arrays.asList(1, 2, 5, 3, 9), uniqueMod5.toList()); // same results again <del> <del> JBIterable<Integer> uniqueMod57 = numTraverser(TreeTraversal.PRE_ORDER_DFS.unique((Integer o) -> o % 5).unique((Integer o) -> o % 7)).fun(1); <del> JBIterable<Integer> uniqueMod75 = numTraverser(TreeTraversal.PRE_ORDER_DFS.unique((Integer o) -> o % 7).unique((Integer o) -> o % 5)).fun(1); <del> assertEquals(Arrays.asList(1, 2, 5, 3, 4), uniqueMod57.toList()); <del> assertEquals(Arrays.asList(1, 2, 5, 3), uniqueMod75.toList()); <del> <del> assertEquals(JBIterable.generate(1, INCREMENT).take(37).toList(), numTraverser2(TreeTraversal.PLAIN_BFS.unique()).fun(1).toList()); <del> assertEquals(JBIterable.generate(1, INCREMENT).take(37).toList(), numTraverser2(TreeTraversal.PLAIN_BFS.unique().unique()).fun(1).toList()); <add> assertEquals(Arrays.asList(1, 2, 5, 6, 7, 3, 8, 9, 10, 4, 11, 12, 13), numTraverser().unique().toList()); <add> JBIterable<Integer> t0 = numTraverser().unique(o -> o % 5).traverse(); <add> assertEquals(Arrays.asList(1, 2, 5, 3, 9), t0.toList()); <add> assertEquals(Arrays.asList(1, 2, 5, 3, 9), t0.toList()); // same results again <add> <add> JBIterable<Integer> t1 = numTraverser().unique(o -> o % 5).unique(o -> o % 7).traverse(); <add> JBIterable<Integer> t2 = numTraverser().unique(o -> o % 7).unique(o -> o % 5).traverse(); <add> assertEquals(Arrays.asList(1, 2, 5, 3, 4), t1.toList()); <add> assertEquals(Arrays.asList(1, 2, 5, 3), t2.toList()); <add> <add> TreeTraversal preOrder = TreeTraversal.PRE_ORDER_DFS; <add> assertEquals(t1.toList(), numTraverser().traverse(preOrder.unique(o -> ((int)o) % 5).unique(o -> ((int)o) % 7)).toList()); <add> assertEquals(t2.toList(), numTraverser().traverse(preOrder.unique(o -> ((int)o) % 7).unique(o -> ((int)o) % 5)).toList()); <add> <add> assertEquals(JBIterable.generate(1, INCREMENT).take(37).toList(), <add> num2Traverser().withTraversal(TreeTraversal.PLAIN_BFS.unique()).toList()); <add> assertEquals(JBIterable.generate(1, INCREMENT).take(37).toList(), <add> num2Traverser().withTraversal(TreeTraversal.PLAIN_BFS.unique().unique()).toList()); <ide> } <ide> <ide> public void testTraverseMap() { <ide> Condition<String> notEmpty = o -> !o.isEmpty(); <ide> Condition<String> isThirteen = o -> "13".equals(o); <del> JBTreeTraverser<Integer> t = numberTraverser().withRoot(1).filter(IS_ODD).regard(IS_POSITIVE); <add> JBTreeTraverser<Integer> t = numTraverser().filter(IS_ODD).regard(IS_POSITIVE); <ide> JBTreeTraverser<String> mappedA = t.map(String::valueOf, Integer::parseInt); <ide> JBTreeTraverser<String> mappedB = t.map(String::valueOf); <ide> JBTreeTraverser<Integer> mapped2A = mappedA.map(Integer::parseInt); <ide> } <ide> <ide> public void testTraverseMapStateful() { <del> JBTreeTraverser<Integer> t = numberTraverser().withRoot(1); <add> JBTreeTraverser<Integer> t = numTraverser(); <ide> class F extends JBIterable.SFun<Integer, String> { <ide> int count; <ide> <ide> } <ide> <ide> private static void verifyGuidedTraversal(TreeTraversal traversal) { <del> assertEquals(numTraverser2(TreeTraversal.GUIDED_TRAVERSAL(newGuide(traversal))).fun(1).toList(), <del> numTraverser2(traversal).fun(1).toList()); <add> assertEquals(num2Traverser().withTraversal(TreeTraversal.GUIDED_TRAVERSAL(newGuide(traversal))).toList(), <add> num2Traverser().withTraversal(traversal).toList()); <ide> } <ide> <ide> <ide> // FilteredTraverser ---------------------------------------------- <del> <del> @NotNull <del> private static JBTreeTraverser<Integer> numberTraverser() { <del> return new JBTreeTraverser<>(Functions.compose(ASSERT_NUMBER, Functions.fromMap(numbers()))); <del> } <ide> <ide> @NotNull <ide> public JBTreeTraverser<TextRange> rangeTraverser() { <ide> } <ide> <ide> public void testSimpleFilter() { <del> JBTreeTraverser<Integer> t = numberTraverser(); <del> assertEquals(Arrays.asList(1, 5, 7, 3, 9, 11, 13), t.withRoot(1).filter(IS_ODD).toList()); <add> assertEquals(Arrays.asList(1, 5, 7, 3, 9, 11, 13), numTraverser().filter(IS_ODD).toList()); <ide> } <ide> <ide> public void testSimpleExpand() { <del> JBTreeTraverser<Integer> t = numberTraverser(); <del> assertEquals(Arrays.asList(1, 2, 3, 8, 9, 10, 4), t.withRoot(1).expand(IS_ODD).toList()); <add> assertEquals(Arrays.asList(1, 2, 3, 8, 9, 10, 4), numTraverser().expand(IS_ODD).toList()); <ide> } <ide> <ide> public void testExpandFilter() { <del> JBTreeTraverser<Integer> t = numberTraverser(); <del> assertEquals(Arrays.asList(1, 3, 9), t.withRoot(1).expand(IS_ODD).filter(IS_ODD).toList()); <del> assertEquals(Arrays.asList(1, 3, 9), t.withRoot(1).expandAndFilter(IS_ODD).toList()); <add> assertEquals(Arrays.asList(1, 3, 9), numTraverser().expand(IS_ODD).filter(IS_ODD).toList()); <add> assertEquals(Arrays.asList(1, 3, 9), numTraverser().expandAndFilter(IS_ODD).toList()); <ide> } <ide> <ide> public void testSkipExpandedDfs() { <del> JBTreeTraverser<Integer> t = numberTraverser(); <del> assertEquals(Arrays.asList(2, 8, 9, 10, 4), t.withRoot(1).expand(IS_ODD).traverse(TreeTraversal.LEAVES_DFS).toList()); <add> assertEquals(Arrays.asList(2, 8, 9, 10, 4), numTraverser().expand(IS_ODD).traverse(TreeTraversal.LEAVES_DFS).toList()); <ide> } <ide> <ide> public void testOnRange() { <del> assertEquals(13, numberTraverser().withRoot(1).onRange(o -> true).traverse().size()); <add> assertEquals(13, numTraverser().onRange(o -> true).traverse().size()); <ide> JBTreeTraverser<TextRange> ranges = rangeTraverser(); <ide> assertEquals(5, ranges.withRoot(TextRange.from(0, 8)).traverse().size()); <ide> assertEquals(Arrays.asList("(0,64)", "(16,32)", "(28,32)", "(29,30)", "(30,31)", "(31,32)", "(32,48)", "(32,36)", "(32,33)", "(33,34)"), <ide> } <ide> <ide> public void testRangeChildrenLeavesDfs() { <del> JBTreeTraverser<Integer> t = numberTraverser(); <del> assertEquals(Arrays.asList(5, 6, 3, 11, 12, 13), t.withRoot(1).regard(not(inRange(7, 10))).traverse(TreeTraversal.LEAVES_DFS).toList()); <add> assertEquals(Arrays.asList(5, 6, 3, 11, 12, 13), <add> numTraverser().regard(not(inRange(7, 10))).traverse(TreeTraversal.LEAVES_DFS).toList()); <ide> } <ide> <ide> public void testRangeChildrenLeavesBfs() { <del> JBTreeTraverser<Integer> t = numberTraverser(); <del> assertEquals(Arrays.asList(5, 6, 3, 11, 12, 13), t.withRoot(1).regard(not(inRange(7, 10))).traverse(TreeTraversal.LEAVES_DFS).toList()); <add> assertEquals(Arrays.asList(5, 6, 3, 11, 12, 13), <add> numTraverser().regard(not(inRange(7, 10))).traverse(TreeTraversal.LEAVES_DFS).toList()); <ide> } <ide> <ide> public void testHideOneNodeDfs() { <del> JBTreeTraverser<Integer> t = numberTraverser(); <del> assertEquals(Arrays.asList(1, 2, 5, 6, 7, 4, 11, 12, 13), t.withRoot(1).expandAndFilter(x -> x != 3).traverse(TreeTraversal.PRE_ORDER_DFS).toList()); <add> assertEquals(Arrays.asList(1, 2, 5, 6, 7, 4, 11, 12, 13), <add> numTraverser().expandAndFilter(x -> x != 3).traverse(TreeTraversal.PRE_ORDER_DFS).toList()); <ide> } <ide> <ide> public void testHideOneNodeCompletelyBfs() { <del> JBTreeTraverser<Integer> t = numberTraverser(); <del> assertEquals(Arrays.asList(1, 2, 4, 5, 6, 7, 11, 12, 13), t.withRoot(1).expandAndFilter(x -> x != 3).traverse(TreeTraversal.PLAIN_BFS).toList()); <add> assertEquals(Arrays.asList(1, 2, 4, 5, 6, 7, 11, 12, 13), <add> numTraverser().expandAndFilter(x -> x != 3).traverse(TreeTraversal.PLAIN_BFS).toList()); <ide> } <ide> <ide> public void testSkipExpandedCompletelyBfs() { <del> JBTreeTraverser<Integer> t = numberTraverser(); <del> assertEquals(Arrays.asList(2, 4, 8, 9, 10), t.withRoot(1).expand(IS_ODD).traverse(TreeTraversal.LEAVES_BFS).toList()); <add> assertEquals(Arrays.asList(2, 4, 8, 9, 10), numTraverser().expand(IS_ODD).traverse(TreeTraversal.LEAVES_BFS).toList()); <ide> } <ide> <ide> public void testExpandSkipFilterReset() { <del> JBTreeTraverser<Integer> t = numberTraverser(); <del> assertEquals(Arrays.asList(1, 5, 7, 3, 9, 11, 13), t.withRoot(1).expand(IS_ODD). <del> withTraversal(TreeTraversal.LEAVES_DFS).reset().filter(IS_ODD).toList()); <del> } <del> <del> public void testForceExlcudeReset() { <del> JBTreeTraverser<Integer> t = numberTraverser(); <del> assertEquals(Arrays.asList(1, 2, 6, 4, 12), t.withRoot(1).forceIgnore(IS_ODD).reset().toList()); <add> assertEquals(Arrays.asList(1, 5, 7, 3, 9, 11, 13), <add> numTraverser().expand(IS_ODD).withTraversal(TreeTraversal.LEAVES_DFS).reset().filter(IS_ODD).toList()); <add> } <add> <add> public void testForceExcludeReset() { <add> assertEquals(Arrays.asList(1, 2, 6, 4, 12), numTraverser().forceIgnore(IS_ODD).reset().toList()); <ide> } <ide> <ide> public void testForceSkipReset() { <del> JBTreeTraverser<Integer> t = numberTraverser(); <del> assertEquals(Arrays.asList(1, 2, 6, 8, 10, 4, 12), t.withRoot(1).forceDisregard(IS_ODD).reset().toList()); <add> assertEquals(Arrays.asList(1, 2, 6, 8, 10, 4, 12), numTraverser().forceDisregard(IS_ODD).reset().toList()); <ide> } <ide> <ide> public void testForceSkipLeavesDfs() { <del> JBTreeTraverser<Integer> t = numberTraverser(); <del> assertEquals(Arrays.asList(6, 8, 10, 12), t.withRoot(1).forceDisregard(IS_ODD).traverse(TreeTraversal.LEAVES_DFS).toList()); <add> assertEquals(Arrays.asList(6, 8, 10, 12), numTraverser().forceDisregard(IS_ODD).traverse(TreeTraversal.LEAVES_DFS).toList()); <ide> } <ide> <ide> public void testFilterChildren() { <del> JBTreeTraverser<Integer> t = numberTraverser(); <del> assertEquals(Arrays.asList(1, 5, 7, 3, 9, 11, 13), t.withRoot(1).regard(IS_ODD).toList()); <add> assertEquals(Arrays.asList(1, 5, 7, 3, 9, 11, 13), numTraverser().regard(IS_ODD).toList()); <ide> } <ide> <ide> public void testEndlessGraph() { <del> JBTreeTraverser<Integer> t = new JBTreeTraverser<>(k -> JBIterable.generate(k, INCREMENT).transform(SQUARE).take(3)); <add> JBTreeTraverser<Integer> t = new JBTreeTraverser<>(k -> JBIterable.generate(k, INCREMENT).map(SQUARE).take(3)); <ide> assertEquals(Arrays.asList(1, 1, 4, 9, 1, 4, 9, 16, 25, 36, 81), t.withRoot(1).bfsTraversal().take(11).toList()); <ide> } <ide> <ide> } <ide> <ide> public void testEdgeFilter() { <del> JBTreeTraverser<Integer> t = numberTraverser(); <add> JBTreeTraverser<Integer> t = numTraverser(); <ide> JBIterable<Integer> it = t.regard(new FilteredTraverserBase.EdgeFilter<Integer>() { <ide> @Override <ide> public boolean value(Integer integer) { <ide> return (integer / edgeSource) % 2 == 0; <ide> } <del> }).withRoot(1).traverse(); <add> }).traverse(); <ide> assertEquals(Arrays.asList(1, 2, 5, 8, 10, 4, 11), it.toList()); <ide> assertEquals(Arrays.asList(1, 2, 5, 8, 10, 4, 11), it.toList()); <ide> } <ide> <ide> public void testStatefulChildFilter() { <del> JBTreeTraverser<Integer> t = numberTraverser(); <add> JBTreeTraverser<Integer> t = numTraverser(); <ide> class F extends JBIterable.SCond<Integer> { <ide> int count; <del> boolean value; <add> final boolean value; <ide> F(boolean initialVal) { value = initialVal; } <ide> <ide> @Override <ide> } <ide> } <ide> <del> JBIterable<Integer> it = t.regard(new F(true)).withRoot(1).traverse(); <add> JBIterable<Integer> it = t.regard(new F(true)).traverse(); <ide> assertEquals(Arrays.asList(1, 5, 6, 7, 3, 9, 10, 4, 12, 13), it.toList()); <ide> assertEquals(Arrays.asList(1, 5, 6, 7, 3, 9, 10, 4, 12, 13), it.toList()); <del> assertEquals(it.toList(), t.forceDisregard(new F(false)).withRoot(1).reset().traverse().toList()); <add> assertEquals(it.toList(), t.forceDisregard(new F(false)).reset().toList()); <ide> } <ide> <ide> }
Java
mit
b9e4b72a60aa335b61d8abfaa98f42faa823c102
0
GlobalTechnology/android-gto-support,CruGlobal/android-gto-support,CruGlobal/android-gto-support
package org.ccci.gto.android.common.api; import android.annotation.TargetApi; import android.content.Context; import android.content.SharedPreferences; import android.net.Uri; import android.os.Build; import android.support.annotation.NonNull; import android.support.annotation.Nullable; import org.ccci.gto.android.common.api.AbstractApi.Request; import org.ccci.gto.android.common.api.AbstractApi.Session; import org.ccci.gto.android.common.util.IOUtils; import org.ccci.gto.android.common.util.UriUtils; import java.io.IOException; import java.io.OutputStream; import java.io.UnsupportedEncodingException; import java.net.HttpURLConnection; import java.net.MalformedURLException; import java.net.URL; import java.util.ArrayList; import java.util.Collection; import java.util.List; public abstract class AbstractApi<R extends Request<S>, S extends Session> { private static final int DEFAULT_ATTEMPTS = 3; protected static final String PREF_SESSION_BASE_NAME = "session"; protected final Object LOCK_SESSION = new Object(); @NonNull private final Context mContext; @NonNull private final Uri mBaseUri; @NonNull private final String mPrefFile; protected AbstractApi(@NonNull final Context context, @NonNull final String baseUri) { this(context, baseUri, null); } protected AbstractApi(@NonNull final Context context, @NonNull final String baseUri, @Nullable final String prefFile) { this(context, Uri.parse(baseUri.endsWith("/") ? baseUri : baseUri + "/"), prefFile); } protected AbstractApi(@NonNull final Context context, @NonNull final Uri baseUri) { this(context, baseUri, null); } protected AbstractApi(@NonNull final Context context, @NonNull final Uri baseUri, @Nullable final String prefFile) { this.mContext = context; this.mBaseUri = baseUri; this.mPrefFile = prefFile != null ? prefFile : getClass().getSimpleName(); } private SharedPreferences getPrefs() { return mContext.getSharedPreferences(mPrefFile, Context.MODE_PRIVATE); } @NonNull protected final HttpURLConnection sendRequest(@NonNull final R request) throws ApiException { return this.sendRequest(request, DEFAULT_ATTEMPTS); } @NonNull protected final HttpURLConnection sendRequest(@NonNull final R request, final int attempts) throws ApiException { try { HttpURLConnection conn = null; boolean successful = false; try { // load/establish the session if we are using sessions if (request.useSession) { // prepare for the session this.onPrepareSession(request); // get the session, establish a session if one doesn't exist or if we have a stale session synchronized (LOCK_SESSION) { request.session = loadSession(request); if (request.session == null) { request.session = this.establishSession(request); // save the newly established session if (request.session != null) { this.saveSession(request.session); } } } // throw an exception if we don't have a valid session if (request.session == null) { throw new InvalidSessionApiException(); } } // build the request uri final Uri.Builder uri = mBaseUri.buildUpon(); onPrepareUri(uri, request); final URL url; try { url = new URL(uri.build().toString()); } catch (final MalformedURLException e) { throw new RuntimeException("invalid Request URL: " + uri.build().toString(), e); } // prepare the request conn = (HttpURLConnection) url.openConnection(); onPrepareRequest(conn, request); // POST/PUT requests if (request.method == Request.Method.POST || request.method == Request.Method.PUT) { conn.setDoOutput(true); final byte[] data = request.content != null ? request.content : new byte[0]; conn.setFixedLengthStreamingMode(data.length); conn.setUseCaches(false); OutputStream out = null; try { out = conn.getOutputStream(); out.write(data); } finally { // XXX: don't use IOUtils.closeQuietly, we want exceptions thrown if (out != null) { out.close(); } } } // no need to explicitly execute, accessing the response triggers the execute // check for an invalid session if (request.useSession && this.isSessionInvalid(conn, request)) { // reset the session synchronized (LOCK_SESSION) { // only reset if this is still the same session final Session current = this.loadSession(request); if (current != null && current.equals(request.session)) { this.deleteSession(request.session); } } // throw an invalid session exception throw new InvalidSessionApiException(); } // process the response onProcessResponse(conn, request); // return the connection for method specific handling successful = true; return conn; } catch (final IOException e) { throw new ApiSocketException(e); } finally { // close a potentially open connection if we weren't successful if (!successful) { IOUtils.closeQuietly(conn); } // clear out the session that was loaded & used request.session = null; // cleanup any request specific data onCleanupRequest(request); } } catch (final ApiException e) { // retry request on an API exception if (attempts > 0) { return this.sendRequest(request, attempts - 1); } // propagate the exception throw e; } } @NonNull protected final Request.Parameter param(@NonNull final String name, @NonNull final String value) { return new Request.Parameter(name, value); } @Nullable protected S loadSession(@NonNull final R request) { // load a pre-existing session final SharedPreferences prefs = this.getPrefs(); final S session; synchronized (LOCK_SESSION) { session = this.loadSession(prefs, request); } // only return valid sessions return session != null && session.id != null ? session : null; } @Nullable protected abstract S loadSession(@NonNull SharedPreferences prefs, @NonNull R request); @Nullable protected S establishSession(@NonNull final R request) throws ApiException { return null; } @TargetApi(Build.VERSION_CODES.GINGERBREAD) private void saveSession(@NonNull final S session) { final SharedPreferences.Editor prefs = this.getPrefs().edit(); session.save(prefs); synchronized (LOCK_SESSION) { // store updates if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.GINGERBREAD) { prefs.apply(); } else { prefs.commit(); } } } @TargetApi(Build.VERSION_CODES.GINGERBREAD) private void deleteSession(@NonNull final S session) { final SharedPreferences.Editor prefs = this.getPrefs().edit(); session.delete(prefs); synchronized (LOCK_SESSION) { // store updates if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.GINGERBREAD) { prefs.apply(); } else { prefs.commit(); } } } protected boolean isSessionInvalid(@NonNull final HttpURLConnection conn, final R request) { return false; } /* BEGIN request lifecycle events */ protected void onPrepareSession(@NonNull final R request) throws ApiException { } protected void onPrepareUri(@NonNull final Uri.Builder uri, @NonNull final R request) throws ApiException { // build the request uri uri.appendEncodedPath(request.path); if (request.params.size() > 0) { if (request.replaceParams) { final List<String> keys = new ArrayList<>(); for (final Request.Parameter param : request.params) { keys.add(param.name); } UriUtils.removeQueryParams(uri, keys.toArray(new String[keys.size()])); } for (final Request.Parameter param : request.params) { uri.appendQueryParameter(param.name, param.value); } } } protected void onPrepareRequest(@NonNull final HttpURLConnection conn, @NonNull final R request) throws ApiException, IOException { // build base request object conn.setRequestMethod(request.method.toString()); if (request.accept != null) { conn.addRequestProperty("Accept", request.accept.type); } if (request.contentType != null) { conn.addRequestProperty("Content-Type", request.contentType.type); } conn.setInstanceFollowRedirects(request.followRedirects); } protected void onProcessResponse(@NonNull final HttpURLConnection conn, @NonNull final R request) throws ApiException, IOException { } protected void onCleanupRequest(@NonNull final R request) { } /* END request lifecycle events */ protected static class Session { @NonNull private final String baseAttrName; @Nullable public final String id; protected Session(@Nullable final String id) { this(id, PREF_SESSION_BASE_NAME); } protected Session(@Nullable final String id, @Nullable final String baseAttrName) { this.baseAttrName = baseAttrName != null ? baseAttrName : PREF_SESSION_BASE_NAME; this.id = id; } protected Session(@NonNull final SharedPreferences prefs) { this(prefs, null); } protected Session(@NonNull final SharedPreferences prefs, @Nullable final String baseAttrName) { this.baseAttrName = baseAttrName != null ? baseAttrName : PREF_SESSION_BASE_NAME; this.id = prefs.getString(getPrefAttrName("id"), null); } protected final String getPrefAttrName(@NonNull final String type) { return baseAttrName + "." + type; } protected void save(@NonNull final SharedPreferences.Editor prefs) { prefs.putString(getPrefAttrName("id"), this.id); } protected void delete(@NonNull final SharedPreferences.Editor prefs) { prefs.remove(getPrefAttrName("id")); } @Override public boolean equals(final Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } final Session that = (Session) o; return baseAttrName.equals(that.baseAttrName) && !(id != null ? !id.equals(that.id) : that.id != null); } } protected static class Request<S extends Session> { public enum Method {GET, POST, PUT, DELETE} public enum MediaType { APPLICATION_FORM_URLENCODED("application/x-www-form-urlencoded"), APPLICATION_JSON("application/json"), APPLICATION_XML("application/xml"), TEXT_PLAIN("text/plain"); final String type; private MediaType(final String type) { this.type = type; } } protected static final class Parameter { final String name; final String value; public Parameter(@NonNull final String name, @NonNull final String value) { this.name = name; this.value = value; } } @NonNull public Method method = Method.GET; // uri attributes @NonNull final String path; public final Collection<Parameter> params = new ArrayList<>(); public boolean replaceParams = false; // POST/PUT data MediaType contentType = null; byte[] content = null; // session attributes public boolean useSession = false; @Nullable public S session = null; // miscellaneous attributes @Nullable public MediaType accept = null; public boolean followRedirects = false; public Request(@NonNull final String path) { this.path = path; } protected void setContent(final MediaType type, final byte[] data) { this.contentType = type; this.content = data; } protected void setContent(final MediaType type, final String data) { try { this.setContent(type, data != null ? data.getBytes("UTF-8") : null); } catch (final UnsupportedEncodingException e) { throw new RuntimeException("unexpected error, UTF-8 encoding isn't present", e); } } } }
src/main/java/org/ccci/gto/android/common/api/AbstractApi.java
package org.ccci.gto.android.common.api; import android.annotation.TargetApi; import android.content.Context; import android.content.SharedPreferences; import android.net.Uri; import android.os.Build; import android.support.annotation.NonNull; import android.support.annotation.Nullable; import org.ccci.gto.android.common.api.AbstractApi.Request; import org.ccci.gto.android.common.api.AbstractApi.Session; import org.ccci.gto.android.common.util.IOUtils; import org.ccci.gto.android.common.util.UriUtils; import java.io.IOException; import java.io.OutputStream; import java.io.UnsupportedEncodingException; import java.net.HttpURLConnection; import java.net.MalformedURLException; import java.net.URL; import java.util.ArrayList; import java.util.Collection; import java.util.List; public abstract class AbstractApi<R extends Request<S>, S extends Session> { private static final int DEFAULT_ATTEMPTS = 3; protected static final String PREF_SESSION_BASE_NAME = "session"; protected final Object LOCK_SESSION = new Object(); @NonNull private final Context mContext; @NonNull private final Uri mBaseUri; @NonNull private final String mPrefFile; protected AbstractApi(@NonNull final Context context, @NonNull final String baseUri) { this(context, baseUri, null); } protected AbstractApi(@NonNull final Context context, @NonNull final String baseUri, @Nullable final String prefFile) { this(context, Uri.parse(baseUri.endsWith("/") ? baseUri : baseUri + "/"), prefFile); } protected AbstractApi(@NonNull final Context context, @NonNull final Uri baseUri) { this(context, baseUri, null); } protected AbstractApi(@NonNull final Context context, @NonNull final Uri baseUri, @Nullable final String prefFile) { this.mContext = context; this.mBaseUri = baseUri; this.mPrefFile = prefFile != null ? prefFile : getClass().getSimpleName(); } private SharedPreferences getPrefs() { return mContext.getSharedPreferences(mPrefFile, Context.MODE_PRIVATE); } @NonNull protected final HttpURLConnection sendRequest(@NonNull final R request) throws ApiException { return this.sendRequest(request, DEFAULT_ATTEMPTS); } @NonNull protected final HttpURLConnection sendRequest(@NonNull final R request, final int attempts) throws ApiException { HttpURLConnection conn = null; boolean successful = false; try { // load/establish the session if we are using sessions if (request.useSession) { // prepare for the session this.onPrepareSession(request); // get the session, establish a session if one doesn't exist or if we have a stale session synchronized (LOCK_SESSION) { request.session = loadSession(request); if (request.session == null) { request.session = this.establishSession(request); // save the newly established session if (request.session != null) { this.saveSession(request.session); } } } // throw an exception if we don't have a valid session if (request.session == null) { throw new InvalidSessionApiException(); } } // build the request uri final Uri.Builder uri = mBaseUri.buildUpon(); onPrepareUri(uri, request); final URL url; try { url = new URL(uri.build().toString()); } catch (final MalformedURLException e) { throw new RuntimeException("invalid Request URL: " + uri.build().toString(), e); } // prepare the request conn = (HttpURLConnection) url.openConnection(); onPrepareRequest(conn, request); // POST/PUT requests if (request.method == Request.Method.POST || request.method == Request.Method.PUT) { conn.setDoOutput(true); final byte[] data = request.content != null ? request.content : new byte[0]; conn.setFixedLengthStreamingMode(data.length); conn.setUseCaches(false); OutputStream out = null; try { out = conn.getOutputStream(); out.write(data); } finally { // XXX: don't use IOUtils.closeQuietly, we want exceptions thrown if (out != null) { out.close(); } } } // no need to explicitly execute, accessing the response triggers the execute // check for an invalid session if (request.useSession && this.isSessionInvalid(conn, request)) { // reset the session synchronized (LOCK_SESSION) { // only reset if this is still the same session final Session current = this.loadSession(request); if (current != null && current.equals(request.session)) { this.deleteSession(request.session); } } // throw an invalid session exception throw new InvalidSessionApiException(); } // process the response onProcessResponse(conn, request); // return the connection for method specific handling successful = true; return conn; } catch (final IOException e) { throw new ApiSocketException(e); } finally { // close a potentially open connection if we weren't successful if(!successful) { IOUtils.closeQuietly(conn); } // clear out the session that was loaded & used request.session = null; // cleanup any request specific data onCleanupRequest(request); } } @NonNull protected final Request.Parameter param(@NonNull final String name, @NonNull final String value) { return new Request.Parameter(name, value); } @Nullable protected S loadSession(@NonNull final R request) { // load a pre-existing session final SharedPreferences prefs = this.getPrefs(); final S session; synchronized (LOCK_SESSION) { session = this.loadSession(prefs, request); } // only return valid sessions return session != null && session.id != null ? session : null; } @Nullable protected abstract S loadSession(@NonNull SharedPreferences prefs, @NonNull R request); @Nullable protected S establishSession(@NonNull final R request) throws ApiException { return null; } @TargetApi(Build.VERSION_CODES.GINGERBREAD) private void saveSession(@NonNull final S session) { final SharedPreferences.Editor prefs = this.getPrefs().edit(); session.save(prefs); synchronized (LOCK_SESSION) { // store updates if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.GINGERBREAD) { prefs.apply(); } else { prefs.commit(); } } } @TargetApi(Build.VERSION_CODES.GINGERBREAD) private void deleteSession(@NonNull final S session) { final SharedPreferences.Editor prefs = this.getPrefs().edit(); session.delete(prefs); synchronized (LOCK_SESSION) { // store updates if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.GINGERBREAD) { prefs.apply(); } else { prefs.commit(); } } } protected boolean isSessionInvalid(@NonNull final HttpURLConnection conn, final R request) { return false; } /* BEGIN request lifecycle events */ protected void onPrepareSession(@NonNull final R request) throws ApiException { } protected void onPrepareUri(@NonNull final Uri.Builder uri, @NonNull final R request) throws ApiException { // build the request uri uri.appendEncodedPath(request.path); if (request.params.size() > 0) { if (request.replaceParams) { final List<String> keys = new ArrayList<>(); for (final Request.Parameter param : request.params) { keys.add(param.name); } UriUtils.removeQueryParams(uri, keys.toArray(new String[keys.size()])); } for (final Request.Parameter param : request.params) { uri.appendQueryParameter(param.name, param.value); } } } protected void onPrepareRequest(@NonNull final HttpURLConnection conn, @NonNull final R request) throws ApiException, IOException { // build base request object conn.setRequestMethod(request.method.toString()); if (request.accept != null) { conn.addRequestProperty("Accept", request.accept.type); } if (request.contentType != null) { conn.addRequestProperty("Content-Type", request.contentType.type); } conn.setInstanceFollowRedirects(request.followRedirects); } protected void onProcessResponse(@NonNull final HttpURLConnection conn, @NonNull final R request) throws ApiException, IOException { } protected void onCleanupRequest(@NonNull final R request) { } /* END request lifecycle events */ protected static class Session { @NonNull private final String baseAttrName; @Nullable public final String id; protected Session(@Nullable final String id) { this(id, PREF_SESSION_BASE_NAME); } protected Session(@Nullable final String id, @Nullable final String baseAttrName) { this.baseAttrName = baseAttrName != null ? baseAttrName : PREF_SESSION_BASE_NAME; this.id = id; } protected Session(@NonNull final SharedPreferences prefs) { this(prefs, null); } protected Session(@NonNull final SharedPreferences prefs, @Nullable final String baseAttrName) { this.baseAttrName = baseAttrName != null ? baseAttrName : PREF_SESSION_BASE_NAME; this.id = prefs.getString(getPrefAttrName("id"), null); } protected final String getPrefAttrName(@NonNull final String type) { return baseAttrName + "." + type; } protected void save(@NonNull final SharedPreferences.Editor prefs) { prefs.putString(getPrefAttrName("id"), this.id); } protected void delete(@NonNull final SharedPreferences.Editor prefs) { prefs.remove(getPrefAttrName("id")); } @Override public boolean equals(final Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } final Session that = (Session) o; return baseAttrName.equals(that.baseAttrName) && !(id != null ? !id.equals(that.id) : that.id != null); } } protected static class Request<S extends Session> { public enum Method {GET, POST, PUT, DELETE} public enum MediaType { APPLICATION_FORM_URLENCODED("application/x-www-form-urlencoded"), APPLICATION_JSON("application/json"), APPLICATION_XML("application/xml"), TEXT_PLAIN("text/plain"); final String type; private MediaType(final String type) { this.type = type; } } protected static final class Parameter { final String name; final String value; public Parameter(@NonNull final String name, @NonNull final String value) { this.name = name; this.value = value; } } @NonNull public Method method = Method.GET; // uri attributes @NonNull final String path; public final Collection<Parameter> params = new ArrayList<>(); public boolean replaceParams = false; // POST/PUT data MediaType contentType = null; byte[] content = null; // session attributes public boolean useSession = false; @Nullable public S session = null; // miscellaneous attributes @Nullable public MediaType accept = null; public boolean followRedirects = false; public Request(@NonNull final String path) { this.path = path; } protected void setContent(final MediaType type, final byte[] data) { this.contentType = type; this.content = data; } protected void setContent(final MediaType type, final String data) { try { this.setContent(type, data != null ? data.getBytes("UTF-8") : null); } catch (final UnsupportedEncodingException e) { throw new RuntimeException("unexpected error, UTF-8 encoding isn't present", e); } } } }
retry request on ApiException
src/main/java/org/ccci/gto/android/common/api/AbstractApi.java
retry request on ApiException
<ide><path>rc/main/java/org/ccci/gto/android/common/api/AbstractApi.java <ide> @NonNull <ide> protected final HttpURLConnection sendRequest(@NonNull final R request, final int attempts) <ide> throws ApiException { <del> HttpURLConnection conn = null; <del> boolean successful = false; <ide> try { <del> // load/establish the session if we are using sessions <del> if (request.useSession) { <del> // prepare for the session <del> this.onPrepareSession(request); <del> <del> // get the session, establish a session if one doesn't exist or if we have a stale session <del> synchronized (LOCK_SESSION) { <del> request.session = loadSession(request); <del> if (request.session == null) { <del> request.session = this.establishSession(request); <del> <del> // save the newly established session <del> if (request.session != null) { <del> this.saveSession(request.session); <add> HttpURLConnection conn = null; <add> boolean successful = false; <add> try { <add> // load/establish the session if we are using sessions <add> if (request.useSession) { <add> // prepare for the session <add> this.onPrepareSession(request); <add> <add> // get the session, establish a session if one doesn't exist or if we have a stale session <add> synchronized (LOCK_SESSION) { <add> request.session = loadSession(request); <add> if (request.session == null) { <add> request.session = this.establishSession(request); <add> <add> // save the newly established session <add> if (request.session != null) { <add> this.saveSession(request.session); <add> } <ide> } <ide> } <del> } <del> <del> // throw an exception if we don't have a valid session <del> if (request.session == null) { <add> <add> // throw an exception if we don't have a valid session <add> if (request.session == null) { <add> throw new InvalidSessionApiException(); <add> } <add> } <add> <add> // build the request uri <add> final Uri.Builder uri = mBaseUri.buildUpon(); <add> onPrepareUri(uri, request); <add> final URL url; <add> try { <add> url = new URL(uri.build().toString()); <add> } catch (final MalformedURLException e) { <add> throw new RuntimeException("invalid Request URL: " + uri.build().toString(), e); <add> } <add> <add> // prepare the request <add> conn = (HttpURLConnection) url.openConnection(); <add> onPrepareRequest(conn, request); <add> <add> // POST/PUT requests <add> if (request.method == Request.Method.POST || request.method == Request.Method.PUT) { <add> conn.setDoOutput(true); <add> final byte[] data = request.content != null ? request.content : new byte[0]; <add> conn.setFixedLengthStreamingMode(data.length); <add> conn.setUseCaches(false); <add> OutputStream out = null; <add> try { <add> out = conn.getOutputStream(); <add> out.write(data); <add> } finally { <add> // XXX: don't use IOUtils.closeQuietly, we want exceptions thrown <add> if (out != null) { <add> out.close(); <add> } <add> } <add> } <add> <add> // no need to explicitly execute, accessing the response triggers the execute <add> <add> // check for an invalid session <add> if (request.useSession && this.isSessionInvalid(conn, request)) { <add> // reset the session <add> synchronized (LOCK_SESSION) { <add> // only reset if this is still the same session <add> final Session current = this.loadSession(request); <add> if (current != null && current.equals(request.session)) { <add> this.deleteSession(request.session); <add> } <add> } <add> <add> // throw an invalid session exception <ide> throw new InvalidSessionApiException(); <ide> } <del> } <del> <del> // build the request uri <del> final Uri.Builder uri = mBaseUri.buildUpon(); <del> onPrepareUri(uri, request); <del> final URL url; <del> try { <del> url = new URL(uri.build().toString()); <del> } catch (final MalformedURLException e) { <del> throw new RuntimeException("invalid Request URL: " + uri.build().toString(), e); <del> } <del> <del> // prepare the request <del> conn = (HttpURLConnection) url.openConnection(); <del> onPrepareRequest(conn, request); <del> <del> // POST/PUT requests <del> if (request.method == Request.Method.POST || request.method == Request.Method.PUT) { <del> conn.setDoOutput(true); <del> final byte[] data = request.content != null ? request.content : new byte[0]; <del> conn.setFixedLengthStreamingMode(data.length); <del> conn.setUseCaches(false); <del> OutputStream out = null; <del> try { <del> out = conn.getOutputStream(); <del> out.write(data); <del> } finally { <del> // XXX: don't use IOUtils.closeQuietly, we want exceptions thrown <del> if (out != null) { <del> out.close(); <del> } <del> } <del> } <del> <del> // no need to explicitly execute, accessing the response triggers the execute <del> <del> // check for an invalid session <del> if (request.useSession && this.isSessionInvalid(conn, request)) { <del> // reset the session <del> synchronized (LOCK_SESSION) { <del> // only reset if this is still the same session <del> final Session current = this.loadSession(request); <del> if (current != null && current.equals(request.session)) { <del> this.deleteSession(request.session); <del> } <del> } <del> <del> // throw an invalid session exception <del> throw new InvalidSessionApiException(); <del> } <del> <del> // process the response <del> onProcessResponse(conn, request); <del> <del> // return the connection for method specific handling <del> successful = true; <del> return conn; <del> } catch (final IOException e) { <del> throw new ApiSocketException(e); <del> } finally { <del> // close a potentially open connection if we weren't successful <del> if(!successful) { <del> IOUtils.closeQuietly(conn); <del> } <del> <del> // clear out the session that was loaded & used <del> request.session = null; <del> <del> // cleanup any request specific data <del> onCleanupRequest(request); <add> <add> // process the response <add> onProcessResponse(conn, request); <add> <add> // return the connection for method specific handling <add> successful = true; <add> return conn; <add> } catch (final IOException e) { <add> throw new ApiSocketException(e); <add> } finally { <add> // close a potentially open connection if we weren't successful <add> if (!successful) { <add> IOUtils.closeQuietly(conn); <add> } <add> <add> // clear out the session that was loaded & used <add> request.session = null; <add> <add> // cleanup any request specific data <add> onCleanupRequest(request); <add> } <add> } catch (final ApiException e) { <add> // retry request on an API exception <add> if (attempts > 0) { <add> return this.sendRequest(request, attempts - 1); <add> } <add> <add> // propagate the exception <add> throw e; <ide> } <ide> } <ide>
Java
agpl-3.0
deb16bac3994d556ecd257028962b0849b1d015a
0
zeineb/scheduling,jrochas/scheduling,laurianed/scheduling,sgRomaric/scheduling,tobwiens/scheduling,youribonnaffe/scheduling,jrochas/scheduling,sgRomaric/scheduling,youribonnaffe/scheduling,laurianed/scheduling,lpellegr/scheduling,jrochas/scheduling,marcocast/scheduling,mbenguig/scheduling,jrochas/scheduling,tobwiens/scheduling,sgRomaric/scheduling,sandrineBeauche/scheduling,ShatalovYaroslav/scheduling,marcocast/scheduling,marcocast/scheduling,ow2-proactive/scheduling,laurianed/scheduling,ow2-proactive/scheduling,paraita/scheduling,marcocast/scheduling,youribonnaffe/scheduling,youribonnaffe/scheduling,marcocast/scheduling,zeineb/scheduling,lpellegr/scheduling,mbenguig/scheduling,tobwiens/scheduling,laurianed/scheduling,youribonnaffe/scheduling,ow2-proactive/scheduling,ow2-proactive/scheduling,fviale/scheduling,paraita/scheduling,yinan-liu/scheduling,tobwiens/scheduling,sandrineBeauche/scheduling,lpellegr/scheduling,zeineb/scheduling,laurianed/scheduling,ShatalovYaroslav/scheduling,mbenguig/scheduling,ShatalovYaroslav/scheduling,fviale/scheduling,ow2-proactive/scheduling,yinan-liu/scheduling,tobwiens/scheduling,yinan-liu/scheduling,paraita/scheduling,sandrineBeauche/scheduling,youribonnaffe/scheduling,sandrineBeauche/scheduling,fviale/scheduling,tobwiens/scheduling,ShatalovYaroslav/scheduling,paraita/scheduling,jrochas/scheduling,mbenguig/scheduling,paraita/scheduling,mbenguig/scheduling,lpellegr/scheduling,ow2-proactive/scheduling,marcocast/scheduling,sgRomaric/scheduling,fviale/scheduling,lpellegr/scheduling,sgRomaric/scheduling,ShatalovYaroslav/scheduling,zeineb/scheduling,youribonnaffe/scheduling,yinan-liu/scheduling,yinan-liu/scheduling,fviale/scheduling,fviale/scheduling,fviale/scheduling,paraita/scheduling,yinan-liu/scheduling,mbenguig/scheduling,ow2-proactive/scheduling,zeineb/scheduling,sandrineBeauche/scheduling,mbenguig/scheduling,sgRomaric/scheduling,jrochas/scheduling,zeineb/scheduling,sgRomaric/scheduling,laurianed/scheduling,ShatalovYaroslav/scheduling,tobwiens/scheduling,zeineb/scheduling,sandrineBeauche/scheduling,sandrineBeauche/scheduling,jrochas/scheduling,marcocast/scheduling,lpellegr/scheduling,lpellegr/scheduling,ShatalovYaroslav/scheduling,yinan-liu/scheduling,paraita/scheduling,laurianed/scheduling
package org.ow2.proactive.resourcemanager.utils.adminconsole; import java.io.BufferedReader; import java.io.File; import java.io.FileReader; import java.io.IOException; import java.io.InputStreamReader; import java.net.URI; import java.util.List; import javax.script.ScriptEngine; import javax.script.ScriptEngineManager; import javax.script.ScriptException; import javax.security.auth.login.LoginException; import org.apache.commons.cli.AlreadySelectedException; import org.apache.commons.cli.CommandLine; import org.apache.commons.cli.GnuParser; import org.apache.commons.cli.HelpFormatter; import org.apache.commons.cli.MissingArgumentException; import org.apache.commons.cli.MissingOptionException; import org.apache.commons.cli.Option; import org.apache.commons.cli.OptionGroup; import org.apache.commons.cli.Options; import org.apache.commons.cli.ParseException; import org.apache.commons.cli.Parser; import org.apache.commons.cli.UnrecognizedOptionException; import org.apache.log4j.Logger; import org.objectweb.proactive.core.config.PAProperties; import org.objectweb.proactive.core.util.log.ProActiveLogger; import org.objectweb.proactive.core.util.passwordhandler.PasswordField; import org.ow2.proactive.resourcemanager.authentication.RMAuthentication; import org.ow2.proactive.resourcemanager.common.event.RMNodeEvent; import org.ow2.proactive.resourcemanager.common.event.RMNodeSourceEvent; import org.ow2.proactive.resourcemanager.exception.RMException; import org.ow2.proactive.resourcemanager.frontend.RMAdmin; import org.ow2.proactive.resourcemanager.frontend.RMConnection; import org.ow2.proactive.resourcemanager.nodesource.NodeSource; import org.ow2.proactive.resourcemanager.nodesource.infrastructure.manager.GCMInfrastructure; import org.ow2.proactive.resourcemanager.nodesource.policy.StaticPolicy; import org.ow2.proactive.resourcemanager.utils.RMLoggers; import org.ow2.proactive.utils.FileToBytesConverter; import org.ow2.proactive.utils.console.Console; import org.ow2.proactive.utils.console.SimpleConsole; /** * Class with a main provides a way to list nodes, nodes sources, * add/remove nodes and nodes sources and shutdown Resource Manager. * * * @author The ProActive Team * @since ProActive Scheduling 1.0 * */ public class AdminController { private static final String RM_DEFAULT_URL = getHostURL("//localhost/"); private final String JS_INIT_FILE = "AdminActions.js"; public static Logger logger = ProActiveLogger.getLogger(RMLoggers.RMLAUNCHER); protected static final String control = "<ctl> "; private static final String ADDNODE_CMD = "addnode(nodeURL, nsName)"; private static final String REMOVENODE_CMD = "removenode(nodeURL,preempt)"; private static final String GCMDEPLOY_CMD = "gcmdeploy(gcmdFile,nsName)"; private static final String CREATENS_CMD = "createns(nsName)"; private static final String REMOVENS_CMD = "removens(nsName,preempt)"; private static final String LISTNODES_CMD = "listnodes()"; private static final String LISTNS_CMD = "listns()"; private static final String SHUTDOWN_CMD = "shutdown(preempt)"; private static final String EXIT_CMD = "exit()"; private static final String EXEC_CMD = "exec(commandFilePath)"; private String commandName = "adminRM"; protected RMAdmin rm; protected boolean initialized = false; protected boolean terminated = false; protected boolean intercativeMode = false; protected ScriptEngine engine; protected Console console = new SimpleConsole(); protected RMAuthentication auth = null; protected CommandLine cmd = null; protected String user = null; protected String pwd = null; protected static AdminController shell; /** * @param args */ public static void main(String[] args) { shell = new AdminController(); shell.load(args); } public void load(String[] args) { Options options = new Options(); Option help = new Option("h", "help", false, "Display this help"); help.setRequired(false); options.addOption(help); Option username = new Option("l", "login", true, "The username to join the Resource Manager"); username.setArgName("login"); username.setArgs(1); username.setRequired(false); options.addOption(username); Option rmURL = new Option("u", "rmURL", true, "The Resource manager URL (default " + RM_DEFAULT_URL + ")"); rmURL.setArgName("rmURL"); rmURL.setArgs(1); rmURL.setRequired(false); options.addOption(rmURL); addCommandLineOptions(options); boolean displayHelp = false; try { String pwdMsg = null; Parser parser = new GnuParser(); cmd = parser.parse(options, args); if (cmd.hasOption("h")) { displayHelp = true; } else { String url; if (cmd.hasOption("u")) { url = cmd.getOptionValue("u"); } else { url = RM_DEFAULT_URL; } logger.info("Trying to connect RM on " + url); auth = RMConnection.join(url); logger.info("\t-> Connection established on " + url); logger.info("\nConnecting admin to the RM"); if (cmd.hasOption("l")) { user = cmd.getOptionValue("l"); pwdMsg = user + "'s password: "; } else { System.out.print("login: "); BufferedReader buf = new BufferedReader(new InputStreamReader(System.in)); user = buf.readLine(); pwdMsg = "password: "; } //ask password to User char password[] = null; try { password = PasswordField.getPassword(System.in, pwdMsg); if (password == null) { pwd = ""; } else { pwd = String.valueOf(password); } } catch (IOException ioe) { logger.error("", ioe); } //connect to the scheduler connect(); //start the command line or the interactive mode start(); } } catch (MissingArgumentException e) { logger.error(e.getLocalizedMessage()); displayHelp = true; } catch (MissingOptionException e) { logger.error("Missing option: " + e.getLocalizedMessage()); displayHelp = true; } catch (UnrecognizedOptionException e) { logger.error(e.getLocalizedMessage()); displayHelp = true; } catch (AlreadySelectedException e) { logger.error(e.getClass().getSimpleName() + " : " + e.getLocalizedMessage()); displayHelp = true; } catch (ParseException e) { displayHelp = true; } catch (RMException e) { logger.error("Error at connection : " + e.getMessage() + "\nShutdown the controller.\n"); System.exit(1); } catch (LoginException e) { logger.error(e.getMessage() + "\nShutdown the controller.\n"); System.exit(1); } catch (Exception e) { logger.error("An error has occurred : " + e.getMessage() + "\nShutdown the controller.\n", e); System.exit(1); } if (displayHelp) { logger.info(""); HelpFormatter hf = new HelpFormatter(); hf.setWidth(160); String note = "\nNOTE : if no command marked with " + control + "is specified, the controller will start in interactive mode."; hf.printHelp(commandName + shellExtension(), "", options, note, true); System.exit(2); } // if execution reaches this point this means it must exit System.exit(0); } protected void connect() throws LoginException { rm = auth.logAsAdmin(user, pwd); logger.info("\t-> Admin '" + user + "' successfully connected\n"); } private void start() throws Exception { //start one of the two command behavior if (startCommandLine(cmd)) { startCommandListener(); } } protected OptionGroup addCommandLineOptions(Options options) { OptionGroup actionGroup = new OptionGroup(); Option addNodesOpt = new Option("a", "addnodes", true, control + "Add nodes by their URLs"); addNodesOpt.setArgName("node URLs"); addNodesOpt.setRequired(false); addNodesOpt.setArgs(Option.UNLIMITED_VALUES); actionGroup.addOption(addNodesOpt); Option gcmdOpt = new Option("gcmd", "gcmdeploy", true, control + "Add nodes by GCM deployment descriptor files"); gcmdOpt.setArgName("GCMD files"); gcmdOpt.setRequired(false); gcmdOpt.setArgs(Option.UNLIMITED_VALUES); actionGroup.addOption(gcmdOpt); Option removeNodesOpt = new Option("d", "removenodes", true, control + "Remove nodes by their URLs"); removeNodesOpt.setArgName("node URLs"); removeNodesOpt.setRequired(false); removeNodesOpt.setArgs(Option.UNLIMITED_VALUES); actionGroup.addOption(removeNodesOpt); Option createNSOpt = new Option("c", "createns", true, control + "Create new node sources"); createNSOpt.setArgName("names"); createNSOpt.setRequired(false); createNSOpt.setArgs(Option.UNLIMITED_VALUES); actionGroup.addOption(createNSOpt); Option listNodesOpt = new Option("ln", "listnodes", false, control + "List nodes handled by Resource Manager. Display is : NODESOURCE HOSTNAME STATE NODE_URL"); listNodesOpt.setRequired(false); actionGroup.addOption(listNodesOpt); Option listNSOpt = new Option("lns", "listns", false, control + "List node sources on Resource Manager. Display is : NODESOURCE TYPE"); listNSOpt.setRequired(false); actionGroup.addOption(listNSOpt); Option removeNSOpt = new Option("r", "removens", true, control + "Remove given node sources"); removeNSOpt.setArgName("names"); removeNSOpt.setRequired(false); removeNSOpt.setArgs(Option.UNLIMITED_VALUES); actionGroup.addOption(removeNSOpt); Option shutdownOpt = new Option("s", "shutdown", false, control + "Shutdown Resource Manager"); shutdownOpt.setRequired(false); actionGroup.addOption(shutdownOpt); options.addOptionGroup(actionGroup); Option nodeSourceNameOpt = new Option("ns", "nodesource", true, control + "Specify an existing node source name for " + "adding nodes on and deploying GCMD actions (-a and -gcmd)"); nodeSourceNameOpt.setArgName("nodes URLs"); nodeSourceNameOpt.setRequired(false); nodeSourceNameOpt.setArgs(1); options.addOption(nodeSourceNameOpt); Option preeemptiveRemovalOpt = new Option("f", "force", false, control + "Do not wait for busy nodes to be freed before " + "nodes removal, node source removal and shutdown actions (-d, -r and -s)"); preeemptiveRemovalOpt.setRequired(false); options.addOption(preeemptiveRemovalOpt); return actionGroup; } private void startCommandListener() throws Exception { initialize(); console.start(" > "); console.printf("Type command here (type '?' or help() to see the list of commands)\n"); String stmt; while (!terminated) { stmt = console.readStatement(); if (stmt.equals("?")) { console.printf("\n" + helpScreen()); } else { eval(stmt); console.printf(""); } } console.stop(); } protected boolean startCommandLine(CommandLine cmd) { intercativeMode = false; if (cmd.hasOption("addnodes")) { String[] nodesURls = cmd.getOptionValues("addnodes"); if (cmd.hasOption("ns")) { String nsName = cmd.getOptionValue("ns"); for (String nUrl : nodesURls) { addnode(nUrl, nsName); } } else { for (String nUrl : nodesURls) { addnode(nUrl, null); } } } else if (cmd.hasOption("gcmdeploy")) { String[] gcmdTab = cmd.getOptionValues("gcmdeploy"); for (String gcmdf : gcmdTab) { File gcmdFile = new File(gcmdf); if (!(gcmdFile.exists() && gcmdFile.isFile() && gcmdFile.canRead())) { error("Cannot read GCMDeployment descriptor : " + gcmdf); } } if (cmd.hasOption("ns")) { String nsName = cmd.getOptionValue("ns"); for (String desc : gcmdTab) { gcmdeploy(desc, nsName); } } else { for (String desc : gcmdTab) { gcmdeploy(desc, null); } } } else if (cmd.hasOption("removenodes")) { String[] nodesURls = cmd.getOptionValues("removenodes"); boolean preempt = cmd.hasOption("f"); for (String nUrl : nodesURls) { removenode(nUrl, preempt); } } else if (cmd.hasOption("createns")) { String[] nsNames = cmd.getOptionValues("createns"); for (String nsName : nsNames) { createns(nsName); } } else if (cmd.hasOption("listnodes")) { listnodes(); } else if (cmd.hasOption("listns")) { listns(); } else if (cmd.hasOption("removens")) { String[] nsNames = cmd.getOptionValues("removens"); boolean preempt = cmd.hasOption("f"); for (String nsName : nsNames) { removens(nsName, preempt); } } else if (cmd.hasOption("shutdown")) { shutdown(cmd.hasOption("f")); } else { intercativeMode = true; return intercativeMode; } return false; } //***************** COMMAND LISTENER ******************* protected void handleExceptionDisplay(String msg, Throwable t) { if (intercativeMode) { console.handleExceptionDisplay(msg, t); } else { System.err.printf(msg); t.printStackTrace(); } } protected void printf(String format, Object... args) { if (intercativeMode) { console.printf(format, args); } else { System.out.printf(format, args); } } protected void error(String format, Object... args) { if (intercativeMode) { console.error(format, args); } else { System.err.printf(format, args); } } public static void help() { shell.help_(); } private void help_() { printf("\n" + helpScreen()); } public static void shutdown(boolean preempt) { shell.shutdown_(preempt); } private void shutdown_(boolean preempt) { try { rm.shutdown(preempt); printf("Shutdown request sent to Resource Manager, controller will shutdown !"); terminated = true; } catch (Exception e) { handleExceptionDisplay("Error while shutting down the RM", e); } } public static void removens(String nodeSourceName, boolean preempt) { shell.removens_(nodeSourceName, preempt); } private void removens_(String nodeSourceName, boolean preempt) { try { rm.removeSource(nodeSourceName, preempt); printf("Node source '" + nodeSourceName + "' removal request sent to Resource Manager"); } catch (Exception e) { handleExceptionDisplay("Error while removing node source '" + nodeSourceName, e); } } public static void listns() { shell.listns_(); } private void listns_() { List<RMNodeSourceEvent> list = rm.getNodeSourcesList(); for (RMNodeSourceEvent evt : list) { printf(evt.getSourceName() + "\t" + evt.getSourceDescription()); } } public static void listnodes() { shell.listnodes_(); } private void listnodes_() { List<RMNodeEvent> list = rm.getNodesList(); if (list.size() == 0) { printf("No nodes handled by Resource Manager"); } else { for (RMNodeEvent evt : list) { String state = null; switch (evt.getState()) { case DOWN: state = "DOWN"; break; case FREE: state = "FREE"; break; case BUSY: state = "BUSY"; break; case TO_BE_RELEASED: state = "TO_BE_RELEASED"; } printf(evt.getNodeSource() + "\t" + evt.getHostName() + "\t" + state + "\t" + evt.getNodeUrl()); } } } public static void createns(String nodeSourceName) { shell.createns_(nodeSourceName); } private void createns_(String nodeSourceName) { try { rm.createNodesource(nodeSourceName, GCMInfrastructure.class.getName(), null, StaticPolicy.class .getName(), null); printf("Node source '" + nodeSourceName + "' creation request sent to Resource Manager"); } catch (Exception e) { handleExceptionDisplay("Error while creating node source '" + nodeSourceName, e); } } public static void removenode(String nodeURL, boolean preempt) { shell.removenode_(nodeURL, preempt); } private void removenode_(String nodeURL, boolean preempt) { rm.removeNode(nodeURL, preempt); printf("Nodes '" + nodeURL + "' removal request sent to Resource Manager"); } public static void gcmdeploy(String fileName, String nodeSourceName) { shell.gcmdeploy_(fileName, nodeSourceName); } private void gcmdeploy_(String fileName, String nodeSourceName) { try { File gcmDeployFile = new File(fileName); if (nodeSourceName != null) { rm.addNodes(nodeSourceName, new Object[] { FileToBytesConverter .convertFileToByteArray(gcmDeployFile) }); } else { rm.addNodes(NodeSource.DEFAULT_NAME, new Object[] { FileToBytesConverter .convertFileToByteArray(gcmDeployFile) }); } printf("GCM deployment '" + fileName + "' request sent to Resource Manager"); } catch (Exception e) { handleExceptionDisplay("Error while load GCMD file '" + fileName, e); } } public static void addnode(String nodeName, String nodeSourceName) { shell.addnode_(nodeName, nodeSourceName); } private void addnode_(String nodeName, String nodeSourceName) { try { if (nodeSourceName != null) { rm.addNode(nodeName, nodeSourceName); } else { rm.addNode(nodeName); } printf("Adding node '" + nodeName + "' request sent to Resource Manager"); } catch (Exception e) { handleExceptionDisplay("Error while adding node '" + nodeName + "'", e); } } public static void exec(String commandFilePath) { shell.exec_(commandFilePath); } private void exec_(String commandFilePath) { try { File f = new File(commandFilePath.trim()); BufferedReader br = new BufferedReader(new FileReader(f)); eval(readFileContent(br)); br.close(); } catch (Exception e) { handleExceptionDisplay("*ERROR*", e); } } public static void exit() { shell.exit_(); } private void exit_() { console.printf("Exiting controller."); terminated = true; } //***************** OTHER ******************* protected void initialize() throws IOException { if (!initialized) { ScriptEngineManager manager = new ScriptEngineManager(); // Engine selection engine = manager.getEngineByName("rhino"); initialized = true; //read and launch Action.js BufferedReader br = new BufferedReader(new InputStreamReader(AdminController.class .getResourceAsStream(JS_INIT_FILE))); eval(readFileContent(br)); } } protected void eval(String cmd) { try { if (!initialized) { initialize(); } //Evaluate the command engine.eval(cmd); } catch (ScriptException e) { console.error("*SYNTAX ERROR* - " + format(e.getMessage())); } catch (Exception e) { handleExceptionDisplay("Error while evaluating command", e); } } private static String format(String msg) { msg = msg.replaceFirst("[^:]+:", ""); return msg.replaceFirst("[(]<.*", "").trim(); } protected static String readFileContent(BufferedReader reader) throws IOException { StringBuilder sb = new StringBuilder(); String tmp; while ((tmp = reader.readLine()) != null) { sb.append(tmp); } return sb.toString(); } //***************** HELP SCREEN ******************* protected String helpScreen() { StringBuilder out = new StringBuilder("Resource Manager controller commands are :\n\n"); out.append(String.format( " %1$-28s\t Add node to the given node source (parameters is a string representing the node URL to add AND" + " a string representing the node source in which to add the node)\n", ADDNODE_CMD)); out.append(String.format( " %1$-28s\t Remove the given node (parameter is a string representing the node URL," + " node is removed immediately if second parameter is true)\n", REMOVENODE_CMD)); out.append(String .format( " %1$-28s\t Add node(s) to the given node source (parameter is a string representing the a GCMD file AND" + " a string representing the node source in which to add the node(s) )\n", GCMDEPLOY_CMD)); out .append(String .format( " %1$-28s\t Create a new node source (parameter is a string representing the node source name to create)\n", CREATENS_CMD)); out.append(String.format( " %1$-28s\t Remove the given node source (parameter is a string representing the node source name to remove," + " nodeSource is removed immediately if second parameter is true)\n", REMOVENS_CMD)); out.append(String.format(" %1$-28s\t List every handled nodes\n", LISTNODES_CMD)); out.append(String.format(" %1$-28s\t List every handled node sources\n", LISTNS_CMD)); out.append(String.format( " %1$-28s\t Shutdown the Resource Manager (RM shutdown immediately if parameter is true)\n", SHUTDOWN_CMD)); out .append(String .format( " %1$-28s\t Execute the content of the given script file (parameter is a string representing a command-file path)\n", EXEC_CMD)); out.append(String.format(" %1$-28s\t Exits RM controller\n", EXIT_CMD)); return out.toString(); } /** * Normalize the given URL into an URL that only contains protocol://host:port/ * * @param url the url to transform * @return an URL that only contains protocol://host:port/ */ public static String getHostURL(String url) { URI uri = URI.create(url); String scheme = (uri.getScheme() == null) ? "rmi" : uri.getScheme(); String host = (uri.getHost() == null) ? "localhost" : uri.getHost(); int port = (uri.getPort() == -1) ? PAProperties.PA_RMI_PORT.getValueAsInt() : uri.getPort(); return scheme + "://" + host + ":" + port + "/"; } /** * Return the extension of shell script depending the current OS * * @return the extension of shell script depending the current OS */ public static String shellExtension() { if (System.getProperty("os.name").contains("Windows")) { return ".bat"; } else { return ".sh"; } } /** * Set the commandName value to the given commandName value * * @param commandName the commandName to set */ public void setCommandName(String commandName) { this.commandName = commandName; } }
src/resource-manager/src/org/ow2/proactive/resourcemanager/utils/adminconsole/AdminController.java
package org.ow2.proactive.resourcemanager.utils.adminconsole; import java.io.BufferedReader; import java.io.File; import java.io.FileReader; import java.io.IOException; import java.io.InputStreamReader; import java.net.URI; import java.util.List; import javax.script.ScriptEngine; import javax.script.ScriptEngineManager; import javax.script.ScriptException; import javax.security.auth.login.LoginException; import org.apache.commons.cli.AlreadySelectedException; import org.apache.commons.cli.CommandLine; import org.apache.commons.cli.GnuParser; import org.apache.commons.cli.HelpFormatter; import org.apache.commons.cli.MissingArgumentException; import org.apache.commons.cli.MissingOptionException; import org.apache.commons.cli.Option; import org.apache.commons.cli.OptionGroup; import org.apache.commons.cli.Options; import org.apache.commons.cli.ParseException; import org.apache.commons.cli.Parser; import org.apache.commons.cli.UnrecognizedOptionException; import org.apache.log4j.Logger; import org.objectweb.proactive.core.config.PAProperties; import org.objectweb.proactive.core.util.log.ProActiveLogger; import org.objectweb.proactive.core.util.passwordhandler.PasswordField; import org.ow2.proactive.resourcemanager.authentication.RMAuthentication; import org.ow2.proactive.resourcemanager.common.event.RMNodeEvent; import org.ow2.proactive.resourcemanager.common.event.RMNodeSourceEvent; import org.ow2.proactive.resourcemanager.exception.RMException; import org.ow2.proactive.resourcemanager.frontend.RMAdmin; import org.ow2.proactive.resourcemanager.frontend.RMConnection; import org.ow2.proactive.resourcemanager.nodesource.NodeSource; import org.ow2.proactive.resourcemanager.nodesource.infrastructure.manager.GCMInfrastructure; import org.ow2.proactive.resourcemanager.nodesource.policy.StaticPolicy; import org.ow2.proactive.resourcemanager.utils.RMLoggers; import org.ow2.proactive.utils.FileToBytesConverter; import org.ow2.proactive.utils.console.Console; import org.ow2.proactive.utils.console.SimpleConsole; /** * Class with a main provides a way to list nodes, nodes sources, * add/remove nodes and nodes sources and shutdown Resource Manager. * * * @author The ProActive Team * @since ProActive Scheduling 1.0 * */ public class AdminController { private static final String RM_DEFAULT_URL = getHostURL("//localhost/"); private final String JS_INIT_FILE = "AdminActions.js"; public static Logger logger = ProActiveLogger.getLogger(RMLoggers.RMLAUNCHER); protected static final String control = "<ctl> "; private static final String ADDNODE_CMD = "addnode(nodeURL, nsName)"; private static final String REMOVENODE_CMD = "removenode(nodeURL,preempt)"; private static final String GCMDEPLOY_CMD = "gcmdeploy(gcmdFile,nsName)"; private static final String CREATENS_CMD = "createns(nsName)"; private static final String REMOVENS_CMD = "removens(nsName,preempt)"; private static final String LISTNODES_CMD = "listnodes()"; private static final String LISTNS_CMD = "listns()"; private static final String SHUTDOWN_CMD = "shutdown(preempt)"; private static final String EXIT_CMD = "exit()"; private static final String EXEC_CMD = "exec(commandFilePath)"; private String commandName = "adminRM"; protected RMAdmin rm; protected boolean initialized = false; protected boolean terminated = false; protected boolean intercativeMode = false; protected ScriptEngine engine; protected Console console = new SimpleConsole(); protected RMAuthentication auth = null; protected CommandLine cmd = null; protected String user = null; protected String pwd = null; protected static AdminController shell; /** * @param args */ public static void main(String[] args) { shell = new AdminController(); shell.load(args); } public void load(String[] args) { Options options = new Options(); Option help = new Option("h", "help", false, "Display this help"); help.setRequired(false); options.addOption(help); Option username = new Option("l", "login", true, "The username to join the Resource Manager"); username.setArgName("login"); username.setArgs(1); username.setRequired(false); options.addOption(username); Option rmURL = new Option("u", "rmURL", true, "The Resource manager URL (default " + RM_DEFAULT_URL + ")"); rmURL.setArgName("rmURL"); rmURL.setArgs(1); rmURL.setRequired(false); options.addOption(rmURL); addCommandLineOptions(options); boolean displayHelp = false; try { String pwdMsg = null; Parser parser = new GnuParser(); cmd = parser.parse(options, args); if (cmd.hasOption("h")) { displayHelp = true; } else { String url; if (cmd.hasOption("u")) { url = cmd.getOptionValue("u"); } else { url = RM_DEFAULT_URL; } logger.info("Trying to connect RM on " + url); auth = RMConnection.join(url); logger.info("\t-> Connection established on " + url); logger.info("\nConnecting admin to the RM"); if (cmd.hasOption("l")) { user = cmd.getOptionValue("l"); pwdMsg = user + "'s password: "; } else { System.out.print("login: "); BufferedReader buf = new BufferedReader(new InputStreamReader(System.in)); user = buf.readLine(); pwdMsg = "password: "; } //ask password to User char password[] = null; try { password = PasswordField.getPassword(System.in, pwdMsg); if (password == null) { pwd = ""; } else { pwd = String.valueOf(password); } } catch (IOException ioe) { logger.error("", ioe); } //connect to the scheduler connect(); //start the command line or the interactive mode start(); } } catch (MissingArgumentException e) { logger.error(e.getLocalizedMessage()); displayHelp = true; } catch (MissingOptionException e) { logger.error("Missing option: " + e.getLocalizedMessage()); displayHelp = true; } catch (UnrecognizedOptionException e) { logger.error(e.getLocalizedMessage()); displayHelp = true; } catch (AlreadySelectedException e) { logger.error(e.getClass().getSimpleName() + " : " + e.getLocalizedMessage()); displayHelp = true; } catch (ParseException e) { displayHelp = true; } catch (RMException e) { logger.error("Error at connection : " + e.getMessage() + "\nShutdown the controller.\n"); System.exit(1); } catch (LoginException e) { logger.error(e.getMessage() + "\nShutdown the controller.\n"); System.exit(1); } catch (Exception e) { logger.error("An error has occurred : " + e.getMessage() + "\nShutdown the controller.\n", e); System.exit(1); } if (displayHelp) { logger.info(""); HelpFormatter hf = new HelpFormatter(); hf.setWidth(160); String note = "\nNOTE : if no command marked with " + control + "is specified, the controller will start in interactive mode."; hf.printHelp(commandName + shellExtension(), "", options, note, true); System.exit(2); } // if execution reaches this point this means it must exit System.exit(0); } protected void connect() throws LoginException { rm = auth.logAsAdmin(user, pwd); logger.info("\t-> Admin '" + user + "' successfully connected\n"); } private void start() throws Exception { //start one of the two command behavior if (startCommandLine(cmd)) { startCommandListener(); } } protected OptionGroup addCommandLineOptions(Options options) { OptionGroup actionGroup = new OptionGroup(); Option addNodesOpt = new Option("a", "addnodes", true, control + "Add nodes by their URLs"); addNodesOpt.setArgName("node URLs"); addNodesOpt.setRequired(false); addNodesOpt.setArgs(Option.UNLIMITED_VALUES); actionGroup.addOption(addNodesOpt); Option gcmdOpt = new Option("gcmd", "gcmdeploy", true, control + "Add nodes by GCM deployment descriptor files"); gcmdOpt.setArgName("GCMD files"); gcmdOpt.setRequired(false); gcmdOpt.setArgs(Option.UNLIMITED_VALUES); actionGroup.addOption(gcmdOpt); Option removeNodesOpt = new Option("d", "removenodes", true, control + "Remove nodes by their URLs"); removeNodesOpt.setArgName("node URLs"); removeNodesOpt.setRequired(false); removeNodesOpt.setArgs(Option.UNLIMITED_VALUES); actionGroup.addOption(removeNodesOpt); Option createNSOpt = new Option("c", "createns", true, control + "Create new node sources"); createNSOpt.setArgName("names"); createNSOpt.setRequired(false); createNSOpt.setArgs(Option.UNLIMITED_VALUES); actionGroup.addOption(createNSOpt); Option listNodesOpt = new Option("ln", "listnodes", false, control + "List nodes handled by Resource Manager. Display is : NODESOURCE HOSTNAME STATE NODE_URL"); listNodesOpt.setRequired(false); actionGroup.addOption(listNodesOpt); Option listNSOpt = new Option("lns", "listns", false, control + "List node sources on Resource Manager. Display is : NODESOURCE TYPE"); listNSOpt.setRequired(false); actionGroup.addOption(listNSOpt); Option removeNSOpt = new Option("r", "removens", true, control + "Remove given node sources"); removeNSOpt.setArgName("names"); removeNSOpt.setRequired(false); removeNSOpt.setArgs(Option.UNLIMITED_VALUES); actionGroup.addOption(removeNSOpt); Option shutdownOpt = new Option("s", "shutdown", false, control + "Shutdown Resource Manager"); shutdownOpt.setRequired(false); actionGroup.addOption(shutdownOpt); options.addOptionGroup(actionGroup); Option nodeSourceNameOpt = new Option("ns", "nodesource", true, control + "Specify an existing node source name for " + "adding nodes on and deploying GCMD actions (-a and -gcmd)"); nodeSourceNameOpt.setArgName("nodes URLs"); nodeSourceNameOpt.setRequired(false); nodeSourceNameOpt.setArgs(1); options.addOption(nodeSourceNameOpt); Option preeemptiveRemovalOpt = new Option("f", "force", false, control + "Do not wait for busy nodes to be freed before " + "nodes removal, node source removal and shutdown actions (-d, -r and -s)"); preeemptiveRemovalOpt.setRequired(false); options.addOption(preeemptiveRemovalOpt); return actionGroup; } private void startCommandListener() throws Exception { initialize(); console.start(" > "); console.printf("Type command here (type '?' or help() to see the list of commands)\n"); String stmt; while (!terminated) { stmt = console.readStatement(); if (stmt.equals("?")) { console.printf("\n" + helpScreen()); } else { eval(stmt); console.printf(""); } } console.stop(); } protected boolean startCommandLine(CommandLine cmd) { intercativeMode = false; if (cmd.hasOption("addnodes")) { String[] nodesURls = cmd.getOptionValues("addnodes"); if (cmd.hasOption("ns")) { String nsName = cmd.getOptionValue("ns"); for (String nUrl : nodesURls) { addnode(nUrl, nsName); } } else { for (String nUrl : nodesURls) { addnode(nUrl, null); } } } else if (cmd.hasOption("gcmdeploy")) { String[] gcmdTab = cmd.getOptionValues("gcmdeploy"); for (String gcmdf : gcmdTab) { File gcmdFile = new File(gcmdf); if (!(gcmdFile.exists() && gcmdFile.isFile() && gcmdFile.canRead())) { error("Cannot read GCMDeployment descriptor : " + gcmdf); } } if (cmd.hasOption("ns")) { String nsName = cmd.getOptionValue("ns"); for (String desc : gcmdTab) { gcmdeploy(desc, nsName); } } else { for (String desc : gcmdTab) { gcmdeploy(desc, null); } } } else if (cmd.hasOption("removenodes")) { String[] nodesURls = cmd.getOptionValues("removenodes"); boolean preempt = cmd.hasOption("f"); for (String nUrl : nodesURls) { removenode(nUrl, preempt); } } else if (cmd.hasOption("createns")) { String[] nsNames = cmd.getOptionValues("createns"); for (String nsName : nsNames) { createns(nsName); } } else if (cmd.hasOption("listnodes")) { listnodes(); } else if (cmd.hasOption("listns")) { listns(); } else if (cmd.hasOption("removens")) { String[] nsNames = cmd.getOptionValues("removens"); boolean preempt = cmd.hasOption("f"); for (String nsName : nsNames) { removens(nsName, preempt); } } else if (cmd.hasOption("shutdown")) { shutdown(cmd.hasOption("f")); } else { intercativeMode = true; return intercativeMode; } return false; } //***************** COMMAND LISTENER ******************* protected void handleExceptionDisplay(String msg, Throwable t) { if (intercativeMode) { console.handleExceptionDisplay(msg, t); } else { System.err.printf(msg); t.printStackTrace(); } } protected void printf(String format, Object... args) { if (intercativeMode) { console.printf(format, args); } else { System.out.printf(format, args); } } protected void error(String format, Object... args) { if (intercativeMode) { console.error(format, args); } else { System.err.printf(format, args); } } public static void help() { shell.help_(); } private void help_() { printf("\n" + helpScreen()); } public static void shutdown(boolean preempt) { shell.shutdown_(preempt); } private void shutdown_(boolean preempt) { try { rm.shutdown(preempt); printf("Shutdown request sent to Resource Manager, controller will shutdown !"); terminated = true; } catch (Exception e) { handleExceptionDisplay("Error while shutting down the RM", e); } } public static void removens(String nodeSourceName, boolean preempt) { shell.removens_(nodeSourceName, preempt); } private void removens_(String nodeSourceName, boolean preempt) { try { rm.removeSource(nodeSourceName, preempt); printf("Node source '" + nodeSourceName + "' removal request sent to Resource Manager"); } catch (Exception e) { handleExceptionDisplay("Error while removing node source '" + nodeSourceName, e); } } public static void listns() { shell.listns_(); } private void listns_() { List<RMNodeSourceEvent> list = rm.getNodeSourcesList(); for (RMNodeSourceEvent evt : list) { printf(evt.getSourceName() + "\t" + evt.getSourceDescription()); } } public static void listnodes() { shell.listnodes_(); } private void listnodes_() { List<RMNodeEvent> list = rm.getNodesList(); if (list.size() == 0) { printf("No nodes handled by Resource Manager"); } else { for (RMNodeEvent evt : list) { String state = null; switch (evt.getState()) { case DOWN: state = "DOWN"; break; case FREE: state = "FREE"; break; case BUSY: state = "BUSY"; break; case TO_BE_RELEASED: state = "TO_BE_RELEASED"; } printf(evt.getNodeSource() + "\t" + evt.getHostName() + "\t" + state + "\t" + evt.getNodeUrl()); } } } public static void createns(String nodeSourceName) { shell.createns_(nodeSourceName); } private void createns_(String nodeSourceName) { try { rm.createNodesource(nodeSourceName, GCMInfrastructure.class.getName(), null, StaticPolicy.class .getName(), null); printf("Node source '" + nodeSourceName + "' creation request sent to Resource Manager"); } catch (Exception e) { handleExceptionDisplay("Error while removing node source '" + nodeSourceName, e); } } public static void removenode(String nodeURL, boolean preempt) { shell.removenode_(nodeURL, preempt); } private void removenode_(String nodeURL, boolean preempt) { rm.removeNode(nodeURL, preempt); printf("Nodes '" + nodeURL + "' removal request sent to Resource Manager"); } public static void gcmdeploy(String fileName, String nodeSourceName) { shell.gcmdeploy_(fileName, nodeSourceName); } private void gcmdeploy_(String fileName, String nodeSourceName) { try { File gcmDeployFile = new File(fileName); if (nodeSourceName != null) { rm.addNodes(nodeSourceName, new Object[] { FileToBytesConverter .convertFileToByteArray(gcmDeployFile) }); } else { rm.addNodes(NodeSource.DEFAULT_NAME, new Object[] { FileToBytesConverter .convertFileToByteArray(gcmDeployFile) }); } printf("GCM deployment '" + fileName + "' request sent to Resource Manager"); } catch (Exception e) { handleExceptionDisplay("Error while load GCMD file '" + fileName, e); } } public static void addnode(String nodeName, String nodeSourceName) { shell.addnode_(nodeName, nodeSourceName); } private void addnode_(String nodeName, String nodeSourceName) { try { if (nodeSourceName != null) { rm.addNode(nodeName, nodeSourceName); } else { rm.addNode(nodeName); } printf("Adding node '" + nodeName + "' request sent to Resource Manager"); } catch (Exception e) { handleExceptionDisplay("Error while adding node '" + nodeName + "'", e); } } public static void exec(String commandFilePath) { shell.exec_(commandFilePath); } private void exec_(String commandFilePath) { try { File f = new File(commandFilePath.trim()); BufferedReader br = new BufferedReader(new FileReader(f)); eval(readFileContent(br)); br.close(); } catch (Exception e) { handleExceptionDisplay("*ERROR*", e); } } public static void exit() { shell.exit_(); } private void exit_() { console.printf("Exiting controller."); terminated = true; } //***************** OTHER ******************* protected void initialize() throws IOException { if (!initialized) { ScriptEngineManager manager = new ScriptEngineManager(); // Engine selection engine = manager.getEngineByName("rhino"); initialized = true; //read and launch Action.js BufferedReader br = new BufferedReader(new InputStreamReader(AdminController.class .getResourceAsStream(JS_INIT_FILE))); eval(readFileContent(br)); } } protected void eval(String cmd) { try { if (!initialized) { initialize(); } //Evaluate the command engine.eval(cmd); } catch (ScriptException e) { console.error("*SYNTAX ERROR* - " + format(e.getMessage())); } catch (Exception e) { handleExceptionDisplay("Error while evaluating command", e); } } private static String format(String msg) { msg = msg.replaceFirst("[^:]+:", ""); return msg.replaceFirst("[(]<.*", "").trim(); } protected static String readFileContent(BufferedReader reader) throws IOException { StringBuilder sb = new StringBuilder(); String tmp; while ((tmp = reader.readLine()) != null) { sb.append(tmp); } return sb.toString(); } //***************** HELP SCREEN ******************* protected String helpScreen() { StringBuilder out = new StringBuilder("Resource Manager controller commands are :\n\n"); out.append(String.format( " %1$-28s\t Add node to the given node source (parameters is a string representing the node URL to add AND" + " a string representing the node source in which to add the node)\n", ADDNODE_CMD)); out.append(String.format( " %1$-28s\t Remove the given node (parameter is a string representing the node URL," + " node is removed immediately if second parameter is true)\n", REMOVENODE_CMD)); out.append(String .format( " %1$-28s\t Add node(s) to the given node source (parameter is a string representing the a GCMD file AND" + " a string representing the node source in which to add the node(s) )\n", GCMDEPLOY_CMD)); out .append(String .format( " %1$-28s\t Create a new node source (parameter is a string representing the node source name to create)\n", CREATENS_CMD)); out.append(String.format( " %1$-28s\t Remove the given node source (parameter is a string representing the node source name to remove," + " nodeSource is removed immediately if second parameter is true)\n", REMOVENS_CMD)); out.append(String.format(" %1$-28s\t List every handled nodes\n", LISTNODES_CMD)); out.append(String.format(" %1$-28s\t List every handled node sources\n", LISTNS_CMD)); out.append(String.format( " %1$-28s\t Shutdown the Resource Manager (RM shutdown immediately if parameter is true)\n", SHUTDOWN_CMD)); out .append(String .format( " %1$-28s\t Execute the content of the given script file (parameter is a string representing a command-file path)\n", EXEC_CMD)); out.append(String.format(" %1$-28s\t Exits RM controller\n", EXIT_CMD)); return out.toString(); } /** * Normalize the given URL into an URL that only contains protocol://host:port/ * * @param url the url to transform * @return an URL that only contains protocol://host:port/ */ public static String getHostURL(String url) { URI uri = URI.create(url); String scheme = (uri.getScheme() == null) ? "rmi" : uri.getScheme(); String host = (uri.getHost() == null) ? "localhost" : uri.getHost(); int port = (uri.getPort() == -1) ? PAProperties.PA_RMI_PORT.getValueAsInt() : uri.getPort(); return scheme + "://" + host + ":" + port + "/"; } /** * Return the extension of shell script depending the current OS * * @return the extension of shell script depending the current OS */ public static String shellExtension() { if (System.getProperty("os.name").contains("Windows")) { return ".bat"; } else { return ".sh"; } } /** * Set the commandName value to the given commandName value * * @param commandName the commandName to set */ public void setCommandName(String commandName) { this.commandName = commandName; } }
syntax error in admin controller git-svn-id: 27916816d6cfa57849e9a885196bf7392b80e1ac@11813 28e8926c-6b08-0410-baaa-805c5e19b8d6
src/resource-manager/src/org/ow2/proactive/resourcemanager/utils/adminconsole/AdminController.java
syntax error in admin controller
<ide><path>rc/resource-manager/src/org/ow2/proactive/resourcemanager/utils/adminconsole/AdminController.java <ide> .getName(), null); <ide> printf("Node source '" + nodeSourceName + "' creation request sent to Resource Manager"); <ide> } catch (Exception e) { <del> handleExceptionDisplay("Error while removing node source '" + nodeSourceName, e); <add> handleExceptionDisplay("Error while creating node source '" + nodeSourceName, e); <ide> } <ide> } <ide>
Java
apache-2.0
cbadaea8f846ebf9f7abe7057ab93a6a5f07d131
0
apache/solr,apache/solr,apache/solr,apache/solr,apache/solr
package org.apache.lucene.search; /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ import java.io.IOException; import java.util.List; import java.util.concurrent.CountDownLatch; import java.util.concurrent.ExecutorService; import java.util.concurrent.atomic.AtomicBoolean; import org.apache.lucene.analysis.Analyzer; import org.apache.lucene.analysis.MockAnalyzer; import org.apache.lucene.document.Document; import org.apache.lucene.document.Field; import org.apache.lucene.index.DirectoryReader; import org.apache.lucene.index.IndexDocument; import org.apache.lucene.index.IndexReader; import org.apache.lucene.index.IndexWriter; import org.apache.lucene.index.IndexWriterConfig; import org.apache.lucene.index.NoMergePolicy; import org.apache.lucene.index.RandomIndexWriter; import org.apache.lucene.index.Term; import org.apache.lucene.index.ThreadedIndexingAndSearchingTestCase; import org.apache.lucene.store.Directory; import org.apache.lucene.store.NRTCachingDirectory; import org.apache.lucene.util.IOUtils; import org.apache.lucene.util.LuceneTestCase.SuppressCodecs; import org.apache.lucene.util.ThreadInterruptedException; @SuppressCodecs({ "SimpleText", "Memory", "Direct" }) public class TestNRTManager extends ThreadedIndexingAndSearchingTestCase { private final ThreadLocal<Long> lastGens = new ThreadLocal<Long>(); private boolean warmCalled; public void testNRTManager() throws Exception { runTest("TestNRTManager"); } @Override protected IndexSearcher getFinalSearcher() throws Exception { if (VERBOSE) { System.out.println("TEST: finalSearcher maxGen=" + maxGen); } nrtDeletes.waitForGeneration(maxGen); return nrtDeletes.acquire(); } @Override protected Directory getDirectory(Directory in) { // Randomly swap in NRTCachingDir if (random().nextBoolean()) { if (VERBOSE) { System.out.println("TEST: wrap NRTCachingDir"); } return new NRTCachingDirectory(in, 5.0, 60.0); } else { return in; } } @Override protected void updateDocuments(Term id, List<? extends IndexDocument> docs) throws Exception { final long gen = genWriter.updateDocuments(id, docs); // Randomly verify the update "took": if (random().nextInt(20) == 2) { if (VERBOSE) { System.out.println(Thread.currentThread().getName() + ": nrt: verify " + id); } nrtDeletes.waitForGeneration(gen); final IndexSearcher s = nrtDeletes.acquire(); if (VERBOSE) { System.out.println(Thread.currentThread().getName() + ": nrt: got searcher=" + s); } try { assertEquals(docs.size(), s.search(new TermQuery(id), 10).totalHits); } finally { nrtDeletes.release(s); } } lastGens.set(gen); } @Override protected void addDocuments(Term id, List<? extends IndexDocument> docs) throws Exception { final long gen = genWriter.addDocuments(docs); // Randomly verify the add "took": if (random().nextInt(20) == 2) { if (VERBOSE) { System.out.println(Thread.currentThread().getName() + ": nrt: verify " + id); } nrtNoDeletes.waitForGeneration(gen); final IndexSearcher s = nrtNoDeletes.acquire(); if (VERBOSE) { System.out.println(Thread.currentThread().getName() + ": nrt: got searcher=" + s); } try { assertEquals(docs.size(), s.search(new TermQuery(id), 10).totalHits); } finally { nrtNoDeletes.release(s); } } lastGens.set(gen); } @Override protected void addDocument(Term id, IndexDocument doc) throws Exception { final long gen = genWriter.addDocument(doc); // Randomly verify the add "took": if (random().nextInt(20) == 2) { if (VERBOSE) { System.out.println(Thread.currentThread().getName() + ": nrt: verify " + id); } nrtNoDeletes.waitForGeneration(gen); final IndexSearcher s = nrtNoDeletes.acquire(); if (VERBOSE) { System.out.println(Thread.currentThread().getName() + ": nrt: got searcher=" + s); } try { assertEquals(1, s.search(new TermQuery(id), 10).totalHits); } finally { nrtNoDeletes.release(s); } } lastGens.set(gen); } @Override protected void updateDocument(Term id, IndexDocument doc) throws Exception { final long gen = genWriter.updateDocument(id, doc); // Randomly verify the udpate "took": if (random().nextInt(20) == 2) { if (VERBOSE) { System.out.println(Thread.currentThread().getName() + ": nrt: verify " + id); } nrtDeletes.waitForGeneration(gen); final IndexSearcher s = nrtDeletes.acquire(); if (VERBOSE) { System.out.println(Thread.currentThread().getName() + ": nrt: got searcher=" + s); } try { assertEquals(1, s.search(new TermQuery(id), 10).totalHits); } finally { nrtDeletes.release(s); } } lastGens.set(gen); } @Override protected void deleteDocuments(Term id) throws Exception { final long gen = genWriter.deleteDocuments(id); // randomly verify the delete "took": if (random().nextInt(20) == 7) { if (VERBOSE) { System.out.println(Thread.currentThread().getName() + ": nrt: verify del " + id); } nrtDeletes.waitForGeneration(gen); final IndexSearcher s = nrtDeletes.acquire(); if (VERBOSE) { System.out.println(Thread.currentThread().getName() + ": nrt: got searcher=" + s); } try { assertEquals(0, s.search(new TermQuery(id), 10).totalHits); } finally { nrtDeletes.release(s); } } lastGens.set(gen); } // Not guaranteed to reflect deletes: private NRTManager nrtNoDeletes; // Is guaranteed to reflect deletes: private NRTManager nrtDeletes; private NRTManager.TrackingIndexWriter genWriter; private NRTManagerReopenThread nrtDeletesThread; private NRTManagerReopenThread nrtNoDeletesThread; @Override protected void doAfterWriter(final ExecutorService es) throws Exception { final double minReopenSec = 0.01 + 0.05 * random().nextDouble(); final double maxReopenSec = minReopenSec * (1.0 + 10 * random().nextDouble()); if (VERBOSE) { System.out.println("TEST: make NRTManager maxReopenSec=" + maxReopenSec + " minReopenSec=" + minReopenSec); } genWriter = new NRTManager.TrackingIndexWriter(writer); final SearcherFactory sf = new SearcherFactory() { @Override public IndexSearcher newSearcher(IndexReader r) throws IOException { TestNRTManager.this.warmCalled = true; IndexSearcher s = new IndexSearcher(r, es); s.search(new TermQuery(new Term("body", "united")), 10); return s; } }; nrtNoDeletes = new NRTManager(genWriter, sf, false); nrtDeletes = new NRTManager(genWriter, sf, true); nrtDeletesThread = new NRTManagerReopenThread(nrtDeletes, maxReopenSec, minReopenSec); nrtDeletesThread.setName("NRTDeletes Reopen Thread"); nrtDeletesThread.setPriority(Math.min(Thread.currentThread().getPriority()+2, Thread.MAX_PRIORITY)); nrtDeletesThread.setDaemon(true); nrtDeletesThread.start(); nrtNoDeletesThread = new NRTManagerReopenThread(nrtNoDeletes, maxReopenSec, minReopenSec); nrtNoDeletesThread.setName("NRTNoDeletes Reopen Thread"); nrtNoDeletesThread.setPriority(Math.min(Thread.currentThread().getPriority()+2, Thread.MAX_PRIORITY)); nrtNoDeletesThread.setDaemon(true); nrtNoDeletesThread.start(); } @Override protected void doAfterIndexingThreadDone() { Long gen = lastGens.get(); if (gen != null) { addMaxGen(gen); } } private long maxGen = -1; private synchronized void addMaxGen(long gen) { maxGen = Math.max(gen, maxGen); } @Override protected void doSearching(ExecutorService es, long stopTime) throws Exception { runSearchThreads(stopTime); } @Override protected IndexSearcher getCurrentSearcher() throws Exception { // Test doesn't assert deletions until the end, so we // can randomize whether dels must be applied final NRTManager nrt; if (random().nextBoolean()) { nrt = nrtDeletes; } else { nrt = nrtNoDeletes; } return nrt.acquire(); } @Override protected void releaseSearcher(IndexSearcher s) throws Exception { // NOTE: a bit iffy... technically you should release // against the same NRT mgr you acquired from... but // both impls just decRef the underlying reader so we // can get away w/ cheating: nrtNoDeletes.release(s); } @Override protected void doClose() throws Exception { assertTrue(warmCalled); if (VERBOSE) { System.out.println("TEST: now close NRTManager"); } nrtDeletesThread.close(); nrtDeletes.close(); nrtNoDeletesThread.close(); nrtNoDeletes.close(); } /* * LUCENE-3528 - NRTManager hangs in certain situations */ public void testThreadStarvationNoDeleteNRTReader() throws IOException, InterruptedException { IndexWriterConfig conf = newIndexWriterConfig(TEST_VERSION_CURRENT, new MockAnalyzer(random())); conf.setMergePolicy(random().nextBoolean() ? NoMergePolicy.COMPOUND_FILES : NoMergePolicy.NO_COMPOUND_FILES); Directory d = newDirectory(); final CountDownLatch latch = new CountDownLatch(1); final CountDownLatch signal = new CountDownLatch(1); LatchedIndexWriter _writer = new LatchedIndexWriter(d, conf, latch, signal); final NRTManager.TrackingIndexWriter writer = new NRTManager.TrackingIndexWriter(_writer); final NRTManager manager = new NRTManager(writer, null, false); Document doc = new Document(); doc.add(newTextField("test", "test", Field.Store.YES)); long gen = writer.addDocument(doc); manager.maybeRefresh(); assertFalse(gen < manager.getCurrentSearchingGen()); Thread t = new Thread() { @Override public void run() { try { signal.await(); manager.maybeRefresh(); writer.deleteDocuments(new TermQuery(new Term("foo", "barista"))); manager.maybeRefresh(); // kick off another reopen so we inc. the internal gen } catch (Exception e) { e.printStackTrace(); } finally { latch.countDown(); // let the add below finish } } }; t.start(); _writer.waitAfterUpdate = true; // wait in addDocument to let some reopens go through final long lastGen = writer.updateDocument(new Term("foo", "bar"), doc); // once this returns the doc is already reflected in the last reopen assertFalse(manager.isSearcherCurrent()); // false since there is a delete in the queue IndexSearcher searcher = manager.acquire(); try { assertEquals(2, searcher.getIndexReader().numDocs()); } finally { manager.release(searcher); } NRTManagerReopenThread thread = new NRTManagerReopenThread(manager, 0.01, 0.01); thread.start(); // start reopening if (VERBOSE) { System.out.println("waiting now for generation " + lastGen); } final AtomicBoolean finished = new AtomicBoolean(false); Thread waiter = new Thread() { @Override public void run() { manager.waitForGeneration(lastGen); finished.set(true); } }; waiter.start(); manager.maybeRefresh(); waiter.join(1000); if (!finished.get()) { waiter.interrupt(); fail("thread deadlocked on waitForGeneration"); } thread.close(); thread.join(); IOUtils.close(manager, _writer, d); } public static class LatchedIndexWriter extends IndexWriter { private CountDownLatch latch; boolean waitAfterUpdate = false; private CountDownLatch signal; public LatchedIndexWriter(Directory d, IndexWriterConfig conf, CountDownLatch latch, CountDownLatch signal) throws IOException { super(d, conf); this.latch = latch; this.signal = signal; } @Override public void updateDocument(Term term, IndexDocument doc, Analyzer analyzer) throws IOException { super.updateDocument(term, doc, analyzer); try { if (waitAfterUpdate) { signal.countDown(); latch.await(); } } catch (InterruptedException e) { throw new ThreadInterruptedException(e); } } } public void testEvilSearcherFactory() throws Exception { final Directory dir = newDirectory(); final RandomIndexWriter w = new RandomIndexWriter(random(), dir); w.commit(); final IndexReader other = DirectoryReader.open(dir); final SearcherFactory theEvilOne = new SearcherFactory() { @Override public IndexSearcher newSearcher(IndexReader ignored) { return new IndexSearcher(other); } }; try { new NRTManager(new NRTManager.TrackingIndexWriter(w.w), theEvilOne); } catch (IllegalStateException ise) { // expected } w.close(); other.close(); dir.close(); } public void testListenerCalled() throws Exception { Directory dir = newDirectory(); IndexWriter iw = new IndexWriter(dir, new IndexWriterConfig(TEST_VERSION_CURRENT, null)); final AtomicBoolean afterRefreshCalled = new AtomicBoolean(false); NRTManager sm = new NRTManager(new NRTManager.TrackingIndexWriter(iw),new SearcherFactory()); sm.addListener(new ReferenceManager.RefreshListener() { @Override public void afterRefresh() { afterRefreshCalled.set(true); } }); iw.addDocument(new Document()); iw.commit(); assertFalse(afterRefreshCalled.get()); sm.maybeRefreshBlocking(); assertTrue(afterRefreshCalled.get()); sm.close(); iw.close(); dir.close(); } }
lucene/core/src/test/org/apache/lucene/search/TestNRTManager.java
package org.apache.lucene.search; /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ import java.io.IOException; import java.util.List; import java.util.concurrent.CountDownLatch; import java.util.concurrent.ExecutorService; import java.util.concurrent.atomic.AtomicBoolean; import org.apache.lucene.analysis.Analyzer; import org.apache.lucene.analysis.MockAnalyzer; import org.apache.lucene.document.Document; import org.apache.lucene.document.Field; import org.apache.lucene.index.DirectoryReader; import org.apache.lucene.index.IndexDocument; import org.apache.lucene.index.IndexReader; import org.apache.lucene.index.IndexWriter; import org.apache.lucene.index.IndexWriterConfig; import org.apache.lucene.index.RandomIndexWriter; import org.apache.lucene.index.Term; import org.apache.lucene.index.ThreadedIndexingAndSearchingTestCase; import org.apache.lucene.store.Directory; import org.apache.lucene.store.NRTCachingDirectory; import org.apache.lucene.util.IOUtils; import org.apache.lucene.util.LuceneTestCase.SuppressCodecs; import org.apache.lucene.util.ThreadInterruptedException; @SuppressCodecs({ "SimpleText", "Memory", "Direct" }) public class TestNRTManager extends ThreadedIndexingAndSearchingTestCase { private final ThreadLocal<Long> lastGens = new ThreadLocal<Long>(); private boolean warmCalled; public void testNRTManager() throws Exception { runTest("TestNRTManager"); } @Override protected IndexSearcher getFinalSearcher() throws Exception { if (VERBOSE) { System.out.println("TEST: finalSearcher maxGen=" + maxGen); } nrtDeletes.waitForGeneration(maxGen); return nrtDeletes.acquire(); } @Override protected Directory getDirectory(Directory in) { // Randomly swap in NRTCachingDir if (random().nextBoolean()) { if (VERBOSE) { System.out.println("TEST: wrap NRTCachingDir"); } return new NRTCachingDirectory(in, 5.0, 60.0); } else { return in; } } @Override protected void updateDocuments(Term id, List<? extends IndexDocument> docs) throws Exception { final long gen = genWriter.updateDocuments(id, docs); // Randomly verify the update "took": if (random().nextInt(20) == 2) { if (VERBOSE) { System.out.println(Thread.currentThread().getName() + ": nrt: verify " + id); } nrtDeletes.waitForGeneration(gen); final IndexSearcher s = nrtDeletes.acquire(); if (VERBOSE) { System.out.println(Thread.currentThread().getName() + ": nrt: got searcher=" + s); } try { assertEquals(docs.size(), s.search(new TermQuery(id), 10).totalHits); } finally { nrtDeletes.release(s); } } lastGens.set(gen); } @Override protected void addDocuments(Term id, List<? extends IndexDocument> docs) throws Exception { final long gen = genWriter.addDocuments(docs); // Randomly verify the add "took": if (random().nextInt(20) == 2) { if (VERBOSE) { System.out.println(Thread.currentThread().getName() + ": nrt: verify " + id); } nrtNoDeletes.waitForGeneration(gen); final IndexSearcher s = nrtNoDeletes.acquire(); if (VERBOSE) { System.out.println(Thread.currentThread().getName() + ": nrt: got searcher=" + s); } try { assertEquals(docs.size(), s.search(new TermQuery(id), 10).totalHits); } finally { nrtNoDeletes.release(s); } } lastGens.set(gen); } @Override protected void addDocument(Term id, IndexDocument doc) throws Exception { final long gen = genWriter.addDocument(doc); // Randomly verify the add "took": if (random().nextInt(20) == 2) { if (VERBOSE) { System.out.println(Thread.currentThread().getName() + ": nrt: verify " + id); } nrtNoDeletes.waitForGeneration(gen); final IndexSearcher s = nrtNoDeletes.acquire(); if (VERBOSE) { System.out.println(Thread.currentThread().getName() + ": nrt: got searcher=" + s); } try { assertEquals(1, s.search(new TermQuery(id), 10).totalHits); } finally { nrtNoDeletes.release(s); } } lastGens.set(gen); } @Override protected void updateDocument(Term id, IndexDocument doc) throws Exception { final long gen = genWriter.updateDocument(id, doc); // Randomly verify the udpate "took": if (random().nextInt(20) == 2) { if (VERBOSE) { System.out.println(Thread.currentThread().getName() + ": nrt: verify " + id); } nrtDeletes.waitForGeneration(gen); final IndexSearcher s = nrtDeletes.acquire(); if (VERBOSE) { System.out.println(Thread.currentThread().getName() + ": nrt: got searcher=" + s); } try { assertEquals(1, s.search(new TermQuery(id), 10).totalHits); } finally { nrtDeletes.release(s); } } lastGens.set(gen); } @Override protected void deleteDocuments(Term id) throws Exception { final long gen = genWriter.deleteDocuments(id); // randomly verify the delete "took": if (random().nextInt(20) == 7) { if (VERBOSE) { System.out.println(Thread.currentThread().getName() + ": nrt: verify del " + id); } nrtDeletes.waitForGeneration(gen); final IndexSearcher s = nrtDeletes.acquire(); if (VERBOSE) { System.out.println(Thread.currentThread().getName() + ": nrt: got searcher=" + s); } try { assertEquals(0, s.search(new TermQuery(id), 10).totalHits); } finally { nrtDeletes.release(s); } } lastGens.set(gen); } // Not guaranteed to reflect deletes: private NRTManager nrtNoDeletes; // Is guaranteed to reflect deletes: private NRTManager nrtDeletes; private NRTManager.TrackingIndexWriter genWriter; private NRTManagerReopenThread nrtDeletesThread; private NRTManagerReopenThread nrtNoDeletesThread; @Override protected void doAfterWriter(final ExecutorService es) throws Exception { final double minReopenSec = 0.01 + 0.05 * random().nextDouble(); final double maxReopenSec = minReopenSec * (1.0 + 10 * random().nextDouble()); if (VERBOSE) { System.out.println("TEST: make NRTManager maxReopenSec=" + maxReopenSec + " minReopenSec=" + minReopenSec); } genWriter = new NRTManager.TrackingIndexWriter(writer); final SearcherFactory sf = new SearcherFactory() { @Override public IndexSearcher newSearcher(IndexReader r) throws IOException { TestNRTManager.this.warmCalled = true; IndexSearcher s = new IndexSearcher(r, es); s.search(new TermQuery(new Term("body", "united")), 10); return s; } }; nrtNoDeletes = new NRTManager(genWriter, sf, false); nrtDeletes = new NRTManager(genWriter, sf, true); nrtDeletesThread = new NRTManagerReopenThread(nrtDeletes, maxReopenSec, minReopenSec); nrtDeletesThread.setName("NRTDeletes Reopen Thread"); nrtDeletesThread.setPriority(Math.min(Thread.currentThread().getPriority()+2, Thread.MAX_PRIORITY)); nrtDeletesThread.setDaemon(true); nrtDeletesThread.start(); nrtNoDeletesThread = new NRTManagerReopenThread(nrtNoDeletes, maxReopenSec, minReopenSec); nrtNoDeletesThread.setName("NRTNoDeletes Reopen Thread"); nrtNoDeletesThread.setPriority(Math.min(Thread.currentThread().getPriority()+2, Thread.MAX_PRIORITY)); nrtNoDeletesThread.setDaemon(true); nrtNoDeletesThread.start(); } @Override protected void doAfterIndexingThreadDone() { Long gen = lastGens.get(); if (gen != null) { addMaxGen(gen); } } private long maxGen = -1; private synchronized void addMaxGen(long gen) { maxGen = Math.max(gen, maxGen); } @Override protected void doSearching(ExecutorService es, long stopTime) throws Exception { runSearchThreads(stopTime); } @Override protected IndexSearcher getCurrentSearcher() throws Exception { // Test doesn't assert deletions until the end, so we // can randomize whether dels must be applied final NRTManager nrt; if (random().nextBoolean()) { nrt = nrtDeletes; } else { nrt = nrtNoDeletes; } return nrt.acquire(); } @Override protected void releaseSearcher(IndexSearcher s) throws Exception { // NOTE: a bit iffy... technically you should release // against the same NRT mgr you acquired from... but // both impls just decRef the underlying reader so we // can get away w/ cheating: nrtNoDeletes.release(s); } @Override protected void doClose() throws Exception { assertTrue(warmCalled); if (VERBOSE) { System.out.println("TEST: now close NRTManager"); } nrtDeletesThread.close(); nrtDeletes.close(); nrtNoDeletesThread.close(); nrtNoDeletes.close(); } /* * LUCENE-3528 - NRTManager hangs in certain situations */ public void testThreadStarvationNoDeleteNRTReader() throws IOException, InterruptedException { IndexWriterConfig conf = newIndexWriterConfig(TEST_VERSION_CURRENT, new MockAnalyzer(random())); Directory d = newDirectory(); final CountDownLatch latch = new CountDownLatch(1); final CountDownLatch signal = new CountDownLatch(1); LatchedIndexWriter _writer = new LatchedIndexWriter(d, conf, latch, signal); final NRTManager.TrackingIndexWriter writer = new NRTManager.TrackingIndexWriter(_writer); final NRTManager manager = new NRTManager(writer, null, false); Document doc = new Document(); doc.add(newTextField("test", "test", Field.Store.YES)); long gen = writer.addDocument(doc); manager.maybeRefresh(); assertFalse(gen < manager.getCurrentSearchingGen()); Thread t = new Thread() { @Override public void run() { try { signal.await(); manager.maybeRefresh(); writer.deleteDocuments(new TermQuery(new Term("foo", "barista"))); manager.maybeRefresh(); // kick off another reopen so we inc. the internal gen } catch (Exception e) { e.printStackTrace(); } finally { latch.countDown(); // let the add below finish } } }; t.start(); _writer.waitAfterUpdate = true; // wait in addDocument to let some reopens go through final long lastGen = writer.updateDocument(new Term("foo", "bar"), doc); // once this returns the doc is already reflected in the last reopen assertFalse(manager.isSearcherCurrent()); // false since there is a delete in the queue IndexSearcher searcher = manager.acquire(); try { assertEquals(2, searcher.getIndexReader().numDocs()); } finally { manager.release(searcher); } NRTManagerReopenThread thread = new NRTManagerReopenThread(manager, 0.01, 0.01); thread.start(); // start reopening if (VERBOSE) { System.out.println("waiting now for generation " + lastGen); } final AtomicBoolean finished = new AtomicBoolean(false); Thread waiter = new Thread() { @Override public void run() { manager.waitForGeneration(lastGen); finished.set(true); } }; waiter.start(); manager.maybeRefresh(); waiter.join(1000); if (!finished.get()) { waiter.interrupt(); fail("thread deadlocked on waitForGeneration"); } thread.close(); thread.join(); IOUtils.close(manager, _writer, d); } public static class LatchedIndexWriter extends IndexWriter { private CountDownLatch latch; boolean waitAfterUpdate = false; private CountDownLatch signal; public LatchedIndexWriter(Directory d, IndexWriterConfig conf, CountDownLatch latch, CountDownLatch signal) throws IOException { super(d, conf); this.latch = latch; this.signal = signal; } @Override public void updateDocument(Term term, IndexDocument doc, Analyzer analyzer) throws IOException { super.updateDocument(term, doc, analyzer); try { if (waitAfterUpdate) { signal.countDown(); latch.await(); } } catch (InterruptedException e) { throw new ThreadInterruptedException(e); } } } public void testEvilSearcherFactory() throws Exception { final Directory dir = newDirectory(); final RandomIndexWriter w = new RandomIndexWriter(random(), dir); w.commit(); final IndexReader other = DirectoryReader.open(dir); final SearcherFactory theEvilOne = new SearcherFactory() { @Override public IndexSearcher newSearcher(IndexReader ignored) { return new IndexSearcher(other); } }; try { new NRTManager(new NRTManager.TrackingIndexWriter(w.w), theEvilOne); } catch (IllegalStateException ise) { // expected } w.close(); other.close(); dir.close(); } public void testListenerCalled() throws Exception { Directory dir = newDirectory(); IndexWriter iw = new IndexWriter(dir, new IndexWriterConfig(TEST_VERSION_CURRENT, null)); final AtomicBoolean afterRefreshCalled = new AtomicBoolean(false); NRTManager sm = new NRTManager(new NRTManager.TrackingIndexWriter(iw),new SearcherFactory()); sm.addListener(new ReferenceManager.RefreshListener() { @Override public void afterRefresh() { afterRefreshCalled.set(true); } }); iw.addDocument(new Document()); iw.commit(); assertFalse(afterRefreshCalled.get()); sm.maybeRefreshBlocking(); assertTrue(afterRefreshCalled.get()); sm.close(); iw.close(); dir.close(); } }
LUCENE-4676: Use NoMergePolicy in starvation test to prevent buffered deletes pruning git-svn-id: 308d55f399f3bd9aa0560a10e81a003040006c48@1433079 13f79535-47bb-0310-9956-ffa450edef68
lucene/core/src/test/org/apache/lucene/search/TestNRTManager.java
LUCENE-4676: Use NoMergePolicy in starvation test to prevent buffered deletes pruning
<ide><path>ucene/core/src/test/org/apache/lucene/search/TestNRTManager.java <ide> import org.apache.lucene.index.IndexReader; <ide> import org.apache.lucene.index.IndexWriter; <ide> import org.apache.lucene.index.IndexWriterConfig; <add>import org.apache.lucene.index.NoMergePolicy; <ide> import org.apache.lucene.index.RandomIndexWriter; <ide> import org.apache.lucene.index.Term; <ide> import org.apache.lucene.index.ThreadedIndexingAndSearchingTestCase; <ide> */ <ide> public void testThreadStarvationNoDeleteNRTReader() throws IOException, InterruptedException { <ide> IndexWriterConfig conf = newIndexWriterConfig(TEST_VERSION_CURRENT, new MockAnalyzer(random())); <add> conf.setMergePolicy(random().nextBoolean() ? NoMergePolicy.COMPOUND_FILES : NoMergePolicy.NO_COMPOUND_FILES); <ide> Directory d = newDirectory(); <ide> final CountDownLatch latch = new CountDownLatch(1); <ide> final CountDownLatch signal = new CountDownLatch(1);
Java
apache-2.0
1d30c1d800beca6f0e9cdb265aea7cba5876f173
0
apache/commons-chain,apache/commons-chain,apache/commons-chain
/* * 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.commons.chain.web.servlet; import javax.servlet.RequestDispatcher; import javax.servlet.Servlet; import javax.servlet.ServletContext; import javax.servlet.ServletException; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import java.io.InputStream; import java.net.MalformedURLException; import java.net.URL; import java.util.Enumeration; import java.util.Hashtable; import java.util.Set; // Mock Object for ServletContext (Version 2.3) public class MockServletContext implements ServletContext { private Log log = LogFactory.getLog(MockServletContext.class); private Hashtable attributes = new Hashtable(); private Hashtable parameters = new Hashtable(); // --------------------------------------------------------- Public Methods public void addInitParameter(String name, String value) { parameters.put(name, value); } // ------------------------------------------------- ServletContext Methods public Object getAttribute(String name) { return (attributes.get(name)); } public Enumeration getAttributeNames() { return (attributes.keys()); } public ServletContext getContext(String uripath) { throw new UnsupportedOperationException(); } public String getInitParameter(String name) { return ((String) parameters.get(name)); } public Enumeration getInitParameterNames() { return (parameters.keys()); } public int getMajorVersion() { return (2); } public String getMimeType(String path) { throw new UnsupportedOperationException(); } public int getMinorVersion() { return (3); } public RequestDispatcher getNamedDispatcher(String name) { throw new UnsupportedOperationException(); } public String getRealPath(String path) { throw new UnsupportedOperationException(); } public RequestDispatcher getRequestDispatcher(String path) { throw new UnsupportedOperationException(); } public URL getResource(String path) throws MalformedURLException { throw new UnsupportedOperationException(); } public InputStream getResourceAsStream(String path) { throw new UnsupportedOperationException(); } public Set getResourcePaths(String path) { throw new UnsupportedOperationException(); } public Servlet getServlet(String name) throws ServletException { throw new UnsupportedOperationException(); } public String getServletContextName() { return ("MockServletContext"); } public String getServerInfo() { return ("MockServletContext"); } public Enumeration getServlets() { throw new UnsupportedOperationException(); } public Enumeration getServletNames() { throw new UnsupportedOperationException(); } public void log(String message) { log.info(message); } public void log(Exception exception, String message) { log.error(message, exception); } public void log(String message, Throwable exception) { log.error(message, exception); } public void removeAttribute(String name) { attributes.remove(name); } public void setAttribute(String name, Object value) { attributes.put(name, value); } }
src/test/org/apache/commons/chain/web/servlet/MockServletContext.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.chain.web.servlet; import javax.servlet.RequestDispatcher; import javax.servlet.Servlet; import javax.servlet.ServletContext; import javax.servlet.ServletException; import java.io.InputStream; import java.net.MalformedURLException; import java.net.URL; import java.util.Enumeration; import java.util.Hashtable; import java.util.Set; // Mock Object for ServletContext (Version 2.3) public class MockServletContext implements ServletContext { private Hashtable attributes = new Hashtable(); private Hashtable parameters = new Hashtable(); // --------------------------------------------------------- Public Methods public void addInitParameter(String name, String value) { parameters.put(name, value); } // ------------------------------------------------- ServletContext Methods public Object getAttribute(String name) { return (attributes.get(name)); } public Enumeration getAttributeNames() { return (attributes.keys()); } public ServletContext getContext(String uripath) { throw new UnsupportedOperationException(); } public String getInitParameter(String name) { return ((String) parameters.get(name)); } public Enumeration getInitParameterNames() { return (parameters.keys()); } public int getMajorVersion() { return (2); } public String getMimeType(String path) { throw new UnsupportedOperationException(); } public int getMinorVersion() { return (3); } public RequestDispatcher getNamedDispatcher(String name) { throw new UnsupportedOperationException(); } public String getRealPath(String path) { throw new UnsupportedOperationException(); } public RequestDispatcher getRequestDispatcher(String path) { throw new UnsupportedOperationException(); } public URL getResource(String path) throws MalformedURLException { throw new UnsupportedOperationException(); } public InputStream getResourceAsStream(String path) { throw new UnsupportedOperationException(); } public Set getResourcePaths(String path) { throw new UnsupportedOperationException(); } public Servlet getServlet(String name) throws ServletException { throw new UnsupportedOperationException(); } public String getServletContextName() { return ("MockServletContext"); } public String getServerInfo() { return ("MockServletContext"); } public Enumeration getServlets() { throw new UnsupportedOperationException(); } public Enumeration getServletNames() { throw new UnsupportedOperationException(); } public void log(String message) { throw new UnsupportedOperationException(); } public void log(Exception exception, String message) { throw new UnsupportedOperationException(); } public void log(String message, Throwable exception) { throw new UnsupportedOperationException(); } public void removeAttribute(String name) { attributes.remove(name); } public void setAttribute(String name, Object value) { attributes.put(name, value); } }
implement log() methods git-svn-id: 09202cd7a08c7d0e03544b190c2294d96b23c5f4@661352 13f79535-47bb-0310-9956-ffa450edef68
src/test/org/apache/commons/chain/web/servlet/MockServletContext.java
implement log() methods
<ide><path>rc/test/org/apache/commons/chain/web/servlet/MockServletContext.java <ide> import javax.servlet.Servlet; <ide> import javax.servlet.ServletContext; <ide> import javax.servlet.ServletException; <add> <add>import org.apache.commons.logging.Log; <add>import org.apache.commons.logging.LogFactory; <add> <ide> import java.io.InputStream; <ide> import java.net.MalformedURLException; <ide> import java.net.URL; <ide> public class MockServletContext implements ServletContext { <ide> <ide> <add> private Log log = LogFactory.getLog(MockServletContext.class); <ide> private Hashtable attributes = new Hashtable(); <ide> private Hashtable parameters = new Hashtable(); <ide> <ide> } <ide> <ide> public void log(String message) { <del> throw new UnsupportedOperationException(); <add> log.info(message); <ide> } <ide> <ide> public void log(Exception exception, String message) { <del> throw new UnsupportedOperationException(); <add> log.error(message, exception); <ide> } <ide> <ide> public void log(String message, Throwable exception) { <del> throw new UnsupportedOperationException(); <add> log.error(message, exception); <ide> } <ide> <ide> public void removeAttribute(String name) {
Java
mit
dbb43566fed45a9ecbee9c4741fe3019c071b3bf
0
CS2103AUG2016-T09-C2/main,CS2103AUG2016-T09-C2/main
package seedu.jimi.logic.commands; /** * * @author Wei Yin * * Sets save directory for the tasks and events in Jimi. */ public class SaveAsCommand extends Command { public static final String COMMAND_WORD = "saveas"; public static final String MESSAGE_USAGE = COMMAND_WORD + ": Set a new save directory for all your tasks and events in Jimi.\n" + "Parameters: FILEPATH/FILENAME.xml \n" + "Example: " + COMMAND_WORD + " saveas C:/dropbox/taskbook.xml"; public static final String MESSAGE_SUCCESS = "Save directory changed: %1$s"; public static final String MESSAGE_DUPLICATE_TASK = "This save directory is originally used in Jimi"; private String taskBookFilePath; /** * Convenience constructor using raw values. */ public SaveAsCommand(String filePath) { this.taskBookFilePath = filePath; } @Override public CommandResult execute() { // TODO Auto-generated method stub return null; } }
src/main/java/seedu/jimi/logic/commands/SaveAsCommand.java
package seedu.jimi.logic.commands; /** * * @author Wei Yin * * Sets save directory for the tasks and events in Jimi. */ public class SaveAsCommand extends Command { public static final String COMMAND_WORD = "saveas"; public static final String MESSAGE_USAGE = COMMAND_WORD + ": Set a new save directory for all your tasks and events in Jimi.\n" + "Parameters: FILEPATH/FILENAME.xml \n" + "Example: " + COMMAND_WORD + " saveas C:/dropbox/taskbook.xml"; public static final String MESSAGE_SUCCESS = "Save directory changed: %1$s"; public static final String MESSAGE_DUPLICATE_TASK = "This save directory is originally used in Jimi"; @Override public CommandResult execute() { // TODO Auto-generated method stub return null; } }
Implement constructors for SaveAsCommand
src/main/java/seedu/jimi/logic/commands/SaveAsCommand.java
Implement constructors for SaveAsCommand
<ide><path>rc/main/java/seedu/jimi/logic/commands/SaveAsCommand.java <ide> public static final String MESSAGE_SUCCESS = "Save directory changed: %1$s"; <ide> public static final String MESSAGE_DUPLICATE_TASK = "This save directory is originally used in Jimi"; <ide> <add> private String taskBookFilePath; <ide> <add> /** <add> * Convenience constructor using raw values. <add> */ <add> public SaveAsCommand(String filePath) { <add> this.taskBookFilePath = filePath; <add> } <add> <ide> @Override <ide> public CommandResult execute() { <ide> // TODO Auto-generated method stub
Java
mit
9c34ec23a82427ba0807eeffbbf4449e1535ba92
0
joshsh/smsn,joshsh/extendo,joshsh/smsn,joshsh/smsn,joshsh/extendo,joshsh/smsn,joshsh/extendo,joshsh/smsn,joshsh/smsn,joshsh/extendo,joshsh/extendo,joshsh/extendo,joshsh/smsn,joshsh/extendo
package net.fortytwo.extendo.p2p; import net.fortytwo.extendo.Extendo; import net.fortytwo.extendo.util.properties.PropertyException; import org.json.JSONException; import org.json.JSONObject; import java.io.IOException; import java.net.DatagramPacket; import java.net.DatagramSocket; import java.net.InetAddress; import java.util.logging.Logger; /** * @author Joshua Shinavier (http://fortytwo.net) */ public class ServiceBroadcaster { protected static final Logger LOGGER = Logger.getLogger(ServiceBroadcaster.class.getName()); // TODO: make this configurable private static final long MAX_BACKOFF = 60000; private final ServiceDescription serviceDescription; private boolean stopped; public ServiceBroadcaster(final ServiceDescription serviceDescription) { this.serviceDescription = serviceDescription; } public void start() { stopped = false; new Thread(new Runnable() { public void run() { LOGGER.info("starting service broadcaster thread"); try { sendBroadcastMessages(); } catch (Throwable t) { LOGGER.severe("service broadcaster thread failed: " + t.getMessage()); t.printStackTrace(System.err); } LOGGER.info("service broadcaster thread stopped"); } }).start(); } public void stop() { stopped = true; } private void sendBroadcastMessages() { long broadcastInterval; int port; try { broadcastInterval = Extendo.getConfiguration().getLong(Extendo.P2P_BROADCAST_INTERVAL); port = Extendo.getConfiguration().getInt(Extendo.P2P_BROADCAST_PORT); } catch (PropertyException e) { LOGGER.severe("error accessing config properties when sending broadcast message: " + e.getMessage()); e.printStackTrace(System.err); return; } JSONObject j; try { j = serviceDescription.toJSON(); } catch (JSONException e) { LOGGER.severe("error creating JSON content of broadcast message: " + e.getMessage()); e.printStackTrace(System.err); return; } byte[] buffer = j.toString().getBytes(); long backoff = broadcastInterval; // outer loop recovers from IO errors while (!stopped) { try { // TODO: temporary InetAddress broadcastAddress = InetAddress.getByName("10.0.2.255"); DatagramPacket packet; packet = new DatagramPacket(buffer, buffer.length, broadcastAddress, port); DatagramSocket socket = new DatagramSocket(); socket.setBroadcast(true); try { // inner loop repeatedly sends a broadcast message in absence of errors while (!stopped) { LOGGER.fine("sending broadcast message: " + j); socket.send(packet); backoff = broadcastInterval; try { Thread.sleep(broadcastInterval); } catch (InterruptedException e) { LOGGER.warning("error while waiting to send next broadcast: " + e.getMessage()); e.printStackTrace(System.err); return; } } } finally { socket.close(); } } catch (IOException e) { LOGGER.warning("error while sending broadcast message(s): " + e.getMessage()); //e.printStackTrace(System.err); backoff *= 2; if (backoff > MAX_BACKOFF) { backoff = MAX_BACKOFF; } LOGGER.info("waiting " + backoff + "ms before next broadcast"); try { Thread.sleep(backoff); } catch (InterruptedException e2) { LOGGER.warning("error while waiting to reopen broadcast socket: " + e.getMessage()); e2.printStackTrace(System.err); return; } } } } }
extendo-p2p/src/main/java/net/fortytwo/extendo/p2p/ServiceBroadcaster.java
package net.fortytwo.extendo.p2p; import net.fortytwo.extendo.Extendo; import net.fortytwo.extendo.util.properties.PropertyException; import org.json.JSONException; import org.json.JSONObject; import java.io.IOException; import java.net.DatagramPacket; import java.net.DatagramSocket; import java.net.InetAddress; import java.util.logging.Logger; /** * @author Joshua Shinavier (http://fortytwo.net) */ public class ServiceBroadcaster { protected static final Logger LOGGER = Logger.getLogger(ServiceBroadcaster.class.getName()); private final ServiceDescription serviceDescription; private boolean stopped; public ServiceBroadcaster(final ServiceDescription serviceDescription) { this.serviceDescription = serviceDescription; } public void start() { stopped = false; new Thread(new Runnable() { public void run() { LOGGER.info("listening for facilitator broadcast messages"); try { sendBroadcastMessages(); } catch (Throwable t) { LOGGER.severe("broadcast message listener thread failed: " + t.getMessage()); t.printStackTrace(System.err); } LOGGER.info("broadcast message listener stopped"); } }).start(); } public void stop() { stopped = true; } private void sendBroadcastMessages() { try { DatagramSocket socket = new DatagramSocket(); socket.setBroadcast(true); try { long broadcastInterval = Extendo.getConfiguration().getLong(Extendo.P2P_BROADCAST_INTERVAL); JSONObject j = serviceDescription.toJSON(); byte[] buffer = j.toString().getBytes(); // TODO: temporary InetAddress broadcastAddress = InetAddress.getByName("10.0.2.255"); int port = Extendo.getConfiguration().getInt(Extendo.P2P_BROADCAST_PORT); DatagramPacket packet; packet = new DatagramPacket(buffer, buffer.length, broadcastAddress, port); while (!stopped) { LOGGER.fine("sending broadcast message: " + j); socket.send(packet); try { Thread.sleep(broadcastInterval); } catch (InterruptedException e) { LOGGER.warning("error while waiting to send next broadcast: " + e.getMessage()); e.printStackTrace(System.err); break; } } } finally { socket.close(); } } catch (IOException e) { LOGGER.severe("error while sending broadcast message(s): " + e.getMessage()); e.printStackTrace(System.err); } catch (JSONException e) { LOGGER.severe("error creating JSON content of broadcast message: " + e.getMessage()); e.printStackTrace(System.err); } catch (PropertyException e) { LOGGER.severe("error accessing config properties when sending broadcast message: " + e.getMessage()); e.printStackTrace(System.err); } } }
Service broadcaster now recovers from IO errors (e.g. due to a down network), backing off exponentially up to a fixed interval
extendo-p2p/src/main/java/net/fortytwo/extendo/p2p/ServiceBroadcaster.java
Service broadcaster now recovers from IO errors (e.g. due to a down network), backing off exponentially up to a fixed interval
<ide><path>xtendo-p2p/src/main/java/net/fortytwo/extendo/p2p/ServiceBroadcaster.java <ide> import java.util.logging.Logger; <ide> <ide> /** <del>* @author Joshua Shinavier (http://fortytwo.net) <del>*/ <add> * @author Joshua Shinavier (http://fortytwo.net) <add> */ <ide> public class ServiceBroadcaster { <ide> protected static final Logger LOGGER = Logger.getLogger(ServiceBroadcaster.class.getName()); <add> <add> // TODO: make this configurable <add> private static final long MAX_BACKOFF = 60000; <ide> <ide> private final ServiceDescription serviceDescription; <ide> <ide> <ide> new Thread(new Runnable() { <ide> public void run() { <del> LOGGER.info("listening for facilitator broadcast messages"); <add> LOGGER.info("starting service broadcaster thread"); <ide> <ide> try { <ide> sendBroadcastMessages(); <ide> } catch (Throwable t) { <del> LOGGER.severe("broadcast message listener thread failed: " + t.getMessage()); <add> LOGGER.severe("service broadcaster thread failed: " + t.getMessage()); <ide> t.printStackTrace(System.err); <ide> } <ide> <del> LOGGER.info("broadcast message listener stopped"); <add> LOGGER.info("service broadcaster thread stopped"); <ide> } <ide> }).start(); <ide> } <ide> } <ide> <ide> private void sendBroadcastMessages() { <add> long broadcastInterval; <add> int port; <add> <ide> try { <del> DatagramSocket socket = new DatagramSocket(); <del> socket.setBroadcast(true); <add> broadcastInterval = Extendo.getConfiguration().getLong(Extendo.P2P_BROADCAST_INTERVAL); <add> port = Extendo.getConfiguration().getInt(Extendo.P2P_BROADCAST_PORT); <add> } catch (PropertyException e) { <add> LOGGER.severe("error accessing config properties when sending broadcast message: " + e.getMessage()); <add> e.printStackTrace(System.err); <add> return; <add> } <ide> <add> JSONObject j; <add> try { <add> j = serviceDescription.toJSON(); <add> } catch (JSONException e) { <add> LOGGER.severe("error creating JSON content of broadcast message: " + e.getMessage()); <add> e.printStackTrace(System.err); <add> return; <add> } <add> byte[] buffer = j.toString().getBytes(); <add> <add> long backoff = broadcastInterval; <add> <add> // outer loop recovers from IO errors <add> while (!stopped) { <ide> try { <del> long broadcastInterval = Extendo.getConfiguration().getLong(Extendo.P2P_BROADCAST_INTERVAL); <del> <del> JSONObject j = serviceDescription.toJSON(); <del> byte[] buffer = j.toString().getBytes(); <del> <ide> // TODO: temporary <ide> InetAddress broadcastAddress = InetAddress.getByName("10.0.2.255"); <del> <del> int port = Extendo.getConfiguration().getInt(Extendo.P2P_BROADCAST_PORT); <ide> <ide> DatagramPacket packet; <ide> packet = new DatagramPacket(buffer, buffer.length, broadcastAddress, port); <ide> <del> while (!stopped) { <del> LOGGER.fine("sending broadcast message: " + j); <del> socket.send(packet); <add> DatagramSocket socket = new DatagramSocket(); <add> socket.setBroadcast(true); <ide> <del> try { <del> Thread.sleep(broadcastInterval); <del> } catch (InterruptedException e) { <del> LOGGER.warning("error while waiting to send next broadcast: " + e.getMessage()); <del> e.printStackTrace(System.err); <del> break; <add> try { <add> // inner loop repeatedly sends a broadcast message in absence of errors <add> while (!stopped) { <add> LOGGER.fine("sending broadcast message: " + j); <add> socket.send(packet); <add> <add> backoff = broadcastInterval; <add> <add> try { <add> Thread.sleep(broadcastInterval); <add> } catch (InterruptedException e) { <add> LOGGER.warning("error while waiting to send next broadcast: " + e.getMessage()); <add> e.printStackTrace(System.err); <add> return; <add> } <ide> } <add> } finally { <add> socket.close(); <ide> } <del> } finally { <del> socket.close(); <add> } catch (IOException e) { <add> LOGGER.warning("error while sending broadcast message(s): " + e.getMessage()); <add> //e.printStackTrace(System.err); <add> backoff *= 2; <add> if (backoff > MAX_BACKOFF) { <add> backoff = MAX_BACKOFF; <add> } <add> <add> LOGGER.info("waiting " + backoff + "ms before next broadcast"); <add> try { <add> Thread.sleep(backoff); <add> } catch (InterruptedException e2) { <add> LOGGER.warning("error while waiting to reopen broadcast socket: " + e.getMessage()); <add> e2.printStackTrace(System.err); <add> return; <add> } <ide> } <del> } catch (IOException e) { <del> LOGGER.severe("error while sending broadcast message(s): " + e.getMessage()); <del> e.printStackTrace(System.err); <del> } catch (JSONException e) { <del> LOGGER.severe("error creating JSON content of broadcast message: " + e.getMessage()); <del> e.printStackTrace(System.err); <del> } catch (PropertyException e) { <del> LOGGER.severe("error accessing config properties when sending broadcast message: " + e.getMessage()); <del> e.printStackTrace(System.err); <ide> } <ide> } <ide> }
JavaScript
mit
cbe3bced0531ea697bfd1e6c301fe12d282e65a9
0
trailsjs/trailpack-repl
'use strict' const repl = require('repl') const Trailpack = require('trailpack') const lib = require('./lib') /** * @class REPL * * Provide an interactive Javascript shell for Trails applications * * @see {@link https://nodejs.org/api/repl.html#repl_repl} */ module.exports = class REPL extends Trailpack { configure() { lib.Inspect.configureApp(this.app) lib.Inspect.configureApi(this.app.api) lib.Inspect.configurePacks(this.app.packs) lib.Http.init(this.app) } initialize() { this.app.once('trails:ready', () => { this.server = repl.start({ // green prompt prompt: '\u001b[1;32mtrails > \u001b[0m', useColors: true }) this.server.once('exit', () => { this.app.stop().then(() => process.exit()) }) this.server.context.app = this.app this.server.context.get = lib.Http.get.bind(lib.Http) this.server.context.post = lib.Http.post.bind(lib.Http) this.server.context.put = lib.Http.put.bind(lib.Http) this.server.context.delete = lib.Http.delete.bind(lib.Http) }) } unload () { this.server.removeAllListeners() this.server.close() } constructor(app) { super(app, { config: require('./config'), pkg: require('./package') }) } }
index.js
'use strict' const repl = require('repl') const Trailpack = require('trailpack') const lib = require('./lib') /** * @class REPL * * Provide an interactive Javascript shell for Trails applications * * @see {@link https://nodejs.org/api/repl.html#repl_repl} */ module.exports = class REPL extends Trailpack { configure() { lib.Inspect.configureApp(this.app) lib.Inspect.configureApi(this.app.api) lib.Inspect.configurePacks(this.app.packs) lib.Http.init(this.app) } initialize() { this.app.once('trails:ready', () => { this.server = repl.start({ // green prompt prompt: '\u001b[1;32mtrails > \u001b[0m', useColors: true }) this.server.once('exit', () => { this.app.stop().then(() => process.exit()) }) this.server.context.app = this.app this.server.context.get = lib.Http.get.bind(lib.Http) this.server.context.post = lib.Http.post.bind(lib.Http) this.server.context.put = lib.Http.put.bind(lib.Http) this.server.context.delete = lib.Http.delete.bind(lib.Http) }) } unload () { this.server.close() } constructor(app) { super(app, { config: require('./config'), pkg: require('./package') }) } }
[fix] remove listeners on unload
index.js
[fix] remove listeners on unload
<ide><path>ndex.js <ide> } <ide> <ide> unload () { <add> this.server.removeAllListeners() <ide> this.server.close() <ide> } <ide>
Java
apache-2.0
beeb8d217110045a0c6b186b861f6cc1792b4db3
0
Maurice-Betzel/lmdbjava-jca-resource-adapter,Maurice-Betzel/lmdbjava-resource-adapter
/* Copyright 2017 Maurice Betzel Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ package net.betzel.lmdb.jca; import javax.transaction.xa.XAException; import javax.transaction.xa.XAResource; import javax.transaction.xa.Xid; import java.util.ArrayList; import java.util.Collections; import java.util.List; import java.util.logging.Logger; /** * Created by mbetzel on 05.04.2017. */ public class LMDbXAResource implements XAResource { private static Logger log = Logger.getLogger(LMDbXAResource.class.getName()); private LMDbManagedConnection managedConnection; private List<Xid> xids = Collections.synchronizedList(new ArrayList()); private volatile boolean onePhase = false; public LMDbXAResource(LMDbManagedConnection managedConnection) { this.managedConnection = managedConnection; } @Override public void commit(Xid xid, boolean onePhase) throws XAException { log.finest("commit()"); if (onePhase) { // 1PC this.onePhase = true; } } @Override public void end(Xid xid, int i) throws XAException { log.finest("end()"); } @Override public void forget(Xid xid) throws XAException { log.finest("forget()"); } @Override public int getTransactionTimeout() throws XAException { log.finest("getTransactionTimeout()"); return 0; } @Override public boolean isSameRM(XAResource xaResource) throws XAException { log.finest("isSameRM()"); return false; } @Override public int prepare(Xid xid) throws XAException { log.finest("prepare()"); // get txn return 0; } @Override public Xid[] recover(int i) throws XAException { log.finest("recover()"); if (onePhase) { return new Xid[0]; } else { return xids.toArray(new Xid[xids.size()]); } } @Override public void rollback(Xid xid) throws XAException { log.finest("rollback()"); } @Override public boolean setTransactionTimeout(int i) throws XAException { log.finest("setTransactionTimeout()"); return false; } @Override public void start(Xid xid, int i) throws XAException { log.finest("start()"); if (i == TMNOFLAGS) { log.finest("TMNOFLAGS"); // create / get tx database with xid UID AXGTRIDSIZE+MAXBQUALSIZE as key (write as combined byte[]?) // value consists of the key/value action(s) to be preformed on the original database within this transaction // lmdb supports one key / many values, which fits nicely here. Mabe no need for extra XA DB? // local txn fetched from managedConnection and set on the connectionImpl to perform tx database mods // on commit copy tx database to original database with one local txn. } else if (i == TMJOIN) { log.finest("TMJOIN"); } else if (i == TMRESUME) { log.finest("TMRESUME"); } else { log.finest("UNKNOWN"); } //managedConnection.getConnection() xids.add(xid); } }
src/main/java/net/betzel/lmdb/jca/LMDbXAResource.java
/* Copyright 2017 Maurice Betzel Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ package net.betzel.lmdb.jca; import javax.transaction.xa.XAException; import javax.transaction.xa.XAResource; import javax.transaction.xa.Xid; import java.util.ArrayList; import java.util.Collections; import java.util.List; import java.util.logging.Logger; /** * Created by mbetzel on 05.04.2017. */ public class LMDbXAResource implements XAResource { private static Logger log = Logger.getLogger(LMDbXAResource.class.getName()); private LMDbManagedConnection managedConnection; private List<Xid> xids = Collections.synchronizedList(new ArrayList()); private volatile boolean onePhase = false; public LMDbXAResource(LMDbManagedConnection managedConnection) { this.managedConnection = managedConnection; } @Override public void commit(Xid xid, boolean onePhase) throws XAException { log.finest("commit()"); if (onePhase) { // 1PC this.onePhase = true; } } @Override public void end(Xid xid, int i) throws XAException { log.finest("end()"); } @Override public void forget(Xid xid) throws XAException { log.finest("forget()"); } @Override public int getTransactionTimeout() throws XAException { log.finest("getTransactionTimeout()"); return 0; } @Override public boolean isSameRM(XAResource xaResource) throws XAException { log.finest("isSameRM()"); return false; } @Override public int prepare(Xid xid) throws XAException { log.finest("prepare()"); // get txn return 0; } @Override public Xid[] recover(int i) throws XAException { log.finest("recover()"); if (onePhase) { return new Xid[0]; } else { return xids.toArray(new Xid[xids.size()]); } } @Override public void rollback(Xid xid) throws XAException { log.finest("rollback()"); } @Override public boolean setTransactionTimeout(int i) throws XAException { log.finest("setTransactionTimeout()"); return false; } @Override public void start(Xid xid, int i) throws XAException { log.finest("start()"); if (i == TMNOFLAGS) { log.finest("TMNOFLAGS"); // create / get tx database with xid UID AXGTRIDSIZE+MAXBQUALSIZE as key (write as combined byte[]?) // value consists of the key/value action(s) to be preformed on the original database within this transaction // local txn fetched from managedConnection and set on the connectionImpl to perform tx database mods // on commit copy tx database to original database with one local txn. } else if (i == TMJOIN) { log.finest("TMJOIN"); } else if (i == TMRESUME) { log.finest("TMRESUME"); } else { log.finest("UNKNOWN"); } //managedConnection.getConnection() xids.add(xid); } }
Extend tx db idea
src/main/java/net/betzel/lmdb/jca/LMDbXAResource.java
Extend tx db idea
<ide><path>rc/main/java/net/betzel/lmdb/jca/LMDbXAResource.java <ide> log.finest("TMNOFLAGS"); <ide> // create / get tx database with xid UID AXGTRIDSIZE+MAXBQUALSIZE as key (write as combined byte[]?) <ide> // value consists of the key/value action(s) to be preformed on the original database within this transaction <add> // lmdb supports one key / many values, which fits nicely here. Mabe no need for extra XA DB? <ide> // local txn fetched from managedConnection and set on the connectionImpl to perform tx database mods <ide> // on commit copy tx database to original database with one local txn. <ide> } else if (i == TMJOIN) {
Java
apache-2.0
f6bc66cb2f4e06ff509e796670834c76fc7369f9
0
sbespalov/strongbox,sbespalov/strongbox,sbespalov/strongbox,strongbox/strongbox,sbespalov/strongbox,strongbox/strongbox,strongbox/strongbox,strongbox/strongbox
package org.carlspring.strongbox.controllers.users; import org.carlspring.strongbox.controllers.BaseController; import org.carlspring.strongbox.users.domain.AccessModel; import org.carlspring.strongbox.users.domain.User; import org.carlspring.strongbox.users.service.UserService; import org.carlspring.strongbox.users.userdetails.SpringSecurityUser; import javax.inject.Inject; import java.util.Collections; import java.util.List; import java.util.stream.Collectors; import io.swagger.annotations.*; import org.apache.commons.lang3.StringUtils; import org.jose4j.lang.JoseException; import org.springframework.http.HttpHeaders; import org.springframework.http.HttpStatus; import org.springframework.http.MediaType; import org.springframework.http.ResponseEntity; import org.springframework.security.access.prepost.PreAuthorize; import org.springframework.security.core.Authentication; import org.springframework.security.core.context.SecurityContextHolder; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.*; /** * @author Pablo Tirado */ @Controller @RequestMapping("/users") @Api(value = "/users") public class UserController extends BaseController { @Inject private UserService userService; /** * This method exists for testing purposes. */ @ApiOperation(value = "Used to retrieve an request param", position = 1) @ApiResponses(value = { @ApiResponse(code = 200, message = "") }) @PreAuthorize("authenticated") @GetMapping(value = "/{anyString}", produces = { MediaType.TEXT_PLAIN_VALUE, MediaType.APPLICATION_JSON_VALUE }) // maps to /greet or any other string @ResponseBody public ResponseEntity greet(@PathVariable String anyString, @ApiParam(value = "The param name", required = true) @RequestParam(value = "name", required = false) String param, @RequestHeader(HttpHeaders.ACCEPT) String accept) { logger.debug("UserController -> Say hello to {}. Path variable: {}", param, anyString); return ResponseEntity.ok(getResponseEntityBody("hello, " + param, accept)); } @ApiOperation(value = "Used to create new user") @ApiResponses(value = { @ApiResponse(code = 200, message = "The user was created successfully."), @ApiResponse(code = 409, message = "A user with this username already exists! Please enter another username..") }) @PreAuthorize("hasAuthority('CREATE_USER')") @PostMapping(value = "/user", produces = { MediaType.TEXT_PLAIN_VALUE, MediaType.APPLICATION_JSON_VALUE }) @ResponseBody public ResponseEntity create(@RequestBody UserInput userInput, @RequestHeader(HttpHeaders.ACCEPT) String accept) { User user = userService.findByUserName(userInput.asUser().getUsername()); if (user != null) { String message = "A user with this username already exists! Please enter another username."; return ResponseEntity.status(HttpStatus.CONFLICT) .body(getResponseEntityBody(message, accept)); } userService.save(userInput.asUser()); return ResponseEntity.ok(getResponseEntityBody("The user was created successfully.", accept)); } @ApiOperation(value = "Used to retrieve an user") @ApiResponses(value = { @ApiResponse(code = 200, message = ""), @ApiResponse(code = 400, message = "An error occurred."), @ApiResponse(code = 404, message = "The specified user does not exist!.") }) @PreAuthorize("hasAuthority('VIEW_USER') || #name == principal.username") @GetMapping(value = "user/{name}", produces = { MediaType.TEXT_PLAIN_VALUE, MediaType.APPLICATION_JSON_VALUE }) @ResponseBody public ResponseEntity getUser(@ApiParam(value = "The name of the user", required = true) @PathVariable String name, @RequestHeader(HttpHeaders.ACCEPT) String accept) { User user = userService.findByUserName(name); if (user == null) { return ResponseEntity.status(HttpStatus.NOT_FOUND) .body(getResponseEntityBody("The specified user does not exist!", accept)); } return ResponseEntity.ok(getUserOutputEntityBody(UserOutput.fromUser(user), accept)); } @ApiOperation(value = "Used to retrieve an user") @ApiResponses(value = { @ApiResponse(code = 200, message = ""), @ApiResponse(code = 400, message = "An error occurred.") }) @PreAuthorize("hasAuthority('VIEW_USER')") @GetMapping(value = "/all", produces = { MediaType.APPLICATION_JSON_VALUE }) @ResponseBody public ResponseEntity getUsers() { List<UserOutput> users = userService.findAll() .orElse(Collections.emptyList()) .stream() .map(UserOutput::fromUser).collect(Collectors.toList()); return getJSONListResponseEntityBody("users", users); } @ApiOperation(value = "Used to update user") @ApiResponses(value = { @ApiResponse(code = 200, message = "The user was updated successfully."), @ApiResponse(code = 400, message = "Could not update user.") }) @PreAuthorize("hasAuthority('UPDATE_USER') || #userToUpdate.username == principal.username") @PutMapping(value = "user", produces = { MediaType.TEXT_PLAIN_VALUE, MediaType.APPLICATION_JSON_VALUE }) @ResponseBody public ResponseEntity update(@RequestBody UserInput userToUpdate, Authentication authentication, @RequestHeader(HttpHeaders.ACCEPT) String accept) { if (StringUtils.isBlank(userToUpdate.getUsername())) { String message = "Username not provided."; return ResponseEntity.status(HttpStatus.BAD_REQUEST) .body(getResponseEntityBody(message, accept)); } if (!(authentication.getPrincipal() instanceof SpringSecurityUser)) { String message = "Unsupported logged user principal type " + authentication.getPrincipal().getClass(); return ResponseEntity.status(HttpStatus.BAD_REQUEST) .body(getResponseEntityBody(message, accept)); } User user = userToUpdate.asUser(); final SpringSecurityUser loggedUser = (SpringSecurityUser) authentication.getPrincipal(); if (StringUtils.equals(loggedUser.getUsername(), user.getUsername())) { userService.updatePassword(user); } else { userService.updateByUsername(user); } return ResponseEntity.ok(getResponseEntityBody("The user was updated successfully.", accept)); } @ApiOperation(value = "Deletes a user from a repository.") @ApiResponses(value = { @ApiResponse(code = 200, message = "The user was deleted."), @ApiResponse(code = 400, message = "Could not delete a user."), @ApiResponse(code = 404, message = "The specified user does not exist!") }) @PreAuthorize("hasAuthority('DELETE_USER')") @DeleteMapping(value = "user/{name}", produces = { MediaType.TEXT_PLAIN_VALUE, MediaType.APPLICATION_JSON_VALUE }) @ResponseBody public ResponseEntity delete(@ApiParam(value = "The name of the user") @PathVariable String name, Authentication authentication, @RequestHeader(HttpHeaders.ACCEPT) String accept) { if (!(authentication.getPrincipal() instanceof SpringSecurityUser)) { String message = "Unsupported logged user principal type " + authentication.getPrincipal().getClass(); return ResponseEntity.status(HttpStatus.BAD_REQUEST) .body(getResponseEntityBody(message, accept)); } final SpringSecurityUser loggedUser = (SpringSecurityUser) authentication.getPrincipal(); if (StringUtils.equals(loggedUser.getUsername(), name)) { String message = "Unable to delete yourself"; return ResponseEntity.status(HttpStatus.BAD_REQUEST) .body(getResponseEntityBody(message, accept)); } User user = userService.findByUserName(name); if (user == null || user.getObjectId() == null) { String message = "The specified user does not exist!"; return ResponseEntity.status(HttpStatus.NOT_FOUND) .body(getResponseEntityBody(message, accept)); } userService.delete(user.getObjectId()); return ResponseEntity.ok(getResponseEntityBody("The user was deleted.", accept)); } @ApiOperation(value = "Generate new security token for specified user.", position = 3) @ApiResponses(value = { @ApiResponse(code = 200, message = "The security token was generated."), @ApiResponse(code = 400, message = "Could not generate new security token.") }) @PreAuthorize("hasAuthority('UPDATE_USER')") @GetMapping(value = "user/{username}/generate-security-token", produces = { MediaType.TEXT_PLAIN_VALUE, MediaType.APPLICATION_JSON_VALUE }) public ResponseEntity generateSecurityToken(@ApiParam(value = "The name of the user") @PathVariable String username, @RequestHeader(HttpHeaders.ACCEPT) String accept) throws JoseException { String securityToken = userService.generateSecurityToken(username); if (securityToken == null) { String message = String.format("Failed to generate SecurityToken, probably you should first set" + " SecurityTokenKey for the user: user-[%s]", username); return ResponseEntity.status(HttpStatus.BAD_REQUEST) .body(getResponseEntityBody(message, accept)); } return ResponseEntity.ok(getTokenEntityBody(securityToken, accept)); } @ApiOperation(value = "Generate authentication token.", position = 3) @ApiResponses(value = { @ApiResponse(code = 200, message = "The authentication token was generated."), @ApiResponse(code = 400, message = "Could not generate authentication token..") }) @PreAuthorize("authenticated") @GetMapping(value = "user/authenticate", produces = { MediaType.TEXT_PLAIN_VALUE, MediaType.APPLICATION_JSON_VALUE }) public ResponseEntity authenticate(@RequestParam(name = "expireSeconds", required = false) Integer expireSeconds, @RequestHeader(HttpHeaders.ACCEPT) String accept) throws JoseException { // We use Security Context from BasicAuth here String username = SecurityContextHolder.getContext().getAuthentication().getName(); String authToken = userService.generateAuthenticationToken(username, expireSeconds); return ResponseEntity.ok(getTokenEntityBody(authToken, accept)); } @ApiOperation(value = "Update custom access model for the user.", position = 3) @ApiResponses(value = { @ApiResponse(code = 200, message = "The custom access model was updated."), @ApiResponse(code = 403, message = "Not enough access rights for this operation."), @ApiResponse(code = 400, message = "An error occurred.") }) @PreAuthorize("hasAuthority('UPDATE_USER')") @PutMapping(value = "user/{userName}/access-model", produces = { MediaType.TEXT_PLAIN_VALUE, MediaType.APPLICATION_JSON_VALUE }) public ResponseEntity updateAccessModel(@ApiParam(value = "The name of the user") @PathVariable String userName, @RequestBody AccessModel accessModel, @RequestHeader(HttpHeaders.ACCEPT) String accept) { User user = userService.findByUserName(userName); if (user == null || user.getObjectId() == null) { String message = "The specified user does not exist!"; return ResponseEntity.status(HttpStatus.NOT_FOUND).body(getResponseEntityBody(message, accept)); } user.setAccessModel(accessModel); userService.save(user); return ResponseEntity.ok(getUserEntityBody(user, accept)); } private Object getUserOutputEntityBody(UserOutput userOutput, String accept) { if (MediaType.APPLICATION_JSON_VALUE.equals(accept)) { return userOutput; } else { return String.valueOf(userOutput); } } private Object getUserEntityBody(User user, String accept) { if (MediaType.APPLICATION_JSON_VALUE.equals(accept)) { return user; } else { return String.valueOf(user); } } private Object getTokenEntityBody(String token, String accept) { if (MediaType.APPLICATION_JSON_VALUE.equals(accept)) { return new TokenEntityBody(token); } else { return token; } } }
strongbox-web-core/src/main/java/org/carlspring/strongbox/controllers/users/UserController.java
package org.carlspring.strongbox.controllers.users; import org.carlspring.strongbox.controllers.BaseController; import org.carlspring.strongbox.users.domain.AccessModel; import org.carlspring.strongbox.users.domain.User; import org.carlspring.strongbox.users.service.UserService; import org.carlspring.strongbox.users.userdetails.SpringSecurityUser; import javax.inject.Inject; import java.util.Collections; import java.util.List; import java.util.stream.Collectors; import io.swagger.annotations.*; import org.apache.commons.lang3.StringUtils; import org.jose4j.lang.JoseException; import org.springframework.http.HttpHeaders; import org.springframework.http.HttpStatus; import org.springframework.http.MediaType; import org.springframework.http.ResponseEntity; import org.springframework.security.access.prepost.PreAuthorize; import org.springframework.security.core.Authentication; import org.springframework.security.core.context.SecurityContextHolder; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.*; /** * @author Pablo Tirado */ @Controller @RequestMapping("/users") @Api(value = "/users") public class UserController extends BaseController { @Inject private UserService userService; /** * This method exists for testing purposes. */ @ApiOperation(value = "Used to retrieve an request param", position = 1) @ApiResponses(value = { @ApiResponse(code = 200, message = "") }) @PreAuthorize("authenticated") @GetMapping(value = "/{anyString}", produces = { MediaType.TEXT_PLAIN_VALUE, MediaType.APPLICATION_JSON_VALUE }) // maps to /greet or any other string @ResponseBody public ResponseEntity greet(@PathVariable String anyString, @ApiParam(value = "The param name", required = true) @RequestParam(value = "name", required = false) String param, @RequestHeader(HttpHeaders.ACCEPT) String accept) { logger.debug("UserController -> Say hello to {}. Path variable: {}", param, anyString); return ResponseEntity.ok(getResponseEntityBody("hello, " + param, accept)); } @ApiOperation(value = "Used to create new user") @ApiResponses(value = { @ApiResponse(code = 200, message = "The user was created successfully."), @ApiResponse(code = 409, message = "A user with this username already exists! Please enter another username..") }) @PreAuthorize("hasAuthority('CREATE_USER')") @PostMapping(value = "/user", produces = { MediaType.TEXT_PLAIN_VALUE, MediaType.APPLICATION_JSON_VALUE }) @ResponseBody public ResponseEntity create(@RequestBody UserInput userInput, @RequestHeader(HttpHeaders.ACCEPT) String accept) { User user = userService.findByUserName(userInput.asUser().getUsername()); if (user != null) { String message = "A user with this username already exists! Please enter another username."; return ResponseEntity.status(HttpStatus.CONFLICT) .body(getResponseEntityBody(message, accept)); } userService.save(userInput.asUser()); return ResponseEntity.ok(getResponseEntityBody("The user was created successfully.", accept)); } @ApiOperation(value = "Used to retrieve an user") @ApiResponses(value = { @ApiResponse(code = 200, message = ""), @ApiResponse(code = 400, message = "An error occurred."), @ApiResponse(code = 404, message = "The specified user does not exist!.") }) @PreAuthorize("hasAuthority('VIEW_USER') || #name == principal.username") @GetMapping(value = "user/{name}", produces = { MediaType.TEXT_PLAIN_VALUE, MediaType.APPLICATION_JSON_VALUE }) @ResponseBody public ResponseEntity getUser(@ApiParam(value = "The name of the user", required = true) @PathVariable String name, @RequestHeader(HttpHeaders.ACCEPT) String accept) { User user = userService.findByUserName(name); if (user == null) { return ResponseEntity.status(HttpStatus.NOT_FOUND) .body(getResponseEntityBody("The specified user does not exist!", accept)); } return ResponseEntity.ok(getUserOutputEntityBody(UserOutput.fromUser(user), accept)); } @ApiOperation(value = "Used to retrieve an user") @ApiResponses(value = { @ApiResponse(code = 200, message = ""), @ApiResponse(code = 400, message = "An error occurred.") }) @PreAuthorize("hasAuthority('VIEW_USER')") @GetMapping(value = "/all", produces = { MediaType.APPLICATION_JSON_VALUE }) @ResponseBody public ResponseEntity getUsers() { List<UserOutput> users = userService.findAll() .orElse(Collections.emptyList()) .stream() .map(UserOutput::fromUser).collect(Collectors.toList()); return getJSONListResponseEntityBody("users", users); } @ApiOperation(value = "Used to update user") @ApiResponses(value = { @ApiResponse(code = 200, message = "The user was updated successfully."), @ApiResponse(code = 400, message = "Could not update user.") }) @PreAuthorize("hasAuthority('UPDATE_USER') || #userToUpdate.username == principal.username") @PutMapping(value = "user", produces = { MediaType.TEXT_PLAIN_VALUE, MediaType.APPLICATION_JSON_VALUE }) @ResponseBody public ResponseEntity update(@RequestBody UserInput userToUpdate, Authentication authentication, @RequestHeader(HttpHeaders.ACCEPT) String accept) { if (StringUtils.isBlank(userToUpdate.getUsername())) { String message = "Username not provided."; return ResponseEntity.status(HttpStatus.BAD_REQUEST) .body(getResponseEntityBody(message, accept)); } if (!(authentication.getPrincipal() instanceof SpringSecurityUser)) { String message = "Unsupported logged user principal type " + authentication.getPrincipal().getClass(); return ResponseEntity.status(HttpStatus.BAD_REQUEST) .body(getResponseEntityBody(message, accept)); } User user = userToUpdate.asUser(); final SpringSecurityUser loggedUser = (SpringSecurityUser) authentication.getPrincipal(); if (StringUtils.equals(loggedUser.getUsername(), user.getUsername())) { userService.updatePassword(user); } else { userService.updateByUsername(user); } return ResponseEntity.ok(getResponseEntityBody("The user was updated successfully.", accept)); } @ApiOperation(value = "Deletes a user from a repository.") @ApiResponses(value = { @ApiResponse(code = 200, message = "The user was deleted."), @ApiResponse(code = 400, message = "Could not delete a user."), @ApiResponse(code = 404, message = "The specified user does not exist!") }) @PreAuthorize("hasAuthority('DELETE_USER')") @DeleteMapping(value = "user/{name}", produces = { MediaType.TEXT_PLAIN_VALUE, MediaType.APPLICATION_JSON_VALUE }) @ResponseBody public ResponseEntity delete(@ApiParam(value = "The name of the user") @PathVariable String name, Authentication authentication, @RequestHeader(HttpHeaders.ACCEPT) String accept) { if (!(authentication.getPrincipal() instanceof SpringSecurityUser)) { String message = "Unsupported logged user principal type " + authentication.getPrincipal().getClass(); return ResponseEntity.status(HttpStatus.BAD_REQUEST) .body(getResponseEntityBody(message, accept)); } final SpringSecurityUser loggedUser = (SpringSecurityUser) authentication.getPrincipal(); if (StringUtils.equals(loggedUser.getUsername(), name)) { String message = "Unable to delete yourself"; return ResponseEntity.status(HttpStatus.BAD_REQUEST) .body(getResponseEntityBody(message, accept)); } User user = userService.findByUserName(name); if (user == null || user.getObjectId() == null) { String message = "The specified user does not exist!"; return ResponseEntity.status(HttpStatus.NOT_FOUND) .body(getResponseEntityBody(message, accept)); } userService.delete(user.getObjectId()); return ResponseEntity.ok(getResponseEntityBody("The user was deleted.", accept)); } @ApiOperation(value = "Generate new security token for specified user.", position = 3) @ApiResponses(value = { @ApiResponse(code = 200, message = "The security token was generated."), @ApiResponse(code = 400, message = "Could not generate new security token.") }) @PreAuthorize("hasAuthority('UPDATE_USER')") @GetMapping(value = "user/{username}/generate-security-token", produces = { MediaType.TEXT_PLAIN_VALUE, MediaType.APPLICATION_JSON_VALUE }) public ResponseEntity generateSecurityToken(@ApiParam(value = "The name of the user") @PathVariable String username, @RequestHeader(HttpHeaders.ACCEPT) String accept) throws JoseException { String securityToken = userService.generateSecurityToken(username); if (securityToken == null) { String message = String.format("Failed to generate SecurityToken, probably you should first set" + " SecurityTokenKey for the user: user-[%s]", username); return ResponseEntity.status(HttpStatus.BAD_REQUEST) .body(getResponseEntityBody(message, accept)); } return ResponseEntity.ok(getTokenEntityBody(securityToken, accept)); } @ApiOperation(value = "Generate authentication token.", position = 3) @ApiResponses(value = { @ApiResponse(code = 200, message = "The authentication token was generated."), @ApiResponse(code = 400, message = "Could not generate authentication token..") }) @PreAuthorize("authenticated") @GetMapping(value = "user/authenticate", produces = { MediaType.TEXT_PLAIN_VALUE, MediaType.APPLICATION_JSON_VALUE }) public ResponseEntity authenticate(@RequestParam(name = "expireSeconds", required = false) Integer expireSeconds, @RequestHeader(HttpHeaders.ACCEPT) String accept) throws JoseException { // We use Security Context from BasicAuth here String username = SecurityContextHolder.getContext().getAuthentication().getName(); String authToken = userService.generateAuthenticationToken(username, expireSeconds); return ResponseEntity.ok(getTokenEntityBody(authToken, accept)); } @ApiOperation(value = "Update custom access model for the user.", position = 3) @ApiResponses(value = { @ApiResponse(code = 200, message = "The custom access model was updated."), @ApiResponse(code = 403, message = "Not enough access rights for this operation."), @ApiResponse(code = 400, message = "An error occurred.") }) @PreAuthorize("hasAuthority('UPDATE_USER')") @PutMapping(value = "user/{username}/access-model", produces = { MediaType.TEXT_PLAIN_VALUE, MediaType.APPLICATION_JSON_VALUE }) public ResponseEntity updateAccessModel(@ApiParam(value = "The name of the user") @PathVariable String userName, @RequestBody AccessModel accessModel, @RequestHeader(HttpHeaders.ACCEPT) String accept) { User user = userService.findByUserName(userName); if (user == null || user.getObjectId() == null) { String message = "The specified user does not exist!"; return ResponseEntity.status(HttpStatus.NOT_FOUND).body(getResponseEntityBody(message, accept)); } user.setAccessModel(accessModel); userService.save(user); return ResponseEntity.ok(getUserEntityBody(user, accept)); } private Object getUserOutputEntityBody(UserOutput userOutput, String accept) { if (MediaType.APPLICATION_JSON_VALUE.equals(accept)) { return userOutput; } else { return String.valueOf(userOutput); } } private Object getUserEntityBody(User user, String accept) { if (MediaType.APPLICATION_JSON_VALUE.equals(accept)) { return user; } else { return String.valueOf(user); } } private Object getTokenEntityBody(String token, String accept) { if (MediaType.APPLICATION_JSON_VALUE.equals(accept)) { return new TokenEntityBody(token); } else { return token; } } }
UserController issue fixed
strongbox-web-core/src/main/java/org/carlspring/strongbox/controllers/users/UserController.java
UserController issue fixed
<ide><path>trongbox-web-core/src/main/java/org/carlspring/strongbox/controllers/users/UserController.java <ide> @ApiResponse(code = 403, message = "Not enough access rights for this operation."), <ide> @ApiResponse(code = 400, message = "An error occurred.") }) <ide> @PreAuthorize("hasAuthority('UPDATE_USER')") <del> @PutMapping(value = "user/{username}/access-model", produces = { MediaType.TEXT_PLAIN_VALUE, <add> @PutMapping(value = "user/{userName}/access-model", produces = { MediaType.TEXT_PLAIN_VALUE, <ide> MediaType.APPLICATION_JSON_VALUE }) <ide> public ResponseEntity updateAccessModel(@ApiParam(value = "The name of the user") @PathVariable String userName, <ide> @RequestBody AccessModel accessModel,
Java
mpl-2.0
53dec73716145b85135312cc0d09757b82a2c7a4
0
vertretungsplanme/substitution-schedule-parser,johan12345/substitution-schedule-parser,johan12345/substitution-schedule-parser,vertretungsplanme/substitution-schedule-parser
/* * substitution-schedule-parser - Java library for parsing schools' substitution schedules * Copyright (c) 2016 Johan v. Forstner * Copyright (c) 2016 Nico Alt * * This Source Code Form is subject to the terms of the Mozilla Public License, v. 2.0. * If a copy of the MPL was not distributed with this file, You can obtain one at https://mozilla.org/MPL/2.0/. */ package me.vertretungsplan.parser; import me.vertretungsplan.exception.CredentialInvalidException; import me.vertretungsplan.objects.Substitution; import me.vertretungsplan.objects.SubstitutionSchedule; import me.vertretungsplan.objects.SubstitutionScheduleData; import me.vertretungsplan.objects.SubstitutionScheduleDay; import me.vertretungsplan.objects.credential.Credential; import me.vertretungsplan.objects.credential.UserPasswordCredential; import org.apache.commons.codec.digest.DigestUtils; import org.apache.http.client.HttpResponseException; import org.joda.time.LocalDate; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; import java.io.IOException; import java.util.*; /** * Parser for LegionBoard, an open source changes management system for schools. * <p> * More information can be found on the <a href="http://legionboard.org">official website</a> and on its * <a href="https://gitlab.com/groups/legionboard">project page on GitLab</a>. * <p> * This parser can be accessed using <code>"legionboard"</code> for {@link SubstitutionScheduleData#setApi(String)}. * * <h4>Configuration parameters</h4> * These parameters can be supplied in {@link SubstitutionScheduleData#setData(JSONObject)} to configure the parser: * * <dl> * <dt><code>api</code> (String, required)</dt> * <dd>The URL where the LegionBoard Heart API can be found.</dd> * * <dt><code>website</code> (String, recommended)</dt> * <dd>The URL of a website where the substitution schedule can be seen online. Normally, this would be the URL of the * LegionBoard Eye instance.</dd> * </dl> * * You have to use a {@link me.vertretungsplan.objects.authentication.UserPasswordAuthenticationData} because all * schedules on LegionBoard are protected by a login. */ public class LegionBoardParser extends BaseParser { private static final String PARAM_API = "api"; private static final String PARAM_WEBSITE = "website"; /** * URL of given LegionBoard Heart instance */ private String api; /** * URL of given LegionBoard Eye instance */ private String website; public LegionBoardParser(SubstitutionScheduleData scheduleData, CookieProvider cookieProvider) { super(scheduleData, cookieProvider); JSONObject data = scheduleData.getData(); try { api = data.getString(PARAM_API); website = data.getString(PARAM_WEBSITE); } catch (JSONException e) { e.printStackTrace(); } } public SubstitutionSchedule getSubstitutionSchedule() throws IOException, JSONException, CredentialInvalidException { final SubstitutionSchedule substitutionSchedule = SubstitutionSchedule.fromData(scheduleData); substitutionSchedule.setClasses(getAllClasses()); substitutionSchedule.setTeachers(getAllTeachers()); substitutionSchedule.setWebsite(website); final JSONArray changes = getChanges(); final JSONArray courses = getCourses(); final JSONArray teachers = getTeachers(); parseLegionBoard(substitutionSchedule, changes, courses, teachers); return substitutionSchedule; } /** * Returns authentication key as shown * <a href="https://gitlab.com/legionboard/heart/blob/master/doc/README.md">in the documentation</a>. */ private String getAuthenticationKey(Credential credential) { final UserPasswordCredential userPasswordCredential = (UserPasswordCredential) credential; final String username = userPasswordCredential.getUsername(); final String password = userPasswordCredential.getPassword(); return DigestUtils.sha256Hex(username.toLowerCase() + "//" + password); } /** * Returns a JSONArray with all changes from now to in one week. * More information: <a href="https://gitlab.com/legionboard/heart/blob/master/doc/changes/list.md">List changes</a> */ private JSONArray getChanges() throws IOException, JSONException { // Date (or alias of date) when the changes start final String startBy = "now"; // Date (or alias of date) when the changes end final String endBy = "i1w"; final String url = api + "/changes?startBy=" + startBy + "&endBy=" + endBy + "&k=" + getAuthenticationKey(getCredential()); return getJSONArray(url); } /** * Returns a JSONArray with all courses. * More information: <a href="https://gitlab.com/legionboard/heart/blob/master/doc/courses/list.md">List courses</a> */ private JSONArray getCourses() throws IOException, JSONException { final String url = api + "/courses?k=" + getAuthenticationKey(getCredential()); return getJSONArray(url); } /** * Returns a JSONArray with all teachers. * More information: <a href="https://gitlab.com/legionboard/heart/blob/master/doc/teachers/list.md">List teachers</a> */ private JSONArray getTeachers() throws IOException, JSONException { final String url = api + "/teachers?k=" + getAuthenticationKey(getCredential()); return getJSONArray(url); } private JSONArray getJSONArray(String url) throws IOException, JSONException { try { return new JSONArray(httpGet(url, "UTF-8")); } catch (HttpResponseException httpResponseException) { if (httpResponseException.getStatusCode() == 404) { return null; } throw httpResponseException; } } void parseLegionBoard(SubstitutionSchedule substitutionSchedule, JSONArray changes, JSONArray courses, JSONArray teachers) throws IOException, JSONException { if (changes == null) { return; } // Link course IDs to their names HashMap<String, String> coursesHashMap = null; if (courses != null) { coursesHashMap = new HashMap<>(); for (int i = 0; i < courses.length(); i++) { JSONObject course = courses.getJSONObject(i); coursesHashMap.put(course.getString("id"), course.getString("name")); } } // Link teacher IDs to their names HashMap<String, String> teachersHashMap = null; if (teachers != null) { teachersHashMap = new HashMap<>(); for (int i = 0; i < teachers.length(); i++) { JSONObject teacher = teachers.getJSONObject(i); teachersHashMap.put(teacher.getString("id"), teacher.getString("name")); } } // Add changes to SubstitutionSchedule LocalDate currentDate = LocalDate.now(); SubstitutionScheduleDay substitutionScheduleDay = new SubstitutionScheduleDay(); substitutionScheduleDay.setDate(currentDate); for (int i = 0; i < changes.length(); i++) { final JSONObject change = changes.getJSONObject(i); final Substitution substitution = getSubstitution(change, coursesHashMap, teachersHashMap); final LocalDate startingDate = new LocalDate(change.getString("startingDate")); final LocalDate endingDate = new LocalDate(change.getString("endingDate")); // Handle multi-day changes if (!startingDate.isEqual(endingDate)) { if (!substitutionScheduleDay.getSubstitutions().isEmpty()) { substitutionSchedule.addDay(substitutionScheduleDay); } for (int k = 0; k < 7; k++) { final LocalDate date = LocalDate.now().plusDays(k); if ((date.isAfter(startingDate) || date.isEqual(startingDate)) && (date.isBefore(endingDate) || date.isEqual(endingDate))) { substitutionScheduleDay = new SubstitutionScheduleDay(); substitutionScheduleDay.setDate(date); substitutionScheduleDay.addSubstitution(substitution); substitutionSchedule.addDay(substitutionScheduleDay); currentDate = date; } } continue; } // If starting date of change does not equal date of SubstitutionScheduleDay if (!startingDate.isEqual(currentDate)) { if (!substitutionScheduleDay.getSubstitutions().isEmpty()) { substitutionSchedule.addDay(substitutionScheduleDay); } substitutionScheduleDay = new SubstitutionScheduleDay(); substitutionScheduleDay.setDate(startingDate); currentDate = startingDate; } substitutionScheduleDay.addSubstitution(substitution); } substitutionSchedule.addDay(substitutionScheduleDay); } private Substitution getSubstitution(JSONObject change, HashMap<String, String> coursesHashMap, HashMap<String, String> teachersHashMap) throws IOException, JSONException { final Substitution substitution = new Substitution(); // Set class final String classId = change.getString("course"); if (!classId.equals("0")) { if (coursesHashMap == null) { throw new IOException("Change references a course but courses are empty."); } final String singleClass = coursesHashMap.get(classId); final HashSet<String> classes = new HashSet<>(); classes.add(singleClass); substitution.setClasses(classes); } // Set type String type = "Unknown"; switch (change.getString("type")) { case "0": type = "Entfall"; break; case "1": type = "Vertretung"; break; case "2": type = "Information"; break; } substitution.setType(type); // Set color substitution.setColor(colorProvider.getColor(type)); // Set covering teacher final String coveringTeacherId = change.getString("coveringTeacher"); if (!coveringTeacherId.equals("0")) { if (teachersHashMap == null) { throw new IOException("Change references a covering teacher but teachers are empty."); } substitution.setTeacher(teachersHashMap.get(coveringTeacherId)); } // Set teacher final String teacherId = change.getString("teacher"); if (!teacherId.equals("0")) { if (teachersHashMap == null) { throw new IOException("Change references a teacher but teachers are empty."); } if (type.equals("Vertretung") || !coveringTeacherId.equals("0")) { substitution.setPreviousTeacher(teachersHashMap.get(teacherId)); } else { substitution.setTeacher(teachersHashMap.get(teacherId)); } } // Set description substitution.setDesc(change.getString("text")); // Set lesson final String startingHour = change.getString("startingHour"); final String endingHour = change.getString("endingHour"); if (!startingHour.equals("") || !endingHour.equals("")) { String lesson = ""; if (!startingHour.equals("") && endingHour.equals("")) { lesson = "Ab " + startingHour; } if (startingHour.equals("") && !endingHour.equals("")) { lesson = "Bis " + endingHour; } if (!startingHour.equals("") && !endingHour.equals("")) { lesson = startingHour + " - " + endingHour; } substitution.setLesson(lesson); } return substitution; } @Override public List<String> getAllClasses() throws IOException, JSONException { final List<String> classes = new ArrayList<>(); final JSONArray courses = getCourses(); if (courses == null) { return null; } for (int i = 0; i < courses.length(); i++) { final JSONObject course = courses.getJSONObject(i); if (!course.getBoolean("archived")) { classes.add(course.getString("name")); } } Collections.sort(classes); return classes; } @Override public List<String> getAllTeachers() throws IOException, JSONException { final List<String> teachers = new ArrayList<>(); final JSONArray jsonTeachers = getTeachers(); if (jsonTeachers == null) { return null; } for (int i = 0; i < jsonTeachers.length(); i++) { final JSONObject teacher = jsonTeachers.getJSONObject(i); if (!teacher.getBoolean("archived")) { teachers.add(teacher.getString("name")); } } Collections.sort(teachers); return teachers; } }
parser/src/main/java/me/vertretungsplan/parser/LegionBoardParser.java
/* * substitution-schedule-parser - Java library for parsing schools' substitution schedules * Copyright (c) 2016 Johan v. Forstner * Copyright (c) 2016 Nico Alt * * This Source Code Form is subject to the terms of the Mozilla Public License, v. 2.0. * If a copy of the MPL was not distributed with this file, You can obtain one at https://mozilla.org/MPL/2.0/. */ package me.vertretungsplan.parser; import me.vertretungsplan.exception.CredentialInvalidException; import me.vertretungsplan.objects.Substitution; import me.vertretungsplan.objects.SubstitutionSchedule; import me.vertretungsplan.objects.SubstitutionScheduleData; import me.vertretungsplan.objects.SubstitutionScheduleDay; import me.vertretungsplan.objects.credential.Credential; import me.vertretungsplan.objects.credential.UserPasswordCredential; import org.apache.commons.codec.digest.DigestUtils; import org.apache.http.client.HttpResponseException; import org.joda.time.LocalDate; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; import java.io.IOException; import java.util.*; /** * Parser for LegionBoard, an open source changes management system for schools. * <p> * More information can be found on the <a href="https://legionboard.github.io">official website</a> and on its * <a href="https://gitlab.com/groups/legionboard">project page on GitLab</a>. * <p> * This parser can be accessed using <code>"legionboard"</code> for {@link SubstitutionScheduleData#setApi(String)}. * * <h4>Configuration parameters</h4> * These parameters can be supplied in {@link SubstitutionScheduleData#setData(JSONObject)} to configure the parser: * * <dl> * <dt><code>api</code> (String, required)</dt> * <dd>The URL where the LegionBoard Heart API can be found.</dd> * * <dt><code>website</code> (String, recommended)</dt> * <dd>The URL of a website where the substitution schedule can be seen online. Normally, this would be the URL of the * LegionBoard Eye instance.</dd> * </dl> * * You have to use a {@link me.vertretungsplan.objects.authentication.UserPasswordAuthenticationData} because all * schedules on LegionBoard are protected by a login. */ public class LegionBoardParser extends BaseParser { private static final String PARAM_API = "api"; private static final String PARAM_WEBSITE = "website"; /** * URL of given LegionBoard Heart instance */ private String api; /** * URL of given LegionBoard Eye instance */ private String website; public LegionBoardParser(SubstitutionScheduleData scheduleData, CookieProvider cookieProvider) { super(scheduleData, cookieProvider); JSONObject data = scheduleData.getData(); try { api = data.getString(PARAM_API); website = data.getString(PARAM_WEBSITE); } catch (JSONException e) { e.printStackTrace(); } } public SubstitutionSchedule getSubstitutionSchedule() throws IOException, JSONException, CredentialInvalidException { final SubstitutionSchedule substitutionSchedule = SubstitutionSchedule.fromData(scheduleData); substitutionSchedule.setClasses(getAllClasses()); substitutionSchedule.setTeachers(getAllTeachers()); substitutionSchedule.setWebsite(website); final JSONArray changes = getChanges(); final JSONArray courses = getCourses(); final JSONArray teachers = getTeachers(); parseLegionBoard(substitutionSchedule, changes, courses, teachers); return substitutionSchedule; } /** * Returns authentication key as shown * <a href="https://gitlab.com/legionboard/heart/blob/master/doc/README.md">in the documentation</a>. */ private String getAuthenticationKey(Credential credential) { final UserPasswordCredential userPasswordCredential = (UserPasswordCredential) credential; final String username = userPasswordCredential.getUsername(); final String password = userPasswordCredential.getPassword(); return DigestUtils.sha256Hex(username.toLowerCase() + "//" + password); } /** * Returns a JSONArray with all changes from now to in one week. * More information: <a href="https://gitlab.com/legionboard/heart/blob/master/doc/changes/list.md">List changes</a> */ private JSONArray getChanges() throws IOException, JSONException { // Date (or alias of date) when the changes start final String startBy = "now"; // Date (or alias of date) when the changes end final String endBy = "i1w"; final String url = api + "/changes?startBy=" + startBy + "&endBy=" + endBy + "&k=" + getAuthenticationKey(getCredential()); return getJSONArray(url); } /** * Returns a JSONArray with all courses. * More information: <a href="https://gitlab.com/legionboard/heart/blob/master/doc/courses/list.md">List courses</a> */ private JSONArray getCourses() throws IOException, JSONException { final String url = api + "/courses?k=" + getAuthenticationKey(getCredential()); return getJSONArray(url); } /** * Returns a JSONArray with all teachers. * More information: <a href="https://gitlab.com/legionboard/heart/blob/master/doc/teachers/list.md">List teachers</a> */ private JSONArray getTeachers() throws IOException, JSONException { final String url = api + "/teachers?k=" + getAuthenticationKey(getCredential()); return getJSONArray(url); } private JSONArray getJSONArray(String url) throws IOException, JSONException { try { return new JSONArray(httpGet(url, "UTF-8")); } catch (HttpResponseException httpResponseException) { if (httpResponseException.getStatusCode() == 404) { return null; } throw httpResponseException; } } void parseLegionBoard(SubstitutionSchedule substitutionSchedule, JSONArray changes, JSONArray courses, JSONArray teachers) throws IOException, JSONException { if (changes == null) { return; } // Link course IDs to their names HashMap<String, String> coursesHashMap = null; if (courses != null) { coursesHashMap = new HashMap<>(); for (int i = 0; i < courses.length(); i++) { JSONObject course = courses.getJSONObject(i); coursesHashMap.put(course.getString("id"), course.getString("name")); } } // Link teacher IDs to their names HashMap<String, String> teachersHashMap = null; if (teachers != null) { teachersHashMap = new HashMap<>(); for (int i = 0; i < teachers.length(); i++) { JSONObject teacher = teachers.getJSONObject(i); teachersHashMap.put(teacher.getString("id"), teacher.getString("name")); } } // Add changes to SubstitutionSchedule LocalDate currentDate = LocalDate.now(); SubstitutionScheduleDay substitutionScheduleDay = new SubstitutionScheduleDay(); substitutionScheduleDay.setDate(currentDate); for (int i = 0; i < changes.length(); i++) { final JSONObject change = changes.getJSONObject(i); final Substitution substitution = getSubstitution(change, coursesHashMap, teachersHashMap); final LocalDate startingDate = new LocalDate(change.getString("startingDate")); final LocalDate endingDate = new LocalDate(change.getString("endingDate")); // Handle multi-day changes if (!startingDate.isEqual(endingDate)) { if (!substitutionScheduleDay.getSubstitutions().isEmpty()) { substitutionSchedule.addDay(substitutionScheduleDay); } for (int k = 0; k < 7; k++) { final LocalDate date = LocalDate.now().plusDays(k); if ((date.isAfter(startingDate) || date.isEqual(startingDate)) && (date.isBefore(endingDate) || date.isEqual(endingDate))) { substitutionScheduleDay = new SubstitutionScheduleDay(); substitutionScheduleDay.setDate(date); substitutionScheduleDay.addSubstitution(substitution); substitutionSchedule.addDay(substitutionScheduleDay); currentDate = date; } } continue; } // If starting date of change does not equal date of SubstitutionScheduleDay if (!startingDate.isEqual(currentDate)) { if (!substitutionScheduleDay.getSubstitutions().isEmpty()) { substitutionSchedule.addDay(substitutionScheduleDay); } substitutionScheduleDay = new SubstitutionScheduleDay(); substitutionScheduleDay.setDate(startingDate); currentDate = startingDate; } substitutionScheduleDay.addSubstitution(substitution); } substitutionSchedule.addDay(substitutionScheduleDay); } private Substitution getSubstitution(JSONObject change, HashMap<String, String> coursesHashMap, HashMap<String, String> teachersHashMap) throws IOException, JSONException { final Substitution substitution = new Substitution(); // Set class final String classId = change.getString("course"); if (!classId.equals("0")) { if (coursesHashMap == null) { throw new IOException("Change references a course but courses are empty."); } final String singleClass = coursesHashMap.get(classId); final HashSet<String> classes = new HashSet<>(); classes.add(singleClass); substitution.setClasses(classes); } // Set type String type = "Unknown"; switch (change.getString("type")) { case "0": type = "Entfall"; break; case "1": type = "Vertretung"; break; case "2": type = "Information"; break; } substitution.setType(type); // Set color substitution.setColor(colorProvider.getColor(type)); // Set covering teacher final String coveringTeacherId = change.getString("coveringTeacher"); if (!coveringTeacherId.equals("0")) { if (teachersHashMap == null) { throw new IOException("Change references a covering teacher but teachers are empty."); } substitution.setTeacher(teachersHashMap.get(coveringTeacherId)); } // Set teacher final String teacherId = change.getString("teacher"); if (!teacherId.equals("0")) { if (teachersHashMap == null) { throw new IOException("Change references a teacher but teachers are empty."); } if (type.equals("Vertretung") || !coveringTeacherId.equals("0")) { substitution.setPreviousTeacher(teachersHashMap.get(teacherId)); } else { substitution.setTeacher(teachersHashMap.get(teacherId)); } } // Set description substitution.setDesc(change.getString("text")); // Set lesson final String startingHour = change.getString("startingHour"); final String endingHour = change.getString("endingHour"); if (!startingHour.equals("") || !endingHour.equals("")) { String lesson = ""; if (!startingHour.equals("") && endingHour.equals("")) { lesson = "Ab " + startingHour; } if (startingHour.equals("") && !endingHour.equals("")) { lesson = "Bis " + endingHour; } if (!startingHour.equals("") && !endingHour.equals("")) { lesson = startingHour + " - " + endingHour; } substitution.setLesson(lesson); } return substitution; } @Override public List<String> getAllClasses() throws IOException, JSONException { final List<String> classes = new ArrayList<>(); final JSONArray courses = getCourses(); if (courses == null) { return null; } for (int i = 0; i < courses.length(); i++) { final JSONObject course = courses.getJSONObject(i); if (!course.getBoolean("archived")) { classes.add(course.getString("name")); } } Collections.sort(classes); return classes; } @Override public List<String> getAllTeachers() throws IOException, JSONException { final List<String> teachers = new ArrayList<>(); final JSONArray jsonTeachers = getTeachers(); if (jsonTeachers == null) { return null; } for (int i = 0; i < jsonTeachers.length(); i++) { final JSONObject teacher = jsonTeachers.getJSONObject(i); if (!teacher.getBoolean("archived")) { teachers.add(teacher.getString("name")); } } Collections.sort(teachers); return teachers; } }
Link to legionboard.org
parser/src/main/java/me/vertretungsplan/parser/LegionBoardParser.java
Link to legionboard.org
<ide><path>arser/src/main/java/me/vertretungsplan/parser/LegionBoardParser.java <ide> /** <ide> * Parser for LegionBoard, an open source changes management system for schools. <ide> * <p> <del> * More information can be found on the <a href="https://legionboard.github.io">official website</a> and on its <add> * More information can be found on the <a href="http://legionboard.org">official website</a> and on its <ide> * <a href="https://gitlab.com/groups/legionboard">project page on GitLab</a>. <ide> * <p> <ide> * This parser can be accessed using <code>"legionboard"</code> for {@link SubstitutionScheduleData#setApi(String)}.
Java
mit
b55fb99162a66b2c93957abf1a8138ced21281bc
0
ngageoint/geopackage-core-java
package mil.nga.geopackage.extension.elevation; import mil.nga.geopackage.BoundingBox; import mil.nga.geopackage.tiles.TileBoundingBoxUtils; /** * Elevation request to retrieve elevation values for a point or bounding box * * @author osbornb * @since 1.2.1 */ public class ElevationRequest { /** * Bounding box */ private BoundingBox boundingBox; /** * Point flag, true when a single point request */ private boolean point; /** * Bounding box projected to the elevation tiles projection */ private BoundingBox projectedBoundingBox; /** * Constructor * * @param boundingBox * bounding box */ public ElevationRequest(BoundingBox boundingBox) { this.boundingBox = boundingBox; } /** * Constructor * * @param latitude * latitude coordinate * @param longitude * longitude coordinate */ public ElevationRequest(double latitude, double longitude) { this(new BoundingBox(longitude, longitude, latitude, latitude)); point = true; } /** * Get the bounding box * * @return bounding box */ public BoundingBox getBoundingBox() { return boundingBox; } /** * Is the request for a single point * * @return true if a point request */ public boolean isPoint() { return point; } /** * Get the projected bounding box * * @return projected bounding box */ public BoundingBox getProjectedBoundingBox() { return projectedBoundingBox; } /** * Set the projected bounding box * * @param projectedBoundingBox * projected bounding box */ public void setProjectedBoundingBox(BoundingBox projectedBoundingBox) { this.projectedBoundingBox = projectedBoundingBox; } /** * Get the bounding box overlap between the projected bounding box and the * elevation bounding box * * @param projectedElevation * projected elevation * @return overlap bounding box */ public BoundingBox overlap(BoundingBox projectedElevation) { BoundingBox overlap = null; if (point) { overlap = projectedBoundingBox; } else { overlap = TileBoundingBoxUtils.overlap(projectedBoundingBox, projectedElevation); } return overlap; } }
src/main/java/mil/nga/geopackage/extension/elevation/ElevationRequest.java
package mil.nga.geopackage.extension.elevation; import mil.nga.geopackage.BoundingBox; import mil.nga.geopackage.tiles.TileBoundingBoxUtils; /** * Elevation request to retrieve elevation values for a point or bounding box * * @author osbornb * @since 1.2.1 */ public class ElevationRequest { /** * Bounding box */ private BoundingBox boundingBox; /** * Point flag, true when a single point request */ private boolean point; /** * Bounding box projected to the elevation tiles projection */ private BoundingBox projectedBoundingBox; /** * Constructor * * @param boundingBox * bounding box */ public ElevationRequest(BoundingBox boundingBox) { this.boundingBox = boundingBox; } /** * Constructor * * @param latitude * latitude coordinate * @param longitude * longitude coordinate */ public ElevationRequest(double latitude, double longitude) { this(new BoundingBox(longitude, longitude, latitude, latitude)); point = true; } /** * Get the bounding box * * @return bounding box */ public BoundingBox getBoundingBox() { return boundingBox; } /** * Is the request for a single point * * @return true if a point request */ public boolean isPoint() { return point; } /** * Get the projected bounding box * * @return projected bounding box */ public BoundingBox getProjectedBoundingBox() { return projectedBoundingBox; } /** * Set the projected bounding box * * @param projectedBoundingBox * projected bounding box */ public void setProjectedBoundingBox(BoundingBox projectedBoundingBox) { this.projectedBoundingBox = projectedBoundingBox; } /** * Get the bounding box overlap between the projected bounding box and the * elevation bounding box * * @param projectedElevation * projected elevation * @return overlap bounding box */ public BoundingBox overlap(BoundingBox projectedElevation) { BoundingBox overlap = null; if (point) { if (projectedBoundingBox.getMinLatitude() >= projectedElevation .getMinLatitude() && projectedBoundingBox.getMaxLatitude() <= projectedElevation .getMaxLatitude() && projectedBoundingBox.getMinLongitude() >= projectedElevation .getMinLongitude() && projectedBoundingBox.getMaxLongitude() <= projectedElevation .getMaxLongitude()) { overlap = projectedBoundingBox; } } else { overlap = TileBoundingBoxUtils.overlap(projectedBoundingBox, projectedElevation); } return overlap; } }
for point queries use the query as the overlap request on tile borders
src/main/java/mil/nga/geopackage/extension/elevation/ElevationRequest.java
for point queries use the query as the overlap request on tile borders
<ide><path>rc/main/java/mil/nga/geopackage/extension/elevation/ElevationRequest.java <ide> public BoundingBox overlap(BoundingBox projectedElevation) { <ide> BoundingBox overlap = null; <ide> if (point) { <del> if (projectedBoundingBox.getMinLatitude() >= projectedElevation <del> .getMinLatitude() <del> && projectedBoundingBox.getMaxLatitude() <= projectedElevation <del> .getMaxLatitude() <del> && projectedBoundingBox.getMinLongitude() >= projectedElevation <del> .getMinLongitude() <del> && projectedBoundingBox.getMaxLongitude() <= projectedElevation <del> .getMaxLongitude()) { <del> overlap = projectedBoundingBox; <del> } <add> overlap = projectedBoundingBox; <ide> } else { <ide> overlap = TileBoundingBoxUtils.overlap(projectedBoundingBox, <ide> projectedElevation);
Java
agpl-3.0
6e24870698cbc1bb6cb2c4d360a9ddaaee9499bd
0
horizon-institute/placebooks,horizon-institute/placebooks
package placebooks.controller; import java.io.BufferedInputStream; import java.io.ByteArrayOutputStream; import java.io.File; import java.io.FileInputStream; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.io.OutputStreamWriter; import java.io.PrintWriter; import java.io.Writer; import java.net.URL; import java.util.ArrayList; import java.util.Collection; import java.util.HashMap; import java.util.Iterator; import java.util.List; import java.util.Map; import javax.imageio.ImageIO; import javax.imageio.ImageReader; import javax.imageio.stream.ImageInputStream; import javax.persistence.EntityManager; import javax.persistence.NoResultException; import javax.persistence.TypedQuery; import javax.servlet.ServletOutputStream; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.apache.commons.fileupload.FileItem; import org.apache.commons.fileupload.disk.DiskFileItemFactory; import org.apache.commons.fileupload.servlet.ServletFileUpload; import org.apache.commons.fileupload.util.Streams; import org.apache.log4j.Logger; import org.codehaus.jackson.map.ObjectMapper; import org.codehaus.jackson.map.annotate.JsonSerialize; import org.springframework.security.authentication.encoding.Md5PasswordEncoder; import org.springframework.security.web.WebAttributes; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.servlet.ModelAndView; import org.w3c.dom.NamedNodeMap; import org.w3c.dom.Node; import org.w3c.dom.NodeList; import placebooks.model.AudioItem; import placebooks.model.EverytrailLoginResponse; import placebooks.model.EverytrailPicturesResponse; import placebooks.model.EverytrailTracksResponse; import placebooks.model.EverytrailTripsResponse; import placebooks.model.GPSTraceItem; import placebooks.model.ImageItem; import placebooks.model.LoginDetails; import placebooks.model.MediaItem; import placebooks.model.PlaceBook; import placebooks.model.PlaceBook.State; import placebooks.model.PlaceBookItem; import placebooks.model.User; import placebooks.model.VideoItem; import placebooks.model.json.PlaceBookDistanceEntry; import placebooks.model.json.PlaceBookItemDistanceEntry; import placebooks.model.json.PlaceBookSearchEntry; import placebooks.model.json.ServerInfo; import placebooks.model.json.Shelf; import placebooks.model.json.ShelfEntry; import placebooks.model.json.UserShelf; import com.vividsolutions.jts.geom.Geometry; import com.vividsolutions.jts.io.ParseException; import com.vividsolutions.jts.io.WKTReader; // TODO: general todo is to do file checking to reduce unnecessary file writes, // part of which is ensuring new file writes in cases of changes // // TODO: stop orphan / null field elements being added to database @Controller public class PlaceBooksAdminController { // Helper class for passing around general PlaceBookItem data public static class ItemData { private Geometry geometry; private User owner; private URL sourceURL; public ItemData() { } public Geometry getGeometry() { return geometry; } public User getOwner() { return owner; } public URL getSourceURL() { return sourceURL; } public boolean processItemData(final EntityManager pm, final String field, final String value) { if (field.equals("owner")) { setOwner(UserManager.getUser(pm, value)); } else if (field.equals("sourceurl")) { try { setSourceURL(new URL(value)); } catch (final java.net.MalformedURLException e) { log.error(e.toString(), e); } } else if (field.equals("geometry")) { try { setGeometry(new WKTReader().read(value)); } catch (final ParseException e) { log.error(e.toString(), e); } } else { return false; } return true; } private void setGeometry(final Geometry geometry) { this.geometry = geometry; } private void setOwner(final User owner) { this.owner = owner; } private void setSourceURL(final URL sourceURL) { this.sourceURL = sourceURL; } } private static final Logger log = Logger.getLogger(PlaceBooksAdminController.class.getName()); private static final int MEGABYTE = 1048576; @RequestMapping(value = "/admin/import_everytrail") public void getEverytrailData() { final EntityManager manager = EMFSingleton.getEntityManager(); final User user = UserManager.getCurrentUser(manager); final LoginDetails details = user.getLoginDetails(EverytrailHelper.SERVICE_NAME); if (details == null) { log.error("Everytrail import failed, login details null"); return; } final EverytrailLoginResponse loginResponse = EverytrailHelper.UserLogin( details.getUsername(), details.getPassword()); if (loginResponse.getStatus().equals("error")) { log.error("Everytrail login failed"); return; } try { manager.getTransaction().begin(); // Save user id details.setUserID(loginResponse.getValue()); manager.getTransaction().commit(); } finally { if (manager.getTransaction().isActive()) { manager.getTransaction().rollback(); log.error("Rolling Everytrail import back"); manager.close(); return; } else manager.close(); } final EverytrailTripsResponse trips = EverytrailHelper.Trips(loginResponse.getValue()); for (Node trip : trips.getTrips()) { // Get trip ID final NamedNodeMap tripAttr = trip.getAttributes(); final String tripId = tripAttr.getNamedItem("id").getNodeValue(); // Get other trip attributes... String tripName = ""; String tripGPX = ""; String tripKML = ""; // Then look at the properties in the child nodes to get url, title, description, etc. final NodeList tripProperties = trip.getChildNodes(); for (int propertyIndex = 0; propertyIndex < tripProperties.getLength(); propertyIndex++) { final Node item = tripProperties.item(propertyIndex); final String itemName = item.getNodeName(); // log.debug("Inspecting property: " + itemName + " which is " + // item.getTextContent()); if (itemName.equals("name")) { log.debug("Trip name is: " + item.getTextContent()); tripName = item.getTextContent(); } if (itemName.equals("gpx")) { log.debug("Trip GPX is: " + item.getTextContent()); tripGPX = item.getTextContent(); } if (itemName.equals("kml")) { log.debug("Trip KML is: " + item.getTextContent()); tripKML = item.getTextContent(); } } log.debug("Getting tracks for trip: " + tripId); EverytrailTracksResponse tracks = EverytrailHelper.Tracks( tripId, details.getUsername(), details.getPassword()); int i = 0; for (Node track : tracks.getTracks()) { log.info("Processing track " + i++ + " of " + tracks.getTracks().size()); GPSTraceItem gpsItem = new GPSTraceItem(user, null, null); ItemFactory.toGPSTraceItem(user, track, gpsItem, tripId, tripName); try { final InputStream is = CommunicationHelper.getConnection(new URL(tripGPX)).getInputStream(); log.info("InputStream for tripGPX is " + is.toString()); gpsItem.readTrace(is); } catch (final Exception e) { log.info(tripGPX + ": " + e.getMessage(), e); } gpsItem = (GPSTraceItem) gpsItem.saveUpdatedItem(); } final EverytrailPicturesResponse picturesResponse = EverytrailHelper.TripPictures( tripId, details.getUsername(), details.getPassword(), tripName); final HashMap<String, Node> pictures = picturesResponse.getPicturesMap(); i = 0; for (final Node picture : pictures.values()) { log.info("Processing picture " + i++); ImageItem imageItem = new ImageItem(user, null, null, null); ItemFactory.toImageItem(user, picture, imageItem, tripId, tripName); imageItem = (ImageItem) imageItem.saveUpdatedItem(); } } log.info("Finished Everytrail import"); } @RequestMapping(value = "/view/{key}", method = RequestMethod.GET) public void viewPlaceBook(final HttpServletResponse res, @PathVariable("key") final String key) { final EntityManager manager = EMFSingleton.getEntityManager(); try { final PlaceBook placebook = manager.find(PlaceBook.class, key); if (placebook != null) { try { if(placebook.getState() != State.PUBLISHED) { return; } final PrintWriter writer = res.getWriter(); writer.write("<!doctype html>\n"); writer.write("<html xmlns=\"http://www.w3.org/1999/xhtml\""); writer.write("xmlns:og=\"http://ogp.me/ns#\""); writer.write("xmlns:fb=\"http://www.facebook.com/2008/fbml\">"); writer.write("<head>"); writer.write("<meta http-equiv=\"content-type\" content=\"text/html; charset=UTF-8\">"); writer.write("<title>PlaceBooks</title>"); writer.write("<script type=\"text/javascript\" src=\"../../../placebooks.PlaceBookEditor/placebooks.PlaceBookEditor.nocache.js\"></script>"); writer.write("<link rel=\"icon\" type=\"image/png\" href=\"../../../images/Logo_016.png\" />"); writer.write("<meta property=\"og:site_name\" content=\"PlaceBooks\"/>"); writer.write("<meta property=\"og:title\" content=\"" + placebook.getMetadataValue("title") + "\"/>"); writer.write("<meta property=\"og:image\" content=\"" + placebook.getMetadataValue("title") + "\"/>"); writer.write("<meta property=\"og:description\" content=\"" + placebook.getMetadataValue("description") + "\"/>"); writer.write("<style>@media print { .printHidden { display: none; } }</style>"); writer.write("</head>"); writer.write("<body></body>"); writer.write("</html>"); writer.flush(); writer.close(); } catch (final IOException e) { log.error(e.toString()); } } } catch (final Throwable e) { log.error(e.getMessage(), e); } finally { manager.close(); } } @RequestMapping(value = "/account", method = RequestMethod.GET) public String accountPage() { return "account"; } @RequestMapping(value = "/addLoginDetails", method = RequestMethod.POST) public void addLoginDetails(@RequestParam final String username, @RequestParam final String password, @RequestParam final String service, final HttpServletResponse res) { if (service.equals(EverytrailHelper.SERVICE_NAME)) { EverytrailLoginResponse response = EverytrailHelper.UserLogin(username, password); log.info(response.getStatus() + ":" + response.getValue()); if (response.getStatus().equals("error")) { res.setStatus(HttpServletResponse.SC_BAD_REQUEST); return; } } final EntityManager manager = EMFSingleton.getEntityManager(); final User user = UserManager.getCurrentUser(manager); try { manager.getTransaction().begin(); final LoginDetails loginDetails = new LoginDetails(user, service, null, username, password); manager.persist(loginDetails); user.add(loginDetails); manager.getTransaction().commit(); } catch (final Exception e) { log.error("Error creating user", e); } finally { if (manager.getTransaction().isActive()) { manager.getTransaction().rollback(); log.error("Rolling login detail creation"); } manager.close(); } } @RequestMapping(value = "/createUserAccount", method = RequestMethod.POST) public String createUserAccount(@RequestParam final String name, @RequestParam final String email, @RequestParam final String password) { final Md5PasswordEncoder encoder = new Md5PasswordEncoder(); final User user = new User(name, email, encoder.encodePassword(password, null)); final EntityManager manager = EMFSingleton.getEntityManager(); try { manager.getTransaction().begin(); manager.persist(user); manager.getTransaction().commit(); } catch (final Exception e) { log.error("Error creating user", e); } finally { if (manager.getTransaction().isActive()) { manager.getTransaction().rollback(); log.error("Rolling back user creation"); } manager.close(); } return "redirect:/index.html"; } @RequestMapping(value = "/currentUser", method = RequestMethod.GET) public void currentUser(final HttpServletRequest req, final HttpServletResponse res) { res.setContentType("application/json"); final EntityManager entityManager = EMFSingleton.getEntityManager(); try { final User user = UserManager.getCurrentUser(entityManager); if (user == null) { } else { try { final ObjectMapper mapper = new ObjectMapper(); final ServletOutputStream sos = res.getOutputStream(); mapper.writeValue(sos, user); log.info("User: " + mapper.writeValueAsString(user)); sos.flush(); } catch (final IOException e) { log.error(e.getMessage(), e); } } } finally { if (entityManager.getTransaction().isActive()) { entityManager.getTransaction().rollback(); } entityManager.close(); } } @RequestMapping(value = "/palette", method = RequestMethod.GET) public void getPaletteItemsJSON(final HttpServletResponse res) { final EntityManager manager = EMFSingleton.getEntityManager(); final User user = UserManager.getCurrentUser(manager); if (user == null) { try { log.info("User not logged in"); res.setStatus(HttpServletResponse.SC_UNAUTHORIZED); res.setContentType("application/json"); res.getWriter().write("User not logged in"); return; } catch (final Exception e) { log.error(e.getMessage(), e); } } final TypedQuery<PlaceBookItem> q = manager .createQuery( "SELECT p FROM PlaceBookItem p WHERE p.owner = :owner AND p.placebook IS NULL", PlaceBookItem.class); q.setParameter("owner", user); final Collection<PlaceBookItem> pbs = q.getResultList(); log.info("Converting " + pbs.size() + " PlaceBooks to JSON"); log.info("User " + user.getName()); try { final Writer sos = res.getWriter(); final ObjectMapper mapper = new ObjectMapper(); mapper.getSerializationConfig().setSerializationInclusion(JsonSerialize.Inclusion.NON_DEFAULT); sos.write("["); boolean comma = false; for (final PlaceBookItem item : pbs) { if (comma) { sos.write(","); } else { comma = true; } sos.write(mapper.writeValueAsString(item)); } sos.write("]"); // mapper.enableDefaultTyping(DefaultTyping.JAVA_LANG_OBJECT); res.setContentType("application/json"); //log.debug("Palette Items: " + mapper.writeValueAsString(pbs)); sos.flush(); sos.close(); } catch (final Exception e) { log.error(e.getMessage(), e); } manager.close(); } @RequestMapping(value = "/placebookitem/{key}", method = RequestMethod.GET) public void getPlaceBookItemJSON(final HttpServletResponse res, @PathVariable("key") final String key) { final EntityManager manager = EMFSingleton.getEntityManager(); try { final PlaceBookItem item = manager.find(PlaceBookItem.class, key); if (item != null) { try { final ObjectMapper mapper = new ObjectMapper(); mapper.getSerializationConfig().setSerializationInclusion(JsonSerialize.Inclusion.NON_DEFAULT); final ServletOutputStream sos = res.getOutputStream(); res.setContentType("application/json"); mapper.writeValue(sos, item); log.info("PlacebookItem: " + mapper.writeValueAsString(item)); sos.flush(); } catch (final IOException e) { log.error(e.toString()); } } } catch (final Throwable e) { log.error(e.getMessage(), e); } finally { manager.close(); } } @RequestMapping(value = "/placebook/{key}", method = RequestMethod.GET) public void getPlaceBookJSON(final HttpServletResponse res, @PathVariable("key") final String key) { final EntityManager manager = EMFSingleton.getEntityManager(); try { final PlaceBook placebook = manager.find(PlaceBook.class, key); if (placebook != null) { try { final ObjectMapper mapper = new ObjectMapper(); mapper.getSerializationConfig().setSerializationInclusion(JsonSerialize.Inclusion.NON_DEFAULT); final ServletOutputStream sos = res.getOutputStream(); res.setContentType("application/json"); mapper.writeValue(sos, placebook); log.info("Placebook: " + mapper.writeValueAsString(placebook)); sos.flush(); } catch (final IOException e) { log.error(e.toString()); } } } catch (final Throwable e) { log.error(e.getMessage(), e); } finally { manager.close(); } } @RequestMapping(value = "/shelf", method = RequestMethod.GET) public void getPlaceBooksJSON(final HttpServletRequest req, final HttpServletResponse res) { final EntityManager manager = EMFSingleton.getEntityManager(); try { final User user = UserManager.getCurrentUser(manager); if (user != null) { final TypedQuery<PlaceBook> q = manager.createQuery("SELECT p FROM PlaceBook p WHERE p.owner= :owner", PlaceBook.class); q.setParameter("owner", user); final Collection<PlaceBook> pbs = q.getResultList(); log.info("Converting " + pbs.size() + " PlaceBooks to JSON"); log.info("User " + user.getName()); try { final UserShelf shelf = new UserShelf(pbs, user); final ObjectMapper mapper = new ObjectMapper(); log.info("Shelf: " + mapper.writeValueAsString(shelf)); final ServletOutputStream sos = res.getOutputStream(); res.setContentType("application/json"); mapper.writeValue(sos, shelf); sos.flush(); } catch (final Exception e) { log.error(e.toString()); } } else { try { res.setStatus(HttpServletResponse.SC_UNAUTHORIZED); final ObjectMapper mapper = new ObjectMapper(); final ServletOutputStream sos = res.getOutputStream(); mapper.writeValue(sos, req.getSession().getAttribute(WebAttributes.AUTHENTICATION_EXCEPTION)); sos.flush(); } catch (final IOException e) { log.error(e.getMessage(), e); } } } finally { manager.close(); } } @RequestMapping(value = "/admin/shelf/{owner}", method = RequestMethod.GET) public ModelAndView getPlaceBooksJSON(final HttpServletRequest req, final HttpServletResponse res, @PathVariable("owner") final String owner) { if (owner.trim().isEmpty()) { return null; } final EntityManager pm = EMFSingleton.getEntityManager(); final TypedQuery<User> uq = pm.createQuery("SELECT u FROM User u WHERE u.email LIKE :email", User.class); uq.setParameter("email", owner.trim()); try { final User user = uq.getSingleResult(); final TypedQuery<PlaceBook> q = pm.createQuery( "SELECT p FROM PlaceBook p WHERE p.owner = :user", PlaceBook.class); q.setParameter("user", user); final Collection<PlaceBook> pbs = q.getResultList(); log.info("Converting " + pbs.size() + " PlaceBooks to JSON"); if (!pbs.isEmpty()) { final UserShelf s = new UserShelf(pbs, user); try { final ObjectMapper mapper = new ObjectMapper(); final ServletOutputStream sos = res.getOutputStream(); res.setContentType("application/json"); mapper.writeValue(sos, s); sos.flush(); } catch (final IOException e) { log.error(e.toString()); } } } catch (final NoResultException e) { log.error(e.toString()); } finally { pm.close(); } return null; } @RequestMapping(value = "/admin/package/{key}", method = RequestMethod.GET) public ModelAndView makePackage(final HttpServletRequest req, final HttpServletResponse res, @PathVariable("key") final String key) { final EntityManager pm = EMFSingleton.getEntityManager(); final PlaceBook p = pm.find(PlaceBook.class, key); final File zipFile = PlaceBooksAdminHelper.makePackage(pm, p); if (zipFile == null) { return new ModelAndView("message", "text", "Making and compressing package"); } try { // Serve up file from disk final ByteArrayOutputStream bos = new ByteArrayOutputStream(); final FileInputStream fis = new FileInputStream(zipFile); final BufferedInputStream bis = new BufferedInputStream(fis); final byte data[] = new byte[2048]; int i; while ((i = bis.read(data, 0, 2048)) != -1) { bos.write(data, 0, i); } fis.close(); final ServletOutputStream sos = res.getOutputStream(); res.setContentType("application/zip"); res.setHeader("Content-Disposition", "attachment; filename=\"" + p.getKey() + ".zip\""); res.addHeader("Content-Length", Integer.toString(bos.size())); sos.write(bos.toByteArray()); sos.flush(); } catch (final IOException e) { log.error(e.toString(), e); return new ModelAndView("message", "text", "Error sending package"); } finally { pm.close(); } return null; } @RequestMapping(value = "/publishplacebook", method = RequestMethod.POST) public void publishPlaceBookJSON(final HttpServletResponse res, @RequestParam("placebook") final String json) { log.info("Publish Placebook: " + json); final EntityManager manager = EMFSingleton.getEntityManager(); final User currentUser = UserManager.getCurrentUser(manager); if (currentUser == null) { res.setStatus(HttpServletResponse.SC_UNAUTHORIZED); try { res.getWriter().write("User not logged in"); } catch (final IOException e) { e.printStackTrace(); } return; } try { final ObjectMapper mapper = new ObjectMapper(); mapper.getSerializationConfig().setSerializationInclusion(JsonSerialize.Inclusion.NON_DEFAULT); final PlaceBook placebook = mapper.readValue(json, PlaceBook.class); final PlaceBook result = PlaceBooksAdminHelper.savePlaceBook(manager, placebook); log.info("Published Placebook:" + mapper.writeValueAsString(result)); final PlaceBook published = PlaceBooksAdminHelper.publishPlaceBook(manager, result); res.setContentType("application/json"); final ServletOutputStream sos = res.getOutputStream(); log.debug("Published Placebook:" + mapper.writeValueAsString(published)); mapper.writeValue(sos, published); sos.flush(); } catch (final Throwable e) { log.warn(e.getMessage(), e); } finally { if (manager.getTransaction().isActive()) { manager.getTransaction().rollback(); } manager.close(); } } @RequestMapping(value = "/saveplacebook", method = RequestMethod.POST) public void savePlaceBookJSON(final HttpServletResponse res, @RequestParam("placebook") final String json) { log.info("Save Placebook: " + json); final EntityManager manager = EMFSingleton.getEntityManager(); final User currentUser = UserManager.getCurrentUser(manager); if (currentUser == null) { res.setStatus(HttpServletResponse.SC_UNAUTHORIZED); try { res.getWriter().write("User not logged in"); } catch (final IOException e) { e.printStackTrace(); } return; } try { final ObjectMapper mapper = new ObjectMapper(); mapper.getSerializationConfig().setSerializationInclusion(JsonSerialize.Inclusion.NON_DEFAULT); final PlaceBook placebook = mapper.readValue(json, PlaceBook.class); final PlaceBook result = PlaceBooksAdminHelper.savePlaceBook(manager, placebook); res.setContentType("application/json"); final ServletOutputStream sos = res.getOutputStream(); log.debug("Saved Placebook:" + mapper.writeValueAsString(result)); mapper.writeValue(sos, result); sos.flush(); } catch (final Throwable e) { log.info(json); log.warn(e.getMessage(), e); } finally { if (manager.getTransaction().isActive()) { manager.getTransaction().rollback(); } manager.close(); } } @RequestMapping(value = "/admin/location_search/placebook/{geometry}", method = RequestMethod.GET) public ModelAndView searchLocationPlaceBooksGET(final HttpServletRequest req, final HttpServletResponse res, @PathVariable("geometry") final String geometry) { Geometry geometry_ = null; try { geometry_ = new WKTReader().read(geometry); } catch (final ParseException e) { log.error(e.toString(), e); return null; } final EntityManager em = EMFSingleton.getEntityManager(); final StringBuffer out = new StringBuffer(); final Collection<ShelfEntry> pbs = new ArrayList<ShelfEntry>(); for (final Map.Entry<PlaceBook, Double> entry : PlaceBooksAdminHelper .searchLocationForPlaceBooks(em, geometry_)) { final PlaceBook p = entry.getKey(); if (p != null) { log.info("Search result: pb key=" + entry.getKey().getKey() + ", distance=" + entry.getValue()); pbs.add(new PlaceBookDistanceEntry(p, entry.getValue())); } } em.close(); final Shelf s = new Shelf(); s.setEntries(pbs); try { final ObjectMapper mapper = new ObjectMapper(); final ServletOutputStream sos = res.getOutputStream(); res.setContentType("application/json"); mapper.writeValue(sos, s); sos.flush(); } catch (final IOException e) { log.error(e.toString()); } return null; } @RequestMapping(value = "/admin/location_search/placebookitem/{geometry}", method = RequestMethod.GET) public ModelAndView searchLocationPlaceBookItemsGET(final HttpServletRequest req, final HttpServletResponse res, @PathVariable("geometry") final String geometry) { Geometry geometry_ = null; try { geometry_ = new WKTReader().read(geometry); } catch (final ParseException e) { log.error(e.toString(), e); return null; } final EntityManager em = EMFSingleton.getEntityManager(); final StringBuffer out = new StringBuffer(); final Collection<ShelfEntry> ps = new ArrayList<ShelfEntry>(); for (final Map.Entry<PlaceBookItem, Double> entry : PlaceBooksAdminHelper .searchLocationForPlaceBookItems(em, geometry_)) { final PlaceBookItem p = entry.getKey(); if (p != null) { log.info("Search result: pbi key=" + entry.getKey().getKey() + ", distance=" + entry.getValue()); ps.add(new PlaceBookItemDistanceEntry(p, entry.getValue())); } } em.close(); final Shelf s = new Shelf(); s.setEntries(ps); try { final ObjectMapper mapper = new ObjectMapper(); final ServletOutputStream sos = res.getOutputStream(); res.setContentType("application/json"); mapper.writeValue(sos, s); sos.flush(); } catch (final IOException e) { log.error(e.toString()); } return null; } @RequestMapping(value = "/admin/search/{terms}", method = RequestMethod.GET) public ModelAndView searchGET(final HttpServletRequest req, final HttpServletResponse res, @PathVariable("terms") final String terms) { final long timeStart = System.nanoTime(); final long timeEnd; final EntityManager em = EMFSingleton.getEntityManager(); final StringBuffer out = new StringBuffer(); final Collection<ShelfEntry> pbs = new ArrayList<ShelfEntry>(); for (final Map.Entry<PlaceBook, Integer> entry : PlaceBooksAdminHelper.search(em, terms)) { final PlaceBook p = entry.getKey(); if (p != null && p.getState() == PlaceBook.State.PUBLISHED) { log.info("Search result: pb key=" + entry.getKey().getKey() + ", score=" + entry.getValue()); pbs.add(new PlaceBookSearchEntry(p, entry.getValue())); } } em.close(); final Shelf s = new Shelf(); s.setEntries(pbs); try { final ObjectMapper mapper = new ObjectMapper(); final ServletOutputStream sos = res.getOutputStream(); res.setContentType("application/json"); mapper.writeValue(sos, s); sos.flush(); } catch (final IOException e) { log.error(e.toString()); } timeEnd = System.nanoTime(); log.info("Search execution time = " + (timeEnd - timeStart) + " ns"); return null; } @RequestMapping(value = "/admin/search", method = RequestMethod.POST) public ModelAndView searchPOST(final HttpServletRequest req, final HttpServletResponse res) { final StringBuffer out = new StringBuffer(); final String[] terms = req.getParameter("terms").split("\\s"); for (int i = 0; i < terms.length; ++i) { out.append(terms[i]); if (i < terms.length - 1) { out.append("+"); } } return searchGET(req, res, out.toString()); } @RequestMapping(value = "/admin/serve/gpstraceitem/{key}", method = RequestMethod.GET) public ModelAndView serveGPSTraceItem(final HttpServletRequest req, final HttpServletResponse res, @PathVariable("key") final String key) { final EntityManager em = EMFSingleton.getEntityManager(); log.info("Serving GPS Trace for " + key); try { final GPSTraceItem g = em.find(GPSTraceItem.class, key); if (g != null) { final String trace = g.getTrace(); res.setContentType("text/xml"); final PrintWriter p = res.getWriter(); p.print(trace); p.close(); } else { throw new Exception("GPSTrace is null"); } } catch (final Throwable e) { log.error(e.getMessage(), e); } finally { em.close(); } return null; } @RequestMapping(value = "/admin/serve/imageitem/{key}", method = RequestMethod.GET) public ModelAndView serveImageItem(final HttpServletRequest req, final HttpServletResponse res, @PathVariable("key") final String key) { final EntityManager em = EMFSingleton.getEntityManager(); log.info("Serving Image Item " + key); try { final ImageItem i = em.find(ImageItem.class, key); if (i != null) { em.getTransaction().begin(); i.attemptPathFix(); em.getTransaction().commit(); if (i.getPath() != null) { log.info(i.getPath()); try { final File image = new File(i.getPath()); final ImageInputStream iis = ImageIO.createImageInputStream(image); final Iterator<ImageReader> readers = ImageIO.getImageReaders(iis); String fmt = "png"; while (readers.hasNext()) { final ImageReader read = readers.next(); fmt = read.getFormatName(); } final OutputStream out = res.getOutputStream(); ImageIO.write(ImageIO.read(image), fmt, out); out.close(); } catch (final IOException e) { log.error(e.toString()); } } } } catch (final Throwable e) { log.error(e.getMessage(), e); } finally { em.close(); } return null; } @RequestMapping(value = "/admin/serve/{type}item/{key}", method = RequestMethod.GET) public void streamMediaItem(final HttpServletRequest req, final HttpServletResponse res, @PathVariable("type") final String type, @PathVariable("key") final String key) { String path = null; final EntityManager em = EMFSingleton.getEntityManager(); try { final MediaItem m = em.find(MediaItem.class, key); if (m != null) { em.getTransaction().begin(); m.attemptPathFix(); em.getTransaction().commit(); } else { throw new Exception("Error getting media file, invalid key"); } path = m.getPath(); } catch (final Throwable e) { log.error(e.getMessage(), e); } finally { em.close(); } if (path == null) { return; } try { String type_ = null; if (type.trim().equalsIgnoreCase("video")) { type_ = "video"; } else if (type.trim().equalsIgnoreCase("audio")) { type_ = "audio"; } else { throw new Exception("Unrecognised media item type"); } final File file = new File(path); final String[] split = PlaceBooksAdminHelper.getExtension(path); if (split == null) { throw new Exception("Error getting file suffix"); } final ServletOutputStream sos = res.getOutputStream(); final long contentLength = file.length(); res.setContentType(type_ + "/" + split[1]); res.addHeader("Accept-Ranges", "bytes"); res.addHeader("Content-Length", Long.toString(contentLength)); final FileInputStream fis = new FileInputStream(file); final BufferedInputStream bis = new BufferedInputStream(fis); final String range = req.getHeader("Range"); long startByte = 0; long endByte = contentLength - 1; if (range != null) { if (range.startsWith("bytes=")) { try { final String[] rangeItems = range.substring(6).split("-"); startByte = Long.parseLong(rangeItems[0]); endByte = Long.parseLong(rangeItems[1]); } catch (final Exception e) { } } } res.addHeader("Content-Range", "bytes " + startByte + "-" + endByte + "/" + contentLength); final int bufferLen = 2048; final byte data[] = new byte[bufferLen]; int length; bis.skip(startByte); try { while ((length = bis.read(data, 0, bufferLen)) != -1) { sos.write(data, 0, length); } sos.flush(); } finally { sos.close(); fis.close(); } } catch (final Throwable e) { // Enumeration headers = req.getHeaderNames(); // while(headers.hasMoreElements()) // { // String header = (String)headers.nextElement(); // log.info(header + ": " + req.getHeader(header)); // } log.error("Error serving " + type + " " + key); } } @RequestMapping(value = "/admin/add_item/upload", method = RequestMethod.POST) public ModelAndView uploadFile(final HttpServletRequest req) { final EntityManager manager = EMFSingleton.getEntityManager(); final ItemData itemData = new ItemData(); try { FileItem fileData = null; String name = null; String type = null; String itemKey = null; String placebookKey = null; manager.getTransaction().begin(); @SuppressWarnings("unchecked") final List<FileItem> items = new ServletFileUpload(new DiskFileItemFactory()).parseRequest(req); for (final FileItem item : items) { if (item.isFormField()) { final String value = Streams.asString(item.getInputStream()); if (!itemData.processItemData(manager, item.getFieldName(), value)) { if (item.getFieldName().equals("key")) { placebookKey = value; } else if (item.getFieldName().equals("itemKey")) { itemKey = value; } } } else { name = item.getName(); fileData = item; final String[] split = PlaceBooksAdminHelper.getExtension(item.getFieldName()); if (split == null) { continue; } type = split[0]; String dLimit = null, iden = null; if (type.equals("image")) { iden = PropertiesSingleton.IDEN_IMAGE_MAX_SIZE; dLimit = "1"; } else if (type.equals("video")) { iden = PropertiesSingleton.IDEN_VIDEO_MAX_SIZE; dLimit = "20"; } else if (type.equals("audio")) { iden = PropertiesSingleton.IDEN_AUDIO_MAX_SIZE; dLimit = "10"; } if (dLimit != null && iden != null) { final int maxSize = Integer.parseInt(PropertiesSingleton.get( PlaceBooksAdminHelper.class .getClassLoader()) .getProperty(iden, dLimit)); if ((item.getSize() / MEGABYTE) > maxSize) { throw new Exception("File too big, limit = " + Integer.toString(maxSize) + "Mb"); } } } } if (itemData.getOwner() == null) { itemData.setOwner(UserManager.getCurrentUser(manager)); } PlaceBookItem item = null; if (itemKey != null) { item = manager.find(PlaceBookItem.class, itemKey); } else if (placebookKey != null) { final PlaceBook placebook = manager.find(PlaceBook.class, placebookKey); if (type.equals("gpstrace")) { item = new GPSTraceItem(itemData.getOwner(), itemData.getSourceURL(), null); item.setPlaceBook(placebook); } else if (type.equals("image")) { item = new ImageItem(itemData.getOwner(), itemData.getGeometry(), itemData.getSourceURL(), null); item.setPlaceBook(placebook); } else if (type.equals("video")) { item = new VideoItem(itemData.getOwner(), itemData.getGeometry(), itemData.getSourceURL(), null); item.setPlaceBook(placebook); } else if (type.equals("audio")) { item = new AudioItem(itemData.getOwner(), itemData.getGeometry(), itemData.getSourceURL(), null); item.setPlaceBook(placebook); } } if (item instanceof MediaItem) { ((MediaItem) item).setSourceURL(null); ((MediaItem) item).writeDataToDisk(name, fileData.getInputStream()); } else if (item instanceof GPSTraceItem) { ((GPSTraceItem) item).setSourceURL(null); ((GPSTraceItem) item).readTrace(fileData.getInputStream()); } manager.getTransaction().commit(); return new ModelAndView("message", "text", "Success"); } catch (final Exception e) { log.error(e.toString(), e); } finally { if (manager.getTransaction().isActive()) { manager.getTransaction().rollback(); } manager.close(); } return new ModelAndView("message", "text", "Failed"); } @RequestMapping(value = "/admin/serverinfo", method = RequestMethod.GET) public ModelAndView getServerInfoJSON(final HttpServletRequest req, final HttpServletResponse res) { final ServerInfo si = new ServerInfo(); try { final ObjectMapper mapper = new ObjectMapper(); final ServletOutputStream sos = res.getOutputStream(); res.setContentType("application/json"); mapper.writeValue(sos, si); sos.flush(); } catch (final IOException e) { log.error(e.toString()); } return null; } }
placebooks-webapp/src/placebooks/controller/PlaceBooksAdminController.java
package placebooks.controller; import java.io.BufferedInputStream; import java.io.ByteArrayOutputStream; import java.io.File; import java.io.FileInputStream; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.io.OutputStreamWriter; import java.io.PrintWriter; import java.io.Writer; import java.net.URL; import java.util.ArrayList; import java.util.Collection; import java.util.HashMap; import java.util.Iterator; import java.util.List; import java.util.Map; import javax.imageio.ImageIO; import javax.imageio.ImageReader; import javax.imageio.stream.ImageInputStream; import javax.persistence.EntityManager; import javax.persistence.NoResultException; import javax.persistence.TypedQuery; import javax.servlet.ServletOutputStream; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.apache.commons.fileupload.FileItem; import org.apache.commons.fileupload.disk.DiskFileItemFactory; import org.apache.commons.fileupload.servlet.ServletFileUpload; import org.apache.commons.fileupload.util.Streams; import org.apache.log4j.Logger; import org.codehaus.jackson.map.ObjectMapper; import org.codehaus.jackson.map.annotate.JsonSerialize; import org.springframework.security.authentication.encoding.Md5PasswordEncoder; import org.springframework.security.web.WebAttributes; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.servlet.ModelAndView; import org.w3c.dom.NamedNodeMap; import org.w3c.dom.Node; import org.w3c.dom.NodeList; import placebooks.model.AudioItem; import placebooks.model.EverytrailLoginResponse; import placebooks.model.EverytrailPicturesResponse; import placebooks.model.EverytrailTracksResponse; import placebooks.model.EverytrailTripsResponse; import placebooks.model.GPSTraceItem; import placebooks.model.ImageItem; import placebooks.model.LoginDetails; import placebooks.model.MediaItem; import placebooks.model.PlaceBook; import placebooks.model.PlaceBook.State; import placebooks.model.PlaceBookItem; import placebooks.model.User; import placebooks.model.VideoItem; import placebooks.model.json.PlaceBookDistanceEntry; import placebooks.model.json.PlaceBookItemDistanceEntry; import placebooks.model.json.PlaceBookSearchEntry; import placebooks.model.json.ServerInfo; import placebooks.model.json.Shelf; import placebooks.model.json.ShelfEntry; import placebooks.model.json.UserShelf; import com.vividsolutions.jts.geom.Geometry; import com.vividsolutions.jts.io.ParseException; import com.vividsolutions.jts.io.WKTReader; // TODO: general todo is to do file checking to reduce unnecessary file writes, // part of which is ensuring new file writes in cases of changes // // TODO: stop orphan / null field elements being added to database @Controller public class PlaceBooksAdminController { // Helper class for passing around general PlaceBookItem data public static class ItemData { private Geometry geometry; private User owner; private URL sourceURL; public ItemData() { } public Geometry getGeometry() { return geometry; } public User getOwner() { return owner; } public URL getSourceURL() { return sourceURL; } public boolean processItemData(final EntityManager pm, final String field, final String value) { if (field.equals("owner")) { setOwner(UserManager.getUser(pm, value)); } else if (field.equals("sourceurl")) { try { setSourceURL(new URL(value)); } catch (final java.net.MalformedURLException e) { log.error(e.toString(), e); } } else if (field.equals("geometry")) { try { setGeometry(new WKTReader().read(value)); } catch (final ParseException e) { log.error(e.toString(), e); } } else { return false; } return true; } private void setGeometry(final Geometry geometry) { this.geometry = geometry; } private void setOwner(final User owner) { this.owner = owner; } private void setSourceURL(final URL sourceURL) { this.sourceURL = sourceURL; } } private static final Logger log = Logger.getLogger(PlaceBooksAdminController.class.getName()); private static final int MEGABYTE = 1048576; @RequestMapping(value = "/admin/import_everytrail") public void getEverytrailData() { final EntityManager manager = EMFSingleton.getEntityManager(); final User user = UserManager.getCurrentUser(manager); final LoginDetails details = user.getLoginDetails(EverytrailHelper.SERVICE_NAME); if (details == null) { log.error("Everytrail import failed, login details null"); return; } final EverytrailLoginResponse loginResponse = EverytrailHelper.UserLogin( details.getUsername(), details.getPassword()); if (loginResponse.getStatus().equals("error")) { log.error("Everytrail login failed"); return; } try { manager.getTransaction().begin(); // Save user id details.setUserID(loginResponse.getValue()); manager.getTransaction().commit(); } finally { if (manager.getTransaction().isActive()) { manager.getTransaction().rollback(); log.error("Rolling Everytrail import back"); manager.close(); return; } else manager.close(); } final EverytrailTripsResponse trips = EverytrailHelper.Trips(loginResponse.getValue()); for (Node trip : trips.getTrips()) { // Get trip ID final NamedNodeMap tripAttr = trip.getAttributes(); final String tripId = tripAttr.getNamedItem("id").getNodeValue(); // Get other trip attributes... String tripName = ""; String tripGPX = ""; String tripKML = ""; // Then look at the properties in the child nodes to get url, title, description, etc. final NodeList tripProperties = trip.getChildNodes(); for (int propertyIndex = 0; propertyIndex < tripProperties.getLength(); propertyIndex++) { final Node item = tripProperties.item(propertyIndex); final String itemName = item.getNodeName(); // log.debug("Inspecting property: " + itemName + " which is " + // item.getTextContent()); if (itemName.equals("name")) { log.debug("Trip name is: " + item.getTextContent()); tripName = item.getTextContent(); } if (itemName.equals("gpx")) { log.debug("Trip GPX is: " + item.getTextContent()); tripGPX = item.getTextContent(); } if (itemName.equals("kml")) { log.debug("Trip KML is: " + item.getTextContent()); tripKML = item.getTextContent(); } } log.debug("Getting tracks for trip: " + tripId); EverytrailTracksResponse tracks = EverytrailHelper.Tracks( tripId, details.getUsername(), details.getPassword()); int i = 0; for (Node track : tracks.getTracks()) { log.info("Processing track " + i++ + " of " + tracks.getTracks().size()); GPSTraceItem gpsItem = new GPSTraceItem(user, null, null); ItemFactory.toGPSTraceItem(user, track, gpsItem, tripId, tripName); try { final InputStream is = CommunicationHelper.getConnection(new URL(tripGPX)).getInputStream(); log.info("InputStream for tripGPX is " + is.toString()); gpsItem.readTrace(is); } catch (final Exception e) { log.info(tripGPX + ": " + e.getMessage(), e); } gpsItem = (GPSTraceItem) gpsItem.saveUpdatedItem(); } final EverytrailPicturesResponse picturesResponse = EverytrailHelper.TripPictures( tripId, details.getUsername(), details.getPassword(), tripName); final HashMap<String, Node> pictures = picturesResponse.getPicturesMap(); i = 0; for (final Node picture : pictures.values()) { log.info("Processing picture " + i++); ImageItem imageItem = new ImageItem(user, null, null, null); ItemFactory.toImageItem(user, picture, imageItem, tripId, tripName); imageItem = (ImageItem) imageItem.saveUpdatedItem(); } } log.info("Finished Everytrail import"); } @RequestMapping(value = "/view/{key}", method = RequestMethod.GET) public void viewPlaceBook(final HttpServletResponse res, @PathVariable("key") final String key) { final EntityManager manager = EMFSingleton.getEntityManager(); try { final PlaceBook placebook = manager.find(PlaceBook.class, key); if (placebook != null) { try { if(placebook.getState() != State.PUBLISHED) { return; } final PrintWriter writer = res.getWriter(); writer.write("<!doctype html>\n"); writer.write("<html xmlns=\"http://www.w3.org/1999/xhtml\""); writer.write("xmlns:og=\"http://ogp.me/ns#\""); writer.write("xmlns:fb=\"http://www.facebook.com/2008/fbml\">"); writer.write("<head>"); writer.write("<meta http-equiv=\"content-type\" content=\"text/html; charset=UTF-8\">"); writer.write("<title>PlaceBooks</title>"); writer.write("<script type=\"text/javascript\" src=\"../../../placebooks.PlaceBookEditor/placebooks.PlaceBookEditor.nocache.js\"></script>"); writer.write("<link rel=\"icon\" type=\"image/png\" href=\"../../../images/Logo_016.png\" />"); writer.write("<meta property=\"og:site_name\" content=\"PlaceBooks\"/>"); writer.write("<meta property=\"og:title\" content=\"" + placebook.getMetadataValue("title") + "\"/>"); writer.write("<meta property=\"og:image\" content=\"" + placebook.getMetadataValue("title") + "\"/>"); writer.write("<meta property=\"og:description\" content=\"" + placebook.getMetadataValue("description") + "\"/>"); writer.write("</head>"); writer.write("<body></body>"); writer.write("</html>"); writer.flush(); writer.close(); } catch (final IOException e) { log.error(e.toString()); } } } catch (final Throwable e) { log.error(e.getMessage(), e); } finally { manager.close(); } } @RequestMapping(value = "/account", method = RequestMethod.GET) public String accountPage() { return "account"; } @RequestMapping(value = "/addLoginDetails", method = RequestMethod.POST) public void addLoginDetails(@RequestParam final String username, @RequestParam final String password, @RequestParam final String service, final HttpServletResponse res) { if (service.equals(EverytrailHelper.SERVICE_NAME)) { EverytrailLoginResponse response = EverytrailHelper.UserLogin(username, password); log.info(response.getStatus() + ":" + response.getValue()); if (response.getStatus().equals("error")) { res.setStatus(HttpServletResponse.SC_BAD_REQUEST); return; } } final EntityManager manager = EMFSingleton.getEntityManager(); final User user = UserManager.getCurrentUser(manager); try { manager.getTransaction().begin(); final LoginDetails loginDetails = new LoginDetails(user, service, null, username, password); manager.persist(loginDetails); user.add(loginDetails); manager.getTransaction().commit(); } catch (final Exception e) { log.error("Error creating user", e); } finally { if (manager.getTransaction().isActive()) { manager.getTransaction().rollback(); log.error("Rolling login detail creation"); } manager.close(); } } @RequestMapping(value = "/createUserAccount", method = RequestMethod.POST) public String createUserAccount(@RequestParam final String name, @RequestParam final String email, @RequestParam final String password) { final Md5PasswordEncoder encoder = new Md5PasswordEncoder(); final User user = new User(name, email, encoder.encodePassword(password, null)); final EntityManager manager = EMFSingleton.getEntityManager(); try { manager.getTransaction().begin(); manager.persist(user); manager.getTransaction().commit(); } catch (final Exception e) { log.error("Error creating user", e); } finally { if (manager.getTransaction().isActive()) { manager.getTransaction().rollback(); log.error("Rolling back user creation"); } manager.close(); } return "redirect:/index.html"; } @RequestMapping(value = "/currentUser", method = RequestMethod.GET) public void currentUser(final HttpServletRequest req, final HttpServletResponse res) { res.setContentType("application/json"); final EntityManager entityManager = EMFSingleton.getEntityManager(); try { final User user = UserManager.getCurrentUser(entityManager); if (user == null) { } else { try { final ObjectMapper mapper = new ObjectMapper(); final ServletOutputStream sos = res.getOutputStream(); mapper.writeValue(sos, user); log.info("User: " + mapper.writeValueAsString(user)); sos.flush(); } catch (final IOException e) { log.error(e.getMessage(), e); } } } finally { if (entityManager.getTransaction().isActive()) { entityManager.getTransaction().rollback(); } entityManager.close(); } } @RequestMapping(value = "/palette", method = RequestMethod.GET) public void getPaletteItemsJSON(final HttpServletResponse res) { final EntityManager manager = EMFSingleton.getEntityManager(); final User user = UserManager.getCurrentUser(manager); if (user == null) { try { log.info("User not logged in"); res.setStatus(HttpServletResponse.SC_UNAUTHORIZED); res.setContentType("application/json"); res.getWriter().write("User not logged in"); return; } catch (final Exception e) { log.error(e.getMessage(), e); } } final TypedQuery<PlaceBookItem> q = manager .createQuery( "SELECT p FROM PlaceBookItem p WHERE p.owner = :owner AND p.placebook IS NULL", PlaceBookItem.class); q.setParameter("owner", user); final Collection<PlaceBookItem> pbs = q.getResultList(); log.info("Converting " + pbs.size() + " PlaceBooks to JSON"); log.info("User " + user.getName()); try { final Writer sos = res.getWriter(); final ObjectMapper mapper = new ObjectMapper(); mapper.getSerializationConfig().setSerializationInclusion(JsonSerialize.Inclusion.NON_DEFAULT); sos.write("["); boolean comma = false; for (final PlaceBookItem item : pbs) { if (comma) { sos.write(","); } else { comma = true; } sos.write(mapper.writeValueAsString(item)); } sos.write("]"); // mapper.enableDefaultTyping(DefaultTyping.JAVA_LANG_OBJECT); res.setContentType("application/json"); //log.debug("Palette Items: " + mapper.writeValueAsString(pbs)); sos.flush(); sos.close(); } catch (final Exception e) { log.error(e.getMessage(), e); } manager.close(); } @RequestMapping(value = "/placebookitem/{key}", method = RequestMethod.GET) public void getPlaceBookItemJSON(final HttpServletResponse res, @PathVariable("key") final String key) { final EntityManager manager = EMFSingleton.getEntityManager(); try { final PlaceBookItem item = manager.find(PlaceBookItem.class, key); if (item != null) { try { final ObjectMapper mapper = new ObjectMapper(); mapper.getSerializationConfig().setSerializationInclusion(JsonSerialize.Inclusion.NON_DEFAULT); final ServletOutputStream sos = res.getOutputStream(); res.setContentType("application/json"); mapper.writeValue(sos, item); log.info("PlacebookItem: " + mapper.writeValueAsString(item)); sos.flush(); } catch (final IOException e) { log.error(e.toString()); } } } catch (final Throwable e) { log.error(e.getMessage(), e); } finally { manager.close(); } } @RequestMapping(value = "/placebook/{key}", method = RequestMethod.GET) public void getPlaceBookJSON(final HttpServletResponse res, @PathVariable("key") final String key) { final EntityManager manager = EMFSingleton.getEntityManager(); try { final PlaceBook placebook = manager.find(PlaceBook.class, key); if (placebook != null) { try { final ObjectMapper mapper = new ObjectMapper(); mapper.getSerializationConfig().setSerializationInclusion(JsonSerialize.Inclusion.NON_DEFAULT); final ServletOutputStream sos = res.getOutputStream(); res.setContentType("application/json"); mapper.writeValue(sos, placebook); log.info("Placebook: " + mapper.writeValueAsString(placebook)); sos.flush(); } catch (final IOException e) { log.error(e.toString()); } } } catch (final Throwable e) { log.error(e.getMessage(), e); } finally { manager.close(); } } @RequestMapping(value = "/shelf", method = RequestMethod.GET) public void getPlaceBooksJSON(final HttpServletRequest req, final HttpServletResponse res) { final EntityManager manager = EMFSingleton.getEntityManager(); try { final User user = UserManager.getCurrentUser(manager); if (user != null) { final TypedQuery<PlaceBook> q = manager.createQuery("SELECT p FROM PlaceBook p WHERE p.owner= :owner", PlaceBook.class); q.setParameter("owner", user); final Collection<PlaceBook> pbs = q.getResultList(); log.info("Converting " + pbs.size() + " PlaceBooks to JSON"); log.info("User " + user.getName()); try { final UserShelf shelf = new UserShelf(pbs, user); final ObjectMapper mapper = new ObjectMapper(); log.info("Shelf: " + mapper.writeValueAsString(shelf)); final ServletOutputStream sos = res.getOutputStream(); res.setContentType("application/json"); mapper.writeValue(sos, shelf); sos.flush(); } catch (final Exception e) { log.error(e.toString()); } } else { try { res.setStatus(HttpServletResponse.SC_UNAUTHORIZED); final ObjectMapper mapper = new ObjectMapper(); final ServletOutputStream sos = res.getOutputStream(); mapper.writeValue(sos, req.getSession().getAttribute(WebAttributes.AUTHENTICATION_EXCEPTION)); sos.flush(); } catch (final IOException e) { log.error(e.getMessage(), e); } } } finally { manager.close(); } } @RequestMapping(value = "/admin/shelf/{owner}", method = RequestMethod.GET) public ModelAndView getPlaceBooksJSON(final HttpServletRequest req, final HttpServletResponse res, @PathVariable("owner") final String owner) { if (owner.trim().isEmpty()) { return null; } final EntityManager pm = EMFSingleton.getEntityManager(); final TypedQuery<User> uq = pm.createQuery("SELECT u FROM User u WHERE u.email LIKE :email", User.class); uq.setParameter("email", owner.trim()); try { final User user = uq.getSingleResult(); final TypedQuery<PlaceBook> q = pm.createQuery( "SELECT p FROM PlaceBook p WHERE p.owner = :user", PlaceBook.class); q.setParameter("user", user); final Collection<PlaceBook> pbs = q.getResultList(); log.info("Converting " + pbs.size() + " PlaceBooks to JSON"); if (!pbs.isEmpty()) { final UserShelf s = new UserShelf(pbs, user); try { final ObjectMapper mapper = new ObjectMapper(); final ServletOutputStream sos = res.getOutputStream(); res.setContentType("application/json"); mapper.writeValue(sos, s); sos.flush(); } catch (final IOException e) { log.error(e.toString()); } } } catch (final NoResultException e) { log.error(e.toString()); } finally { pm.close(); } return null; } @RequestMapping(value = "/admin/package/{key}", method = RequestMethod.GET) public ModelAndView makePackage(final HttpServletRequest req, final HttpServletResponse res, @PathVariable("key") final String key) { final EntityManager pm = EMFSingleton.getEntityManager(); final PlaceBook p = pm.find(PlaceBook.class, key); final File zipFile = PlaceBooksAdminHelper.makePackage(pm, p); if (zipFile == null) { return new ModelAndView("message", "text", "Making and compressing package"); } try { // Serve up file from disk final ByteArrayOutputStream bos = new ByteArrayOutputStream(); final FileInputStream fis = new FileInputStream(zipFile); final BufferedInputStream bis = new BufferedInputStream(fis); final byte data[] = new byte[2048]; int i; while ((i = bis.read(data, 0, 2048)) != -1) { bos.write(data, 0, i); } fis.close(); final ServletOutputStream sos = res.getOutputStream(); res.setContentType("application/zip"); res.setHeader("Content-Disposition", "attachment; filename=\"" + p.getKey() + ".zip\""); res.addHeader("Content-Length", Integer.toString(bos.size())); sos.write(bos.toByteArray()); sos.flush(); } catch (final IOException e) { log.error(e.toString(), e); return new ModelAndView("message", "text", "Error sending package"); } finally { pm.close(); } return null; } @RequestMapping(value = "/publishplacebook", method = RequestMethod.POST) public void publishPlaceBookJSON(final HttpServletResponse res, @RequestParam("placebook") final String json) { log.info("Publish Placebook: " + json); final EntityManager manager = EMFSingleton.getEntityManager(); final User currentUser = UserManager.getCurrentUser(manager); if (currentUser == null) { res.setStatus(HttpServletResponse.SC_UNAUTHORIZED); try { res.getWriter().write("User not logged in"); } catch (final IOException e) { e.printStackTrace(); } return; } try { final ObjectMapper mapper = new ObjectMapper(); mapper.getSerializationConfig().setSerializationInclusion(JsonSerialize.Inclusion.NON_DEFAULT); final PlaceBook placebook = mapper.readValue(json, PlaceBook.class); final PlaceBook result = PlaceBooksAdminHelper.savePlaceBook(manager, placebook); log.info("Published Placebook:" + mapper.writeValueAsString(result)); final PlaceBook published = PlaceBooksAdminHelper.publishPlaceBook(manager, result); res.setContentType("application/json"); final ServletOutputStream sos = res.getOutputStream(); log.debug("Published Placebook:" + mapper.writeValueAsString(published)); mapper.writeValue(sos, published); sos.flush(); } catch (final Throwable e) { log.warn(e.getMessage(), e); } finally { if (manager.getTransaction().isActive()) { manager.getTransaction().rollback(); } manager.close(); } } @RequestMapping(value = "/saveplacebook", method = RequestMethod.POST) public void savePlaceBookJSON(final HttpServletResponse res, @RequestParam("placebook") final String json) { log.info("Save Placebook: " + json); final EntityManager manager = EMFSingleton.getEntityManager(); final User currentUser = UserManager.getCurrentUser(manager); if (currentUser == null) { res.setStatus(HttpServletResponse.SC_UNAUTHORIZED); try { res.getWriter().write("User not logged in"); } catch (final IOException e) { e.printStackTrace(); } return; } try { final ObjectMapper mapper = new ObjectMapper(); mapper.getSerializationConfig().setSerializationInclusion(JsonSerialize.Inclusion.NON_DEFAULT); final PlaceBook placebook = mapper.readValue(json, PlaceBook.class); final PlaceBook result = PlaceBooksAdminHelper.savePlaceBook(manager, placebook); res.setContentType("application/json"); final ServletOutputStream sos = res.getOutputStream(); log.debug("Saved Placebook:" + mapper.writeValueAsString(result)); mapper.writeValue(sos, result); sos.flush(); } catch (final Throwable e) { log.info(json); log.warn(e.getMessage(), e); } finally { if (manager.getTransaction().isActive()) { manager.getTransaction().rollback(); } manager.close(); } } @RequestMapping(value = "/admin/location_search/placebook/{geometry}", method = RequestMethod.GET) public ModelAndView searchLocationPlaceBooksGET(final HttpServletRequest req, final HttpServletResponse res, @PathVariable("geometry") final String geometry) { Geometry geometry_ = null; try { geometry_ = new WKTReader().read(geometry); } catch (final ParseException e) { log.error(e.toString(), e); return null; } final EntityManager em = EMFSingleton.getEntityManager(); final StringBuffer out = new StringBuffer(); final Collection<ShelfEntry> pbs = new ArrayList<ShelfEntry>(); for (final Map.Entry<PlaceBook, Double> entry : PlaceBooksAdminHelper .searchLocationForPlaceBooks(em, geometry_)) { final PlaceBook p = entry.getKey(); if (p != null) { log.info("Search result: pb key=" + entry.getKey().getKey() + ", distance=" + entry.getValue()); pbs.add(new PlaceBookDistanceEntry(p, entry.getValue())); } } em.close(); final Shelf s = new Shelf(); s.setEntries(pbs); try { final ObjectMapper mapper = new ObjectMapper(); final ServletOutputStream sos = res.getOutputStream(); res.setContentType("application/json"); mapper.writeValue(sos, s); sos.flush(); } catch (final IOException e) { log.error(e.toString()); } return null; } @RequestMapping(value = "/admin/location_search/placebookitem/{geometry}", method = RequestMethod.GET) public ModelAndView searchLocationPlaceBookItemsGET(final HttpServletRequest req, final HttpServletResponse res, @PathVariable("geometry") final String geometry) { Geometry geometry_ = null; try { geometry_ = new WKTReader().read(geometry); } catch (final ParseException e) { log.error(e.toString(), e); return null; } final EntityManager em = EMFSingleton.getEntityManager(); final StringBuffer out = new StringBuffer(); final Collection<ShelfEntry> ps = new ArrayList<ShelfEntry>(); for (final Map.Entry<PlaceBookItem, Double> entry : PlaceBooksAdminHelper .searchLocationForPlaceBookItems(em, geometry_)) { final PlaceBookItem p = entry.getKey(); if (p != null) { log.info("Search result: pbi key=" + entry.getKey().getKey() + ", distance=" + entry.getValue()); ps.add(new PlaceBookItemDistanceEntry(p, entry.getValue())); } } em.close(); final Shelf s = new Shelf(); s.setEntries(ps); try { final ObjectMapper mapper = new ObjectMapper(); final ServletOutputStream sos = res.getOutputStream(); res.setContentType("application/json"); mapper.writeValue(sos, s); sos.flush(); } catch (final IOException e) { log.error(e.toString()); } return null; } @RequestMapping(value = "/admin/search/{terms}", method = RequestMethod.GET) public ModelAndView searchGET(final HttpServletRequest req, final HttpServletResponse res, @PathVariable("terms") final String terms) { final long timeStart = System.nanoTime(); final long timeEnd; final EntityManager em = EMFSingleton.getEntityManager(); final StringBuffer out = new StringBuffer(); final Collection<ShelfEntry> pbs = new ArrayList<ShelfEntry>(); for (final Map.Entry<PlaceBook, Integer> entry : PlaceBooksAdminHelper.search(em, terms)) { final PlaceBook p = entry.getKey(); if (p != null && p.getState() == PlaceBook.State.PUBLISHED) { log.info("Search result: pb key=" + entry.getKey().getKey() + ", score=" + entry.getValue()); pbs.add(new PlaceBookSearchEntry(p, entry.getValue())); } } em.close(); final Shelf s = new Shelf(); s.setEntries(pbs); try { final ObjectMapper mapper = new ObjectMapper(); final ServletOutputStream sos = res.getOutputStream(); res.setContentType("application/json"); mapper.writeValue(sos, s); sos.flush(); } catch (final IOException e) { log.error(e.toString()); } timeEnd = System.nanoTime(); log.info("Search execution time = " + (timeEnd - timeStart) + " ns"); return null; } @RequestMapping(value = "/admin/search", method = RequestMethod.POST) public ModelAndView searchPOST(final HttpServletRequest req, final HttpServletResponse res) { final StringBuffer out = new StringBuffer(); final String[] terms = req.getParameter("terms").split("\\s"); for (int i = 0; i < terms.length; ++i) { out.append(terms[i]); if (i < terms.length - 1) { out.append("+"); } } return searchGET(req, res, out.toString()); } @RequestMapping(value = "/admin/serve/gpstraceitem/{key}", method = RequestMethod.GET) public ModelAndView serveGPSTraceItem(final HttpServletRequest req, final HttpServletResponse res, @PathVariable("key") final String key) { final EntityManager em = EMFSingleton.getEntityManager(); log.info("Serving GPS Trace for " + key); try { final GPSTraceItem g = em.find(GPSTraceItem.class, key); if (g != null) { final String trace = g.getTrace(); res.setContentType("text/xml"); final PrintWriter p = res.getWriter(); p.print(trace); p.close(); } else { throw new Exception("GPSTrace is null"); } } catch (final Throwable e) { log.error(e.getMessage(), e); } finally { em.close(); } return null; } @RequestMapping(value = "/admin/serve/imageitem/{key}", method = RequestMethod.GET) public ModelAndView serveImageItem(final HttpServletRequest req, final HttpServletResponse res, @PathVariable("key") final String key) { final EntityManager em = EMFSingleton.getEntityManager(); log.info("Serving Image Item " + key); try { final ImageItem i = em.find(ImageItem.class, key); if (i != null) { em.getTransaction().begin(); i.attemptPathFix(); em.getTransaction().commit(); if (i.getPath() != null) { log.info(i.getPath()); try { final File image = new File(i.getPath()); final ImageInputStream iis = ImageIO.createImageInputStream(image); final Iterator<ImageReader> readers = ImageIO.getImageReaders(iis); String fmt = "png"; while (readers.hasNext()) { final ImageReader read = readers.next(); fmt = read.getFormatName(); } final OutputStream out = res.getOutputStream(); ImageIO.write(ImageIO.read(image), fmt, out); out.close(); } catch (final IOException e) { log.error(e.toString()); } } } } catch (final Throwable e) { log.error(e.getMessage(), e); } finally { em.close(); } return null; } @RequestMapping(value = "/admin/serve/{type}item/{key}", method = RequestMethod.GET) public void streamMediaItem(final HttpServletRequest req, final HttpServletResponse res, @PathVariable("type") final String type, @PathVariable("key") final String key) { String path = null; final EntityManager em = EMFSingleton.getEntityManager(); try { final MediaItem m = em.find(MediaItem.class, key); if (m != null) { em.getTransaction().begin(); m.attemptPathFix(); em.getTransaction().commit(); } else { throw new Exception("Error getting media file, invalid key"); } path = m.getPath(); } catch (final Throwable e) { log.error(e.getMessage(), e); } finally { em.close(); } if (path == null) { return; } try { String type_ = null; if (type.trim().equalsIgnoreCase("video")) { type_ = "video"; } else if (type.trim().equalsIgnoreCase("audio")) { type_ = "audio"; } else { throw new Exception("Unrecognised media item type"); } final File file = new File(path); final String[] split = PlaceBooksAdminHelper.getExtension(path); if (split == null) { throw new Exception("Error getting file suffix"); } final ServletOutputStream sos = res.getOutputStream(); final long contentLength = file.length(); res.setContentType(type_ + "/" + split[1]); res.addHeader("Accept-Ranges", "bytes"); res.addHeader("Content-Length", Long.toString(contentLength)); final FileInputStream fis = new FileInputStream(file); final BufferedInputStream bis = new BufferedInputStream(fis); final String range = req.getHeader("Range"); long startByte = 0; long endByte = contentLength - 1; if (range != null) { if (range.startsWith("bytes=")) { try { final String[] rangeItems = range.substring(6).split("-"); startByte = Long.parseLong(rangeItems[0]); endByte = Long.parseLong(rangeItems[1]); } catch (final Exception e) { } } } res.addHeader("Content-Range", "bytes " + startByte + "-" + endByte + "/" + contentLength); final int bufferLen = 2048; final byte data[] = new byte[bufferLen]; int length; bis.skip(startByte); try { while ((length = bis.read(data, 0, bufferLen)) != -1) { sos.write(data, 0, length); } sos.flush(); } finally { sos.close(); fis.close(); } } catch (final Throwable e) { // Enumeration headers = req.getHeaderNames(); // while(headers.hasMoreElements()) // { // String header = (String)headers.nextElement(); // log.info(header + ": " + req.getHeader(header)); // } log.error("Error serving " + type + " " + key); } } @RequestMapping(value = "/admin/add_item/upload", method = RequestMethod.POST) public ModelAndView uploadFile(final HttpServletRequest req) { final EntityManager manager = EMFSingleton.getEntityManager(); final ItemData itemData = new ItemData(); try { FileItem fileData = null; String name = null; String type = null; String itemKey = null; String placebookKey = null; manager.getTransaction().begin(); @SuppressWarnings("unchecked") final List<FileItem> items = new ServletFileUpload(new DiskFileItemFactory()).parseRequest(req); for (final FileItem item : items) { if (item.isFormField()) { final String value = Streams.asString(item.getInputStream()); if (!itemData.processItemData(manager, item.getFieldName(), value)) { if (item.getFieldName().equals("key")) { placebookKey = value; } else if (item.getFieldName().equals("itemKey")) { itemKey = value; } } } else { name = item.getName(); fileData = item; final String[] split = PlaceBooksAdminHelper.getExtension(item.getFieldName()); if (split == null) { continue; } type = split[0]; String dLimit = null, iden = null; if (type.equals("image")) { iden = PropertiesSingleton.IDEN_IMAGE_MAX_SIZE; dLimit = "1"; } else if (type.equals("video")) { iden = PropertiesSingleton.IDEN_VIDEO_MAX_SIZE; dLimit = "20"; } else if (type.equals("audio")) { iden = PropertiesSingleton.IDEN_AUDIO_MAX_SIZE; dLimit = "10"; } if (dLimit != null && iden != null) { final int maxSize = Integer.parseInt(PropertiesSingleton.get( PlaceBooksAdminHelper.class .getClassLoader()) .getProperty(iden, dLimit)); if ((item.getSize() / MEGABYTE) > maxSize) { throw new Exception("File too big, limit = " + Integer.toString(maxSize) + "Mb"); } } } } if (itemData.getOwner() == null) { itemData.setOwner(UserManager.getCurrentUser(manager)); } PlaceBookItem item = null; if (itemKey != null) { item = manager.find(PlaceBookItem.class, itemKey); } else if (placebookKey != null) { final PlaceBook placebook = manager.find(PlaceBook.class, placebookKey); if (type.equals("gpstrace")) { item = new GPSTraceItem(itemData.getOwner(), itemData.getSourceURL(), null); item.setPlaceBook(placebook); } else if (type.equals("image")) { item = new ImageItem(itemData.getOwner(), itemData.getGeometry(), itemData.getSourceURL(), null); item.setPlaceBook(placebook); } else if (type.equals("video")) { item = new VideoItem(itemData.getOwner(), itemData.getGeometry(), itemData.getSourceURL(), null); item.setPlaceBook(placebook); } else if (type.equals("audio")) { item = new AudioItem(itemData.getOwner(), itemData.getGeometry(), itemData.getSourceURL(), null); item.setPlaceBook(placebook); } } if (item instanceof MediaItem) { ((MediaItem) item).setSourceURL(null); ((MediaItem) item).writeDataToDisk(name, fileData.getInputStream()); } else if (item instanceof GPSTraceItem) { ((GPSTraceItem) item).setSourceURL(null); ((GPSTraceItem) item).readTrace(fileData.getInputStream()); } manager.getTransaction().commit(); return new ModelAndView("message", "text", "Success"); } catch (final Exception e) { log.error(e.toString(), e); } finally { if (manager.getTransaction().isActive()) { manager.getTransaction().rollback(); } manager.close(); } return new ModelAndView("message", "text", "Failed"); } @RequestMapping(value = "/admin/serverinfo", method = RequestMethod.GET) public ModelAndView getServerInfoJSON(final HttpServletRequest req, final HttpServletResponse res) { final ServerInfo si = new ServerInfo(); try { final ObjectMapper mapper = new ObjectMapper(); final ServletOutputStream sos = res.getOutputStream(); res.setContentType("application/json"); mapper.writeValue(sos, si); sos.flush(); } catch (final IOException e) { log.error(e.toString()); } return null; } }
Fix toolbar not hiding in print preview
placebooks-webapp/src/placebooks/controller/PlaceBooksAdminController.java
Fix toolbar not hiding in print preview
<ide><path>lacebooks-webapp/src/placebooks/controller/PlaceBooksAdminController.java <ide> writer.write("<meta property=\"og:title\" content=\"" + placebook.getMetadataValue("title") + "\"/>"); <ide> writer.write("<meta property=\"og:image\" content=\"" + placebook.getMetadataValue("title") + "\"/>"); <ide> writer.write("<meta property=\"og:description\" content=\"" + placebook.getMetadataValue("description") + "\"/>"); <add> writer.write("<style>@media print { .printHidden { display: none; } }</style>"); <ide> writer.write("</head>"); <ide> writer.write("<body></body>"); <ide> writer.write("</html>");
Java
mit
ea5a4c6ee87f6622cef06a64d569c81597ca2416
0
wizzardo/http,wizzardo/http
package com.wizzardo.http.framework.template; import java.io.IOException; import java.io.OutputStream; import java.nio.charset.Charset; import java.nio.charset.StandardCharsets; import java.util.ArrayList; import java.util.function.Consumer; /** * @author: moxa * Date: 11/24/12 */ public class RenderResult { protected byte[] bytes; protected ArrayList<RenderResult> renders; public RenderResult() { } public RenderResult(byte[] bytes) { this.bytes = bytes; } public RenderResult(String s, Charset charset) { bytes = s.getBytes(charset); } public RenderResult(String s) { this(s, Charset.defaultCharset()); } public void add(RenderResult r) { if (renders == null) renders = new ArrayList<>(); if (bytes != null) { renders.add(new RenderResult(bytes)); bytes = null; } renders.add(r); } public RenderResult append(RenderResult r) { add(r); return this; } public RenderResult append(String r) { add(new RenderResult(r)); return this; } public RenderResult append(byte[] r) { add(new RenderResult(r)); return this; } public byte[] bytes() { if (bytes == null) compact(); return bytes; } public int size() { if (bytes != null) return bytes.length; if (renders == null) return 0; int size = 0; for (RenderResult r : renders) { size += r.size(); } return size; } public void write(OutputStream out) throws IOException { if (bytes != null) { out.write(bytes); } else { for (RenderResult r : renders) { r.write(out); } } } public RenderResult compact() { if (bytes != null) return this; bytes = new byte[size()]; int offset = 0; for (RenderResult r : renders) { System.arraycopy(r.bytes(), 0, bytes, offset, r.size()); offset += r.size(); } renders = null; return this; } public String toString() { return toString(StandardCharsets.UTF_8); } public String toString(Charset charset) { StringBuilder sb = new StringBuilder(size()); toString(sb, charset); return sb.toString(); } public void toString(StringBuilder sb, Charset charset) { if (bytes != null) { sb.append(new String(bytes, charset)); } else { if (renders != null) for (RenderResult r : renders) { r.toString(sb, charset); } } } public void provideBytes(Consumer<byte[]> consumer) { if (bytes != null) consumer.accept(bytes); else for (RenderResult render : renders) { render.provideBytes(consumer); } } }
src/main/java/com/wizzardo/http/framework/template/RenderResult.java
package com.wizzardo.http.framework.template; import java.io.IOException; import java.io.OutputStream; import java.nio.charset.Charset; import java.nio.charset.StandardCharsets; import java.util.ArrayList; import java.util.function.Consumer; /** * @author: moxa * Date: 11/24/12 */ public class RenderResult { protected byte[] bytes; protected ArrayList<RenderResult> renders; public RenderResult() { } public RenderResult(byte[] bytes) { this.bytes = bytes; } public RenderResult(String s, Charset charset) { bytes = s.getBytes(charset); } public RenderResult(String s) { this(s, Charset.defaultCharset()); } public void add(RenderResult r) { if (renders == null) renders = new ArrayList<>(); if (bytes != null) { renders.add(new RenderResult(bytes)); bytes = null; } renders.add(r); } public RenderResult append(RenderResult r) { add(r); return this; } public RenderResult append(String r) { add(new RenderResult(r)); return this; } public RenderResult append(byte[] r) { add(new RenderResult(r)); return this; } public byte[] bytes() { if (bytes == null) compact(); return bytes; } public int size() { if (bytes != null) { return bytes.length; } int size = 0; for (RenderResult r : renders) { size += r.size(); } return size; } public void write(OutputStream out) throws IOException { if (bytes != null) { out.write(bytes); } else { for (RenderResult r : renders) { r.write(out); } } } public RenderResult compact() { if (bytes != null) return this; bytes = new byte[size()]; int offset = 0; for (RenderResult r : renders) { System.arraycopy(r.bytes(), 0, bytes, offset, r.size()); offset += r.size(); } renders = null; return this; } public String toString() { return toString(StandardCharsets.UTF_8); } public String toString(Charset charset) { StringBuilder sb = new StringBuilder(size()); if (bytes != null) { sb.append(new String(bytes, charset)); } else { for (RenderResult r : renders) { sb.append(r.toString(charset)); } } return sb.toString(); } public void provideBytes(Consumer<byte[]> consumer) { if (bytes != null) consumer.accept(bytes); else for (RenderResult render : renders) { render.provideBytes(consumer); } } }
small fixes
src/main/java/com/wizzardo/http/framework/template/RenderResult.java
small fixes
<ide><path>rc/main/java/com/wizzardo/http/framework/template/RenderResult.java <ide> } <ide> <ide> public int size() { <del> if (bytes != null) { <add> if (bytes != null) <ide> return bytes.length; <del> } <add> <add> if (renders == null) <add> return 0; <add> <ide> int size = 0; <ide> for (RenderResult r : renders) { <ide> size += r.size(); <ide> <ide> public String toString(Charset charset) { <ide> StringBuilder sb = new StringBuilder(size()); <add> toString(sb, charset); <add> return sb.toString(); <add> } <add> <add> public void toString(StringBuilder sb, Charset charset) { <ide> if (bytes != null) { <ide> sb.append(new String(bytes, charset)); <ide> } else { <del> for (RenderResult r : renders) { <del> sb.append(r.toString(charset)); <del> } <add> if (renders != null) <add> for (RenderResult r : renders) { <add> r.toString(sb, charset); <add> } <ide> } <del> return sb.toString(); <ide> } <ide> <ide> public void provideBytes(Consumer<byte[]> consumer) {
Java
epl-1.0
f6c1767b916c8014ce05baa08c6742f5569e33d9
0
css-iter/org.csstudio.iter,ControlSystemStudio/org.csstudio.iter,ControlSystemStudio/org.csstudio.iter,css-iter/org.csstudio.iter,ControlSystemStudio/org.csstudio.iter,ControlSystemStudio/org.csstudio.iter,css-iter/org.csstudio.iter,css-iter/org.csstudio.iter,css-iter/org.csstudio.iter,ControlSystemStudio/org.csstudio.iter,css-iter/org.csstudio.iter,css-iter/org.csstudio.iter,css-iter/org.csstudio.iter,ControlSystemStudio/org.csstudio.iter,ControlSystemStudio/org.csstudio.iter,ControlSystemStudio/org.csstudio.iter
package de.desy.language.snl.diagram.persistence; import java.io.File; import java.io.FileOutputStream; import java.util.HashMap; import java.util.List; import java.util.Map; import javax.xml.parsers.SAXParser; import javax.xml.parsers.SAXParserFactory; import org.eclipse.core.resources.ResourcesPlugin; import org.eclipse.core.runtime.IPath; import org.eclipse.draw2d.geometry.Point; import org.jdom.Element; import org.jdom.output.Format; import org.jdom.output.XMLOutputter; import org.xml.sax.helpers.DefaultHandler; import de.desy.language.snl.diagram.model.SNLDiagram; import de.desy.language.snl.diagram.model.SNLModel; import de.desy.language.snl.diagram.model.StateModel; import de.desy.language.snl.diagram.model.StateSetModel; import de.desy.language.snl.diagram.model.WhenConnection; /** * Stores and loads the diagram layout to a XML file. * * @author Kai Meyer, Sebastian Middeke (C1 WPS) * */ public class XMLPersistenceHandler implements IPersistenceHandler { /** * {@inheritDoc} * * @throws Exception * if data could not be stored * @require originalFilePath != null * @require diagram != null */ public void store(IPath originalFilePath, SNLDiagram diagram) throws Exception { assert originalFilePath != null : "originalFilePath != null"; assert diagram != null : "diagram != null"; XMLOutputter outputter = new XMLOutputter(Format.getPrettyFormat()); Element diagramElement = createDiagramTag(diagram); IPath layoutDataPath = getLayoutDataPath(originalFilePath); try (FileOutputStream outputStream = new FileOutputStream(layoutDataPath .toFile())) { outputter.output(diagramElement, outputStream); } catch (Exception e) { throw new Exception("Exception occurred while storing layout data", e); } } /** * Determines the path for file containing the layout data. * * @param originalFilePath * The path to the *.st file * @return The path * @require originalFilePath != null * @ensure result != null */ private IPath getLayoutDataPath(IPath originalFilePath) { assert originalFilePath != null : "originalFilePath != null"; String fileExtension = originalFilePath.getFileExtension(); String fileName = originalFilePath.lastSegment(); fileName = fileName.replace("." + fileExtension, ".layout"); int segmentCount = originalFilePath.segmentCount(); IPath constraintFilePath = originalFilePath .uptoSegment(segmentCount - 1); constraintFilePath = constraintFilePath.append(fileName); IPath workspacePath = ResourcesPlugin.getWorkspace().getRoot() .getLocation(); IPath result = workspacePath.append(constraintFilePath); assert result != null : "result != null"; return result; } /** * Creates a XML element for the diagram * * @param diagram * the diagram to store * @return The corresponding {@link Element} * @require diagram != null * @ensure rootElement != null */ private Element createDiagramTag(SNLDiagram diagram) { assert diagram != null : "diagram != null"; Element rootElement = new Element(XMLConstant.DIAGRAM.getIdentifier()); rootElement.setAttribute(XMLConstant.NAME.getIdentifier(), diagram .getIdentifier()); rootElement.addContent(createStateDataTag(diagram)); rootElement.addContent(createConnectionDataTag(diagram)); assert rootElement != null : "rootElement != null"; return rootElement; } /** * Creates a XML Element for all connections. * * @param diagram * The diagram to store * @require diagram != null * @ensure connectionDataElement != null */ private Element createConnectionDataTag(SNLDiagram diagram) { assert diagram != null : "diagram != null"; Element connectionDataElement = new Element(XMLConstant.CONNECTION_DATA .getIdentifier()); for (SNLModel model : diagram.getChildren()) { List<WhenConnection> sourceConnections = model .getSourceConnections(); if (!sourceConnections.isEmpty()) { for (WhenConnection connection : sourceConnections) { connectionDataElement.addContent(createConnectionTag( connection, model.getIdentifier())); } } } assert connectionDataElement != null : "connectionDataElement != null"; return connectionDataElement; } /** * Creates a XML element for a connection * * @param connection * The connection to store * @param sourceIdentifier * The identifier of the source state * @return The corresponding element * @require connection != null * @require sourceIdentifier != null * @require sourceIdentifier.trim().length() > 0 * @ensure connectionElement != null */ private Element createConnectionTag(WhenConnection connection, String sourceIdentifier) { assert connection != null : "connection != null"; assert sourceIdentifier != null : "sourceIdentifier != null"; assert sourceIdentifier.trim().length() > 0 : "${param}.trim().length() > 0"; Element connectionElement = new Element(XMLConstant.CONNECTION .getIdentifier()); connectionElement.setAttribute(XMLConstant.NAME.getIdentifier(), connection.getPropertyValue(SNLModel.PARENT) + "." + sourceIdentifier + ".(" + connection.getIdentifier() + ")"); for (Point current : connection.getBendPoints()) { connectionElement.addContent(createPointTag(current)); } assert connectionElement != null : "connectionElement != null"; return connectionElement; } /** * Creates a XML element for a point * * @param point * The point to store * @return The corresponding element * @require point != null * @ensure pointElement != null */ private Element createPointTag(Point point) { assert point != null : "point != null"; Element pointElement = new Element(XMLConstant.POINT.getIdentifier()); pointElement.setAttribute(XMLConstant.LOCATION_X.getIdentifier(), String.valueOf(point.x)); pointElement.setAttribute(XMLConstant.LOCATION_Y.getIdentifier(), String.valueOf(point.y)); assert pointElement != null : "pointElement != null"; return pointElement; } /** * Create a XML element for all states and state-sets. * * @param diagram * The diagram to store * @return The corresponding element * @require diagram != null * @ensure stateDataElement != null */ private Element createStateDataTag(SNLDiagram diagram) { assert diagram != null : "diagram != null"; Element stateDataElement = new Element(XMLConstant.STATE_DATA .getIdentifier()); for (SNLModel model : diagram.getChildren()) { if (model instanceof StateSetModel) { stateDataElement .addContent(createStateSetTag((StateSetModel) model)); } else if (model instanceof StateModel) { stateDataElement.addContent(createStateTag((StateModel) model)); } } assert stateDataElement != null : "stateDataElement != null"; return stateDataElement; } /** * Creates a XML element for a state. * * @param model * The state to store * @return The corresponding element * @require model != null * @ensure stateElement != null */ private Element createStateTag(StateModel model) { assert model != null : "model != null"; Element stateElement = new Element(XMLConstant.STATE.getIdentifier()); stateElement.setAttribute(XMLConstant.NAME.getIdentifier(), model .getPropertyValue(SNLModel.PARENT) + "." + model.getIdentifier()); stateElement.setAttribute(XMLConstant.LOCATION_X.getIdentifier(), String.valueOf(model.getLocation().x)); stateElement.setAttribute(XMLConstant.LOCATION_Y.getIdentifier(), String.valueOf(model.getLocation().y)); stateElement.setAttribute(XMLConstant.WIDTH.getIdentifier(), String .valueOf(model.getSize().width)); stateElement.setAttribute(XMLConstant.HEIGHT.getIdentifier(), String .valueOf(model.getSize().height)); assert stateElement != null : "stateElement != null"; return stateElement; } /** * Creates a XML element for a state-set. * * @param model * The state-set to store * @return The corresponding element * @require model != null * @ensure stateSetElement != null */ private Element createStateSetTag(StateSetModel model) { Element stateSetElement = new Element(XMLConstant.STATE_SET .getIdentifier()); stateSetElement.setAttribute(XMLConstant.NAME.getIdentifier(), model .getIdentifier()); stateSetElement.setAttribute(XMLConstant.LOCATION_X.getIdentifier(), String.valueOf(model.getLocation().x)); stateSetElement.setAttribute(XMLConstant.LOCATION_Y.getIdentifier(), String.valueOf(model.getLocation().y)); stateSetElement.setAttribute(XMLConstant.WIDTH.getIdentifier(), String .valueOf(model.getSize().width)); stateSetElement.setAttribute(XMLConstant.HEIGHT.getIdentifier(), String .valueOf(model.getSize().height)); return stateSetElement; } /** * {@inheritDoc} * @require originalFilePath != null */ public Map<String, List<Point>> loadConnectionLayoutData( IPath originalFilePath) { assert originalFilePath != null : "originalFilePath != null"; Map<String, List<Point>> result = new HashMap<String, List<Point>>(); ConnectionLayoutHandler handler = new ConnectionLayoutHandler(result); fillMap(originalFilePath, handler); return result; } /** * {@inheritDoc} * @require originalFilePath != null */ public Map<String, StateLayoutData> loadStateLayoutData( IPath originalFilePath) { assert originalFilePath != null : "originalFilePath != null"; Map<String, StateLayoutData> result = new HashMap<String, StateLayoutData>(); StateLayoutHandler handler = new StateLayoutHandler(result); fillMap(originalFilePath, handler); return result; } /** * Fills the given map with the loaded layout data. * * @param originalFilePath * The path to the *.st file * @param handler * The handler for the XML parser * @require originalFilePath != null * @require handler != null */ private void fillMap(IPath originalFilePath, DefaultHandler handler) { assert originalFilePath != null : "originalFilePath != null"; assert handler != null : "handler != null"; IPath layoutDataPath = getLayoutDataPath(originalFilePath); File file = layoutDataPath.toFile(); if (file.exists()) { try { SAXParser parser = SAXParserFactory.newInstance() .newSAXParser(); parser.parse(file, handler); } catch (Exception e) { e.printStackTrace(); } } } }
products/ITER/thirdparty/de.desy.language.snl.diagram/src/de/desy/language/snl/diagram/persistence/XMLPersistenceHandler.java
package de.desy.language.snl.diagram.persistence; import java.io.File; import java.io.FileOutputStream; import java.util.HashMap; import java.util.List; import java.util.Map; import javax.xml.parsers.SAXParser; import javax.xml.parsers.SAXParserFactory; import org.eclipse.core.resources.ResourcesPlugin; import org.eclipse.core.runtime.IPath; import org.eclipse.draw2d.geometry.Point; import org.jdom.Element; import org.jdom.output.Format; import org.jdom.output.XMLOutputter; import org.xml.sax.helpers.DefaultHandler; import de.desy.language.snl.diagram.model.SNLDiagram; import de.desy.language.snl.diagram.model.SNLModel; import de.desy.language.snl.diagram.model.StateModel; import de.desy.language.snl.diagram.model.StateSetModel; import de.desy.language.snl.diagram.model.WhenConnection; /** * Stores and loads the diagram layout to a XML file. * * @author Kai Meyer, Sebastian Middeke (C1 WPS) * */ public class XMLPersistenceHandler implements IPersistenceHandler { /** * {@inheritDoc} * * @throws Exception * if data could not be stored * @require originalFilePath != null * @require diagram != null */ public void store(IPath originalFilePath, SNLDiagram diagram) throws Exception { assert originalFilePath != null : "originalFilePath != null"; assert diagram != null : "diagram != null"; XMLOutputter outputter = new XMLOutputter(Format.getPrettyFormat()); Element diagramElement = createDiagramTag(diagram); IPath layoutDataPath = getLayoutDataPath(originalFilePath); try { FileOutputStream outputStream = new FileOutputStream(layoutDataPath .toFile()); outputter.output(diagramElement, outputStream); } catch (Exception e) { throw new Exception("Exception occurred while storing layout data", e); } } /** * Determines the path for file containing the layout data. * * @param originalFilePath * The path to the *.st file * @return The path * @require originalFilePath != null * @ensure result != null */ private IPath getLayoutDataPath(IPath originalFilePath) { assert originalFilePath != null : "originalFilePath != null"; String fileExtension = originalFilePath.getFileExtension(); String fileName = originalFilePath.lastSegment(); fileName = fileName.replace("." + fileExtension, ".layout"); int segmentCount = originalFilePath.segmentCount(); IPath constraintFilePath = originalFilePath .uptoSegment(segmentCount - 1); constraintFilePath = constraintFilePath.append(fileName); IPath workspacePath = ResourcesPlugin.getWorkspace().getRoot() .getLocation(); IPath result = workspacePath.append(constraintFilePath); assert result != null : "result != null"; return result; } /** * Creates a XML element for the diagram * * @param diagram * the diagram to store * @return The corresponding {@link Element} * @require diagram != null * @ensure rootElement != null */ private Element createDiagramTag(SNLDiagram diagram) { assert diagram != null : "diagram != null"; Element rootElement = new Element(XMLConstant.DIAGRAM.getIdentifier()); rootElement.setAttribute(XMLConstant.NAME.getIdentifier(), diagram .getIdentifier()); rootElement.addContent(createStateDataTag(diagram)); rootElement.addContent(createConnectionDataTag(diagram)); assert rootElement != null : "rootElement != null"; return rootElement; } /** * Creates a XML Element for all connections. * * @param diagram * The diagram to store * @require diagram != null * @ensure connectionDataElement != null */ private Element createConnectionDataTag(SNLDiagram diagram) { assert diagram != null : "diagram != null"; Element connectionDataElement = new Element(XMLConstant.CONNECTION_DATA .getIdentifier()); for (SNLModel model : diagram.getChildren()) { List<WhenConnection> sourceConnections = model .getSourceConnections(); if (!sourceConnections.isEmpty()) { for (WhenConnection connection : sourceConnections) { connectionDataElement.addContent(createConnectionTag( connection, model.getIdentifier())); } } } assert connectionDataElement != null : "connectionDataElement != null"; return connectionDataElement; } /** * Creates a XML element for a connection * * @param connection * The connection to store * @param sourceIdentifier * The identifier of the source state * @return The corresponding element * @require connection != null * @require sourceIdentifier != null * @require sourceIdentifier.trim().length() > 0 * @ensure connectionElement != null */ private Element createConnectionTag(WhenConnection connection, String sourceIdentifier) { assert connection != null : "connection != null"; assert sourceIdentifier != null : "sourceIdentifier != null"; assert sourceIdentifier.trim().length() > 0 : "${param}.trim().length() > 0"; Element connectionElement = new Element(XMLConstant.CONNECTION .getIdentifier()); connectionElement.setAttribute(XMLConstant.NAME.getIdentifier(), connection.getPropertyValue(SNLModel.PARENT) + "." + sourceIdentifier + ".(" + connection.getIdentifier() + ")"); for (Point current : connection.getBendPoints()) { connectionElement.addContent(createPointTag(current)); } assert connectionElement != null : "connectionElement != null"; return connectionElement; } /** * Creates a XML element for a point * * @param point * The point to store * @return The corresponding element * @require point != null * @ensure pointElement != null */ private Element createPointTag(Point point) { assert point != null : "point != null"; Element pointElement = new Element(XMLConstant.POINT.getIdentifier()); pointElement.setAttribute(XMLConstant.LOCATION_X.getIdentifier(), String.valueOf(point.x)); pointElement.setAttribute(XMLConstant.LOCATION_Y.getIdentifier(), String.valueOf(point.y)); assert pointElement != null : "pointElement != null"; return pointElement; } /** * Create a XML element for all states and state-sets. * * @param diagram * The diagram to store * @return The corresponding element * @require diagram != null * @ensure stateDataElement != null */ private Element createStateDataTag(SNLDiagram diagram) { assert diagram != null : "diagram != null"; Element stateDataElement = new Element(XMLConstant.STATE_DATA .getIdentifier()); for (SNLModel model : diagram.getChildren()) { if (model instanceof StateSetModel) { stateDataElement .addContent(createStateSetTag((StateSetModel) model)); } else if (model instanceof StateModel) { stateDataElement.addContent(createStateTag((StateModel) model)); } } assert stateDataElement != null : "stateDataElement != null"; return stateDataElement; } /** * Creates a XML element for a state. * * @param model * The state to store * @return The corresponding element * @require model != null * @ensure stateElement != null */ private Element createStateTag(StateModel model) { assert model != null : "model != null"; Element stateElement = new Element(XMLConstant.STATE.getIdentifier()); stateElement.setAttribute(XMLConstant.NAME.getIdentifier(), model .getPropertyValue(SNLModel.PARENT) + "." + model.getIdentifier()); stateElement.setAttribute(XMLConstant.LOCATION_X.getIdentifier(), String.valueOf(model.getLocation().x)); stateElement.setAttribute(XMLConstant.LOCATION_Y.getIdentifier(), String.valueOf(model.getLocation().y)); stateElement.setAttribute(XMLConstant.WIDTH.getIdentifier(), String .valueOf(model.getSize().width)); stateElement.setAttribute(XMLConstant.HEIGHT.getIdentifier(), String .valueOf(model.getSize().height)); assert stateElement != null : "stateElement != null"; return stateElement; } /** * Creates a XML element for a state-set. * * @param model * The state-set to store * @return The corresponding element * @require model != null * @ensure stateSetElement != null */ private Element createStateSetTag(StateSetModel model) { Element stateSetElement = new Element(XMLConstant.STATE_SET .getIdentifier()); stateSetElement.setAttribute(XMLConstant.NAME.getIdentifier(), model .getIdentifier()); stateSetElement.setAttribute(XMLConstant.LOCATION_X.getIdentifier(), String.valueOf(model.getLocation().x)); stateSetElement.setAttribute(XMLConstant.LOCATION_Y.getIdentifier(), String.valueOf(model.getLocation().y)); stateSetElement.setAttribute(XMLConstant.WIDTH.getIdentifier(), String .valueOf(model.getSize().width)); stateSetElement.setAttribute(XMLConstant.HEIGHT.getIdentifier(), String .valueOf(model.getSize().height)); return stateSetElement; } /** * {@inheritDoc} * @require originalFilePath != null */ public Map<String, List<Point>> loadConnectionLayoutData( IPath originalFilePath) { assert originalFilePath != null : "originalFilePath != null"; Map<String, List<Point>> result = new HashMap<String, List<Point>>(); ConnectionLayoutHandler handler = new ConnectionLayoutHandler(result); fillMap(originalFilePath, handler); return result; } /** * {@inheritDoc} * @require originalFilePath != null */ public Map<String, StateLayoutData> loadStateLayoutData( IPath originalFilePath) { assert originalFilePath != null : "originalFilePath != null"; Map<String, StateLayoutData> result = new HashMap<String, StateLayoutData>(); StateLayoutHandler handler = new StateLayoutHandler(result); fillMap(originalFilePath, handler); return result; } /** * Fills the given map with the loaded layout data. * * @param originalFilePath * The path to the *.st file * @param handler * The handler for the XML parser * @require originalFilePath != null * @require handler != null */ private void fillMap(IPath originalFilePath, DefaultHandler handler) { assert originalFilePath != null : "originalFilePath != null"; assert handler != null : "handler != null"; IPath layoutDataPath = getLayoutDataPath(originalFilePath); File file = layoutDataPath.toFile(); if (file.exists()) { try { SAXParser parser = SAXParserFactory.newInstance() .newSAXParser(); parser.parse(file, handler); } catch (Exception e) { e.printStackTrace(); } } } }
Warnings fixed.
products/ITER/thirdparty/de.desy.language.snl.diagram/src/de/desy/language/snl/diagram/persistence/XMLPersistenceHandler.java
Warnings fixed.
<ide><path>roducts/ITER/thirdparty/de.desy.language.snl.diagram/src/de/desy/language/snl/diagram/persistence/XMLPersistenceHandler.java <ide> <ide> IPath layoutDataPath = getLayoutDataPath(originalFilePath); <ide> <del> try { <del> FileOutputStream outputStream = new FileOutputStream(layoutDataPath <del> .toFile()); <add> try (FileOutputStream outputStream = new FileOutputStream(layoutDataPath <add> .toFile())) { <ide> outputter.output(diagramElement, outputStream); <ide> } catch (Exception e) { <ide> throw new Exception("Exception occurred while storing layout data",
Java
mit
0f0ebaddbac8277b29dd6125c9bb7a40415ab81d
0
kumoregdev/kumoreg,kumoregdev/kumoreg,jashort/kumoreg,jashort/kumoreg
package org.kumoricon.service.print.formatter; import org.apache.pdfbox.cos.COSDictionary; import org.apache.pdfbox.cos.COSName; import org.apache.pdfbox.pdmodel.PDDocument; import org.apache.pdfbox.pdmodel.PDPage; import org.apache.pdfbox.pdmodel.PDPageContentStream; import org.apache.pdfbox.pdmodel.common.PDRectangle; import org.apache.pdfbox.pdmodel.font.PDFont; import org.apache.pdfbox.util.Matrix; import org.kumoricon.model.attendee.Attendee; import java.util.List; import java.awt.*; import java.io.IOException; import java.time.LocalDate; public class AttendeeBadge2017 extends FormatterBase { private PDFont bankGothic; private PDDocument frontBackground; private LocalDate currentDateForAgeCalculation; AttendeeBadge2017(PDDocument document) { super(document); frontBackground = BadgeLib.loadBackground("2017_attendee_badge.pdf"); bankGothic = BadgeLib.loadFont(document); this.currentDateForAgeCalculation = LocalDate.now(); } public AttendeeBadge2017(PDDocument document, LocalDate currentDateForAgeCalculation) { super(document); frontBackground = BadgeLib.loadBackground("2017_attendee_badge.pdf"); this.currentDateForAgeCalculation = currentDateForAgeCalculation; bankGothic = BadgeLib.loadFont(document); } void addBadge(Attendee attendee, Integer xOffset, Integer yOffset) throws IOException { // PDPage page = document.importPage(new PDPage(new PDRectangle(612f, 396f))); PDPage templatePage = frontBackground.getDocumentCatalog().getPages().get(0); COSDictionary pageDict = templatePage.getCOSObject(); COSDictionary newPageDict = new COSDictionary(pageDict); newPageDict.removeItem(COSName.ANNOTS); newPageDict.removeItem(COSName.ACTUAL_TEXT); PDPage page = document.importPage(new PDPage(newPageDict)); // Positions are measured from the bottom left corner of the page at 72 DPI drawAgeColorStripe(page, attendee); drawVerticalAgeRangeText(page, bankGothic, attendee); drawName(page, attendee); drawBadgeTypeStripe(page, attendee); drawBadgeTypeText(page, bankGothic, attendee); drawBadgeNumber(page, bankGothic, attendee); } private void drawBadgeNumber(PDPage page, PDFont font, Attendee attendee) throws IOException { String badgeNumber = attendee.getBadgeNumber(); if (badgeNumber == null) { return; // no text, don't draw anything } List<String> badgeNumberParts = BadgeLib.splitBadgeNumber(badgeNumber); PDPageContentStream stream = new PDPageContentStream(document, page, PDPageContentStream.AppendMode.APPEND, true, false); stream.setNonStrokingColor(Color.white); stream.setStrokingColor(Color.black); // Bounding box: // stream.fillRect(163, 95, 40, 30); PDRectangle boundingBox = new PDRectangle(163, 95, 40, 30); stream.setLineWidth(0.25f); stream.beginText(); int fontSize = BadgeLib.findMaxFontSize(font, badgeNumberParts,boundingBox); stream.setFont(font, fontSize); float textWidth = font.getStringWidth(badgeNumberParts.get(0)); Float offset = textWidth * (fontSize/(2*1000.0f)); stream.newLineAtOffset(185-offset, 105+fontSize); // First character position stream.showText(badgeNumberParts.get(0)); if (badgeNumberParts.size() > 1) { textWidth = font.getStringWidth(badgeNumberParts.get(1)); Float newOffset = textWidth * (fontSize/(2*1000.0f)); stream.newLineAtOffset(offset-newOffset, -1*fontSize); // First character position stream.showText(badgeNumberParts.get(1)); } stream.close(); } private void drawBadgeTypeStripe(PDPage page, Attendee attendee) throws IOException { PDPageContentStream stream = new PDPageContentStream(document, page, PDPageContentStream.AppendMode.APPEND, true, false); if (attendee.getBadge() != null && attendee.getBadge().getBadgeTypeBackgroundColor() != null) { stream.setNonStrokingColor(Color.decode(attendee.getBadge().getBadgeTypeBackgroundColor())); } else { stream.setNonStrokingColor(Color.black); } stream.addRect(206, 85, 253, 44); stream.fill(); stream.close(); } private void drawBadgeTypeText(PDPage page, PDFont font, Attendee attendee) throws IOException { if (attendee.getBadge() == null || attendee.getBadge().getBadgeTypeText() == null) { return; // no text, don't draw anything } String badgeTypeText = attendee.getBadge().getBadgeTypeText(); PDPageContentStream stream = new PDPageContentStream(document, page, PDPageContentStream.AppendMode.APPEND, true, false); // PDRectangle boundingBox = new PDRectangle(206, 85, 253, 44); stream.setLineWidth(0.5f); stream.beginText(); int fontSize = BadgeLib.findMaxLineSize(font, badgeTypeText,240, 40); stream.setFont(font, fontSize); stream.setNonStrokingColor(Color.white); stream.setStrokingColor(Color.black); float textWidth = font.getStringWidth(badgeTypeText); Float offset = textWidth * (fontSize/(2*1000.0f)); stream.newLineAtOffset(330-offset, 100); // First character position stream.showText(badgeTypeText); stream.close(); } private void drawVerticalAgeRangeText(PDPage page, PDFont font, Attendee attendee) throws IOException { PDPageContentStream stream = new PDPageContentStream(document, page, PDPageContentStream.AppendMode.APPEND, true, false); stream.setLineWidth(0.5f); stream.beginText(); stream.setFont(font, 30); stream.setNonStrokingColor(Color.white); stream.setStrokingColor(Color.black); stream.newLineAtOffset(172, 275); // First character position String ageString = BadgeLib.getAgeRangeAtCon(attendee, currentDateForAgeCalculation); if (ageString.toLowerCase().equals("adult")) { stream.showText("A"); stream.newLineAtOffset(-1, -32); stream.showText("D"); stream.newLineAtOffset(0, -32); stream.showText("U"); stream.newLineAtOffset(2, -32); stream.showText("L"); stream.newLineAtOffset(2, -32); stream.showText("T"); } else if (ageString.toLowerCase().equals("youth")) { stream.showText("Y"); stream.newLineAtOffset(-2, -32); stream.showText("O"); stream.newLineAtOffset(0, -32); stream.showText("U"); stream.newLineAtOffset(4, -32); stream.showText("T"); stream.newLineAtOffset(-3, -32); stream.showText("H"); } else if (ageString.toLowerCase().equals("child")) { stream.showText("C"); stream.newLineAtOffset(0, -32); stream.showText("H"); stream.newLineAtOffset(5, -32); stream.showText("I"); stream.newLineAtOffset(-3, -32); stream.showText("L"); stream.newLineAtOffset(-2, -32); stream.showText("D"); } else { stream.showText("V"); stream.newLineAtOffset(0, -32); stream.showText("O"); stream.newLineAtOffset(5, -32); stream.showText("I"); stream.newLineAtOffset(-5, -32); stream.showText("D"); } stream.close(); } private void drawAgeColorStripe(PDPage page, Attendee attendee) throws IOException { PDPageContentStream stream = new PDPageContentStream(document, page, PDPageContentStream.AppendMode.APPEND, true, false); if (attendee.getCurrentAgeRange() != null) { stream.setNonStrokingColor(Color.decode(attendee.getCurrentAgeRange().getStripeColor())); } else { stream.setNonStrokingColor(Color.black); } stream.addRect(160, 85, 46, 230); stream.fill(); stream.close(); } private void drawName(PDPage page, Attendee attendee) throws IOException { PDPageContentStream stream = new PDPageContentStream(document, page, PDPageContentStream.AppendMode.APPEND, true, false); // Name bounding box: // stream.fillRect(285, 165, 170, 50); stream.beginText(); stream.setNonStrokingColor(Color.BLACK); if (attendee.getFanName() == null) { // Draw preferred name, no fan name int fontSize = BadgeLib.findMaxLineSize(bankGothic, attendee.getName(), 160, 50); stream.setFont(bankGothic, fontSize); Matrix offsetLine1 = Matrix.getTranslateInstance(285, 165); stream.setTextMatrix(offsetLine1); stream.showText(attendee.getName()); } else { // Draw fan name and preferred name stream.setFont(bankGothic, BadgeLib.findMaxLineSize(bankGothic, attendee.getFanName(), 160, 25)); Matrix offsetLine1 = Matrix.getTranslateInstance(285, 190); stream.setTextMatrix(offsetLine1); stream.showText(attendee.getFanName()); stream.setFont(bankGothic, BadgeLib.findMaxLineSize(bankGothic, attendee.getName(), 160, 25)); Matrix offsetLine2 = Matrix.getTranslateInstance(285, 165); stream.setTextMatrix(offsetLine2); stream.showText(attendee.getName()); } // drawStringWithResizing(stream, 200, 190, attendee.getFirstName() + " " + attendee.getLastName(), opts); // drawStringWithResizing(stream, 200, 190, attendee.getFirstName(), opts); // drawStringWithResizing(stream, 200, 160, attendee.getLastName(), opts); stream.close(); } public static String getFormatterName() { return "2017Attendee"; } }
src/main/java/org/kumoricon/service/print/formatter/AttendeeBadge2017.java
package org.kumoricon.service.print.formatter; import org.apache.pdfbox.cos.COSDictionary; import org.apache.pdfbox.cos.COSName; import org.apache.pdfbox.pdmodel.PDDocument; import org.apache.pdfbox.pdmodel.PDPage; import org.apache.pdfbox.pdmodel.PDPageContentStream; import org.apache.pdfbox.pdmodel.common.PDRectangle; import org.apache.pdfbox.pdmodel.font.PDFont; import org.apache.pdfbox.util.Matrix; import org.kumoricon.model.attendee.Attendee; import java.util.List; import java.awt.*; import java.io.IOException; import java.time.LocalDate; public class AttendeeBadge2017 extends FormatterBase { private PDFont bankGothic; private PDDocument frontBackground; private LocalDate currentDateForAgeCalculation; AttendeeBadge2017(PDDocument document) { super(document); frontBackground = BadgeLib.loadBackground("2017_attendee_badge.pdf"); bankGothic = BadgeLib.loadFont(document); this.currentDateForAgeCalculation = LocalDate.now(); } public AttendeeBadge2017(PDDocument document, LocalDate currentDateForAgeCalculation) { super(document); frontBackground = BadgeLib.loadBackground("2017_attendee_badge.pdf"); this.currentDateForAgeCalculation = currentDateForAgeCalculation; bankGothic = BadgeLib.loadFont(document); } void addBadge(Attendee attendee, Integer xOffset, Integer yOffset) throws IOException { // PDPage page = document.importPage(new PDPage(new PDRectangle(612f, 396f))); PDPage templatePage = frontBackground.getDocumentCatalog().getPages().get(0); COSDictionary pageDict = templatePage.getCOSObject(); COSDictionary newPageDict = new COSDictionary(pageDict); newPageDict.removeItem(COSName.ANNOTS); newPageDict.removeItem(COSName.ACTUAL_TEXT); PDPage page = document.importPage(new PDPage(newPageDict)); // Positions are measured from the bottom left corner of the page at 72 DPI drawAgeColorStripe(page, attendee); drawVerticalAgeRangeText(page, bankGothic, attendee); drawName(page, attendee); drawBadgeTypeStripe(page, attendee); drawBadgeTypeText(page, bankGothic, attendee); drawBadgeNumber(page, bankGothic, attendee); } private void drawBadgeNumber(PDPage page, PDFont font, Attendee attendee) throws IOException { String badgeNumber = attendee.getBadgeNumber(); if (badgeNumber == null) { return; // no text, don't draw anything } List<String> badgeNumberParts = BadgeLib.splitBadgeNumber(badgeNumber); PDPageContentStream stream = new PDPageContentStream(document, page, PDPageContentStream.AppendMode.APPEND, true, false); stream.setNonStrokingColor(Color.white); stream.setStrokingColor(Color.black); // Bounding box: // stream.fillRect(163, 95, 40, 30); PDRectangle boundingBox = new PDRectangle(163, 95, 40, 30); stream.setLineWidth(0.25f); stream.beginText(); int fontSize = BadgeLib.findMaxFontSize(font, badgeNumberParts,boundingBox); stream.setFont(font, fontSize); float textWidth = font.getStringWidth(badgeNumberParts.get(0)); Float offset = textWidth * (fontSize/(2*1000.0f)); stream.newLineAtOffset(185-offset, 105+fontSize); // First character position stream.showText(badgeNumberParts.get(0)); if (badgeNumberParts.size() > 1) { textWidth = font.getStringWidth(badgeNumberParts.get(1)); Float newOffset = textWidth * (fontSize/(2*1000.0f)); stream.newLineAtOffset(offset-newOffset, -1*fontSize); // First character position stream.showText(badgeNumberParts.get(1)); } stream.close(); } private void drawBadgeTypeStripe(PDPage page, Attendee attendee) throws IOException { PDPageContentStream stream = new PDPageContentStream(document, page, PDPageContentStream.AppendMode.APPEND, true, false); if (attendee.getBadge() != null && attendee.getBadge().getBadgeTypeBackgroundColor() != null) { stream.setNonStrokingColor(Color.decode(attendee.getBadge().getBadgeTypeBackgroundColor())); } else { stream.setNonStrokingColor(Color.black); } stream.addRect(206, 85, 253, 44); stream.fill(); stream.close(); } private void drawBadgeTypeText(PDPage page, PDFont font, Attendee attendee) throws IOException { if (attendee.getBadge() == null || attendee.getBadge().getBadgeTypeText() == null) { return; // no text, don't draw anything } String badgeTypeText = attendee.getBadge().getBadgeTypeText(); PDPageContentStream stream = new PDPageContentStream(document, page, PDPageContentStream.AppendMode.APPEND, true, false); // PDRectangle boundingBox = new PDRectangle(206, 85, 253, 44); stream.setLineWidth(0.5f); stream.beginText(); int fontSize = BadgeLib.findMaxLineSize(font, badgeTypeText,240, 40); stream.setFont(font, fontSize); stream.setNonStrokingColor(Color.white); stream.setStrokingColor(Color.black); float textWidth = font.getStringWidth(badgeTypeText); Float offset = textWidth * (fontSize/(2*1000.0f)); stream.newLineAtOffset(330-offset, 100); // First character position stream.showText(badgeTypeText); stream.close(); } private void drawVerticalAgeRangeText(PDPage page, PDFont font, Attendee attendee) throws IOException { PDPageContentStream stream = new PDPageContentStream(document, page, PDPageContentStream.AppendMode.APPEND, true, false); stream.setLineWidth(0.5f); stream.beginText(); stream.setFont(font, 30); stream.setNonStrokingColor(Color.white); stream.setStrokingColor(Color.black); stream.newLineAtOffset(172, 275); // First character position String ageString = BadgeLib.getAgeRangeAtCon(attendee, currentDateForAgeCalculation); if (ageString.toLowerCase().equals("adult")) { stream.showText("A"); stream.newLineAtOffset(-1, -32); stream.showText("D"); stream.newLineAtOffset(0, -32); stream.showText("U"); stream.newLineAtOffset(2, -32); stream.showText("L"); stream.newLineAtOffset(2, -32); stream.showText("T"); } else if (ageString.toLowerCase().equals("youth")) { stream.showText("Y"); stream.newLineAtOffset(-2, -32); stream.showText("O"); stream.newLineAtOffset(0, -32); stream.showText("U"); stream.newLineAtOffset(4, -32); stream.showText("T"); stream.newLineAtOffset(-3, -32); stream.showText("H"); } else if (ageString.toLowerCase().equals("child")) { stream.showText("C"); stream.newLineAtOffset(0, -32); stream.showText("H"); stream.newLineAtOffset(5, -32); stream.showText("I"); stream.newLineAtOffset(-3, -32); stream.showText("L"); stream.newLineAtOffset(-2, -32); stream.showText("D"); } else { stream.showText("V"); stream.newLineAtOffset(0, -32); stream.showText("O"); stream.newLineAtOffset(5, -32); stream.showText("I"); stream.newLineAtOffset(-5, -32); stream.showText("D"); } stream.close(); } private void drawAgeColorStripe(PDPage page, Attendee attendee) throws IOException { PDPageContentStream stream = new PDPageContentStream(document, page, PDPageContentStream.AppendMode.APPEND, true, false); if (attendee.getCurrentAgeRange() != null) { stream.setNonStrokingColor(Color.decode(attendee.getCurrentAgeRange().getStripeColor())); } else { stream.setNonStrokingColor(Color.black); } stream.addRect(160, 85, 46, 230); stream.fill(); stream.close(); } private void drawName(PDPage page, Attendee attendee) throws IOException { PDPageContentStream stream = new PDPageContentStream(document, page, PDPageContentStream.AppendMode.APPEND, true, false); // Name bounding box: // stream.fillRect(285, 165, 170, 50); stream.beginText(); if (attendee.getFanName() == null) { // Draw preferred name, no fan name int fontSize = BadgeLib.findMaxLineSize(bankGothic, attendee.getName(), 160, 50); stream.setFont(bankGothic, fontSize); Matrix offsetLine1 = Matrix.getTranslateInstance(285, 165); stream.setTextMatrix(offsetLine1); stream.showText(attendee.getName()); } else { // Draw fan name and preferred name stream.setFont(bankGothic, BadgeLib.findMaxLineSize(bankGothic, attendee.getFanName(), 160, 25)); Matrix offsetLine1 = Matrix.getTranslateInstance(285, 190); stream.setTextMatrix(offsetLine1); stream.showText(attendee.getFanName()); stream.setFont(bankGothic, BadgeLib.findMaxLineSize(bankGothic, attendee.getName(), 160, 25)); Matrix offsetLine2 = Matrix.getTranslateInstance(285, 165); stream.setTextMatrix(offsetLine2); stream.showText(attendee.getName()); } // drawStringWithResizing(stream, 200, 190, attendee.getFirstName() + " " + attendee.getLastName(), opts); // drawStringWithResizing(stream, 200, 190, attendee.getFirstName(), opts); // drawStringWithResizing(stream, 200, 160, attendee.getLastName(), opts); stream.close(); } public static String getFormatterName() { return "2017Attendee"; } }
Set names to solid black on badges
src/main/java/org/kumoricon/service/print/formatter/AttendeeBadge2017.java
Set names to solid black on badges
<ide><path>rc/main/java/org/kumoricon/service/print/formatter/AttendeeBadge2017.java <ide> // stream.fillRect(285, 165, 170, 50); <ide> <ide> stream.beginText(); <add> stream.setNonStrokingColor(Color.BLACK); <ide> if (attendee.getFanName() == null) { <ide> // Draw preferred name, no fan name <ide> int fontSize = BadgeLib.findMaxLineSize(bankGothic, attendee.getName(), 160, 50);
Java
mit
9b595d5ebc2294b92af17b2c0221cad764565ad9
0
judovana/jenkins-scm-koji-plugin,judovana/jenkins-scm-koji-plugin,judovana/jenkins-scm-koji-plugin,TheIndifferent/jenkins-scm-koji-plugin,TheIndifferent/jenkins-scm-koji-plugin
/* * The MIT License * * Copyright 2017 jvanek. * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package org.fakekoji.xmlrpc.server.core; import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.File; import java.io.FileReader; import java.io.FileWriter; import java.io.IOException; import java.io.InputStreamReader; import java.net.ServerSocket; import java.nio.file.Files; import java.nio.file.attribute.PosixFilePermission; import java.security.GeneralSecurityException; import java.util.ArrayList; import java.util.Arrays; import java.util.HashSet; import java.util.List; import java.util.Set; import org.apache.sshd.server.SshServer; import org.fakekoji.xmlrpc.server.SshUploadService; import org.junit.After; import org.junit.AfterClass; import org.junit.Assert; import org.junit.BeforeClass; import org.junit.Test; public class TestSshApi { private static final String IDS_RSA = "-----BEGIN RSA PRIVATE KEY-----\n" + "MIISKQIBAAKCBAEA6DOkXJ7K89Ai3E+XTvFjefNmXRrYVIxx8TFonXGfUvSdNISD\n" + "uZW+tC9FbFNBJWZUFludQdHAczLCKLOoUq7mTBe/wPOreSyIDI1iNnawV/KsX7Ok\n" + "yThsDolKxgRA+we8JuUYAes2y94FKaw4kAY/Ob16WSf7AP9Y8Oa4/PcK6KCIkzQx\n" + "iqL+SGG3mLy+XhTU/pJYnEC8c1lw+Gah8oPWG1vx5W578iWixgTbNp0TTXNr1+jU\n" + "xVRg1SitC4WP8g67af6f5rhcJZt5Dz/gWajHqKkK97nmPSDttso56ueeUW3L8lM3\n" + "scFjGQu3QbpLmFpMZeTpePOn7CjVjfBZnocNzDdqkgE+ivEB7nWWNbgEwALX4NR4\n" + "DzkGGoFPUKdsIdEBC5D73XC6NJxHKWOO9L+KyUxoeA8hUHBuWc3pVSi7NyG04Pvq\n" + "EfO0Ea1p4Tn2nb2CreEgOyCQ/nLJJrPEDef+8GUKKs3tVawbOn6tLFyi7aFY9u35\n" + "KX3fgt5t8TiIqmcIxs7oC16ny/97pe7gBRZuLU4AxK76m6Nxr1lGw7wJOXllhoKb\n" + "Zys676qlIG6VvSw/dAUekY/Vk9duIm9BHHLVZetv/LL4hWNy7xMvlpl8V141azJw\n" + "BE10V1GuvJnRtsf57ZqSOjiezTewavteJLwTZlRTV7QwsVpUGM7YyYJacv1GkFzz\n" + "00UWg+/Pf1gyLHf+JgsWx1ftUU9WlnVgBSfZpWKHexjcKrJzk4n96HWFL4ihCfxd\n" + "895ZkBsbTyuRAsC3Tw+k/FC6j0bbM5eE9weBH9b3Ap6tZFlIwEwXCvU28i0SbxEq\n" + "PXpnxpK33XRHz3byu8QtX4BulVrwa0P/ZeY0fvooUJo+tUqHbE7Pf5DlzylZarXQ\n" + "BSHjPcG+bs37LA2ar/1o6hRXJ5Z3b8f4YH3HumGuiYY3NjDvq++P5RTnasWFN7+f\n" + "1xYexB3HZE9RXxCTTVIn09fVHnaloNCnvhl6fn40TfsmS10qN1hwh55nzvpUjqGz\n" + "qyC+9Z/F+RpqIIAVKyijyMy2PiJRBy8sPZa1qf9+xDCZsRYdUPebr8t38sPEYYtR\n" + "8wMfY1iq0qXn1Pi/G+ghmTn+/UIdubn/m7Iu/F0GSyN6cjz4fskpS5bAb1oJhoWD\n" + "yrx6EAf96OoVIrMQcaBkLVcd7MW59rSDK0gNK7DE3ZXa85VwcMj/Y9HCybY/Xlf5\n" + "v7Csi38E+ybHP2R3YEPMduLg3hrs0UVfQaZoirA/yVtvVF3mv5Nh/RfCvCvGGR2s\n" + "PNgnq7ZKia5/nXqV4/l2Yrrg2QPYtAYwuv2Sf6GK5MqhqBtWb8qZRZVH7df4IroJ\n" + "orWmi2obRqdU5+w2F+OaL7OOs8GIwLb9iGeswwIDAQABAoIEAQC9ZPnoLgEeMyNs\n" + "DWM+GbfozXYt9OqEs/VwJLvOx9GLaUgcgQWsRw7Ai1oVzCZz6e4mOl2fRQWzMLCb\n" + "YEaoAk6HvEtEh7vSX1cs3dlA0Thu09pzSOTc16+Tf7pEn02dM6btFqmpTwBn8tTF\n" + "M9sC5oWFhB4aQHkETEJwY9B5TMtSCTa80rKiAOZlhYaqBzFDLby5VAcAk/DiKQ7z\n" + "HUt0ssHdmPZKC/7++GG3IFjpR99pqf5JoniB55v/4Wib4DoT1p5ZCz3Dg5Ztek2Y\n" + "+aH1n6wSzqbKfo/kRkp+cJ4jEv7YLjVOlz/zNeitkhfMfbaRMv3jkn44kIzkHD5r\n" + "wqJmooPHkV/UbT1lOMU5iiGV+V2ue+M3WDYBPKLU1aorABQ71O0EUSKOcRcAOIP2\n" + "p2UADoeWP0NqwfSLVtk7WK+8LTfe9RhC9lbqg5vZW1fkRFH6QYwoZVrTv3FkiZ22\n" + "eqQsL5GK5O8RENxHp9ShtpdrerfOGW+mIV680BWR+fk06sbWLqpC9prgQzmcM+vX\n" + "4WpJ3AzL2TbZNlvkvMDKpIgKuQHRJkqAF2HIGcO9nrOHK4vpPAEZkd9oHSi4qNwF\n" + "LDewi52xvwKd3CDHM+GYTU7giJqZ7JantAEYEVEWs+JRpSkf7CbX/d7NrEci3gyA\n" + "hj04u0sbiSZdf/TDhAjaH0VFv5Qk+xEf4NbGvL+UZse/WYCINYQNSbLZCH3ZmnFn\n" + "3JG/vlAB1ojpAHJb2Eg2zTIcPw//ocig27ZvzZG1fwebLB0dwPoMOtaeh66hzSv/\n" + "TTduDJsiLg/x/I9Fbw/uJd6DSypndSCq+BNUy3g32umnsmj4x3XTnfn56d2E5n2w\n" + "ivMxYaFlyMTJ3ilJJEpk2ioLzlWYVhZFMielmrpsE8EM4Rnv+lVfPzu7VDSIyMDI\n" + "L6VPLRG4+wakSajacwKBGfVB/wEWrhGxQb9uHdFcXbzNmx2m/70S5LEiOTmTv47g\n" + "rSD7bPxQ9ghx9XcXnoFjts+Crz9Pl0NbmMCJQ2KTPmAXCMJNBC0Xof3yrP0+ZKM+\n" + "ZNXTAhCPesDTgOmYtMnyKZa0XxzCf5DgBYa6zzT484w0qZcMRYewFLJEv0oD2cwC\n" + "WSbjvvCmBJLHxp9+L3H5uE4hMLuZhdIV7+KrwTetylRNxjM7wi8w0uUUE9/6uHK4\n" + "Wy4DA7kfjPmvGhbbv/63baVQRRCs7M8Sk6rUD+JZ+ZKzVK31+j8WwNT7zbXte2qs\n" + "NCnEPrGvJRKb3arq6VMJXzLlknFUbOiO6S8EvgeglunPtqyadMIhNQdk7cW+4hzq\n" + "tY4aNtT4zdozmji/WzDBSPMhIYh0CV7zSgVuFS/SsWyAWDHX4IvZCoHLlg+bROaE\n" + "NdnX6B6JAoICAQD9V6GdwcUsgbH0jJb3dhQ0Zpqcrrl8U496msYkg+b6MyqX55Ev\n" + "YItv16grvhl7QupK93pD256zGm+83e6Jxox4ZxLLmgx6fH3ubkRC7CbpRWtb7R1o\n" + "3YENjo8wmbjjcs38tUG5LEHFsZOeyVWkkW+/PCuOUl4m/3m7BOiwEYIA6vYdC42F\n" + "kBH8FaRi2zZ+kiHX2vHIbdpb7H013gSZt8ieKrLJh6FESFSINuW4ISGbCgn9nEw7\n" + "uAG7EMwQliCe66SIx+aYxaaxJL0q0tJkX/glzO//9Fu5LX+n5nCgqcTv2TB5IANi\n" + "fyi/YrbaX1hUxJFYyh39a1rIpjk4wSZwXZIC6ZHc3CKu5mNhML4a809W5siKXR/9\n" + "hQqiSeCIXuBq96E+s9kGNp9hLBUgQGooZwMZdVgOX0dSf4E6KoVz5c4PTEuJO7K8\n" + "wxlTfegUxzKzYi+A29lNHiYJF51CSJGr7Z1VFWpVUa7Ts953SgsfIYqB1Yrflgtn\n" + "vJi3+FDuNLPIMeVJLDdp8tXBUDnDzZL4eRdQEIzmYJuExEj3g3i8Vmd1fJ5yhtEd\n" + "7N93KVstqp8mGvYYnfCfXZUiwn1ivRgzfeYR+siTKuTXmwhsXBcy6Z5cLZOatjUC\n" + "uBME4We4ra9AoXc6iU9Zrn8zAEMeEtl8QSiIk2OJkqTIaWck1Li6RpRJVwKCAgEA\n" + "6qM8dzcv6naHOSJmbdZT8c8yVVAEbhkgj22mdfHJa437o0dqXm8oKyDhucDhG1kx\n" + "Uj4lBlx7vH5uDJJ3YbrsLQcQhf1r7ol84VAlJmm9OF6horLKRWc2Eke8LbtRw3VV\n" + "9M9fOP4b5gwJFeVOYHK61iKRwDw+qs1GX/5jOQLPdDC+BSzLFCGvDCFk6BrAadcn\n" + "IVfJ+7Sid9v30kpUPGpDiJzZ0Ofb6+1ppcW/YlZE6OPBJMD0cIcd3ogMFPBA+ZuQ\n" + "zLPf3PVbEUxDNLOCjTvLie5jvGvBTXrGSvXXTRt+rpBkkrd6GqM3jKBEOPMxWiFm\n" + "Uiw8WqOKKC46FpiUAD82uJddnd1R/dM1cbtJiF3QX5CEGbaKdAWzoG0CODw5tyX1\n" + "Cxgy43PCQafz/AOKAecNp6eCWkyEbjCBsCrJg3lKfQWyJ0MqToadSA+iDUYRA6PB\n" + "sEJWiy8UtnbwgDtTtUNKxWhbGOLxGRQnnSo7USE93ew8tuWa9oW9S/BEF7AiCk+S\n" + "HCINMB7ek2QXzFqS3h7WBSzDn+ZsSOo3EH5I5NV0EfgeGfAnC9mKLc9wM6XiuBOY\n" + "eLiFPc6nLlB8jJpEFioK44oQl4qV8NCP4Dwz2r+iLUt8E8vQAypYNZrZTLEktIL9\n" + "Egl+3+bUPgMJOVqwI4YCkICnJjnlVDkBL2xpFmsOGHUCggIAEvUDuvJM9s+dqVb7\n" + "1PiY+nLTDvZkGtGF4v7B5OmZ1w8NGODTFGB9DplslBldfsO7FHEATSOZ9Hz973wL\n" + "5XNd/4R2+5VDacb3BWhq4zcYkkwHhJFxqe8pQQJx5IkcNKjakRZfHKQbJ9fp2+/k\n" + "4LOhUQYHnFa9hN2JFl1/q+0jdT4fvHyo0l29eseDzYHpyf7VWXmgrgbKWCaSF/3N\n" + "ClOeR3eaeUoU3y8qZCb3eZfBFADkTn3rlmxmdMEFBBi3yCyJ21JaBwSDPK4rGZE8\n" + "/RXRU8LKErUOSAUHkGDF/L+3ZNszrVyf5DbvraKNXDnWOkGbPrGhHN1zpaAKmByb\n" + "67yUuHMR3xz522yR8yvajdm3DiGmz/O3+RiDezFcA9hVoqt0/WQn0Tc1JehOjGNF\n" + "jlBnAvis5iZrB9lSqi+UXN/NU4e5/0LgVQ+kTYMWYrelK5clRtcso4CmB/gkZFlZ\n" + "zSuyojNACbJbCqxi8ToxKtsvqhd4lNJ9d/28z8ddBvYandhd9+O/IcZyCE0ghW5U\n" + "mRM2k18pq/N+r6igbSUBW9Z7V2dD0/4Sl9KpxhjqIbiqwAc0cxMedk5iYn97MnBD\n" + "51Z8aMwDRj/nb9rB/pnFgqHIn80pRmJsBRARHERhpogYnRV3/oFX1rYf/oj+fLmc\n" + "XJfjmJSu1hSLEBQTC8Z/LDEr13ECggIBAOlnB7bvRtLMpSbIeWu5UDeyDDehKUb7\n" + "58/FG1kn81zyF+cMG1tk52g/hUrp+wLhbpaJCvuQ8+VFPuNyrx6gel8wL9eZh8v5\n" + "KChZORtFA90XBWJ6x4rSaI82nJJBS8xK4/5qaiafX9EvF7qYJ6b5ebGZIbNAOnZd\n" + "TCwhOUJ08Th7ZApxzHFyMFa4wU/BjLW8OEiKs3mW7iacwaCGH9UZP6Sdom6Utcey\n" + "mu00EHUZq+Ke7HpLFtz5C1VZr+sEMx4ZCakXJRD/YF+MpS2/g5ZKbOYAJWZBKkCQ\n" + "aMAYXNtvBk1PhTwNF4F36sIQisy73dPydX44UrE3DS97DH19uXulZiGpMI7gobcE\n" + "ap1/2F22NJlbgIyzcHaJVW24AgU+o4r0TxWCNNzdQddd4u5F9vp9hK/JiXmZtAKI\n" + "bfl4FoyaEubay6USwvrqHXqZUnIxyKr+MqXK15wMcWYwWny0h0hAcBh+/l97IKn5\n" + "yo4kfGzvzEL9xEeLjuK7ltn7X0DRDIuFK6qglM3RZ0bmwmWdk4sw0WTEarSc2gqO\n" + "MchOVuSLELLvRcI3ih/XfgSj3NEDqsvBcmJj6ubYsqT3m22h5yjFGZ/Or0KPsSej\n" + "z/sW594p0oGMHRj0HS+I58YrCw2nCQQnaOaQW40OaQJmsr5C4AP2QobL83mrDd0B\n" + "95PdG4wZYiQhAoICAAEQjP1dbHOT/4oycWukZIayEN3rGJbwjLJcM5n+VVMMprDE\n" + "2Bx9YmjijOMRHqCZY7rDr6OMhnuI1E2gkAbTfHfLWM3OpnagdL73uAjYWoU8QIZl\n" + "8NS3u8lNbDQby4WIbmtvIbPbKrnV47illLfdfcMvp16E+zXpgBERZfA5kjdvL2Zs\n" + "CoKitgJmes6Cw7gpxq04wuuq5xJ856rPmwiFTJCJGoN5yXQYZsqNsz1iWvjTVUen\n" + "JjNj5aveSb1a34JEqlLxk2NoYrT47A54iMJQSqXQQDwbW2U0vOZMv9FtwjJti9EO\n" + "aIma8wcoQhLGqt9/yQ66BzLCCQfnxMDgGUK7RD85Jcq7WghgSJv8iRQ4Hu8J7tTO\n" + "SZJOJy9IDmSp/Yh5R/9KMEdgvUQRo4JFqORyguokkKTa2EYYPpoDfCv1uEg8rr+4\n" + "xtKBxoiw+UJZGnEbUGJw2Yt2ynbV4dUlUkgMOBrznYdtmivaF544DD8Tgk8elNdT\n" + "WowvdHlPa9HCY7VNWo80vaOUXUSo6ftUkTVhyd9EI84g1JyFGPcpd624NsAhQrSm\n" + "kg8qubbQM3Tij5oGYewJ2PzeweosiQ4AVlq3+mVGnkNLPLyABHOgGmoUPpyR297R\n" + "nDe3iQJfqKGHQck94dCtx7mlbcgBwWiM1SCdZcJ8H06gBWA99hNqcwWS9kSv\n" + "-----END RSA PRIVATE KEY-----\n"; private static final String IDS_RSA_PUB = "ssh-rsa AAAAB3NzaC1yc2EAAAADAQABAAAEAQDoM6Rcnsrz0CLcT5dO8WN582ZdGthUjHHxMWidcZ9S9J00hIO5lb60L0VsU0ElZlQWW51B0cBzMsIos6hSruZMF7/A86t5LIgMjWI2drBX8qxfs6TJOGwOiUrGBED7B7wm5RgB6zbL3gUprDiQBj85vXpZJ/sA/1jw5rj89wrooIiTNDGKov5IYbeYvL5eFNT+klicQLxzWXD4ZqHyg9YbW/HlbnvyJaLGBNs2nRNNc2vX6NTFVGDVKK0LhY/yDrtp/p/muFwlm3kPP+BZqMeoqQr3ueY9IO22yjnq555RbcvyUzexwWMZC7dBukuYWkxl5Ol486fsKNWN8Fmehw3MN2qSAT6K8QHudZY1uATAAtfg1HgPOQYagU9Qp2wh0QELkPvdcLo0nEcpY470v4rJTGh4DyFQcG5ZzelVKLs3IbTg++oR87QRrWnhOfadvYKt4SA7IJD+cskms8QN5/7wZQoqze1VrBs6fq0sXKLtoVj27fkpfd+C3m3xOIiqZwjGzugLXqfL/3ul7uAFFm4tTgDErvqbo3GvWUbDvAk5eWWGgptnKzrvqqUgbpW9LD90BR6Rj9WT124ib0EcctVl62/8sviFY3LvEy+WmXxXXjVrMnAETXRXUa68mdG2x/ntmpI6OJ7NN7Bq+14kvBNmVFNXtDCxWlQYztjJglpy/UaQXPPTRRaD789/WDIsd/4mCxbHV+1RT1aWdWAFJ9mlYod7GNwqsnOTif3odYUviKEJ/F3z3lmQGxtPK5ECwLdPD6T8ULqPRtszl4T3B4Ef1vcCnq1kWUjATBcK9TbyLRJvESo9emfGkrfddEfPdvK7xC1fgG6VWvBrQ/9l5jR++ihQmj61SodsTs9/kOXPKVlqtdAFIeM9wb5uzfssDZqv/WjqFFcnlndvx/hgfce6Ya6Jhjc2MO+r74/lFOdqxYU3v5/XFh7EHcdkT1FfEJNNUifT19UedqWg0Ke+GXp+fjRN+yZLXSo3WHCHnmfO+lSOobOrIL71n8X5GmoggBUrKKPIzLY+IlEHLyw9lrWp/37EMJmxFh1Q95uvy3fyw8Rhi1HzAx9jWKrSpefU+L8b6CGZOf79Qh25uf+bsi78XQZLI3pyPPh+ySlLlsBvWgmGhYPKvHoQB/3o6hUisxBxoGQtVx3sxbn2tIMrSA0rsMTdldrzlXBwyP9j0cLJtj9eV/m/sKyLfwT7Jsc/ZHdgQ8x24uDeGuzRRV9BpmiKsD/JW29UXea/k2H9F8K8K8YZHaw82CertkqJrn+depXj+XZiuuDZA9i0BjC6/ZJ/oYrkyqGoG1ZvyplFlUft1/giugmitaaLahtGp1Tn7DYX45ovs46zwYjAtv2IZ6zD tester"; private static File kojiDb; private static File sources; private static File secondDir; private static File priv; private static File pub; private static int port; private static SshServer sshd; private static final boolean debug = true; @BeforeClass public static void startSshdServer() throws IOException, GeneralSecurityException { ServerSocket s = new ServerSocket(0); port = s.getLocalPort(); final File keys = File.createTempFile("ssh-fake-koji.", ".TestKeys"); keys.delete(); keys.mkdir(); priv = new File(keys, "id_rsa"); pub = new File(keys, "id_rsa.pub"); createFile(priv, IDS_RSA); createFile(pub, IDS_RSA_PUB); Set<PosixFilePermission> perms = new HashSet<>(); Files.setPosixFilePermissions(pub.toPath(), perms); Files.setPosixFilePermissions(priv.toPath(), perms); perms.add(PosixFilePermission.OWNER_READ); perms.add(PosixFilePermission.OWNER_WRITE); Files.setPosixFilePermissions(pub.toPath(), perms); Files.setPosixFilePermissions(priv.toPath(), perms); Runtime.getRuntime().addShutdownHook(new Thread() { @Override public void run() { priv.delete(); pub.delete(); keys.delete(); } }); s.close(); SshUploadService server = new SshUploadService(); kojiDb = File.createTempFile("ssh-fake-koji.", ".root"); kojiDb.delete(); kojiDb.mkdir(); kojiDb.deleteOnExit(); sshd = server.setup(port, kojiDb, "tester=" + pub.getAbsolutePath()); sources = File.createTempFile("ssh-fake-koji.", ".sources"); sources.delete(); sources.mkdir(); sources.deleteOnExit(); secondDir = File.createTempFile("ssh-fake-koji.", ".secondDir"); secondDir.delete(); secondDir.mkdir(); secondDir.deleteOnExit(); } @AfterClass public static void stopSshd() throws IOException { sshd.stop(true); } private static void createFile(File path, String content) throws IOException { try (BufferedWriter bw = new BufferedWriter(new FileWriter(path))) { bw.write(content); } } private static String readFile(File path) { try { try (BufferedReader br = new BufferedReader(new FileReader(path))) { return br.readLine(); } } catch (Exception ex) { ex.printStackTrace(); return "impossible"; } } private static int scpTo(String target, String... source) throws InterruptedException, IOException { return scpTo(new String[0], target, null, source); } private static int scpToCwd(String target, File cwd, String... source) throws InterruptedException, IOException { return scpTo(new String[0], target, cwd, source); } private static int scpTo(String[] params, String target, File cwd, String... source) throws InterruptedException, IOException { String fullTarget = "tester@localhost:" + target; return scpRaw(params, fullTarget, cwd, source); } private static int scpFrom(String target, String source) throws InterruptedException, IOException { return scpFrom(new String[0], target, null, source); } private static int scpFromCwd(String target, File cwd, String source) throws InterruptedException, IOException { return scpFrom(new String[0], target, cwd, source); } private static int scpFrom(String[] params, String target, File cwd, String source) throws InterruptedException, IOException { String fullSource = "tester@localhost:" + source; return scpRaw(params, target, cwd, fullSource); } private static int scpRaw(String[] params, String target, File cwd, String... source) throws InterruptedException, IOException { title(3); List<String> cmd = new ArrayList<>(params.length + source.length + 9); cmd.add("scp"); //cmd.add("-v"); //verbose cmd.add("-o"); cmd.add("StrictHostKeyChecking=no"); cmd.add("-i"); cmd.add(priv.getAbsolutePath()); cmd.add("-P"); cmd.add("" + port); cmd.addAll(Arrays.asList(params)); cmd.addAll(Arrays.asList(source)); cmd.add(target); if (debug) { for (int i = 0; i < source.length; i++) { String string = source[i]; System.out.println(i + ". scp from " + string); System.out.println(" scp to " + target); } } ProcessBuilder pb = new ProcessBuilder(cmd); if (cwd != null) { pb.directory(cwd); } Process p = pb.start(); if (debug) { BufferedReader br = new BufferedReader(new InputStreamReader(p.getErrorStream())); while (true) { String s = br.readLine(); if (s == null) { break; } System.out.println(s); } } int i = p.waitFor(); if (debug) { System.out.println(" === scpEnd === "); } return i; } @After public void cleanSecondDir() { clean(secondDir); } @After public void cleanSources() { clean(sources); } @After public void cleanKojiDb() { clean(kojiDb); } private void clean(File f) { File[] content = f.listFiles(); for (File file : content) { deleteRecursively(file); } Assert.assertTrue(f.isDirectory()); Assert.assertTrue(f.listFiles().length == 0); } private void deleteRecursively(File file) { if (file.isDirectory()) { File[] content = file.listFiles(); for (File f : content) { deleteRecursively(f); } } file.delete(); } private static void checkFileExists(File f) { if (debug) { System.out.println(f + " is supposed to exists. f.exists() is: " + f.exists()); if (f.exists()) { System.out.println("content: '" + readFile(f) + "'"); } } Assert.assertTrue(f + " was supposed to exists. was not", f.exists()); } private static void checkFileNotExists(File f) { if (debug) { System.out.println(f + " is supposed to NOT exists. f.exists() is: " + f.exists()); if (f.exists()) { System.out.println("content: '" + readFile(f) + "'"); } } Assert.assertFalse(f + " was supposed to NOT exists. was", f.exists()); } private static void title(int i) { if (debug) { String s = "method-unknow"; if (Thread.currentThread().getStackTrace().length > i) { s = Thread.currentThread().getStackTrace()[i].getMethodName(); } System.out.println(" ==" + i + "== " + s + " ==" + i + "== "); } } private class NvraTarballPathsHelper { private final String vid; private final String rid; private final String aid; public NvraTarballPathsHelper(String id) { this(id, id, id); } public NvraTarballPathsHelper(String vid, String rid, String aid) { this.vid = vid; this.rid = rid; this.aid = aid; } public String getName() { return "terrible-x-name-version" + vid + "-release" + rid + ".arch" + aid + ".suffix"; } public String getLocalName() { return getName(); } public String getRemoteName() { return getName(); } public String getNVRstub() { return "terrible-x-name/version" + vid + "/release" + rid; } public String getStub() { return getNVRstub() + "/arch" + aid; } public String getContent() { return "nvra - " + vid + ":" + rid + ":" + ":" + aid; } public String getStubWithName() { return getStub() + "/" + getRemoteName(); } public File getLocalFile() { return new File(sources, getLocalName()); } public File getSecondaryLocalFile() { return new File(secondDir, getLocalName()); } public void createLocal() throws IOException { createFile(getLocalFile(), getContent()); checkFileExists(getLocalFile()); } public void createSecondaryLocal() throws IOException { createFile(getSecondaryLocalFile(), getContent()); checkFileExists(getSecondaryLocalFile()); } public void createRemote() throws IOException { getRemoteFile().getParentFile().mkdirs(); createFile(getRemoteFile(), getContent()); checkFileExists(getRemoteFile()); } public File getRemoteFile() { return new File(kojiDb, getStubWithName()); } } @Test /* * scp /abs/path/nvra tester@localhost: */ public void scpNvraAbsPathsTo() throws IOException, InterruptedException { title(2); NvraTarballPathsHelper nvra = new NvraTarballPathsHelper("1t1"); nvra.createLocal(); int r = scpTo("", nvra.getLocalFile().getAbsolutePath()); Assert.assertTrue(r == 0); checkFileExists(nvra.getRemoteFile()); } @Test /* *scp tester@localhost:nvra /abs/path/ */ public void scpNvraAbsPathsFrom1() throws IOException, InterruptedException { title(2); NvraTarballPathsHelper nvra = new NvraTarballPathsHelper("1f1"); nvra.createRemote(); int r2 = scpFrom(nvra.getLocalFile().getParent(), nvra.getName()); Assert.assertTrue(r2 == 0); checkFileExists(nvra.getLocalFile()); } @Test /* *scp tester@localhost:/nvra /abs/path */ public void scpNvraAbsPathsFrom2() throws IOException, InterruptedException { title(2); NvraTarballPathsHelper nvra = new NvraTarballPathsHelper("1f2"); nvra.createRemote(); int r3 = scpFrom(nvra.getLocalFile().getParent(), "/" + nvra.getName()); Assert.assertTrue(r3 == 0); checkFileExists(nvra.getLocalFile()); } @Test /* * scp /abs/path/nvra tester@localhost:/nvra */ public void scpNvraAbsPathsRenameLikeTo() throws IOException, InterruptedException { title(2); NvraTarballPathsHelper nvra = new NvraTarballPathsHelper("2t1"); nvra.createLocal(); int r = scpTo("/" + nvra.getName(), nvra.getLocalFile().getAbsolutePath()); Assert.assertTrue(r == 0); checkFileExists(nvra.getRemoteFile()); } @Test /* * scp tester@localhost:nvra /abs/path/nvra */ public void scpNvraAbsPathsRenameLikeFrom1() throws IOException, InterruptedException { title(2); NvraTarballPathsHelper nvra = new NvraTarballPathsHelper("2t1"); nvra.createRemote(); int r1 = scpFrom(nvra.getLocalFile().getAbsolutePath(), nvra.getName()); Assert.assertTrue(r1 == 0); checkFileExists(nvra.getLocalFile()); } @Test /* * scp tester@localhost:nvra /abs/path/nvra2 */ public void scpNvraAbsPathsRenameLikeFrom2() throws IOException, InterruptedException { title(2); NvraTarballPathsHelper nvra = new NvraTarballPathsHelper("2t2"); nvra.createRemote(); int r2 = scpFrom(new File(nvra.getLocalFile().getParent(), "nvra2").getAbsolutePath(), nvra.getName()); Assert.assertTrue(r2 == 0); checkFileExists(new File(nvra.getLocalFile().getParent(), "nvra2")); } @Test /* * scp nvra tester@localhost: */ public void scpNvraAllRelativeToNoTarget() throws IOException, InterruptedException { title(2); NvraTarballPathsHelper nvra = new NvraTarballPathsHelper("3t1"); nvra.createLocal(); int r = scpToCwd("", sources, nvra.getLocalFile().getName()); Assert.assertTrue(r == 0); checkFileExists(nvra.getRemoteFile()); } @Test /* * scp nvra tester@localhost:nvra */ public void scpNvraAllRelativeTo() throws IOException, InterruptedException { title(2); NvraTarballPathsHelper nvra = new NvraTarballPathsHelper("3t1"); nvra.createLocal(); int r = scpToCwd("", sources, nvra.getLocalFile().getName()); Assert.assertTrue(r == 0); checkFileExists(nvra.getRemoteFile()); } @Test /* * scp nvra tester@localhost:/nvra */ public void scpNvraAllRelativeToPseudoAbs() throws IOException, InterruptedException { title(2); NvraTarballPathsHelper nvra = new NvraTarballPathsHelper("3t2"); nvra.createLocal(); int r = scpToCwd("/", sources, nvra.getLocalFile().getName()); Assert.assertTrue(r == 0); checkFileExists(nvra.getRemoteFile()); } @Test /* * scp tester@localhost:nvra . */ public void scpNvraAbsPathsFromNameToCwd() throws IOException, InterruptedException { title(2); NvraTarballPathsHelper nvra = new NvraTarballPathsHelper("3f1"); nvra.createRemote(); int r2 = scpFromCwd(".", sources, nvra.getName()); Assert.assertTrue(r2 == 0); checkFileExists(nvra.getLocalFile()); } @Test /* * scp tester@localhost:nvra ./nvra2 */ public void scpNvraAbsPathsFromNameToCwdrenamed() throws IOException, InterruptedException { title(2); NvraTarballPathsHelper nvra = new NvraTarballPathsHelper("3f2"); nvra.createRemote(); int r2 = scpFromCwd("./renamed", sources, nvra.getName()); Assert.assertTrue(r2 == 0); checkFileExists(new File(nvra.getLocalFile().getParentFile(), "renamed")); } @Test /* * scp /abs/path/nvra tester@localhost:/some/garbage */ public void scpNvraAbsToAbsGarbage() throws IOException, InterruptedException { title(2); NvraTarballPathsHelper nvra = new NvraTarballPathsHelper("4t1"); nvra.createLocal(); int r = scpTo("/some/garbage", nvra.getLocalFile().getAbsolutePath()); Assert.assertTrue(r == 0); checkFileExists(nvra.getRemoteFile()); } @Test /* scp /abs/path/nvra tester@localhost:/some/garbage/nvra */ public void scpNvraAbsToAbsGarbageRenameLike() throws IOException, InterruptedException { title(2); NvraTarballPathsHelper nvra = new NvraTarballPathsHelper("4t2"); nvra.createLocal(); int r = scpTo("/some/garbage/" + nvra.getName(), nvra.getLocalFile().getAbsolutePath()); Assert.assertTrue(r == 0); checkFileExists(nvra.getRemoteFile()); } @Test /* * scp nvra tester@localhost:some/garbage */ public void scpNvraRelToRelGarbage() throws IOException, InterruptedException { title(2); NvraTarballPathsHelper nvra = new NvraTarballPathsHelper("4t3"); nvra.createLocal(); int r = scpToCwd("some/garbage/" + nvra.getName(), nvra.getLocalFile().getParentFile(), nvra.getName()); Assert.assertTrue(r == 0); checkFileExists(nvra.getRemoteFile()); } @Test /* scp nvra tester@localhost:some/garbage/nvra */ public void scpNvraRelToRelGarbageRenameLike() throws IOException, InterruptedException { title(2); NvraTarballPathsHelper nvra = new NvraTarballPathsHelper("4t3"); nvra.createLocal(); int r = scpToCwd("some/garbage/" + nvra.getName(), nvra.getLocalFile().getParentFile(), nvra.getName()); Assert.assertTrue(r == 0); checkFileExists(nvra.getRemoteFile()); } @Test /* * scp tester@localhost:/some/garbage/nvra /abs/path/ */ public void scpAbsGarbagedNvraToAbs() throws IOException, InterruptedException { title(2); NvraTarballPathsHelper nvra = new NvraTarballPathsHelper("4f1"); nvra.createRemote(); int r2 = scpFrom(nvra.getLocalFile().getAbsolutePath(), "/some/garbage/" + nvra.getName()); Assert.assertTrue(r2 == 0); checkFileExists(nvra.getLocalFile()); } @Test /* * scp tester@localhost:some/garbage/nvra some/path/ */ public void scpRelGarbagedNvraToRel() throws IOException, InterruptedException { title(2); NvraTarballPathsHelper nvra = new NvraTarballPathsHelper("4f2"); nvra.createRemote(); int r2 = scpFromCwd(nvra.getName(), sources, "some/garbage/" + nvra.getName()); Assert.assertTrue(r2 == 0); checkFileExists(nvra.getLocalFile()); } @Test /* scp /some/path/nvra2 tester@localhost:some/garbage/nvra1 */ public void scpNvraAbsToAbsGarbageRenameLikeAnotherNvraRel() throws IOException, InterruptedException { title(2); NvraTarballPathsHelper nvraSource = new NvraTarballPathsHelper("5t1x1"); NvraTarballPathsHelper nvraTarget = new NvraTarballPathsHelper("5t1x2"); nvraSource.createLocal(); checkFileNotExists(nvraTarget.getLocalFile()); int r = scpTo("some/garbage/" + nvraTarget.getName(), nvraSource.getLocalFile().getAbsolutePath()); Assert.assertTrue(r == 0); checkFileExists(nvraTarget.getRemoteFile()); checkFileNotExists(nvraSource.getRemoteFile()); } @Test /* scp /some/path/nvra2 tester@localhost:/some/garbage/nvra1 */ public void scpNvraAbsToAbsGarbageRenameLikeAnotherNvraAbs() throws IOException, InterruptedException { title(2); NvraTarballPathsHelper nvraSource = new NvraTarballPathsHelper("5t2x1"); NvraTarballPathsHelper nvraTarget = new NvraTarballPathsHelper("5t2x2"); nvraSource.createLocal(); checkFileNotExists(nvraTarget.getLocalFile()); int r = scpTo("/some/garbage/" + nvraTarget.getName(), nvraSource.getLocalFile().getAbsolutePath()); Assert.assertTrue(r == 0); checkFileExists(nvraTarget.getRemoteFile()); checkFileNotExists(nvraSource.getRemoteFile()); } @Test /* * scp tester@localhost:some/garbage/nvra1 /some/path/nvra2 */ public void scpNvrFromAbsGarbageRenameLikeAnotherNvraAbs() throws IOException, InterruptedException { title(2); NvraTarballPathsHelper nvraSource = new NvraTarballPathsHelper("5t2x1"); NvraTarballPathsHelper nvraTarget = new NvraTarballPathsHelper("5t2x2"); nvraSource.createRemote(); checkFileNotExists(nvraTarget.getRemoteFile()); int r = scpFrom(nvraTarget.getLocalFile().getAbsolutePath(), "/some/garbage/" + nvraSource.getName()); Assert.assertTrue(r == 0); checkFileExists(nvraTarget.getLocalFile()); checkFileNotExists(nvraSource.getLocalFile()); } @Test /* * scp some/path/nonNvra tester@localhost:some/garbage/nvra */ public void scpSomeFileToGarbagedNvra() throws IOException, InterruptedException { title(2); NvraTarballPathsHelper nvra = new NvraTarballPathsHelper("5t3"); nvra.createLocal(); File renamed = new File(nvra.getLocalFile().getParentFile(), "renamed"); nvra.getLocalFile().renameTo(renamed); checkFileNotExists(nvra.getLocalFile()); checkFileExists(renamed); nvra.getLocalFile().renameTo(renamed); int r = scpTo("some/garbage/" + nvra.getName(), renamed.getAbsolutePath()); Assert.assertTrue(r == 0); checkFileExists(nvra.getRemoteFile()); } @Test /* * scp tester@localhost:some/garbage/nvra /some/path/nonNvra */ public void scpSomeFileFromGarbagedNvra() throws IOException, InterruptedException { title(2); NvraTarballPathsHelper nvra = new NvraTarballPathsHelper("5f3"); nvra.createRemote(); File nwFile = new File(nvra.getLocalFile().getParent(), "renamed"); int r = scpFrom(nwFile.getAbsolutePath(), "some/garbage/" + nvra.getName()); Assert.assertTrue(r == 0); checkFileNotExists(nvra.getLocalFile()); checkFileExists(nwFile); } @Test /* * scp some/path/nvra tester@localhost:some/garbage/NonNvra */ public void scpNvraToMoreGarbaged() throws IOException, InterruptedException { title(2); NvraTarballPathsHelper nvra = new NvraTarballPathsHelper("6t2"); nvra.createLocal(); int r2 = scpTo("/some/garbage/someFile", nvra.getLocalFile().getAbsolutePath()); Assert.assertTrue(r2 == 0); checkFileExists(nvra.getRemoteFile()); } @Test /* * scp tester@localhost:some/garbage/nonNvra some/path/nvra */ public void scpNonsenseToNvra() throws IOException, InterruptedException { //inccorect case title(2); NvraTarballPathsHelper nvra = new NvraTarballPathsHelper("6f1"); nvra.createRemote(); int r = scpFrom(nvra.getLocalFile().getAbsolutePath(), "some/garbage/notExisting"); Assert.assertTrue(r != 0); checkFileNotExists(nvra.getLocalFile()); } @Test /* * scp some/path/nvra1 some/path/nvra1 tester@localhost: */ public void scpMultipleFilesToRelNothing() throws IOException, InterruptedException { title(2); NvraTarballPathsHelper nvra1 = new NvraTarballPathsHelper("7t3"); NvraTarballPathsHelper nvra2 = new NvraTarballPathsHelper("8t3"); nvra1.createLocal(); nvra2.createLocal(); int r = scpTo("", nvra1.getLocalFile().getAbsolutePath(), nvra2.getLocalFile().getAbsolutePath()); Assert.assertTrue(r == 0); checkFileExists(nvra1.getRemoteFile()); checkFileExists(nvra2.getRemoteFile()); } @Test /* * scp some/path/nvra1 some/path/nvra1 tester@localhost: */ public void scpMultipleFilesToAbsGarbage() throws IOException, InterruptedException { title(2); NvraTarballPathsHelper nvra1 = new NvraTarballPathsHelper("7t4"); NvraTarballPathsHelper nvra2 = new NvraTarballPathsHelper("8t4"); nvra1.createLocal(); nvra2.createLocal(); int r = scpTo("/some/path/", nvra1.getLocalFile().getAbsolutePath(), nvra2.getLocalFile().getAbsolutePath()); Assert.assertTrue(r == 0); checkFileExists(nvra1.getRemoteFile()); checkFileExists(nvra2.getRemoteFile()); } /* DATA */ private class NvraDataPathsHelper extends NvraTarballPathsHelper { private final String localName; private final String remoteName; public NvraDataPathsHelper(String id, String name) { this(id, name, name); } public NvraDataPathsHelper(String id, String localName, String remoteName) { super(id); this.localName = localName; this.remoteName = remoteName; } @Override public String getRemoteName() { return remoteName; } @Override public String getLocalName() { return localName; } @Override public String getStub() { //no arch! return super.getNVRstub() + "/data"; } } // scp /some/path/logname tester@localhost:nvra/data @Test public void scpDataToRelativeNvraDataNoSlash() throws IOException, InterruptedException { title(2); NvraDataPathsHelper nvraDataFile = new NvraDataPathsHelper("data1To", "dataFile"); nvraDataFile.createLocal(); int r2 = scpTo(nvraDataFile.getName() + "/data", nvraDataFile.getLocalFile().getAbsolutePath()); Assert.assertTrue(r2 == 0); checkFileExists(nvraDataFile.getRemoteFile()); } // scp /some/path/logname tester@localhost:nvra/data/ @Test public void scpDataToRelativeNvraDataSlash() throws IOException, InterruptedException { title(2); NvraDataPathsHelper nvraDataFile = new NvraDataPathsHelper("data2To", "dataFile"); nvraDataFile.createLocal(); int r2 = scpTo(nvraDataFile.getName() + "/data/", nvraDataFile.getLocalFile().getAbsolutePath()); Assert.assertTrue(r2 == 0); checkFileExists(nvraDataFile.getRemoteFile()); } // scp /some/path/logname tester@localhost:some/garbage/nvra/data @Test public void scpDataToRelGarbageNvraDataNoSlash() throws IOException, InterruptedException { title(2); NvraDataPathsHelper nvraDataFile = new NvraDataPathsHelper("data3To", "dataFile"); nvraDataFile.createLocal(); int r2 = scpTo("some/garbage/" + nvraDataFile.getName() + "/data", nvraDataFile.getLocalFile().getAbsolutePath()); Assert.assertTrue(r2 == 0); checkFileExists(nvraDataFile.getRemoteFile()); } // scp /some/path/logname tester@localhost:some/garbage/nvra/data/ @Test public void scpDataToRelGarbageNvraDataSlash() throws IOException, InterruptedException { title(2); NvraDataPathsHelper nvraDataFile = new NvraDataPathsHelper("data4To", "dataFile"); nvraDataFile.createLocal(); int r2 = scpTo("some/garbage/" + nvraDataFile.getName() + "/data/", nvraDataFile.getLocalFile().getAbsolutePath()); Assert.assertTrue(r2 == 0); checkFileExists(nvraDataFile.getRemoteFile()); } // scp /some/path/logname tester@localhost:/some/garbage/nvra/data @Test public void scpDataToAbsGarbageNvraDataNoSlash() throws IOException, InterruptedException { title(2); NvraDataPathsHelper nvraDataFile = new NvraDataPathsHelper("data5To", "dataFile"); nvraDataFile.createLocal(); int r2 = scpTo("/some/garbage/" + nvraDataFile.getName() + "/data", nvraDataFile.getLocalFile().getAbsolutePath()); Assert.assertTrue(r2 == 0); checkFileExists(nvraDataFile.getRemoteFile()); } // scp /some/path/logname tester@localhost:nvra/data/renamedLog @Test public void scpDataToRelNvraDataRenamed() throws IOException, InterruptedException { title(2); NvraDataPathsHelper nvraDataFile = new NvraDataPathsHelper("data6To", "dataFile", "newName"); nvraDataFile.createLocal(); int r2 = scpTo(nvraDataFile.getName() + "/data/newName", nvraDataFile.getLocalFile().getAbsolutePath()); Assert.assertTrue(r2 == 0); checkFileExists(nvraDataFile.getRemoteFile()); } // scp /some/path/logname tester@localhost:some/garbage/nvra/data/renamedLog @Test public void scpDataToRelGarbageNvraDataRenamed() throws IOException, InterruptedException { title(2); NvraDataPathsHelper nvraDataFile = new NvraDataPathsHelper("data7To", "dataFile", "newName"); nvraDataFile.createLocal(); int r2 = scpTo("some/garabge/" + nvraDataFile.getName() + "/data/newName", nvraDataFile.getLocalFile().getAbsolutePath()); Assert.assertTrue(r2 == 0); checkFileExists(nvraDataFile.getRemoteFile()); } // scp /some/path/logname tester@localhost:/some/garbage/nvra/data/renamedLog @Test public void scpDataToAbsGarbageNvraDataRenamed() throws IOException, InterruptedException { title(2); NvraDataPathsHelper nvraDataFile = new NvraDataPathsHelper("data8To", "dataFile", "newName"); nvraDataFile.createLocal(); int r2 = scpTo("/some/garabge/" + nvraDataFile.getName() + "/data/newName", nvraDataFile.getLocalFile().getAbsolutePath()); Assert.assertTrue(r2 == 0); checkFileExists(nvraDataFile.getRemoteFile()); } // scp /some/path/logname tester@localhost:data @Test public void scpDataToRelDataWrong() throws IOException, InterruptedException { title(2); NvraDataPathsHelper nvraDataFile = new NvraDataPathsHelper("data9To", "dataFile"); nvraDataFile.createLocal(); int r2 = scpTo("data", nvraDataFile.getLocalFile().getAbsolutePath()); Assert.assertFalse(r2 == 0); checkFileNotExists(nvraDataFile.getRemoteFile()); } // scp /some/path/logname tester@localhost:/ @Test public void scpDataToNothing() throws IOException, InterruptedException { title(2); NvraDataPathsHelper nvraDataFile = new NvraDataPathsHelper("data10To", "dataFile", "newName"); nvraDataFile.createLocal(); int r2 = scpTo("/", nvraDataFile.getLocalFile().getAbsolutePath()); Assert.assertFalse(r2 == 0); checkFileNotExists(nvraDataFile.getRemoteFile()); } // -r uploads // // scp tester@localhost:nvra/data . // scp tester@localhost:nvra/data/ /some/path/ // scp tester@localhost:nvra/data . // scp tester@localhost:nvra/data/ /some/path/ // // scp tester@localhost:nvra/data/name . // scp tester@localhost:nvra/data/name /some/path/ // scp tester@localhost:nvra/data/name . // scp tester@localhost:nvra/data/name /some/path/ // // scp tester@localhost:nvra/data/name rename // scp tester@localhost:nvra/data/name /some/path/rename // scp tester@localhost:nvra/data/name rename // scp tester@localhost:nvra/data/name /some/path/rename // // -r may need logs implementation // scp -r tester@localhost:nvra/data . // scp -r tester@localhost:nvra/data/ /some/path/ // scp -r tester@localhost:nvra/data . // scp -r tester@localhost:nvra/data/ /some/path/ // scp -r tester@localhost:nvra/data/name . // scp -r tester@localhost:nvra/data/name /some/path/ // scp -r tester@localhost:nvra/data/name . // scp -r tester@localhost:nvra/data/name /some/path/ // scp -r tester@localhost:nvra/data/name rename // scp -r tester@localhost:nvra/data/name /some/path/rename // scp -r tester@localhost:nvra/data/name rename // scp -r tester@localhost:nvra/data/name /some/path/rename //logs //data/logs //genereic/path // -r version }
fake-koji/src/test/java/org/fakekoji/xmlrpc/server/core/TestSshApi.java
/* * The MIT License * * Copyright 2017 jvanek. * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package org.fakekoji.xmlrpc.server.core; import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.File; import java.io.FileReader; import java.io.FileWriter; import java.io.IOException; import java.io.InputStreamReader; import java.net.ServerSocket; import java.nio.file.Files; import java.nio.file.attribute.PosixFilePermission; import java.security.GeneralSecurityException; import java.util.ArrayList; import java.util.Arrays; import java.util.HashSet; import java.util.List; import java.util.Set; import org.apache.sshd.server.SshServer; import org.fakekoji.xmlrpc.server.SshUploadService; import org.junit.After; import org.junit.AfterClass; import org.junit.Assert; import org.junit.BeforeClass; import org.junit.Test; public class TestSshApi { private static final String IDS_RSA = "-----BEGIN RSA PRIVATE KEY-----\n" + "MIISKQIBAAKCBAEA6DOkXJ7K89Ai3E+XTvFjefNmXRrYVIxx8TFonXGfUvSdNISD\n" + "uZW+tC9FbFNBJWZUFludQdHAczLCKLOoUq7mTBe/wPOreSyIDI1iNnawV/KsX7Ok\n" + "yThsDolKxgRA+we8JuUYAes2y94FKaw4kAY/Ob16WSf7AP9Y8Oa4/PcK6KCIkzQx\n" + "iqL+SGG3mLy+XhTU/pJYnEC8c1lw+Gah8oPWG1vx5W578iWixgTbNp0TTXNr1+jU\n" + "xVRg1SitC4WP8g67af6f5rhcJZt5Dz/gWajHqKkK97nmPSDttso56ueeUW3L8lM3\n" + "scFjGQu3QbpLmFpMZeTpePOn7CjVjfBZnocNzDdqkgE+ivEB7nWWNbgEwALX4NR4\n" + "DzkGGoFPUKdsIdEBC5D73XC6NJxHKWOO9L+KyUxoeA8hUHBuWc3pVSi7NyG04Pvq\n" + "EfO0Ea1p4Tn2nb2CreEgOyCQ/nLJJrPEDef+8GUKKs3tVawbOn6tLFyi7aFY9u35\n" + "KX3fgt5t8TiIqmcIxs7oC16ny/97pe7gBRZuLU4AxK76m6Nxr1lGw7wJOXllhoKb\n" + "Zys676qlIG6VvSw/dAUekY/Vk9duIm9BHHLVZetv/LL4hWNy7xMvlpl8V141azJw\n" + "BE10V1GuvJnRtsf57ZqSOjiezTewavteJLwTZlRTV7QwsVpUGM7YyYJacv1GkFzz\n" + "00UWg+/Pf1gyLHf+JgsWx1ftUU9WlnVgBSfZpWKHexjcKrJzk4n96HWFL4ihCfxd\n" + "895ZkBsbTyuRAsC3Tw+k/FC6j0bbM5eE9weBH9b3Ap6tZFlIwEwXCvU28i0SbxEq\n" + "PXpnxpK33XRHz3byu8QtX4BulVrwa0P/ZeY0fvooUJo+tUqHbE7Pf5DlzylZarXQ\n" + "BSHjPcG+bs37LA2ar/1o6hRXJ5Z3b8f4YH3HumGuiYY3NjDvq++P5RTnasWFN7+f\n" + "1xYexB3HZE9RXxCTTVIn09fVHnaloNCnvhl6fn40TfsmS10qN1hwh55nzvpUjqGz\n" + "qyC+9Z/F+RpqIIAVKyijyMy2PiJRBy8sPZa1qf9+xDCZsRYdUPebr8t38sPEYYtR\n" + "8wMfY1iq0qXn1Pi/G+ghmTn+/UIdubn/m7Iu/F0GSyN6cjz4fskpS5bAb1oJhoWD\n" + "yrx6EAf96OoVIrMQcaBkLVcd7MW59rSDK0gNK7DE3ZXa85VwcMj/Y9HCybY/Xlf5\n" + "v7Csi38E+ybHP2R3YEPMduLg3hrs0UVfQaZoirA/yVtvVF3mv5Nh/RfCvCvGGR2s\n" + "PNgnq7ZKia5/nXqV4/l2Yrrg2QPYtAYwuv2Sf6GK5MqhqBtWb8qZRZVH7df4IroJ\n" + "orWmi2obRqdU5+w2F+OaL7OOs8GIwLb9iGeswwIDAQABAoIEAQC9ZPnoLgEeMyNs\n" + "DWM+GbfozXYt9OqEs/VwJLvOx9GLaUgcgQWsRw7Ai1oVzCZz6e4mOl2fRQWzMLCb\n" + "YEaoAk6HvEtEh7vSX1cs3dlA0Thu09pzSOTc16+Tf7pEn02dM6btFqmpTwBn8tTF\n" + "M9sC5oWFhB4aQHkETEJwY9B5TMtSCTa80rKiAOZlhYaqBzFDLby5VAcAk/DiKQ7z\n" + "HUt0ssHdmPZKC/7++GG3IFjpR99pqf5JoniB55v/4Wib4DoT1p5ZCz3Dg5Ztek2Y\n" + "+aH1n6wSzqbKfo/kRkp+cJ4jEv7YLjVOlz/zNeitkhfMfbaRMv3jkn44kIzkHD5r\n" + "wqJmooPHkV/UbT1lOMU5iiGV+V2ue+M3WDYBPKLU1aorABQ71O0EUSKOcRcAOIP2\n" + "p2UADoeWP0NqwfSLVtk7WK+8LTfe9RhC9lbqg5vZW1fkRFH6QYwoZVrTv3FkiZ22\n" + "eqQsL5GK5O8RENxHp9ShtpdrerfOGW+mIV680BWR+fk06sbWLqpC9prgQzmcM+vX\n" + "4WpJ3AzL2TbZNlvkvMDKpIgKuQHRJkqAF2HIGcO9nrOHK4vpPAEZkd9oHSi4qNwF\n" + "LDewi52xvwKd3CDHM+GYTU7giJqZ7JantAEYEVEWs+JRpSkf7CbX/d7NrEci3gyA\n" + "hj04u0sbiSZdf/TDhAjaH0VFv5Qk+xEf4NbGvL+UZse/WYCINYQNSbLZCH3ZmnFn\n" + "3JG/vlAB1ojpAHJb2Eg2zTIcPw//ocig27ZvzZG1fwebLB0dwPoMOtaeh66hzSv/\n" + "TTduDJsiLg/x/I9Fbw/uJd6DSypndSCq+BNUy3g32umnsmj4x3XTnfn56d2E5n2w\n" + "ivMxYaFlyMTJ3ilJJEpk2ioLzlWYVhZFMielmrpsE8EM4Rnv+lVfPzu7VDSIyMDI\n" + "L6VPLRG4+wakSajacwKBGfVB/wEWrhGxQb9uHdFcXbzNmx2m/70S5LEiOTmTv47g\n" + "rSD7bPxQ9ghx9XcXnoFjts+Crz9Pl0NbmMCJQ2KTPmAXCMJNBC0Xof3yrP0+ZKM+\n" + "ZNXTAhCPesDTgOmYtMnyKZa0XxzCf5DgBYa6zzT484w0qZcMRYewFLJEv0oD2cwC\n" + "WSbjvvCmBJLHxp9+L3H5uE4hMLuZhdIV7+KrwTetylRNxjM7wi8w0uUUE9/6uHK4\n" + "Wy4DA7kfjPmvGhbbv/63baVQRRCs7M8Sk6rUD+JZ+ZKzVK31+j8WwNT7zbXte2qs\n" + "NCnEPrGvJRKb3arq6VMJXzLlknFUbOiO6S8EvgeglunPtqyadMIhNQdk7cW+4hzq\n" + "tY4aNtT4zdozmji/WzDBSPMhIYh0CV7zSgVuFS/SsWyAWDHX4IvZCoHLlg+bROaE\n" + "NdnX6B6JAoICAQD9V6GdwcUsgbH0jJb3dhQ0Zpqcrrl8U496msYkg+b6MyqX55Ev\n" + "YItv16grvhl7QupK93pD256zGm+83e6Jxox4ZxLLmgx6fH3ubkRC7CbpRWtb7R1o\n" + "3YENjo8wmbjjcs38tUG5LEHFsZOeyVWkkW+/PCuOUl4m/3m7BOiwEYIA6vYdC42F\n" + "kBH8FaRi2zZ+kiHX2vHIbdpb7H013gSZt8ieKrLJh6FESFSINuW4ISGbCgn9nEw7\n" + "uAG7EMwQliCe66SIx+aYxaaxJL0q0tJkX/glzO//9Fu5LX+n5nCgqcTv2TB5IANi\n" + "fyi/YrbaX1hUxJFYyh39a1rIpjk4wSZwXZIC6ZHc3CKu5mNhML4a809W5siKXR/9\n" + "hQqiSeCIXuBq96E+s9kGNp9hLBUgQGooZwMZdVgOX0dSf4E6KoVz5c4PTEuJO7K8\n" + "wxlTfegUxzKzYi+A29lNHiYJF51CSJGr7Z1VFWpVUa7Ts953SgsfIYqB1Yrflgtn\n" + "vJi3+FDuNLPIMeVJLDdp8tXBUDnDzZL4eRdQEIzmYJuExEj3g3i8Vmd1fJ5yhtEd\n" + "7N93KVstqp8mGvYYnfCfXZUiwn1ivRgzfeYR+siTKuTXmwhsXBcy6Z5cLZOatjUC\n" + "uBME4We4ra9AoXc6iU9Zrn8zAEMeEtl8QSiIk2OJkqTIaWck1Li6RpRJVwKCAgEA\n" + "6qM8dzcv6naHOSJmbdZT8c8yVVAEbhkgj22mdfHJa437o0dqXm8oKyDhucDhG1kx\n" + "Uj4lBlx7vH5uDJJ3YbrsLQcQhf1r7ol84VAlJmm9OF6horLKRWc2Eke8LbtRw3VV\n" + "9M9fOP4b5gwJFeVOYHK61iKRwDw+qs1GX/5jOQLPdDC+BSzLFCGvDCFk6BrAadcn\n" + "IVfJ+7Sid9v30kpUPGpDiJzZ0Ofb6+1ppcW/YlZE6OPBJMD0cIcd3ogMFPBA+ZuQ\n" + "zLPf3PVbEUxDNLOCjTvLie5jvGvBTXrGSvXXTRt+rpBkkrd6GqM3jKBEOPMxWiFm\n" + "Uiw8WqOKKC46FpiUAD82uJddnd1R/dM1cbtJiF3QX5CEGbaKdAWzoG0CODw5tyX1\n" + "Cxgy43PCQafz/AOKAecNp6eCWkyEbjCBsCrJg3lKfQWyJ0MqToadSA+iDUYRA6PB\n" + "sEJWiy8UtnbwgDtTtUNKxWhbGOLxGRQnnSo7USE93ew8tuWa9oW9S/BEF7AiCk+S\n" + "HCINMB7ek2QXzFqS3h7WBSzDn+ZsSOo3EH5I5NV0EfgeGfAnC9mKLc9wM6XiuBOY\n" + "eLiFPc6nLlB8jJpEFioK44oQl4qV8NCP4Dwz2r+iLUt8E8vQAypYNZrZTLEktIL9\n" + "Egl+3+bUPgMJOVqwI4YCkICnJjnlVDkBL2xpFmsOGHUCggIAEvUDuvJM9s+dqVb7\n" + "1PiY+nLTDvZkGtGF4v7B5OmZ1w8NGODTFGB9DplslBldfsO7FHEATSOZ9Hz973wL\n" + "5XNd/4R2+5VDacb3BWhq4zcYkkwHhJFxqe8pQQJx5IkcNKjakRZfHKQbJ9fp2+/k\n" + "4LOhUQYHnFa9hN2JFl1/q+0jdT4fvHyo0l29eseDzYHpyf7VWXmgrgbKWCaSF/3N\n" + "ClOeR3eaeUoU3y8qZCb3eZfBFADkTn3rlmxmdMEFBBi3yCyJ21JaBwSDPK4rGZE8\n" + "/RXRU8LKErUOSAUHkGDF/L+3ZNszrVyf5DbvraKNXDnWOkGbPrGhHN1zpaAKmByb\n" + "67yUuHMR3xz522yR8yvajdm3DiGmz/O3+RiDezFcA9hVoqt0/WQn0Tc1JehOjGNF\n" + "jlBnAvis5iZrB9lSqi+UXN/NU4e5/0LgVQ+kTYMWYrelK5clRtcso4CmB/gkZFlZ\n" + "zSuyojNACbJbCqxi8ToxKtsvqhd4lNJ9d/28z8ddBvYandhd9+O/IcZyCE0ghW5U\n" + "mRM2k18pq/N+r6igbSUBW9Z7V2dD0/4Sl9KpxhjqIbiqwAc0cxMedk5iYn97MnBD\n" + "51Z8aMwDRj/nb9rB/pnFgqHIn80pRmJsBRARHERhpogYnRV3/oFX1rYf/oj+fLmc\n" + "XJfjmJSu1hSLEBQTC8Z/LDEr13ECggIBAOlnB7bvRtLMpSbIeWu5UDeyDDehKUb7\n" + "58/FG1kn81zyF+cMG1tk52g/hUrp+wLhbpaJCvuQ8+VFPuNyrx6gel8wL9eZh8v5\n" + "KChZORtFA90XBWJ6x4rSaI82nJJBS8xK4/5qaiafX9EvF7qYJ6b5ebGZIbNAOnZd\n" + "TCwhOUJ08Th7ZApxzHFyMFa4wU/BjLW8OEiKs3mW7iacwaCGH9UZP6Sdom6Utcey\n" + "mu00EHUZq+Ke7HpLFtz5C1VZr+sEMx4ZCakXJRD/YF+MpS2/g5ZKbOYAJWZBKkCQ\n" + "aMAYXNtvBk1PhTwNF4F36sIQisy73dPydX44UrE3DS97DH19uXulZiGpMI7gobcE\n" + "ap1/2F22NJlbgIyzcHaJVW24AgU+o4r0TxWCNNzdQddd4u5F9vp9hK/JiXmZtAKI\n" + "bfl4FoyaEubay6USwvrqHXqZUnIxyKr+MqXK15wMcWYwWny0h0hAcBh+/l97IKn5\n" + "yo4kfGzvzEL9xEeLjuK7ltn7X0DRDIuFK6qglM3RZ0bmwmWdk4sw0WTEarSc2gqO\n" + "MchOVuSLELLvRcI3ih/XfgSj3NEDqsvBcmJj6ubYsqT3m22h5yjFGZ/Or0KPsSej\n" + "z/sW594p0oGMHRj0HS+I58YrCw2nCQQnaOaQW40OaQJmsr5C4AP2QobL83mrDd0B\n" + "95PdG4wZYiQhAoICAAEQjP1dbHOT/4oycWukZIayEN3rGJbwjLJcM5n+VVMMprDE\n" + "2Bx9YmjijOMRHqCZY7rDr6OMhnuI1E2gkAbTfHfLWM3OpnagdL73uAjYWoU8QIZl\n" + "8NS3u8lNbDQby4WIbmtvIbPbKrnV47illLfdfcMvp16E+zXpgBERZfA5kjdvL2Zs\n" + "CoKitgJmes6Cw7gpxq04wuuq5xJ856rPmwiFTJCJGoN5yXQYZsqNsz1iWvjTVUen\n" + "JjNj5aveSb1a34JEqlLxk2NoYrT47A54iMJQSqXQQDwbW2U0vOZMv9FtwjJti9EO\n" + "aIma8wcoQhLGqt9/yQ66BzLCCQfnxMDgGUK7RD85Jcq7WghgSJv8iRQ4Hu8J7tTO\n" + "SZJOJy9IDmSp/Yh5R/9KMEdgvUQRo4JFqORyguokkKTa2EYYPpoDfCv1uEg8rr+4\n" + "xtKBxoiw+UJZGnEbUGJw2Yt2ynbV4dUlUkgMOBrznYdtmivaF544DD8Tgk8elNdT\n" + "WowvdHlPa9HCY7VNWo80vaOUXUSo6ftUkTVhyd9EI84g1JyFGPcpd624NsAhQrSm\n" + "kg8qubbQM3Tij5oGYewJ2PzeweosiQ4AVlq3+mVGnkNLPLyABHOgGmoUPpyR297R\n" + "nDe3iQJfqKGHQck94dCtx7mlbcgBwWiM1SCdZcJ8H06gBWA99hNqcwWS9kSv\n" + "-----END RSA PRIVATE KEY-----\n"; private static final String IDS_RSA_PUB = "ssh-rsa AAAAB3NzaC1yc2EAAAADAQABAAAEAQDoM6Rcnsrz0CLcT5dO8WN582ZdGthUjHHxMWidcZ9S9J00hIO5lb60L0VsU0ElZlQWW51B0cBzMsIos6hSruZMF7/A86t5LIgMjWI2drBX8qxfs6TJOGwOiUrGBED7B7wm5RgB6zbL3gUprDiQBj85vXpZJ/sA/1jw5rj89wrooIiTNDGKov5IYbeYvL5eFNT+klicQLxzWXD4ZqHyg9YbW/HlbnvyJaLGBNs2nRNNc2vX6NTFVGDVKK0LhY/yDrtp/p/muFwlm3kPP+BZqMeoqQr3ueY9IO22yjnq555RbcvyUzexwWMZC7dBukuYWkxl5Ol486fsKNWN8Fmehw3MN2qSAT6K8QHudZY1uATAAtfg1HgPOQYagU9Qp2wh0QELkPvdcLo0nEcpY470v4rJTGh4DyFQcG5ZzelVKLs3IbTg++oR87QRrWnhOfadvYKt4SA7IJD+cskms8QN5/7wZQoqze1VrBs6fq0sXKLtoVj27fkpfd+C3m3xOIiqZwjGzugLXqfL/3ul7uAFFm4tTgDErvqbo3GvWUbDvAk5eWWGgptnKzrvqqUgbpW9LD90BR6Rj9WT124ib0EcctVl62/8sviFY3LvEy+WmXxXXjVrMnAETXRXUa68mdG2x/ntmpI6OJ7NN7Bq+14kvBNmVFNXtDCxWlQYztjJglpy/UaQXPPTRRaD789/WDIsd/4mCxbHV+1RT1aWdWAFJ9mlYod7GNwqsnOTif3odYUviKEJ/F3z3lmQGxtPK5ECwLdPD6T8ULqPRtszl4T3B4Ef1vcCnq1kWUjATBcK9TbyLRJvESo9emfGkrfddEfPdvK7xC1fgG6VWvBrQ/9l5jR++ihQmj61SodsTs9/kOXPKVlqtdAFIeM9wb5uzfssDZqv/WjqFFcnlndvx/hgfce6Ya6Jhjc2MO+r74/lFOdqxYU3v5/XFh7EHcdkT1FfEJNNUifT19UedqWg0Ke+GXp+fjRN+yZLXSo3WHCHnmfO+lSOobOrIL71n8X5GmoggBUrKKPIzLY+IlEHLyw9lrWp/37EMJmxFh1Q95uvy3fyw8Rhi1HzAx9jWKrSpefU+L8b6CGZOf79Qh25uf+bsi78XQZLI3pyPPh+ySlLlsBvWgmGhYPKvHoQB/3o6hUisxBxoGQtVx3sxbn2tIMrSA0rsMTdldrzlXBwyP9j0cLJtj9eV/m/sKyLfwT7Jsc/ZHdgQ8x24uDeGuzRRV9BpmiKsD/JW29UXea/k2H9F8K8K8YZHaw82CertkqJrn+depXj+XZiuuDZA9i0BjC6/ZJ/oYrkyqGoG1ZvyplFlUft1/giugmitaaLahtGp1Tn7DYX45ovs46zwYjAtv2IZ6zD tester"; private static File kojiDb; private static File sources; private static File secondDir; private static File priv; private static File pub; private static int port; private static SshServer sshd; private static final boolean debug = true; @BeforeClass public static void startSshdServer() throws IOException, GeneralSecurityException { ServerSocket s = new ServerSocket(0); port = s.getLocalPort(); final File keys = File.createTempFile("ssh-fake-koji.", ".TestKeys"); keys.delete(); keys.mkdir(); priv = new File(keys, "id_rsa"); pub = new File(keys, "id_rsa.pub"); createFile(priv, IDS_RSA); createFile(pub, IDS_RSA_PUB); Set<PosixFilePermission> perms = new HashSet<>(); Files.setPosixFilePermissions(pub.toPath(), perms); Files.setPosixFilePermissions(priv.toPath(), perms); perms.add(PosixFilePermission.OWNER_READ); perms.add(PosixFilePermission.OWNER_WRITE); Files.setPosixFilePermissions(pub.toPath(), perms); Files.setPosixFilePermissions(priv.toPath(), perms); Runtime.getRuntime().addShutdownHook(new Thread() { @Override public void run() { priv.delete(); pub.delete(); keys.delete(); } }); s.close(); SshUploadService server = new SshUploadService(); kojiDb = File.createTempFile("ssh-fake-koji.", ".root"); kojiDb.delete(); kojiDb.mkdir(); kojiDb.deleteOnExit(); sshd = server.setup(port, kojiDb, "tester=" + pub.getAbsolutePath()); sources = File.createTempFile("ssh-fake-koji.", ".sources"); sources.delete(); sources.mkdir(); sources.deleteOnExit(); secondDir = File.createTempFile("ssh-fake-koji.", ".secondDir"); secondDir.delete(); secondDir.mkdir(); secondDir.deleteOnExit(); } @AfterClass public static void stopSshd() throws IOException { sshd.stop(true); } private static void createFile(File path, String content) throws IOException { try (BufferedWriter bw = new BufferedWriter(new FileWriter(path))) { bw.write(content); } } private static String readFile(File path) { try { try (BufferedReader br = new BufferedReader(new FileReader(path))) { return br.readLine(); } } catch (Exception ex) { ex.printStackTrace(); return "impossible"; } } private static int scpTo(String target, String... source) throws InterruptedException, IOException { return scpTo(new String[0], target, null, source); } private static int scpToCwd(String target, File cwd, String... source) throws InterruptedException, IOException { return scpTo(new String[0], target, cwd, source); } private static int scpTo(String[] params, String target, File cwd, String... source) throws InterruptedException, IOException { String fullTarget = "tester@localhost:" + target; return scpRaw(params, fullTarget, cwd, source); } private static int scpFrom(String target, String source) throws InterruptedException, IOException { return scpFrom(new String[0], target, null, source); } private static int scpFromCwd(String target, File cwd, String source) throws InterruptedException, IOException { return scpFrom(new String[0], target, cwd, source); } private static int scpFrom(String[] params, String target, File cwd, String source) throws InterruptedException, IOException { String fullSource = "tester@localhost:" + source; return scpRaw(params, target, cwd, fullSource); } private static int scpRaw(String[] params, String target, File cwd, String... source) throws InterruptedException, IOException { title(3); List<String> cmd = new ArrayList<>(params.length + source.length + 9); cmd.add("scp"); //cmd.add("-v"); //verbose cmd.add("-o"); cmd.add("StrictHostKeyChecking=no"); cmd.add("-i"); cmd.add(priv.getAbsolutePath()); cmd.add("-P"); cmd.add("" + port); cmd.addAll(Arrays.asList(params)); cmd.addAll(Arrays.asList(source)); cmd.add(target); if (debug) { for (int i = 0; i < source.length; i++) { String string = source[i]; System.out.println(i + ". scp from " + string); System.out.println(" scp to " + target); } } ProcessBuilder pb = new ProcessBuilder(cmd); if (cwd != null) { pb.directory(cwd); } Process p = pb.start(); if (debug) { BufferedReader br = new BufferedReader(new InputStreamReader(p.getErrorStream())); while (true) { String s = br.readLine(); if (s == null) { break; } System.out.println(s); } } int i = p.waitFor(); if (debug) { System.out.println(" === scpEnd === "); } return i; } @After public void cleanSecondDir() { clean(secondDir); } @After public void cleanSources() { clean(sources); } @After public void cleanKojiDb() { clean(kojiDb); } private void clean(File f) { File[] content = f.listFiles(); for (File file : content) { deleteRecursively(file); } Assert.assertTrue(f.isDirectory()); Assert.assertTrue(f.listFiles().length == 0); } private void deleteRecursively(File file) { if (file.isDirectory()) { File[] content = file.listFiles(); for (File f : content) { deleteRecursively(f); } } file.delete(); } private static void checkFileExists(File f) { if (debug) { System.out.println(f + " is supposed to exists. f.exists() is: " + f.exists()); if (f.exists()) { System.out.println("content: '" + readFile(f) + "'"); } } Assert.assertTrue(f + " was supposed to exists. was not", f.exists()); } private static void checkFileNotExists(File f) { if (debug) { System.out.println(f + " is supposed to NOT exists. f.exists() is: " + f.exists()); if (f.exists()) { System.out.println("content: '" + readFile(f) + "'"); } } Assert.assertFalse(f + " was supposed to NOT exists. was", f.exists()); } private static void title(int i) { if (debug) { String s = "method-unknow"; if (Thread.currentThread().getStackTrace().length > i) { s = Thread.currentThread().getStackTrace()[i].getMethodName(); } System.out.println(" ==" + i + "== " + s + " ==" + i + "== "); } } private class NvraTarballPathsHelper { private final String vid; private final String rid; private final String aid; public NvraTarballPathsHelper(String id) { this(id, id, id); } public NvraTarballPathsHelper(String vid, String rid, String aid) { this.vid = vid; this.rid = rid; this.aid = aid; } public String getName() { return "terrible-x-name-version" + vid + "-release" + rid + ".arch" + aid + ".suffix"; } public String getLocalName() { return getName(); } public String getRemoteName() { return getName(); } public String getNVRstub() { return "terrible-x-name/version" + vid + "/release" + rid; } public String getStub() { return getNVRstub() + "/arch" + aid; } public String getContent() { return "nvra - " + vid + ":" + rid + ":" + ":" + aid; } public String getStubWithName() { return getStub() + "/" + getRemoteName(); } public File getLocalFile() { return new File(sources, getLocalName()); } public File getSecondaryLocalFile() { return new File(secondDir, getLocalName()); } public void createLocal() throws IOException { createFile(getLocalFile(), getContent()); checkFileExists(getLocalFile()); } public void createSecondaryLocal() throws IOException { createFile(getSecondaryLocalFile(), getContent()); checkFileExists(getSecondaryLocalFile()); } public void createRemote() throws IOException { getRemoteFile().getParentFile().mkdirs(); createFile(getRemoteFile(), getContent()); checkFileExists(getRemoteFile()); } public File getRemoteFile() { return new File(kojiDb, getStubWithName()); } } @Test /* * scp /abs/path/nvra tester@localhost: */ public void scpNvraAbsPathsTo() throws IOException, InterruptedException { title(2); NvraTarballPathsHelper nvra = new NvraTarballPathsHelper("1t1"); nvra.createLocal(); int r = scpTo("", nvra.getLocalFile().getAbsolutePath()); Assert.assertTrue(r == 0); checkFileExists(nvra.getRemoteFile()); } @Test /* *scp tester@localhost:nvra /abs/path/ */ public void scpNvraAbsPathsFrom1() throws IOException, InterruptedException { title(2); NvraTarballPathsHelper nvra = new NvraTarballPathsHelper("1f1"); nvra.createRemote(); int r2 = scpFrom(nvra.getLocalFile().getParent(), nvra.getName()); Assert.assertTrue(r2 == 0); checkFileExists(nvra.getLocalFile()); } @Test /* *scp tester@localhost:/nvra /abs/path */ public void scpNvraAbsPathsFrom2() throws IOException, InterruptedException { title(2); NvraTarballPathsHelper nvra = new NvraTarballPathsHelper("1f2"); nvra.createRemote(); int r3 = scpFrom(nvra.getLocalFile().getParent(), "/" + nvra.getName()); Assert.assertTrue(r3 == 0); checkFileExists(nvra.getLocalFile()); } @Test /* * scp /abs/path/nvra tester@localhost:/nvra */ public void scpNvraAbsPathsRenameLikeTo() throws IOException, InterruptedException { title(2); NvraTarballPathsHelper nvra = new NvraTarballPathsHelper("2t1"); nvra.createLocal(); int r = scpTo("/" + nvra.getName(), nvra.getLocalFile().getAbsolutePath()); Assert.assertTrue(r == 0); checkFileExists(nvra.getRemoteFile()); } @Test /* * scp tester@localhost:nvra /abs/path/nvra */ public void scpNvraAbsPathsRenameLikeFrom1() throws IOException, InterruptedException { title(2); NvraTarballPathsHelper nvra = new NvraTarballPathsHelper("2t1"); nvra.createRemote(); int r1 = scpFrom(nvra.getLocalFile().getAbsolutePath(), nvra.getName()); Assert.assertTrue(r1 == 0); checkFileExists(nvra.getLocalFile()); } @Test /* * scp tester@localhost:nvra /abs/path/nvra2 */ public void scpNvraAbsPathsRenameLikeFrom2() throws IOException, InterruptedException { title(2); NvraTarballPathsHelper nvra = new NvraTarballPathsHelper("2t2"); nvra.createRemote(); int r2 = scpFrom(new File(nvra.getLocalFile().getParent(), "nvra2").getAbsolutePath(), nvra.getName()); Assert.assertTrue(r2 == 0); checkFileExists(new File(nvra.getLocalFile().getParent(), "nvra2")); } @Test /* * scp nvra tester@localhost: */ public void scpNvraAllRelativeToNoTarget() throws IOException, InterruptedException { title(2); NvraTarballPathsHelper nvra = new NvraTarballPathsHelper("3t1"); nvra.createLocal(); int r = scpToCwd("", sources, nvra.getLocalFile().getName()); Assert.assertTrue(r == 0); checkFileExists(nvra.getRemoteFile()); } @Test /* * scp nvra tester@localhost:nvra */ public void scpNvraAllRelativeTo() throws IOException, InterruptedException { title(2); NvraTarballPathsHelper nvra = new NvraTarballPathsHelper("3t1"); nvra.createLocal(); int r = scpToCwd("", sources, nvra.getLocalFile().getName()); Assert.assertTrue(r == 0); checkFileExists(nvra.getRemoteFile()); } @Test /* * scp nvra tester@localhost:/nvra */ public void scpNvraAllRelativeToPseudoAbs() throws IOException, InterruptedException { title(2); NvraTarballPathsHelper nvra = new NvraTarballPathsHelper("3t2"); nvra.createLocal(); int r = scpToCwd("/", sources, nvra.getLocalFile().getName()); Assert.assertTrue(r == 0); checkFileExists(nvra.getRemoteFile()); } @Test /* * scp tester@localhost:nvra . */ public void scpNvraAbsPathsFromNameToCwd() throws IOException, InterruptedException { title(2); NvraTarballPathsHelper nvra = new NvraTarballPathsHelper("3f1"); nvra.createRemote(); int r2 = scpFromCwd(".", sources, nvra.getName()); Assert.assertTrue(r2 == 0); checkFileExists(nvra.getLocalFile()); } @Test /* * scp tester@localhost:nvra ./nvra2 */ public void scpNvraAbsPathsFromNameToCwdrenamed() throws IOException, InterruptedException { title(2); NvraTarballPathsHelper nvra = new NvraTarballPathsHelper("3f2"); nvra.createRemote(); int r2 = scpFromCwd("./renamed", sources, nvra.getName()); Assert.assertTrue(r2 == 0); checkFileExists(new File(nvra.getLocalFile().getParentFile(), "renamed")); } @Test /* * scp /abs/path/nvra tester@localhost:/some/garbage */ public void scpNvraAbsToAbsGarbage() throws IOException, InterruptedException { title(2); NvraTarballPathsHelper nvra = new NvraTarballPathsHelper("4t1"); nvra.createLocal(); int r = scpTo("/some/garbage", nvra.getLocalFile().getAbsolutePath()); Assert.assertTrue(r == 0); checkFileExists(nvra.getRemoteFile()); } @Test /* scp /abs/path/nvra tester@localhost:/some/garbage/nvra */ public void scpNvraAbsToAbsGarbageRenameLike() throws IOException, InterruptedException { title(2); NvraTarballPathsHelper nvra = new NvraTarballPathsHelper("4t2"); nvra.createLocal(); int r = scpTo("/some/garbage/" + nvra.getName(), nvra.getLocalFile().getAbsolutePath()); Assert.assertTrue(r == 0); checkFileExists(nvra.getRemoteFile()); } @Test /* * scp nvra tester@localhost:some/garbage */ public void scpNvraRelToRelGarbage() throws IOException, InterruptedException { title(2); NvraTarballPathsHelper nvra = new NvraTarballPathsHelper("4t3"); nvra.createLocal(); int r = scpToCwd("some/garbage/" + nvra.getName(), nvra.getLocalFile().getParentFile(), nvra.getName()); Assert.assertTrue(r == 0); checkFileExists(nvra.getRemoteFile()); } @Test /* scp nvra tester@localhost:some/garbage/nvra */ public void scpNvraRelToRelGarbageRenameLike() throws IOException, InterruptedException { title(2); NvraTarballPathsHelper nvra = new NvraTarballPathsHelper("4t3"); nvra.createLocal(); int r = scpToCwd("some/garbage/" + nvra.getName(), nvra.getLocalFile().getParentFile(), nvra.getName()); Assert.assertTrue(r == 0); checkFileExists(nvra.getRemoteFile()); } @Test /* * scp tester@localhost:/some/garbage/nvra /abs/path/ */ public void scpAbsGarbagedNvraToAbs() throws IOException, InterruptedException { title(2); NvraTarballPathsHelper nvra = new NvraTarballPathsHelper("4f1"); nvra.createRemote(); int r2 = scpFrom(nvra.getLocalFile().getAbsolutePath(), "/some/garbage/" + nvra.getName()); Assert.assertTrue(r2 == 0); checkFileExists(nvra.getLocalFile()); } @Test /* * scp tester@localhost:some/garbage/nvra some/path/ */ public void scpRelGarbagedNvraToRel() throws IOException, InterruptedException { title(2); NvraTarballPathsHelper nvra = new NvraTarballPathsHelper("4f2"); nvra.createRemote(); int r2 = scpFromCwd(nvra.getName(), sources, "some/garbage/" + nvra.getName()); Assert.assertTrue(r2 == 0); checkFileExists(nvra.getLocalFile()); } @Test /* scp /some/path/nvra2 tester@localhost:some/garbage/nvra1 */ public void scpNvraAbsToAbsGarbageRenameLikeAnotherNvraRel() throws IOException, InterruptedException { title(2); NvraTarballPathsHelper nvraSource = new NvraTarballPathsHelper("5t1x1"); NvraTarballPathsHelper nvraTarget = new NvraTarballPathsHelper("5t1x2"); nvraSource.createLocal(); checkFileNotExists(nvraTarget.getLocalFile()); int r = scpTo("some/garbage/" + nvraTarget.getName(), nvraSource.getLocalFile().getAbsolutePath()); Assert.assertTrue(r == 0); checkFileExists(nvraTarget.getRemoteFile()); checkFileNotExists(nvraSource.getRemoteFile()); } @Test /* scp /some/path/nvra2 tester@localhost:/some/garbage/nvra1 */ public void scpNvraAbsToAbsGarbageRenameLikeAnotherNvraAbs() throws IOException, InterruptedException { title(2); NvraTarballPathsHelper nvraSource = new NvraTarballPathsHelper("5t2x1"); NvraTarballPathsHelper nvraTarget = new NvraTarballPathsHelper("5t2x2"); nvraSource.createLocal(); checkFileNotExists(nvraTarget.getLocalFile()); int r = scpTo("/some/garbage/" + nvraTarget.getName(), nvraSource.getLocalFile().getAbsolutePath()); Assert.assertTrue(r == 0); checkFileExists(nvraTarget.getRemoteFile()); checkFileNotExists(nvraSource.getRemoteFile()); } @Test /* * scp tester@localhost:some/garbage/nvra1 /some/path/nvra2 */ public void scpNvrFromAbsGarbageRenameLikeAnotherNvraAbs() throws IOException, InterruptedException { title(2); NvraTarballPathsHelper nvraSource = new NvraTarballPathsHelper("5t2x1"); NvraTarballPathsHelper nvraTarget = new NvraTarballPathsHelper("5t2x2"); nvraSource.createRemote(); checkFileNotExists(nvraTarget.getRemoteFile()); int r = scpFrom(nvraTarget.getLocalFile().getAbsolutePath(), "/some/garbage/" + nvraSource.getName()); Assert.assertTrue(r == 0); checkFileExists(nvraTarget.getLocalFile()); checkFileNotExists(nvraSource.getLocalFile()); } @Test /* * scp some/path/nonNvra tester@localhost:some/garbage/nvra */ public void scpSomeFileToGarbagedNvra() throws IOException, InterruptedException { title(2); NvraTarballPathsHelper nvra = new NvraTarballPathsHelper("5t3"); nvra.createLocal(); File renamed = new File(nvra.getLocalFile().getParentFile(), "renamed"); nvra.getLocalFile().renameTo(renamed); checkFileNotExists(nvra.getLocalFile()); checkFileExists(renamed); nvra.getLocalFile().renameTo(renamed); int r = scpTo("some/garbage/" + nvra.getName(), renamed.getAbsolutePath()); Assert.assertTrue(r == 0); checkFileExists(nvra.getRemoteFile()); } @Test /* * scp tester@localhost:some/garbage/nvra /some/path/nonNvra */ public void scpSomeFileFromGarbagedNvra() throws IOException, InterruptedException { title(2); NvraTarballPathsHelper nvra = new NvraTarballPathsHelper("5f3"); nvra.createRemote(); File nwFile = new File(nvra.getLocalFile().getParent(), "renamed"); int r = scpFrom(nwFile.getAbsolutePath(), "some/garbage/" + nvra.getName()); Assert.assertTrue(r == 0); checkFileNotExists(nvra.getLocalFile()); checkFileExists(nwFile); } @Test /* * scp some/path/nvra tester@localhost:some/garbage/NonNvra */ public void scpNvraToMoreGarbaged() throws IOException, InterruptedException { title(2); NvraTarballPathsHelper nvra = new NvraTarballPathsHelper("6t2"); nvra.createLocal(); int r2 = scpTo("/some/garbage/someFile", nvra.getLocalFile().getAbsolutePath()); Assert.assertTrue(r2 == 0); checkFileExists(nvra.getRemoteFile()); } @Test /* * scp tester@localhost:some/garbage/nonNvra some/path/nvra */ public void scpNonsenseToNvra() throws IOException, InterruptedException { //inccorect case title(2); NvraTarballPathsHelper nvra = new NvraTarballPathsHelper("6f1"); nvra.createRemote(); int r = scpFrom(nvra.getLocalFile().getAbsolutePath(), "some/garbage/notExisting"); Assert.assertTrue(r != 0); checkFileNotExists(nvra.getLocalFile()); } /* DATA */ private class NvraDataPathsHelper extends NvraTarballPathsHelper { private final String localName; private final String remoteName; public NvraDataPathsHelper(String id, String name) { this(id, name, name); } public NvraDataPathsHelper(String id, String localName, String remoteName) { super(id); this.localName = localName; this.remoteName = remoteName; } @Override public String getRemoteName() { return remoteName; } @Override public String getLocalName() { return localName; } @Override public String getStub() { //no arch! return super.getNVRstub() + "/data"; } } // scp /some/path/logname tester@localhost:nvra/data @Test public void scpDataToRelativeNvraDataNoSlash() throws IOException, InterruptedException { title(2); NvraDataPathsHelper nvraDataFile = new NvraDataPathsHelper("data1To", "dataFile"); nvraDataFile.createLocal(); int r2 = scpTo(nvraDataFile.getName() + "/data", nvraDataFile.getLocalFile().getAbsolutePath()); Assert.assertTrue(r2 == 0); checkFileExists(nvraDataFile.getRemoteFile()); } // scp /some/path/logname tester@localhost:nvra/data/ @Test public void scpDataToRelativeNvraDataSlash() throws IOException, InterruptedException { title(2); NvraDataPathsHelper nvraDataFile = new NvraDataPathsHelper("data2To", "dataFile"); nvraDataFile.createLocal(); int r2 = scpTo(nvraDataFile.getName() + "/data/", nvraDataFile.getLocalFile().getAbsolutePath()); Assert.assertTrue(r2 == 0); checkFileExists(nvraDataFile.getRemoteFile()); } // scp /some/path/logname tester@localhost:some/garbage/nvra/data @Test public void scpDataToRelGarbageNvraDataNoSlash() throws IOException, InterruptedException { title(2); NvraDataPathsHelper nvraDataFile = new NvraDataPathsHelper("data3To", "dataFile"); nvraDataFile.createLocal(); int r2 = scpTo("some/garbage/" + nvraDataFile.getName() + "/data", nvraDataFile.getLocalFile().getAbsolutePath()); Assert.assertTrue(r2 == 0); checkFileExists(nvraDataFile.getRemoteFile()); } // scp /some/path/logname tester@localhost:some/garbage/nvra/data/ @Test public void scpDataToRelGarbageNvraDataSlash() throws IOException, InterruptedException { title(2); NvraDataPathsHelper nvraDataFile = new NvraDataPathsHelper("data4To", "dataFile"); nvraDataFile.createLocal(); int r2 = scpTo("some/garbage/" + nvraDataFile.getName() + "/data/", nvraDataFile.getLocalFile().getAbsolutePath()); Assert.assertTrue(r2 == 0); checkFileExists(nvraDataFile.getRemoteFile()); } // scp /some/path/logname tester@localhost:/some/garbage/nvra/data @Test public void scpDataToAbsGarbageNvraDataNoSlash() throws IOException, InterruptedException { title(2); NvraDataPathsHelper nvraDataFile = new NvraDataPathsHelper("data5To", "dataFile"); nvraDataFile.createLocal(); int r2 = scpTo("/some/garbage/" + nvraDataFile.getName() + "/data", nvraDataFile.getLocalFile().getAbsolutePath()); Assert.assertTrue(r2 == 0); checkFileExists(nvraDataFile.getRemoteFile()); } // scp /some/path/logname tester@localhost:nvra/data/renamedLog @Test public void scpDataToRelNvraDataRenamed() throws IOException, InterruptedException { title(2); NvraDataPathsHelper nvraDataFile = new NvraDataPathsHelper("data6To", "dataFile", "newName"); nvraDataFile.createLocal(); int r2 = scpTo(nvraDataFile.getName() + "/data/newName", nvraDataFile.getLocalFile().getAbsolutePath()); Assert.assertTrue(r2 == 0); checkFileExists(nvraDataFile.getRemoteFile()); } // scp /some/path/logname tester@localhost:some/garbage/nvra/data/renamedLog @Test public void scpDataToRelGarbageNvraDataRenamed() throws IOException, InterruptedException { title(2); NvraDataPathsHelper nvraDataFile = new NvraDataPathsHelper("data7To", "dataFile", "newName"); nvraDataFile.createLocal(); int r2 = scpTo("some/garabge/" + nvraDataFile.getName() + "/data/newName", nvraDataFile.getLocalFile().getAbsolutePath()); Assert.assertTrue(r2 == 0); checkFileExists(nvraDataFile.getRemoteFile()); } // scp /some/path/logname tester@localhost:/some/garbage/nvra/data/renamedLog @Test public void scpDataToAbsGarbageNvraDataRenamed() throws IOException, InterruptedException { title(2); NvraDataPathsHelper nvraDataFile = new NvraDataPathsHelper("data8To", "dataFile", "newName"); nvraDataFile.createLocal(); int r2 = scpTo("/some/garabge/" + nvraDataFile.getName() + "/data/newName", nvraDataFile.getLocalFile().getAbsolutePath()); Assert.assertTrue(r2 == 0); checkFileExists(nvraDataFile.getRemoteFile()); } // scp /some/path/logname tester@localhost:data @Test public void scpDataToRelDataWrong() throws IOException, InterruptedException { title(2); NvraDataPathsHelper nvraDataFile = new NvraDataPathsHelper("data9To", "dataFile"); nvraDataFile.createLocal(); int r2 = scpTo("data", nvraDataFile.getLocalFile().getAbsolutePath()); Assert.assertFalse(r2 == 0); checkFileNotExists(nvraDataFile.getRemoteFile()); } // scp /some/path/logname tester@localhost:/ @Test public void scpDataToNothing() throws IOException, InterruptedException { title(2); NvraDataPathsHelper nvraDataFile = new NvraDataPathsHelper("data10To", "dataFile", "newName"); nvraDataFile.createLocal(); int r2 = scpTo("/", nvraDataFile.getLocalFile().getAbsolutePath()); Assert.assertFalse(r2 == 0); checkFileNotExists(nvraDataFile.getRemoteFile()); } // -r uploads // // scp tester@localhost:nvra/data . // scp tester@localhost:nvra/data/ /some/path/ // scp tester@localhost:nvra/data . // scp tester@localhost:nvra/data/ /some/path/ // // scp tester@localhost:nvra/data/name . // scp tester@localhost:nvra/data/name /some/path/ // scp tester@localhost:nvra/data/name . // scp tester@localhost:nvra/data/name /some/path/ // // scp tester@localhost:nvra/data/name rename // scp tester@localhost:nvra/data/name /some/path/rename // scp tester@localhost:nvra/data/name rename // scp tester@localhost:nvra/data/name /some/path/rename // // -r may need logs implementation // scp -r tester@localhost:nvra/data . // scp -r tester@localhost:nvra/data/ /some/path/ // scp -r tester@localhost:nvra/data . // scp -r tester@localhost:nvra/data/ /some/path/ // scp -r tester@localhost:nvra/data/name . // scp -r tester@localhost:nvra/data/name /some/path/ // scp -r tester@localhost:nvra/data/name . // scp -r tester@localhost:nvra/data/name /some/path/ // scp -r tester@localhost:nvra/data/name rename // scp -r tester@localhost:nvra/data/name /some/path/rename // scp -r tester@localhost:nvra/data/name rename // scp -r tester@localhost:nvra/data/name /some/path/rename //logs //data/logs //genereic/path // -r version }
Added tests for multiple nvra upload
fake-koji/src/test/java/org/fakekoji/xmlrpc/server/core/TestSshApi.java
Added tests for multiple nvra upload
<ide><path>ake-koji/src/test/java/org/fakekoji/xmlrpc/server/core/TestSshApi.java <ide> checkFileNotExists(nvra.getLocalFile()); <ide> } <ide> <add> @Test <add> /* <add> * scp some/path/nvra1 some/path/nvra1 tester@localhost: <add> */ <add> public void scpMultipleFilesToRelNothing() throws IOException, InterruptedException { <add> title(2); <add> NvraTarballPathsHelper nvra1 = new NvraTarballPathsHelper("7t3"); <add> NvraTarballPathsHelper nvra2 = new NvraTarballPathsHelper("8t3"); <add> nvra1.createLocal(); <add> nvra2.createLocal(); <add> int r = scpTo("", nvra1.getLocalFile().getAbsolutePath(), nvra2.getLocalFile().getAbsolutePath()); <add> Assert.assertTrue(r == 0); <add> checkFileExists(nvra1.getRemoteFile()); <add> checkFileExists(nvra2.getRemoteFile()); <add> } <add> <add> @Test <add> /* <add> * scp some/path/nvra1 some/path/nvra1 tester@localhost: <add> */ <add> public void scpMultipleFilesToAbsGarbage() throws IOException, InterruptedException { <add> title(2); <add> NvraTarballPathsHelper nvra1 = new NvraTarballPathsHelper("7t4"); <add> NvraTarballPathsHelper nvra2 = new NvraTarballPathsHelper("8t4"); <add> nvra1.createLocal(); <add> nvra2.createLocal(); <add> int r = scpTo("/some/path/", nvra1.getLocalFile().getAbsolutePath(), nvra2.getLocalFile().getAbsolutePath()); <add> Assert.assertTrue(r == 0); <add> checkFileExists(nvra1.getRemoteFile()); <add> checkFileExists(nvra2.getRemoteFile()); <add> } <add> <ide> /* <ide> DATA <ide> */ <ide> Assert.assertTrue(r2 == 0); <ide> checkFileExists(nvraDataFile.getRemoteFile()); <ide> } <add> <ide> // scp /some/path/logname tester@localhost:data <ide> @Test <ide> public void scpDataToRelDataWrong() throws IOException, InterruptedException { <ide> Assert.assertFalse(r2 == 0); <ide> checkFileNotExists(nvraDataFile.getRemoteFile()); <ide> } <add> <ide> // scp /some/path/logname tester@localhost:/ <ide> @Test <ide> public void scpDataToNothing() throws IOException, InterruptedException {
JavaScript
mit
3612b18e69be1c9fbe03ad07731b79da8d4f3e0f
0
jacobwindsor/pathway-presenter,jacobwindsor/pathway-presenter
import { Pvjs } from '@wikipathways/pvjs'; import React from 'react'; import './index.css'; import PropTypes from 'prop-types'; const Diagram = props => { const onPvjsReady = ({ entities, manipulator }) => { const { onReady } = props; if (onReady) onReady({ entities, manipulator }); }; const { wpId, version, showPanZoomControls, isHidden, slide, detailPanelEnabled, onEntityClick, panZoomLocked, onPanZoomChanged } = props; const getEntityIds = entities => entities.map(singleEntity => singleEntity.entityId); const highlightedEntities = targets .filter(singleTarget => singleTarget.highlighted) .map(singleTarget => Object.assign( {}, { entityId: singleTarget.entityId, color: singleTarget.highlightedColor } ) ); const { panCoordinates, zoomLevel, targets } = slide; const hiddenEntities = getEntityIds( targets.filter(singleTarget => singleTarget.hidden) ); return ( <div className={`diagram-wrapper ${isHidden ? 'isHidden' : ''}`}> <Pvjs wpId={wpId} version={version} showPanZoomControls={showPanZoomControls} panZoomLockd={panZoomLocked} detailPanelEnabled={detailPanelEnabled} onEntityClick={onEntityClick} highlightedEntities={highlightedEntities} panCoordinates={panCoordinates} onPanZoomChanged={onPanZoomChanged} zoomLevel={zoomLevel} hiddenEntities={hiddenEntities} onReady={onPvjsReady} /> </div> ); }; Diagram.propTypes = { wpId: PropTypes.string.isRequired, version: PropTypes.number.isRequired, showPanZoomControls: PropTypes.bool.isRequired, onReady: PropTypes.func, slide: PropTypes.shape({ targets: PropTypes.array.isRequired }).isRequired, isHidden: PropTypes.bool, detailPanelEnabled: PropTypes.bool, onEntityClick: PropTypes.func, panZoomLocked: PropTypes.bool, onPanZoomChanged: PropTypes.func }; Diagram.defaultProps = { hidden: false, detailPanelEnabled: true, panZoomLocked: false }; export default Diagram;
src/components/Diagram/index.js
import { Pvjs } from '@wikipathways/pvjs'; import React from 'react'; import './index.css'; import PropTypes from 'prop-types'; const Diagram = props => { const onPvjsReady = ({ entities, manipulator }) => { const { onReady } = props; if (onReady) onReady({ entities, manipulator }); }; const { wpId, version, showPanZoomControls, isHidden, slide, detailPanelEnabled, onEntityClick, panZoomLocked, onPanZoomChanged } = props; const getEntityIds = entities => entities.map(singleEntity => singleEntity.entityId); const highlightedEntities = targets .filter(singleTarget => singleTarget.highlighted) .map(singleTarget => Object.assign( {}, { entityId: singleTarget.entityId, color: singleTarget.highlightedColor } ) ); const { panCoordinates, zoomLevel, targets } = slide; const hiddenEntities = getEntityIds( targets.filter(singleTarget => singleTarget.hidden) ); return ( <div className={`diagram-wrapper ${isHidden ? 'isHidden' : ''}`}> <Pvjs wpId={wpId} version={version} showPanZoomControls={showPanZoomControls} panZoomLockd={panZoomLocked} detailPanelEnabled={detailPanelEnabled} onEntityClick={onEntityClick} highlightedEntities={highlightedEntities} panCoordinates={panCoordinates} onPanZoomChanged={onPanZoomChanged} zoomLevel={zoomLevel} hiddenEntities={hiddenEntities} onReady={onPvjsReady} /> </div> ); }; Diagram.propTypes = { wpId: PropTypes.string.isRequired, version: PropTypes.number.isRequired, showPanZoomControls: PropTypes.bool.isRequired, onReady: PropTypes.func, slide: PropTypes.shape({ targets: PropTypes.array.isRequired }).isRequired, isHidden: PropTypes.bool, detailPanelEnabled: PropTypes.bool, onEntityClick: PropTypes.func }; Diagram.defaultProps = { hidden: false, detailPanelEnabled: true }; export default Diagram;
Add propTypes to Diagram
src/components/Diagram/index.js
Add propTypes to Diagram
<ide><path>rc/components/Diagram/index.js <ide> }).isRequired, <ide> isHidden: PropTypes.bool, <ide> detailPanelEnabled: PropTypes.bool, <del> onEntityClick: PropTypes.func <add> onEntityClick: PropTypes.func, <add> panZoomLocked: PropTypes.bool, <add> onPanZoomChanged: PropTypes.func <ide> }; <ide> <ide> Diagram.defaultProps = { <ide> hidden: false, <del> detailPanelEnabled: true <add> detailPanelEnabled: true, <add> panZoomLocked: false <ide> }; <ide> <ide> export default Diagram;
Java
apache-2.0
ba9d63794664b9d6f3bb3b649229736dc3e607d5
0
michalkurka/h2o-3,h2oai/h2o-3,michalkurka/h2o-3,h2oai/h2o-3,michalkurka/h2o-3,michalkurka/h2o-3,michalkurka/h2o-3,h2oai/h2o-3,h2oai/h2o-3,h2oai/h2o-3,h2oai/h2o-3,michalkurka/h2o-3,h2oai/h2o-3,michalkurka/h2o-3,h2oai/h2o-3
package hex.glm; import hex.*; import hex.DataInfo.TransformType; import hex.genmodel.algos.glm.GlmMojoModel; import hex.glm.GLMModel.GLMParameters.MissingValuesHandling; import hex.glm.GLMModel.GLMParameters; import hex.glm.GLMModel.GLMParameters.Family; import hex.glm.GLMModel.GLMParameters.Link; import hex.glm.GLMModel.GLMParameters.Solver; import hex.glm.GLMModel.GLMWeightsFun; import hex.glm.GLMTask.*; import org.junit.Assert; import org.junit.BeforeClass; import org.junit.Ignore; import org.junit.Test; import water.*; import water.H2O.H2OCountedCompleter; import water.fvec.*; import water.parser.BufferedString; import water.parser.ParseDataset; import water.util.ArrayUtils; import java.util.Arrays; import java.util.HashMap; import java.util.Random; import java.util.concurrent.ExecutionException; import static hex.genmodel.utils.ArrayUtils.flat; import static org.junit.Assert.*; public class GLMTest extends TestUtil { @BeforeClass public static void setup() { stall_till_cloudsize(1); } public static void testScoring(GLMModel m, Frame fr) { Scope.enter(); // try scoring without response Frame fr2 = new Frame(fr); fr2.remove(m._output.responseName()); // Frame preds0 = Scope.track(m.score(fr2)); // fr2.add(m._output.responseName(),fr.vec(m._output.responseName())); // standard predictions Frame preds = Scope.track(m.score(fr2)); m.adaptTestForTrain(fr2,true,false); fr2.remove(fr2.numCols()-1); // remove response int p = m._output._dinfo._cats + m._output._dinfo._nums; int p2 = fr2.numCols() - (m._output._dinfo._weights?1:0)- (m._output._dinfo._offset?1:0); assert p == p2: p + " != " + p2; fr2.add(preds.names(),preds.vecs()); // test score0 new TestScore0(m,m._output._dinfo._weights,m._output._dinfo._offset).doAll(fr2); // test pojo if((!m._output._dinfo._weights && !m._output._dinfo._offset)) Assert.assertTrue(m.testJavaScoring(fr,preds,1e-15)); Scope.exit(); } // class to test score0 since score0 is now not being called by the standard bulk scoring public static class TestScore0 extends MRTask { final GLMModel _m; final boolean _weights; final boolean _offset; public TestScore0(GLMModel m, boolean w, boolean o) {_m = m; _weights = w; _offset = o;} private void checkScore(long rid, double [] predictions, double [] outputs){ int start = 0; if(_m._parms._family == Family.binomial && Math.abs(predictions[2] - _m.defaultThreshold()) < 1e-10) start = 1; if(_m._parms._family == Family.multinomial) { double [] maxs = new double[2]; for(int j = 1; j < predictions.length; ++j) { if(predictions[j] > maxs[0]) { if(predictions[j] > maxs[1]) { maxs[0] = maxs[1]; maxs[1] = predictions[j]; } else maxs[0] = predictions[j]; } } if((maxs[1] - maxs[0]) < 1e-10) start = 1; } for (int j = start; j < predictions.length; ++j) assertEquals("mismatch at row " + (rid) + ", p = " + j + ": " + outputs[j] + " != " + predictions[j] + ", predictions = " + Arrays.toString(predictions) + ", output = " + Arrays.toString(outputs), outputs[j], predictions[j], 1e-6); } @Override public void map(Chunk [] chks) { int nout = _m._parms._family == Family.multinomial ? _m._output.nclasses() + 1 : _m._parms._family == Family.binomial ? 3 : 1; Chunk[] outputChks = Arrays.copyOfRange(chks, chks.length - nout, chks.length); chks = Arrays.copyOf(chks, chks.length - nout); Chunk off = new C0DChunk(0, chks[0]._len); double[] tmp = new double[_m._output._dinfo._cats + _m._output._dinfo._nums]; double[] predictions = new double[nout]; double[] outputs = new double[nout]; if (_offset) { off = chks[chks.length - 1]; chks = Arrays.copyOf(chks, chks.length - 1); } if (_weights) { chks = Arrays.copyOf(chks, chks.length - 1); } for (int i = 0; i < chks[0]._len; ++i) { if (_weights || _offset) _m.score0(chks, off.atd(i), i, tmp, predictions); else _m.score0(chks, i, tmp, predictions); for (int j = 0; j < predictions.length; ++j) outputs[j] = outputChks[j].atd(i); checkScore(i + chks[0].start(), predictions, outputs); } } } @Test public void testStandardizedCoeff() { // test for multinomial testCoeffs(Family.multinomial, "smalldata/glm_test/multinomial_10_classes_10_cols_10000_Rows_train.csv", "C11"); // test for binomial testCoeffs(Family.binomial, "smalldata/glm_test/binomial_20_cols_10KRows.csv", "C21"); // test for Gaussian testCoeffs(Family.gaussian, "smalldata/glm_test/gaussian_20cols_10000Rows.csv", "C21"); } public void testCoeffs(Family family, String fileName, String responseColumn) { try { Scope.enter(); Frame train = parse_test_file(fileName); // set cat columns int numCols = train.numCols(); int enumCols = (numCols-1)/2; for (int cindex=0; cindex<enumCols; cindex++) { train.replace(cindex, train.vec(cindex).toCategoricalVec()).remove(); } int response_index = numCols-1; if (family.equals(Family.binomial) || (family.equals(Family.multinomial))) { train.replace((response_index), train.vec(response_index).toCategoricalVec()).remove(); } DKV.put(train); Scope.track(train); GLMParameters params = new GLMParameters(family); params._standardize=true; params._response_column = responseColumn; params._train = train._key; GLMModel glm = new GLM(params).trainModel().get(); Scope.track_generic(glm); // standardize numerical columns of train int numStart = enumCols; // start of numerical columns int[] numCols2Transform = new int[enumCols]; double[] colMeans = new double[enumCols]; double[] oneOSigma = new double[enumCols]; int countIndex = 0; HashMap<String, Double> cMeans = new HashMap<>(); HashMap<String, Double> cSigmas = new HashMap<>(); String[] cnames = train.names(); for (int cindex = numStart; cindex < response_index; cindex++) { numCols2Transform[countIndex]=cindex; colMeans[countIndex] = train.vec(cindex).mean(); oneOSigma[countIndex] = 1.0/train.vec(cindex).sigma(); cMeans.put(cnames[cindex], colMeans[countIndex]); cSigmas.put(cnames[cindex], train.vec(cindex).sigma()); countIndex++; } params._standardize = false; // build a model on non-standardized columns with no standardization. GLMModel glmF = new GLM(params).trainModel().get(); Scope.track_generic(glmF); HashMap<String, Double> coeffSF = glmF.coefficients(true); HashMap<String, Double> coeffF = glmF.coefficients(); if (family.equals(Family.multinomial)) { double[] interPClass = new double[glmF._output._nclasses]; for (String key : coeffSF.keySet()) { double temp1 = coeffSF.get(key); double temp2 = coeffF.get(key); if (Math.abs(temp1 - temp2) > 1e-6) { // coefficient same for categoricals, different for numericals String[] coNames = key.split("_"); if (!(coNames[0].equals("Intercept"))) { // skip over intercepts String colnames = coNames[0]; interPClass[Integer.valueOf(coNames[1])] += temp2 * cMeans.get(colnames); temp2 = temp2 * cSigmas.get(colnames); assert Math.abs(temp1 - temp2) < 1e-6 : "Expected coefficients for " + coNames[0] + " is " + temp1 + " but actual " + temp2; } } } // check for equality of intercepts for (int index = 0; index < glmF._output._nclasses; index++) { String interceptKey = "Intercept_" + index; double temp1 = coeffSF.get(interceptKey); double temp2 = coeffF.get(interceptKey) + interPClass[index]; assert Math.abs(temp1 - temp2) < 1e-6 : "Expected coefficients for " + interceptKey + " is " + temp1 + " but actual " + temp2; } } else { double interceptOffset = 0; for (String key:coeffF.keySet()) { double temp1 = coeffSF.get(key); double temp2 = coeffF.get(key); if (Math.abs(temp1 - temp2) > 1e-6) { if (!key.equals("Intercept")) { interceptOffset += temp2*cMeans.get(key); temp2 = temp2*cSigmas.get(key); assert Math.abs(temp1 - temp2) < 1e-6 : "Expected coefficients for " + key + " is " + temp1 + " but actual " + temp2; } } } // check intercept terms double temp1 = coeffSF.get("Intercept"); double temp2 = coeffF.get("Intercept")+interceptOffset; assert Math.abs(temp1 - temp2) < 1e-6 : "Expected coefficients for Intercept is " + temp1 + " but actual " + temp2; } new TestUtil.StandardizeColumns(numCols2Transform, colMeans, oneOSigma, train).doAll(train); DKV.put(train); Scope.track(train); params._standardize=false; params._train = train._key; GLMModel glmS = new GLM(params).trainModel().get(); Scope.track_generic(glmS); if (family.equals(Family.multinomial)) { double[][] coeff1 = glm._output.getNormBetaMultinomial(); double[][] coeff2 = glmS._output.getNormBetaMultinomial(); for (int classind = 0; classind < coeff1.length; classind++) { assert TestUtil.equalTwoArrays(coeff1[classind], coeff2[classind], 1e-6); } } else { assert TestUtil.equalTwoArrays(glm._output.getNormBeta(), glmS._output.getNormBeta(), 1e-6); } HashMap<String, Double> coeff1 = glm.coefficients(true); HashMap<String, Double> coeff2 = glmS.coefficients(true); assert TestUtil.equalTwoHashMaps(coeff1, coeff2, 1e-6); } finally { Scope.exit(); } } //------------------- simple tests on synthetic data------------------------------------ @Test public void testGaussianRegression() throws InterruptedException, ExecutionException { Key raw = Key.make("gaussian_test_data_raw"); Key parsed = Key.make("gaussian_test_data_parsed"); GLMModel model = null; Frame fr = null, res = null; for (Family family : new Family[]{Family.gaussian, Family.AUTO}) { try { // make data so that the expected coefficients is icept = col[0] = 1.0 FVecFactory.makeByteVec(raw, "x,y\n0,0\n1,0.1\n2,0.2\n3,0.3\n4,0.4\n5,0.5\n6,0.6\n7,0.7\n8,0.8\n9,0.9"); fr = ParseDataset.parse(parsed, raw); GLMParameters params = new GLMParameters(family); params._train = fr._key; // params._response = 1; params._response_column = fr._names[1]; params._lambda = new double[]{0}; // params._standardize= false; model = new GLM(params).trainModel().get(); HashMap<String, Double> coefs = model.coefficients(); assertEquals(0.0, coefs.get("Intercept"), 1e-4); assertEquals(0.1, coefs.get("x"), 1e-4); testScoring(model,fr); } finally { if (fr != null) fr.remove(); if (res != null) res.remove(); if (model != null) model.remove(); } } } /** * Test Poisson regression on simple and small synthetic dataset. * Equation is: y = exp(x+1); */ @Test public void testPoissonRegression() throws InterruptedException, ExecutionException { Key raw = Key.make("poisson_test_data_raw"); Key parsed = Key.make("poisson_test_data_parsed"); GLMModel model = null; Frame fr = null, res = null; try { // make data so that the expected coefficients is icept = col[0] = 1.0 FVecFactory.makeByteVec(raw, "x,y\n0,2\n1,4\n2,8\n3,16\n4,32\n5,64\n6,128\n7,256"); fr = ParseDataset.parse(parsed, raw); Vec v = fr.vec(0); System.out.println(v.min() + ", " + v.max() + ", mean = " + v.mean()); GLMParameters params = new GLMParameters(Family.poisson); params._train = fr._key; // params._response = 1; params._response_column = fr._names[1]; params._lambda = new double[]{0}; params._standardize = false; model = new GLM(params).trainModel().get(); for (double c : model.beta()) assertEquals(Math.log(2), c, 1e-2); // only 1e-2 precision cause the perfect solution is too perfect -> will trigger grid search testScoring(model,fr); model.delete(); fr.delete(); // Test 2, example from http://www.biostat.umn.edu/~dipankar/bmtry711.11/lecture_13.pdf FVecFactory.makeByteVec(raw, "x,y\n1,0\n2,1\n3,2\n4,3\n5,1\n6,4\n7,9\n8,18\n9,23\n10,31\n11,20\n12,25\n13,37\n14,45\n150,7.193936e+16\n"); fr = ParseDataset.parse(parsed, raw); GLMParameters params2 = new GLMParameters(Family.poisson); params2._train = fr._key; // params2._response = 1; params2._response_column = fr._names[1]; params2._lambda = new double[]{0}; params2._standardize = true; params2._beta_epsilon = 1e-5; model = new GLM(params2).trainModel().get(); assertEquals(0.3396, model.beta()[1], 1e-1); assertEquals(0.2565, model.beta()[0], 1e-1); // test scoring testScoring(model,fr); } finally { if (fr != null) fr.delete(); if (res != null) res.delete(); if (model != null) model.delete(); } } /** * Test Gamma regression on simple and small synthetic dataset. * Equation is: y = 1/(x+1); * * @throws ExecutionException * @throws InterruptedException */ @Test public void testGammaRegression() throws InterruptedException, ExecutionException { GLMModel model = null; Frame fr = null, res = null; try { // make data so that the expected coefficients is icept = col[0] = 1.0 Key raw = Key.make("gamma_test_data_raw"); Key parsed = Key.make("gamma_test_data_parsed"); FVecFactory.makeByteVec(raw, "x,y\n0,1\n1,0.5\n2,0.3333333\n3,0.25\n4,0.2\n5,0.1666667\n6,0.1428571\n7,0.125"); fr = ParseDataset.parse(parsed, raw); // /public GLM2(String desc, Key dest, Frame src, Family family, Link link, double alpha, double lambda) { // double [] vals = new double[] {1.0,1.0}; //public GLM2(String desc, Key dest, Frame src, Family family, Link link, double alpha, double lambda) { GLMParameters params = new GLMParameters(Family.gamma); // params._response = 1; params._response_column = fr._names[1]; params._train = parsed; params._lambda = new double[]{0}; model = new GLM(params).trainModel().get(); for (double c : model.beta()) assertEquals(1.0, c, 1e-4); // test scoring testScoring(model,fr); } finally { if (fr != null) fr.delete(); if (res != null) res.delete(); if (model != null) model.delete(); } } //// //simple tweedie test // @Test public void testTweedieRegression() throws InterruptedException, ExecutionException{ // Key raw = Key.make("gaussian_test_data_raw"); // Key parsed = Key.make("gaussian_test_data_parsed"); // Key<GLMModel> modelKey = Key.make("gaussian_test"); // Frame fr = null; // GLMModel model = null; // try { // // make data so that the expected coefficients is icept = col[0] = 1.0 // FVecFactory.makeByteVec(raw, "x,y\n0,0\n1,0.1\n2,0.2\n3,0.3\n4,0.4\n5,0.5\n6,0.6\n7,0.7\n8,0.8\n9,0.9\n0,0\n1,0\n2,0\n3,0\n4,0\n5,0\n6,0\n7,0\n8,0\n9,0"); // fr = ParseDataset.parse(parsed, new Key[]{raw}); // double [] powers = new double [] {1.5,1.1,1.9}; // double [] intercepts = new double []{3.643,1.318,9.154}; // double [] xs = new double []{-0.260,-0.0284,-0.853}; // for(int i = 0; i < powers.length; ++i){ // DataInfo dinfo = new DataInfo(fr, 1, false, DataInfo.TransformType.NONE); // GLMParameters glm = new GLMParameters(Family.tweedie); // // new GLM2("GLM test of gaussian(linear) regression.",Key.make(),modelKey,dinfo,glm,new double[]{0},0).fork().get(); // model = DKV.get(modelKey).get(); // testHTML(model); // HashMap<String, Double> coefs = model.coefficients(); // assertEquals(intercepts[i],coefs.get("Intercept"),1e-3); // assertEquals(xs[i],coefs.get("x"),1e-3); // } // }finally{ // if( fr != null ) fr.delete(); // if(model != null)model.delete(); // } // } @Test public void testAllNAs() { Key raw = Key.make("gamma_test_data_raw"); Key parsed = Key.make("gamma_test_data_parsed"); FVecFactory.makeByteVec(raw, "x,y,z\n1,0,NA\n2,NA,1\nNA,3,2\n4,3,NA\n5,NA,1\nNA,6,4\n7,NA,9\n8,NA,18\nNA,9,23\n10,31,NA\nNA,11,20\n12,NA,25\nNA,13,37\n14,45,NA\n"); Frame fr = ParseDataset.parse(parsed, raw); GLM job = null; try { GLMParameters params = new GLMParameters(Family.poisson); // params._response = 1; params._response_column = fr._names[1]; params._train = parsed; params._lambda = new double[]{0}; params._missing_values_handling = MissingValuesHandling.Skip; GLM glm = new GLM( params); glm.trainModel().get(); assertFalse("should've thrown IAE", true); } catch (IllegalArgumentException e) { assertTrue(e.getMessage(), e.getMessage().contains("No rows left in the dataset")); } finally { fr.delete(); } } // Make sure all three implementations of ginfo computation in GLM get the same results @Test public void testGradientTask() { Key parsed = Key.make("cars_parsed"); Frame fr = null; DataInfo dinfo = null; try { fr = parse_test_file(parsed, "smalldata/junit/mixcat_train.csv"); GLMParameters params = new GLMParameters(Family.binomial, Family.binomial.defaultLink, new double[]{0}, new double[]{0}, 0, 0); // params._response = fr.find(params._response_column); params._train = parsed; params._lambda = new double[]{0}; params._use_all_factor_levels = true; fr.add("Useless", fr.remove("Useless")); dinfo = new DataInfo(fr, null, 1, params._use_all_factor_levels || params._lambda_search, params._standardize ? DataInfo.TransformType.STANDARDIZE : DataInfo.TransformType.NONE, DataInfo.TransformType.NONE, true, false, false, false, false, false); DKV.put(dinfo._key,dinfo); double [] beta = MemoryManager.malloc8d(dinfo.fullN()+1); Random rnd = new Random(987654321); for (int i = 0; i < beta.length; ++i) beta[i] = 1 - 2 * rnd.nextDouble(); GLMGradientTask grtSpc = new GLMBinomialGradientTask(null,dinfo, params, params._lambda[0], beta).doAll(dinfo._adaptedFrame); GLMGradientTask grtGen = new GLMGenericGradientTask(null,dinfo, params, params._lambda[0], beta).doAll(dinfo._adaptedFrame); for (int i = 0; i < beta.length; ++i) assertEquals("gradients differ", grtSpc._gradient[i], grtGen._gradient[i], 1e-4); params = new GLMParameters(Family.gaussian, Family.gaussian.defaultLink, new double[]{0}, new double[]{0}, 0, 0); params._use_all_factor_levels = false; dinfo.remove(); dinfo = new DataInfo(fr, null, 1, params._use_all_factor_levels || params._lambda_search, params._standardize ? DataInfo.TransformType.STANDARDIZE : DataInfo.TransformType.NONE, DataInfo.TransformType.NONE, true, false, false, false, false, false); DKV.put(dinfo._key,dinfo); beta = MemoryManager.malloc8d(dinfo.fullN()+1); rnd = new Random(1987654321); for (int i = 0; i < beta.length; ++i) beta[i] = 1 - 2 * rnd.nextDouble(); grtSpc = new GLMGaussianGradientTask(null,dinfo, params, params._lambda[0], beta).doAll(dinfo._adaptedFrame); grtGen = new GLMGenericGradientTask(null,dinfo, params, params._lambda[0], beta).doAll(dinfo._adaptedFrame); for (int i = 0; i < beta.length; ++i) assertEquals("gradients differ: " + Arrays.toString(grtSpc._gradient) + " != " + Arrays.toString(grtGen._gradient), grtSpc._gradient[i], grtGen._gradient[i], 1e-4); dinfo.remove(); } finally { if (fr != null) fr.delete(); if (dinfo != null) dinfo.remove(); } } @Test public void testMultinomialGradient(){ Key parsed = Key.make("covtype"); Frame fr = null; double [][] beta = new double[][]{ { 5.886754459, -0.270479620, -0.075466082, -0.157524534, -0.225843747, -0.975387326, -0.018808013, -0.597839451, 0.931896624, 1.060006010, 1.513888539, 0.588802780, 0.157815155, -2.158268564, -0.504962385, -1.218970183, -0.840958642, -0.425931637, -0.355548831, -0.845035489, -0.065364107, 0.215897656, 0.213009374, 0.006831714, 1.212368946, 0.006106444, -0.350643486, -0.268207009, -0.252099054, -1.374010836, 0.257935860, 0.397459631, 0.411530391, 0.728368253, 0.292076224, 0.170774269, -0.059574793, 0.273670163, 0.180844505, -0.186483071, 0.369186813, 0.161909512, 0.249411716, -0.094481604, 0.413354360, -0.419043967, 0.044517794, -0.252596992, -0.371926422, 0.253835004, 0.588162090, 0.123330837, 2.856812217 }, { 1.89790254, -0.29776886, 0.15613197, 0.37602123, -0.36464436, -0.30240244, -0.57284370, 0.62408956, -0.22369305, 0.33644602, 0.79886400, 0.65351945, -0.53682819, -0.58319898, -1.07762513, -0.28527470, 0.46563482, -0.76956081, -0.72513805, 0.29857876, 0.03993456, 0.15835864, -0.24797599, -0.02483503, 0.93822490, -0.12406087, -0.75837978, -0.23516944, -0.48520212, 0.73571466, 0.19652011, 0.21602846, -0.32743154, 0.49421903, -0.02262943, 0.08093216, 0.11524497, 0.21657128, 0.18072853, 0.30872666, 0.17947687, 0.20156151, 0.16812179, -0.12286908, 0.29630502, 0.09992565, -0.00603293, 0.20700058, -0.49706211, -0.14534034, -0.18819217, 0.03642680, 7.31828340 }, { -6.098728943, 0.284144173, 0.114373474, 0.328977319, 0.417830082, 0.285696150, -0.652674822, 0.319136906, -0.942440279, -1.619235397, -1.272568201, -0.079855555, 1.191263550, 0.205102353, 0.991773314, 0.930363203, 1.014021007, 0.651243292, 0.646532457, 0.914336030, 0.012171754, -0.053042102, 0.777710362, 0.527369151, -0.019496049, 0.186290583, 0.554926655, 0.476911685, 0.529207520, -0.133243060, -0.198957274, -0.561552913, -0.069239959, -0.236600870, -0.969503908, -0.848089244, 0.001498592, -0.241007311, -0.129271912, -0.259961677, -0.895676033, -0.865827509, -0.972629899, 0.307756211, -1.809423763, -0.199557594, 0.024221965, -0.024834485, 0.047044475, 0.028951561, -0.157701002, 0.007940593, -2.073329675, }, { -8.36044440, 0.10541672, -0.01628680, -0.43787017, 0.42383466, 2.45802808, 0.59818831, 0.61971728, -0.62598983, 0.20261555, -0.21909545, 0.35125447, -3.29155913, 3.74668257, 0.18126128, -0.13948924, 0.20465077, -0.39930635, 0.15704570, -0.01036891, 0.02822546, -0.02349234, -0.93922249, -0.20025910, 0.25184125, 0.06415974, 0.35271290, 0.04609060, 0.03018497, -0.10641540, 0.00354805, -0.12194129, 0.05115876, 0.23981864, -0.10007012, 0.04773226, 0.01217421, 0.02367464, 0.05552397, 0.05343606, -0.05818705, -0.30055029, -0.03898723, 0.02322906, -0.04908215, 0.04274038, 0.25045428, 0.08561191, 0.15228160, 0.67005377, 0.59311621, 0.58814959, -4.83776046 }, { -0.39251919, 0.07053038, 0.09397355, 0.19394977, -0.02030732, -0.87489691, 0.21295049, 0.31800509, -0.05347208, -1.03491602, 2.20106706, -1.20895873, 1.06158893, -3.29214054, -0.69334082, 0.62309414, -1.64753442, 0.10189669, -0.44746013, -1.04084383, -0.01997483, -0.23356180, 0.34384724, 0.37566329, -1.79316510, 0.46183758, -0.58814389, 0.12072985, 0.48349078, 1.18956325, 0.41962148, 0.18767160, -0.25252495, -1.13671540, 0.71488183, 0.27405258, -0.03527945, 0.43124949, -0.28740586, 0.35165348, 1.17594079, 1.13893507, 0.49423372, 0.30525649, 0.70809680, 0.16660330, -0.37726163, -0.14687217, -0.17079711, -1.01897715, -1.17494223, -0.72698683, 1.64022531 }, { -5.892381502, 0.295534637, -0.112763568, 0.080283203, 0.197113227, 0.525435203, 0.727252262, -1.190672917, 1.137103389, -0.648526151, -2.581362158, -0.268338673, 2.010179009, 0.902074450, 0.816138328, 0.557071470, 0.389932578, 0.009422297, 0.542270816, 0.550653667, 0.005211720, -0.071954379, 0.320008238, 0.155814784, -0.264213966, 0.320538295, 0.569730803, 0.444518874, 0.247279544, -0.319484330, -0.372129988, 0.340944707, -0.158424299, -0.479426774, 0.026966661, 0.273389077, -0.004744599, -0.339321329, -0.119323949, -0.210123558, -1.218998166, -0.740525896, 0.134778587, 0.252701229, 0.527468284, 0.214164427, -0.080104361, -0.021448994, 0.004509104, -0.189729053, -0.335041198, -0.080698796, -1.192518082 }, { 12.9594170391, -0.1873774300, -0.1599625360, -0.3838368119, -0.4279825390, -1.1164727575, -0.2940645257, -0.0924364781, -0.2234047720, 1.7036099945, -0.4407937881, -0.0364237384, -0.5924593214, 1.1797487023, 0.2867554171, -0.4667946900, 0.4142538835, 0.8322365174, 0.1822980332, 0.1326797653, -0.0002045542, 0.0077943238, -0.4673767424, -0.8405848140, -0.3255599769, -0.9148717663, 0.2197967986, -0.5848745645, -0.5528616430, 0.0078757154, -0.3065382365, -0.4586101971, 0.3449315968, 0.3903371200, 0.0582787537, 0.0012089013, -0.0293189213, -0.3648369414, 0.1189047254, -0.0572478953, 0.4482567793, 0.4044976082, -0.0349286763, -0.6715923088, -0.0867185553, 0.0951677966, 0.1442048837, 0.1531401571, 0.8359504674, 0.4012062075, 0.6745982951, 0.0518378060, -3.7117127004 } }; double [] exp_grad = new double[]{ -8.955455e-05, 6.429112e-04, 4.384381e-04, 1.363695e-03, 4.714468e-04, -2.264769e-03, 4.412849e-04, 1.461760e-03, -2.957754e-05, -2.244325e-03, -2.744438e-03, 9.109376e-04, 1.920764e-03, 7.562221e-04, 1.840414e-04, 2.455081e-04, 3.077885e-04, 2.833261e-04, 1.248686e-04, 2.509248e-04, 9.681260e-06, -1.097335e-04, 1.005934e-03, 5.623159e-04, -2.568397e-03, 1.113900e-03, 1.263858e-04, 9.075801e-05, 8.056571e-05, 1.848318e-04, -1.291357e-04, -3.710570e-04, 5.693621e-05, 1.328082e-04, 3.244018e-04, 4.130594e-04, 9.681066e-06, 5.215260e-04, 4.054695e-04, 2.904901e-05, -3.074865e-03, -1.247025e-04, 1.044981e-03, 8.612937e-04, 1.376526e-03, 4.543256e-05, -4.596319e-06, 3.062111e-05, 5.649646e-05, 5.392599e-04, 9.681357e-04, 2.298219e-04, -1.369109e-03, -6.884926e-04, -9.921529e-04, -5.369346e-04, -1.732447e-03, 5.677645e-04, 1.655432e-03, -4.786890e-04, -8.688757e-04, 2.922016e-04, 3.601210e-03, 4.050781e-03, -6.409806e-04, -2.788663e-03, -1.426483e-03, -1.946904e-04, -8.279536e-04, -3.148338e-04, 2.263577e-06, -1.320917e-04, 3.635088e-04, -1.024655e-05, 1.079612e-04, -1.607591e-03, -1.801967e-04, 2.548311e-03, -1.007139e-03, -1.336990e-04, 2.538803e-04, -4.851292e-04, -9.168206e-04, 1.027708e-04, 1.061545e-03, -4.098038e-05, 1.070448e-04, 3.220238e-04, -7.011285e-04, -1.024153e-05, -7.967380e-04, -2.708138e-04, -2.698165e-04, 3.088978e-03, 4.260939e-04, -5.868815e-04, -1.562233e-03, -1.007565e-03, -2.034456e-04, -6.198011e-04, -3.277194e-05, -5.976557e-05, -1.143198e-03, -1.025416e-03, 3.671158e-04, 1.448332e-03, 1.940231e-03, -6.130695e-04, -2.086460e-03, -2.969848e-04, 1.455597e-04, 1.745515e-03, 2.123991e-03, 9.036201e-04, -5.270206e-04, 1.053891e-03, 1.358911e-03, 2.528711e-04, 1.326987e-04, -1.825879e-03, -6.085616e-04, -1.347628e-04, 3.499544e-04, 3.616313e-04, -7.008672e-04, -1.211077e-03, 1.117824e-05, 3.535679e-05, -2.668903e-03, -2.399884e-04, 3.979678e-04, 2.519517e-04, 1.113206e-04, 6.029871e-04, 3.512828e-04, 2.134159e-04, 7.590052e-05, 1.729959e-04, 4.472972e-05, 2.094373e-04, 3.136961e-04, 1.835530e-04, 1.117824e-05, 8.225263e-05, 4.330828e-05, 3.354142e-05, 7.452883e-04, 4.631413e-04, 2.054077e-04, -5.520636e-05, 2.818063e-04, 5.246077e-05, 1.131811e-04, 3.535664e-05, 6.523360e-05, 3.072416e-04, 2.913399e-04, 2.422760e-04, -1.580841e-03, -1.117356e-04, 2.573351e-04, 8.117137e-04, 1.168873e-04, -4.216143e-04, -5.847717e-05, 3.501109e-04, 2.344622e-04, -1.330097e-04, -5.948309e-04, -2.349808e-04, -4.495448e-05, -1.916493e-04, 5.017336e-04, -8.440468e-05, 4.767465e-04, 2.485018e-04, 2.060573e-04, -1.527142e-04, -9.268231e-06, -1.985972e-06, -6.285478e-06, -2.214673e-05, 5.822250e-04, -7.069316e-05, -4.387924e-05, -2.774128e-04, -5.455282e-04, 3.186328e-04, -3.793242e-05, -1.349306e-05, -3.070112e-05, -7.951882e-06, -3.723186e-05, -5.571437e-05, -3.260780e-05, -1.987225e-06, -1.462245e-05, -7.699184e-06, -5.962867e-06, -1.316053e-04, -8.108570e-05, -3.651228e-05, -5.312255e-05, -5.009791e-05, -9.325808e-06, -2.012086e-05, -6.285571e-06, -1.159698e-05, -5.462022e-05, -5.179310e-05, -4.307092e-05, 2.810360e-04, 3.869942e-04, -3.450936e-05, -7.805675e-05, 6.405561e-04, -2.284402e-04, -1.866295e-04, -4.858359e-04, 3.496890e-04, 7.352780e-04, 5.767877e-04, -8.477014e-04, -5.512698e-05, 1.091158e-03, -1.900036e-04, -4.632766e-05, 1.086153e-05, -7.743051e-05, -7.545391e-04, -3.143243e-05, -6.316374e-05, -2.435782e-06, -7.707894e-06, 4.451785e-04, 2.043479e-04, -8.673378e-05, -3.314975e-05, -3.181369e-05, -5.422704e-04, -9.020739e-05, 6.747588e-04, 5.997742e-06, -9.729086e-04, -9.751490e-06, -4.565744e-05, -4.181943e-04, 7.522183e-04, -2.436958e-06, 2.531532e-04, -9.441600e-06, 2.317743e-04, 4.254207e-04, -3.224488e-04, 3.979052e-04, 2.066697e-04, 2.486194e-05, 1.189306e-04, -2.465884e-05, -7.708071e-06, -1.422152e-05, -6.697064e-05, -6.351172e-05, -5.281060e-05, 3.446379e-04, -1.212986e-03, 9.206612e-04, 6.469824e-04, -6.605882e-04, -1.646537e-05, -6.854543e-04, -2.079925e-03, -1.031449e-03, 3.926585e-04, -1.556234e-03, -1.129748e-03, -2.113480e-04, -4.922559e-04, 1.938461e-03, 6.900824e-04, 1.497533e-04, -6.140808e-04, -3.365137e-04, 8.516225e-04, 5.874586e-04, -9.342693e-06, -2.955083e-05, 2.692614e-03, -9.928211e-04, -3.326157e-04, -3.572773e-04, 1.641113e-04, 7.442831e-05, -2.543959e-04, -1.783712e-04, -6.343638e-05, 9.077554e-05, -3.738480e-05, -1.750387e-04, -6.568480e-04, -2.035799e-04, -9.342694e-06, -6.874421e-05, -3.619677e-05, -2.803369e-05, -6.228932e-04, -3.870861e-04, -1.103792e-03, 9.585360e-04, -7.037269e-05, 2.736606e-04, -9.459508e-05, -2.955084e-05, -5.452180e-05, -2.567899e-04, -2.434930e-04, -2.024919e-04, 1.321256e-03, -2.244563e-04, -1.811758e-04, 8.043173e-04, 5.688820e-04, -5.182511e-04, -2.056167e-04, 1.290635e-04, -1.049207e-03, -7.305304e-04, -8.364983e-04, -4.528248e-04, -2.113987e-04, 3.279472e-04, 2.459491e-04, 5.986061e-05, 7.984705e-05, 1.001005e-04, 2.377746e-04, 4.061439e-05, 8.161668e-05, 3.151497e-06, 9.959707e-06, 1.549140e-04, 6.411739e-05, 1.121613e-04, 7.559378e-05, 4.110778e-05, 6.574476e-05, 7.925128e-05, 6.011770e-05, 2.139605e-05, 4.934971e-05, -5.597385e-06, -1.913622e-04, 1.706349e-04, -4.115145e-04, 3.149101e-06, 2.317293e-05, -1.246264e-04, 9.448371e-06, -4.303234e-04, 2.608783e-05, 7.889196e-05, -3.559375e-04, -5.551586e-04, -2.777131e-04, 6.505911e-04, 1.033867e-05, 1.837583e-05, 6.750772e-04, 1.247379e-04, -5.408403e-04, -4.453114e-04, }; Vec origRes = null; for (Family family : new Family[]{Family.multinomial, Family.AUTO}) { try { fr = parse_test_file(parsed, "smalldata/covtype/covtype.20k.data"); fr.remove("C21").remove(); fr.remove("C29").remove(); GLMParameters params = new GLMParameters(family/*Family.multinomial*/); params._response_column = "C55"; // params._response = fr.find(params._response_column); params._ignored_columns = new String[]{}; params._train = parsed; params._lambda = new double[]{0}; params._alpha = new double[]{0}; origRes = fr.remove("C55"); Vec res = fr.add("C55",origRes.toCategoricalVec()); double [] means = new double [res.domain().length]; long [] bins = res.bins(); double sumInv = 1.0/ArrayUtils.sum(bins); for(int i = 0; i < bins.length; ++i) means[i] = bins[i]*sumInv; DataInfo dinfo = new DataInfo(fr, null, 1, true, TransformType.STANDARDIZE, DataInfo.TransformType.NONE, true, false, false, false, false, false); GLMTask.GLMMultinomialGradientBaseTask gmt = new GLMTask.GLMMultinomialGradientTask(null,dinfo,0,beta,1.0/fr.numRows()).doAll(dinfo._adaptedFrame); assertEquals(0.6421113,gmt._likelihood/fr.numRows(),1e-8); System.out.println("likelihood = " + gmt._likelihood/fr.numRows()); double [] g = gmt.gradient(); for(int i = 0; i < g.length; ++i) assertEquals("Mismatch at coefficient '" + "' (" + i + ")",exp_grad[i], g[i], 1e-8); } finally { if(origRes != null)origRes.remove(); if (fr != null) fr.delete(); } } } //------------ TEST on selected files form small data and compare to R results ------------------------------------ /** * Simple test for poisson, gamma and gaussian families (no regularization, test both lsm solvers). * Basically tries to predict horse power based on other parameters of the cars in the dataset. * Compare against the results from standard R glm implementation. * * @throws ExecutionException * @throws InterruptedException */ @Test public void testCars() throws InterruptedException, ExecutionException { Scope.enter(); Key parsed = Key.make("cars_parsed"); Frame fr = null; GLMModel model = null; Frame score = null; try { fr = parse_test_file(parsed, "smalldata/junit/cars.csv"); GLMParameters params = new GLMParameters(Family.poisson, Family.poisson.defaultLink, new double[]{0}, new double[]{0},0,0); params._response_column = "power (hp)"; // params._response = fr.find(params._response_column); params._ignored_columns = new String[]{"name"}; params._train = parsed; params._lambda = new double[]{0}; params._alpha = new double[]{0}; params._missing_values_handling = MissingValuesHandling.Skip; model = new GLM( params).trainModel().get(); HashMap<String, Double> coefs = model.coefficients(); String[] cfs1 = new String[]{"Intercept", "economy (mpg)", "cylinders", "displacement (cc)", "weight (lb)", "0-60 mph (s)", "year"}; double[] vls1 = new double[]{4.9504805, -0.0095859, -0.0063046, 0.0004392, 0.0001762, -0.0469810, 0.0002891}; for (int i = 0; i < cfs1.length; ++i) assertEquals(vls1[i], coefs.get(cfs1[i]), 1e-4); // test gamma double[] vls2 = new double[]{8.992e-03, 1.818e-04, -1.125e-04, 1.505e-06, -1.284e-06, 4.510e-04, -7.254e-05}; testScoring(model,fr); model.delete(); params = new GLMParameters(Family.gamma, Family.gamma.defaultLink, new double[]{0}, new double[]{0},0,0); params._response_column = "power (hp)"; // params._response = fr.find(params._response_column); params._ignored_columns = new String[]{"name"}; params._train = parsed; params._lambda = new double[]{0}; params._beta_epsilon = 1e-5; params._missing_values_handling = MissingValuesHandling.Skip; model = new GLM( params).trainModel().get(); coefs = model.coefficients(); for (int i = 0; i < cfs1.length; ++i) assertEquals(vls2[i], coefs.get(cfs1[i]), 1e-4); testScoring(model,fr); model.delete(); // test gaussian double[] vls3 = new double[]{166.95862, -0.00531, -2.46690, 0.12635, 0.02159, -4.66995, -0.85724}; params = new GLMParameters(Family.gaussian); params._response_column = "power (hp)"; // params._response = fr.find(params._response_column); params._ignored_columns = new String[]{"name"}; params._train = parsed; params._lambda = new double[]{0}; params._missing_values_handling = MissingValuesHandling.Skip; model = new GLM( params).trainModel().get(); coefs = model.coefficients(); for (int i = 0; i < cfs1.length; ++i) assertEquals(vls3[i], coefs.get(cfs1[i]), 1e-4); // test scoring } finally { if (fr != null) fr.delete(); if (score != null) score.delete(); if (model != null) model.delete(); Scope.exit(); } } // Leask xval keys // @Test public void testXval() { // GLMModel model = null; // Frame fr = parse_test_file("smalldata/glm_test/prostate_cat_replaced.csv"); // Frame score = null; // try{ // Scope.enter(); // // R results //// Coefficients: //// (Intercept) ID AGE RACER2 RACER3 DPROS DCAPS PSA VOL GLEASON //// -8.894088 0.001588 -0.009589 0.231777 -0.459937 0.556231 0.556395 0.027854 -0.011355 1.010179 // String [] cfs1 = new String [] {"Intercept","AGE", "RACE.R2","RACE.R3", "DPROS", "DCAPS", "PSA", "VOL", "GLEASON"}; // double [] vals = new double [] {-8.14867, -0.01368, 0.32337, -0.38028, 0.55964, 0.49548, 0.02794, -0.01104, 0.97704}; // GLMParameters params = new GLMParameters(Family.binomial); // params._n_folds = 10; // params._response_column = "CAPSULE"; // params._ignored_columns = new String[]{"ID"}; // params._train = fr._key; // params._lambda = new double[]{0}; // model = new GLM(params,Key.make("prostate_model")).trainModel().get(); // HashMap<String, Double> coefs = model.coefficients(); // for(int i = 0; i < cfs1.length; ++i) // assertEquals(vals[i], coefs.get(cfs1[i]),1e-4); // GLMValidation val = model.trainVal(); //// assertEquals(512.3, val.nullDeviance(),1e-1); //// assertEquals(378.3, val.residualDeviance(),1e-1); //// assertEquals(396.3, val.AIC(),1e-1); //// score = model.score(fr); //// //// hex.ModelMetrics mm = hex.ModelMetrics.getFromDKV(model,fr); //// //// AUCData adata = mm._aucdata; //// assertEquals(val.auc(),adata.AUC(),1e-2); //// GLMValidation val2 = new GLMValidationTsk(params,model._ymu,rank(model.beta())).doAll(new Vec[]{fr.vec("CAPSULE"),score.vec("1")})._val; //// assertEquals(val.residualDeviance(),val2.residualDeviance(),1e-6); //// assertEquals(val.nullDeviance(),val2.nullDeviance(),1e-6); // } finally { // fr.delete(); // if(model != null)model.delete(); // if(score != null)score.delete(); // Scope.exit(); // } // } /** * Test bounds on prostate dataset, 2 cases : * 1) test against known result in glmnet (with elastic net regularization) with elastic net penalty * 2) test with no regularization, check the ginfo in the end. */ @Test public void testBounds() { // glmnet's result: // res2 <- glmnet(x=M,y=D$CAPSULE,lower.limits=-.5,upper.limits=.5,family='binomial') // res2$beta[,58] // AGE RACE DPROS PSA VOL GLEASON // -0.00616326 -0.50000000 0.50000000 0.03628192 -0.01249324 0.50000000 // res2$a0[100] // res2$a0[58] // s57 // -4.155864 // lambda = 0.001108, null dev = 512.2888, res dev = 379.7597 GLMModel model = null; Key parsed = Key.make("prostate_parsed"); Key modelKey = Key.make("prostate_model"); Frame fr = parse_test_file(parsed, "smalldata/logreg/prostate.csv"); Key betaConsKey = Key.make("beta_constraints"); String[] cfs1 = new String[]{"AGE", "RACE", "DPROS", "DCAPS", "PSA", "VOL", "GLEASON", "Intercept"}; double[] vals = new double[]{-0.006502588, -0.500000000, 0.500000000, 0.400000000, 0.034826559, -0.011661747, 0.500000000, -4.564024}; // [AGE, RACE, DPROS, DCAPS, PSA, VOL, GLEASON, Intercept] FVecFactory.makeByteVec(betaConsKey, "names, lower_bounds, upper_bounds\n AGE, -.5, .5\n RACE, -.5, .5\n DCAPS, -.4, .4\n DPROS, -.5, .5 \nPSA, -.5, .5\n VOL, -.5, .5\nGLEASON, -.5, .5"); Frame betaConstraints = ParseDataset.parse(Key.make("beta_constraints.hex"), betaConsKey); try { // H2O differs on intercept and race, same residual deviance though GLMParameters params = new GLMParameters(); params._standardize = true; params._family = Family.binomial; params._beta_constraints = betaConstraints._key; params._response_column = "CAPSULE"; params._ignored_columns = new String[]{"ID"}; params._train = fr._key; params._objective_epsilon = 0; params._alpha = new double[]{1}; params._lambda = new double[]{0.001607}; params._obj_reg = 1.0/380; GLM glm = new GLM( params, modelKey); model = glm.trainModel().get(); assertTrue(glm.isStopped()); // Map<String, Double> coefs = model.coefficients(); // for (int i = 0; i < cfs1.length; ++i) // assertEquals(vals[i], coefs.get(cfs1[i]), 1e-1); ModelMetricsBinomialGLM val = (ModelMetricsBinomialGLM) model._output._training_metrics; assertEquals(512.2888, val._nullDev, 1e-1); // 388.4952716196743 assertTrue(val._resDev <= 388.5); model.delete(); params._lambda = new double[]{0}; params._alpha = new double[]{0}; FVecFactory.makeByteVec(betaConsKey, "names, lower_bounds, upper_bounds\n RACE, -.5, .5\n DCAPS, -.4, .4\n DPROS, -.5, .5 \nPSA, -.5, .5\n VOL, -.5, .5"); betaConstraints = ParseDataset.parse(Key.make("beta_constraints.hex"), betaConsKey); glm = new GLM( params, modelKey); model = glm.trainModel().get(); assertTrue(glm.isStopped()); double[] beta = model.beta(); System.out.println("beta = " + Arrays.toString(beta)); fr.add("CAPSULE", fr.remove("CAPSULE")); fr.remove("ID").remove(); DKV.put(fr._key, fr); // now check the ginfo DataInfo dinfo = new DataInfo(fr, null, 1, true, TransformType.NONE, DataInfo.TransformType.NONE, true, false, false, false, false, false); GLMGradientTask lt = new GLMBinomialGradientTask(null,dinfo,params,0,beta).doAll(dinfo._adaptedFrame); double [] grad = lt._gradient; String [] names = model.dinfo().coefNames(); BufferedString tmpStr = new BufferedString(); outer: for (int i = 0; i < names.length; ++i) { for (int j = 0; j < betaConstraints.numRows(); ++j) { if (betaConstraints.vec("names").atStr(tmpStr, j).toString().equals(names[i])) { if (Math.abs(beta[i] - betaConstraints.vec("lower_bounds").at(j)) < 1e-4 || Math.abs(beta[i] - betaConstraints.vec("upper_bounds").at(j)) < 1e-4) { continue outer; } } } assertEquals(0, grad[i], 1e-2); } } finally { fr.delete(); betaConstraints.delete(); if (model != null) model.delete(); } } @Ignore // remove when PUBDEV-7693 is fixed @Test public void testInteractionPairs_airlines() { Scope.enter(); try { Frame train = Scope.track(parse_test_file("smalldata/airlines/AirlinesTrain.csv.zip")); Frame test = Scope.track(parse_test_file("smalldata/airlines/AirlinesTest.csv.zip")); GLMParameters params = new GLMParameters(); params._family = Family.binomial; params._response_column = "IsDepDelayed"; params._ignored_columns = new String[]{"IsDepDelayed_REC"}; params._train = train._key; params._interaction_pairs = new StringPair[] { new StringPair("DepTime", "UniqueCarrier"), new StringPair("DepTime", "Origin"), new StringPair("UniqueCarrier", "Origin") }; GLM glm = new GLM(params); GLMModel model = (GLMModel) Scope.track_generic(glm.trainModel().get()); Frame scored = Scope.track(model.score(test)); model.testJavaScoring(train, scored, 0); } finally { Scope.exit(); } } @Test public void testCoordinateDescent_airlines() { GLMModel model = null; Key parsed = Key.make("airlines_parsed"); Key<GLMModel> modelKey = Key.make("airlines_model"); Frame fr = parse_test_file(parsed, "smalldata/airlines/AirlinesTrain.csv.zip"); try { // H2O differs on intercept and race, same residual deviance though GLMParameters params = new GLMParameters(); params._standardize = true; params._family = Family.binomial; params._solver = Solver.COORDINATE_DESCENT_NAIVE; params._response_column = "IsDepDelayed"; params._ignored_columns = new String[]{"IsDepDelayed_REC"}; params._train = fr._key; GLM glm = new GLM( params, modelKey); model = glm.trainModel().get(); assertTrue(glm.isStopped()); System.out.println(model._output._training_metrics); } finally { fr.delete(); if (model != null) model.delete(); } } @Test public void testCoordinateDescent_airlines_CovUpdates() { GLMModel model = null; Key parsed = Key.make("airlines_parsed"); Key<GLMModel> modelKey = Key.make("airlines_model"); Frame fr = parse_test_file(parsed, "smalldata/airlines/AirlinesTrain.csv.zip"); try { // H2O differs on intercept and race, same residual deviance though GLMParameters params = new GLMParameters(); params._standardize = true; params._family = Family.binomial; params._solver = Solver.COORDINATE_DESCENT; params._response_column = "IsDepDelayed"; params._ignored_columns = new String[]{"IsDepDelayed_REC"}; params._train = fr._key; GLM glm = new GLM( params, modelKey); model = glm.trainModel().get(); assertTrue(glm.isStopped()); System.out.println(model._output._training_metrics); } finally { fr.delete(); if (model != null) model.delete(); } } @Test public void testCoordinateDescent_anomaly() { GLMModel model = null; Key parsed = Key.make("anomaly_parsed"); Key<GLMModel> modelKey = Key.make("anomaly_model"); Frame fr = parse_test_file(parsed, "smalldata/anomaly/ecg_discord_train.csv"); try { // H2O differs on intercept and race, same residual deviance though GLMParameters params = new GLMParameters(); params._standardize = true; params._family = Family.gaussian; params._solver = Solver.COORDINATE_DESCENT_NAIVE; params._response_column = "C1"; params._train = fr._key; GLM glm = new GLM( params, modelKey); model = glm.trainModel().get(); assertTrue(glm.isStopped()); System.out.println(model._output._training_metrics); } finally { fr.delete(); if (model != null) model.delete(); } } @Test public void testCoordinateDescent_anomaly_CovUpdates() { GLMModel model = null; Key parsed = Key.make("anomaly_parsed"); Key<GLMModel> modelKey = Key.make("anomaly_model"); Frame fr = parse_test_file(parsed, "smalldata/anomaly/ecg_discord_train.csv"); try { // H2O differs on intercept and race, same residual deviance though GLMParameters params = new GLMParameters(); params._standardize = true; params._family = Family.gaussian; params._solver = Solver.COORDINATE_DESCENT; params._response_column = "C1"; params._train = fr._key; GLM glm = new GLM( params, modelKey); model = glm.trainModel().get(); assertTrue(glm.isStopped()); System.out.println(model._output._training_metrics); } finally { fr.delete(); if (model != null) model.delete(); } } @Test public void testProximal() { // glmnet's result: // res2 <- glmnet(x=M,y=D$CAPSULE,lower.limits=-.5,upper.limits=.5,family='binomial') // res2$beta[,58] // AGE RACE DPROS PSA VOL GLEASON // -0.00616326 -0.50000000 0.50000000 0.03628192 -0.01249324 0.50000000 // res2$a0[100] // res2$a0[58] // s57 // -4.155864 // lambda = 0.001108, null dev = 512.2888, res dev = 379.7597 Key parsed = Key.make("prostate_parsed"); Key<GLMModel> modelKey = Key.make("prostate_model"); GLMModel model = null; Frame fr = parse_test_file(parsed, "smalldata/logreg/prostate.csv"); fr.remove("ID").remove(); DKV.put(fr._key, fr); Key betaConsKey = Key.make("beta_constraints"); FVecFactory.makeByteVec(betaConsKey, "names, beta_given, rho\n AGE, 0.1, 1\n RACE, -0.1, 1 \n DPROS, 10, 1 \n DCAPS, -10, 1 \n PSA, 0, 1\n VOL, 0, 1\nGLEASON, 0, 1\n Intercept, 0, 0 \n"); Frame betaConstraints = ParseDataset.parse(Key.make("beta_constraints.hex"), betaConsKey); try { // H2O differs on intercept and race, same residual deviance though GLMParameters params = new GLMParameters(); params._standardize = false; params._family = Family.binomial; params._beta_constraints = betaConstraints._key; params._response_column = "CAPSULE"; params._ignored_columns = new String[]{"ID"}; params._train = fr._key; params._alpha = new double[]{0}; params._lambda = new double[]{0}; params._obj_reg = 1.0/380; params._objective_epsilon = 0; GLM glm = new GLM( params, modelKey); model = glm.trainModel().get(); double[] beta_1 = model.beta(); params._solver = Solver.L_BFGS; params._max_iterations = 1000; glm = new GLM( params, modelKey); model = glm.trainModel().get(); fr.add("CAPSULE", fr.remove("CAPSULE")); // now check the ginfo DataInfo dinfo = new DataInfo(fr, null, 1, true, TransformType.NONE, DataInfo.TransformType.NONE, true, false, false, false, false, false); GLMGradientTask lt = new GLMBinomialGradientTask(null,dinfo, params, 0, beta_1).doAll(dinfo._adaptedFrame); double[] grad = lt._gradient; for (int i = 0; i < beta_1.length; ++i) assertEquals(0, grad[i] + betaConstraints.vec("rho").at(i) * (beta_1[i] - betaConstraints.vec("beta_given").at(i)), 1e-4); } finally { betaConstraints.delete(); fr.delete(); if (model != null) model.delete(); } } // // test categorical autoexpansions, run on airlines which has several categorical columns, // // once on explicitly expanded data, once on h2o autoexpanded and compare the results // @Test public void testSparseCategoricals() { // GLMModel model1 = null, model2 = null, model3 = null, model4 = null; // // Frame frMM = parse_test_file("smalldata/glm_tets/train-2.csv"); // //// Vec xy = frG.remove("xy"); // frMM.remove("").remove(); // frMM.add("IsDepDelayed", frMM.remove("IsDepDelayed")); // DKV.put(frMM._key,frMM); // Frame fr = parse_test_file("smalldata/airlines/AirlinesTrain.csv.zip"), res = null; // // Distance + Origin + Dest + UniqueCarrier // String [] ignoredCols = new String[]{"fYear", "fMonth", "fDayofMonth", "fDayOfWeek", "DepTime","ArrTime","IsDepDelayed_REC"}; // try{ // Scope.enter(); // GLMParameters params = new GLMParameters(Family.gaussian); // params._response_column = "IsDepDelayed"; // params._ignored_columns = ignoredCols; // params._train = fr._key; // params._l2pen = new double[]{1e-5}; // params._standardize = false; // model1 = new GLM(params,glmkey("airlines_cat_nostd")).trainModel().get(); // Frame score1 = model1.score(fr); // ModelMetricsRegressionGLM mm = (ModelMetricsRegressionGLM) ModelMetrics.getFromDKV(model1, fr); // Assert.assertEquals(model1.validation().residual_deviance, mm._resDev, 1e-4); // System.out.println("NDOF = " + model1.validation().nullDOF() + ", numRows = " + score1.numRows()); // Assert.assertEquals(model1.validation().residual_deviance, mm._MSE * score1.numRows(), 1e-4); // mm.remove(); // res = model1.score(fr); // // Build a POJO, validate same results // Assert.assertTrue(model1.testJavaScoring(fr, res, 1e-15)); // // params._train = frMM._key; // params._ignored_columns = new String[]{"X"}; // model2 = new GLM(params,glmkey("airlines_mm")).trainModel().get(); // params._standardize = true; // params._train = frMM._key; // params._use_all_factor_levels = true; // // test the gram // DataInfo dinfo = new DataInfo(Key.make(),frMM, null, 1, true, DataInfo.TransformType.STANDARDIZE, DataInfo.TransformType.NONE, true); // GLMIterationTask glmt = new GLMIterationTask(null,dinfo,1e-5,params,false,null,0,null, null).doAll(dinfo._adaptedFrame); // for(int i = 0; i < glmt._xy.length; ++i) { // for(int j = 0; j <= i; ++j ) { // assertEquals(frG.vec(j).at(i), glmt._gram.get(i, j), 1e-5); // } // assertEquals(xy.at(i), glmt._xy[i], 1e-5); // } // frG.delete(); // xy.remove(); // params._standardize = true; // params._family = Family.binomial; // params._link = Link.logit; // model3 = new GLM(params,glmkey("airlines_mm")).trainModel().get(); // params._train = fr._key; // params._ignored_columns = ignoredCols; // model4 = new GLM(params,glmkey("airlines_mm")).trainModel().get(); // assertEquals(model3.validation().null_deviance,model4.validation().nullDeviance(),1e-4); // assertEquals(model4.validation().residual_deviance, model3.validation().residualDeviance(), model3.validation().null_deviance * 1e-3); // HashMap<String, Double> coefs1 = model1.coefficients(); // HashMap<String, Double> coefs2 = model2.coefficients(); // GLMValidation val1 = model1.validation(); // GLMValidation val2 = model2.validation(); // // compare against each other // for(String s:coefs2.keySet()) { // String s1 = s; // if(s.startsWith("Origin")) // s1 = "Origin." + s.substring(6); // if(s.startsWith("Dest")) // s1 = "Dest." + s.substring(4); // if(s.startsWith("UniqueCarrier")) // s1 = "UniqueCarrier." + s.substring(13); // assertEquals("coeff " + s1 + " differs, " + coefs1.get(s1) + " != " + coefs2.get(s), coefs1.get(s1), coefs2.get(s),1e-4); // DKV.put(frMM._key,frMM); // update the frame in the KV after removing the vec! // } // assertEquals(val1.nullDeviance(), val2.nullDeviance(),1e-4); // assertEquals(val1.residualDeviance(), val2.residualDeviance(),1e-4); // assertEquals(val1._aic, val2._aic,1e-2); // // compare result against glmnet // assertEquals(5336.918,val1.residualDeviance(),1); // assertEquals(6051.613,val1.nullDeviance(),1); // // // // lbfgs //// params._solver = Solver.L_BFGS; //// params._train = fr._key; //// params._lambda = new double[]{.3}; //// model3 = new GLM(params,glmkey("lbfgs_cat")).trainModel().get(); //// params._train = frMM._key; //// model4 = new GLM(params,glmkey("lbfgs_mm")).trainModel().get(); //// HashMap<String, Double> coefs3 = model3.coefficients(); //// HashMap<String, Double> coefs4 = model4.coefficients(); //// // compare against each other //// for(String s:coefs4.keySet()) { //// String s1 = s; //// if(s.startsWith("Origin")) //// s1 = "Origin." + s.substring(6); //// if(s.startsWith("Dest")) //// s1 = "Dest." + s.substring(4); //// if(s.startsWith("UniqueCarrier")) //// s1 = "UniqueCarrier." + s.substring(13); //// assertEquals("coeff " + s1 + " differs, " + coefs3.get(s1) + " != " + coefs4.get(s), coefs3.get(s1), coefs4.get(s),1e-4); //// } // // } finally { // fr.delete(); // frMM.delete(); // if(res != null)res.delete(); // if(model1 != null)model1.delete(); // if(model2 != null)model2.delete(); // if(model3 != null)model3.delete(); // if(model4 != null)model4.delete(); //// if(score != null)score.delete(); // Scope.exit(); // } // } /** * Test we get correct gram on dataset which contains categoricals and sparse and dense numbers */ @Test public void testSparseGramComputation() { Random rnd = new Random(123456789l); double[] d0 = MemoryManager.malloc8d(1000); double[] d1 = MemoryManager.malloc8d(1000); double[] d2 = MemoryManager.malloc8d(1000); double[] d3 = MemoryManager.malloc8d(1000); double[] d4 = MemoryManager.malloc8d(1000); double[] d5 = MemoryManager.malloc8d(1000); double[] d6 = MemoryManager.malloc8d(1000); double[] d7 = MemoryManager.malloc8d(1000); double[] d8 = MemoryManager.malloc8d(1000); double[] d9 = MemoryManager.malloc8d(1000); long[] c1 = MemoryManager.malloc8(1000); long[] c2 = MemoryManager.malloc8(1000); String[] dom = new String[]{"a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k", "l", "m", "n", "o", "p", "q", "r", "s", "t", "u", "v", "w", "x", "y", "z"}; for (int i = 0; i < d1.length; ++i) { c1[i] = rnd.nextInt(dom.length); c2[i] = rnd.nextInt(dom.length); d0[i] = rnd.nextDouble(); d1[i] = rnd.nextDouble(); } for (int i = 0; i < 30; ++i) { d2[rnd.nextInt(d2.length)] = rnd.nextDouble(); d3[rnd.nextInt(d2.length)] = rnd.nextDouble(); d4[rnd.nextInt(d2.length)] = rnd.nextDouble(); d5[rnd.nextInt(d2.length)] = rnd.nextDouble(); d6[rnd.nextInt(d2.length)] = rnd.nextDouble(); d7[rnd.nextInt(d2.length)] = rnd.nextDouble(); d8[rnd.nextInt(d2.length)] = rnd.nextDouble(); d9[rnd.nextInt(d2.length)] = 1; } Vec.VectorGroup vg_1 = Vec.VectorGroup.VG_LEN1; Vec v01 = Vec.makeVec(c1, dom, vg_1.addVec()); Vec v02 = Vec.makeVec(c2, dom,vg_1.addVec()); Vec v03 = Vec.makeVec(d0, vg_1.addVec()); Vec v04 = Vec.makeVec(d1, vg_1.addVec()); Vec v05 = Vec.makeVec(d2, vg_1.addVec()); Vec v06 = Vec.makeVec(d3, vg_1.addVec()); Vec v07 = Vec.makeVec(d4, vg_1.addVec()); Vec v08 = Vec.makeVec(d5, vg_1.addVec()); Vec v09 = Vec.makeVec(d6, vg_1.addVec()); Vec v10 = Vec.makeVec(d7, vg_1.addVec()); Vec v11 = Vec.makeVec(d8, vg_1.addVec()); Vec v12 = Vec.makeVec(d9, vg_1.addVec()); Frame f = new Frame(Key.<Frame>make("TestData"), null, new Vec[]{v01, v02, v03, v04, v05, v05, v06, v07, v08, v09, v10, v11, v12}); DKV.put(f); DataInfo dinfo = new DataInfo(f, null, 1, true, DataInfo.TransformType.STANDARDIZE, DataInfo.TransformType.NONE, true, false, false, false, false, false); GLMParameters params = new GLMParameters(Family.gaussian); // public GLMIterationTask(Key jobKey, DataInfo dinfo, GLMWeightsFun glmw,double [] beta, double lambda) { final GLMIterationTask glmtSparse = new GLMIterationTask(null, dinfo, new GLMWeightsFun(params), null).setSparse(true).doAll(dinfo._adaptedFrame); final GLMIterationTask glmtDense = new GLMIterationTask(null, dinfo, new GLMWeightsFun(params), null).setSparse(false).doAll(dinfo._adaptedFrame); for (int i = 0; i < glmtDense._xy.length; ++i) { for (int j = 0; j <= i; ++j) { assertEquals(glmtDense._gram.get(i, j), glmtSparse._gram.get(i, j), 1e-8); } assertEquals(glmtDense._xy[i], glmtSparse._xy[i], 1e-8); } final double[] beta = MemoryManager.malloc8d(dinfo.fullN() + 1); // now do the same but weighted, use LSM solution as beta to generate meaningfull weights H2O.submitTask(new H2OCountedCompleter() { @Override public void compute2() { new GLM.GramSolver(glmtDense._gram, glmtDense._xy, true, 1e-5, 0, null, null, null, null).solve(null, beta); tryComplete(); } }).join(); final GLMIterationTask glmtSparse2 = new GLMIterationTask(null, dinfo, new GLMWeightsFun(params), beta).setSparse(true).doAll(dinfo._adaptedFrame); final GLMIterationTask glmtDense2 = new GLMIterationTask(null, dinfo, new GLMWeightsFun(params), beta).setSparse(false).doAll(dinfo._adaptedFrame); for (int i = 0; i < glmtDense2._xy.length; ++i) { for (int j = 0; j <= i; ++j) { assertEquals(glmtDense2._gram.get(i, j), glmtSparse2._gram.get(i, j), 1e-8); } assertEquals(glmtDense2._xy[i], glmtSparse2._xy[i], 1e-8); } dinfo.remove(); f.delete(); } @Test @Ignore public void testConstantColumns(){ GLMModel model1 = null, model2 = null, model3 = null, model4 = null; Frame fr = parse_test_file(Key.make("Airlines"), "smalldata/airlines/allyears2k_headers.zip"); Vec y = fr.vec("IsDepDelayed").makeCopy(null); fr.replace(fr.find("IsDepDelayed"),y).remove(); Vec weights = fr.anyVec().makeZero(); new MRTask(){ @Override public void map(Chunk c){ int i = 0; for(i = 0; i < c._len; ++i){ long rid = c.start()+i; if(rid >= 1999) break; c.set(i,1); } } }.doAll(weights); fr.add("weights", weights); DKV.put(fr); GLMParameters parms = new GLMParameters(Family.gaussian); parms._train = fr._key; parms._weights_column = "weights"; parms._lambda_search = true; parms._alpha = new double[]{0}; parms._response_column = "IsDepDelayed"; parms._ignored_columns = new String[]{"DepTime", "ArrTime", "Cancelled", "CancellationCode", "DepDelay", "Diverted", "CarrierDelay", "WeatherDelay", "NASDelay", "SecurityDelay", "LateAircraftDelay", "IsArrDelayed"}; parms._standardize = true; model1 = new GLM(parms).trainModel().get(); model1.delete(); fr.delete(); } // test categorical autoexpansions, run on airlines which has several categorical columns, // once on explicitly expanded data, once on h2o autoexpanded and compare the results @Test public void testAirlines() { GLMModel model1 = null, model2 = null, model3 = null, model4 = null; Frame frMM = parse_test_file(Key.make("AirlinesMM"), "smalldata/airlines/AirlinesTrainMM.csv.zip"); Frame frG = parse_test_file(Key.make("gram"), "smalldata/airlines/gram_std.csv"); Vec xy = frG.remove("xy"); frMM.remove("C1").remove(); Vec v; frMM.add("IsDepDelayed", (v = frMM.remove("IsDepDelayed")).makeCopy(null)); v.remove(); DKV.put(frMM._key, frMM); Frame fr = parse_test_file(Key.make("Airlines"), "smalldata/airlines/AirlinesTrain.csv.zip"), res = null; fr.add("IsDepDelayed",(v =fr.remove("IsDepDelayed")).makeCopy(null)); v.remove(); DKV.put(fr._key,fr); // Distance + Origin + Dest + UniqueCarrier String[] ignoredCols = new String[]{"fYear", "fMonth", "fDayofMonth", "fDayOfWeek", "DepTime", "ArrTime", "IsDepDelayed_REC"}; try { Scope.enter(); GLMParameters params = new GLMParameters(Family.gaussian); params._response_column = "IsDepDelayed"; params._ignored_columns = ignoredCols; params._train = fr._key; params._lambda = new double[]{0}; params._alpha = new double[]{0}; params._standardize = false; params._use_all_factor_levels = false; model1 = new GLM(params).trainModel().get(); testScoring(model1,fr); Frame score1 = model1.score(fr); ModelMetricsRegressionGLM mm = (ModelMetricsRegressionGLM) ModelMetrics.getFromDKV(model1, fr); Assert.assertEquals(((ModelMetricsRegressionGLM) model1._output._training_metrics)._resDev, mm._resDev, 1e-4); Assert.assertEquals(((ModelMetricsRegressionGLM) model1._output._training_metrics)._resDev, mm._MSE * score1.numRows(), 1e-4); score1.delete(); mm.remove(); res = model1.score(fr); // Build a POJO, validate same results params._train = frMM._key; params._ignored_columns = new String[]{"X"}; model2 = new GLM( params).trainModel().get(); HashMap<String, Double> coefs1 = model1.coefficients(); testScoring(model2,frMM); HashMap<String, Double> coefs2 = model2.coefficients(); boolean failed = false; // compare against each other for (String s : coefs2.keySet()) { String s1 = s; if (s.startsWith("Origin")) s1 = "Origin." + s.substring(6); if (s.startsWith("Dest")) s1 = "Dest." + s.substring(4); if (s.startsWith("UniqueCarrier")) s1 = "UniqueCarrier." + s.substring(13); if(Math.abs(coefs1.get(s1) - coefs2.get(s)) > 1e-4) { System.out.println("coeff " + s1 + " differs, " + coefs1.get(s1) + " != " + coefs2.get(s)); failed = true; } // assertEquals("coeff " + s1 + " differs, " + coefs1.get(s1) + " != " + coefs2.get(s), coefs1.get(s1), coefs2.get(s), 1e-4); } assertFalse(failed); params._standardize = true; params._train = frMM._key; params._use_all_factor_levels = true; // test the gram DataInfo dinfo = new DataInfo(frMM, null, 1, true, DataInfo.TransformType.STANDARDIZE, DataInfo.TransformType.NONE, true, false, false, false, false, false); GLMIterationTask glmt = new GLMIterationTask(null, dinfo, new GLMWeightsFun(params), null).doAll(dinfo._adaptedFrame); for(int i = 0; i < glmt._xy.length; ++i) { for(int j = 0; j <= i; ++j ) { assertEquals(frG.vec(j).at(i), glmt._gram.get(i, j), 1e-5); } assertEquals(xy.at(i), glmt._xy[i], 1e-5); } xy.remove(); params = (GLMParameters) params.clone(); params._standardize = false; params._family = Family.binomial; params._link = Link.logit; model3 = new GLM( params).trainModel().get(); testScoring(model3,frMM); params._train = fr._key; params._ignored_columns = ignoredCols; model4 = new GLM( params).trainModel().get(); testScoring(model4,fr); assertEquals(nullDeviance(model3), nullDeviance(model4), 1e-4); assertEquals(residualDeviance(model4), residualDeviance(model3), nullDeviance(model3) * 1e-3); assertEquals(nullDeviance(model1), nullDeviance(model2), 1e-4); assertEquals(residualDeviance(model1), residualDeviance(model2), 1e-4); // assertEquals(val1._aic, val2._aic,1e-2); // compare result against glmnet assertEquals(5336.918, residualDeviance(model1), 1); assertEquals(6051.613, nullDeviance(model2), 1); // lbfgs // params._solver = Solver.L_BFGS; // params._train = fr._key; // params._lambda = new double[]{.3}; // model3 = new GLM(params,glmkey("lbfgs_cat")).trainModel().get(); // params._train = frMM._key; // mdoel4 = new GLM(params,glmkey("lbfgs_mm")).trainModel().get(); // HashMap<String, Double> coefs3 = model3.coefficients(); // HashMap<String, Double> coefs4 = model4.coefficients(); // // compare against each other // for(String s:coefs4.keySet()) { // String s1 = s; // if(s.startsWith("Origin")) // s1 = "Origin." + s.substring(6); // if(s.startsWith("Dest")) // s1 = "Dest." + s.substring(4); // if(s.startsWith("UniqueCarrier")) // s1 = "UniqueCarrier." + s.substring(13); // assertEquals("coeff " + s1 + " differs, " + coefs3.get(s1) + " != " + coefs4.get(s), coefs3.get(s1), coefs4.get(s),1e-4); // } } finally { fr.delete(); frMM.delete(); frG.delete(); if (res != null) res.delete(); if (model1 != null) model1.delete(); if (model2 != null) model2.delete(); if (model3 != null) model3.delete(); if (model4 != null) model4.delete(); // if(score != null)score.delete(); Scope.exit(); } } // test categorical autoexpansions, run on airlines which has several categorical columns, // once on explicitly expanded data, once on h2o autoexpanded and compare the results @Test public void test_COD_Airlines_SingleLambda() { GLMModel model1 = null; Frame fr = parse_test_file(Key.make("Airlines"), "smalldata/airlines/AirlinesTrain.csv.zip"); // Distance + Origin + Dest + UniqueCarrier String[] ignoredCols = new String[]{"IsDepDelayed_REC"}; try { Scope.enter(); GLMParameters params = new GLMParameters(Family.binomial); params._response_column = "IsDepDelayed"; params._ignored_columns = ignoredCols; params._train = fr._key; params._valid = fr._key; params._lambda = new double[] {0.01};//null; //new double[]{0.02934};//{0.02934494}; // null; params._alpha = new double[]{1}; params._standardize = false; params._solver = Solver.COORDINATE_DESCENT_NAIVE; params._lambda_search = true; params._nlambdas = 5; GLM glm = new GLM( params); model1 = glm.trainModel().get(); double [] beta = model1.beta(); double l1pen = ArrayUtils.l1norm(beta,true); double l2pen = ArrayUtils.l2norm2(beta,true); //System.out.println( " lambda min " + params._l2pen[params._l2pen.length-1] ); //System.out.println( " lambda_max " + model1._lambda_max); //System.out.println(" intercept " + beta[beta.length-1]); // double objective = model1._output._training_metrics./model1._nobs + // params._l2pen[params._l2pen.length-1]*params._alpha[0]*l1pen + params._l2pen[params._l2pen.length-1]*(1-params._alpha[0])*l2pen/2 ; // System.out.println( " objective value " + objective); // assertEquals(0.670921, objective,1e-4); } finally { fr.delete(); if (model1 != null) model1.delete(); } } @Test public void test_COD_Airlines_SingleLambda_CovUpdates() { GLMModel model1 = null; Frame fr = parse_test_file(Key.make("Airlines"), "smalldata/airlines/AirlinesTrain.csv.zip"); // Distance + Origin + Dest + UniqueCarrier String[] ignoredCols = new String[]{"IsDepDelayed_REC"}; try { Scope.enter(); GLMParameters params = new GLMParameters(Family.binomial); params._response_column = "IsDepDelayed"; params._ignored_columns = ignoredCols; params._train = fr._key; params._valid = fr._key; params._lambda = new double[] {0.01};//null; //new double[]{0.02934};//{0.02934494}; // null; params._alpha = new double[]{1}; params._standardize = false; params._solver = Solver.COORDINATE_DESCENT; params._lambda_search = true; GLM glm = new GLM( params); model1 = glm.trainModel().get(); double [] beta = model1.beta(); double l1pen = ArrayUtils.l1norm(beta,true); double l2pen = ArrayUtils.l2norm2(beta,true); // double objective = job.likelihood()/model1._nobs + // params._l2pen[params._l2pen.length-1]*params._alpha[0]*l1pen + params._l2pen[params._l2pen.length-1]*(1-params._alpha[0])*l2pen/2 ; // System.out.println( " objective value " + objective); // assertEquals(0.670921, objective,1e-2); } finally { fr.delete(); if (model1 != null) model1.delete(); } } @Test public void test_COD_Airlines_LambdaSearch() { GLMModel model1 = null; Frame fr = parse_test_file(Key.make("Airlines"), "smalldata/airlines/AirlinesTrain.csv.zip"); // Distance + Origin + Dest + UniqueCarrier String[] ignoredCols = new String[]{"IsDepDelayed_REC"}; try { Scope.enter(); GLMParameters params = new GLMParameters(Family.binomial); params._response_column = "IsDepDelayed"; params._ignored_columns = ignoredCols; params._train = fr._key; params._valid = fr._key; params._lambda = null; // new double [] {0.25}; params._alpha = new double[]{1}; params._standardize = false; params._solver = Solver.COORDINATE_DESCENT_NAIVE;//IRLSM params._lambda_search = true; params._nlambdas = 5; GLM glm = new GLM(params); model1 = glm.trainModel().get(); GLMModel.Submodel sm = model1._output._submodels[model1._output._submodels.length - 1]; double[] beta = sm.beta; System.out.println("lambda " + sm.lambda_value); double l1pen = ArrayUtils.l1norm(beta, true); double l2pen = ArrayUtils.l2norm2(beta, true); // double objective = job.likelihood()/model1._nobs + // gives likelihood of the last lambda // params._l2pen[params._l2pen.length-1]*params._alpha[0]*l1pen + params._l2pen[params._l2pen.length-1]*(1-params._alpha[0])*l2pen/2 ; // assertEquals(0.65689, objective,1e-4); } finally { fr.delete(); if (model1 != null) model1.delete(); } } @Test public void test_COD_Airlines_LambdaSearch_CovUpdates() { GLMModel model1 = null; Frame fr = parse_test_file(Key.make("Airlines"), "smalldata/airlines/AirlinesTrain.csv.zip"); // Distance + Origin + Dest + UniqueCarrier String[] ignoredCols = new String[]{"IsDepDelayed_REC"}; try { Scope.enter(); GLMParameters params = new GLMParameters(Family.binomial); params._response_column = "IsDepDelayed"; params._ignored_columns = ignoredCols; params._train = fr._key; params._valid = fr._key; params._lambda = null; // new double [] {0.25}; params._alpha = new double[]{1}; params._standardize = false; params._solver = Solver.COORDINATE_DESCENT; params._lambda_search = true; params._nlambdas = 5; GLM glm = new GLM( params); model1 = glm.trainModel().get(); GLMModel.Submodel sm = model1._output._submodels[model1._output._submodels.length-1]; double [] beta = sm.beta; System.out.println("lambda " + sm.lambda_value); double l1pen = ArrayUtils.l1norm(beta,true); double l2pen = ArrayUtils.l2norm2(beta,true); // double objective = job.likelihood()/model1._nobs + // gives likelihood of the last lambda // params._l2pen[params._l2pen.length-1]*params._alpha[0]*l1pen + params._l2pen[params._l2pen.length-1]*(1-params._alpha[0])*l2pen/2 ; // assertEquals(0.65689, objective,1e-4); } finally { fr.delete(); if (model1 != null) model1.delete(); } } public static double residualDeviance(GLMModel m) { if (m._parms._family == Family.binomial || m._parms._family == Family.quasibinomial) { ModelMetricsBinomialGLM metrics = (ModelMetricsBinomialGLM) m._output._training_metrics; return metrics._resDev; } else { ModelMetricsRegressionGLM metrics = (ModelMetricsRegressionGLM) m._output._training_metrics; return metrics._resDev; } } public static double residualDevianceTest(GLMModel m) { if(m._parms._family == Family.binomial) { ModelMetricsBinomialGLM metrics = (ModelMetricsBinomialGLM)m._output._validation_metrics; return metrics._resDev; } else { ModelMetricsRegressionGLM metrics = (ModelMetricsRegressionGLM)m._output._validation_metrics; return metrics._resDev; } } public static double nullDevianceTest(GLMModel m) { if(m._parms._family == Family.binomial) { ModelMetricsBinomialGLM metrics = (ModelMetricsBinomialGLM)m._output._validation_metrics; return metrics._nullDev; } else { ModelMetricsRegressionGLM metrics = (ModelMetricsRegressionGLM)m._output._validation_metrics; return metrics._nullDev; } } public static double aic(GLMModel m) { if (m._parms._family == Family.binomial) { ModelMetricsBinomialGLM metrics = (ModelMetricsBinomialGLM) m._output._training_metrics; return metrics._AIC; } else { ModelMetricsRegressionGLM metrics = (ModelMetricsRegressionGLM) m._output._training_metrics; return metrics._AIC; } } public static double nullDOF(GLMModel m) { if (m._parms._family == Family.binomial) { ModelMetricsBinomialGLM metrics = (ModelMetricsBinomialGLM) m._output._training_metrics; return metrics._nullDegressOfFreedom; } else { ModelMetricsRegressionGLM metrics = (ModelMetricsRegressionGLM) m._output._training_metrics; return metrics._nullDegressOfFreedom; } } public static double resDOF(GLMModel m) { if (m._parms._family == Family.binomial || m._parms._family == Family.quasibinomial) { ModelMetricsBinomialGLM metrics = (ModelMetricsBinomialGLM) m._output._training_metrics; return metrics._residualDegressOfFreedom; } else { ModelMetricsRegressionGLM metrics = (ModelMetricsRegressionGLM) m._output._training_metrics; return metrics._residualDegressOfFreedom; } } public static double auc(GLMModel m) { ModelMetricsBinomialGLM metrics = (ModelMetricsBinomialGLM) m._output._training_metrics; return metrics.auc_obj()._auc; } public static double logloss(GLMModel m) { ModelMetricsBinomialGLM metrics = (ModelMetricsBinomialGLM) m._output._training_metrics; return metrics._logloss; } public static double mse(GLMModel m) { if (m._parms._family == Family.binomial) { ModelMetricsBinomialGLM metrics = (ModelMetricsBinomialGLM) m._output._training_metrics; return metrics._MSE; } else { ModelMetricsRegressionGLM metrics = (ModelMetricsRegressionGLM) m._output._training_metrics; return metrics._MSE; } } public static double nullDeviance(GLMModel m) { if (m._parms._family == Family.binomial || m._parms._family == Family.quasibinomial) { ModelMetricsBinomialGLM metrics = (ModelMetricsBinomialGLM) m._output._training_metrics; return metrics._nullDev; } else { ModelMetricsRegressionGLM metrics = (ModelMetricsRegressionGLM) m._output._training_metrics; return metrics._nullDev; } } // test class private static final class GLMIterationTaskTest extends GLMIterationTask { final GLMModel _m; GLMMetricBuilder _val2; public GLMIterationTaskTest(Key jobKey, DataInfo dinfo, double lambda, GLMParameters glm, boolean validate, double[] beta, double ymu, GLMModel m) { // null, dinfo, new GLMWeightsFun(params), beta, 1e-5 super(jobKey, dinfo, new GLMWeightsFun(glm), beta); _m = m; } public void map(Chunk[] chks) { super.map(chks); _val2 = (GLMMetricBuilder) _m.makeMetricBuilder(chks[chks.length - 1].vec().domain()); double[] ds = new double[3]; float[] actual = new float[1]; for (int i = 0; i < chks[0]._len; ++i) { _m.score0(chks, i, null, ds); actual[0] = (float) chks[chks.length - 1].atd(i); _val2.perRow(ds, actual, _m); } } public void reduce(GLMIterationTask gmt) { super.reduce(gmt); GLMIterationTaskTest g = (GLMIterationTaskTest) gmt; _val2.reduce(g._val2); } } /** * Simple test for binomial family (no regularization, test both lsm solvers). * Runs the classical prostate, using dataset with race replaced by categoricals (probably as it's supposed to be?), in any case, * it gets to test correct processing of categoricals. * * Compare against the results from standard R glm implementation. * @throws ExecutionException * @throws InterruptedException */ @Test public void testProstate() throws InterruptedException, ExecutionException { GLMModel model = null, model2 = null, model3 = null, model4 = null; Frame fr = parse_test_file("smalldata/glm_test/prostate_cat_replaced.csv"); try{ Scope.enter(); // R results // Coefficients: // (Intercept) ID AGE RACER2 RACER3 DPROS DCAPS PSA VOL GLEASON // -8.894088 0.001588 -0.009589 0.231777 -0.459937 0.556231 0.556395 0.027854 -0.011355 1.010179 String [] cfs1 = new String [] {"Intercept","AGE", "RACE.R2","RACE.R3", "DPROS", "DCAPS", "PSA", "VOL", "GLEASON"}; double [] vals = new double [] {-8.14867, -0.01368, 0.32337, -0.38028, 0.55964, 0.49548, 0.02794, -0.01104, 0.97704}; GLMParameters params = new GLMParameters(Family.binomial); params._response_column = "CAPSULE"; params._ignored_columns = new String[]{"ID"}; params._train = fr._key; params._lambda = new double[]{0}; params._standardize = false; // params._missing_values_handling = MissingValuesHandling.Skip; GLM glm = new GLM(params); model = glm.trainModel().get(); assertTrue(model._output.bestSubmodel().iteration == 5); model.delete(); params._max_iterations = 4; glm = new GLM(params); model = glm.trainModel().get(); assertTrue(model._output.bestSubmodel().iteration == 4); System.out.println(model._output._model_summary); HashMap<String, Double> coefs = model.coefficients(); System.out.println(coefs); for(int i = 0; i < cfs1.length; ++i) assertEquals(vals[i], coefs.get(cfs1[i]),1e-4); assertEquals(512.3, nullDeviance(model),1e-1); assertEquals(378.3, residualDeviance(model),1e-1); assertEquals(371, resDOF(model),0); assertEquals(396.3, aic(model),1e-1); testScoring(model,fr); // test scoring model.score(fr).delete(); hex.ModelMetricsBinomial mm = hex.ModelMetricsBinomial.getFromDKV(model,fr); hex.AUC2 adata = mm._auc; assertEquals(model._output._training_metrics.auc_obj()._auc, adata._auc, 1e-8); assertEquals(0.7654038154645615, adata.pr_auc(), 1e-8); assertEquals(model._output._training_metrics._MSE, mm._MSE, 1e-8); assertEquals(((ModelMetricsBinomialGLM)model._output._training_metrics)._resDev, ((ModelMetricsBinomialGLM)mm)._resDev, 1e-8); model.score(fr).delete(); mm = hex.ModelMetricsBinomial.getFromDKV(model,fr); assertEquals(model._output._training_metrics.auc_obj()._auc, adata._auc, 1e-8); assertEquals(model._output._training_metrics._MSE, mm._MSE, 1e-8); assertEquals(((ModelMetricsBinomialGLM)model._output._training_metrics)._resDev, ((ModelMetricsBinomialGLM)mm)._resDev, 1e-8); double prior = 1e-5; params._prior = prior; // test the same data and model with prior, should get the same model except for the intercept glm = new GLM(params); model2 = glm.trainModel().get(); for(int i = 0; i < model2.beta().length-1; ++i) assertEquals(model.beta()[i], model2.beta()[i], 1e-8); assertEquals(model.beta()[model.beta().length-1] -Math.log(model._ymu[0] * (1-prior)/(prior * (1-model._ymu[0]))),model2.beta()[model.beta().length-1],1e-10); // run with lambda search, check the final submodel params._lambda_search = true; params._lambda = null; params._alpha = new double[]{0}; params._prior = -1; params._obj_reg = -1; params._max_iterations = 500; params._objective_epsilon = 1e-6; // test the same data and model with prior, should get the same model except for the intercept glm = new GLM(params); model3 = glm.trainModel().get(); double lambda = model3._output._submodels[model3._output._best_lambda_idx].lambda_value; params._lambda_search = false; params._lambda = new double[]{lambda}; ModelMetrics mm3 = ModelMetrics.getFromDKV(model3,fr); assertEquals("mse don't match, " + model3._output._training_metrics._MSE + " != " + mm3._MSE,model3._output._training_metrics._MSE,mm3._MSE,1e-8); assertEquals("res-devs don't match, " + ((ModelMetricsBinomialGLM)model3._output._training_metrics)._resDev + " != " + ((ModelMetricsBinomialGLM)mm3)._resDev,((ModelMetricsBinomialGLM)model3._output._training_metrics)._resDev, ((ModelMetricsBinomialGLM)mm3)._resDev,1e-4); fr.add("CAPSULE", fr.remove("CAPSULE")); fr.remove("ID").remove(); DKV.put(fr); model3.score(fr).delete(); mm3 = ModelMetrics.getFromDKV(model3,fr); assertEquals("mse don't match, " + model3._output._training_metrics._MSE + " != " + mm3._MSE,model3._output._training_metrics._MSE,mm3._MSE,1e-8); assertEquals("res-devs don't match, " + ((ModelMetricsBinomialGLM)model3._output._training_metrics)._resDev + " != " + ((ModelMetricsBinomialGLM)mm3)._resDev,((ModelMetricsBinomialGLM)model3._output._training_metrics)._resDev, ((ModelMetricsBinomialGLM)mm3)._resDev,1e-4); // test the same data and model with prior, should get the same model except for the intercept glm = new GLM(params); model4 = glm.trainModel().get(); assertEquals("mse don't match, " + model3._output._training_metrics._MSE + " != " + model4._output._training_metrics._MSE,model3._output._training_metrics._MSE,model4._output._training_metrics._MSE,1e-6); assertEquals("res-devs don't match, " + ((ModelMetricsBinomialGLM)model3._output._training_metrics)._resDev + " != " + ((ModelMetricsBinomialGLM)model4._output._training_metrics)._resDev,((ModelMetricsBinomialGLM)model3._output._training_metrics)._resDev, ((ModelMetricsBinomialGLM)model4._output._training_metrics)._resDev,1e-4); model4.score(fr).delete(); ModelMetrics mm4 = ModelMetrics.getFromDKV(model4,fr); assertEquals("mse don't match, " + mm3._MSE + " != " + mm4._MSE,mm3._MSE,mm4._MSE,1e-6); assertEquals("res-devs don't match, " + ((ModelMetricsBinomialGLM)mm3)._resDev + " != " + ((ModelMetricsBinomialGLM)mm4)._resDev,((ModelMetricsBinomialGLM)mm3)._resDev, ((ModelMetricsBinomialGLM)mm4)._resDev,1e-4); // GLMValidation val2 = new GLMValidationTsk(params,model._ymu,rank(model.beta())).doAll(new Vec[]{fr.vec("CAPSULE"),score.vec("1")})._val; // assertEquals(val.residualDeviance(),val2.residualDeviance(),1e-6); // assertEquals(val.nullDeviance(),val2.nullDeviance(),1e-6); } finally { fr.delete(); if(model != null)model.delete(); if(model2 != null)model2.delete(); if(model3 != null)model3.delete(); if(model4 != null)model4.delete(); Scope.exit(); } } @Test public void testQuasibinomial(){ GLMParameters params = new GLMParameters(Family.quasibinomial); GLM glm = new GLM(params); params.validate(glm); params._link = Link.log; try { params.validate(glm); Assert.assertTrue("should've thrown IAE", false); } catch(IllegalArgumentException iae){ // do nothing } // test it behaves like binomial on binary data GLMModel model = null; Frame fr = parse_test_file("smalldata/glm_test/prostate_cat_replaced.csv"); try { Scope.enter(); // R results // Coefficients: // (Intercept) ID AGE RACER2 RACER3 DPROS DCAPS PSA VOL GLEASON // -8.894088 0.001588 -0.009589 0.231777 -0.459937 0.556231 0.556395 0.027854 -0.011355 1.010179 String[] cfs1 = new String[]{"Intercept", "AGE", "RACE.R2", "RACE.R3", "DPROS", "DCAPS", "PSA", "VOL", "GLEASON"}; double[] vals = new double[]{-8.14867, -0.01368, 0.32337, -0.38028, 0.55964, 0.49548, 0.02794, -0.01104, 0.97704}; params = new GLMParameters(Family.quasibinomial); params._response_column = "CAPSULE"; params._ignored_columns = new String[]{"ID"}; params._train = fr._key; params._lambda = new double[]{0}; params._nfolds = 5; params._standardize = false; params._link = Link.logit; // params._missing_values_handling = MissingValuesHandling.Skip; glm = new GLM(params); model = glm.trainModel().get(); HashMap<String, Double> coefs = model.coefficients(); System.out.println(coefs); for (int i = 0; i < cfs1.length; ++i) assertEquals(vals[i], coefs.get(cfs1[i]), 1e-4); assertEquals(512.3, nullDeviance(model), 1e-1); assertEquals(378.3, residualDeviance(model), 1e-1); assertEquals(371, resDOF(model), 0); } finally { fr.delete(); if(model != null){ model.deleteCrossValidationModels(); model.delete(); } Scope.exit(); } } @Test public void testSynthetic() throws Exception { GLMModel model = null; Frame fr = parse_test_file("smalldata/glm_test/glm_test2.csv"); Frame score = null; try { Scope.enter(); GLMParameters params = new GLMParameters(Family.binomial); params._response_column = "response"; // params._response = fr.find(params._response_column); params._ignored_columns = new String[]{"ID"}; params._train = fr._key; params._lambda = new double[]{0}; params._standardize = false; params._max_iterations = 20; GLM glm = new GLM( params); model = glm.trainModel().get(); double [] beta = model.beta(); System.out.println("beta = " + Arrays.toString(beta)); assertEquals(auc(model), 1, 1e-4); score = model.score(fr); hex.ModelMetricsBinomial mm = hex.ModelMetricsBinomial.getFromDKV(model,fr); hex.AUC2 adata = mm._auc; assertEquals(auc(model), adata._auc, 1e-2); } finally { fr.remove(); if(model != null)model.delete(); if(score != null)score.delete(); Scope.exit(); } } @Test //PUBDEV-1839 public void testCitibikeReproPUBDEV1839() throws Exception { GLMModel model = null; Frame tfr = parse_test_file("smalldata/jira/pubdev_1839_repro_train.csv"); Frame vfr = parse_test_file("smalldata/jira/pubdev_1839_repro_test.csv"); try { Scope.enter(); GLMParameters params = new GLMParameters(Family.poisson); params._response_column = "bikes"; params._train = tfr._key; params._valid = vfr._key; GLM glm = new GLM(params); model = glm.trainModel().get(); testScoring(model,vfr); } finally { tfr.remove(); vfr.remove(); if(model != null)model.delete(); Scope.exit(); } } @Test public void testCitibikeReproPUBDEV1953() throws Exception { GLMModel model = null; Frame tfr = parse_test_file("smalldata/glm_test/citibike_small_train.csv"); Frame vfr = parse_test_file("smalldata/glm_test/citibike_small_test.csv"); try { Scope.enter(); GLMParameters params = new GLMParameters(Family.poisson); params._response_column = "bikes"; params._train = tfr._key; params._valid = vfr._key; params._family = Family.poisson; GLM glm = new GLM( params); model = glm.trainModel().get(); testScoring(model,vfr); } finally { tfr.remove(); vfr.remove(); if(model != null)model.delete(); Scope.exit(); } } @Test public void testXval(){ GLMModel model = null; Frame fr = parse_test_file("smalldata/glm_test/prostate_cat_replaced.csv"); try{ GLMParameters params = new GLMParameters(Family.binomial); params._response_column = "CAPSULE"; params._ignored_columns = new String[]{"ID"}; params._train = fr._key; params._lambda_search = true; params._nfolds = 3; params._standardize = false; params._keep_cross_validation_models = true; GLM glm = new GLM(params); model = glm.trainModel().get(); } finally { fr.delete(); if(model != null) { for(Key k:model._output._cross_validation_models) Keyed.remove(k); model.delete(); } } } /** * Test that lambda search gets (almost) the same result as running the model for each lambda separately. */ @Test public void testCustomLambdaSearch(){ Key pros = Key.make("prostate"); Frame f = parse_test_file(pros, "smalldata/glm_test/prostate_cat_replaced.csv"); for(Family fam:new Family[]{Family.multinomial,Family.binomial}) { for (double alpha : new double[]{0, .5, 1}) { for (Solver s : Solver.values()) { if (s == Solver.COORDINATE_DESCENT_NAIVE || s== Solver.AUTO || s.equals(Solver.GRADIENT_DESCENT_LH) || s.equals(Solver.GRADIENT_DESCENT_SQERR)) continue; // if(fam == Family.multinomial && (s != Solver.L_BFGS || alpha != 0)) continue; try { Scope.enter(); GLMParameters parms = new GLMParameters(fam); parms._train = pros; parms._alpha = new double[]{alpha}; parms._solver = s; parms._lambda = new double[]{10, 1, .1, 1e-5, 0}; parms._lambda_search = true; parms._response_column = fam == Family.multinomial?"RACE":"CAPSULE"; GLMModel model = new GLM(parms).trainModel().get(); GLMModel.RegularizationPath rp = model.getRegularizationPath(); for (int i = 0; i < parms._lambda.length; ++i) { GLMParameters parms2 = new GLMParameters(fam); parms2._train = pros; parms2._alpha = new double[]{alpha}; parms2._solver = s; parms2._lambda = new double[]{parms._lambda[i]}; parms2._lambda_search = false; parms2._response_column = fam == Family.multinomial?"RACE":"CAPSULE"; parms2._beta_epsilon = 1e-5; parms2._objective_epsilon = 1e-8; GLMModel model2 = new GLM(parms2).trainModel().get(); double[] beta_ls = rp._coefficients_std[i]; double [] beta = fam == Family.multinomial?flat(model2._output.getNormBetaMultinomial()):model2._output.getNormBeta(); System.out.println(ArrayUtils.pprint(new double[][]{beta,beta_ls})); // Can't compare beta here, have to compare objective value double null_dev = ((GLMMetrics) model2._output._training_metrics).null_deviance(); double res_dev_ls = null_dev * (1 - rp._explained_deviance_train[i]); double likelihood_ls = .5 * res_dev_ls; double likelihood = .5 * ((GLMMetrics) model2._output._training_metrics).residual_deviance(); double nobs = model._nobs; if(fam == Family.multinomial){ beta = beta.clone(); beta_ls = beta_ls.clone(); int P = beta.length/model._output.nclasses(); assert beta.length == P*model._output.nclasses(); for(int j = P-1; j < beta.length; j += P) { beta[j] = 0; beta_ls[j] = 0; } } double obj_ls = likelihood_ls / nobs + ((1 - alpha) * parms._lambda[i] * .5 * ArrayUtils.l2norm2(beta_ls, true)) + alpha * parms._lambda[i] * ArrayUtils.l1norm(beta_ls, true); double obj = likelihood / nobs + ((1 - alpha) * parms._lambda[i] * .5 * ArrayUtils.l2norm2(beta, true)) + alpha * parms._lambda[i] * ArrayUtils.l1norm(beta, true); Assert.assertEquals(obj, obj_ls, 2*parms._objective_epsilon); model2.delete(); } model.delete(); } finally { Scope.exit(); } } } } f.delete(); } /** * Test strong rules on arcene datasets (10k predictors, 100 rows). * Should be able to obtain good model (~100 predictors, ~1 explained deviance) with up to 250 active predictors. * Scaled down (higher lambda min, fewer lambdas) to run at reasonable speed (whole test takes 20s on my laptop). * * Test runs glm with gaussian on arcene dataset and verifies it gets all lambda while limiting maximum actove predictors to reasonably small number. * Compares the objective value to expected one. */ @Test public void testArcene() throws InterruptedException, ExecutionException{ Key parsed = Key.make("arcene_parsed"); Key<GLMModel> modelKey = Key.make("arcene_model"); GLMModel model = null; Frame fr = parse_test_file(parsed, "smalldata/glm_test/arcene.csv"); try{ Scope.enter(); // test LBFGS with l1 pen GLMParameters params = new GLMParameters(Family.gaussian); // params._response = 0; params._lambda = null; params._response_column = fr._names[0]; params._train = parsed; params._lambda_search = true; params._nlambdas = 35; params._lambda_min_ratio = 0.18; params._max_iterations = 100000; params._max_active_predictors = 10000; params._alpha = new double[]{1}; for(Solver s: new Solver[]{Solver.IRLSM, Solver.COORDINATE_DESCENT}){//Solver.COORDINATE_DESCENT,}) { // LBFGS lambda-search is too slow now params._solver = s; GLM glm = new GLM( params, modelKey); glm.trainModel().get(); model = DKV.get(modelKey).get(); System.out.println(model._output._model_summary); // assert on that we got all submodels (if strong rules work, we should be able to get the results with this many active predictors) assertEquals(params._nlambdas, model._output._submodels.length); System.out.println(model._output._training_metrics); // assert on the quality of the result, technically should compare objective value, but this should be good enough for now } model.delete(); params._solver = Solver.COORDINATE_DESCENT; params._max_active_predictors = 100; params._lambda_min_ratio = 1e-2; params._nlambdas = 100; GLM glm = new GLM( params, modelKey); glm.trainModel().get(); model = DKV.get(modelKey).get(); assertTrue(model._output.rank() <= params._max_active_predictors); // System.out.println("============================================================================================================"); System.out.println(model._output._model_summary); // assert on that we got all submodels (if strong rules work, we should be able to get the results with this many active predictors) System.out.println(model._output._training_metrics); System.out.println("============================================================================================================"); model.delete(); params._max_active_predictors = 250; params._lambda = null; params._lambda_search = false; glm = new GLM( params, modelKey); glm.trainModel().get(); model = DKV.get(modelKey).get(); assertTrue(model._output.rank() <= params._max_active_predictors); // System.out.println("============================================================================================================"); System.out.println(model._output._model_summary); // assert on that we got all submodels (if strong rules work, we should be able to get the results with this many active predictors) System.out.println(model._output._training_metrics); System.out.println("============================================================================================================"); model.delete(); } finally { fr.delete(); if(model != null)model.delete(); Scope.exit(); } } /** Test large GLM POJO model generation. * Make a 10K predictor model, emit, javac, and score with it. */ @Test public void testBigPOJO() { GLMModel model = null; Frame fr = parse_test_file(Key.make("arcene_parsed"), "smalldata/glm_test/arcene.csv"), res=null; try{ Scope.enter(); // test LBFGS with l1 pen GLMParameters params = new GLMParameters(Family.gaussian); // params._response = 0; params._lambda = null; params._response_column = fr._names[0]; params._train = fr._key; params._max_active_predictors = 100000; params._alpha = new double[]{0}; params._solver = Solver.L_BFGS; GLM glm = new GLM(params); model = glm.trainModel().get(); res = model.score(fr); model.testJavaScoring(fr,res,0.0); } finally { fr.delete(); if(model != null) model.delete(); if( res != null ) res.delete(); Scope.exit(); } } @Test public void testAbalone() { Scope.enter(); GLMModel model = null; try { Frame fr = parse_test_file("smalldata/glm_test/Abalone.gz"); Scope.track(fr); GLMParameters params = new GLMParameters(Family.gaussian); params._train = fr._key; params._response_column = fr._names[8]; params._alpha = new double[]{1.0}; params._lambda_search = true; GLM glm = new GLM(params); model = glm.trainModel().get(); testScoring(model,fr); } finally { if( model != null ) model.delete(); Scope.exit(); } } @Test public void testZeroedColumn(){ Vec x = Vec.makeCon(Vec.newKey(),1,2,3,4,5); Vec y = Vec.makeCon(x.group().addVec(),0,1,0,1,0); Vec z = Vec.makeCon(Vec.newKey(),1,2,3,4,5); Vec w = Vec.makeCon(x.group().addVec(),1,0,1,0,1); Frame fr = new Frame(Key.<Frame>make("test"),new String[]{"x","y","z","w"},new Vec[]{x,y,z,w}); DKV.put(fr); GLMParameters parms = new GLMParameters(Family.gaussian); parms._train = fr._key; parms._lambda = new double[]{0}; parms._alpha = new double[]{0}; parms._compute_p_values = true; parms._response_column = "z"; parms._weights_column = "w"; GLMModel m = new GLM(parms).trainModel().get(); System.out.println(m.coefficients()); m.delete(); fr.delete(); } @Test public void testDeviances() { for (Family fam : Family.values()) { if(fam == Family.quasibinomial || fam == Family.ordinal) continue; Frame tfr = null; Frame res = null; Frame preds = null; GLMModel gbm = null; try { tfr = parse_test_file("./smalldata/gbm_test/BostonHousing.csv"); GLMModel.GLMParameters parms = new GLMModel.GLMParameters(); parms._train = tfr._key; String resp = tfr.lastVecName(); if (fam==Family.binomial || fam==Family.multinomial || fam == Family.fractionalbinomial) { resp = fam==Family.multinomial?"rad":"chas"; Vec v = tfr.remove(resp); tfr.add(resp, v.toCategoricalVec()); v.remove(); DKV.put(tfr); } parms._response_column = resp; parms._family = fam; gbm = new GLM(parms).trainModel().get(); preds = gbm.score(tfr); res = gbm.computeDeviances(tfr,preds,"myDeviances"); double meanDeviances = res.anyVec().mean(); if (gbm._output.nclasses()==2) Assert.assertEquals(meanDeviances,((ModelMetricsBinomial) gbm._output._training_metrics)._logloss,1e-6*Math.abs(meanDeviances)); else if (gbm._output.nclasses()>2) Assert.assertEquals(meanDeviances,((ModelMetricsMultinomial) gbm._output._training_metrics)._logloss,1e-6*Math.abs(meanDeviances)); else Assert.assertEquals(meanDeviances,((ModelMetricsRegression) gbm._output._training_metrics)._mean_residual_deviance,1e-6*Math.abs(meanDeviances)); } finally { if (tfr != null) tfr.delete(); if (res != null) res.delete(); if (preds != null) preds.delete(); if (gbm != null) gbm.delete(); } } } /** * train = data.frame(c('red', 'blue','blue'),c('x','x','y'),c(1,'0','0')) names(train)= c('color', 'letter', 'label') test = data.frame(c('red', 'blue','blue','yellow'),c('x','x','y','y'),c(1,'0','0','0')) names(test)= c('color', 'letter', 'label') htrain = as.h2o(train) htest = as.h2o(test) hh = h2o.glm(x = 1:2,y = 3,training_frame = htrain,family = "binomial",max_iterations = 15,alpha = 1,missing_values_handling = 'Skip') h2o.predict(hh,htest) */ @Test public void testUnseenLevels(){ Scope.enter(); try { Vec v0 = Vec.makeCon(Vec.newKey(), 1, 0, 0, 1,1); v0.setDomain(new String[]{"blue", "red"}); Frame trn = new Frame(Key.<Frame>make("train"), new String[]{"color", "label"}, new Vec[]{v0, v0.makeCopy(null)}); DKV.put(trn); Vec v3 = Vec.makeCon(Vec.newKey(), 1, 0, 0, 2); v3.setDomain(new String[]{"blue", "red", "yellow"}); Vec v5 = Vec.makeCon(v3.group().addVec(), 1, 0, 0, 0); Frame tst = new Frame(Key.<Frame>make("test"), new String[]{"color", "label"}, new Vec[]{v3, v5}); DKV.put(tst); GLMParameters parms = new GLMParameters(Family.gaussian); parms._train = trn._key; parms._response_column = "label"; parms._missing_values_handling = MissingValuesHandling.Skip; GLMParameters parms2 = (GLMParameters) parms.clone(); GLMModel m = new GLM(parms).trainModel().get(); System.out.println("coefficients = " + m.coefficients()); double icpt = m.coefficients().get("Intercept"); Frame preds = m.score(tst); Assert.assertEquals(icpt+m.coefficients().get("color.red"), preds.vec(0).at(0), 0); Assert.assertEquals(icpt+m.coefficients().get("color.blue"), preds.vec(0).at(1), 0); Assert.assertEquals(icpt+m.coefficients().get("color.blue"), preds.vec(0).at(2), 0); Assert.assertEquals(icpt, preds.vec(0).at(3), 0); parms2._missing_values_handling = MissingValuesHandling.MeanImputation; GLMModel m2 = new GLM(parms2).trainModel().get(); Frame preds2 = m2.score(tst); icpt = m2.coefficients().get("Intercept"); System.out.println("coefficients = " + m2.coefficients()); Assert.assertEquals(icpt+m2.coefficients().get("color.red"), preds2.vec(0).at(0), 0); Assert.assertEquals(icpt+m2.coefficients().get("color.blue"), preds2.vec(0).at(1), 0); Assert.assertEquals(icpt+m2.coefficients().get("color.blue"), preds2.vec(0).at(2), 0); Assert.assertEquals(icpt+m2.coefficients().get("color.red"), preds2.vec(0).at(3), 0); trn.delete(); tst.delete(); m.delete(); preds.delete(); preds2.delete(); m2.delete(); }finally { Scope.exit(); } } @Test public void testIsFeatureUsedInPredict() { isFeatureUsedInPredictHelper(false, false); isFeatureUsedInPredictHelper(true, false); isFeatureUsedInPredictHelper(false, true); isFeatureUsedInPredictHelper(true, true); } private void isFeatureUsedInPredictHelper(boolean ignoreConstCols, boolean multinomial) { Scope.enter(); Vec target = Vec.makeRepSeq(100, 3); if (multinomial) target = target.toCategoricalVec(); Vec zeros = Vec.makeCon(0d, 100); Vec nonzeros = Vec.makeCon(1e10d, 100); Frame dummyFrame = new Frame( new String[]{"a", "b", "c", "d", "e", "target"}, new Vec[]{zeros, zeros, zeros, zeros, target, target} ); dummyFrame._key = Key.make("DummyFrame_testIsFeatureUsedInPredict"); Frame otherFrame = new Frame( new String[]{"a", "b", "c", "d", "e", "target"}, new Vec[]{nonzeros, nonzeros, nonzeros, nonzeros, target, target} ); Frame reference = null; Frame prediction = null; GLMModel model = null; try { DKV.put(dummyFrame); GLMModel.GLMParameters glm = new GLMModel.GLMParameters(); glm._train = dummyFrame._key; glm._response_column = "target"; glm._seed = 1; glm._ignore_const_cols = ignoreConstCols; if (multinomial) { glm._family = Family.multinomial; } GLM job = new GLM(glm); model = job.trainModel().get(); String lastUsedFeature = ""; int usedFeatures = 0; for(String feature : model._output._names) { if (model.isFeatureUsedInPredict(feature)) { usedFeatures ++; lastUsedFeature = feature; } } assertEquals(1, usedFeatures); assertEquals("e", lastUsedFeature); reference = model.score(dummyFrame); prediction = model.score(otherFrame); for (int i = 0; i < reference.numRows(); i++) { assertEquals(reference.vec(0).at(i), prediction.vec(0).at(i), 1e-10); } } finally { dummyFrame.delete(); if (model != null) model.delete(); if (reference != null) reference.delete(); if (prediction != null) prediction.delete(); target.remove(); zeros.remove(); nonzeros.remove(); Scope.exit(); } } /** * testBounds() from this file adjusted to use AGE as categorical column */ @Test public void testBoundsCategoricalCol() { Scope.enter(); Key parsed = Key.make("prostate_parsed"); Key modelKey = Key.make("prostate_model"); Frame fr = Scope.track(parse_test_file(parsed, "smalldata/logreg/prostate.csv")); fr.toCategoricalCol("AGE"); Key betaConsKey = Key.make("beta_constraints"); FVecFactory.makeByteVec(betaConsKey, "names, lower_bounds, upper_bounds\n AGE, -.5, .5\n RACE, -.5, .5\n DCAPS, -.4, .4\n DPROS, -.5, .5 \nPSA, -.5, .5\n VOL, -.5, .5\nGLEASON, -.5, .5"); Frame betaConstraints = Scope.track(ParseDataset.parse(Key.make("beta_constraints.hex"), betaConsKey)); try { // H2O differs on intercept and race, same residual deviance though GLMParameters params = new GLMParameters(); params._standardize = true; params._family = Family.binomial; params._beta_constraints = betaConstraints._key; params._response_column = "CAPSULE"; params._ignored_columns = new String[]{"ID"}; params._train = fr._key; params._objective_epsilon = 0; params._alpha = new double[]{1}; params._lambda = new double[]{0.001607}; params._obj_reg = 1.0/380; GLM glm = new GLM( params, modelKey); GLMModel model = glm.trainModel().get(); Scope.track_generic(model); assertTrue(glm.isStopped()); ModelMetricsBinomialGLM val = (ModelMetricsBinomialGLM) model._output._training_metrics; assertEquals(512.2888, val._nullDev, 1e-1); assertTrue(val._resDev <= 388.5); model.delete(); params._lambda = new double[]{0}; params._alpha = new double[]{0}; FVecFactory.makeByteVec(betaConsKey, "names, lower_bounds, upper_bounds\n RACE, -.5, .5\n DCAPS, -.4, .4\n DPROS, -.5, .5 \nPSA, -.5, .5\n VOL, -.5, .5\n AGE, -.5, .5"); betaConstraints = ParseDataset.parse(Key.make("beta_constraints.hex"), betaConsKey); glm = new GLM( params, modelKey); model = glm.trainModel().get(); Scope.track_generic(model); assertTrue(glm.isStopped()); double[] beta = model.beta(); System.out.println("beta = " + Arrays.toString(beta)); fr.add("CAPSULE", fr.remove("CAPSULE")); fr.remove("ID").remove(); DKV.put(fr._key, fr); DataInfo dinfo = new DataInfo(fr, null, 1, true, TransformType.NONE, DataInfo.TransformType.NONE, true, false, false, false, false, false); GLMGradientTask lt = new GLMBinomialGradientTask(null,dinfo,params,0,beta).doAll(dinfo._adaptedFrame); double [] grad = lt._gradient; String [] names = model.dinfo().coefNames(); BufferedString tmpStr = new BufferedString(); outer: for (int i = 0; i < names.length; ++i) { for (int j = 0; j < betaConstraints.numRows(); ++j) { if (betaConstraints.vec("names").atStr(tmpStr, j).toString().equals(names[i])) { if (Math.abs(beta[i] - betaConstraints.vec("lower_bounds").at(j)) < 1e-4 || Math.abs(beta[i] - betaConstraints.vec("upper_bounds").at(j)) < 1e-4) { continue outer; } } } assertEquals(0, grad[i], 1e-2); } } finally { Scope.exit(); } } }
h2o-algos/src/test/java/hex/glm/GLMTest.java
package hex.glm; import hex.*; import hex.DataInfo.TransformType; import hex.genmodel.algos.glm.GlmMojoModel; import hex.glm.GLMModel.GLMParameters.MissingValuesHandling; import hex.glm.GLMModel.GLMParameters; import hex.glm.GLMModel.GLMParameters.Family; import hex.glm.GLMModel.GLMParameters.Link; import hex.glm.GLMModel.GLMParameters.Solver; import hex.glm.GLMModel.GLMWeightsFun; import hex.glm.GLMTask.*; import org.junit.Assert; import org.junit.BeforeClass; import org.junit.Ignore; import org.junit.Test; import water.*; import water.H2O.H2OCountedCompleter; import water.fvec.*; import water.parser.BufferedString; import water.parser.ParseDataset; import water.util.ArrayUtils; import java.util.Arrays; import java.util.HashMap; import java.util.Random; import java.util.concurrent.ExecutionException; import static hex.genmodel.utils.ArrayUtils.flat; import static org.junit.Assert.*; public class GLMTest extends TestUtil { @BeforeClass public static void setup() { stall_till_cloudsize(1); } public static void testScoring(GLMModel m, Frame fr) { Scope.enter(); // try scoring without response Frame fr2 = new Frame(fr); fr2.remove(m._output.responseName()); // Frame preds0 = Scope.track(m.score(fr2)); // fr2.add(m._output.responseName(),fr.vec(m._output.responseName())); // standard predictions Frame preds = Scope.track(m.score(fr2)); m.adaptTestForTrain(fr2,true,false); fr2.remove(fr2.numCols()-1); // remove response int p = m._output._dinfo._cats + m._output._dinfo._nums; int p2 = fr2.numCols() - (m._output._dinfo._weights?1:0)- (m._output._dinfo._offset?1:0); assert p == p2: p + " != " + p2; fr2.add(preds.names(),preds.vecs()); // test score0 new TestScore0(m,m._output._dinfo._weights,m._output._dinfo._offset).doAll(fr2); // test pojo if((!m._output._dinfo._weights && !m._output._dinfo._offset)) Assert.assertTrue(m.testJavaScoring(fr,preds,1e-15)); Scope.exit(); } // class to test score0 since score0 is now not being called by the standard bulk scoring public static class TestScore0 extends MRTask { final GLMModel _m; final boolean _weights; final boolean _offset; public TestScore0(GLMModel m, boolean w, boolean o) {_m = m; _weights = w; _offset = o;} private void checkScore(long rid, double [] predictions, double [] outputs){ int start = 0; if(_m._parms._family == Family.binomial && Math.abs(predictions[2] - _m.defaultThreshold()) < 1e-10) start = 1; if(_m._parms._family == Family.multinomial) { double [] maxs = new double[2]; for(int j = 1; j < predictions.length; ++j) { if(predictions[j] > maxs[0]) { if(predictions[j] > maxs[1]) { maxs[0] = maxs[1]; maxs[1] = predictions[j]; } else maxs[0] = predictions[j]; } } if((maxs[1] - maxs[0]) < 1e-10) start = 1; } for (int j = start; j < predictions.length; ++j) assertEquals("mismatch at row " + (rid) + ", p = " + j + ": " + outputs[j] + " != " + predictions[j] + ", predictions = " + Arrays.toString(predictions) + ", output = " + Arrays.toString(outputs), outputs[j], predictions[j], 1e-6); } @Override public void map(Chunk [] chks) { int nout = _m._parms._family == Family.multinomial ? _m._output.nclasses() + 1 : _m._parms._family == Family.binomial ? 3 : 1; Chunk[] outputChks = Arrays.copyOfRange(chks, chks.length - nout, chks.length); chks = Arrays.copyOf(chks, chks.length - nout); Chunk off = new C0DChunk(0, chks[0]._len); double[] tmp = new double[_m._output._dinfo._cats + _m._output._dinfo._nums]; double[] predictions = new double[nout]; double[] outputs = new double[nout]; if (_offset) { off = chks[chks.length - 1]; chks = Arrays.copyOf(chks, chks.length - 1); } if (_weights) { chks = Arrays.copyOf(chks, chks.length - 1); } for (int i = 0; i < chks[0]._len; ++i) { if (_weights || _offset) _m.score0(chks, off.atd(i), i, tmp, predictions); else _m.score0(chks, i, tmp, predictions); for (int j = 0; j < predictions.length; ++j) outputs[j] = outputChks[j].atd(i); checkScore(i + chks[0].start(), predictions, outputs); } } } @Test public void testStandardizedCoeff() { // test for multinomial testCoeffs(Family.multinomial, "smalldata/glm_test/multinomial_10_classes_10_cols_10000_Rows_train.csv", "C11"); // test for binomial testCoeffs(Family.binomial, "smalldata/glm_test/binomial_20_cols_10KRows.csv", "C21"); // test for Gaussian testCoeffs(Family.gaussian, "smalldata/glm_test/gaussian_20cols_10000Rows.csv", "C21"); } public void testCoeffs(Family family, String fileName, String responseColumn) { try { Scope.enter(); Frame train = parse_test_file(fileName); // set cat columns int numCols = train.numCols(); int enumCols = (numCols-1)/2; for (int cindex=0; cindex<enumCols; cindex++) { train.replace(cindex, train.vec(cindex).toCategoricalVec()).remove(); } int response_index = numCols-1; if (family.equals(Family.binomial) || (family.equals(Family.multinomial))) { train.replace((response_index), train.vec(response_index).toCategoricalVec()).remove(); } DKV.put(train); Scope.track(train); GLMParameters params = new GLMParameters(family); params._standardize=true; params._response_column = responseColumn; params._train = train._key; GLMModel glm = new GLM(params).trainModel().get(); Scope.track_generic(glm); // standardize numerical columns of train int numStart = enumCols; // start of numerical columns int[] numCols2Transform = new int[enumCols]; double[] colMeans = new double[enumCols]; double[] oneOSigma = new double[enumCols]; int countIndex = 0; HashMap<String, Double> cMeans = new HashMap<>(); HashMap<String, Double> cSigmas = new HashMap<>(); String[] cnames = train.names(); for (int cindex = numStart; cindex < response_index; cindex++) { numCols2Transform[countIndex]=cindex; colMeans[countIndex] = train.vec(cindex).mean(); oneOSigma[countIndex] = 1.0/train.vec(cindex).sigma(); cMeans.put(cnames[cindex], colMeans[countIndex]); cSigmas.put(cnames[cindex], train.vec(cindex).sigma()); countIndex++; } params._standardize = false; // build a model on non-standardized columns with no standardization. GLMModel glmF = new GLM(params).trainModel().get(); Scope.track_generic(glmF); HashMap<String, Double> coeffSF = glmF.coefficients(true); HashMap<String, Double> coeffF = glmF.coefficients(); if (family.equals(Family.multinomial)) { double[] interPClass = new double[glmF._output._nclasses]; for (String key : coeffSF.keySet()) { double temp1 = coeffSF.get(key); double temp2 = coeffF.get(key); if (Math.abs(temp1 - temp2) > 1e-6) { // coefficient same for categoricals, different for numericals String[] coNames = key.split("_"); if (!(coNames[0].equals("Intercept"))) { // skip over intercepts String colnames = coNames[0]; interPClass[Integer.valueOf(coNames[1])] += temp2 * cMeans.get(colnames); temp2 = temp2 * cSigmas.get(colnames); assert Math.abs(temp1 - temp2) < 1e-6 : "Expected coefficients for " + coNames[0] + " is " + temp1 + " but actual " + temp2; } } } // check for equality of intercepts for (int index = 0; index < glmF._output._nclasses; index++) { String interceptKey = "Intercept_" + index; double temp1 = coeffSF.get(interceptKey); double temp2 = coeffF.get(interceptKey) + interPClass[index]; assert Math.abs(temp1 - temp2) < 1e-6 : "Expected coefficients for " + interceptKey + " is " + temp1 + " but actual " + temp2; } } else { double interceptOffset = 0; for (String key:coeffF.keySet()) { double temp1 = coeffSF.get(key); double temp2 = coeffF.get(key); if (Math.abs(temp1 - temp2) > 1e-6) { if (!key.equals("Intercept")) { interceptOffset += temp2*cMeans.get(key); temp2 = temp2*cSigmas.get(key); assert Math.abs(temp1 - temp2) < 1e-6 : "Expected coefficients for " + key + " is " + temp1 + " but actual " + temp2; } } } // check intercept terms double temp1 = coeffSF.get("Intercept"); double temp2 = coeffF.get("Intercept")+interceptOffset; assert Math.abs(temp1 - temp2) < 1e-6 : "Expected coefficients for Intercept is " + temp1 + " but actual " + temp2; } new TestUtil.StandardizeColumns(numCols2Transform, colMeans, oneOSigma, train).doAll(train); DKV.put(train); Scope.track(train); params._standardize=false; params._train = train._key; GLMModel glmS = new GLM(params).trainModel().get(); Scope.track_generic(glmS); if (family.equals(Family.multinomial)) { double[][] coeff1 = glm._output.getNormBetaMultinomial(); double[][] coeff2 = glmS._output.getNormBetaMultinomial(); for (int classind = 0; classind < coeff1.length; classind++) { assert TestUtil.equalTwoArrays(coeff1[classind], coeff2[classind], 1e-6); } } else { assert TestUtil.equalTwoArrays(glm._output.getNormBeta(), glmS._output.getNormBeta(), 1e-6); } HashMap<String, Double> coeff1 = glm.coefficients(true); HashMap<String, Double> coeff2 = glmS.coefficients(true); assert TestUtil.equalTwoHashMaps(coeff1, coeff2, 1e-6); } finally { Scope.exit(); } } //------------------- simple tests on synthetic data------------------------------------ @Test public void testGaussianRegression() throws InterruptedException, ExecutionException { Key raw = Key.make("gaussian_test_data_raw"); Key parsed = Key.make("gaussian_test_data_parsed"); GLMModel model = null; Frame fr = null, res = null; for (Family family : new Family[]{Family.gaussian, Family.AUTO}) { try { // make data so that the expected coefficients is icept = col[0] = 1.0 FVecFactory.makeByteVec(raw, "x,y\n0,0\n1,0.1\n2,0.2\n3,0.3\n4,0.4\n5,0.5\n6,0.6\n7,0.7\n8,0.8\n9,0.9"); fr = ParseDataset.parse(parsed, raw); GLMParameters params = new GLMParameters(family); params._train = fr._key; // params._response = 1; params._response_column = fr._names[1]; params._lambda = new double[]{0}; // params._standardize= false; model = new GLM(params).trainModel().get(); HashMap<String, Double> coefs = model.coefficients(); assertEquals(0.0, coefs.get("Intercept"), 1e-4); assertEquals(0.1, coefs.get("x"), 1e-4); testScoring(model,fr); } finally { if (fr != null) fr.remove(); if (res != null) res.remove(); if (model != null) model.remove(); } } } /** * Test Poisson regression on simple and small synthetic dataset. * Equation is: y = exp(x+1); */ @Test public void testPoissonRegression() throws InterruptedException, ExecutionException { Key raw = Key.make("poisson_test_data_raw"); Key parsed = Key.make("poisson_test_data_parsed"); GLMModel model = null; Frame fr = null, res = null; try { // make data so that the expected coefficients is icept = col[0] = 1.0 FVecFactory.makeByteVec(raw, "x,y\n0,2\n1,4\n2,8\n3,16\n4,32\n5,64\n6,128\n7,256"); fr = ParseDataset.parse(parsed, raw); Vec v = fr.vec(0); System.out.println(v.min() + ", " + v.max() + ", mean = " + v.mean()); GLMParameters params = new GLMParameters(Family.poisson); params._train = fr._key; // params._response = 1; params._response_column = fr._names[1]; params._lambda = new double[]{0}; params._standardize = false; model = new GLM(params).trainModel().get(); for (double c : model.beta()) assertEquals(Math.log(2), c, 1e-2); // only 1e-2 precision cause the perfect solution is too perfect -> will trigger grid search testScoring(model,fr); model.delete(); fr.delete(); // Test 2, example from http://www.biostat.umn.edu/~dipankar/bmtry711.11/lecture_13.pdf FVecFactory.makeByteVec(raw, "x,y\n1,0\n2,1\n3,2\n4,3\n5,1\n6,4\n7,9\n8,18\n9,23\n10,31\n11,20\n12,25\n13,37\n14,45\n150,7.193936e+16\n"); fr = ParseDataset.parse(parsed, raw); GLMParameters params2 = new GLMParameters(Family.poisson); params2._train = fr._key; // params2._response = 1; params2._response_column = fr._names[1]; params2._lambda = new double[]{0}; params2._standardize = true; params2._beta_epsilon = 1e-5; model = new GLM(params2).trainModel().get(); assertEquals(0.3396, model.beta()[1], 1e-1); assertEquals(0.2565, model.beta()[0], 1e-1); // test scoring testScoring(model,fr); } finally { if (fr != null) fr.delete(); if (res != null) res.delete(); if (model != null) model.delete(); } } /** * Test Gamma regression on simple and small synthetic dataset. * Equation is: y = 1/(x+1); * * @throws ExecutionException * @throws InterruptedException */ @Test public void testGammaRegression() throws InterruptedException, ExecutionException { GLMModel model = null; Frame fr = null, res = null; try { // make data so that the expected coefficients is icept = col[0] = 1.0 Key raw = Key.make("gamma_test_data_raw"); Key parsed = Key.make("gamma_test_data_parsed"); FVecFactory.makeByteVec(raw, "x,y\n0,1\n1,0.5\n2,0.3333333\n3,0.25\n4,0.2\n5,0.1666667\n6,0.1428571\n7,0.125"); fr = ParseDataset.parse(parsed, raw); // /public GLM2(String desc, Key dest, Frame src, Family family, Link link, double alpha, double lambda) { // double [] vals = new double[] {1.0,1.0}; //public GLM2(String desc, Key dest, Frame src, Family family, Link link, double alpha, double lambda) { GLMParameters params = new GLMParameters(Family.gamma); // params._response = 1; params._response_column = fr._names[1]; params._train = parsed; params._lambda = new double[]{0}; model = new GLM(params).trainModel().get(); for (double c : model.beta()) assertEquals(1.0, c, 1e-4); // test scoring testScoring(model,fr); } finally { if (fr != null) fr.delete(); if (res != null) res.delete(); if (model != null) model.delete(); } } //// //simple tweedie test // @Test public void testTweedieRegression() throws InterruptedException, ExecutionException{ // Key raw = Key.make("gaussian_test_data_raw"); // Key parsed = Key.make("gaussian_test_data_parsed"); // Key<GLMModel> modelKey = Key.make("gaussian_test"); // Frame fr = null; // GLMModel model = null; // try { // // make data so that the expected coefficients is icept = col[0] = 1.0 // FVecFactory.makeByteVec(raw, "x,y\n0,0\n1,0.1\n2,0.2\n3,0.3\n4,0.4\n5,0.5\n6,0.6\n7,0.7\n8,0.8\n9,0.9\n0,0\n1,0\n2,0\n3,0\n4,0\n5,0\n6,0\n7,0\n8,0\n9,0"); // fr = ParseDataset.parse(parsed, new Key[]{raw}); // double [] powers = new double [] {1.5,1.1,1.9}; // double [] intercepts = new double []{3.643,1.318,9.154}; // double [] xs = new double []{-0.260,-0.0284,-0.853}; // for(int i = 0; i < powers.length; ++i){ // DataInfo dinfo = new DataInfo(fr, 1, false, DataInfo.TransformType.NONE); // GLMParameters glm = new GLMParameters(Family.tweedie); // // new GLM2("GLM test of gaussian(linear) regression.",Key.make(),modelKey,dinfo,glm,new double[]{0},0).fork().get(); // model = DKV.get(modelKey).get(); // testHTML(model); // HashMap<String, Double> coefs = model.coefficients(); // assertEquals(intercepts[i],coefs.get("Intercept"),1e-3); // assertEquals(xs[i],coefs.get("x"),1e-3); // } // }finally{ // if( fr != null ) fr.delete(); // if(model != null)model.delete(); // } // } @Test public void testAllNAs() { Key raw = Key.make("gamma_test_data_raw"); Key parsed = Key.make("gamma_test_data_parsed"); FVecFactory.makeByteVec(raw, "x,y,z\n1,0,NA\n2,NA,1\nNA,3,2\n4,3,NA\n5,NA,1\nNA,6,4\n7,NA,9\n8,NA,18\nNA,9,23\n10,31,NA\nNA,11,20\n12,NA,25\nNA,13,37\n14,45,NA\n"); Frame fr = ParseDataset.parse(parsed, raw); GLM job = null; try { GLMParameters params = new GLMParameters(Family.poisson); // params._response = 1; params._response_column = fr._names[1]; params._train = parsed; params._lambda = new double[]{0}; params._missing_values_handling = MissingValuesHandling.Skip; GLM glm = new GLM( params); glm.trainModel().get(); assertFalse("should've thrown IAE", true); } catch (IllegalArgumentException e) { assertTrue(e.getMessage(), e.getMessage().contains("No rows left in the dataset")); } finally { fr.delete(); } } // Make sure all three implementations of ginfo computation in GLM get the same results @Test public void testGradientTask() { Key parsed = Key.make("cars_parsed"); Frame fr = null; DataInfo dinfo = null; try { fr = parse_test_file(parsed, "smalldata/junit/mixcat_train.csv"); GLMParameters params = new GLMParameters(Family.binomial, Family.binomial.defaultLink, new double[]{0}, new double[]{0}, 0, 0); // params._response = fr.find(params._response_column); params._train = parsed; params._lambda = new double[]{0}; params._use_all_factor_levels = true; fr.add("Useless", fr.remove("Useless")); dinfo = new DataInfo(fr, null, 1, params._use_all_factor_levels || params._lambda_search, params._standardize ? DataInfo.TransformType.STANDARDIZE : DataInfo.TransformType.NONE, DataInfo.TransformType.NONE, true, false, false, false, false, false); DKV.put(dinfo._key,dinfo); double [] beta = MemoryManager.malloc8d(dinfo.fullN()+1); Random rnd = new Random(987654321); for (int i = 0; i < beta.length; ++i) beta[i] = 1 - 2 * rnd.nextDouble(); GLMGradientTask grtSpc = new GLMBinomialGradientTask(null,dinfo, params, params._lambda[0], beta).doAll(dinfo._adaptedFrame); GLMGradientTask grtGen = new GLMGenericGradientTask(null,dinfo, params, params._lambda[0], beta).doAll(dinfo._adaptedFrame); for (int i = 0; i < beta.length; ++i) assertEquals("gradients differ", grtSpc._gradient[i], grtGen._gradient[i], 1e-4); params = new GLMParameters(Family.gaussian, Family.gaussian.defaultLink, new double[]{0}, new double[]{0}, 0, 0); params._use_all_factor_levels = false; dinfo.remove(); dinfo = new DataInfo(fr, null, 1, params._use_all_factor_levels || params._lambda_search, params._standardize ? DataInfo.TransformType.STANDARDIZE : DataInfo.TransformType.NONE, DataInfo.TransformType.NONE, true, false, false, false, false, false); DKV.put(dinfo._key,dinfo); beta = MemoryManager.malloc8d(dinfo.fullN()+1); rnd = new Random(1987654321); for (int i = 0; i < beta.length; ++i) beta[i] = 1 - 2 * rnd.nextDouble(); grtSpc = new GLMGaussianGradientTask(null,dinfo, params, params._lambda[0], beta).doAll(dinfo._adaptedFrame); grtGen = new GLMGenericGradientTask(null,dinfo, params, params._lambda[0], beta).doAll(dinfo._adaptedFrame); for (int i = 0; i < beta.length; ++i) assertEquals("gradients differ: " + Arrays.toString(grtSpc._gradient) + " != " + Arrays.toString(grtGen._gradient), grtSpc._gradient[i], grtGen._gradient[i], 1e-4); dinfo.remove(); } finally { if (fr != null) fr.delete(); if (dinfo != null) dinfo.remove(); } } @Test public void testMultinomialGradient(){ Key parsed = Key.make("covtype"); Frame fr = null; double [][] beta = new double[][]{ { 5.886754459, -0.270479620, -0.075466082, -0.157524534, -0.225843747, -0.975387326, -0.018808013, -0.597839451, 0.931896624, 1.060006010, 1.513888539, 0.588802780, 0.157815155, -2.158268564, -0.504962385, -1.218970183, -0.840958642, -0.425931637, -0.355548831, -0.845035489, -0.065364107, 0.215897656, 0.213009374, 0.006831714, 1.212368946, 0.006106444, -0.350643486, -0.268207009, -0.252099054, -1.374010836, 0.257935860, 0.397459631, 0.411530391, 0.728368253, 0.292076224, 0.170774269, -0.059574793, 0.273670163, 0.180844505, -0.186483071, 0.369186813, 0.161909512, 0.249411716, -0.094481604, 0.413354360, -0.419043967, 0.044517794, -0.252596992, -0.371926422, 0.253835004, 0.588162090, 0.123330837, 2.856812217 }, { 1.89790254, -0.29776886, 0.15613197, 0.37602123, -0.36464436, -0.30240244, -0.57284370, 0.62408956, -0.22369305, 0.33644602, 0.79886400, 0.65351945, -0.53682819, -0.58319898, -1.07762513, -0.28527470, 0.46563482, -0.76956081, -0.72513805, 0.29857876, 0.03993456, 0.15835864, -0.24797599, -0.02483503, 0.93822490, -0.12406087, -0.75837978, -0.23516944, -0.48520212, 0.73571466, 0.19652011, 0.21602846, -0.32743154, 0.49421903, -0.02262943, 0.08093216, 0.11524497, 0.21657128, 0.18072853, 0.30872666, 0.17947687, 0.20156151, 0.16812179, -0.12286908, 0.29630502, 0.09992565, -0.00603293, 0.20700058, -0.49706211, -0.14534034, -0.18819217, 0.03642680, 7.31828340 }, { -6.098728943, 0.284144173, 0.114373474, 0.328977319, 0.417830082, 0.285696150, -0.652674822, 0.319136906, -0.942440279, -1.619235397, -1.272568201, -0.079855555, 1.191263550, 0.205102353, 0.991773314, 0.930363203, 1.014021007, 0.651243292, 0.646532457, 0.914336030, 0.012171754, -0.053042102, 0.777710362, 0.527369151, -0.019496049, 0.186290583, 0.554926655, 0.476911685, 0.529207520, -0.133243060, -0.198957274, -0.561552913, -0.069239959, -0.236600870, -0.969503908, -0.848089244, 0.001498592, -0.241007311, -0.129271912, -0.259961677, -0.895676033, -0.865827509, -0.972629899, 0.307756211, -1.809423763, -0.199557594, 0.024221965, -0.024834485, 0.047044475, 0.028951561, -0.157701002, 0.007940593, -2.073329675, }, { -8.36044440, 0.10541672, -0.01628680, -0.43787017, 0.42383466, 2.45802808, 0.59818831, 0.61971728, -0.62598983, 0.20261555, -0.21909545, 0.35125447, -3.29155913, 3.74668257, 0.18126128, -0.13948924, 0.20465077, -0.39930635, 0.15704570, -0.01036891, 0.02822546, -0.02349234, -0.93922249, -0.20025910, 0.25184125, 0.06415974, 0.35271290, 0.04609060, 0.03018497, -0.10641540, 0.00354805, -0.12194129, 0.05115876, 0.23981864, -0.10007012, 0.04773226, 0.01217421, 0.02367464, 0.05552397, 0.05343606, -0.05818705, -0.30055029, -0.03898723, 0.02322906, -0.04908215, 0.04274038, 0.25045428, 0.08561191, 0.15228160, 0.67005377, 0.59311621, 0.58814959, -4.83776046 }, { -0.39251919, 0.07053038, 0.09397355, 0.19394977, -0.02030732, -0.87489691, 0.21295049, 0.31800509, -0.05347208, -1.03491602, 2.20106706, -1.20895873, 1.06158893, -3.29214054, -0.69334082, 0.62309414, -1.64753442, 0.10189669, -0.44746013, -1.04084383, -0.01997483, -0.23356180, 0.34384724, 0.37566329, -1.79316510, 0.46183758, -0.58814389, 0.12072985, 0.48349078, 1.18956325, 0.41962148, 0.18767160, -0.25252495, -1.13671540, 0.71488183, 0.27405258, -0.03527945, 0.43124949, -0.28740586, 0.35165348, 1.17594079, 1.13893507, 0.49423372, 0.30525649, 0.70809680, 0.16660330, -0.37726163, -0.14687217, -0.17079711, -1.01897715, -1.17494223, -0.72698683, 1.64022531 }, { -5.892381502, 0.295534637, -0.112763568, 0.080283203, 0.197113227, 0.525435203, 0.727252262, -1.190672917, 1.137103389, -0.648526151, -2.581362158, -0.268338673, 2.010179009, 0.902074450, 0.816138328, 0.557071470, 0.389932578, 0.009422297, 0.542270816, 0.550653667, 0.005211720, -0.071954379, 0.320008238, 0.155814784, -0.264213966, 0.320538295, 0.569730803, 0.444518874, 0.247279544, -0.319484330, -0.372129988, 0.340944707, -0.158424299, -0.479426774, 0.026966661, 0.273389077, -0.004744599, -0.339321329, -0.119323949, -0.210123558, -1.218998166, -0.740525896, 0.134778587, 0.252701229, 0.527468284, 0.214164427, -0.080104361, -0.021448994, 0.004509104, -0.189729053, -0.335041198, -0.080698796, -1.192518082 }, { 12.9594170391, -0.1873774300, -0.1599625360, -0.3838368119, -0.4279825390, -1.1164727575, -0.2940645257, -0.0924364781, -0.2234047720, 1.7036099945, -0.4407937881, -0.0364237384, -0.5924593214, 1.1797487023, 0.2867554171, -0.4667946900, 0.4142538835, 0.8322365174, 0.1822980332, 0.1326797653, -0.0002045542, 0.0077943238, -0.4673767424, -0.8405848140, -0.3255599769, -0.9148717663, 0.2197967986, -0.5848745645, -0.5528616430, 0.0078757154, -0.3065382365, -0.4586101971, 0.3449315968, 0.3903371200, 0.0582787537, 0.0012089013, -0.0293189213, -0.3648369414, 0.1189047254, -0.0572478953, 0.4482567793, 0.4044976082, -0.0349286763, -0.6715923088, -0.0867185553, 0.0951677966, 0.1442048837, 0.1531401571, 0.8359504674, 0.4012062075, 0.6745982951, 0.0518378060, -3.7117127004 } }; double [] exp_grad = new double[]{ -8.955455e-05, 6.429112e-04, 4.384381e-04, 1.363695e-03, 4.714468e-04, -2.264769e-03, 4.412849e-04, 1.461760e-03, -2.957754e-05, -2.244325e-03, -2.744438e-03, 9.109376e-04, 1.920764e-03, 7.562221e-04, 1.840414e-04, 2.455081e-04, 3.077885e-04, 2.833261e-04, 1.248686e-04, 2.509248e-04, 9.681260e-06, -1.097335e-04, 1.005934e-03, 5.623159e-04, -2.568397e-03, 1.113900e-03, 1.263858e-04, 9.075801e-05, 8.056571e-05, 1.848318e-04, -1.291357e-04, -3.710570e-04, 5.693621e-05, 1.328082e-04, 3.244018e-04, 4.130594e-04, 9.681066e-06, 5.215260e-04, 4.054695e-04, 2.904901e-05, -3.074865e-03, -1.247025e-04, 1.044981e-03, 8.612937e-04, 1.376526e-03, 4.543256e-05, -4.596319e-06, 3.062111e-05, 5.649646e-05, 5.392599e-04, 9.681357e-04, 2.298219e-04, -1.369109e-03, -6.884926e-04, -9.921529e-04, -5.369346e-04, -1.732447e-03, 5.677645e-04, 1.655432e-03, -4.786890e-04, -8.688757e-04, 2.922016e-04, 3.601210e-03, 4.050781e-03, -6.409806e-04, -2.788663e-03, -1.426483e-03, -1.946904e-04, -8.279536e-04, -3.148338e-04, 2.263577e-06, -1.320917e-04, 3.635088e-04, -1.024655e-05, 1.079612e-04, -1.607591e-03, -1.801967e-04, 2.548311e-03, -1.007139e-03, -1.336990e-04, 2.538803e-04, -4.851292e-04, -9.168206e-04, 1.027708e-04, 1.061545e-03, -4.098038e-05, 1.070448e-04, 3.220238e-04, -7.011285e-04, -1.024153e-05, -7.967380e-04, -2.708138e-04, -2.698165e-04, 3.088978e-03, 4.260939e-04, -5.868815e-04, -1.562233e-03, -1.007565e-03, -2.034456e-04, -6.198011e-04, -3.277194e-05, -5.976557e-05, -1.143198e-03, -1.025416e-03, 3.671158e-04, 1.448332e-03, 1.940231e-03, -6.130695e-04, -2.086460e-03, -2.969848e-04, 1.455597e-04, 1.745515e-03, 2.123991e-03, 9.036201e-04, -5.270206e-04, 1.053891e-03, 1.358911e-03, 2.528711e-04, 1.326987e-04, -1.825879e-03, -6.085616e-04, -1.347628e-04, 3.499544e-04, 3.616313e-04, -7.008672e-04, -1.211077e-03, 1.117824e-05, 3.535679e-05, -2.668903e-03, -2.399884e-04, 3.979678e-04, 2.519517e-04, 1.113206e-04, 6.029871e-04, 3.512828e-04, 2.134159e-04, 7.590052e-05, 1.729959e-04, 4.472972e-05, 2.094373e-04, 3.136961e-04, 1.835530e-04, 1.117824e-05, 8.225263e-05, 4.330828e-05, 3.354142e-05, 7.452883e-04, 4.631413e-04, 2.054077e-04, -5.520636e-05, 2.818063e-04, 5.246077e-05, 1.131811e-04, 3.535664e-05, 6.523360e-05, 3.072416e-04, 2.913399e-04, 2.422760e-04, -1.580841e-03, -1.117356e-04, 2.573351e-04, 8.117137e-04, 1.168873e-04, -4.216143e-04, -5.847717e-05, 3.501109e-04, 2.344622e-04, -1.330097e-04, -5.948309e-04, -2.349808e-04, -4.495448e-05, -1.916493e-04, 5.017336e-04, -8.440468e-05, 4.767465e-04, 2.485018e-04, 2.060573e-04, -1.527142e-04, -9.268231e-06, -1.985972e-06, -6.285478e-06, -2.214673e-05, 5.822250e-04, -7.069316e-05, -4.387924e-05, -2.774128e-04, -5.455282e-04, 3.186328e-04, -3.793242e-05, -1.349306e-05, -3.070112e-05, -7.951882e-06, -3.723186e-05, -5.571437e-05, -3.260780e-05, -1.987225e-06, -1.462245e-05, -7.699184e-06, -5.962867e-06, -1.316053e-04, -8.108570e-05, -3.651228e-05, -5.312255e-05, -5.009791e-05, -9.325808e-06, -2.012086e-05, -6.285571e-06, -1.159698e-05, -5.462022e-05, -5.179310e-05, -4.307092e-05, 2.810360e-04, 3.869942e-04, -3.450936e-05, -7.805675e-05, 6.405561e-04, -2.284402e-04, -1.866295e-04, -4.858359e-04, 3.496890e-04, 7.352780e-04, 5.767877e-04, -8.477014e-04, -5.512698e-05, 1.091158e-03, -1.900036e-04, -4.632766e-05, 1.086153e-05, -7.743051e-05, -7.545391e-04, -3.143243e-05, -6.316374e-05, -2.435782e-06, -7.707894e-06, 4.451785e-04, 2.043479e-04, -8.673378e-05, -3.314975e-05, -3.181369e-05, -5.422704e-04, -9.020739e-05, 6.747588e-04, 5.997742e-06, -9.729086e-04, -9.751490e-06, -4.565744e-05, -4.181943e-04, 7.522183e-04, -2.436958e-06, 2.531532e-04, -9.441600e-06, 2.317743e-04, 4.254207e-04, -3.224488e-04, 3.979052e-04, 2.066697e-04, 2.486194e-05, 1.189306e-04, -2.465884e-05, -7.708071e-06, -1.422152e-05, -6.697064e-05, -6.351172e-05, -5.281060e-05, 3.446379e-04, -1.212986e-03, 9.206612e-04, 6.469824e-04, -6.605882e-04, -1.646537e-05, -6.854543e-04, -2.079925e-03, -1.031449e-03, 3.926585e-04, -1.556234e-03, -1.129748e-03, -2.113480e-04, -4.922559e-04, 1.938461e-03, 6.900824e-04, 1.497533e-04, -6.140808e-04, -3.365137e-04, 8.516225e-04, 5.874586e-04, -9.342693e-06, -2.955083e-05, 2.692614e-03, -9.928211e-04, -3.326157e-04, -3.572773e-04, 1.641113e-04, 7.442831e-05, -2.543959e-04, -1.783712e-04, -6.343638e-05, 9.077554e-05, -3.738480e-05, -1.750387e-04, -6.568480e-04, -2.035799e-04, -9.342694e-06, -6.874421e-05, -3.619677e-05, -2.803369e-05, -6.228932e-04, -3.870861e-04, -1.103792e-03, 9.585360e-04, -7.037269e-05, 2.736606e-04, -9.459508e-05, -2.955084e-05, -5.452180e-05, -2.567899e-04, -2.434930e-04, -2.024919e-04, 1.321256e-03, -2.244563e-04, -1.811758e-04, 8.043173e-04, 5.688820e-04, -5.182511e-04, -2.056167e-04, 1.290635e-04, -1.049207e-03, -7.305304e-04, -8.364983e-04, -4.528248e-04, -2.113987e-04, 3.279472e-04, 2.459491e-04, 5.986061e-05, 7.984705e-05, 1.001005e-04, 2.377746e-04, 4.061439e-05, 8.161668e-05, 3.151497e-06, 9.959707e-06, 1.549140e-04, 6.411739e-05, 1.121613e-04, 7.559378e-05, 4.110778e-05, 6.574476e-05, 7.925128e-05, 6.011770e-05, 2.139605e-05, 4.934971e-05, -5.597385e-06, -1.913622e-04, 1.706349e-04, -4.115145e-04, 3.149101e-06, 2.317293e-05, -1.246264e-04, 9.448371e-06, -4.303234e-04, 2.608783e-05, 7.889196e-05, -3.559375e-04, -5.551586e-04, -2.777131e-04, 6.505911e-04, 1.033867e-05, 1.837583e-05, 6.750772e-04, 1.247379e-04, -5.408403e-04, -4.453114e-04, }; Vec origRes = null; for (Family family : new Family[]{Family.multinomial, Family.AUTO}) { try { fr = parse_test_file(parsed, "smalldata/covtype/covtype.20k.data"); fr.remove("C21").remove(); fr.remove("C29").remove(); GLMParameters params = new GLMParameters(family/*Family.multinomial*/); params._response_column = "C55"; // params._response = fr.find(params._response_column); params._ignored_columns = new String[]{}; params._train = parsed; params._lambda = new double[]{0}; params._alpha = new double[]{0}; origRes = fr.remove("C55"); Vec res = fr.add("C55",origRes.toCategoricalVec()); double [] means = new double [res.domain().length]; long [] bins = res.bins(); double sumInv = 1.0/ArrayUtils.sum(bins); for(int i = 0; i < bins.length; ++i) means[i] = bins[i]*sumInv; DataInfo dinfo = new DataInfo(fr, null, 1, true, TransformType.STANDARDIZE, DataInfo.TransformType.NONE, true, false, false, false, false, false); GLMTask.GLMMultinomialGradientBaseTask gmt = new GLMTask.GLMMultinomialGradientTask(null,dinfo,0,beta,1.0/fr.numRows()).doAll(dinfo._adaptedFrame); assertEquals(0.6421113,gmt._likelihood/fr.numRows(),1e-8); System.out.println("likelihood = " + gmt._likelihood/fr.numRows()); double [] g = gmt.gradient(); for(int i = 0; i < g.length; ++i) assertEquals("Mismatch at coefficient '" + "' (" + i + ")",exp_grad[i], g[i], 1e-8); } finally { if(origRes != null)origRes.remove(); if (fr != null) fr.delete(); } } } //------------ TEST on selected files form small data and compare to R results ------------------------------------ /** * Simple test for poisson, gamma and gaussian families (no regularization, test both lsm solvers). * Basically tries to predict horse power based on other parameters of the cars in the dataset. * Compare against the results from standard R glm implementation. * * @throws ExecutionException * @throws InterruptedException */ @Test public void testCars() throws InterruptedException, ExecutionException { Scope.enter(); Key parsed = Key.make("cars_parsed"); Frame fr = null; GLMModel model = null; Frame score = null; try { fr = parse_test_file(parsed, "smalldata/junit/cars.csv"); GLMParameters params = new GLMParameters(Family.poisson, Family.poisson.defaultLink, new double[]{0}, new double[]{0},0,0); params._response_column = "power (hp)"; // params._response = fr.find(params._response_column); params._ignored_columns = new String[]{"name"}; params._train = parsed; params._lambda = new double[]{0}; params._alpha = new double[]{0}; params._missing_values_handling = MissingValuesHandling.Skip; model = new GLM( params).trainModel().get(); HashMap<String, Double> coefs = model.coefficients(); String[] cfs1 = new String[]{"Intercept", "economy (mpg)", "cylinders", "displacement (cc)", "weight (lb)", "0-60 mph (s)", "year"}; double[] vls1 = new double[]{4.9504805, -0.0095859, -0.0063046, 0.0004392, 0.0001762, -0.0469810, 0.0002891}; for (int i = 0; i < cfs1.length; ++i) assertEquals(vls1[i], coefs.get(cfs1[i]), 1e-4); // test gamma double[] vls2 = new double[]{8.992e-03, 1.818e-04, -1.125e-04, 1.505e-06, -1.284e-06, 4.510e-04, -7.254e-05}; testScoring(model,fr); model.delete(); params = new GLMParameters(Family.gamma, Family.gamma.defaultLink, new double[]{0}, new double[]{0},0,0); params._response_column = "power (hp)"; // params._response = fr.find(params._response_column); params._ignored_columns = new String[]{"name"}; params._train = parsed; params._lambda = new double[]{0}; params._beta_epsilon = 1e-5; params._missing_values_handling = MissingValuesHandling.Skip; model = new GLM( params).trainModel().get(); coefs = model.coefficients(); for (int i = 0; i < cfs1.length; ++i) assertEquals(vls2[i], coefs.get(cfs1[i]), 1e-4); testScoring(model,fr); model.delete(); // test gaussian double[] vls3 = new double[]{166.95862, -0.00531, -2.46690, 0.12635, 0.02159, -4.66995, -0.85724}; params = new GLMParameters(Family.gaussian); params._response_column = "power (hp)"; // params._response = fr.find(params._response_column); params._ignored_columns = new String[]{"name"}; params._train = parsed; params._lambda = new double[]{0}; params._missing_values_handling = MissingValuesHandling.Skip; model = new GLM( params).trainModel().get(); coefs = model.coefficients(); for (int i = 0; i < cfs1.length; ++i) assertEquals(vls3[i], coefs.get(cfs1[i]), 1e-4); // test scoring } finally { if (fr != null) fr.delete(); if (score != null) score.delete(); if (model != null) model.delete(); Scope.exit(); } } // Leask xval keys // @Test public void testXval() { // GLMModel model = null; // Frame fr = parse_test_file("smalldata/glm_test/prostate_cat_replaced.csv"); // Frame score = null; // try{ // Scope.enter(); // // R results //// Coefficients: //// (Intercept) ID AGE RACER2 RACER3 DPROS DCAPS PSA VOL GLEASON //// -8.894088 0.001588 -0.009589 0.231777 -0.459937 0.556231 0.556395 0.027854 -0.011355 1.010179 // String [] cfs1 = new String [] {"Intercept","AGE", "RACE.R2","RACE.R3", "DPROS", "DCAPS", "PSA", "VOL", "GLEASON"}; // double [] vals = new double [] {-8.14867, -0.01368, 0.32337, -0.38028, 0.55964, 0.49548, 0.02794, -0.01104, 0.97704}; // GLMParameters params = new GLMParameters(Family.binomial); // params._n_folds = 10; // params._response_column = "CAPSULE"; // params._ignored_columns = new String[]{"ID"}; // params._train = fr._key; // params._lambda = new double[]{0}; // model = new GLM(params,Key.make("prostate_model")).trainModel().get(); // HashMap<String, Double> coefs = model.coefficients(); // for(int i = 0; i < cfs1.length; ++i) // assertEquals(vals[i], coefs.get(cfs1[i]),1e-4); // GLMValidation val = model.trainVal(); //// assertEquals(512.3, val.nullDeviance(),1e-1); //// assertEquals(378.3, val.residualDeviance(),1e-1); //// assertEquals(396.3, val.AIC(),1e-1); //// score = model.score(fr); //// //// hex.ModelMetrics mm = hex.ModelMetrics.getFromDKV(model,fr); //// //// AUCData adata = mm._aucdata; //// assertEquals(val.auc(),adata.AUC(),1e-2); //// GLMValidation val2 = new GLMValidationTsk(params,model._ymu,rank(model.beta())).doAll(new Vec[]{fr.vec("CAPSULE"),score.vec("1")})._val; //// assertEquals(val.residualDeviance(),val2.residualDeviance(),1e-6); //// assertEquals(val.nullDeviance(),val2.nullDeviance(),1e-6); // } finally { // fr.delete(); // if(model != null)model.delete(); // if(score != null)score.delete(); // Scope.exit(); // } // } /** * Test bounds on prostate dataset, 2 cases : * 1) test against known result in glmnet (with elastic net regularization) with elastic net penalty * 2) test with no regularization, check the ginfo in the end. */ @Test public void testBounds() { // glmnet's result: // res2 <- glmnet(x=M,y=D$CAPSULE,lower.limits=-.5,upper.limits=.5,family='binomial') // res2$beta[,58] // AGE RACE DPROS PSA VOL GLEASON // -0.00616326 -0.50000000 0.50000000 0.03628192 -0.01249324 0.50000000 // res2$a0[100] // res2$a0[58] // s57 // -4.155864 // lambda = 0.001108, null dev = 512.2888, res dev = 379.7597 GLMModel model = null; Key parsed = Key.make("prostate_parsed"); Key modelKey = Key.make("prostate_model"); Frame fr = parse_test_file(parsed, "smalldata/logreg/prostate.csv"); Key betaConsKey = Key.make("beta_constraints"); String[] cfs1 = new String[]{"AGE", "RACE", "DPROS", "DCAPS", "PSA", "VOL", "GLEASON", "Intercept"}; double[] vals = new double[]{-0.006502588, -0.500000000, 0.500000000, 0.400000000, 0.034826559, -0.011661747, 0.500000000, -4.564024}; // [AGE, RACE, DPROS, DCAPS, PSA, VOL, GLEASON, Intercept] FVecFactory.makeByteVec(betaConsKey, "names, lower_bounds, upper_bounds\n AGE, -.5, .5\n RACE, -.5, .5\n DCAPS, -.4, .4\n DPROS, -.5, .5 \nPSA, -.5, .5\n VOL, -.5, .5\nGLEASON, -.5, .5"); Frame betaConstraints = ParseDataset.parse(Key.make("beta_constraints.hex"), betaConsKey); try { // H2O differs on intercept and race, same residual deviance though GLMParameters params = new GLMParameters(); params._standardize = true; params._family = Family.binomial; params._beta_constraints = betaConstraints._key; params._response_column = "CAPSULE"; params._ignored_columns = new String[]{"ID"}; params._train = fr._key; params._objective_epsilon = 0; params._alpha = new double[]{1}; params._lambda = new double[]{0.001607}; params._obj_reg = 1.0/380; GLM glm = new GLM( params, modelKey); model = glm.trainModel().get(); assertTrue(glm.isStopped()); // Map<String, Double> coefs = model.coefficients(); // for (int i = 0; i < cfs1.length; ++i) // assertEquals(vals[i], coefs.get(cfs1[i]), 1e-1); ModelMetricsBinomialGLM val = (ModelMetricsBinomialGLM) model._output._training_metrics; assertEquals(512.2888, val._nullDev, 1e-1); // 388.4952716196743 assertTrue(val._resDev <= 388.5); model.delete(); params._lambda = new double[]{0}; params._alpha = new double[]{0}; FVecFactory.makeByteVec(betaConsKey, "names, lower_bounds, upper_bounds\n RACE, -.5, .5\n DCAPS, -.4, .4\n DPROS, -.5, .5 \nPSA, -.5, .5\n VOL, -.5, .5"); betaConstraints = ParseDataset.parse(Key.make("beta_constraints.hex"), betaConsKey); glm = new GLM( params, modelKey); model = glm.trainModel().get(); assertTrue(glm.isStopped()); double[] beta = model.beta(); System.out.println("beta = " + Arrays.toString(beta)); fr.add("CAPSULE", fr.remove("CAPSULE")); fr.remove("ID").remove(); DKV.put(fr._key, fr); // now check the ginfo DataInfo dinfo = new DataInfo(fr, null, 1, true, TransformType.NONE, DataInfo.TransformType.NONE, true, false, false, false, false, false); GLMGradientTask lt = new GLMBinomialGradientTask(null,dinfo,params,0,beta).doAll(dinfo._adaptedFrame); double [] grad = lt._gradient; String [] names = model.dinfo().coefNames(); BufferedString tmpStr = new BufferedString(); outer: for (int i = 0; i < names.length; ++i) { for (int j = 0; j < betaConstraints.numRows(); ++j) { if (betaConstraints.vec("names").atStr(tmpStr, j).toString().equals(names[i])) { if (Math.abs(beta[i] - betaConstraints.vec("lower_bounds").at(j)) < 1e-4 || Math.abs(beta[i] - betaConstraints.vec("upper_bounds").at(j)) < 1e-4) { continue outer; } } } assertEquals(0, grad[i], 1e-2); } } finally { fr.delete(); betaConstraints.delete(); if (model != null) model.delete(); } } @Ignore // remove when PUBDEV-7693 is fixed @Test public void testInteractionPairs_airlines() { Scope.enter(); try { Frame train = Scope.track(parse_test_file("smalldata/airlines/AirlinesTrain.csv.zip")); Frame test = Scope.track(parse_test_file("smalldata/airlines/AirlinesTest.csv.zip")); GLMParameters params = new GLMParameters(); params._family = Family.binomial; params._response_column = "IsDepDelayed"; params._ignored_columns = new String[]{"IsDepDelayed_REC"}; params._train = train._key; params._interaction_pairs = new StringPair[] { new StringPair("DepTime", "UniqueCarrier"), new StringPair("DepTime", "Origin"), new StringPair("UniqueCarrier", "Origin") }; GLM glm = new GLM(params); GLMModel model = (GLMModel) Scope.track_generic(glm.trainModel().get()); Frame scored = Scope.track(model.score(test)); model.testJavaScoring(train, scored, 0); } finally { Scope.exit(); } } @Test public void testCoordinateDescent_airlines() { GLMModel model = null; Key parsed = Key.make("airlines_parsed"); Key<GLMModel> modelKey = Key.make("airlines_model"); Frame fr = parse_test_file(parsed, "smalldata/airlines/AirlinesTrain.csv.zip"); try { // H2O differs on intercept and race, same residual deviance though GLMParameters params = new GLMParameters(); params._standardize = true; params._family = Family.binomial; params._solver = Solver.COORDINATE_DESCENT_NAIVE; params._response_column = "IsDepDelayed"; params._ignored_columns = new String[]{"IsDepDelayed_REC"}; params._train = fr._key; GLM glm = new GLM( params, modelKey); model = glm.trainModel().get(); assertTrue(glm.isStopped()); System.out.println(model._output._training_metrics); } finally { fr.delete(); if (model != null) model.delete(); } } @Test public void testCoordinateDescent_airlines_CovUpdates() { GLMModel model = null; Key parsed = Key.make("airlines_parsed"); Key<GLMModel> modelKey = Key.make("airlines_model"); Frame fr = parse_test_file(parsed, "smalldata/airlines/AirlinesTrain.csv.zip"); try { // H2O differs on intercept and race, same residual deviance though GLMParameters params = new GLMParameters(); params._standardize = true; params._family = Family.binomial; params._solver = Solver.COORDINATE_DESCENT; params._response_column = "IsDepDelayed"; params._ignored_columns = new String[]{"IsDepDelayed_REC"}; params._train = fr._key; GLM glm = new GLM( params, modelKey); model = glm.trainModel().get(); assertTrue(glm.isStopped()); System.out.println(model._output._training_metrics); } finally { fr.delete(); if (model != null) model.delete(); } } @Test public void testCoordinateDescent_anomaly() { GLMModel model = null; Key parsed = Key.make("anomaly_parsed"); Key<GLMModel> modelKey = Key.make("anomaly_model"); Frame fr = parse_test_file(parsed, "smalldata/anomaly/ecg_discord_train.csv"); try { // H2O differs on intercept and race, same residual deviance though GLMParameters params = new GLMParameters(); params._standardize = true; params._family = Family.gaussian; params._solver = Solver.COORDINATE_DESCENT_NAIVE; params._response_column = "C1"; params._train = fr._key; GLM glm = new GLM( params, modelKey); model = glm.trainModel().get(); assertTrue(glm.isStopped()); System.out.println(model._output._training_metrics); } finally { fr.delete(); if (model != null) model.delete(); } } @Test public void testCoordinateDescent_anomaly_CovUpdates() { GLMModel model = null; Key parsed = Key.make("anomaly_parsed"); Key<GLMModel> modelKey = Key.make("anomaly_model"); Frame fr = parse_test_file(parsed, "smalldata/anomaly/ecg_discord_train.csv"); try { // H2O differs on intercept and race, same residual deviance though GLMParameters params = new GLMParameters(); params._standardize = true; params._family = Family.gaussian; params._solver = Solver.COORDINATE_DESCENT; params._response_column = "C1"; params._train = fr._key; GLM glm = new GLM( params, modelKey); model = glm.trainModel().get(); assertTrue(glm.isStopped()); System.out.println(model._output._training_metrics); } finally { fr.delete(); if (model != null) model.delete(); } } @Test public void testProximal() { // glmnet's result: // res2 <- glmnet(x=M,y=D$CAPSULE,lower.limits=-.5,upper.limits=.5,family='binomial') // res2$beta[,58] // AGE RACE DPROS PSA VOL GLEASON // -0.00616326 -0.50000000 0.50000000 0.03628192 -0.01249324 0.50000000 // res2$a0[100] // res2$a0[58] // s57 // -4.155864 // lambda = 0.001108, null dev = 512.2888, res dev = 379.7597 Key parsed = Key.make("prostate_parsed"); Key<GLMModel> modelKey = Key.make("prostate_model"); GLMModel model = null; Frame fr = parse_test_file(parsed, "smalldata/logreg/prostate.csv"); fr.remove("ID").remove(); DKV.put(fr._key, fr); Key betaConsKey = Key.make("beta_constraints"); FVecFactory.makeByteVec(betaConsKey, "names, beta_given, rho\n AGE, 0.1, 1\n RACE, -0.1, 1 \n DPROS, 10, 1 \n DCAPS, -10, 1 \n PSA, 0, 1\n VOL, 0, 1\nGLEASON, 0, 1\n Intercept, 0, 0 \n"); Frame betaConstraints = ParseDataset.parse(Key.make("beta_constraints.hex"), betaConsKey); try { // H2O differs on intercept and race, same residual deviance though GLMParameters params = new GLMParameters(); params._standardize = false; params._family = Family.binomial; params._beta_constraints = betaConstraints._key; params._response_column = "CAPSULE"; params._ignored_columns = new String[]{"ID"}; params._train = fr._key; params._alpha = new double[]{0}; params._lambda = new double[]{0}; params._obj_reg = 1.0/380; params._objective_epsilon = 0; GLM glm = new GLM( params, modelKey); model = glm.trainModel().get(); double[] beta_1 = model.beta(); params._solver = Solver.L_BFGS; params._max_iterations = 1000; glm = new GLM( params, modelKey); model = glm.trainModel().get(); fr.add("CAPSULE", fr.remove("CAPSULE")); // now check the ginfo DataInfo dinfo = new DataInfo(fr, null, 1, true, TransformType.NONE, DataInfo.TransformType.NONE, true, false, false, false, false, false); GLMGradientTask lt = new GLMBinomialGradientTask(null,dinfo, params, 0, beta_1).doAll(dinfo._adaptedFrame); double[] grad = lt._gradient; for (int i = 0; i < beta_1.length; ++i) assertEquals(0, grad[i] + betaConstraints.vec("rho").at(i) * (beta_1[i] - betaConstraints.vec("beta_given").at(i)), 1e-4); } finally { betaConstraints.delete(); fr.delete(); if (model != null) model.delete(); } } // // test categorical autoexpansions, run on airlines which has several categorical columns, // // once on explicitly expanded data, once on h2o autoexpanded and compare the results // @Test public void testSparseCategoricals() { // GLMModel model1 = null, model2 = null, model3 = null, model4 = null; // // Frame frMM = parse_test_file("smalldata/glm_tets/train-2.csv"); // //// Vec xy = frG.remove("xy"); // frMM.remove("").remove(); // frMM.add("IsDepDelayed", frMM.remove("IsDepDelayed")); // DKV.put(frMM._key,frMM); // Frame fr = parse_test_file("smalldata/airlines/AirlinesTrain.csv.zip"), res = null; // // Distance + Origin + Dest + UniqueCarrier // String [] ignoredCols = new String[]{"fYear", "fMonth", "fDayofMonth", "fDayOfWeek", "DepTime","ArrTime","IsDepDelayed_REC"}; // try{ // Scope.enter(); // GLMParameters params = new GLMParameters(Family.gaussian); // params._response_column = "IsDepDelayed"; // params._ignored_columns = ignoredCols; // params._train = fr._key; // params._l2pen = new double[]{1e-5}; // params._standardize = false; // model1 = new GLM(params,glmkey("airlines_cat_nostd")).trainModel().get(); // Frame score1 = model1.score(fr); // ModelMetricsRegressionGLM mm = (ModelMetricsRegressionGLM) ModelMetrics.getFromDKV(model1, fr); // Assert.assertEquals(model1.validation().residual_deviance, mm._resDev, 1e-4); // System.out.println("NDOF = " + model1.validation().nullDOF() + ", numRows = " + score1.numRows()); // Assert.assertEquals(model1.validation().residual_deviance, mm._MSE * score1.numRows(), 1e-4); // mm.remove(); // res = model1.score(fr); // // Build a POJO, validate same results // Assert.assertTrue(model1.testJavaScoring(fr, res, 1e-15)); // // params._train = frMM._key; // params._ignored_columns = new String[]{"X"}; // model2 = new GLM(params,glmkey("airlines_mm")).trainModel().get(); // params._standardize = true; // params._train = frMM._key; // params._use_all_factor_levels = true; // // test the gram // DataInfo dinfo = new DataInfo(Key.make(),frMM, null, 1, true, DataInfo.TransformType.STANDARDIZE, DataInfo.TransformType.NONE, true); // GLMIterationTask glmt = new GLMIterationTask(null,dinfo,1e-5,params,false,null,0,null, null).doAll(dinfo._adaptedFrame); // for(int i = 0; i < glmt._xy.length; ++i) { // for(int j = 0; j <= i; ++j ) { // assertEquals(frG.vec(j).at(i), glmt._gram.get(i, j), 1e-5); // } // assertEquals(xy.at(i), glmt._xy[i], 1e-5); // } // frG.delete(); // xy.remove(); // params._standardize = true; // params._family = Family.binomial; // params._link = Link.logit; // model3 = new GLM(params,glmkey("airlines_mm")).trainModel().get(); // params._train = fr._key; // params._ignored_columns = ignoredCols; // model4 = new GLM(params,glmkey("airlines_mm")).trainModel().get(); // assertEquals(model3.validation().null_deviance,model4.validation().nullDeviance(),1e-4); // assertEquals(model4.validation().residual_deviance, model3.validation().residualDeviance(), model3.validation().null_deviance * 1e-3); // HashMap<String, Double> coefs1 = model1.coefficients(); // HashMap<String, Double> coefs2 = model2.coefficients(); // GLMValidation val1 = model1.validation(); // GLMValidation val2 = model2.validation(); // // compare against each other // for(String s:coefs2.keySet()) { // String s1 = s; // if(s.startsWith("Origin")) // s1 = "Origin." + s.substring(6); // if(s.startsWith("Dest")) // s1 = "Dest." + s.substring(4); // if(s.startsWith("UniqueCarrier")) // s1 = "UniqueCarrier." + s.substring(13); // assertEquals("coeff " + s1 + " differs, " + coefs1.get(s1) + " != " + coefs2.get(s), coefs1.get(s1), coefs2.get(s),1e-4); // DKV.put(frMM._key,frMM); // update the frame in the KV after removing the vec! // } // assertEquals(val1.nullDeviance(), val2.nullDeviance(),1e-4); // assertEquals(val1.residualDeviance(), val2.residualDeviance(),1e-4); // assertEquals(val1._aic, val2._aic,1e-2); // // compare result against glmnet // assertEquals(5336.918,val1.residualDeviance(),1); // assertEquals(6051.613,val1.nullDeviance(),1); // // // // lbfgs //// params._solver = Solver.L_BFGS; //// params._train = fr._key; //// params._lambda = new double[]{.3}; //// model3 = new GLM(params,glmkey("lbfgs_cat")).trainModel().get(); //// params._train = frMM._key; //// model4 = new GLM(params,glmkey("lbfgs_mm")).trainModel().get(); //// HashMap<String, Double> coefs3 = model3.coefficients(); //// HashMap<String, Double> coefs4 = model4.coefficients(); //// // compare against each other //// for(String s:coefs4.keySet()) { //// String s1 = s; //// if(s.startsWith("Origin")) //// s1 = "Origin." + s.substring(6); //// if(s.startsWith("Dest")) //// s1 = "Dest." + s.substring(4); //// if(s.startsWith("UniqueCarrier")) //// s1 = "UniqueCarrier." + s.substring(13); //// assertEquals("coeff " + s1 + " differs, " + coefs3.get(s1) + " != " + coefs4.get(s), coefs3.get(s1), coefs4.get(s),1e-4); //// } // // } finally { // fr.delete(); // frMM.delete(); // if(res != null)res.delete(); // if(model1 != null)model1.delete(); // if(model2 != null)model2.delete(); // if(model3 != null)model3.delete(); // if(model4 != null)model4.delete(); //// if(score != null)score.delete(); // Scope.exit(); // } // } /** * Test we get correct gram on dataset which contains categoricals and sparse and dense numbers */ @Test public void testSparseGramComputation() { Random rnd = new Random(123456789l); double[] d0 = MemoryManager.malloc8d(1000); double[] d1 = MemoryManager.malloc8d(1000); double[] d2 = MemoryManager.malloc8d(1000); double[] d3 = MemoryManager.malloc8d(1000); double[] d4 = MemoryManager.malloc8d(1000); double[] d5 = MemoryManager.malloc8d(1000); double[] d6 = MemoryManager.malloc8d(1000); double[] d7 = MemoryManager.malloc8d(1000); double[] d8 = MemoryManager.malloc8d(1000); double[] d9 = MemoryManager.malloc8d(1000); long[] c1 = MemoryManager.malloc8(1000); long[] c2 = MemoryManager.malloc8(1000); String[] dom = new String[]{"a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k", "l", "m", "n", "o", "p", "q", "r", "s", "t", "u", "v", "w", "x", "y", "z"}; for (int i = 0; i < d1.length; ++i) { c1[i] = rnd.nextInt(dom.length); c2[i] = rnd.nextInt(dom.length); d0[i] = rnd.nextDouble(); d1[i] = rnd.nextDouble(); } for (int i = 0; i < 30; ++i) { d2[rnd.nextInt(d2.length)] = rnd.nextDouble(); d3[rnd.nextInt(d2.length)] = rnd.nextDouble(); d4[rnd.nextInt(d2.length)] = rnd.nextDouble(); d5[rnd.nextInt(d2.length)] = rnd.nextDouble(); d6[rnd.nextInt(d2.length)] = rnd.nextDouble(); d7[rnd.nextInt(d2.length)] = rnd.nextDouble(); d8[rnd.nextInt(d2.length)] = rnd.nextDouble(); d9[rnd.nextInt(d2.length)] = 1; } Vec.VectorGroup vg_1 = Vec.VectorGroup.VG_LEN1; Vec v01 = Vec.makeVec(c1, dom, vg_1.addVec()); Vec v02 = Vec.makeVec(c2, dom,vg_1.addVec()); Vec v03 = Vec.makeVec(d0, vg_1.addVec()); Vec v04 = Vec.makeVec(d1, vg_1.addVec()); Vec v05 = Vec.makeVec(d2, vg_1.addVec()); Vec v06 = Vec.makeVec(d3, vg_1.addVec()); Vec v07 = Vec.makeVec(d4, vg_1.addVec()); Vec v08 = Vec.makeVec(d5, vg_1.addVec()); Vec v09 = Vec.makeVec(d6, vg_1.addVec()); Vec v10 = Vec.makeVec(d7, vg_1.addVec()); Vec v11 = Vec.makeVec(d8, vg_1.addVec()); Vec v12 = Vec.makeVec(d9, vg_1.addVec()); Frame f = new Frame(Key.<Frame>make("TestData"), null, new Vec[]{v01, v02, v03, v04, v05, v05, v06, v07, v08, v09, v10, v11, v12}); DKV.put(f); DataInfo dinfo = new DataInfo(f, null, 1, true, DataInfo.TransformType.STANDARDIZE, DataInfo.TransformType.NONE, true, false, false, false, false, false); GLMParameters params = new GLMParameters(Family.gaussian); // public GLMIterationTask(Key jobKey, DataInfo dinfo, GLMWeightsFun glmw,double [] beta, double lambda) { final GLMIterationTask glmtSparse = new GLMIterationTask(null, dinfo, new GLMWeightsFun(params), null).setSparse(true).doAll(dinfo._adaptedFrame); final GLMIterationTask glmtDense = new GLMIterationTask(null, dinfo, new GLMWeightsFun(params), null).setSparse(false).doAll(dinfo._adaptedFrame); for (int i = 0; i < glmtDense._xy.length; ++i) { for (int j = 0; j <= i; ++j) { assertEquals(glmtDense._gram.get(i, j), glmtSparse._gram.get(i, j), 1e-8); } assertEquals(glmtDense._xy[i], glmtSparse._xy[i], 1e-8); } final double[] beta = MemoryManager.malloc8d(dinfo.fullN() + 1); // now do the same but weighted, use LSM solution as beta to generate meaningfull weights H2O.submitTask(new H2OCountedCompleter() { @Override public void compute2() { new GLM.GramSolver(glmtDense._gram, glmtDense._xy, true, 1e-5, 0, null, null, null, null).solve(null, beta); tryComplete(); } }).join(); final GLMIterationTask glmtSparse2 = new GLMIterationTask(null, dinfo, new GLMWeightsFun(params), beta).setSparse(true).doAll(dinfo._adaptedFrame); final GLMIterationTask glmtDense2 = new GLMIterationTask(null, dinfo, new GLMWeightsFun(params), beta).setSparse(false).doAll(dinfo._adaptedFrame); for (int i = 0; i < glmtDense2._xy.length; ++i) { for (int j = 0; j <= i; ++j) { assertEquals(glmtDense2._gram.get(i, j), glmtSparse2._gram.get(i, j), 1e-8); } assertEquals(glmtDense2._xy[i], glmtSparse2._xy[i], 1e-8); } dinfo.remove(); f.delete(); } @Test @Ignore public void testConstantColumns(){ GLMModel model1 = null, model2 = null, model3 = null, model4 = null; Frame fr = parse_test_file(Key.make("Airlines"), "smalldata/airlines/allyears2k_headers.zip"); Vec y = fr.vec("IsDepDelayed").makeCopy(null); fr.replace(fr.find("IsDepDelayed"),y).remove(); Vec weights = fr.anyVec().makeZero(); new MRTask(){ @Override public void map(Chunk c){ int i = 0; for(i = 0; i < c._len; ++i){ long rid = c.start()+i; if(rid >= 1999) break; c.set(i,1); } } }.doAll(weights); fr.add("weights", weights); DKV.put(fr); GLMParameters parms = new GLMParameters(Family.gaussian); parms._train = fr._key; parms._weights_column = "weights"; parms._lambda_search = true; parms._alpha = new double[]{0}; parms._response_column = "IsDepDelayed"; parms._ignored_columns = new String[]{"DepTime", "ArrTime", "Cancelled", "CancellationCode", "DepDelay", "Diverted", "CarrierDelay", "WeatherDelay", "NASDelay", "SecurityDelay", "LateAircraftDelay", "IsArrDelayed"}; parms._standardize = true; model1 = new GLM(parms).trainModel().get(); model1.delete(); fr.delete(); } // test categorical autoexpansions, run on airlines which has several categorical columns, // once on explicitly expanded data, once on h2o autoexpanded and compare the results @Test public void testAirlines() { GLMModel model1 = null, model2 = null, model3 = null, model4 = null; Frame frMM = parse_test_file(Key.make("AirlinesMM"), "smalldata/airlines/AirlinesTrainMM.csv.zip"); Frame frG = parse_test_file(Key.make("gram"), "smalldata/airlines/gram_std.csv"); Vec xy = frG.remove("xy"); frMM.remove("C1").remove(); Vec v; frMM.add("IsDepDelayed", (v = frMM.remove("IsDepDelayed")).makeCopy(null)); v.remove(); DKV.put(frMM._key, frMM); Frame fr = parse_test_file(Key.make("Airlines"), "smalldata/airlines/AirlinesTrain.csv.zip"), res = null; fr.add("IsDepDelayed",(v =fr.remove("IsDepDelayed")).makeCopy(null)); v.remove(); DKV.put(fr._key,fr); // Distance + Origin + Dest + UniqueCarrier String[] ignoredCols = new String[]{"fYear", "fMonth", "fDayofMonth", "fDayOfWeek", "DepTime", "ArrTime", "IsDepDelayed_REC"}; try { Scope.enter(); GLMParameters params = new GLMParameters(Family.gaussian); params._response_column = "IsDepDelayed"; params._ignored_columns = ignoredCols; params._train = fr._key; params._lambda = new double[]{0}; params._alpha = new double[]{0}; params._standardize = false; params._use_all_factor_levels = false; model1 = new GLM(params).trainModel().get(); testScoring(model1,fr); Frame score1 = model1.score(fr); ModelMetricsRegressionGLM mm = (ModelMetricsRegressionGLM) ModelMetrics.getFromDKV(model1, fr); Assert.assertEquals(((ModelMetricsRegressionGLM) model1._output._training_metrics)._resDev, mm._resDev, 1e-4); Assert.assertEquals(((ModelMetricsRegressionGLM) model1._output._training_metrics)._resDev, mm._MSE * score1.numRows(), 1e-4); score1.delete(); mm.remove(); res = model1.score(fr); // Build a POJO, validate same results params._train = frMM._key; params._ignored_columns = new String[]{"X"}; model2 = new GLM( params).trainModel().get(); HashMap<String, Double> coefs1 = model1.coefficients(); testScoring(model2,frMM); HashMap<String, Double> coefs2 = model2.coefficients(); boolean failed = false; // compare against each other for (String s : coefs2.keySet()) { String s1 = s; if (s.startsWith("Origin")) s1 = "Origin." + s.substring(6); if (s.startsWith("Dest")) s1 = "Dest." + s.substring(4); if (s.startsWith("UniqueCarrier")) s1 = "UniqueCarrier." + s.substring(13); if(Math.abs(coefs1.get(s1) - coefs2.get(s)) > 1e-4) { System.out.println("coeff " + s1 + " differs, " + coefs1.get(s1) + " != " + coefs2.get(s)); failed = true; } // assertEquals("coeff " + s1 + " differs, " + coefs1.get(s1) + " != " + coefs2.get(s), coefs1.get(s1), coefs2.get(s), 1e-4); } assertFalse(failed); params._standardize = true; params._train = frMM._key; params._use_all_factor_levels = true; // test the gram DataInfo dinfo = new DataInfo(frMM, null, 1, true, DataInfo.TransformType.STANDARDIZE, DataInfo.TransformType.NONE, true, false, false, false, false, false); GLMIterationTask glmt = new GLMIterationTask(null, dinfo, new GLMWeightsFun(params), null).doAll(dinfo._adaptedFrame); for(int i = 0; i < glmt._xy.length; ++i) { for(int j = 0; j <= i; ++j ) { assertEquals(frG.vec(j).at(i), glmt._gram.get(i, j), 1e-5); } assertEquals(xy.at(i), glmt._xy[i], 1e-5); } xy.remove(); params = (GLMParameters) params.clone(); params._standardize = false; params._family = Family.binomial; params._link = Link.logit; model3 = new GLM( params).trainModel().get(); testScoring(model3,frMM); params._train = fr._key; params._ignored_columns = ignoredCols; model4 = new GLM( params).trainModel().get(); testScoring(model4,fr); assertEquals(nullDeviance(model3), nullDeviance(model4), 1e-4); assertEquals(residualDeviance(model4), residualDeviance(model3), nullDeviance(model3) * 1e-3); assertEquals(nullDeviance(model1), nullDeviance(model2), 1e-4); assertEquals(residualDeviance(model1), residualDeviance(model2), 1e-4); // assertEquals(val1._aic, val2._aic,1e-2); // compare result against glmnet assertEquals(5336.918, residualDeviance(model1), 1); assertEquals(6051.613, nullDeviance(model2), 1); // lbfgs // params._solver = Solver.L_BFGS; // params._train = fr._key; // params._lambda = new double[]{.3}; // model3 = new GLM(params,glmkey("lbfgs_cat")).trainModel().get(); // params._train = frMM._key; // mdoel4 = new GLM(params,glmkey("lbfgs_mm")).trainModel().get(); // HashMap<String, Double> coefs3 = model3.coefficients(); // HashMap<String, Double> coefs4 = model4.coefficients(); // // compare against each other // for(String s:coefs4.keySet()) { // String s1 = s; // if(s.startsWith("Origin")) // s1 = "Origin." + s.substring(6); // if(s.startsWith("Dest")) // s1 = "Dest." + s.substring(4); // if(s.startsWith("UniqueCarrier")) // s1 = "UniqueCarrier." + s.substring(13); // assertEquals("coeff " + s1 + " differs, " + coefs3.get(s1) + " != " + coefs4.get(s), coefs3.get(s1), coefs4.get(s),1e-4); // } } finally { fr.delete(); frMM.delete(); frG.delete(); if (res != null) res.delete(); if (model1 != null) model1.delete(); if (model2 != null) model2.delete(); if (model3 != null) model3.delete(); if (model4 != null) model4.delete(); // if(score != null)score.delete(); Scope.exit(); } } // test categorical autoexpansions, run on airlines which has several categorical columns, // once on explicitly expanded data, once on h2o autoexpanded and compare the results @Test public void test_COD_Airlines_SingleLambda() { GLMModel model1 = null; Frame fr = parse_test_file(Key.make("Airlines"), "smalldata/airlines/AirlinesTrain.csv.zip"); // Distance + Origin + Dest + UniqueCarrier String[] ignoredCols = new String[]{"IsDepDelayed_REC"}; try { Scope.enter(); GLMParameters params = new GLMParameters(Family.binomial); params._response_column = "IsDepDelayed"; params._ignored_columns = ignoredCols; params._train = fr._key; params._valid = fr._key; params._lambda = new double[] {0.01};//null; //new double[]{0.02934};//{0.02934494}; // null; params._alpha = new double[]{1}; params._standardize = false; params._solver = Solver.COORDINATE_DESCENT_NAIVE; params._lambda_search = true; params._nlambdas = 5; GLM glm = new GLM( params); model1 = glm.trainModel().get(); double [] beta = model1.beta(); double l1pen = ArrayUtils.l1norm(beta,true); double l2pen = ArrayUtils.l2norm2(beta,true); //System.out.println( " lambda min " + params._l2pen[params._l2pen.length-1] ); //System.out.println( " lambda_max " + model1._lambda_max); //System.out.println(" intercept " + beta[beta.length-1]); // double objective = model1._output._training_metrics./model1._nobs + // params._l2pen[params._l2pen.length-1]*params._alpha[0]*l1pen + params._l2pen[params._l2pen.length-1]*(1-params._alpha[0])*l2pen/2 ; // System.out.println( " objective value " + objective); // assertEquals(0.670921, objective,1e-4); } finally { fr.delete(); if (model1 != null) model1.delete(); } } @Test public void test_COD_Airlines_SingleLambda_CovUpdates() { GLMModel model1 = null; Frame fr = parse_test_file(Key.make("Airlines"), "smalldata/airlines/AirlinesTrain.csv.zip"); // Distance + Origin + Dest + UniqueCarrier String[] ignoredCols = new String[]{"IsDepDelayed_REC"}; try { Scope.enter(); GLMParameters params = new GLMParameters(Family.binomial); params._response_column = "IsDepDelayed"; params._ignored_columns = ignoredCols; params._train = fr._key; params._valid = fr._key; params._lambda = new double[] {0.01};//null; //new double[]{0.02934};//{0.02934494}; // null; params._alpha = new double[]{1}; params._standardize = false; params._solver = Solver.COORDINATE_DESCENT; params._lambda_search = true; GLM glm = new GLM( params); model1 = glm.trainModel().get(); double [] beta = model1.beta(); double l1pen = ArrayUtils.l1norm(beta,true); double l2pen = ArrayUtils.l2norm2(beta,true); // double objective = job.likelihood()/model1._nobs + // params._l2pen[params._l2pen.length-1]*params._alpha[0]*l1pen + params._l2pen[params._l2pen.length-1]*(1-params._alpha[0])*l2pen/2 ; // System.out.println( " objective value " + objective); // assertEquals(0.670921, objective,1e-2); } finally { fr.delete(); if (model1 != null) model1.delete(); } } @Test public void test_COD_Airlines_LambdaSearch() { GLMModel model1 = null; Frame fr = parse_test_file(Key.make("Airlines"), "smalldata/airlines/AirlinesTrain.csv.zip"); // Distance + Origin + Dest + UniqueCarrier String[] ignoredCols = new String[]{"IsDepDelayed_REC"}; try { Scope.enter(); GLMParameters params = new GLMParameters(Family.binomial); params._response_column = "IsDepDelayed"; params._ignored_columns = ignoredCols; params._train = fr._key; params._valid = fr._key; params._lambda = null; // new double [] {0.25}; params._alpha = new double[]{1}; params._standardize = false; params._solver = Solver.COORDINATE_DESCENT_NAIVE;//IRLSM params._lambda_search = true; params._nlambdas = 5; GLM glm = new GLM(params); model1 = glm.trainModel().get(); GLMModel.Submodel sm = model1._output._submodels[model1._output._submodels.length - 1]; double[] beta = sm.beta; System.out.println("lambda " + sm.lambda_value); double l1pen = ArrayUtils.l1norm(beta, true); double l2pen = ArrayUtils.l2norm2(beta, true); // double objective = job.likelihood()/model1._nobs + // gives likelihood of the last lambda // params._l2pen[params._l2pen.length-1]*params._alpha[0]*l1pen + params._l2pen[params._l2pen.length-1]*(1-params._alpha[0])*l2pen/2 ; // assertEquals(0.65689, objective,1e-4); } finally { fr.delete(); if (model1 != null) model1.delete(); } } @Test public void test_COD_Airlines_LambdaSearch_CovUpdates() { GLMModel model1 = null; Frame fr = parse_test_file(Key.make("Airlines"), "smalldata/airlines/AirlinesTrain.csv.zip"); // Distance + Origin + Dest + UniqueCarrier String[] ignoredCols = new String[]{"IsDepDelayed_REC"}; try { Scope.enter(); GLMParameters params = new GLMParameters(Family.binomial); params._response_column = "IsDepDelayed"; params._ignored_columns = ignoredCols; params._train = fr._key; params._valid = fr._key; params._lambda = null; // new double [] {0.25}; params._alpha = new double[]{1}; params._standardize = false; params._solver = Solver.COORDINATE_DESCENT; params._lambda_search = true; params._nlambdas = 5; GLM glm = new GLM( params); model1 = glm.trainModel().get(); GLMModel.Submodel sm = model1._output._submodels[model1._output._submodels.length-1]; double [] beta = sm.beta; System.out.println("lambda " + sm.lambda_value); double l1pen = ArrayUtils.l1norm(beta,true); double l2pen = ArrayUtils.l2norm2(beta,true); // double objective = job.likelihood()/model1._nobs + // gives likelihood of the last lambda // params._l2pen[params._l2pen.length-1]*params._alpha[0]*l1pen + params._l2pen[params._l2pen.length-1]*(1-params._alpha[0])*l2pen/2 ; // assertEquals(0.65689, objective,1e-4); } finally { fr.delete(); if (model1 != null) model1.delete(); } } public static double residualDeviance(GLMModel m) { if (m._parms._family == Family.binomial || m._parms._family == Family.quasibinomial) { ModelMetricsBinomialGLM metrics = (ModelMetricsBinomialGLM) m._output._training_metrics; return metrics._resDev; } else { ModelMetricsRegressionGLM metrics = (ModelMetricsRegressionGLM) m._output._training_metrics; return metrics._resDev; } } public static double residualDevianceTest(GLMModel m) { if(m._parms._family == Family.binomial) { ModelMetricsBinomialGLM metrics = (ModelMetricsBinomialGLM)m._output._validation_metrics; return metrics._resDev; } else { ModelMetricsRegressionGLM metrics = (ModelMetricsRegressionGLM)m._output._validation_metrics; return metrics._resDev; } } public static double nullDevianceTest(GLMModel m) { if(m._parms._family == Family.binomial) { ModelMetricsBinomialGLM metrics = (ModelMetricsBinomialGLM)m._output._validation_metrics; return metrics._nullDev; } else { ModelMetricsRegressionGLM metrics = (ModelMetricsRegressionGLM)m._output._validation_metrics; return metrics._nullDev; } } public static double aic(GLMModel m) { if (m._parms._family == Family.binomial) { ModelMetricsBinomialGLM metrics = (ModelMetricsBinomialGLM) m._output._training_metrics; return metrics._AIC; } else { ModelMetricsRegressionGLM metrics = (ModelMetricsRegressionGLM) m._output._training_metrics; return metrics._AIC; } } public static double nullDOF(GLMModel m) { if (m._parms._family == Family.binomial) { ModelMetricsBinomialGLM metrics = (ModelMetricsBinomialGLM) m._output._training_metrics; return metrics._nullDegressOfFreedom; } else { ModelMetricsRegressionGLM metrics = (ModelMetricsRegressionGLM) m._output._training_metrics; return metrics._nullDegressOfFreedom; } } public static double resDOF(GLMModel m) { if (m._parms._family == Family.binomial || m._parms._family == Family.quasibinomial) { ModelMetricsBinomialGLM metrics = (ModelMetricsBinomialGLM) m._output._training_metrics; return metrics._residualDegressOfFreedom; } else { ModelMetricsRegressionGLM metrics = (ModelMetricsRegressionGLM) m._output._training_metrics; return metrics._residualDegressOfFreedom; } } public static double auc(GLMModel m) { ModelMetricsBinomialGLM metrics = (ModelMetricsBinomialGLM) m._output._training_metrics; return metrics.auc_obj()._auc; } public static double logloss(GLMModel m) { ModelMetricsBinomialGLM metrics = (ModelMetricsBinomialGLM) m._output._training_metrics; return metrics._logloss; } public static double mse(GLMModel m) { if (m._parms._family == Family.binomial) { ModelMetricsBinomialGLM metrics = (ModelMetricsBinomialGLM) m._output._training_metrics; return metrics._MSE; } else { ModelMetricsRegressionGLM metrics = (ModelMetricsRegressionGLM) m._output._training_metrics; return metrics._MSE; } } public static double nullDeviance(GLMModel m) { if (m._parms._family == Family.binomial || m._parms._family == Family.quasibinomial) { ModelMetricsBinomialGLM metrics = (ModelMetricsBinomialGLM) m._output._training_metrics; return metrics._nullDev; } else { ModelMetricsRegressionGLM metrics = (ModelMetricsRegressionGLM) m._output._training_metrics; return metrics._nullDev; } } // test class private static final class GLMIterationTaskTest extends GLMIterationTask { final GLMModel _m; GLMMetricBuilder _val2; public GLMIterationTaskTest(Key jobKey, DataInfo dinfo, double lambda, GLMParameters glm, boolean validate, double[] beta, double ymu, GLMModel m) { // null, dinfo, new GLMWeightsFun(params), beta, 1e-5 super(jobKey, dinfo, new GLMWeightsFun(glm), beta); _m = m; } public void map(Chunk[] chks) { super.map(chks); _val2 = (GLMMetricBuilder) _m.makeMetricBuilder(chks[chks.length - 1].vec().domain()); double[] ds = new double[3]; float[] actual = new float[1]; for (int i = 0; i < chks[0]._len; ++i) { _m.score0(chks, i, null, ds); actual[0] = (float) chks[chks.length - 1].atd(i); _val2.perRow(ds, actual, _m); } } public void reduce(GLMIterationTask gmt) { super.reduce(gmt); GLMIterationTaskTest g = (GLMIterationTaskTest) gmt; _val2.reduce(g._val2); } } /** * Simple test for binomial family (no regularization, test both lsm solvers). * Runs the classical prostate, using dataset with race replaced by categoricals (probably as it's supposed to be?), in any case, * it gets to test correct processing of categoricals. * * Compare against the results from standard R glm implementation. * @throws ExecutionException * @throws InterruptedException */ @Test public void testProstate() throws InterruptedException, ExecutionException { GLMModel model = null, model2 = null, model3 = null, model4 = null; Frame fr = parse_test_file("smalldata/glm_test/prostate_cat_replaced.csv"); try{ Scope.enter(); // R results // Coefficients: // (Intercept) ID AGE RACER2 RACER3 DPROS DCAPS PSA VOL GLEASON // -8.894088 0.001588 -0.009589 0.231777 -0.459937 0.556231 0.556395 0.027854 -0.011355 1.010179 String [] cfs1 = new String [] {"Intercept","AGE", "RACE.R2","RACE.R3", "DPROS", "DCAPS", "PSA", "VOL", "GLEASON"}; double [] vals = new double [] {-8.14867, -0.01368, 0.32337, -0.38028, 0.55964, 0.49548, 0.02794, -0.01104, 0.97704}; GLMParameters params = new GLMParameters(Family.binomial); params._response_column = "CAPSULE"; params._ignored_columns = new String[]{"ID"}; params._train = fr._key; params._lambda = new double[]{0}; params._standardize = false; // params._missing_values_handling = MissingValuesHandling.Skip; GLM glm = new GLM(params); model = glm.trainModel().get(); assertTrue(model._output.bestSubmodel().iteration == 5); model.delete(); params._max_iterations = 4; glm = new GLM(params); model = glm.trainModel().get(); assertTrue(model._output.bestSubmodel().iteration == 4); System.out.println(model._output._model_summary); HashMap<String, Double> coefs = model.coefficients(); System.out.println(coefs); for(int i = 0; i < cfs1.length; ++i) assertEquals(vals[i], coefs.get(cfs1[i]),1e-4); assertEquals(512.3, nullDeviance(model),1e-1); assertEquals(378.3, residualDeviance(model),1e-1); assertEquals(371, resDOF(model),0); assertEquals(396.3, aic(model),1e-1); testScoring(model,fr); // test scoring model.score(fr).delete(); hex.ModelMetricsBinomial mm = hex.ModelMetricsBinomial.getFromDKV(model,fr); hex.AUC2 adata = mm._auc; assertEquals(model._output._training_metrics.auc_obj()._auc, adata._auc, 1e-8); assertEquals(0.7654038154645615, adata.pr_auc(), 1e-8); assertEquals(model._output._training_metrics._MSE, mm._MSE, 1e-8); assertEquals(((ModelMetricsBinomialGLM)model._output._training_metrics)._resDev, ((ModelMetricsBinomialGLM)mm)._resDev, 1e-8); model.score(fr).delete(); mm = hex.ModelMetricsBinomial.getFromDKV(model,fr); assertEquals(model._output._training_metrics.auc_obj()._auc, adata._auc, 1e-8); assertEquals(model._output._training_metrics._MSE, mm._MSE, 1e-8); assertEquals(((ModelMetricsBinomialGLM)model._output._training_metrics)._resDev, ((ModelMetricsBinomialGLM)mm)._resDev, 1e-8); double prior = 1e-5; params._prior = prior; // test the same data and model with prior, should get the same model except for the intercept glm = new GLM(params); model2 = glm.trainModel().get(); for(int i = 0; i < model2.beta().length-1; ++i) assertEquals(model.beta()[i], model2.beta()[i], 1e-8); assertEquals(model.beta()[model.beta().length-1] -Math.log(model._ymu[0] * (1-prior)/(prior * (1-model._ymu[0]))),model2.beta()[model.beta().length-1],1e-10); // run with lambda search, check the final submodel params._lambda_search = true; params._lambda = null; params._alpha = new double[]{0}; params._prior = -1; params._obj_reg = -1; params._max_iterations = 500; params._objective_epsilon = 1e-6; // test the same data and model with prior, should get the same model except for the intercept glm = new GLM(params); model3 = glm.trainModel().get(); double lambda = model3._output._submodels[model3._output._best_lambda_idx].lambda_value; params._lambda_search = false; params._lambda = new double[]{lambda}; ModelMetrics mm3 = ModelMetrics.getFromDKV(model3,fr); assertEquals("mse don't match, " + model3._output._training_metrics._MSE + " != " + mm3._MSE,model3._output._training_metrics._MSE,mm3._MSE,1e-8); assertEquals("res-devs don't match, " + ((ModelMetricsBinomialGLM)model3._output._training_metrics)._resDev + " != " + ((ModelMetricsBinomialGLM)mm3)._resDev,((ModelMetricsBinomialGLM)model3._output._training_metrics)._resDev, ((ModelMetricsBinomialGLM)mm3)._resDev,1e-4); fr.add("CAPSULE", fr.remove("CAPSULE")); fr.remove("ID").remove(); DKV.put(fr._key,fr); DataInfo dinfo = new DataInfo(fr, null, 1, true, TransformType.NONE, DataInfo.TransformType.NONE, true, false, false, false, false, false); model3.score(fr).delete(); mm3 = ModelMetrics.getFromDKV(model3,fr); assertEquals("mse don't match, " + model3._output._training_metrics._MSE + " != " + mm3._MSE,model3._output._training_metrics._MSE,mm3._MSE,1e-8); assertEquals("res-devs don't match, " + ((ModelMetricsBinomialGLM)model3._output._training_metrics)._resDev + " != " + ((ModelMetricsBinomialGLM)mm3)._resDev,((ModelMetricsBinomialGLM)model3._output._training_metrics)._resDev, ((ModelMetricsBinomialGLM)mm3)._resDev,1e-4); // test the same data and model with prior, should get the same model except for the intercept glm = new GLM(params); model4 = glm.trainModel().get(); assertEquals("mse don't match, " + model3._output._training_metrics._MSE + " != " + model4._output._training_metrics._MSE,model3._output._training_metrics._MSE,model4._output._training_metrics._MSE,1e-6); assertEquals("res-devs don't match, " + ((ModelMetricsBinomialGLM)model3._output._training_metrics)._resDev + " != " + ((ModelMetricsBinomialGLM)model4._output._training_metrics)._resDev,((ModelMetricsBinomialGLM)model3._output._training_metrics)._resDev, ((ModelMetricsBinomialGLM)model4._output._training_metrics)._resDev,1e-4); model4.score(fr).delete(); ModelMetrics mm4 = ModelMetrics.getFromDKV(model4,fr); assertEquals("mse don't match, " + mm3._MSE + " != " + mm4._MSE,mm3._MSE,mm4._MSE,1e-6); assertEquals("res-devs don't match, " + ((ModelMetricsBinomialGLM)mm3)._resDev + " != " + ((ModelMetricsBinomialGLM)mm4)._resDev,((ModelMetricsBinomialGLM)mm3)._resDev, ((ModelMetricsBinomialGLM)mm4)._resDev,1e-4); // GLMValidation val2 = new GLMValidationTsk(params,model._ymu,rank(model.beta())).doAll(new Vec[]{fr.vec("CAPSULE"),score.vec("1")})._val; // assertEquals(val.residualDeviance(),val2.residualDeviance(),1e-6); // assertEquals(val.nullDeviance(),val2.nullDeviance(),1e-6); } finally { fr.delete(); if(model != null)model.delete(); if(model2 != null)model2.delete(); if(model3 != null)model3.delete(); if(model4 != null)model4.delete(); Scope.exit(); } } @Test public void testQuasibinomial(){ GLMParameters params = new GLMParameters(Family.quasibinomial); GLM glm = new GLM(params); params.validate(glm); params._link = Link.log; try { params.validate(glm); Assert.assertTrue("should've thrown IAE", false); } catch(IllegalArgumentException iae){ // do nothing } // test it behaves like binomial on binary data GLMModel model = null; Frame fr = parse_test_file("smalldata/glm_test/prostate_cat_replaced.csv"); try { Scope.enter(); // R results // Coefficients: // (Intercept) ID AGE RACER2 RACER3 DPROS DCAPS PSA VOL GLEASON // -8.894088 0.001588 -0.009589 0.231777 -0.459937 0.556231 0.556395 0.027854 -0.011355 1.010179 String[] cfs1 = new String[]{"Intercept", "AGE", "RACE.R2", "RACE.R3", "DPROS", "DCAPS", "PSA", "VOL", "GLEASON"}; double[] vals = new double[]{-8.14867, -0.01368, 0.32337, -0.38028, 0.55964, 0.49548, 0.02794, -0.01104, 0.97704}; params = new GLMParameters(Family.quasibinomial); params._response_column = "CAPSULE"; params._ignored_columns = new String[]{"ID"}; params._train = fr._key; params._lambda = new double[]{0}; params._nfolds = 5; params._standardize = false; params._link = Link.logit; // params._missing_values_handling = MissingValuesHandling.Skip; glm = new GLM(params); model = glm.trainModel().get(); HashMap<String, Double> coefs = model.coefficients(); System.out.println(coefs); for (int i = 0; i < cfs1.length; ++i) assertEquals(vals[i], coefs.get(cfs1[i]), 1e-4); assertEquals(512.3, nullDeviance(model), 1e-1); assertEquals(378.3, residualDeviance(model), 1e-1); assertEquals(371, resDOF(model), 0); } finally { fr.delete(); if(model != null){ model.deleteCrossValidationModels(); model.delete(); } Scope.exit(); } } @Test public void testSynthetic() throws Exception { GLMModel model = null; Frame fr = parse_test_file("smalldata/glm_test/glm_test2.csv"); Frame score = null; try { Scope.enter(); GLMParameters params = new GLMParameters(Family.binomial); params._response_column = "response"; // params._response = fr.find(params._response_column); params._ignored_columns = new String[]{"ID"}; params._train = fr._key; params._lambda = new double[]{0}; params._standardize = false; params._max_iterations = 20; GLM glm = new GLM( params); model = glm.trainModel().get(); double [] beta = model.beta(); System.out.println("beta = " + Arrays.toString(beta)); assertEquals(auc(model), 1, 1e-4); score = model.score(fr); hex.ModelMetricsBinomial mm = hex.ModelMetricsBinomial.getFromDKV(model,fr); hex.AUC2 adata = mm._auc; assertEquals(auc(model), adata._auc, 1e-2); } finally { fr.remove(); if(model != null)model.delete(); if(score != null)score.delete(); Scope.exit(); } } @Test //PUBDEV-1839 public void testCitibikeReproPUBDEV1839() throws Exception { GLMModel model = null; Frame tfr = parse_test_file("smalldata/jira/pubdev_1839_repro_train.csv"); Frame vfr = parse_test_file("smalldata/jira/pubdev_1839_repro_test.csv"); try { Scope.enter(); GLMParameters params = new GLMParameters(Family.poisson); params._response_column = "bikes"; params._train = tfr._key; params._valid = vfr._key; GLM glm = new GLM(params); model = glm.trainModel().get(); testScoring(model,vfr); } finally { tfr.remove(); vfr.remove(); if(model != null)model.delete(); Scope.exit(); } } @Test public void testCitibikeReproPUBDEV1953() throws Exception { GLMModel model = null; Frame tfr = parse_test_file("smalldata/glm_test/citibike_small_train.csv"); Frame vfr = parse_test_file("smalldata/glm_test/citibike_small_test.csv"); try { Scope.enter(); GLMParameters params = new GLMParameters(Family.poisson); params._response_column = "bikes"; params._train = tfr._key; params._valid = vfr._key; params._family = Family.poisson; GLM glm = new GLM( params); model = glm.trainModel().get(); testScoring(model,vfr); } finally { tfr.remove(); vfr.remove(); if(model != null)model.delete(); Scope.exit(); } } @Test public void testXval(){ GLMModel model = null; Frame fr = parse_test_file("smalldata/glm_test/prostate_cat_replaced.csv"); try{ GLMParameters params = new GLMParameters(Family.binomial); params._response_column = "CAPSULE"; params._ignored_columns = new String[]{"ID"}; params._train = fr._key; params._lambda_search = true; params._nfolds = 3; params._standardize = false; params._keep_cross_validation_models = true; GLM glm = new GLM(params); model = glm.trainModel().get(); } finally { fr.delete(); if(model != null) { for(Key k:model._output._cross_validation_models) Keyed.remove(k); model.delete(); } } } /** * Test that lambda search gets (almost) the same result as running the model for each lambda separately. */ @Test public void testCustomLambdaSearch(){ Key pros = Key.make("prostate"); Frame f = parse_test_file(pros, "smalldata/glm_test/prostate_cat_replaced.csv"); for(Family fam:new Family[]{Family.multinomial,Family.binomial}) { for (double alpha : new double[]{0, .5, 1}) { for (Solver s : Solver.values()) { if (s == Solver.COORDINATE_DESCENT_NAIVE || s== Solver.AUTO || s.equals(Solver.GRADIENT_DESCENT_LH) || s.equals(Solver.GRADIENT_DESCENT_SQERR)) continue; // if(fam == Family.multinomial && (s != Solver.L_BFGS || alpha != 0)) continue; try { Scope.enter(); GLMParameters parms = new GLMParameters(fam); parms._train = pros; parms._alpha = new double[]{alpha}; parms._solver = s; parms._lambda = new double[]{10, 1, .1, 1e-5, 0}; parms._lambda_search = true; parms._response_column = fam == Family.multinomial?"RACE":"CAPSULE"; GLMModel model = new GLM(parms).trainModel().get(); GLMModel.RegularizationPath rp = model.getRegularizationPath(); for (int i = 0; i < parms._lambda.length; ++i) { GLMParameters parms2 = new GLMParameters(fam); parms2._train = pros; parms2._alpha = new double[]{alpha}; parms2._solver = s; parms2._lambda = new double[]{parms._lambda[i]}; parms2._lambda_search = false; parms2._response_column = fam == Family.multinomial?"RACE":"CAPSULE"; parms2._beta_epsilon = 1e-5; parms2._objective_epsilon = 1e-8; GLMModel model2 = new GLM(parms2).trainModel().get(); double[] beta_ls = rp._coefficients_std[i]; double [] beta = fam == Family.multinomial?flat(model2._output.getNormBetaMultinomial()):model2._output.getNormBeta(); System.out.println(ArrayUtils.pprint(new double[][]{beta,beta_ls})); // Can't compare beta here, have to compare objective value double null_dev = ((GLMMetrics) model2._output._training_metrics).null_deviance(); double res_dev_ls = null_dev * (1 - rp._explained_deviance_train[i]); double likelihood_ls = .5 * res_dev_ls; double likelihood = .5 * ((GLMMetrics) model2._output._training_metrics).residual_deviance(); double nobs = model._nobs; if(fam == Family.multinomial){ beta = beta.clone(); beta_ls = beta_ls.clone(); int P = beta.length/model._output.nclasses(); assert beta.length == P*model._output.nclasses(); for(int j = P-1; j < beta.length; j += P) { beta[j] = 0; beta_ls[j] = 0; } } double obj_ls = likelihood_ls / nobs + ((1 - alpha) * parms._lambda[i] * .5 * ArrayUtils.l2norm2(beta_ls, true)) + alpha * parms._lambda[i] * ArrayUtils.l1norm(beta_ls, true); double obj = likelihood / nobs + ((1 - alpha) * parms._lambda[i] * .5 * ArrayUtils.l2norm2(beta, true)) + alpha * parms._lambda[i] * ArrayUtils.l1norm(beta, true); Assert.assertEquals(obj, obj_ls, 2*parms._objective_epsilon); model2.delete(); } model.delete(); } finally { Scope.exit(); } } } } f.delete(); } /** * Test strong rules on arcene datasets (10k predictors, 100 rows). * Should be able to obtain good model (~100 predictors, ~1 explained deviance) with up to 250 active predictors. * Scaled down (higher lambda min, fewer lambdas) to run at reasonable speed (whole test takes 20s on my laptop). * * Test runs glm with gaussian on arcene dataset and verifies it gets all lambda while limiting maximum actove predictors to reasonably small number. * Compares the objective value to expected one. */ @Test public void testArcene() throws InterruptedException, ExecutionException{ Key parsed = Key.make("arcene_parsed"); Key<GLMModel> modelKey = Key.make("arcene_model"); GLMModel model = null; Frame fr = parse_test_file(parsed, "smalldata/glm_test/arcene.csv"); try{ Scope.enter(); // test LBFGS with l1 pen GLMParameters params = new GLMParameters(Family.gaussian); // params._response = 0; params._lambda = null; params._response_column = fr._names[0]; params._train = parsed; params._lambda_search = true; params._nlambdas = 35; params._lambda_min_ratio = 0.18; params._max_iterations = 100000; params._max_active_predictors = 10000; params._alpha = new double[]{1}; for(Solver s: new Solver[]{Solver.IRLSM, Solver.COORDINATE_DESCENT}){//Solver.COORDINATE_DESCENT,}) { // LBFGS lambda-search is too slow now params._solver = s; GLM glm = new GLM( params, modelKey); glm.trainModel().get(); model = DKV.get(modelKey).get(); System.out.println(model._output._model_summary); // assert on that we got all submodels (if strong rules work, we should be able to get the results with this many active predictors) assertEquals(params._nlambdas, model._output._submodels.length); System.out.println(model._output._training_metrics); // assert on the quality of the result, technically should compare objective value, but this should be good enough for now } model.delete(); params._solver = Solver.COORDINATE_DESCENT; params._max_active_predictors = 100; params._lambda_min_ratio = 1e-2; params._nlambdas = 100; GLM glm = new GLM( params, modelKey); glm.trainModel().get(); model = DKV.get(modelKey).get(); assertTrue(model._output.rank() <= params._max_active_predictors); // System.out.println("============================================================================================================"); System.out.println(model._output._model_summary); // assert on that we got all submodels (if strong rules work, we should be able to get the results with this many active predictors) System.out.println(model._output._training_metrics); System.out.println("============================================================================================================"); model.delete(); params._max_active_predictors = 250; params._lambda = null; params._lambda_search = false; glm = new GLM( params, modelKey); glm.trainModel().get(); model = DKV.get(modelKey).get(); assertTrue(model._output.rank() <= params._max_active_predictors); // System.out.println("============================================================================================================"); System.out.println(model._output._model_summary); // assert on that we got all submodels (if strong rules work, we should be able to get the results with this many active predictors) System.out.println(model._output._training_metrics); System.out.println("============================================================================================================"); model.delete(); } finally { fr.delete(); if(model != null)model.delete(); Scope.exit(); } } /** Test large GLM POJO model generation. * Make a 10K predictor model, emit, javac, and score with it. */ @Test public void testBigPOJO() { GLMModel model = null; Frame fr = parse_test_file(Key.make("arcene_parsed"), "smalldata/glm_test/arcene.csv"), res=null; try{ Scope.enter(); // test LBFGS with l1 pen GLMParameters params = new GLMParameters(Family.gaussian); // params._response = 0; params._lambda = null; params._response_column = fr._names[0]; params._train = fr._key; params._max_active_predictors = 100000; params._alpha = new double[]{0}; params._solver = Solver.L_BFGS; GLM glm = new GLM(params); model = glm.trainModel().get(); res = model.score(fr); model.testJavaScoring(fr,res,0.0); } finally { fr.delete(); if(model != null) model.delete(); if( res != null ) res.delete(); Scope.exit(); } } @Test public void testAbalone() { Scope.enter(); GLMModel model = null; try { Frame fr = parse_test_file("smalldata/glm_test/Abalone.gz"); Scope.track(fr); GLMParameters params = new GLMParameters(Family.gaussian); params._train = fr._key; params._response_column = fr._names[8]; params._alpha = new double[]{1.0}; params._lambda_search = true; GLM glm = new GLM(params); model = glm.trainModel().get(); testScoring(model,fr); } finally { if( model != null ) model.delete(); Scope.exit(); } } @Test public void testZeroedColumn(){ Vec x = Vec.makeCon(Vec.newKey(),1,2,3,4,5); Vec y = Vec.makeCon(x.group().addVec(),0,1,0,1,0); Vec z = Vec.makeCon(Vec.newKey(),1,2,3,4,5); Vec w = Vec.makeCon(x.group().addVec(),1,0,1,0,1); Frame fr = new Frame(Key.<Frame>make("test"),new String[]{"x","y","z","w"},new Vec[]{x,y,z,w}); DKV.put(fr); GLMParameters parms = new GLMParameters(Family.gaussian); parms._train = fr._key; parms._lambda = new double[]{0}; parms._alpha = new double[]{0}; parms._compute_p_values = true; parms._response_column = "z"; parms._weights_column = "w"; GLMModel m = new GLM(parms).trainModel().get(); System.out.println(m.coefficients()); m.delete(); fr.delete(); } @Test public void testDeviances() { for (Family fam : Family.values()) { if(fam == Family.quasibinomial || fam == Family.ordinal) continue; Frame tfr = null; Frame res = null; Frame preds = null; GLMModel gbm = null; try { tfr = parse_test_file("./smalldata/gbm_test/BostonHousing.csv"); GLMModel.GLMParameters parms = new GLMModel.GLMParameters(); parms._train = tfr._key; String resp = tfr.lastVecName(); if (fam==Family.binomial || fam==Family.multinomial || fam == Family.fractionalbinomial) { resp = fam==Family.multinomial?"rad":"chas"; Vec v = tfr.remove(resp); tfr.add(resp, v.toCategoricalVec()); v.remove(); DKV.put(tfr); } parms._response_column = resp; parms._family = fam; gbm = new GLM(parms).trainModel().get(); preds = gbm.score(tfr); res = gbm.computeDeviances(tfr,preds,"myDeviances"); double meanDeviances = res.anyVec().mean(); if (gbm._output.nclasses()==2) Assert.assertEquals(meanDeviances,((ModelMetricsBinomial) gbm._output._training_metrics)._logloss,1e-6*Math.abs(meanDeviances)); else if (gbm._output.nclasses()>2) Assert.assertEquals(meanDeviances,((ModelMetricsMultinomial) gbm._output._training_metrics)._logloss,1e-6*Math.abs(meanDeviances)); else Assert.assertEquals(meanDeviances,((ModelMetricsRegression) gbm._output._training_metrics)._mean_residual_deviance,1e-6*Math.abs(meanDeviances)); } finally { if (tfr != null) tfr.delete(); if (res != null) res.delete(); if (preds != null) preds.delete(); if (gbm != null) gbm.delete(); } } } /** * train = data.frame(c('red', 'blue','blue'),c('x','x','y'),c(1,'0','0')) names(train)= c('color', 'letter', 'label') test = data.frame(c('red', 'blue','blue','yellow'),c('x','x','y','y'),c(1,'0','0','0')) names(test)= c('color', 'letter', 'label') htrain = as.h2o(train) htest = as.h2o(test) hh = h2o.glm(x = 1:2,y = 3,training_frame = htrain,family = "binomial",max_iterations = 15,alpha = 1,missing_values_handling = 'Skip') h2o.predict(hh,htest) */ @Test public void testUnseenLevels(){ Scope.enter(); try { Vec v0 = Vec.makeCon(Vec.newKey(), 1, 0, 0, 1,1); v0.setDomain(new String[]{"blue", "red"}); Frame trn = new Frame(Key.<Frame>make("train"), new String[]{"color", "label"}, new Vec[]{v0, v0.makeCopy(null)}); DKV.put(trn); Vec v3 = Vec.makeCon(Vec.newKey(), 1, 0, 0, 2); v3.setDomain(new String[]{"blue", "red", "yellow"}); Vec v5 = Vec.makeCon(v3.group().addVec(), 1, 0, 0, 0); Frame tst = new Frame(Key.<Frame>make("test"), new String[]{"color", "label"}, new Vec[]{v3, v5}); DKV.put(tst); GLMParameters parms = new GLMParameters(Family.gaussian); parms._train = trn._key; parms._response_column = "label"; parms._missing_values_handling = MissingValuesHandling.Skip; GLMParameters parms2 = (GLMParameters) parms.clone(); GLMModel m = new GLM(parms).trainModel().get(); System.out.println("coefficients = " + m.coefficients()); double icpt = m.coefficients().get("Intercept"); Frame preds = m.score(tst); Assert.assertEquals(icpt+m.coefficients().get("color.red"), preds.vec(0).at(0), 0); Assert.assertEquals(icpt+m.coefficients().get("color.blue"), preds.vec(0).at(1), 0); Assert.assertEquals(icpt+m.coefficients().get("color.blue"), preds.vec(0).at(2), 0); Assert.assertEquals(icpt, preds.vec(0).at(3), 0); parms2._missing_values_handling = MissingValuesHandling.MeanImputation; GLMModel m2 = new GLM(parms2).trainModel().get(); Frame preds2 = m2.score(tst); icpt = m2.coefficients().get("Intercept"); System.out.println("coefficients = " + m2.coefficients()); Assert.assertEquals(icpt+m2.coefficients().get("color.red"), preds2.vec(0).at(0), 0); Assert.assertEquals(icpt+m2.coefficients().get("color.blue"), preds2.vec(0).at(1), 0); Assert.assertEquals(icpt+m2.coefficients().get("color.blue"), preds2.vec(0).at(2), 0); Assert.assertEquals(icpt+m2.coefficients().get("color.red"), preds2.vec(0).at(3), 0); trn.delete(); tst.delete(); m.delete(); preds.delete(); preds2.delete(); m2.delete(); }finally { Scope.exit(); } } @Test public void testIsFeatureUsedInPredict() { isFeatureUsedInPredictHelper(false, false); isFeatureUsedInPredictHelper(true, false); isFeatureUsedInPredictHelper(false, true); isFeatureUsedInPredictHelper(true, true); } private void isFeatureUsedInPredictHelper(boolean ignoreConstCols, boolean multinomial) { Scope.enter(); Vec target = Vec.makeRepSeq(100, 3); if (multinomial) target = target.toCategoricalVec(); Vec zeros = Vec.makeCon(0d, 100); Vec nonzeros = Vec.makeCon(1e10d, 100); Frame dummyFrame = new Frame( new String[]{"a", "b", "c", "d", "e", "target"}, new Vec[]{zeros, zeros, zeros, zeros, target, target} ); dummyFrame._key = Key.make("DummyFrame_testIsFeatureUsedInPredict"); Frame otherFrame = new Frame( new String[]{"a", "b", "c", "d", "e", "target"}, new Vec[]{nonzeros, nonzeros, nonzeros, nonzeros, target, target} ); Frame reference = null; Frame prediction = null; GLMModel model = null; try { DKV.put(dummyFrame); GLMModel.GLMParameters glm = new GLMModel.GLMParameters(); glm._train = dummyFrame._key; glm._response_column = "target"; glm._seed = 1; glm._ignore_const_cols = ignoreConstCols; if (multinomial) { glm._family = Family.multinomial; } GLM job = new GLM(glm); model = job.trainModel().get(); String lastUsedFeature = ""; int usedFeatures = 0; for(String feature : model._output._names) { if (model.isFeatureUsedInPredict(feature)) { usedFeatures ++; lastUsedFeature = feature; } } assertEquals(1, usedFeatures); assertEquals("e", lastUsedFeature); reference = model.score(dummyFrame); prediction = model.score(otherFrame); for (int i = 0; i < reference.numRows(); i++) { assertEquals(reference.vec(0).at(i), prediction.vec(0).at(i), 1e-10); } } finally { dummyFrame.delete(); if (model != null) model.delete(); if (reference != null) reference.delete(); if (prediction != null) prediction.delete(); target.remove(); zeros.remove(); nonzeros.remove(); Scope.exit(); } } /** * testBounds() from this file adjusted to use AGE as categorical column */ @Test public void testBoundsCategoricalCol() { Scope.enter(); Key parsed = Key.make("prostate_parsed"); Key modelKey = Key.make("prostate_model"); Frame fr = Scope.track(parse_test_file(parsed, "smalldata/logreg/prostate.csv")); fr.toCategoricalCol("AGE"); Key betaConsKey = Key.make("beta_constraints"); FVecFactory.makeByteVec(betaConsKey, "names, lower_bounds, upper_bounds\n AGE, -.5, .5\n RACE, -.5, .5\n DCAPS, -.4, .4\n DPROS, -.5, .5 \nPSA, -.5, .5\n VOL, -.5, .5\nGLEASON, -.5, .5"); Frame betaConstraints = Scope.track(ParseDataset.parse(Key.make("beta_constraints.hex"), betaConsKey)); try { // H2O differs on intercept and race, same residual deviance though GLMParameters params = new GLMParameters(); params._standardize = true; params._family = Family.binomial; params._beta_constraints = betaConstraints._key; params._response_column = "CAPSULE"; params._ignored_columns = new String[]{"ID"}; params._train = fr._key; params._objective_epsilon = 0; params._alpha = new double[]{1}; params._lambda = new double[]{0.001607}; params._obj_reg = 1.0/380; GLM glm = new GLM( params, modelKey); GLMModel model = glm.trainModel().get(); Scope.track_generic(model); assertTrue(glm.isStopped()); ModelMetricsBinomialGLM val = (ModelMetricsBinomialGLM) model._output._training_metrics; assertEquals(512.2888, val._nullDev, 1e-1); assertTrue(val._resDev <= 388.5); model.delete(); params._lambda = new double[]{0}; params._alpha = new double[]{0}; FVecFactory.makeByteVec(betaConsKey, "names, lower_bounds, upper_bounds\n RACE, -.5, .5\n DCAPS, -.4, .4\n DPROS, -.5, .5 \nPSA, -.5, .5\n VOL, -.5, .5\n AGE, -.5, .5"); betaConstraints = ParseDataset.parse(Key.make("beta_constraints.hex"), betaConsKey); glm = new GLM( params, modelKey); model = glm.trainModel().get(); Scope.track_generic(model); assertTrue(glm.isStopped()); double[] beta = model.beta(); System.out.println("beta = " + Arrays.toString(beta)); fr.add("CAPSULE", fr.remove("CAPSULE")); fr.remove("ID").remove(); DKV.put(fr._key, fr); DataInfo dinfo = new DataInfo(fr, null, 1, true, TransformType.NONE, DataInfo.TransformType.NONE, true, false, false, false, false, false); GLMGradientTask lt = new GLMBinomialGradientTask(null,dinfo,params,0,beta).doAll(dinfo._adaptedFrame); double [] grad = lt._gradient; String [] names = model.dinfo().coefNames(); BufferedString tmpStr = new BufferedString(); outer: for (int i = 0; i < names.length; ++i) { for (int j = 0; j < betaConstraints.numRows(); ++j) { if (betaConstraints.vec("names").atStr(tmpStr, j).toString().equals(names[i])) { if (Math.abs(beta[i] - betaConstraints.vec("lower_bounds").at(j)) < 1e-4 || Math.abs(beta[i] - betaConstraints.vec("upper_bounds").at(j)) < 1e-4) { continue outer; } } } assertEquals(0, grad[i], 1e-2); } } finally { Scope.exit(); } } }
Fix GLMTest: redundant call to DataInfo is causing local DKV inconsistency
h2o-algos/src/test/java/hex/glm/GLMTest.java
Fix GLMTest: redundant call to DataInfo is causing local DKV inconsistency
<ide><path>2o-algos/src/test/java/hex/glm/GLMTest.java <ide> assertEquals("res-devs don't match, " + ((ModelMetricsBinomialGLM)model3._output._training_metrics)._resDev + " != " + ((ModelMetricsBinomialGLM)mm3)._resDev,((ModelMetricsBinomialGLM)model3._output._training_metrics)._resDev, ((ModelMetricsBinomialGLM)mm3)._resDev,1e-4); <ide> fr.add("CAPSULE", fr.remove("CAPSULE")); <ide> fr.remove("ID").remove(); <del> DKV.put(fr._key,fr); <del> DataInfo dinfo = new DataInfo(fr, null, 1, true, TransformType.NONE, DataInfo.TransformType.NONE, true, false, false, false, false, false); <add> DKV.put(fr); <ide> model3.score(fr).delete(); <ide> mm3 = ModelMetrics.getFromDKV(model3,fr); <ide> assertEquals("mse don't match, " + model3._output._training_metrics._MSE + " != " + mm3._MSE,model3._output._training_metrics._MSE,mm3._MSE,1e-8);
Java
apache-2.0
007cf443016170a8b4f4afc433a91475ea2f3bd2
0
networknt/light-codegen,networknt/light-codegen,networknt/light-codegen,networknt/light-codegen
package com.networknt.codegen.rest; import com.fasterxml.jackson.databind.JsonNode; import com.networknt.codegen.Generator; import com.networknt.config.JsonMapper; import com.networknt.jsonoverlay.Overlay; import com.networknt.oas.OpenApiParser; import com.networknt.oas.model.*; import com.networknt.oas.model.impl.OpenApi3Impl; import com.networknt.utility.StringUtils; import java.io.ByteArrayInputStream; import java.io.IOException; import java.io.InputStream; import java.net.MalformedURLException; import java.net.URL; import java.nio.file.Paths; import java.util.*; import static java.io.File.separator; public class OpenApiLightGenerator implements OpenApiGenerator { public static final String FRAMEWORK="openapi"; @Override public String getFramework() { return FRAMEWORK; } public OpenApiLightGenerator() { } /** * * @param targetPath The output directory of the generated project * @param model The optional model data that trigger the generation, i.e. swagger specification, graphql IDL etc. * @param config A json object that controls how the generator behaves. * * @throws IOException IO Exception occurs during code generation */ @Override public void generate(final String targetPath, Object model, JsonNode config) throws IOException { // whoever is calling this needs to make sure that model is converted to Map<String, Object> String rootPackage = getRootPackage(config, null); String modelPackage = getModelPackage(config, null); String handlerPackage = getHandlerPackage(config, null); String servicePackage = getServicePackage(config, null); boolean overwriteHandler = isOverwriteHandler(config, null); boolean overwriteHandlerTest = isOverwriteHandlerTest(config, null); boolean overwriteModel = isOverwriteModel(config, null); boolean generateModelOnly = isGenerateModelOnly(config, null); boolean enableHttp = isEnableHttp(config, null); String httpPort = getHttpPort(config, null); boolean enableHttps = isEnableHttps(config, null); String httpsPort = getHttpsPort(config, null); boolean enableHttp2 = isEnableHttp2(config, null); boolean enableRegistry = isEnableRegistry(config, null); boolean eclipseIDE = isEclipseIDE(config, null); boolean supportClient = isSupportClient(config, null); boolean prometheusMetrics = isPrometheusMetrics(config, null); String dockerOrganization = getDockerOrganization(config, null); String version = getVersion(config, null); String groupId = getGroupId(config, null); String artifactId = getArtifactId(config, null); String serviceId = groupId + "." + artifactId + "-" + version; boolean specChangeCodeReGenOnly = isSpecChangeCodeReGenOnly(config, null); boolean enableParamDescription = isEnableParamDescription(config, null); boolean skipPomFile = isSkipPomFile(config, null); boolean kafkaProducer = isKafkaProducer(config, null); boolean kafkaConsumer = isKafkaConsumer(config, null); boolean supportAvro = isSupportAvro(config, null); boolean useLightProxy = isUseLightProxy(config, null); String kafkaTopic = getKafkaTopic(config, null); String decryptOption = getDecryptOption(config, null); boolean supportDb = isSupportDb(config, null); boolean supportH2ForTest = isSupportH2ForTest(config, null); boolean buildMaven = isBuildMaven(config, true); // override the default value false to make sure backward compatible. boolean multipleModule = isMultipleModule(config, null); String configFolder = multipleModule ? "server.src.main.resources.config" : "src.main.resources.config"; String testConfigFolder = multipleModule ? "server.src.test.resources.config" : "src.test.resources.config"; // get the list of operations for this model List<Map<String, Object>> operationList = getOperationList(model, config); // bypass project generation if the mode is the only one requested to be built if (!generateModelOnly) { // if set to true, regenerate the code only (handlers, model and the handler.yml, potentially affected by operation changes if (!specChangeCodeReGenOnly) { // generate configurations, project, masks, certs, etc if(buildMaven) { if (!skipPomFile) { if(multipleModule) { transfer(targetPath, "", "pom.xml", templates.rest.parent.pom.template(config)); transfer(targetPath, "model", "pom.xml", templates.rest.model.pom.template(config)); transfer(targetPath, "service", "pom.xml", templates.rest.service.pom.template(config)); transfer(targetPath, "server", "pom.xml", templates.rest.server.pom.template(config)); transfer(targetPath, "client", "pom.xml", templates.rest.client.pom.template(config)); } else { transfer(targetPath, "", "pom.xml", templates.rest.single.pom.template(config)); } } transferMaven(targetPath); } else { if(multipleModule) { transfer(targetPath, "", "build.gradle.kts", templates.rest.parent.buildGradleKts.template(config)); transfer(targetPath, "", "gradle.properties", templates.rest.parent.gradleProperties.template(config)); transfer(targetPath, "", "settings.gradle.kts", templates.rest.parent.settingsGradleKts.template()); transfer(targetPath, "model", "build.gradle.kts", templates.rest.model.buildGradleKts.template(config)); transfer(targetPath, "model", "settings.gradle.kts", templates.rest.model.settingsGradleKts.template()); transfer(targetPath, "service", "build.gradle.kts", templates.rest.service.buildGradleKts.template(config)); transfer(targetPath, "service", "settings.gradle.kts", templates.rest.service.settingsGradleKts.template()); transfer(targetPath, "server", "build.gradle.kts", templates.rest.server.buildGradleKts.template(config)); transfer(targetPath, "server", "settings.gradle.kts", templates.rest.server.settingsGradleKts.template()); transfer(targetPath, "client", "build.gradle.kts", templates.rest.client.buildGradleKts.template(config)); transfer(targetPath, "client", "settings.gradle.kts", templates.rest.client.settingsGradleKts.template()); } else { transfer(targetPath, "", "build.gradle.kts", templates.rest.single.buildGradleKts.template(config)); transfer(targetPath, "", "gradle.properties", templates.rest.single.gradleProperties.template(config)); transfer(targetPath, "", "settings.gradle.kts", templates.rest.single.settingsGradleKts.template()); } transferGradle(targetPath); } // There is only one port that should be exposed in Dockerfile, otherwise, the service // discovery will be so confused. If https is enabled, expose the https port. Otherwise http port. String expose = ""; if (enableHttps) { expose = httpsPort; } else { expose = httpPort; } transfer(targetPath, "docker", "Dockerfile", templates.rest.dockerfile.template(config, expose)); transfer(targetPath, "docker", "Dockerfile-Slim", templates.rest.dockerfileslim.template(config, expose)); transfer(targetPath, "", "build.sh", templates.rest.buildSh.template(config, serviceId)); transfer(targetPath, "", "kubernetes.yml", templates.rest.kubernetes.template(dockerOrganization, serviceId, config.get("artifactId").textValue(), expose, version)); transfer(targetPath, "", ".gitignore", templates.rest.gitignore.template()); transfer(targetPath, "", "README.md", templates.rest.README.template(config)); transfer(targetPath, "", "LICENSE", templates.rest.LICENSE.template()); if(eclipseIDE) { transfer(targetPath, "", ".classpath", templates.rest.classpath.template()); transfer(targetPath, "", ".project", templates.rest.project.template(config)); } // config transfer(targetPath, (configFolder).replace(".", separator), "service.yml", templates.rest.serviceYml.template(config)); transfer(targetPath, (configFolder).replace(".", separator), "server.yml", templates.rest.serverYml.template(serviceId, enableHttp, httpPort, enableHttps, httpsPort, enableHttp2, enableRegistry, version)); transfer(targetPath, (testConfigFolder).replace(".", separator), "server.yml", templates.rest.serverYml.template(serviceId, enableHttp, "49587", enableHttps, "49588", enableHttp2, enableRegistry, version)); transfer(targetPath, (configFolder).replace(".", separator), "openapi-security.yml", templates.rest.openapiSecurity.template()); transfer(targetPath, (configFolder).replace(".", separator), "openapi-validator.yml", templates.rest.openapiValidator.template()); if (supportClient) { transfer(targetPath, (configFolder).replace(".", separator), "client.yml", templates.rest.clientYml.template()); } else { transfer(targetPath, (testConfigFolder).replace(".", separator), "client.yml", templates.rest.clientYml.template()); } transfer(targetPath, (configFolder).replace(".", separator), "primary.crt", templates.rest.primaryCrt.template()); transfer(targetPath, (configFolder).replace(".", separator), "secondary.crt", templates.rest.secondaryCrt.template()); if(kafkaProducer) { transfer(targetPath, (configFolder).replace(".", separator), "kafka-producer.yml", templates.rest.kafkaProducerYml.template(kafkaTopic)); } if(kafkaConsumer) { transfer(targetPath, (configFolder).replace(".", separator), "kafka-streams.yml", templates.rest.kafkaStreamsYml.template(artifactId)); } if(supportAvro) { transfer(targetPath, (configFolder).replace(".", separator), "schema-registry.yml", templates.rest.schemaRegistryYml.template()); } // mask transfer(targetPath, (configFolder).replace(".", separator), "mask.yml", templates.rest.maskYml.template()); // logging transfer(targetPath, (multipleModule ? "server.src.main.resources" : "src.main.resources").replace(".", separator), "logback.xml", templates.rest.logback.template(rootPackage)); transfer(targetPath, (multipleModule ? "server.src.test.resources" : "src.test.resources").replace(".", separator), "logback-test.xml", templates.rest.logback.template(rootPackage)); // exclusion list for Config module transfer(targetPath, (configFolder).replace(".", separator), "config.yml", templates.rest.config.template(config)); transfer(targetPath, (configFolder).replace(".", separator), "audit.yml", templates.rest.auditYml.template()); transfer(targetPath, (configFolder).replace(".", separator), "body.yml", templates.rest.bodyYml.template()); transfer(targetPath, (configFolder).replace(".", separator), "info.yml", templates.rest.infoYml.template()); transfer(targetPath, (configFolder).replace(".", separator), "correlation.yml", templates.rest.correlationYml.template()); transfer(targetPath, (configFolder).replace(".", separator), "metrics.yml", templates.rest.metricsYml.template()); transfer(targetPath, (configFolder).replace(".", separator), "sanitizer.yml", templates.rest.sanitizerYml.template()); transfer(targetPath, (configFolder).replace(".", separator), "traceability.yml", templates.rest.traceabilityYml.template()); transfer(targetPath, (configFolder).replace(".", separator), "health.yml", templates.rest.healthYml.template()); // added with #471 transfer(targetPath, (configFolder).replace(".", separator), "app-status.yml", templates.rest.appStatusYml.template()); // values.yml file, transfer to suppress the warning message during start startup and encourage usage. transfer(targetPath, (configFolder).replace(".", separator), "values.yml", templates.rest.values.template()); // add portal-registry.yml transfer(targetPath, (configFolder).replace(".", separator), "portal-registry.yml", templates.rest.portalRegistryYml.template()); } // routing handler transfer(targetPath, (configFolder).replace(".", separator), "handler.yml", templates.rest.handlerYml.template(serviceId, handlerPackage, operationList, prometheusMetrics, useLightProxy)); } // model OpenApi3 openApi3 = null; try { openApi3 = (OpenApi3)new OpenApiParser().parse((JsonNode)model, new URL("https://oas.lightapi.net/")); } catch (MalformedURLException e) { throw new RuntimeException("Failed to parse the model", e); } Map<String, Object> specMap = JsonMapper.string2Map(Overlay.toJson((OpenApi3Impl)openApi3).toString()); Map<String, Object> components = (Map<String, Object>)specMap.get("components"); if(components != null) { Map<String, Object> schemas = (Map<String, Object>)components.get("schemas"); if(schemas != null) { ArrayList<Runnable> modelCreators = new ArrayList<>(); final HashMap<String, Object> references = new HashMap<>(); for (Map.Entry<String, Object> entry : schemas.entrySet()) { loadModel(multipleModule, entry.getKey(), null, (Map<String, Object>)entry.getValue(), schemas, overwriteModel, targetPath, modelPackage, modelCreators, references, null, callback); } for (Runnable r : modelCreators) { r.run(); } } } // exit after generating the model if the consumer needs only the model classes if (generateModelOnly) { return; } // handler String serverFolder = multipleModule ? "server.src.main.java." + handlerPackage : "src.main.java." + handlerPackage; String serviceFolder = multipleModule ? "service.src.main.java." + handlerPackage : "src.main.java." + servicePackage; String serverTestFolder = multipleModule ? "server.src.test.java." + handlerPackage : "src.test.java." + handlerPackage; for (Map<String, Object> op : operationList) { String className = op.get("handlerName").toString(); String serviceName = op.get("serviceName").toString(); Object requestModelNameObject = op.get("requestModelName"); String requestModelName = null; if(requestModelNameObject != null) { requestModelName = requestModelNameObject.toString(); } @SuppressWarnings("unchecked") List<Map> parameters = (List<Map>)op.get("parameters"); Map<String, String> responseExample = (Map<String, String>)op.get("responseExample"); String example = responseExample.get("example"); String statusCode = responseExample.get("statusCode"); statusCode = StringUtils.isBlank(statusCode) || statusCode.equals("default") ? "-1" : statusCode; transfer(targetPath, (serverFolder).replace(".", separator), className + ".java", templates.rest.handler.template(handlerPackage, modelPackage, className, serviceName, requestModelName, parameters)); if (checkExist(targetPath, (serviceFolder).replace(".", separator), serviceName + ".java") && !overwriteHandler) { continue; } transfer(targetPath, (serviceFolder).replace(".", separator), serviceName + ".java", templates.rest.handlerService.template(handlerPackage, modelPackage, serviceName, statusCode, requestModelName, example, parameters)); } // handler test cases if (!specChangeCodeReGenOnly) { transfer(targetPath, (serverTestFolder + ".").replace(".", separator), "TestServer.java", templates.rest.testServer.template(handlerPackage)); } for (Map<String, Object> op : operationList) { if (checkExist(targetPath, (serverTestFolder).replace(".", separator), op.get("handlerName") + "Test.java") && !overwriteHandlerTest) { continue; } transfer(targetPath, (serverTestFolder).replace(".", separator), op.get("handlerName") + "Test.java", templates.rest.handlerTest.template(handlerPackage, op)); } // transfer binary files without touching them. try (InputStream is = OpenApiGenerator.class.getResourceAsStream("/binaries/server.keystore")) { Generator.copyFile(is, Paths.get(targetPath, (configFolder).replace(".", separator), "server.keystore")); } try (InputStream is = OpenApiGenerator.class.getResourceAsStream("/binaries/server.truststore")) { Generator.copyFile(is, Paths.get(targetPath, (configFolder).replace(".", separator), "server.truststore")); } if (supportClient) { try (InputStream is = OpenApiGenerator.class.getResourceAsStream("/binaries/client.keystore")) { Generator.copyFile(is, Paths.get(targetPath, (configFolder).replace(".", separator), "client.keystore")); } try (InputStream is = OpenApiGenerator.class.getResourceAsStream("/binaries/client.truststore")) { Generator.copyFile(is, Paths.get(targetPath, (configFolder).replace(".", separator), "client.truststore")); } } else { try (InputStream is = OpenApiGenerator.class.getResourceAsStream("/binaries/client.keystore")) { Generator.copyFile(is, Paths.get(targetPath, (testConfigFolder).replace(".", separator), "client.keystore")); } try (InputStream is = OpenApiGenerator.class.getResourceAsStream("/binaries/client.truststore")) { Generator.copyFile(is, Paths.get(targetPath, (testConfigFolder).replace(".", separator), "client.truststore")); } } try (InputStream is = new ByteArrayInputStream(Generator.yamlMapper.writeValueAsBytes(model))) { Generator.copyFile(is, Paths.get(targetPath, (configFolder).replace(".", separator), "openapi.yaml")); } } ModelCallback callback = new ModelCallback() { @Override public void callback(boolean multipleModule, String targetPath, String modelPackage, String modelFileName, String enumsIfClass, String parentClassName, String classVarName, boolean abstractIfClass, List<Map<String, Object>> props, List<Map<String, Object>> parentClassProps) { try { transfer(targetPath, ((multipleModule ? "model.src.main.java." : "src.main.java.") + modelPackage).replace(".", separator), modelFileName + ".java", enumsIfClass == null ? templates.rest.pojo.template(modelPackage, modelFileName, parentClassName, classVarName, abstractIfClass, props, parentClassProps) : templates.rest.enumClass.template(modelPackage, modelFileName, enumsIfClass)); } catch (IOException ex) { throw new RuntimeException(ex); } } }; }
light-rest-4j/src/main/java/com/networknt/codegen/rest/OpenApiLightGenerator.java
package com.networknt.codegen.rest; import com.fasterxml.jackson.databind.JsonNode; import com.networknt.codegen.Generator; import com.networknt.config.JsonMapper; import com.networknt.jsonoverlay.Overlay; import com.networknt.oas.OpenApiParser; import com.networknt.oas.model.*; import com.networknt.oas.model.impl.OpenApi3Impl; import com.networknt.utility.StringUtils; import java.io.ByteArrayInputStream; import java.io.IOException; import java.io.InputStream; import java.net.MalformedURLException; import java.net.URL; import java.nio.file.Paths; import java.util.*; import static java.io.File.separator; public class OpenApiLightGenerator implements OpenApiGenerator { public static final String FRAMEWORK="openapi"; @Override public String getFramework() { return FRAMEWORK; } public OpenApiLightGenerator() { } /** * * @param targetPath The output directory of the generated project * @param model The optional model data that trigger the generation, i.e. swagger specification, graphql IDL etc. * @param config A json object that controls how the generator behaves. * * @throws IOException IO Exception occurs during code generation */ @Override public void generate(final String targetPath, Object model, JsonNode config) throws IOException { // whoever is calling this needs to make sure that model is converted to Map<String, Object> String rootPackage = getRootPackage(config, null); String modelPackage = getModelPackage(config, null); String handlerPackage = getHandlerPackage(config, null); String servicePackage = getServicePackage(config, null); boolean overwriteHandler = isOverwriteHandler(config, null); boolean overwriteHandlerTest = isOverwriteHandlerTest(config, null); boolean overwriteModel = isOverwriteModel(config, null); boolean generateModelOnly = isGenerateModelOnly(config, null); boolean enableHttp = isEnableHttp(config, null); String httpPort = getHttpPort(config, null); boolean enableHttps = isEnableHttps(config, null); String httpsPort = getHttpsPort(config, null); boolean enableHttp2 = isEnableHttp2(config, null); boolean enableRegistry = isEnableRegistry(config, null); boolean eclipseIDE = isEclipseIDE(config, null); boolean supportClient = isSupportClient(config, null); boolean prometheusMetrics = isPrometheusMetrics(config, null); String dockerOrganization = getDockerOrganization(config, null); String version = getVersion(config, null); String groupId = getGroupId(config, null); String artifactId = getArtifactId(config, null); String serviceId = groupId + "." + artifactId + "-" + version; boolean specChangeCodeReGenOnly = isSpecChangeCodeReGenOnly(config, null); boolean enableParamDescription = isEnableParamDescription(config, null); boolean skipPomFile = isSkipPomFile(config, null); boolean kafkaProducer = isKafkaProducer(config, null); boolean kafkaConsumer = isKafkaConsumer(config, null); boolean supportAvro = isSupportAvro(config, null); boolean useLightProxy = isUseLightProxy(config, null); String kafkaTopic = getKafkaTopic(config, null); String decryptOption = getDecryptOption(config, null); boolean supportDb = isSupportDb(config, null); boolean supportH2ForTest = isSupportH2ForTest(config, null); boolean buildMaven = isBuildMaven(config, true); // override the default value false to make sure backward compatible. boolean multipleModule = isMultipleModule(config, null); String configFolder = multipleModule ? "server.src.main.resources.config" : "src.main.resources.config"; String testConfigFolder = multipleModule ? "server.src.test.resources.config" : "src.test.resources.config"; // get the list of operations for this model List<Map<String, Object>> operationList = getOperationList(model, config); // bypass project generation if the mode is the only one requested to be built if (!generateModelOnly) { // if set to true, regenerate the code only (handlers, model and the handler.yml, potentially affected by operation changes if (!specChangeCodeReGenOnly) { // generate configurations, project, masks, certs, etc if(buildMaven) { if (!skipPomFile) { if(multipleModule) { transfer(targetPath, "", "pom.xml", templates.rest.parent.pom.template(config)); transfer(targetPath, "model", "pom.xml", templates.rest.model.pom.template(config)); transfer(targetPath, "service", "pom.xml", templates.rest.service.pom.template(config)); transfer(targetPath, "server", "pom.xml", templates.rest.server.pom.template(config)); transfer(targetPath, "client", "pom.xml", templates.rest.client.pom.template(config)); } else { transfer(targetPath, "", "pom.xml", templates.rest.single.pom.template(config)); } } transferMaven(targetPath); } else { if(multipleModule) { transfer(targetPath, "", "build.gradle.kts", templates.rest.parent.buildGradleKts.template(config)); transfer(targetPath, "", "gradle.properties", templates.rest.parent.gradleProperties.template(config)); transfer(targetPath, "", "settings.gradle.kts", templates.rest.parent.settingsGradleKts.template()); transfer(targetPath, "model", "build.gradle.kts", templates.rest.model.buildGradleKts.template(config)); transfer(targetPath, "model", "settings.gradle.kts", templates.rest.model.settingsGradleKts.template()); transfer(targetPath, "service", "build.gradle.kts", templates.rest.service.buildGradleKts.template(config)); transfer(targetPath, "service", "settings.gradle.kts", templates.rest.service.settingsGradleKts.template()); transfer(targetPath, "server", "build.gradle.kts", templates.rest.server.buildGradleKts.template(config)); transfer(targetPath, "server", "settings.gradle.kts", templates.rest.server.settingsGradleKts.template()); transfer(targetPath, "client", "build.gradle.kts", templates.rest.client.buildGradleKts.template(config)); transfer(targetPath, "client", "settings.gradle.kts", templates.rest.client.settingsGradleKts.template()); } else { transfer(targetPath, "", "build.gradle.kts", templates.rest.single.buildGradleKts.template(config)); transfer(targetPath, "", "gradle.properties", templates.rest.single.gradleProperties.template(config)); transfer(targetPath, "", "settings.gradle.kts", templates.rest.single.settingsGradleKts.template()); } transferGradle(targetPath); } // There is only one port that should be exposed in Dockerfile, otherwise, the service // discovery will be so confused. If https is enabled, expose the https port. Otherwise http port. String expose = ""; if (enableHttps) { expose = httpsPort; } else { expose = httpPort; } transfer(targetPath, "docker", "Dockerfile", templates.rest.dockerfile.template(config, expose)); transfer(targetPath, "docker", "Dockerfile-Slim", templates.rest.dockerfileslim.template(config, expose)); transfer(targetPath, "", "build.sh", templates.rest.buildSh.template(config, serviceId)); transfer(targetPath, "", "kubernetes.yml", templates.rest.kubernetes.template(dockerOrganization, serviceId, config.get("artifactId").textValue(), expose, version)); transfer(targetPath, "", ".gitignore", templates.rest.gitignore.template()); transfer(targetPath, "", "README.md", templates.rest.README.template(config)); transfer(targetPath, "", "LICENSE", templates.rest.LICENSE.template()); if(eclipseIDE) { transfer(targetPath, "", ".classpath", templates.rest.classpath.template()); transfer(targetPath, "", ".project", templates.rest.project.template(config)); } // config transfer(targetPath, (configFolder).replace(".", separator), "service.yml", templates.rest.serviceYml.template(config)); transfer(targetPath, (configFolder).replace(".", separator), "server.yml", templates.rest.serverYml.template(serviceId, enableHttp, httpPort, enableHttps, httpsPort, enableHttp2, enableRegistry, version)); transfer(targetPath, (testConfigFolder).replace(".", separator), "server.yml", templates.rest.serverYml.template(serviceId, enableHttp, "49587", enableHttps, "49588", enableHttp2, enableRegistry, version)); transfer(targetPath, (configFolder).replace(".", separator), "openapi-security.yml", templates.rest.openapiSecurity.template()); transfer(targetPath, (configFolder).replace(".", separator), "openapi-validator.yml", templates.rest.openapiValidator.template()); if (supportClient) { transfer(targetPath, (configFolder).replace(".", separator), "client.yml", templates.rest.clientYml.template()); } else { transfer(targetPath, (testConfigFolder).replace(".", separator), "client.yml", templates.rest.clientYml.template()); } transfer(targetPath, (configFolder).replace(".", separator), "primary.crt", templates.rest.primaryCrt.template()); transfer(targetPath, (configFolder).replace(".", separator), "secondary.crt", templates.rest.secondaryCrt.template()); if(kafkaProducer) { transfer(targetPath, (configFolder).replace(".", separator), "kafka-producer.yml", templates.rest.kafkaProducerYml.template(kafkaTopic)); } if(kafkaConsumer) { transfer(targetPath, (configFolder).replace(".", separator), "kafka-streams.yml", templates.rest.kafkaStreamsYml.template(artifactId)); } if(supportAvro) { transfer(targetPath, (configFolder).replace(".", separator), "schema-registry.yml", templates.rest.schemaRegistryYml.template()); } // mask transfer(targetPath, (configFolder).replace(".", separator), "mask.yml", templates.rest.maskYml.template()); // logging transfer(targetPath, (multipleModule ? "server.src.main.resources" : "src.main.resources").replace(".", separator), "logback.xml", templates.rest.logback.template(rootPackage)); transfer(targetPath, (multipleModule ? "server.src.test.resources" : "src.test.resources").replace(".", separator), "logback-test.xml", templates.rest.logback.template(rootPackage)); // exclusion list for Config module transfer(targetPath, (configFolder).replace(".", separator), "config.yml", templates.rest.config.template(config)); transfer(targetPath, (configFolder).replace(".", separator), "audit.yml", templates.rest.auditYml.template()); transfer(targetPath, (configFolder).replace(".", separator), "body.yml", templates.rest.bodyYml.template()); transfer(targetPath, (configFolder).replace(".", separator), "info.yml", templates.rest.infoYml.template()); transfer(targetPath, (configFolder).replace(".", separator), "correlation.yml", templates.rest.correlationYml.template()); transfer(targetPath, (configFolder).replace(".", separator), "metrics.yml", templates.rest.metricsYml.template()); transfer(targetPath, (configFolder).replace(".", separator), "sanitizer.yml", templates.rest.sanitizerYml.template()); transfer(targetPath, (configFolder).replace(".", separator), "traceability.yml", templates.rest.traceabilityYml.template()); transfer(targetPath, (configFolder).replace(".", separator), "health.yml", templates.rest.healthYml.template()); // added with #471 transfer(targetPath, (configFolder).replace(".", separator), "app-status.yml", templates.rest.appStatusYml.template()); // values.yml file, transfer to suppress the warning message during start startup and encourage usage. transfer(targetPath, (configFolder).replace(".", separator), "values.yml", templates.rest.values.template()); // add portal-registry.yml transfer(targetPath, (configFolder).replace(".", separator), "portal-registry.yml", templates.rest.portalRegistryYml.template()); } // routing handler transfer(targetPath, (configFolder).replace(".", separator), "handler.yml", templates.rest.handlerYml.template(serviceId, handlerPackage, operationList, prometheusMetrics, useLightProxy)); } // model OpenApi3 openApi3 = null; try { openApi3 = (OpenApi3)new OpenApiParser().parse((JsonNode)model, new URL("https://oas.lightapi.net/")); } catch (MalformedURLException e) { throw new RuntimeException("Failed to parse the model", e); } Map<String, Object> specMap = JsonMapper.string2Map(Overlay.toJson((OpenApi3Impl)openApi3).toString()); Map<String, Object> components = (Map<String, Object>)specMap.get("components"); if(components != null) { Map<String, Object> schemas = (Map<String, Object>)components.get("schemas"); if(schemas != null) { ArrayList<Runnable> modelCreators = new ArrayList<>(); final HashMap<String, Object> references = new HashMap<>(); for (Map.Entry<String, Object> entry : schemas.entrySet()) { loadModel(multipleModule, entry.getKey(), null, (Map<String, Object>)entry.getValue(), schemas, overwriteModel, targetPath, modelPackage, modelCreators, references, null, callback); } for (Runnable r : modelCreators) { r.run(); } } } // exit after generating the model if the consumer needs only the model classes if (generateModelOnly) { return; } // handler String serverFolder = multipleModule ? "server.src.main.java." + handlerPackage : "src.main.java." + handlerPackage; String serviceFolder = multipleModule ? "service.src.main.java." + handlerPackage : "src.main.java." + servicePackage; String serverTestFolder = multipleModule ? "server.src.test.java." + handlerPackage : "src.test.java." + handlerPackage; for (Map<String, Object> op : operationList) { String className = op.get("handlerName").toString(); String serviceName = op.get("serviceName").toString(); Object requestModelNameObject = op.get("requestModelName"); String requestModelName = null; if(requestModelNameObject != null) { requestModelName = requestModelNameObject.toString(); } @SuppressWarnings("unchecked") List<Map> parameters = (List<Map>)op.get("parameters"); Map<String, String> responseExample = (Map<String, String>)op.get("responseExample"); String example = responseExample.get("example"); String statusCode = responseExample.get("statusCode"); statusCode = StringUtils.isBlank(statusCode) || statusCode.equals("default") ? "-1" : statusCode; transfer(targetPath, (serverFolder).replace(".", separator), className + ".java", templates.rest.handler.template(handlerPackage, modelPackage, className, serviceName, requestModelName, parameters)); if (checkExist(targetPath, (serviceFolder).replace(".", separator), serviceName + ".java") && !overwriteHandler) { continue; } transfer(targetPath, (serviceFolder).replace(".", separator), serviceName + ".java", templates.rest.handlerService.template(handlerPackage, modelPackage, serviceName, statusCode, requestModelName, example, parameters)); } // handler test cases if (!specChangeCodeReGenOnly) { transfer(targetPath, (serverTestFolder + ".").replace(".", separator), "TestServer.java", templates.rest.testServer.template(handlerPackage)); } for (Map<String, Object> op : operationList) { if (checkExist(targetPath, (serverTestFolder).replace(".", separator), op.get("handlerName") + "Test.java") && !overwriteHandlerTest) { continue; } transfer(targetPath, (serverTestFolder).replace(".", separator), op.get("handlerName") + "Test.java", templates.rest.handlerTest.template(handlerPackage, op)); } // transfer binary files without touching them. try (InputStream is = OpenApiGenerator.class.getResourceAsStream("/binaries/server.keystore")) { Generator.copyFile(is, Paths.get(targetPath, (configFolder).replace(".", separator), "server.keystore")); } try (InputStream is = OpenApiGenerator.class.getResourceAsStream("/binaries/server.truststore")) { Generator.copyFile(is, Paths.get(targetPath, (configFolder).replace(".", separator), "server.truststore")); } if (supportClient) { try (InputStream is = OpenApiGenerator.class.getResourceAsStream("/binaries/client.keystore")) { Generator.copyFile(is, Paths.get(targetPath, (configFolder).replace(".", separator), "client.keystore")); } try (InputStream is = OpenApiGenerator.class.getResourceAsStream("/binaries/client.truststore")) { Generator.copyFile(is, Paths.get(targetPath, (configFolder).replace(".", separator), "client.truststore")); } } else { try (InputStream is = OpenApiGenerator.class.getResourceAsStream("/binaries/client.keystore")) { Generator.copyFile(is, Paths.get(targetPath, (testConfigFolder).replace(".", separator), "client.keystore")); } try (InputStream is = OpenApiGenerator.class.getResourceAsStream("/binaries/client.truststore")) { Generator.copyFile(is, Paths.get(targetPath, (testConfigFolder).replace(".", separator), "client.truststore")); } } try (InputStream is = new ByteArrayInputStream(Generator.yamlMapper.writeValueAsBytes(model))) { Generator.copyFile(is, Paths.get(targetPath, (configFolder).replace(".", separator), "openapi.yaml")); } } ModelCallback callback = new ModelCallback() { @Override public void callback(boolean multipleModule, String targetPath, String modelPackage, String modelFileName, String enumsIfClass, String parentClassName, String classVarName, boolean abstractIfClass, List<Map<String, Object>> props, List<Map<String, Object>> parentClassProps) { try { transfer(targetPath, (multipleModule ? "model.src.main.java." : "src.main.java." + modelPackage).replace(".", separator), modelFileName + ".java", enumsIfClass == null ? templates.rest.pojo.template(modelPackage, modelFileName, parentClassName, classVarName, abstractIfClass, props, parentClassProps) : templates.rest.enumClass.template(modelPackage, modelFileName, enumsIfClass)); } catch (IOException ex) { throw new RuntimeException(ex); } } }; }
fix #554 (#555) - fixed directory path Co-authored-by: Bolun Wen <[email protected]>
light-rest-4j/src/main/java/com/networknt/codegen/rest/OpenApiLightGenerator.java
fix #554 (#555)
<ide><path>ight-rest-4j/src/main/java/com/networknt/codegen/rest/OpenApiLightGenerator.java <ide> public void callback(boolean multipleModule, String targetPath, String modelPackage, String modelFileName, String enumsIfClass, String parentClassName, String classVarName, boolean abstractIfClass, List<Map<String, Object>> props, List<Map<String, Object>> parentClassProps) { <ide> try { <ide> transfer(targetPath, <del> (multipleModule ? "model.src.main.java." : "src.main.java." + modelPackage).replace(".", separator), <add> ((multipleModule ? "model.src.main.java." : "src.main.java.") + modelPackage).replace(".", separator), <ide> modelFileName + ".java", <ide> enumsIfClass == null <ide> ? templates.rest.pojo.template(modelPackage, modelFileName, parentClassName, classVarName, abstractIfClass, props, parentClassProps)
Java
apache-2.0
9a2702c3de2ed93b8737f687d8ff07a1c9aec0d7
0
oscarbou/isis,apache/isis,incodehq/isis,oscarbou/isis,apache/isis,estatio/isis,apache/isis,apache/isis,estatio/isis,estatio/isis,incodehq/isis,estatio/isis,oscarbou/isis,apache/isis,oscarbou/isis,apache/isis,incodehq/isis,incodehq/isis
/* * 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.isis.core.runtime.services; import java.lang.reflect.Modifier; import java.util.List; import java.util.Set; import java.util.SortedMap; import java.util.SortedSet; import javax.annotation.PreDestroy; import com.google.common.base.Function; import com.google.common.base.Joiner; import com.google.common.base.Predicate; import com.google.common.base.Splitter; import com.google.common.base.Strings; import com.google.common.collect.Iterables; import com.google.common.collect.Lists; import com.google.common.collect.Maps; import org.reflections.Reflections; import org.reflections.vfs.Vfs; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.apache.isis.applib.AppManifest; import org.apache.isis.applib.annotation.DomainService; import org.apache.isis.applib.annotation.DomainServiceLayout; import org.apache.isis.applib.services.classdiscovery.ClassDiscoveryServiceUsingReflections; import org.apache.isis.core.commons.config.IsisConfigurationDefault; import org.apache.isis.core.metamodel.util.DeweyOrderComparator; import static com.google.common.base.Predicates.and; import static com.google.common.base.Predicates.not; public class ServicesInstallerFromAnnotation extends ServicesInstallerAbstract { //region > constants private static final Logger LOG = LoggerFactory.getLogger(ServicesInstallerFromAnnotation.class); public static final String NAME = "annotation"; public final static String PACKAGE_PREFIX_KEY = "isis.services.ServicesInstallerFromAnnotation.packagePrefix"; /** * These package prefixes (core and modules) are always included. * * <p> * It's important that any services annotated {@link org.apache.isis.applib.annotation.DomainService} and residing * in any of these packages must have no side-effects. * * <p> * Services are ordered according to the {@link org.apache.isis.applib.annotation.DomainService#menuOrder() menuOrder}, * with the first service found used. * </p> */ public final static String PACKAGE_PREFIX_STANDARD = Joiner.on(",").join(AppManifest.Registry.FRAMEWORK_PROVIDED_SERVICES); //endregion //region > constructor, fields private final ServiceInstantiator serviceInstantiator; public ServicesInstallerFromAnnotation(final IsisConfigurationDefault isisConfiguration) { this(new ServiceInstantiator(), isisConfiguration); } public ServicesInstallerFromAnnotation( final ServiceInstantiator serviceInstantiator, final IsisConfigurationDefault isisConfiguration) { super(NAME, isisConfiguration); this.serviceInstantiator = serviceInstantiator; } //endregion //region > packagePrefixes private String packagePrefixes; /** * For integration testing. * * <p> * Otherwise these are read from the {@link org.apache.isis.core.commons.config.IsisConfiguration} * </p> */ public void withPackagePrefixes(final String... packagePrefixes) { this.packagePrefixes = Joiner.on(",").join(packagePrefixes); } //endregion //region > init, shutdown public void init() { initIfRequired(); } private boolean initialized = false; protected void initIfRequired() { if(initialized) { return; } if(getConfiguration() == null) { throw new IllegalStateException("No IsisConfiguration injected - aborting"); } try { // lazily copy over the configuration to the instantiator serviceInstantiator.setConfiguration(getConfiguration()); if(packagePrefixes == null) { this.packagePrefixes = PACKAGE_PREFIX_STANDARD; String packagePrefixes = getConfiguration().getString(PACKAGE_PREFIX_KEY); if(!Strings.isNullOrEmpty(packagePrefixes)) { this.packagePrefixes = this.packagePrefixes + "," + packagePrefixes; } } } finally { initialized = true; } } @PreDestroy public void shutdown() { } //endregion //region > helpers private Predicate<Class<?>> instantiatable() { return and(not(nullClass()), not(abstractClass())); } private static Function<String,String> trim() { return new Function<String,String>(){ @Override public String apply(final String input) { return input.trim(); } }; } private static Predicate<Class<?>> nullClass() { return new Predicate<Class<?>>() { @Override public boolean apply(final Class<?> input) { return input == null; } }; } private static Predicate<Class<?>> abstractClass() { return new Predicate<Class<?>>() { @Override public boolean apply(final Class<?> input) { return Modifier.isAbstract(input.getModifiers()); } }; } //endregion //region > getServices (API) private List<Object> services; @Override public List<Object> getServices() { initIfRequired(); if(this.services == null) { final SortedMap<String, SortedSet<String>> positionedServices = Maps.newTreeMap(new DeweyOrderComparator()); appendServices(positionedServices); this.services = ServicesInstallerUtils.instantiateServicesFrom(positionedServices, serviceInstantiator); } return services; } //endregion //region > appendServices public void appendServices(final SortedMap<String, SortedSet<String>> positionedServices) { initIfRequired(); final List<String> packagePrefixList = asList(packagePrefixes); Set<Class<?>> domainServiceTypes = AppManifest.Registry.instance().getDomainServiceTypes(); if(domainServiceTypes == null) { // if no appManifest Vfs.setDefaultURLTypes(ClassDiscoveryServiceUsingReflections.getUrlTypes()); final Reflections reflections = new Reflections(packagePrefixList); domainServiceTypes = reflections.getTypesAnnotatedWith(DomainService.class); } final List<Class<?>> domainServiceClasses = Lists.newArrayList(Iterables.filter(domainServiceTypes, instantiatable())); for (final Class<?> cls : domainServiceClasses) { final String order = orderOf(cls); // we want the class name in order to instantiate it // (and *not* the value of the @DomainServiceLayout(named=...) annotation attribute) final String fullyQualifiedClassName = cls.getName(); final String name = nameOf(cls); ServicesInstallerUtils.appendInPosition(positionedServices, order, fullyQualifiedClassName); } } //endregion //region > helpers: orderOf, nameOf, asList private static String orderOf(final Class<?> cls) { final DomainServiceLayout domainServiceLayout = cls.getAnnotation(DomainServiceLayout.class); String dslayoutOrder = domainServiceLayout != null ? domainServiceLayout.menuOrder(): null; final DomainService domainService = cls.getAnnotation(DomainService.class); String dsOrder = domainService != null ? domainService.menuOrder() : "" + Integer.MAX_VALUE; return minimumOf(dslayoutOrder, dsOrder); } private static String minimumOf(final String dslayoutOrder, final String dsOrder) { if(isUndefined(dslayoutOrder)) { return dsOrder; } if(isUndefined(dsOrder)) { return dslayoutOrder; } return dslayoutOrder.compareTo(dsOrder) < 0 ? dslayoutOrder : dsOrder; } private static boolean isUndefined(final String str) { return str == null || str.equals("" + Integer.MAX_VALUE); } private static String nameOf(final Class<?> cls) { final DomainServiceLayout domainServiceLayout = cls.getAnnotation(DomainServiceLayout.class); String name = domainServiceLayout != null ? domainServiceLayout.named(): null; if(name == null) { name = cls.getName(); } return name; } private static List<String> asList(final String csv) { return Lists.newArrayList(Iterables.transform(Splitter.on(",").split(csv), trim())); } //endregion //region > domain events public static abstract class PropertyDomainEvent<T> extends org.apache.isis.applib.services.eventbus.PropertyDomainEvent<ServicesInstallerFromAnnotation, T> { } public static abstract class CollectionDomainEvent<T> extends org.apache.isis.applib.services.eventbus.CollectionDomainEvent<ServicesInstallerFromAnnotation, T> { } public static abstract class ActionDomainEvent extends org.apache.isis.applib.services.eventbus.ActionDomainEvent<ServicesInstallerFromAnnotation> { } //endregion //region > getTypes (API) @Override public List<Class<?>> getTypes() { return listOf(List.class); // ie List<Object.class>, of services } //endregion }
core/runtime/src/main/java/org/apache/isis/core/runtime/services/ServicesInstallerFromAnnotation.java
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.apache.isis.core.runtime.services; import java.lang.reflect.Modifier; import java.util.List; import java.util.Set; import java.util.SortedMap; import java.util.SortedSet; import javax.annotation.PreDestroy; import com.google.common.base.Function; import com.google.common.base.Joiner; import com.google.common.base.Predicate; import com.google.common.base.Splitter; import com.google.common.base.Strings; import com.google.common.collect.Iterables; import com.google.common.collect.Lists; import com.google.common.collect.Maps; import org.reflections.Reflections; import org.reflections.vfs.Vfs; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.apache.isis.applib.AppManifest; import org.apache.isis.applib.annotation.DomainService; import org.apache.isis.applib.annotation.DomainServiceLayout; import org.apache.isis.applib.services.classdiscovery.ClassDiscoveryServiceUsingReflections; import org.apache.isis.core.commons.config.IsisConfigurationDefault; import org.apache.isis.core.metamodel.util.DeweyOrderComparator; import static com.google.common.base.Predicates.and; import static com.google.common.base.Predicates.not; public class ServicesInstallerFromAnnotation extends ServicesInstallerAbstract { //region > constants private static final Logger LOG = LoggerFactory.getLogger(ServicesInstallerFromAnnotation.class); public static final String NAME = "annotation"; public final static String PACKAGE_PREFIX_KEY = "isis.services.ServicesInstallerFromAnnotation.packagePrefix"; /** * These package prefixes (core and modules) are always included. * * <p> * It's important that any services annotated {@link org.apache.isis.applib.annotation.DomainService} and residing * in any of these packages must have no side-effects. * * <p> * Services are ordered according to the {@link org.apache.isis.applib.annotation.DomainService#menuOrder() menuOrder}, * with the first service found used. * </p> */ public final static String PACKAGE_PREFIX_STANDARD = Joiner.on(",").join(AppManifest.Registry.FRAMEWORK_PROVIDED_SERVICES); //endregion //region > constructor, fields private final ServiceInstantiator serviceInstantiator; public ServicesInstallerFromAnnotation(final IsisConfigurationDefault isisConfiguration) { this(new ServiceInstantiator(), isisConfiguration); } public ServicesInstallerFromAnnotation( final ServiceInstantiator serviceInstantiator, final IsisConfigurationDefault isisConfiguration) { super(NAME, isisConfiguration); this.serviceInstantiator = serviceInstantiator; } //endregion //region > packagePrefixes private String packagePrefixes; /** * For integration testing. * * <p> * Otherwise these are read from the {@link org.apache.isis.core.commons.config.IsisConfiguration} * </p> */ public void withPackagePrefixes(final String... packagePrefixes) { this.packagePrefixes = Joiner.on(",").join(packagePrefixes); } //endregion //region > init, shutdown public void init() { initIfRequired(); } private boolean initialized = false; protected void initIfRequired() { if(initialized) { return; } if(getConfiguration() == null) { throw new IllegalStateException("No IsisConfiguration injected - aborting"); } try { // lazily copy over the configuration to the instantiator serviceInstantiator.setConfiguration(getConfiguration()); if(packagePrefixes == null) { this.packagePrefixes = PACKAGE_PREFIX_STANDARD; String packagePrefixes = getConfiguration().getString(PACKAGE_PREFIX_KEY); if(!Strings.isNullOrEmpty(packagePrefixes)) { this.packagePrefixes = this.packagePrefixes + "," + packagePrefixes; } } } finally { initialized = true; } } @PreDestroy public void shutdown() { } //endregion //region > helpers private Predicate<Class<?>> instantiatable() { return and(not(nullClass()), not(abstractClass())); } private static Function<String,String> trim() { return new Function<String,String>(){ @Override public String apply(final String input) { return input.trim(); } }; } private static Predicate<Class<?>> nullClass() { return new Predicate<Class<?>>() { @Override public boolean apply(final Class<?> input) { return input == null; } }; } private static Predicate<Class<?>> abstractClass() { return new Predicate<Class<?>>() { @Override public boolean apply(final Class<?> input) { return Modifier.isAbstract(input.getModifiers()); } }; } //endregion //region > getServices (API) private List<Object> services; @Override public List<Object> getServices() { initIfRequired(); if(this.services == null) { final SortedMap<String, SortedSet<String>> positionedServices = Maps.newTreeMap(new DeweyOrderComparator()); appendServices(positionedServices); this.services = ServicesInstallerUtils.instantiateServicesFrom(positionedServices, serviceInstantiator); } return services; } //endregion //region > appendServices public void appendServices(final SortedMap<String, SortedSet<String>> positionedServices) { initIfRequired(); final List<String> packagePrefixList = asList(packagePrefixes); Set<Class<?>> domainServiceTypes = AppManifest.Registry.instance().getDomainServiceTypes(); if(domainServiceTypes == null) { // if no appManifest Vfs.setDefaultURLTypes(ClassDiscoveryServiceUsingReflections.getUrlTypes()); final Reflections reflections = new Reflections(packagePrefixList); domainServiceTypes = reflections.getTypesAnnotatedWith(DomainService.class); } final List<Class<?>> domainServiceClasses = Lists.newArrayList(Iterables.filter(domainServiceTypes, instantiatable())); for (final Class<?> cls : domainServiceClasses) { final String order = orderOf(cls); // we want the class name in order to instantiate it // (and *not* the value of the @DomainServiceLayout(named=...) annotation attribute) final String fullyQualifiedClassName = cls.getName(); final String name = nameOf(cls); ServicesInstallerUtils.appendInPosition(positionedServices, order, fullyQualifiedClassName); } } //endregion //region > helpers: orderOf, nameOf, asList private static String orderOf(final Class<?> cls) { final DomainServiceLayout domainServiceLayout = cls.getAnnotation(DomainServiceLayout.class); String order = domainServiceLayout != null ? domainServiceLayout.menuOrder(): null; if(order == null || order.equals("" + Integer.MAX_VALUE)) { final DomainService domainService = cls.getAnnotation(DomainService.class); order = domainService != null ? domainService.menuOrder() : "" + Integer.MAX_VALUE; } return order; } private static String nameOf(final Class<?> cls) { final DomainServiceLayout domainServiceLayout = cls.getAnnotation(DomainServiceLayout.class); String name = domainServiceLayout != null ? domainServiceLayout.named(): null; if(name == null) { name = cls.getName(); } return name; } private static List<String> asList(final String csv) { return Lists.newArrayList(Iterables.transform(Splitter.on(",").split(csv), trim())); } //endregion //region > domain events public static abstract class PropertyDomainEvent<T> extends org.apache.isis.applib.services.eventbus.PropertyDomainEvent<ServicesInstallerFromAnnotation, T> { } public static abstract class CollectionDomainEvent<T> extends org.apache.isis.applib.services.eventbus.CollectionDomainEvent<ServicesInstallerFromAnnotation, T> { } public static abstract class ActionDomainEvent extends org.apache.isis.applib.services.eventbus.ActionDomainEvent<ServicesInstallerFromAnnotation> { } //endregion //region > getTypes (API) @Override public List<Class<?>> getTypes() { return listOf(List.class); // ie List<Object.class>, of services } //endregion }
ISIS-1688: honours both @DomainServiceLayout and @DomainService menuOrder when determining priority
core/runtime/src/main/java/org/apache/isis/core/runtime/services/ServicesInstallerFromAnnotation.java
ISIS-1688: honours both @DomainServiceLayout and @DomainService menuOrder when determining priority
<ide><path>ore/runtime/src/main/java/org/apache/isis/core/runtime/services/ServicesInstallerFromAnnotation.java <ide> <ide> private static String orderOf(final Class<?> cls) { <ide> final DomainServiceLayout domainServiceLayout = cls.getAnnotation(DomainServiceLayout.class); <del> String order = domainServiceLayout != null ? domainServiceLayout.menuOrder(): null; <del> if(order == null || order.equals("" + Integer.MAX_VALUE)) { <del> final DomainService domainService = cls.getAnnotation(DomainService.class); <del> order = domainService != null ? domainService.menuOrder() : "" + Integer.MAX_VALUE; <del> } <del> return order; <add> String dslayoutOrder = domainServiceLayout != null ? domainServiceLayout.menuOrder(): null; <add> final DomainService domainService = cls.getAnnotation(DomainService.class); <add> String dsOrder = domainService != null ? domainService.menuOrder() : "" + Integer.MAX_VALUE; <add> <add> return minimumOf(dslayoutOrder, dsOrder); <add> } <add> <add> private static String minimumOf(final String dslayoutOrder, final String dsOrder) { <add> if(isUndefined(dslayoutOrder)) { <add> return dsOrder; <add> } <add> if(isUndefined(dsOrder)) { <add> return dslayoutOrder; <add> } <add> return dslayoutOrder.compareTo(dsOrder) < 0 ? dslayoutOrder : dsOrder; <add> } <add> <add> private static boolean isUndefined(final String str) { <add> return str == null || str.equals("" + Integer.MAX_VALUE); <ide> } <ide> <ide> private static String nameOf(final Class<?> cls) {
Java
apache-2.0
0a02cbcada72e85f515b665b62b6f281697bd9e3
0
qiscus/qiscus-sdk-android
/* * Copyright (c) 2016 Qiscus. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.qiscus.sdk.chat.core.data.remote; import android.net.Uri; import android.os.Build; import androidx.annotation.NonNull; import androidx.core.util.Pair; import com.google.gson.JsonElement; import com.google.gson.JsonObject; import com.qiscus.sdk.chat.core.BuildConfig; import com.qiscus.sdk.chat.core.QiscusCore; import com.qiscus.sdk.chat.core.R; import com.qiscus.sdk.chat.core.data.model.QUserPresence; import com.qiscus.sdk.chat.core.data.model.QiscusAccount; import com.qiscus.sdk.chat.core.data.model.QiscusAppConfig; import com.qiscus.sdk.chat.core.data.model.QiscusChannels; import com.qiscus.sdk.chat.core.data.model.QiscusChatRoom; import com.qiscus.sdk.chat.core.data.model.QiscusComment; import com.qiscus.sdk.chat.core.data.model.QiscusNonce; import com.qiscus.sdk.chat.core.data.model.QiscusRealtimeStatus; import com.qiscus.sdk.chat.core.data.model.QiscusRoomMember; import com.qiscus.sdk.chat.core.event.QiscusClearCommentsEvent; import com.qiscus.sdk.chat.core.event.QiscusCommentSentEvent; import com.qiscus.sdk.chat.core.util.BuildVersionUtil; import com.qiscus.sdk.chat.core.util.QiscusDateUtil; import com.qiscus.sdk.chat.core.util.QiscusErrorLogger; import com.qiscus.sdk.chat.core.util.QiscusFileUtil; import com.qiscus.sdk.chat.core.util.QiscusHashMapUtil; import com.qiscus.sdk.chat.core.util.QiscusLogger; import com.qiscus.sdk.chat.core.util.QiscusTextUtil; import org.greenrobot.eventbus.EventBus; import org.json.JSONException; import org.json.JSONObject; import java.io.File; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; import java.util.ArrayList; import java.util.Collections; import java.util.Date; import java.util.HashMap; import java.util.Iterator; import java.util.List; import java.util.concurrent.TimeUnit; import okhttp3.ConnectionSpec; import okhttp3.Interceptor; import okhttp3.MediaType; import okhttp3.MultipartBody; import okhttp3.OkHttpClient; import okhttp3.Request; import okhttp3.RequestBody; import okhttp3.Response; import okhttp3.ResponseBody; import okhttp3.internal.Util; import okhttp3.logging.HttpLoggingInterceptor; import okio.BufferedSink; import okio.Okio; import okio.Source; import retrofit2.Retrofit; import retrofit2.adapter.rxjava.RxJavaCallAdapterFactory; import retrofit2.converter.gson.GsonConverterFactory; import retrofit2.http.Body; import retrofit2.http.DELETE; import retrofit2.http.GET; import retrofit2.http.Headers; import retrofit2.http.PATCH; import retrofit2.http.POST; import retrofit2.http.Query; import rx.Emitter; import rx.Observable; import rx.android.schedulers.AndroidSchedulers; import rx.exceptions.OnErrorThrowable; import rx.schedulers.Schedulers; /** * Created on : August 18, 2016 * Author : zetbaitsu * Name : Zetra * GitHub : https://github.com/zetbaitsu */ public enum QiscusApi { INSTANCE; private OkHttpClient httpClient; private Api api; private String baseUrl; QiscusApi() { baseUrl = QiscusCore.getAppServer(); if (Build.VERSION.SDK_INT <= 19) { ConnectionSpec spec = new ConnectionSpec.Builder(ConnectionSpec.COMPATIBLE_TLS) .supportsTlsExtensions(true) .allEnabledTlsVersions() .allEnabledCipherSuites() .build(); httpClient = new OkHttpClient.Builder() .connectTimeout(60, TimeUnit.SECONDS) .readTimeout(60, TimeUnit.SECONDS) .addInterceptor(this::headersInterceptor) .addInterceptor(makeLoggingInterceptor(QiscusCore.getChatConfig().isEnableLog())) .connectionSpecs(Collections.singletonList(spec)) .build(); } else { httpClient = new OkHttpClient.Builder() .connectTimeout(60, TimeUnit.SECONDS) .readTimeout(60, TimeUnit.SECONDS) .addInterceptor(this::headersInterceptor) .addInterceptor(makeLoggingInterceptor(QiscusCore.getChatConfig().isEnableLog())) .build(); } api = new Retrofit.Builder() .baseUrl(baseUrl) .client(httpClient) .addConverterFactory(GsonConverterFactory.create()) .addCallAdapterFactory(RxJavaCallAdapterFactory.create()) .build() .create(Api.class); } public static QiscusApi getInstance() { return INSTANCE; } public void reInitiateInstance() { baseUrl = QiscusCore.getAppServer(); if (Build.VERSION.SDK_INT <= 19) { ConnectionSpec spec = new ConnectionSpec.Builder(ConnectionSpec.COMPATIBLE_TLS) .supportsTlsExtensions(true) .allEnabledTlsVersions() .allEnabledCipherSuites() .build(); httpClient = new OkHttpClient.Builder() .connectTimeout(60, TimeUnit.SECONDS) .readTimeout(60, TimeUnit.SECONDS) .addInterceptor(this::headersInterceptor) .addInterceptor(makeLoggingInterceptor(QiscusCore.getChatConfig().isEnableLog())) .connectionSpecs(Collections.singletonList(spec)) .build(); } else { httpClient = new OkHttpClient.Builder() .connectTimeout(60, TimeUnit.SECONDS) .readTimeout(60, TimeUnit.SECONDS) .addInterceptor(this::headersInterceptor) .addInterceptor(makeLoggingInterceptor(QiscusCore.getChatConfig().isEnableLog())) .build(); } try { api = new Retrofit.Builder() .baseUrl(baseUrl) .client(httpClient) .addConverterFactory(GsonConverterFactory.create()) .addCallAdapterFactory(RxJavaCallAdapterFactory.create()) .build() .create(Api.class); } catch (IllegalArgumentException e) { QiscusErrorLogger.print(e); return; } } private Response headersInterceptor(Interceptor.Chain chain) throws IOException { Request.Builder builder = chain.request().newBuilder(); JSONObject jsonCustomHeader = QiscusCore.getCustomHeader(); builder.addHeader("QISCUS-SDK-APP-ID", QiscusCore.getAppId()); builder.addHeader("QISCUS-SDK-TOKEN", QiscusCore.hasSetupUser() ? QiscusCore.getToken() : ""); builder.addHeader("QISCUS-SDK-USER-EMAIL", QiscusCore.hasSetupUser() ? QiscusCore.getQiscusAccount().getEmail() : ""); builder.addHeader("QISCUS-SDK-VERSION", "ANDROID_" + BuildConfig.VERSION_NAME); builder.addHeader("QISCUS-SDK-PLATFORM", "ANDROID"); builder.addHeader("QISCUS-SDK-DEVICE-BRAND", Build.MANUFACTURER); builder.addHeader("QISCUS-SDK-DEVICE-MODEL", Build.MODEL); builder.addHeader("QISCUS-SDK-DEVICE-OS-VERSION", BuildVersionUtil.OS_VERSION_NAME); if (jsonCustomHeader != null) { Iterator<String> keys = jsonCustomHeader.keys(); while (keys.hasNext()) { String key = keys.next(); try { Object customHeader = jsonCustomHeader.get(key); if (customHeader != null) { builder.addHeader(key, customHeader.toString()); } } catch (JSONException e) { e.printStackTrace(); } } } Request req = builder.build(); return chain.proceed(req); } private HttpLoggingInterceptor makeLoggingInterceptor(boolean isDebug) { HttpLoggingInterceptor logging = new HttpLoggingInterceptor(); logging.setLevel(isDebug ? HttpLoggingInterceptor.Level.BODY : HttpLoggingInterceptor.Level.NONE); return logging; } @Deprecated public Observable<QiscusNonce> requestNonce() { return api.requestNonce().map(QiscusApiParser::parseNonce); } public Observable<QiscusNonce> getJWTNonce() { return api.requestNonce().map(QiscusApiParser::parseNonce); } @Deprecated public Observable<QiscusAccount> login(String token) { return api.login(QiscusHashMapUtil.login(token)).map(QiscusApiParser::parseQiscusAccount); } public Observable<QiscusAccount> setUserWithIdentityToken(String token) { return api.login(QiscusHashMapUtil.login(token)).map(QiscusApiParser::parseQiscusAccount); } @Deprecated public Observable<QiscusAccount> loginOrRegister(String email, String password, String username, String avatarUrl) { return loginOrRegister(email, password, username, avatarUrl, null); } @Deprecated public Observable<QiscusAccount> loginOrRegister(String email, String password, String username, String avatarUrl, JSONObject extras) { return api.loginOrRegister(QiscusHashMapUtil.loginOrRegister( email, password, username, avatarUrl, extras == null ? null : extras.toString() )) .map(QiscusApiParser::parseQiscusAccount); } public Observable<QiscusAccount> setUser(String userId, String userKey, String username, String avatarURL, JSONObject extras) { return api.loginOrRegister(QiscusHashMapUtil.loginOrRegister( userId, userKey, username, avatarURL, extras == null ? null : extras.toString())) .map(QiscusApiParser::parseQiscusAccount); } @Deprecated public Observable<QiscusAccount> updateProfile(String username, String avatarUrl) { return updateProfile(username, avatarUrl, null); } public Observable<QiscusAccount> updateUser(String name, String avatarURL) { return updateUser(name, avatarURL, null); } @Deprecated public Observable<QiscusAccount> updateProfile(String username, String avatarUrl, JSONObject extras) { return api.updateProfile(QiscusHashMapUtil.updateProfile( username, avatarUrl, extras == null ? null : extras.toString())) .map(QiscusApiParser::parseQiscusAccount); } public Observable<QiscusAccount> updateUser(String name, String avatarURL, JSONObject extras) { return api.updateProfile(QiscusHashMapUtil.updateProfile( name, avatarURL, extras == null ? null : extras.toString())) .map(QiscusApiParser::parseQiscusAccount); } public Observable<QiscusAccount> getUserData() { return api.getUserData() .map(QiscusApiParser::parseQiscusAccount); } @Deprecated public Observable<QiscusChatRoom> getChatRoom(String withEmail, JSONObject options) { return api.createOrGetChatRoom(QiscusHashMapUtil.getChatRoom(Collections.singletonList(withEmail), options == null ? null : options.toString())) .map(QiscusApiParser::parseQiscusChatRoom); } public Observable<QiscusChatRoom> chatUser(String userId, JSONObject extras) { return api.createOrGetChatRoom(QiscusHashMapUtil.getChatRoom(Collections.singletonList(userId), extras == null ? null : extras.toString())) .map(QiscusApiParser::parseQiscusChatRoom); } @Deprecated public Observable<QiscusChatRoom> createGroupChatRoom(String name, List<String> emails, String avatarUrl, JSONObject options) { return api.createGroupChatRoom(QiscusHashMapUtil.createGroupChatRoom( name, emails, avatarUrl, options == null ? null : options.toString())) .map(QiscusApiParser::parseQiscusChatRoom); } public Observable<QiscusChatRoom> createGroupChat(String name, List<String> userIds, String avatarURL, JSONObject extras) { return api.createGroupChatRoom(QiscusHashMapUtil.createGroupChatRoom( name, userIds, avatarURL, extras == null ? null : extras.toString())) .map(QiscusApiParser::parseQiscusChatRoom); } @Deprecated public Observable<QiscusChatRoom> getGroupChatRoom(String uniqueId, String name, String avatarUrl, JSONObject options) { return api.createOrGetGroupChatRoom(QiscusHashMapUtil.getGroupChatRoom( uniqueId, name, avatarUrl, options == null ? null : options.toString())) .map(QiscusApiParser::parseQiscusChatRoom); } public Observable<QiscusChatRoom> createChannel(String uniqueId, String name, String avatarURL, JSONObject extras) { return api.createOrGetGroupChatRoom(QiscusHashMapUtil.getGroupChatRoom( uniqueId, name, avatarURL, extras == null ? null : extras.toString())) .map(QiscusApiParser::parseQiscusChatRoom); } public Observable<QiscusChatRoom> getChannel(String uniqueId) { return api.createOrGetGroupChatRoom(QiscusHashMapUtil.getGroupChatRoom( uniqueId, null, null, null)) .map(QiscusApiParser::parseQiscusChatRoom); } @Deprecated public Observable<QiscusChatRoom> getChatRoom(long roomId) { return api.getChatRooms(QiscusHashMapUtil.getChatRooms( Collections.singletonList(String.valueOf(roomId)), new ArrayList<>(), true, false)) .map(QiscusApiParser::parseQiscusChatRoomInfo) .flatMap(Observable::from) .take(1); } public Observable<QiscusChatRoom> getChatRoomInfo(long roomId) { return api.getChatRooms(QiscusHashMapUtil.getChatRooms( Collections.singletonList(String.valueOf(roomId)), new ArrayList<>(), true, false)) .map(QiscusApiParser::parseQiscusChatRoomInfo) .flatMap(Observable::from) .take(1); } @Deprecated public Observable<Pair<QiscusChatRoom, List<QiscusComment>>> getChatRoomComments(long roomId) { return api.getChatRoom(roomId) .map(QiscusApiParser::parseQiscusChatRoomWithComments); } public Observable<Pair<QiscusChatRoom, List<QiscusComment>>> getChatRoomWithMessages(long roomId) { return api.getChatRoom(roomId) .map(QiscusApiParser::parseQiscusChatRoomWithComments); } @Deprecated public Observable<List<QiscusChatRoom>> getChatRooms(int page, int limit, boolean showMembers) { return api.getChatRooms(page, limit, showMembers, false, false) .map(QiscusApiParser::parseQiscusChatRoomInfo); } public Observable<List<QiscusChatRoom>> getAllChatRooms(boolean showParticipant, boolean showRemoved, boolean showEmpty, int page, int limit) { return api.getChatRooms(page, limit, showParticipant, showEmpty, showRemoved) .map(QiscusApiParser::parseQiscusChatRoomInfo); } @Deprecated public Observable<List<QiscusChatRoom>> getChatRooms(List<Long> roomIds, List<String> uniqueIds, boolean showMembers) { List<String> listOfRoomIds = new ArrayList<>(); for (Long roomId : roomIds) { listOfRoomIds.add(String.valueOf(roomId)); } return api.getChatRooms(QiscusHashMapUtil.getChatRooms( listOfRoomIds, uniqueIds, showMembers, false)) .map(QiscusApiParser::parseQiscusChatRoomInfo); } public Observable<List<QiscusChatRoom>> getChatRoomsWithUniqueIds(List<String> uniqueIds, boolean showRemoved, boolean showParticipant) { return api.getChatRooms(QiscusHashMapUtil.getChatRooms( null, uniqueIds, showParticipant, showRemoved)) .map(QiscusApiParser::parseQiscusChatRoomInfo); } public Observable<List<QiscusChatRoom>> getChatRooms(List<Long> roomIds, boolean showRemoved, boolean showParticipant) { List<String> listOfRoomIds = new ArrayList<>(); for (Long roomId : roomIds) { listOfRoomIds.add(String.valueOf(roomId)); } return api.getChatRooms(QiscusHashMapUtil.getChatRooms( listOfRoomIds, null, showParticipant, showRemoved)) .map(QiscusApiParser::parseQiscusChatRoomInfo); } @Deprecated public Observable<QiscusComment> getComments(long roomId, long lastCommentId) { Long lastCommenID = lastCommentId; if (lastCommenID == 0) { lastCommenID = null; } return api.getComments(roomId, lastCommenID, false, 20) .flatMap(jsonElement -> Observable.from(jsonElement.getAsJsonObject().get("results") .getAsJsonObject().get("comments").getAsJsonArray())) .map(jsonElement -> QiscusApiParser.parseQiscusComment(jsonElement, roomId)); } @Deprecated public Observable<QiscusComment> getCommentsAfter(long roomId, long lastCommentId) { Long lastCommentID = lastCommentId; if (lastCommentID == 0) { lastCommentID = null; } return api.getComments(roomId, lastCommentID, true, 20) .flatMap(jsonElement -> Observable.from(jsonElement.getAsJsonObject().get("results") .getAsJsonObject().get("comments").getAsJsonArray())) .map(jsonElement -> QiscusApiParser.parseQiscusComment(jsonElement, roomId)); } public Observable<QiscusComment> getPreviousMessagesById(long roomId, int limit, long messageId) { Long messageID = messageId; if (messageID == 0) { messageID = null; } return api.getComments(roomId, messageID, false, limit) .flatMap(jsonElement -> Observable.from(jsonElement.getAsJsonObject().get("results") .getAsJsonObject().get("comments").getAsJsonArray())) .map(jsonElement -> QiscusApiParser.parseQiscusComment(jsonElement, roomId)); } public Observable<QiscusComment> getPreviousMessagesById(long roomId, int limit) { return api.getComments(roomId, null, false, limit) .flatMap(jsonElement -> Observable.from(jsonElement.getAsJsonObject().get("results") .getAsJsonObject().get("comments").getAsJsonArray())) .map(jsonElement -> QiscusApiParser.parseQiscusComment(jsonElement, roomId)); } public Observable<QiscusComment> getNextMessagesById(long roomId, int limit, long messageId) { Long messageID = messageId; if (messageID == 0) { messageID = null; } return api.getComments(roomId, messageID, true, limit) .flatMap(jsonElement -> Observable.from(jsonElement.getAsJsonObject().get("results") .getAsJsonObject().get("comments").getAsJsonArray())) .map(jsonElement -> QiscusApiParser.parseQiscusComment(jsonElement, roomId)); } public Observable<QiscusComment> getNextMessagesById(long roomId, int limit) { return api.getComments(roomId, null, true, limit) .flatMap(jsonElement -> Observable.from(jsonElement.getAsJsonObject().get("results") .getAsJsonObject().get("comments").getAsJsonArray())) .map(jsonElement -> QiscusApiParser.parseQiscusComment(jsonElement, roomId)); } @Deprecated public Observable<QiscusComment> postComment(QiscusComment qiscusComment) { QiscusCore.getChatConfig().getCommentSendingInterceptor().sendComment(qiscusComment); return api.postComment(QiscusHashMapUtil.postComment(qiscusComment)) .map(jsonElement -> { JsonObject jsonComment = jsonElement.getAsJsonObject() .get("results").getAsJsonObject().get("comment").getAsJsonObject(); qiscusComment.setId(jsonComment.get("id").getAsLong()); qiscusComment.setCommentBeforeId(jsonComment.get("comment_before_id").getAsInt()); //timestamp is in nano seconds format, convert it to milliseconds by divide it long timestamp = jsonComment.get("unix_nano_timestamp").getAsLong() / 1000000L; qiscusComment.setTime(new Date(timestamp)); QiscusLogger.print("Sent Comment..."); return qiscusComment; }) .doOnNext(comment -> EventBus.getDefault().post(new QiscusCommentSentEvent(comment))); } public Observable<QiscusComment> sendMessage(QiscusComment message) { QiscusCore.getChatConfig().getCommentSendingInterceptor().sendComment(message); return api.postComment(QiscusHashMapUtil.postComment(message)) .map(jsonElement -> { JsonObject jsonComment = jsonElement.getAsJsonObject() .get("results").getAsJsonObject().get("comment").getAsJsonObject(); message.setId(jsonComment.get("id").getAsLong()); message.setCommentBeforeId(jsonComment.get("comment_before_id").getAsInt()); //timestamp is in nano seconds format, convert it to milliseconds by divide it long timestamp = jsonComment.get("unix_nano_timestamp").getAsLong() / 1000000L; message.setTime(new Date(timestamp)); QiscusLogger.print("Sent Comment..."); return message; }) .doOnNext(comment -> EventBus.getDefault().post(new QiscusCommentSentEvent(comment))); } public Observable<QiscusComment> sendFileMessage(QiscusComment message, File file, ProgressListener progressUploadListener) { return Observable.create(subscriber -> { long fileLength = file.length(); RequestBody requestBody = new MultipartBody.Builder() .setType(MultipartBody.FORM) .addFormDataPart("file", file.getName(), new CountingFileRequestBody(file, totalBytes -> { int progress = (int) (totalBytes * 100 / fileLength); progressUploadListener.onProgress(progress); })) .build(); Request request = new Request.Builder() .url(baseUrl + "api/v2/mobile/upload") .post(requestBody).build(); try { Response response = httpClient.newCall(request).execute(); JSONObject responseJ = new JSONObject(response.body().string()); String result = responseJ.getJSONObject("results").getJSONObject("file").getString("url"); message.updateAttachmentUrl(Uri.parse(result).toString()); QiscusCore.getDataStore().addOrUpdate(message); QiscusApi.getInstance().sendMessage(message) .doOnSubscribe(() -> QiscusCore.getDataStore().addOrUpdate(message)) .doOnError(throwable -> { subscriber.onError(throwable); }) .subscribeOn(Schedulers.io()) .observeOn(AndroidSchedulers.mainThread()) .subscribe(commentSend -> { subscriber.onNext(commentSend); subscriber.onCompleted(); }, throwable -> { QiscusErrorLogger.print(throwable); throwable.printStackTrace(); subscriber.onError(throwable); }); } catch (IOException | JSONException e) { QiscusErrorLogger.print("UploadFile", e); subscriber.onError(e); } }, Emitter.BackpressureMode.BUFFER); } @Deprecated public Observable<QiscusComment> sync(long lastCommentId) { return api.sync(lastCommentId) .onErrorReturn(throwable -> { QiscusErrorLogger.print("Sync", throwable); return null; }) .filter(jsonElement -> jsonElement != null) .flatMap(jsonElement -> Observable.from(jsonElement.getAsJsonObject().get("results") .getAsJsonObject().get("comments").getAsJsonArray())) .map(jsonElement -> { JsonObject jsonComment = jsonElement.getAsJsonObject(); return QiscusApiParser.parseQiscusComment(jsonElement, jsonComment.get("room_id").getAsLong()); }); } public Observable<QiscusComment> synchronize(long lastMessageId) { return api.sync(lastMessageId) .onErrorReturn(throwable -> { QiscusErrorLogger.print("Sync", throwable); return null; }) .filter(jsonElement -> jsonElement != null) .flatMap(jsonElement -> Observable.from(jsonElement.getAsJsonObject().get("results") .getAsJsonObject().get("comments").getAsJsonArray())) .map(jsonElement -> { JsonObject jsonComment = jsonElement.getAsJsonObject(); return QiscusApiParser.parseQiscusComment(jsonElement, jsonComment.get("room_id").getAsLong()); }); } public Observable<QiscusComment> sync() { QiscusComment latestComment = QiscusCore.getDataStore().getLatestComment(); if (latestComment == null || !QiscusTextUtil.getString(R.string.qiscus_today) .equals(QiscusDateUtil.toTodayOrDate(latestComment.getTime()))) { return Observable.empty(); } return synchronize(latestComment.getId()); } @Deprecated public Observable<Uri> uploadFile(File file, ProgressListener progressListener) { return Observable.create(subscriber -> { long fileLength = file.length(); RequestBody requestBody = new MultipartBody.Builder() .setType(MultipartBody.FORM) .addFormDataPart("file", file.getName(), new CountingFileRequestBody(file, totalBytes -> { int progress = (int) (totalBytes * 100 / fileLength); progressListener.onProgress(progress); })) .build(); Request request = new Request.Builder() .url(baseUrl + "api/v2/mobile/upload") .post(requestBody).build(); try { Response response = httpClient.newCall(request).execute(); JSONObject responseJ = new JSONObject(response.body().string()); String result = responseJ.getJSONObject("results").getJSONObject("file").getString("url"); subscriber.onNext(Uri.parse(result)); subscriber.onCompleted(); } catch (IOException | JSONException e) { QiscusErrorLogger.print("UploadFile", e); subscriber.onError(e); } }, Emitter.BackpressureMode.BUFFER); } public Observable<Uri> upload(File file, ProgressListener progressListener) { return Observable.create(subscriber -> { long fileLength = file.length(); RequestBody requestBody = new MultipartBody.Builder() .setType(MultipartBody.FORM) .addFormDataPart("file", file.getName(), new CountingFileRequestBody(file, totalBytes -> { int progress = (int) (totalBytes * 100 / fileLength); progressListener.onProgress(progress); })) .build(); Request request = new Request.Builder() .url(baseUrl + "api/v2/mobile/upload") .post(requestBody).build(); try { Response response = httpClient.newCall(request).execute(); JSONObject responseJ = new JSONObject(response.body().string()); String result = responseJ.getJSONObject("results").getJSONObject("file").getString("url"); subscriber.onNext(Uri.parse(result)); subscriber.onCompleted(); } catch (IOException | JSONException e) { QiscusErrorLogger.print("UploadFile", e); subscriber.onError(e); } }, Emitter.BackpressureMode.BUFFER); } public Observable<File> downloadFile(String url, String fileName, ProgressListener progressListener) { return Observable.create(subscriber -> { InputStream inputStream = null; FileOutputStream fos = null; try { Request request = new Request.Builder().url(url).build(); Response response = httpClient.newCall(request).execute(); File output = new File(QiscusFileUtil.generateFilePath(fileName)); fos = new FileOutputStream(output.getPath()); if (!response.isSuccessful()) { throw new IOException(); } else { ResponseBody responseBody = response.body(); long fileLength = responseBody.contentLength(); inputStream = responseBody.byteStream(); byte[] buffer = new byte[4096]; long total = 0; int count; while ((count = inputStream.read(buffer)) != -1) { total += count; long totalCurrent = total; if (fileLength > 0) { progressListener.onProgress((totalCurrent * 100 / fileLength)); } fos.write(buffer, 0, count); } fos.flush(); subscriber.onNext(output); subscriber.onCompleted(); } } catch (Exception e) { throw OnErrorThrowable.from(OnErrorThrowable.addValueAsLastCause(e, url)); } finally { try { if (fos != null) { fos.close(); } if (inputStream != null) { inputStream.close(); } } catch (IOException ignored) { //Do nothing } } }, Emitter.BackpressureMode.BUFFER); } public Observable<QiscusChatRoom> updateChatRoom(long roomId, String name, String avatarURL, JSONObject extras) { return api.updateChatRoom(QiscusHashMapUtil.updateChatRoom( String.valueOf(roomId), name, avatarURL, extras == null ? null : extras.toString())) .map(QiscusApiParser::parseQiscusChatRoom) .doOnNext(qiscusChatRoom -> QiscusCore.getDataStore().addOrUpdate(qiscusChatRoom)); } public Observable<Void> updateCommentStatus(long roomId, long lastReadId, long lastReceivedId) { return api.updateCommentStatus(QiscusHashMapUtil.updateCommentStatus( String.valueOf(roomId), String.valueOf(lastReadId), String.valueOf(lastReceivedId))) .map(jsonElement -> null); } @Deprecated public Observable<Void> registerFcmToken(String fcmToken) { return api.registerFcmToken(QiscusHashMapUtil.registerOrRemoveFcmToken(fcmToken)) .map(jsonElement -> null); } public Observable<Void> registerDeviceToken(String token) { return api.registerFcmToken(QiscusHashMapUtil.registerOrRemoveFcmToken(token)) .map(jsonElement -> null); } public Observable<Void> removeDeviceToken(String token) { return api.removeDeviceToken(QiscusHashMapUtil.registerOrRemoveFcmToken(token)) .map(jsonElement -> null); } @Deprecated public Observable<Void> clearCommentsByRoomIds(List<Long> roomIds) { List<String> listOfRoomIds = new ArrayList<>(); for (Long roomId : roomIds) { listOfRoomIds.add(String.valueOf(roomId)); } return api.getChatRooms(QiscusHashMapUtil.getChatRooms( listOfRoomIds, null, false, false)) .map(JsonElement::getAsJsonObject) .map(jsonObject -> jsonObject.get("results").getAsJsonObject()) .map(jsonObject -> jsonObject.get("rooms_info").getAsJsonArray()) .flatMap(Observable::from) .map(JsonElement::getAsJsonObject) .map(jsonObject -> jsonObject.get("unique_id").getAsString()) .toList() .flatMap(this::clearCommentsByRoomUniqueIds); } @Deprecated public Observable<Void> clearCommentsByRoomUniqueIds(List<String> roomUniqueIds) { return api.clearChatRoomMessages(roomUniqueIds) .map(JsonElement::getAsJsonObject) .map(jsonResponse -> jsonResponse.get("results").getAsJsonObject()) .map(jsonResults -> jsonResults.get("rooms").getAsJsonArray()) .flatMap(Observable::from) .map(JsonElement::getAsJsonObject) .doOnNext(json -> { long roomId = json.get("id").getAsLong(); if (QiscusCore.getDataStore().deleteCommentsByRoomId(roomId)) { EventBus.getDefault().post(new QiscusClearCommentsEvent(roomId)); } }) .toList() .map(qiscusChatRooms -> null); } public Observable<Void> clearMessagesByChatRoomIds(List<Long> roomIds) { List<String> listOfRoomIds = new ArrayList<>(); for (Long roomId : roomIds) { listOfRoomIds.add(String.valueOf(roomId)); } return api.getChatRooms(QiscusHashMapUtil.getChatRooms( listOfRoomIds, null, false, false)) .map(JsonElement::getAsJsonObject) .map(jsonObject -> jsonObject.get("results").getAsJsonObject()) .map(jsonObject -> jsonObject.get("rooms_info").getAsJsonArray()) .flatMap(Observable::from) .map(JsonElement::getAsJsonObject) .map(jsonObject -> jsonObject.get("unique_id").getAsString()) .toList() .flatMap(this::clearMessagesByChatRoomUniqueIds); } public Observable<Void> clearMessagesByChatRoomUniqueIds(List<String> roomUniqueIds) { return api.clearChatRoomMessages(roomUniqueIds) .map(JsonElement::getAsJsonObject) .map(jsonResponse -> jsonResponse.get("results").getAsJsonObject()) .map(jsonResults -> jsonResults.get("rooms").getAsJsonArray()) .flatMap(Observable::from) .map(JsonElement::getAsJsonObject) .doOnNext(json -> { long roomId = json.get("id").getAsLong(); if (QiscusCore.getDataStore().deleteCommentsByRoomId(roomId)) { EventBus.getDefault().post(new QiscusClearCommentsEvent(roomId)); } }) .toList() .map(qiscusChatRooms -> null); } @Deprecated public Observable<List<QiscusComment>> deleteComments(List<String> commentUniqueIds, boolean isHardDelete) { // isDeleteForEveryone => akan selalu true, karena deleteForMe deprecated return api.deleteComments(commentUniqueIds, true, isHardDelete) .flatMap(jsonElement -> Observable.from(jsonElement.getAsJsonObject().get("results") .getAsJsonObject().get("comments").getAsJsonArray())) .map(jsonElement -> { JsonObject jsonComment = jsonElement.getAsJsonObject(); return QiscusApiParser.parseQiscusComment(jsonElement, jsonComment.get("room_id").getAsLong()); }) .toList() .doOnNext(comments -> { QiscusAccount account = QiscusCore.getQiscusAccount(); QiscusRoomMember actor = new QiscusRoomMember(); actor.setEmail(account.getEmail()); actor.setUsername(account.getUsername()); actor.setAvatar(account.getAvatar()); List<QiscusDeleteCommentHandler.DeletedCommentsData.DeletedComment> deletedComments = new ArrayList<>(); for (QiscusComment comment : comments) { deletedComments.add(new QiscusDeleteCommentHandler.DeletedCommentsData.DeletedComment(comment.getRoomId(), comment.getUniqueId())); } QiscusDeleteCommentHandler.DeletedCommentsData deletedCommentsData = new QiscusDeleteCommentHandler.DeletedCommentsData(); deletedCommentsData.setActor(actor); deletedCommentsData.setHardDelete(isHardDelete); deletedCommentsData.setDeletedComments(deletedComments); QiscusDeleteCommentHandler.handle(deletedCommentsData); }); } public Observable<List<QiscusComment>> deleteMessages(List<String> messageUniqueIds) { return api.deleteComments(messageUniqueIds, true, true) .flatMap(jsonElement -> Observable.from(jsonElement.getAsJsonObject().get("results") .getAsJsonObject().get("comments").getAsJsonArray())) .map(jsonElement -> { JsonObject jsonComment = jsonElement.getAsJsonObject(); return QiscusApiParser.parseQiscusComment(jsonElement, jsonComment.get("room_id").getAsLong()); }) .toList() .doOnNext(comments -> { QiscusAccount account = QiscusCore.getQiscusAccount(); QiscusRoomMember actor = new QiscusRoomMember(); actor.setEmail(account.getEmail()); actor.setUsername(account.getUsername()); actor.setAvatar(account.getAvatar()); List<QiscusDeleteCommentHandler.DeletedCommentsData.DeletedComment> deletedComments = new ArrayList<>(); for (QiscusComment comment : comments) { deletedComments.add(new QiscusDeleteCommentHandler.DeletedCommentsData.DeletedComment(comment.getRoomId(), comment.getUniqueId())); } QiscusDeleteCommentHandler.DeletedCommentsData deletedCommentsData = new QiscusDeleteCommentHandler.DeletedCommentsData(); deletedCommentsData.setActor(actor); deletedCommentsData.setHardDelete(true); deletedCommentsData.setDeletedComments(deletedComments); QiscusDeleteCommentHandler.handle(deletedCommentsData); }); } @Deprecated public Observable<List<JSONObject>> getEvents(long startEventId) { return api.getEvents(startEventId) .flatMap(jsonElement -> Observable.from(jsonElement.getAsJsonObject().get("events").getAsJsonArray())) .map(jsonEvent -> { try { return new JSONObject(jsonEvent.toString()); } catch (JSONException e) { return null; } }) .filter(jsonObject -> jsonObject != null) .doOnNext(QiscusPusherApi::handleNotification) .toList(); } public Observable<List<JSONObject>> synchronizeEvent(long lastEventId) { return api.getEvents(lastEventId) .flatMap(jsonElement -> Observable.from(jsonElement.getAsJsonObject().get("events").getAsJsonArray())) .map(jsonEvent -> { try { return new JSONObject(jsonEvent.toString()); } catch (JSONException e) { return null; } }) .filter(jsonObject -> jsonObject != null) .doOnNext(QiscusPusherApi::handleNotification) .toList(); } public Observable<Long> getTotalUnreadCount() { return api.getTotalUnreadCount() .map(JsonElement::getAsJsonObject) .map(jsonResponse -> jsonResponse.get("results").getAsJsonObject()) .map(jsonResults -> jsonResults.get("total_unread_count").getAsLong()); } @Deprecated public Observable<QiscusChatRoom> addRoomMember(long roomId, List<String> emails) { return api.addRoomMember(QiscusHashMapUtil.addRoomMember(String.valueOf(roomId), emails)) .flatMap(jsonElement -> getChatRoomInfo(roomId)); } public Observable<QiscusChatRoom> addParticipants(long roomId, List<String> userIds) { return api.addRoomMember(QiscusHashMapUtil.addRoomMember(String.valueOf(roomId), userIds)) .flatMap(jsonElement -> getChatRoomInfo(roomId)); } @Deprecated public Observable<QiscusChatRoom> removeRoomMember(long roomId, List<String> userIds) { return api.removeRoomMember(QiscusHashMapUtil.removeRoomMember(String.valueOf(roomId), userIds)) .flatMap(jsonElement -> getChatRoomInfo(roomId)); } public Observable<QiscusChatRoom> removeParticipants(long roomId, List<String> userIds) { return api.removeRoomMember(QiscusHashMapUtil.removeRoomMember(String.valueOf(roomId), userIds)) .flatMap(jsonElement -> getChatRoomInfo(roomId)); } public Observable<QiscusAccount> blockUser(String userId) { return api.blockUser(QiscusHashMapUtil.blockUser(userId)) .map(JsonElement::getAsJsonObject) .map(jsonResponse -> jsonResponse.getAsJsonObject("results")) .map(jsonResults -> jsonResults.getAsJsonObject("user")) .map(jsonAccount -> { try { return QiscusApiParser.parseQiscusAccount( new JSONObject(jsonAccount.toString()), false); } catch (JSONException e) { e.printStackTrace(); } return null; }); } public Observable<QiscusAccount> unblockUser(String userId) { return api.unblockUser(QiscusHashMapUtil.unblockUser(userId)) .map(JsonElement::getAsJsonObject) .map(jsonResponse -> jsonResponse.getAsJsonObject("results")) .map(jsonResults -> jsonResults.getAsJsonObject("user")) .map(jsonAccount -> { try { return QiscusApiParser.parseQiscusAccount( new JSONObject(jsonAccount.toString()), false); } catch (JSONException e) { e.printStackTrace(); } return null; }); } public Observable<List<QiscusAccount>> getBlockedUsers() { return getBlockedUsers(0, 100); } public Observable<List<QiscusAccount>> getBlockedUsers(long page, long limit) { return api.getBlockedUsers(page, limit) .map(JsonElement::getAsJsonObject) .map(jsonResponse -> jsonResponse.getAsJsonObject("results")) .map(jsonResults -> jsonResults.getAsJsonArray("blocked_users")) .flatMap(Observable::from) .map(JsonElement::getAsJsonObject) .map(jsonAccount -> { try { return QiscusApiParser.parseQiscusAccount( new JSONObject(jsonAccount.toString()), false); } catch (JSONException e) { e.printStackTrace(); } return null; }) .toList(); } @Deprecated public Observable<List<QiscusRoomMember>> getRoomMembers(String roomUniqueId, int offset, MetaRoomMembersListener metaRoomMembersListener) { return getRoomMembers(roomUniqueId, offset, null, metaRoomMembersListener); } @Deprecated public Observable<List<QiscusRoomMember>> getRoomMembers(String roomUniqueId, int offset, String sorting, MetaRoomMembersListener metaRoomMembersListener) { return api.getRoomParticipants(roomUniqueId, 0, 0, offset, sorting) .map(JsonElement::getAsJsonObject) .map(jsonResponse -> jsonResponse.getAsJsonObject("results")) .doOnNext(jsonResults -> { JsonObject meta = jsonResults.getAsJsonObject("meta"); if (metaRoomMembersListener != null) { metaRoomMembersListener.onMetaReceived( meta.get("current_offset").getAsInt(), meta.get("per_page").getAsInt(), meta.get("total").getAsInt() ); } }) .map(jsonResults -> jsonResults.getAsJsonArray("participants")) .flatMap(Observable::from) .map(JsonElement::getAsJsonObject) .map(QiscusApiParser::parseQiscusRoomMember) .toList(); } public Observable<List<QiscusRoomMember>> getParticipants(String roomUniqueId, int page, int limit, String sorting, MetaRoomParticipantsListener metaRoomParticipantListener) { return api.getRoomParticipants(roomUniqueId, page, limit, 0, sorting) .map(JsonElement::getAsJsonObject) .map(jsonResponse -> jsonResponse.getAsJsonObject("results")) .doOnNext(jsonResults -> { JsonObject meta = jsonResults.getAsJsonObject("meta"); if (metaRoomParticipantListener != null) { metaRoomParticipantListener.onMetaReceived( meta.get("current_page").getAsInt(), meta.get("per_page").getAsInt(), meta.get("total").getAsInt() ); } }) .map(jsonResults -> jsonResults.getAsJsonArray("participants")) .flatMap(Observable::from) .map(JsonElement::getAsJsonObject) .map(QiscusApiParser::parseQiscusRoomMember) .toList(); } public Observable<List<QiscusRoomMember>> getParticipants(String roomUniqueId, int page, int limit, String sorting) { return api.getRoomParticipants(roomUniqueId, page, limit, 0, sorting) .map(JsonElement::getAsJsonObject) .map(jsonResponse -> jsonResponse.getAsJsonObject("results")) .doOnNext(jsonResults -> { }) .map(jsonResults -> jsonResults.getAsJsonArray("participants")) .flatMap(Observable::from) .map(JsonElement::getAsJsonObject) .map(QiscusApiParser::parseQiscusRoomMember) .toList(); } public Observable<String> getMqttBaseUrl() { return Observable.create(subscriber -> { OkHttpClient httpClientLB; if (Build.VERSION.SDK_INT <= 19) { ConnectionSpec spec = new ConnectionSpec.Builder(ConnectionSpec.COMPATIBLE_TLS) .supportsTlsExtensions(true) .allEnabledTlsVersions() .allEnabledCipherSuites() .build(); httpClientLB = new OkHttpClient.Builder() .connectTimeout(60, TimeUnit.SECONDS) .readTimeout(60, TimeUnit.SECONDS) .addInterceptor(this::headersInterceptor) .addInterceptor(makeLoggingInterceptor(QiscusCore.getChatConfig().isEnableLog())) .connectionSpecs(Collections.singletonList(spec)) .build(); } else { httpClientLB = new OkHttpClient.Builder() .connectTimeout(60, TimeUnit.SECONDS) .readTimeout(60, TimeUnit.SECONDS) .addInterceptor(this::headersInterceptor) .addInterceptor(makeLoggingInterceptor(QiscusCore.getChatConfig().isEnableLog())) .build(); } String url = QiscusCore.getBaseURLLB(); Request okHttpRequest = new Request.Builder().url(url).build(); try { Response response = httpClientLB.newCall(okHttpRequest).execute(); JSONObject jsonResponse = new JSONObject(response.body().string()); String node = jsonResponse.getString("node"); subscriber.onNext(node); subscriber.onCompleted(); } catch (IOException | JSONException e) { e.printStackTrace(); } }, Emitter.BackpressureMode.BUFFER); } public Observable<List<QiscusAccount>> getUsers(String searchUsername) { return getUsers(searchUsername, 0, 100); } @Deprecated public Observable<List<QiscusAccount>> getUsers(long page, long limit, String query) { return api.getUserList(page, limit, "username asc", query) .map(JsonElement::getAsJsonObject) .map(jsonResponse -> jsonResponse.getAsJsonObject("results")) .map(jsonResults -> jsonResults.getAsJsonArray("users")) .flatMap(Observable::from) .map(JsonElement::getAsJsonObject) .map(jsonAccount -> { try { return QiscusApiParser.parseQiscusAccount( new JSONObject(jsonAccount.toString()), false); } catch (JSONException e) { e.printStackTrace(); } return null; }) .toList(); } public Observable<List<QiscusAccount>> getUsers(String searchUsername, long page, long limit) { return api.getUserList(page, limit, "username asc", searchUsername) .map(JsonElement::getAsJsonObject) .map(jsonResponse -> jsonResponse.getAsJsonObject("results")) .map(jsonResults -> jsonResults.getAsJsonArray("users")) .flatMap(Observable::from) .map(JsonElement::getAsJsonObject) .map(jsonAccount -> { try { return QiscusApiParser.parseQiscusAccount( new JSONObject(jsonAccount.toString()), false); } catch (JSONException e) { e.printStackTrace(); } return null; }) .toList(); } public Observable<Void> eventReport(String moduleName, String event, String message) { return api.eventReport(QiscusHashMapUtil.eventReport(moduleName, event, message)) .map(jsonElement -> null); } public Observable<QiscusAppConfig> getAppConfig() { return api.getAppConfig() .map(QiscusApiParser::parseQiscusAppConfig); } public Observable<QiscusRealtimeStatus> getRealtimeStatus(String topic) { return api.getRealtimeStatus(QiscusHashMapUtil.getRealtimeStatus(topic)) .map(QiscusApiParser::parseQiscusRealtimeStatus); } public Observable<List<QiscusChannels>> getChannels() { return api.getChannels() .map(QiscusApiParser::parseQiscusChannels); } public Observable<List<QiscusChannels>> getChannelsInfo(List<String> uniqueIds) { return api.getChannelsInfo(QiscusHashMapUtil.getChannelsInfo(uniqueIds)) .map(QiscusApiParser::parseQiscusChannels); } public Observable<List<QiscusChannels>> joinChannels(List<String> uniqueIds) { return api.joinChannels(QiscusHashMapUtil.joinChannels(uniqueIds)) .map(QiscusApiParser::parseQiscusChannels); } public Observable<List<QiscusChannels>> leaveChannels(List<String> uniqueIds) { return api.leaveChannels(QiscusHashMapUtil.leaveChannels(uniqueIds)) .map(QiscusApiParser::parseQiscusChannels); } public Observable<List<QUserPresence>> getUserPresence(List<String> userIds) { return api.usersPresence(QiscusHashMapUtil.usersPresence(userIds)) .map(QiscusApiParser::parseQiscusUserPresence); } private interface Api { @Headers("Content-Type: application/json") @POST("api/v2/mobile/event_report") Observable<JsonElement> eventReport( @Body HashMap<String, Object> data ); @Headers("Content-Type: application/json") @POST("api/v2/mobile/auth/nonce") Observable<JsonElement> requestNonce(); @Headers("Content-Type: application/json") @POST("api/v2/mobile/auth/verify_identity_token") Observable<JsonElement> login( @Body HashMap<String, Object> data ); @Headers("Content-Type: application/json") @POST("api/v2/mobile/login_or_register") Observable<JsonElement> loginOrRegister( @Body HashMap<String, Object> data ); @Headers("Content-Type: application/json") @PATCH("api/v2/mobile/my_profile") Observable<JsonElement> updateProfile( @Body HashMap<String, Object> data ); @GET("api/v2/mobile/my_profile") Observable<JsonElement> getUserData( ); @Headers("Content-Type: application/json") @POST("api/v2/mobile/get_or_create_room_with_target") Observable<JsonElement> createOrGetChatRoom( @Body HashMap<String, Object> data ); @Headers("Content-Type: application/json") @POST("api/v2/mobile/create_room") Observable<JsonElement> createGroupChatRoom( @Body HashMap<String, Object> data ); @Headers("Content-Type: application/json") @POST("api/v2/mobile/get_or_create_room_with_unique_id") Observable<JsonElement> createOrGetGroupChatRoom( @Body HashMap<String, Object> data ); @GET("api/v2/mobile/get_room_by_id") Observable<JsonElement> getChatRoom( @Query("id") long roomId ); @GET("api/v2/mobile/load_comments") Observable<JsonElement> getComments( @Query("topic_id") long roomId, @Query("last_comment_id") Long lastCommentId, @Query("after") boolean after, @Query("limit") int limit ); @Headers("Content-Type: application/json") @POST("api/v2/mobile/post_comment") Observable<JsonElement> postComment( @Body HashMap<String, Object> data ); @GET("api/v2/mobile/sync") Observable<JsonElement> sync( @Query("last_received_comment_id") long lastCommentId ); @Headers("Content-Type: application/json") @POST("api/v2/mobile/update_room") Observable<JsonElement> updateChatRoom( @Body HashMap<String, Object> data ); @Headers("Content-Type: application/json") @POST("api/v2/mobile/update_comment_status") Observable<JsonElement> updateCommentStatus( @Body HashMap<String, Object> data ); @Headers("Content-Type: application/json") @POST("api/v2/mobile/set_user_device_token") Observable<JsonElement> registerFcmToken( @Body HashMap<String, Object> data ); @Headers("Content-Type: application/json") @POST("api/v2/mobile/remove_user_device_token") Observable<JsonElement> removeDeviceToken( @Body HashMap<String, Object> data ); @GET("api/v2/mobile/user_rooms") Observable<JsonElement> getChatRooms( @Query("page") int page, @Query("limit") int limit, @Query("show_participants") boolean showParticipants, @Query("show_empty") boolean showEmpty, @Query("show_removed") boolean showRemoved ); @Headers("Content-Type: application/json") @POST("api/v2/mobile/rooms_info") Observable<JsonElement> getChatRooms( @Body HashMap<String, Object> data ); @DELETE("api/v2/mobile/clear_room_messages") Observable<JsonElement> clearChatRoomMessages( @Query("room_channel_ids[]") List<String> roomUniqueIds ); @DELETE("api/v2/mobile/delete_messages") Observable<JsonElement> deleteComments( @Query("unique_ids[]") List<String> commentUniqueIds, @Query("is_delete_for_everyone") boolean isDeleteForEveryone, @Query("is_hard_delete") boolean isHardDelete ); @GET("api/v2/mobile/sync_event") Observable<JsonElement> getEvents( @Query("start_event_id") long startEventId ); @GET("api/v2/mobile/total_unread_count") Observable<JsonElement> getTotalUnreadCount(); @Headers("Content-Type: application/json") @POST("api/v2/mobile/add_room_participants") Observable<JsonElement> addRoomMember( @Body HashMap<String, Object> data ); @Headers("Content-Type: application/json") @POST("api/v2/mobile/remove_room_participants") Observable<JsonElement> removeRoomMember( @Body HashMap<String, Object> data ); @Headers("Content-Type: application/json") @POST("/api/v2/mobile/block_user") Observable<JsonElement> blockUser( @Body HashMap<String, Object> data ); @Headers("Content-Type: application/json") @POST("/api/v2/mobile/unblock_user") Observable<JsonElement> unblockUser( @Body HashMap<String, Object> data ); @GET("/api/v2/mobile/get_blocked_users") Observable<JsonElement> getBlockedUsers( @Query("page") long page, @Query("limit") long limit ); @GET("/api/v2/mobile/room_participants") Observable<JsonElement> getRoomParticipants( @Query("room_unique_id") String roomUniqId, @Query("page") int page, @Query("limit") int limit, @Query("offset") int offset, @Query("sorting") String sorting ); @GET("/api/v2/mobile/get_user_list") Observable<JsonElement> getUserList( @Query("page") long page, @Query("limit") long limit, @Query("order_query") String orderQuery, @Query("query") String query ); @GET("api/v2/mobile/config") Observable<JsonElement> getAppConfig(); @Headers("Content-Type: application/json") @POST("api/v2/mobile/realtime") Observable<JsonElement> getRealtimeStatus( @Body HashMap<String, Object> data ); @GET("api/v2/mobile/channels") Observable<JsonElement> getChannels(); @Headers("Content-Type: application/json") @POST("api/v2/mobile/channels/info") Observable<JsonElement> getChannelsInfo( @Body HashMap<String, Object> data ); @Headers("Content-Type: application/json") @POST("api/v2/mobile/channels/join") Observable<JsonElement> joinChannels( @Body HashMap<String, Object> data ); @Headers("Content-Type: application/json") @POST("api/v2/mobile/channels/leave") Observable<JsonElement> leaveChannels( @Body HashMap<String, Object> data ); @Headers("Content-Type: application/json") @POST("api/v2/mobile/users/status") Observable<JsonElement> usersPresence( @Body HashMap<String, Object> data ); } public interface MetaRoomMembersListener { void onMetaReceived(int currentOffset, int perPage, int total); } public interface MetaRoomParticipantsListener { void onMetaReceived(int currentPage, int perPage, int total); } public interface ProgressListener { void onProgress(long total); } private static class CountingFileRequestBody extends RequestBody { private static final int SEGMENT_SIZE = 2048; private static final int IGNORE_FIRST_NUMBER_OF_WRITE_TO_CALL = 0; private final File file; private final ProgressListener progressListener; private int numWriteToCall = -1; private CountingFileRequestBody(File file, ProgressListener progressListener) { this.file = file; this.progressListener = progressListener; } @Override public MediaType contentType() { return MediaType.parse("application/octet-stream"); } @Override public long contentLength() throws IOException { return file.length(); } @Override public void writeTo(@NonNull BufferedSink sink) throws IOException { numWriteToCall++; Source source = null; try { source = Okio.source(file); long total = 0; long read; while ((read = source.read(sink.buffer(), SEGMENT_SIZE)) != -1) { total += read; sink.flush(); /** * When we use HttpLoggingInterceptor, * we have issue with progress update not valid. * So we must check, first call is to HttpLoggingInterceptor * second call is to request */ if (numWriteToCall > IGNORE_FIRST_NUMBER_OF_WRITE_TO_CALL) { progressListener.onProgress(total); } } } finally { Util.closeQuietly(source); } } } }
chat-core/src/main/java/com/qiscus/sdk/chat/core/data/remote/QiscusApi.java
/* * Copyright (c) 2016 Qiscus. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.qiscus.sdk.chat.core.data.remote; import android.net.Uri; import android.os.Build; import androidx.annotation.NonNull; import androidx.core.util.Pair; import com.google.gson.JsonElement; import com.google.gson.JsonObject; import com.qiscus.sdk.chat.core.BuildConfig; import com.qiscus.sdk.chat.core.QiscusCore; import com.qiscus.sdk.chat.core.R; import com.qiscus.sdk.chat.core.data.model.QUserPresence; import com.qiscus.sdk.chat.core.data.model.QiscusAccount; import com.qiscus.sdk.chat.core.data.model.QiscusAppConfig; import com.qiscus.sdk.chat.core.data.model.QiscusChannels; import com.qiscus.sdk.chat.core.data.model.QiscusChatRoom; import com.qiscus.sdk.chat.core.data.model.QiscusComment; import com.qiscus.sdk.chat.core.data.model.QiscusNonce; import com.qiscus.sdk.chat.core.data.model.QiscusRealtimeStatus; import com.qiscus.sdk.chat.core.data.model.QiscusRoomMember; import com.qiscus.sdk.chat.core.event.QiscusClearCommentsEvent; import com.qiscus.sdk.chat.core.event.QiscusCommentSentEvent; import com.qiscus.sdk.chat.core.util.BuildVersionUtil; import com.qiscus.sdk.chat.core.util.QiscusDateUtil; import com.qiscus.sdk.chat.core.util.QiscusErrorLogger; import com.qiscus.sdk.chat.core.util.QiscusFileUtil; import com.qiscus.sdk.chat.core.util.QiscusHashMapUtil; import com.qiscus.sdk.chat.core.util.QiscusLogger; import com.qiscus.sdk.chat.core.util.QiscusTextUtil; import org.greenrobot.eventbus.EventBus; import org.json.JSONException; import org.json.JSONObject; import java.io.File; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; import java.util.ArrayList; import java.util.Collections; import java.util.Date; import java.util.HashMap; import java.util.Iterator; import java.util.List; import java.util.concurrent.TimeUnit; import okhttp3.ConnectionSpec; import okhttp3.Interceptor; import okhttp3.MediaType; import okhttp3.MultipartBody; import okhttp3.OkHttpClient; import okhttp3.Request; import okhttp3.RequestBody; import okhttp3.Response; import okhttp3.ResponseBody; import okhttp3.internal.Util; import okhttp3.logging.HttpLoggingInterceptor; import okio.BufferedSink; import okio.Okio; import okio.Source; import retrofit2.Retrofit; import retrofit2.adapter.rxjava.RxJavaCallAdapterFactory; import retrofit2.converter.gson.GsonConverterFactory; import retrofit2.http.Body; import retrofit2.http.DELETE; import retrofit2.http.GET; import retrofit2.http.Headers; import retrofit2.http.PATCH; import retrofit2.http.POST; import retrofit2.http.Query; import rx.Emitter; import rx.Observable; import rx.android.schedulers.AndroidSchedulers; import rx.exceptions.OnErrorThrowable; import rx.schedulers.Schedulers; /** * Created on : August 18, 2016 * Author : zetbaitsu * Name : Zetra * GitHub : https://github.com/zetbaitsu */ public enum QiscusApi { INSTANCE; private OkHttpClient httpClient; private Api api; private String baseUrl; QiscusApi() { baseUrl = QiscusCore.getAppServer(); if (Build.VERSION.SDK_INT <= 19) { ConnectionSpec spec = new ConnectionSpec.Builder(ConnectionSpec.COMPATIBLE_TLS) .supportsTlsExtensions(true) .allEnabledTlsVersions() .allEnabledCipherSuites() .build(); httpClient = new OkHttpClient.Builder() .connectTimeout(60, TimeUnit.SECONDS) .readTimeout(60, TimeUnit.SECONDS) .addInterceptor(this::headersInterceptor) .addInterceptor(makeLoggingInterceptor(QiscusCore.getChatConfig().isEnableLog())) .connectionSpecs(Collections.singletonList(spec)) .build(); } else { httpClient = new OkHttpClient.Builder() .connectTimeout(60, TimeUnit.SECONDS) .readTimeout(60, TimeUnit.SECONDS) .addInterceptor(this::headersInterceptor) .addInterceptor(makeLoggingInterceptor(QiscusCore.getChatConfig().isEnableLog())) .build(); } api = new Retrofit.Builder() .baseUrl(baseUrl) .client(httpClient) .addConverterFactory(GsonConverterFactory.create()) .addCallAdapterFactory(RxJavaCallAdapterFactory.create()) .build() .create(Api.class); } public static QiscusApi getInstance() { return INSTANCE; } public void reInitiateInstance() { baseUrl = QiscusCore.getAppServer(); if (Build.VERSION.SDK_INT <= 19) { ConnectionSpec spec = new ConnectionSpec.Builder(ConnectionSpec.COMPATIBLE_TLS) .supportsTlsExtensions(true) .allEnabledTlsVersions() .allEnabledCipherSuites() .build(); httpClient = new OkHttpClient.Builder() .connectTimeout(60, TimeUnit.SECONDS) .readTimeout(60, TimeUnit.SECONDS) .addInterceptor(this::headersInterceptor) .addInterceptor(makeLoggingInterceptor(QiscusCore.getChatConfig().isEnableLog())) .connectionSpecs(Collections.singletonList(spec)) .build(); } else { httpClient = new OkHttpClient.Builder() .connectTimeout(60, TimeUnit.SECONDS) .readTimeout(60, TimeUnit.SECONDS) .addInterceptor(this::headersInterceptor) .addInterceptor(makeLoggingInterceptor(QiscusCore.getChatConfig().isEnableLog())) .build(); } try { api = new Retrofit.Builder() .baseUrl(baseUrl) .client(httpClient) .addConverterFactory(GsonConverterFactory.create()) .addCallAdapterFactory(RxJavaCallAdapterFactory.create()) .build() .create(Api.class); } catch (IllegalArgumentException e) { QiscusErrorLogger.print(e); return; } } private Response headersInterceptor(Interceptor.Chain chain) throws IOException { Request.Builder builder = chain.request().newBuilder(); JSONObject jsonCustomHeader = QiscusCore.getCustomHeader(); builder.addHeader("QISCUS-SDK-APP-ID", QiscusCore.getAppId()); builder.addHeader("QISCUS-SDK-TOKEN", QiscusCore.hasSetupUser() ? QiscusCore.getToken() : ""); builder.addHeader("QISCUS-SDK-USER-EMAIL", QiscusCore.hasSetupUser() ? QiscusCore.getQiscusAccount().getEmail() : ""); builder.addHeader("QISCUS-SDK-VERSION", "ANDROID_" + BuildConfig.VERSION_NAME); builder.addHeader("QISCUS-SDK-PLATFORM", "ANDROID"); builder.addHeader("QISCUS-SDK-DEVICE-BRAND", Build.MANUFACTURER); builder.addHeader("QISCUS-SDK-DEVICE-MODEL", Build.MODEL); builder.addHeader("QISCUS-SDK-DEVICE-OS-VERSION", BuildVersionUtil.OS_VERSION_NAME); if (jsonCustomHeader != null) { Iterator<String> keys = jsonCustomHeader.keys(); while (keys.hasNext()) { String key = keys.next(); try { Object customHeader = jsonCustomHeader.get(key); if (customHeader != null) { builder.addHeader(key, customHeader.toString()); } } catch (JSONException e) { e.printStackTrace(); } } } Request req = builder.build(); return chain.proceed(req); } private HttpLoggingInterceptor makeLoggingInterceptor(boolean isDebug) { HttpLoggingInterceptor logging = new HttpLoggingInterceptor(); logging.setLevel(isDebug ? HttpLoggingInterceptor.Level.BODY : HttpLoggingInterceptor.Level.NONE); return logging; } @Deprecated public Observable<QiscusNonce> requestNonce() { return api.requestNonce().map(QiscusApiParser::parseNonce); } public Observable<QiscusNonce> getJWTNonce() { return api.requestNonce().map(QiscusApiParser::parseNonce); } @Deprecated public Observable<QiscusAccount> login(String token) { return api.login(QiscusHashMapUtil.login(token)).map(QiscusApiParser::parseQiscusAccount); } public Observable<QiscusAccount> setUserWithIdentityToken(String token) { return api.login(QiscusHashMapUtil.login(token)).map(QiscusApiParser::parseQiscusAccount); } @Deprecated public Observable<QiscusAccount> loginOrRegister(String email, String password, String username, String avatarUrl) { return loginOrRegister(email, password, username, avatarUrl, null); } @Deprecated public Observable<QiscusAccount> loginOrRegister(String email, String password, String username, String avatarUrl, JSONObject extras) { return api.loginOrRegister(QiscusHashMapUtil.loginOrRegister( email, password, username, avatarUrl, extras == null ? null : extras.toString() )) .map(QiscusApiParser::parseQiscusAccount); } public Observable<QiscusAccount> setUser(String userId, String userKey, String username, String avatarURL, JSONObject extras) { return api.loginOrRegister(QiscusHashMapUtil.loginOrRegister( userId, userKey, username, avatarURL, extras == null ? null : extras.toString())) .map(QiscusApiParser::parseQiscusAccount); } @Deprecated public Observable<QiscusAccount> updateProfile(String username, String avatarUrl) { return updateProfile(username, avatarUrl, null); } public Observable<QiscusAccount> updateUser(String name, String avatarURL) { return updateUser(name, avatarURL, null); } @Deprecated public Observable<QiscusAccount> updateProfile(String username, String avatarUrl, JSONObject extras) { return api.updateProfile(QiscusHashMapUtil.updateProfile( username, avatarUrl, extras == null ? null : extras.toString())) .map(QiscusApiParser::parseQiscusAccount); } public Observable<QiscusAccount> updateUser(String name, String avatarURL, JSONObject extras) { return api.updateProfile(QiscusHashMapUtil.updateProfile( name, avatarURL, extras == null ? null : extras.toString())) .map(QiscusApiParser::parseQiscusAccount); } public Observable<QiscusAccount> getUserData() { return api.getUserData() .map(QiscusApiParser::parseQiscusAccount); } @Deprecated public Observable<QiscusChatRoom> getChatRoom(String withEmail, JSONObject options) { return api.createOrGetChatRoom(QiscusHashMapUtil.getChatRoom(Collections.singletonList(withEmail), options == null ? null : options.toString())) .map(QiscusApiParser::parseQiscusChatRoom); } public Observable<QiscusChatRoom> chatUser(String userId, JSONObject extras) { return api.createOrGetChatRoom(QiscusHashMapUtil.getChatRoom(Collections.singletonList(userId), extras == null ? null : extras.toString())) .map(QiscusApiParser::parseQiscusChatRoom); } @Deprecated public Observable<QiscusChatRoom> createGroupChatRoom(String name, List<String> emails, String avatarUrl, JSONObject options) { return api.createGroupChatRoom(QiscusHashMapUtil.createGroupChatRoom( name, emails, avatarUrl, options == null ? null : options.toString())) .map(QiscusApiParser::parseQiscusChatRoom); } public Observable<QiscusChatRoom> createGroupChat(String name, List<String> userIds, String avatarURL, JSONObject extras) { return api.createGroupChatRoom(QiscusHashMapUtil.createGroupChatRoom( name, userIds, avatarURL, extras == null ? null : extras.toString())) .map(QiscusApiParser::parseQiscusChatRoom); } @Deprecated public Observable<QiscusChatRoom> getGroupChatRoom(String uniqueId, String name, String avatarUrl, JSONObject options) { return api.createOrGetGroupChatRoom(QiscusHashMapUtil.getGroupChatRoom( uniqueId, name, avatarUrl, options == null ? null : options.toString())) .map(QiscusApiParser::parseQiscusChatRoom); } public Observable<QiscusChatRoom> createChannel(String uniqueId, String name, String avatarURL, JSONObject extras) { return api.createOrGetGroupChatRoom(QiscusHashMapUtil.getGroupChatRoom( uniqueId, name, avatarURL, extras == null ? null : extras.toString())) .map(QiscusApiParser::parseQiscusChatRoom); } public Observable<QiscusChatRoom> getChannel(String uniqueId) { return api.createOrGetGroupChatRoom(QiscusHashMapUtil.getGroupChatRoom( uniqueId, null, null, null)) .map(QiscusApiParser::parseQiscusChatRoom); } @Deprecated public Observable<QiscusChatRoom> getChatRoom(long roomId) { return api.getChatRooms(QiscusHashMapUtil.getChatRooms( Collections.singletonList(String.valueOf(roomId)), new ArrayList<>(), true, false)) .map(QiscusApiParser::parseQiscusChatRoomInfo) .flatMap(Observable::from) .take(1); } public Observable<QiscusChatRoom> getChatRoomInfo(long roomId) { return api.getChatRooms(QiscusHashMapUtil.getChatRooms( Collections.singletonList(String.valueOf(roomId)), new ArrayList<>(), true, false)) .map(QiscusApiParser::parseQiscusChatRoomInfo) .flatMap(Observable::from) .take(1); } @Deprecated public Observable<Pair<QiscusChatRoom, List<QiscusComment>>> getChatRoomComments(long roomId) { return api.getChatRoom(roomId) .map(QiscusApiParser::parseQiscusChatRoomWithComments); } public Observable<Pair<QiscusChatRoom, List<QiscusComment>>> getChatRoomWithMessages(long roomId) { return api.getChatRoom(roomId) .map(QiscusApiParser::parseQiscusChatRoomWithComments); } @Deprecated public Observable<List<QiscusChatRoom>> getChatRooms(int page, int limit, boolean showMembers) { return api.getChatRooms(page, limit, showMembers, false, false) .map(QiscusApiParser::parseQiscusChatRoomInfo); } public Observable<List<QiscusChatRoom>> getAllChatRooms(boolean showParticipant, boolean showRemoved, boolean showEmpty, int page, int limit) { return api.getChatRooms(page, limit, showParticipant, showEmpty, showRemoved) .map(QiscusApiParser::parseQiscusChatRoomInfo); } @Deprecated public Observable<List<QiscusChatRoom>> getChatRooms(List<Long> roomIds, List<String> uniqueIds, boolean showMembers) { List<String> listOfRoomIds = new ArrayList<>(); for (Long roomId : roomIds) { listOfRoomIds.add(String.valueOf(roomId)); } return api.getChatRooms(QiscusHashMapUtil.getChatRooms( listOfRoomIds, uniqueIds, showMembers, false)) .map(QiscusApiParser::parseQiscusChatRoomInfo); } public Observable<List<QiscusChatRoom>> getChatRoomsWithUniqueIds(List<String> uniqueIds, boolean showRemoved, boolean showParticipant) { return api.getChatRooms(QiscusHashMapUtil.getChatRooms( null, uniqueIds, showParticipant, showRemoved)) .map(QiscusApiParser::parseQiscusChatRoomInfo); } public Observable<List<QiscusChatRoom>> getChatRooms(List<Long> roomIds, boolean showRemoved, boolean showParticipant) { List<String> listOfRoomIds = new ArrayList<>(); for (Long roomId : roomIds) { listOfRoomIds.add(String.valueOf(roomId)); } return api.getChatRooms(QiscusHashMapUtil.getChatRooms( listOfRoomIds, null, showParticipant, showRemoved)) .map(QiscusApiParser::parseQiscusChatRoomInfo); } @Deprecated public Observable<QiscusComment> getComments(long roomId, long lastCommentId) { Long lastCommenID = lastCommentId; if (lastCommenID == 0) { lastCommenID = null; } return api.getComments(roomId, lastCommenID, false, 20) .flatMap(jsonElement -> Observable.from(jsonElement.getAsJsonObject().get("results") .getAsJsonObject().get("comments").getAsJsonArray())) .map(jsonElement -> QiscusApiParser.parseQiscusComment(jsonElement, roomId)); } @Deprecated public Observable<QiscusComment> getCommentsAfter(long roomId, long lastCommentId) { Long lastCommentID = lastCommentId; if (lastCommentID == 0) { lastCommentID = null; } return api.getComments(roomId, lastCommentID, true, 20) .flatMap(jsonElement -> Observable.from(jsonElement.getAsJsonObject().get("results") .getAsJsonObject().get("comments").getAsJsonArray())) .map(jsonElement -> QiscusApiParser.parseQiscusComment(jsonElement, roomId)); } public Observable<QiscusComment> getPreviousMessagesById(long roomId, int limit, long messageId) { Long messageID = messageId; if (messageID == 0) { messageID = null; } return api.getComments(roomId, messageID, false, limit) .flatMap(jsonElement -> Observable.from(jsonElement.getAsJsonObject().get("results") .getAsJsonObject().get("comments").getAsJsonArray())) .map(jsonElement -> QiscusApiParser.parseQiscusComment(jsonElement, roomId)); } public Observable<QiscusComment> getPreviousMessagesById(long roomId, int limit) { return api.getComments(roomId, null, false, limit) .flatMap(jsonElement -> Observable.from(jsonElement.getAsJsonObject().get("results") .getAsJsonObject().get("comments").getAsJsonArray())) .map(jsonElement -> QiscusApiParser.parseQiscusComment(jsonElement, roomId)); } public Observable<QiscusComment> getNextMessagesById(long roomId, int limit, long messageId) { Long messageID = messageId; if (messageID == 0) { messageID = null; } return api.getComments(roomId, messageID, true, limit) .flatMap(jsonElement -> Observable.from(jsonElement.getAsJsonObject().get("results") .getAsJsonObject().get("comments").getAsJsonArray())) .map(jsonElement -> QiscusApiParser.parseQiscusComment(jsonElement, roomId)); } public Observable<QiscusComment> getNextMessagesById(long roomId, int limit) { return api.getComments(roomId, null, true, limit) .flatMap(jsonElement -> Observable.from(jsonElement.getAsJsonObject().get("results") .getAsJsonObject().get("comments").getAsJsonArray())) .map(jsonElement -> QiscusApiParser.parseQiscusComment(jsonElement, roomId)); } @Deprecated public Observable<QiscusComment> postComment(QiscusComment qiscusComment) { QiscusCore.getChatConfig().getCommentSendingInterceptor().sendComment(qiscusComment); return api.postComment(QiscusHashMapUtil.postComment(qiscusComment)) .map(jsonElement -> { JsonObject jsonComment = jsonElement.getAsJsonObject() .get("results").getAsJsonObject().get("comment").getAsJsonObject(); qiscusComment.setId(jsonComment.get("id").getAsLong()); qiscusComment.setCommentBeforeId(jsonComment.get("comment_before_id").getAsInt()); //timestamp is in nano seconds format, convert it to milliseconds by divide it long timestamp = jsonComment.get("unix_nano_timestamp").getAsLong() / 1000000L; qiscusComment.setTime(new Date(timestamp)); QiscusLogger.print("Sent Comment..."); return qiscusComment; }) .doOnNext(comment -> EventBus.getDefault().post(new QiscusCommentSentEvent(comment))); } public Observable<QiscusComment> sendMessage(QiscusComment message) { QiscusCore.getChatConfig().getCommentSendingInterceptor().sendComment(message); return api.postComment(QiscusHashMapUtil.postComment(message)) .map(jsonElement -> { JsonObject jsonComment = jsonElement.getAsJsonObject() .get("results").getAsJsonObject().get("comment").getAsJsonObject(); message.setId(jsonComment.get("id").getAsLong()); message.setCommentBeforeId(jsonComment.get("comment_before_id").getAsInt()); //timestamp is in nano seconds format, convert it to milliseconds by divide it long timestamp = jsonComment.get("unix_nano_timestamp").getAsLong() / 1000000L; message.setTime(new Date(timestamp)); QiscusLogger.print("Sent Comment..."); return message; }) .doOnNext(comment -> EventBus.getDefault().post(new QiscusCommentSentEvent(comment))); } public Observable<QiscusComment> sendFileMessage(QiscusComment message, File file, ProgressListener progressUploadListener) { return Observable.create(subscriber -> { long fileLength = file.length(); RequestBody requestBody = new MultipartBody.Builder() .setType(MultipartBody.FORM) .addFormDataPart("file", file.getName(), new CountingFileRequestBody(file, totalBytes -> { int progress = (int) (totalBytes * 100 / fileLength); progressUploadListener.onProgress(progress); })) .build(); Request request = new Request.Builder() .url(baseUrl + "api/v2/mobile/upload") .post(requestBody).build(); try { Response response = httpClient.newCall(request).execute(); JSONObject responseJ = new JSONObject(response.body().string()); String result = responseJ.getJSONObject("results").getJSONObject("file").getString("url"); message.updateAttachmentUrl(Uri.parse(result).toString()); QiscusCore.getDataStore().addOrUpdate(message); QiscusApi.getInstance().sendMessage(message) .doOnSubscribe(() -> QiscusCore.getDataStore().addOrUpdate(message)) .doOnError(throwable -> { subscriber.onError(throwable); }) .subscribeOn(Schedulers.io()) .observeOn(AndroidSchedulers.mainThread()) .subscribe(commentSend -> { subscriber.onNext(commentSend); subscriber.onCompleted(); }, throwable -> { QiscusErrorLogger.print(throwable); throwable.printStackTrace(); subscriber.onError(throwable); }); } catch (IOException | JSONException e) { QiscusErrorLogger.print("UploadFile", e); subscriber.onError(e); } }, Emitter.BackpressureMode.BUFFER); } @Deprecated public Observable<QiscusComment> sync(long lastCommentId) { return api.sync(lastCommentId) .onErrorReturn(throwable -> { QiscusErrorLogger.print("Sync", throwable); return null; }) .filter(jsonElement -> jsonElement != null) .flatMap(jsonElement -> Observable.from(jsonElement.getAsJsonObject().get("results") .getAsJsonObject().get("comments").getAsJsonArray())) .map(jsonElement -> { JsonObject jsonComment = jsonElement.getAsJsonObject(); return QiscusApiParser.parseQiscusComment(jsonElement, jsonComment.get("room_id").getAsLong()); }); } public Observable<QiscusComment> synchronize(long lastMessageId) { return api.sync(lastMessageId) .onErrorReturn(throwable -> { QiscusErrorLogger.print("Sync", throwable); return null; }) .filter(jsonElement -> jsonElement != null) .flatMap(jsonElement -> Observable.from(jsonElement.getAsJsonObject().get("results") .getAsJsonObject().get("comments").getAsJsonArray())) .map(jsonElement -> { JsonObject jsonComment = jsonElement.getAsJsonObject(); return QiscusApiParser.parseQiscusComment(jsonElement, jsonComment.get("room_id").getAsLong()); }); } public Observable<QiscusComment> sync() { QiscusComment latestComment = QiscusCore.getDataStore().getLatestComment(); if (latestComment == null || !QiscusTextUtil.getString(R.string.qiscus_today) .equals(QiscusDateUtil.toTodayOrDate(latestComment.getTime()))) { return Observable.empty(); } return synchronize(latestComment.getId()); } @Deprecated public Observable<Uri> uploadFile(File file, ProgressListener progressListener) { return Observable.create(subscriber -> { long fileLength = file.length(); RequestBody requestBody = new MultipartBody.Builder() .setType(MultipartBody.FORM) .addFormDataPart("file", file.getName(), new CountingFileRequestBody(file, totalBytes -> { int progress = (int) (totalBytes * 100 / fileLength); progressListener.onProgress(progress); })) .build(); Request request = new Request.Builder() .url(baseUrl + "api/v2/mobile/upload") .post(requestBody).build(); try { Response response = httpClient.newCall(request).execute(); JSONObject responseJ = new JSONObject(response.body().string()); String result = responseJ.getJSONObject("results").getJSONObject("file").getString("url"); subscriber.onNext(Uri.parse(result)); subscriber.onCompleted(); } catch (IOException | JSONException e) { QiscusErrorLogger.print("UploadFile", e); subscriber.onError(e); } }, Emitter.BackpressureMode.BUFFER); } public Observable<Uri> upload(File file, ProgressListener progressListener) { return Observable.create(subscriber -> { long fileLength = file.length(); RequestBody requestBody = new MultipartBody.Builder() .setType(MultipartBody.FORM) .addFormDataPart("file", file.getName(), new CountingFileRequestBody(file, totalBytes -> { int progress = (int) (totalBytes * 100 / fileLength); progressListener.onProgress(progress); })) .build(); Request request = new Request.Builder() .url(baseUrl + "api/v2/mobile/upload") .post(requestBody).build(); try { Response response = httpClient.newCall(request).execute(); JSONObject responseJ = new JSONObject(response.body().string()); String result = responseJ.getJSONObject("results").getJSONObject("file").getString("url"); subscriber.onNext(Uri.parse(result)); subscriber.onCompleted(); } catch (IOException | JSONException e) { QiscusErrorLogger.print("UploadFile", e); subscriber.onError(e); } }, Emitter.BackpressureMode.BUFFER); } public Observable<File> downloadFile(String url, String fileName, ProgressListener progressListener) { return Observable.create(subscriber -> { InputStream inputStream = null; FileOutputStream fos = null; try { Request request = new Request.Builder().url(url).build(); Response response = httpClient.newCall(request).execute(); File output = new File(QiscusFileUtil.generateFilePath(fileName)); fos = new FileOutputStream(output.getPath()); if (!response.isSuccessful()) { throw new IOException(); } else { ResponseBody responseBody = response.body(); long fileLength = responseBody.contentLength(); inputStream = responseBody.byteStream(); byte[] buffer = new byte[4096]; long total = 0; int count; while ((count = inputStream.read(buffer)) != -1) { total += count; long totalCurrent = total; if (fileLength > 0) { progressListener.onProgress((totalCurrent * 100 / fileLength)); } fos.write(buffer, 0, count); } fos.flush(); subscriber.onNext(output); subscriber.onCompleted(); } } catch (Exception e) { throw OnErrorThrowable.from(OnErrorThrowable.addValueAsLastCause(e, url)); } finally { try { if (fos != null) { fos.close(); } if (inputStream != null) { inputStream.close(); } } catch (IOException ignored) { //Do nothing } } }, Emitter.BackpressureMode.BUFFER); } public Observable<QiscusChatRoom> updateChatRoom(long roomId, String name, String avatarURL, JSONObject extras) { return api.updateChatRoom(QiscusHashMapUtil.updateChatRoom( String.valueOf(roomId), name, avatarURL, extras == null ? null : extras.toString())) .map(QiscusApiParser::parseQiscusChatRoom) .doOnNext(qiscusChatRoom -> QiscusCore.getDataStore().addOrUpdate(qiscusChatRoom)); } public Observable<Void> updateCommentStatus(long roomId, long lastReadId, long lastReceivedId) { return api.updateCommentStatus(QiscusHashMapUtil.updateCommentStatus( String.valueOf(roomId), String.valueOf(lastReadId), String.valueOf(lastReceivedId))) .map(jsonElement -> null); } @Deprecated public Observable<Void> registerFcmToken(String fcmToken) { return api.registerFcmToken(QiscusHashMapUtil.registerOrRemoveFcmToken(fcmToken)) .map(jsonElement -> null); } public Observable<Void> registerDeviceToken(String token) { return api.registerFcmToken(QiscusHashMapUtil.registerOrRemoveFcmToken(token)) .map(jsonElement -> null); } public Observable<Void> removeDeviceToken(String token) { return api.removeDeviceToken(QiscusHashMapUtil.registerOrRemoveFcmToken(token)) .map(jsonElement -> null); } @Deprecated public Observable<Void> clearCommentsByRoomIds(List<Long> roomIds) { List<String> listOfRoomIds = new ArrayList<>(); for (Long roomId : roomIds) { listOfRoomIds.add(String.valueOf(roomId)); } return api.getChatRooms(QiscusHashMapUtil.getChatRooms( listOfRoomIds, null, false, false)) .map(JsonElement::getAsJsonObject) .map(jsonObject -> jsonObject.get("results").getAsJsonObject()) .map(jsonObject -> jsonObject.get("rooms_info").getAsJsonArray()) .flatMap(Observable::from) .map(JsonElement::getAsJsonObject) .map(jsonObject -> jsonObject.get("unique_id").getAsString()) .toList() .flatMap(this::clearCommentsByRoomUniqueIds); } @Deprecated public Observable<Void> clearCommentsByRoomUniqueIds(List<String> roomUniqueIds) { return api.clearChatRoomMessages(roomUniqueIds) .map(JsonElement::getAsJsonObject) .map(jsonResponse -> jsonResponse.get("results").getAsJsonObject()) .map(jsonResults -> jsonResults.get("rooms").getAsJsonArray()) .flatMap(Observable::from) .map(JsonElement::getAsJsonObject) .doOnNext(json -> { long roomId = json.get("id").getAsLong(); if (QiscusCore.getDataStore().deleteCommentsByRoomId(roomId)) { EventBus.getDefault().post(new QiscusClearCommentsEvent(roomId)); } }) .toList() .map(qiscusChatRooms -> null); } public Observable<Void> clearMessagesByChatRoomIds(List<Long> roomIds) { List<String> listOfRoomIds = new ArrayList<>(); for (Long roomId : roomIds) { listOfRoomIds.add(String.valueOf(roomId)); } return api.getChatRooms(QiscusHashMapUtil.getChatRooms( listOfRoomIds, null, false, false)) .map(JsonElement::getAsJsonObject) .map(jsonObject -> jsonObject.get("results").getAsJsonObject()) .map(jsonObject -> jsonObject.get("rooms_info").getAsJsonArray()) .flatMap(Observable::from) .map(JsonElement::getAsJsonObject) .map(jsonObject -> jsonObject.get("unique_id").getAsString()) .toList() .flatMap(this::clearMessagesByChatRoomUniqueIds); } public Observable<Void> clearMessagesByChatRoomUniqueIds(List<String> roomUniqueIds) { return api.clearChatRoomMessages(roomUniqueIds) .map(JsonElement::getAsJsonObject) .map(jsonResponse -> jsonResponse.get("results").getAsJsonObject()) .map(jsonResults -> jsonResults.get("rooms").getAsJsonArray()) .flatMap(Observable::from) .map(JsonElement::getAsJsonObject) .doOnNext(json -> { long roomId = json.get("id").getAsLong(); if (QiscusCore.getDataStore().deleteCommentsByRoomId(roomId)) { EventBus.getDefault().post(new QiscusClearCommentsEvent(roomId)); } }) .toList() .map(qiscusChatRooms -> null); } @Deprecated public Observable<List<QiscusComment>> deleteComments(List<String> commentUniqueIds, boolean isHardDelete) { // isDeleteForEveryone => akan selalu true, karena deleteForMe deprecated return api.deleteComments(commentUniqueIds, true, isHardDelete) .flatMap(jsonElement -> Observable.from(jsonElement.getAsJsonObject().get("results") .getAsJsonObject().get("comments").getAsJsonArray())) .map(jsonElement -> { JsonObject jsonComment = jsonElement.getAsJsonObject(); return QiscusApiParser.parseQiscusComment(jsonElement, jsonComment.get("room_id").getAsLong()); }) .toList() .doOnNext(comments -> { QiscusAccount account = QiscusCore.getQiscusAccount(); QiscusRoomMember actor = new QiscusRoomMember(); actor.setEmail(account.getEmail()); actor.setUsername(account.getUsername()); actor.setAvatar(account.getAvatar()); List<QiscusDeleteCommentHandler.DeletedCommentsData.DeletedComment> deletedComments = new ArrayList<>(); for (QiscusComment comment : comments) { deletedComments.add(new QiscusDeleteCommentHandler.DeletedCommentsData.DeletedComment(comment.getRoomId(), comment.getUniqueId())); } QiscusDeleteCommentHandler.DeletedCommentsData deletedCommentsData = new QiscusDeleteCommentHandler.DeletedCommentsData(); deletedCommentsData.setActor(actor); deletedCommentsData.setHardDelete(isHardDelete); deletedCommentsData.setDeletedComments(deletedComments); QiscusDeleteCommentHandler.handle(deletedCommentsData); }); } public Observable<List<QiscusComment>> deleteMessages(List<String> messageUniqueIds) { return api.deleteComments(messageUniqueIds, true, true) .flatMap(jsonElement -> Observable.from(jsonElement.getAsJsonObject().get("results") .getAsJsonObject().get("comments").getAsJsonArray())) .map(jsonElement -> { JsonObject jsonComment = jsonElement.getAsJsonObject(); return QiscusApiParser.parseQiscusComment(jsonElement, jsonComment.get("room_id").getAsLong()); }) .toList() .doOnNext(comments -> { QiscusAccount account = QiscusCore.getQiscusAccount(); QiscusRoomMember actor = new QiscusRoomMember(); actor.setEmail(account.getEmail()); actor.setUsername(account.getUsername()); actor.setAvatar(account.getAvatar()); List<QiscusDeleteCommentHandler.DeletedCommentsData.DeletedComment> deletedComments = new ArrayList<>(); for (QiscusComment comment : comments) { deletedComments.add(new QiscusDeleteCommentHandler.DeletedCommentsData.DeletedComment(comment.getRoomId(), comment.getUniqueId())); } QiscusDeleteCommentHandler.DeletedCommentsData deletedCommentsData = new QiscusDeleteCommentHandler.DeletedCommentsData(); deletedCommentsData.setActor(actor); deletedCommentsData.setHardDelete(true); deletedCommentsData.setDeletedComments(deletedComments); QiscusDeleteCommentHandler.handle(deletedCommentsData); }); } @Deprecated public Observable<List<JSONObject>> getEvents(long startEventId) { return api.getEvents(startEventId) .flatMap(jsonElement -> Observable.from(jsonElement.getAsJsonObject().get("events").getAsJsonArray())) .map(jsonEvent -> { try { return new JSONObject(jsonEvent.toString()); } catch (JSONException e) { return null; } }) .filter(jsonObject -> jsonObject != null) .doOnNext(QiscusPusherApi::handleNotification) .toList(); } public Observable<List<JSONObject>> synchronizeEvent(long lastEventId) { return api.getEvents(lastEventId) .flatMap(jsonElement -> Observable.from(jsonElement.getAsJsonObject().get("events").getAsJsonArray())) .map(jsonEvent -> { try { return new JSONObject(jsonEvent.toString()); } catch (JSONException e) { return null; } }) .filter(jsonObject -> jsonObject != null) .doOnNext(QiscusPusherApi::handleNotification) .toList(); } public Observable<Long> getTotalUnreadCount() { return api.getTotalUnreadCount() .map(JsonElement::getAsJsonObject) .map(jsonResponse -> jsonResponse.get("results").getAsJsonObject()) .map(jsonResults -> jsonResults.get("total_unread_count").getAsLong()); } @Deprecated public Observable<QiscusChatRoom> addRoomMember(long roomId, List<String> emails) { return api.addRoomMember(QiscusHashMapUtil.addRoomMember(String.valueOf(roomId), emails)) .flatMap(jsonElement -> getChatRoomInfo(roomId)); } public Observable<QiscusChatRoom> addParticipants(long roomId, List<String> userIds) { return api.addRoomMember(QiscusHashMapUtil.addRoomMember(String.valueOf(roomId), userIds)) .flatMap(jsonElement -> getChatRoomInfo(roomId)); } @Deprecated public Observable<QiscusChatRoom> removeRoomMember(long roomId, List<String> userIds) { return api.removeRoomMember(QiscusHashMapUtil.removeRoomMember(String.valueOf(roomId), userIds)) .flatMap(jsonElement -> getChatRoomInfo(roomId)); } public Observable<QiscusChatRoom> removeParticipants(long roomId, List<String> userIds) { return api.removeRoomMember(QiscusHashMapUtil.removeRoomMember(String.valueOf(roomId), userIds)) .flatMap(jsonElement -> getChatRoomInfo(roomId)); } public Observable<QiscusAccount> blockUser(String userId) { return api.blockUser(QiscusHashMapUtil.blockUser(userId)) .map(JsonElement::getAsJsonObject) .map(jsonResponse -> jsonResponse.getAsJsonObject("results")) .map(jsonResults -> jsonResults.getAsJsonObject("user")) .map(jsonAccount -> { try { return QiscusApiParser.parseQiscusAccount( new JSONObject(jsonAccount.toString()), false); } catch (JSONException e) { e.printStackTrace(); } return null; }); } public Observable<QiscusAccount> unblockUser(String userId) { return api.unblockUser(QiscusHashMapUtil.unblockUser(userId)) .map(JsonElement::getAsJsonObject) .map(jsonResponse -> jsonResponse.getAsJsonObject("results")) .map(jsonResults -> jsonResults.getAsJsonObject("user")) .map(jsonAccount -> { try { return QiscusApiParser.parseQiscusAccount( new JSONObject(jsonAccount.toString()), false); } catch (JSONException e) { e.printStackTrace(); } return null; }); } public Observable<List<QiscusAccount>> getBlockedUsers() { return getBlockedUsers(0, 100); } public Observable<List<QiscusAccount>> getBlockedUsers(long page, long limit) { return api.getBlockedUsers(page, limit) .map(JsonElement::getAsJsonObject) .map(jsonResponse -> jsonResponse.getAsJsonObject("results")) .map(jsonResults -> jsonResults.getAsJsonArray("blocked_users")) .flatMap(Observable::from) .map(JsonElement::getAsJsonObject) .map(jsonAccount -> { try { return QiscusApiParser.parseQiscusAccount( new JSONObject(jsonAccount.toString()), false); } catch (JSONException e) { e.printStackTrace(); } return null; }) .toList(); } @Deprecated public Observable<List<QiscusRoomMember>> getRoomMembers(String roomUniqueId, int offset, MetaRoomMembersListener metaRoomMembersListener) { return getRoomMembers(roomUniqueId, offset, null, metaRoomMembersListener); } @Deprecated public Observable<List<QiscusRoomMember>> getRoomMembers(String roomUniqueId, int offset, String sorting, MetaRoomMembersListener metaRoomMembersListener) { return api.getRoomParticipants(roomUniqueId, 0, 0, offset, sorting) .map(JsonElement::getAsJsonObject) .map(jsonResponse -> jsonResponse.getAsJsonObject("results")) .doOnNext(jsonResults -> { JsonObject meta = jsonResults.getAsJsonObject("meta"); if (metaRoomMembersListener != null) { metaRoomMembersListener.onMetaReceived( meta.get("current_offset").getAsInt(), meta.get("per_page").getAsInt(), meta.get("total").getAsInt() ); } }) .map(jsonResults -> jsonResults.getAsJsonArray("participants")) .flatMap(Observable::from) .map(JsonElement::getAsJsonObject) .map(QiscusApiParser::parseQiscusRoomMember) .toList(); } public Observable<List<QiscusRoomMember>> getParticipants(String roomUniqueId, int page, int limit, String sorting, MetaRoomParticipantsListener metaRoomParticipantListener) { return api.getRoomParticipants(roomUniqueId, page, limit, 0, sorting) .map(JsonElement::getAsJsonObject) .map(jsonResponse -> jsonResponse.getAsJsonObject("results")) .doOnNext(jsonResults -> { JsonObject meta = jsonResults.getAsJsonObject("meta"); if (metaRoomParticipantListener != null) { metaRoomParticipantListener.onMetaReceived( meta.get("current_page").getAsInt(), meta.get("per_page").getAsInt(), meta.get("total").getAsInt() ); } }) .map(jsonResults -> jsonResults.getAsJsonArray("participants")) .flatMap(Observable::from) .map(JsonElement::getAsJsonObject) .map(QiscusApiParser::parseQiscusRoomMember) .toList(); } public Observable<List<QiscusRoomMember>> getParticipants(String roomUniqueId, int page, int limit, String sorting) { return api.getRoomParticipants(roomUniqueId, page, limit, 0, sorting) .map(JsonElement::getAsJsonObject) .map(jsonResponse -> jsonResponse.getAsJsonObject("results")) .doOnNext(jsonResults -> { }) .map(jsonResults -> jsonResults.getAsJsonArray("participants")) .flatMap(Observable::from) .map(JsonElement::getAsJsonObject) .map(QiscusApiParser::parseQiscusRoomMember) .toList(); } public Observable<String> getMqttBaseUrl() { return Observable.create(subscriber -> { OkHttpClient httpClientLB; if (Build.VERSION.SDK_INT <= 19) { ConnectionSpec spec = new ConnectionSpec.Builder(ConnectionSpec.COMPATIBLE_TLS) .supportsTlsExtensions(true) .allEnabledTlsVersions() .allEnabledCipherSuites() .build(); httpClientLB = new OkHttpClient.Builder() .connectTimeout(60, TimeUnit.SECONDS) .readTimeout(60, TimeUnit.SECONDS) .addInterceptor(this::headersInterceptor) .addInterceptor(makeLoggingInterceptor(QiscusCore.getChatConfig().isEnableLog())) .connectionSpecs(Collections.singletonList(spec)) .build(); } else { httpClientLB = new OkHttpClient.Builder() .connectTimeout(60, TimeUnit.SECONDS) .readTimeout(60, TimeUnit.SECONDS) .addInterceptor(this::headersInterceptor) .addInterceptor(makeLoggingInterceptor(QiscusCore.getChatConfig().isEnableLog())) .build(); } String url = QiscusCore.getBaseURLLB(); Request okHttpRequest = new Request.Builder().url(url).build(); try { Response response = httpClientLB.newCall(okHttpRequest).execute(); JSONObject jsonResponse = new JSONObject(response.body().string()); String node = jsonResponse.getString("node"); subscriber.onNext(node); subscriber.onCompleted(); } catch (IOException | JSONException e) { e.printStackTrace(); } }, Emitter.BackpressureMode.BUFFER); } public Observable<List<QiscusAccount>> getUsers(String searchUsername) { return getUsers(searchUsername, 0, 100); } @Deprecated public Observable<List<QiscusAccount>> getUsers(long page, long limit, String query) { return api.getUserList(page, limit, "username asc", query) .map(JsonElement::getAsJsonObject) .map(jsonResponse -> jsonResponse.getAsJsonObject("results")) .map(jsonResults -> jsonResults.getAsJsonArray("users")) .flatMap(Observable::from) .map(JsonElement::getAsJsonObject) .map(jsonAccount -> { try { return QiscusApiParser.parseQiscusAccount( new JSONObject(jsonAccount.toString()), false); } catch (JSONException e) { e.printStackTrace(); } return null; }) .toList(); } public Observable<List<QiscusAccount>> getUsers(String searchUsername, long page, long limit) { return api.getUserList(page, limit, "username asc", searchUsername) .map(JsonElement::getAsJsonObject) .map(jsonResponse -> jsonResponse.getAsJsonObject("results")) .map(jsonResults -> jsonResults.getAsJsonArray("users")) .flatMap(Observable::from) .map(JsonElement::getAsJsonObject) .map(jsonAccount -> { try { return QiscusApiParser.parseQiscusAccount( new JSONObject(jsonAccount.toString()), false); } catch (JSONException e) { e.printStackTrace(); } return null; }) .toList(); } public Observable<Void> eventReport(String moduleName, String event, String message) { return api.eventReport(QiscusHashMapUtil.eventReport(moduleName, event, message)) .map(jsonElement -> null); } public Observable<QiscusAppConfig> getAppConfig() { return api.getAppConfig() .map(QiscusApiParser::parseQiscusAppConfig); } public Observable<QiscusRealtimeStatus> getRealtimeStatus(String topic) { return api.getRealtimeStatus(QiscusHashMapUtil.getRealtimeStatus(topic)) .map(QiscusApiParser::parseQiscusRealtimeStatus); } public Observable<List<QiscusChannels>> getChannels() { return api.getChannels() .map(QiscusApiParser::parseQiscusChannels); } public Observable<List<QiscusChannels>> getChannelsInfo(List<String> uniqueIds) { return api.getChannelsInfo(QiscusHashMapUtil.getChannelsInfo(uniqueIds)) .map(QiscusApiParser::parseQiscusChannels); } public Observable<List<QiscusChannels>> joinChannels(List<String> uniqueIds) { return api.joinChannels(QiscusHashMapUtil.joinChannels(uniqueIds)) .map(QiscusApiParser::parseQiscusChannels); } public Observable<List<QiscusChannels>> leaveChannels(List<String> uniqueIds) { return api.leaveChannels(QiscusHashMapUtil.leaveChannels(uniqueIds)) .map(QiscusApiParser::parseQiscusChannels); } private Observable<List<QUserPresence>> getUserPresence(List<String> userIds) { return api.usersPresence(QiscusHashMapUtil.usersPresence(userIds)) .map(QiscusApiParser::parseQiscusUserPresence); } private interface Api { @Headers("Content-Type: application/json") @POST("api/v2/mobile/event_report") Observable<JsonElement> eventReport( @Body HashMap<String, Object> data ); @Headers("Content-Type: application/json") @POST("api/v2/mobile/auth/nonce") Observable<JsonElement> requestNonce(); @Headers("Content-Type: application/json") @POST("api/v2/mobile/auth/verify_identity_token") Observable<JsonElement> login( @Body HashMap<String, Object> data ); @Headers("Content-Type: application/json") @POST("api/v2/mobile/login_or_register") Observable<JsonElement> loginOrRegister( @Body HashMap<String, Object> data ); @Headers("Content-Type: application/json") @PATCH("api/v2/mobile/my_profile") Observable<JsonElement> updateProfile( @Body HashMap<String, Object> data ); @GET("api/v2/mobile/my_profile") Observable<JsonElement> getUserData( ); @Headers("Content-Type: application/json") @POST("api/v2/mobile/get_or_create_room_with_target") Observable<JsonElement> createOrGetChatRoom( @Body HashMap<String, Object> data ); @Headers("Content-Type: application/json") @POST("api/v2/mobile/create_room") Observable<JsonElement> createGroupChatRoom( @Body HashMap<String, Object> data ); @Headers("Content-Type: application/json") @POST("api/v2/mobile/get_or_create_room_with_unique_id") Observable<JsonElement> createOrGetGroupChatRoom( @Body HashMap<String, Object> data ); @GET("api/v2/mobile/get_room_by_id") Observable<JsonElement> getChatRoom( @Query("id") long roomId ); @GET("api/v2/mobile/load_comments") Observable<JsonElement> getComments( @Query("topic_id") long roomId, @Query("last_comment_id") Long lastCommentId, @Query("after") boolean after, @Query("limit") int limit ); @Headers("Content-Type: application/json") @POST("api/v2/mobile/post_comment") Observable<JsonElement> postComment( @Body HashMap<String, Object> data ); @GET("api/v2/mobile/sync") Observable<JsonElement> sync( @Query("last_received_comment_id") long lastCommentId ); @Headers("Content-Type: application/json") @POST("api/v2/mobile/update_room") Observable<JsonElement> updateChatRoom( @Body HashMap<String, Object> data ); @Headers("Content-Type: application/json") @POST("api/v2/mobile/update_comment_status") Observable<JsonElement> updateCommentStatus( @Body HashMap<String, Object> data ); @Headers("Content-Type: application/json") @POST("api/v2/mobile/set_user_device_token") Observable<JsonElement> registerFcmToken( @Body HashMap<String, Object> data ); @Headers("Content-Type: application/json") @POST("api/v2/mobile/remove_user_device_token") Observable<JsonElement> removeDeviceToken( @Body HashMap<String, Object> data ); @GET("api/v2/mobile/user_rooms") Observable<JsonElement> getChatRooms( @Query("page") int page, @Query("limit") int limit, @Query("show_participants") boolean showParticipants, @Query("show_empty") boolean showEmpty, @Query("show_removed") boolean showRemoved ); @Headers("Content-Type: application/json") @POST("api/v2/mobile/rooms_info") Observable<JsonElement> getChatRooms( @Body HashMap<String, Object> data ); @DELETE("api/v2/mobile/clear_room_messages") Observable<JsonElement> clearChatRoomMessages( @Query("room_channel_ids[]") List<String> roomUniqueIds ); @DELETE("api/v2/mobile/delete_messages") Observable<JsonElement> deleteComments( @Query("unique_ids[]") List<String> commentUniqueIds, @Query("is_delete_for_everyone") boolean isDeleteForEveryone, @Query("is_hard_delete") boolean isHardDelete ); @GET("api/v2/mobile/sync_event") Observable<JsonElement> getEvents( @Query("start_event_id") long startEventId ); @GET("api/v2/mobile/total_unread_count") Observable<JsonElement> getTotalUnreadCount(); @Headers("Content-Type: application/json") @POST("api/v2/mobile/add_room_participants") Observable<JsonElement> addRoomMember( @Body HashMap<String, Object> data ); @Headers("Content-Type: application/json") @POST("api/v2/mobile/remove_room_participants") Observable<JsonElement> removeRoomMember( @Body HashMap<String, Object> data ); @Headers("Content-Type: application/json") @POST("/api/v2/mobile/block_user") Observable<JsonElement> blockUser( @Body HashMap<String, Object> data ); @Headers("Content-Type: application/json") @POST("/api/v2/mobile/unblock_user") Observable<JsonElement> unblockUser( @Body HashMap<String, Object> data ); @GET("/api/v2/mobile/get_blocked_users") Observable<JsonElement> getBlockedUsers( @Query("page") long page, @Query("limit") long limit ); @GET("/api/v2/mobile/room_participants") Observable<JsonElement> getRoomParticipants( @Query("room_unique_id") String roomUniqId, @Query("page") int page, @Query("limit") int limit, @Query("offset") int offset, @Query("sorting") String sorting ); @GET("/api/v2/mobile/get_user_list") Observable<JsonElement> getUserList( @Query("page") long page, @Query("limit") long limit, @Query("order_query") String orderQuery, @Query("query") String query ); @GET("api/v2/mobile/config") Observable<JsonElement> getAppConfig(); @Headers("Content-Type: application/json") @POST("api/v2/mobile/realtime") Observable<JsonElement> getRealtimeStatus( @Body HashMap<String, Object> data ); @GET("api/v2/mobile/channels") Observable<JsonElement> getChannels(); @Headers("Content-Type: application/json") @POST("api/v2/mobile/channels/info") Observable<JsonElement> getChannelsInfo( @Body HashMap<String, Object> data ); @Headers("Content-Type: application/json") @POST("api/v2/mobile/channels/join") Observable<JsonElement> joinChannels( @Body HashMap<String, Object> data ); @Headers("Content-Type: application/json") @POST("api/v2/mobile/channels/leave") Observable<JsonElement> leaveChannels( @Body HashMap<String, Object> data ); @Headers("Content-Type: application/json") @POST("api/v2/mobile/users/status") Observable<JsonElement> usersPresence( @Body HashMap<String, Object> data ); } public interface MetaRoomMembersListener { void onMetaReceived(int currentOffset, int perPage, int total); } public interface MetaRoomParticipantsListener { void onMetaReceived(int currentPage, int perPage, int total); } public interface ProgressListener { void onProgress(long total); } private static class CountingFileRequestBody extends RequestBody { private static final int SEGMENT_SIZE = 2048; private static final int IGNORE_FIRST_NUMBER_OF_WRITE_TO_CALL = 0; private final File file; private final ProgressListener progressListener; private int numWriteToCall = -1; private CountingFileRequestBody(File file, ProgressListener progressListener) { this.file = file; this.progressListener = progressListener; } @Override public MediaType contentType() { return MediaType.parse("application/octet-stream"); } @Override public long contentLength() throws IOException { return file.length(); } @Override public void writeTo(@NonNull BufferedSink sink) throws IOException { numWriteToCall++; Source source = null; try { source = Okio.source(file); long total = 0; long read; while ((read = source.read(sink.buffer(), SEGMENT_SIZE)) != -1) { total += read; sink.flush(); /** * When we use HttpLoggingInterceptor, * we have issue with progress update not valid. * So we must check, first call is to HttpLoggingInterceptor * second call is to request */ if (numWriteToCall > IGNORE_FIRST_NUMBER_OF_WRITE_TO_CALL) { progressListener.onProgress(total); } } } finally { Util.closeQuietly(source); } } } }
set to public for api getUserPresence
chat-core/src/main/java/com/qiscus/sdk/chat/core/data/remote/QiscusApi.java
set to public for api getUserPresence
<ide><path>hat-core/src/main/java/com/qiscus/sdk/chat/core/data/remote/QiscusApi.java <ide> .map(QiscusApiParser::parseQiscusChannels); <ide> } <ide> <del> private Observable<List<QUserPresence>> getUserPresence(List<String> userIds) { <add> public Observable<List<QUserPresence>> getUserPresence(List<String> userIds) { <ide> return api.usersPresence(QiscusHashMapUtil.usersPresence(userIds)) <ide> .map(QiscusApiParser::parseQiscusUserPresence); <ide> }
JavaScript
mit
56a9aa7642659187a822b598eeac9d45111d54e6
0
joseluisq/jquery.xrequest,joseluisq/jquery.xrequest,joseluisq/jquery.xrequest
/* * jQuery xRequest Plugin v1.0.3 * Release: 07/07/2014 * Author: Jose Luis Quintana <[email protected]> * https://github.com/joseluisq/jquery.xrequest * Released under MIT Licence: http://www.opensource.org/licenses/mit-license.php */ (function () { window.xRequest = function (element, list) { this.isform = false; this.sending = false; this.options = { url: './', type: 'post', dataType: 'json', csrf: true, processForm: true, data: null, onStart: function () { }, onSuccess: function (data, textStatus, jqXHR) { }, onError: function (jqXHR, textStatus, errorThrown) { } }; this.initialize = function (element, options) { this.csrf = $('meta[name="csrf-token"]'); this.csrf = this.csrf.length > 0 ? this.csrf : null; if (element instanceof $) { this.setForm(element); } else { options = element; } this.setOptions(options); }; this.send = function () { var s = this, data = this.encodeObjects(), key, opt = this.options; this.sending = true; opt.onStart.apply(s, []); if (opt.data && typeof (data) === 'object') { for (key in opt.data) { opt.data[key] = data[key]; } } data['r'] = new Date().getTime(); opt.data = data; if (opt.csrf) { var s = this; if ('ajaxPrefilter' in $) { $.ajaxPrefilter(function (o, o, xhr) { s.setCSRFHeader(xhr); }); } else { $(document).ajaxSend(function (e, xhr) { s.setCSRFHeader(xhr); }); } } return $.ajax({ type: opt.type, url: opt.url, data: data, cache: false, dataType: opt.dataType, success: function (data, textStatus, jqXHR) { if (typeof (data) == 'object') { if (data['header'] && data.header['token']) { if (s.csrf) { s.csrf.attr('content', data.header.token); } } } delete s.options.data['r']; s.sending = false; opt.onSuccess.apply(s, [data, textStatus, jqXHR]); }, complete: opt.onComplete, error: opt.onError }); }; this.setOptions = function (options) { this.options = this.merge(this.options, options); this.options.csrf = !!this.csrf; }; this.merge = function (a, b) { for (var i in b) { a[i] = b[i]; } return a; }; this.setData = function () { if (arguments.length > 0) { var data = this.options.data || {}; switch (arguments.length) { case 1: this.options.data = this.merge(data, arguments[0]); break; case 2: data[arguments[0]] = arguments[1]; this.options.data = data; break; } } }; this.isSending = function () { return this.sending; }; this.setOption = function (opt, val) { this.options[opt] = val; }; this.getOption = function (opt) { return this.options[opt]; }; this.unsetDataBy = function (key) { delete this.options.data[key]; }; this.removeDataElement = function (key) { this.unsetDataBy(key); }; this.clearData = function () { this.options.data = null; }; this.isForm = function () { return this.isform = this.element ? (this.element.prop('tagName').toString().toLowerCase() === 'form') : false; }; this.setForm = function (element) { this.element = element; this.isForm(); }; this.encodeObjects = function () { var data = {}, name; if (this.isform && this.options.processForm) { $('input,select,textarea,.xcombobox', this.element).each(function () { if ($(this).hasClass('xcombobox')) { name = $.trim($(this).attr('id')); data[name] = $.trim($(this).xcombobox('getValue')); } else { name = $.trim($(this).attr('name')); data[name] = $.trim($(this).val()); } }); } return data; }; this.setCSRFHeader = function (xhr) { if (this.csrf) { var token = this.csrf.attr('content'); if (token) { xhr.setRequestHeader('X-CSRF-Token', token); } } }; this.initialize(element, list); }; })();
jquery.xrequest.js
/* jQuery xRequest Plugin v1.0.2 Release: 07/07/2014 Author: Jose Luis Quintana <[email protected]> https://github.com/joseluisq/jquery.xrequest Released under MIT Licence: http://www.opensource.org/licenses/mit-license.php */ (function() { window.xRequest = function(element, list) { this.isform = false; this.sending = false; this.options = { url: './', type: 'post', dataType: 'json', csrf: true, processForm: true, data: null, onStart: function() { }, onSuccess: function(data, textStatus, jqXHR) { }, onError: function(jqXHR, textStatus, errorThrown) { } }; this.initialize = function(element, options) { this.element = element; this.csrf = $('meta[name="csrf-token"]'); this.csrf = this.csrf.length > 0 ? this.csrf : null; if (this.element instanceof $) { this.isForm(); } else { options = element; } this.setOptions(options); }; this.send = function() { var s = this, data = this.encodeObjects(), key, opt = this.options; this.sending = true; opt.onStart.apply(s, []); if (opt.data && typeof (data) === 'object') { for (key in opt.data) { opt.data[key] = data[key]; } } data['r'] = new Date().getTime(); opt.data = data; if (opt.csrf) { var s = this; if ('ajaxPrefilter' in $) { $.ajaxPrefilter(function(o, o, xhr) { s.setCSRFHeader(xhr); }); } else { $(document).ajaxSend(function(e, xhr) { s.setCSRFHeader(xhr); }); } } return $.ajax({ type: opt.type, url: opt.url, data: data, cache: false, dataType: opt.dataType, success: function(data, textStatus, jqXHR) { if (typeof (data) == 'object') { if (data['header'] && data.header['token']) { if (s.csrf) { s.csrf.attr('content', data.header.token); } } } delete s.options.data['r']; s.sending = false; opt.onSuccess.apply(s, [data, textStatus, jqXHR]); }, complete: opt.onComplete, error: opt.onError }); }; this.setOptions = function(options) { this.options = this.merge(this.options, options); this.options.csrf = !!this.csrf; }; this.merge = function(a, b) { for (var i in b) { a[i] = b[i]; } return a; }; this.setData = function() { if (arguments.length > 0) { var data = this.options.data || {}; switch (arguments.length) { case 1: this.options.data = this.merge(data, arguments[0]); break; case 2: data[arguments[0]] = arguments[1]; this.options.data = data; break; } } }; this.isSending = function() { return this.sending; }; this.setOption = function(opt, val) { this.options[opt] = val; }; this.getOption = function(opt) { return this.options[opt]; }; this.unsetDataBy = function(key) { delete this.options.data[key]; }; this.removeDataElement = function(key) { this.unsetDataBy(key); }; this.clearData = function() { this.options.data = null; }; this.isForm = function() { return this.isform = this.element ? (this.element.prop('tagName').toString().toLowerCase() === 'form') : false; }; this.setForm = function(element) { this.element = element; this.isForm(); }; this.encodeObjects = function() { var data = {}, name; if (this.isform && this.options.processForm) { $('input,select,textarea,.xcombobox', this.element).each(function() { if ($(this).hasClass('xcombobox')) { name = $.trim($(this).attr('id')); data[name] = $.trim($(this).xcombobox('getValue')); } else { name = $.trim($(this).attr('name')); data[name] = $.trim($(this).val()); } }); } return data; }; this.setCSRFHeader = function(xhr) { if (this.csrf) { var token = this.csrf.attr('content'); if (token) { xhr.setRequestHeader('X-CSRF-Token', token); } } }; this.initialize(element, list); }; })();
Added setForm function in constructor Now it using setForm function to sets the form in constructor
jquery.xrequest.js
Added setForm function in constructor
<ide><path>query.xrequest.js <ide> /* <del> jQuery xRequest Plugin v1.0.2 <del> <del> Release: 07/07/2014 <del> Author: Jose Luis Quintana <[email protected]> <del> <del> https://github.com/joseluisq/jquery.xrequest <del> <del> Released under MIT Licence: http://www.opensource.org/licenses/mit-license.php <add> * jQuery xRequest Plugin v1.0.3 <add> * Release: 07/07/2014 <add> * Author: Jose Luis Quintana <[email protected]> <add> * https://github.com/joseluisq/jquery.xrequest <add> * Released under MIT Licence: http://www.opensource.org/licenses/mit-license.php <ide> */ <ide> <del>(function() { <del> window.xRequest = function(element, list) { <add>(function () { <add> window.xRequest = function (element, list) { <ide> this.isform = false; <ide> this.sending = false; <ide> <ide> csrf: true, <ide> processForm: true, <ide> data: null, <del> onStart: function() { <add> onStart: function () { <ide> }, <del> onSuccess: function(data, textStatus, jqXHR) { <add> onSuccess: function (data, textStatus, jqXHR) { <ide> }, <del> onError: function(jqXHR, textStatus, errorThrown) { <add> onError: function (jqXHR, textStatus, errorThrown) { <ide> } <ide> }; <ide> <del> this.initialize = function(element, options) { <del> this.element = element; <add> this.initialize = function (element, options) { <ide> this.csrf = $('meta[name="csrf-token"]'); <ide> this.csrf = this.csrf.length > 0 ? this.csrf : null; <ide> <del> if (this.element instanceof $) { <del> this.isForm(); <add> if (element instanceof $) { <add> this.setForm(element); <ide> } else { <ide> options = element; <ide> } <ide> this.setOptions(options); <ide> }; <ide> <del> this.send = function() { <add> this.send = function () { <ide> var s = this, data = this.encodeObjects(), key, opt = this.options; <ide> this.sending = true; <ide> opt.onStart.apply(s, []); <ide> var s = this; <ide> <ide> if ('ajaxPrefilter' in $) { <del> $.ajaxPrefilter(function(o, o, xhr) { <add> $.ajaxPrefilter(function (o, o, xhr) { <ide> s.setCSRFHeader(xhr); <ide> }); <ide> } else { <del> $(document).ajaxSend(function(e, xhr) { <add> $(document).ajaxSend(function (e, xhr) { <ide> s.setCSRFHeader(xhr); <ide> }); <ide> } <ide> data: data, <ide> cache: false, <ide> dataType: opt.dataType, <del> success: function(data, textStatus, jqXHR) { <add> success: function (data, textStatus, jqXHR) { <ide> if (typeof (data) == 'object') { <ide> if (data['header'] && data.header['token']) { <ide> if (s.csrf) { <ide> }); <ide> }; <ide> <del> this.setOptions = function(options) { <add> this.setOptions = function (options) { <ide> this.options = this.merge(this.options, options); <ide> this.options.csrf = !!this.csrf; <ide> }; <ide> <del> this.merge = function(a, b) { <add> this.merge = function (a, b) { <ide> for (var i in b) { <ide> a[i] = b[i]; <ide> } <ide> return a; <ide> }; <ide> <del> this.setData = function() { <add> this.setData = function () { <ide> if (arguments.length > 0) { <ide> var data = this.options.data || {}; <ide> <ide> } <ide> }; <ide> <del> this.isSending = function() { <add> this.isSending = function () { <ide> return this.sending; <ide> }; <ide> <del> this.setOption = function(opt, val) { <add> this.setOption = function (opt, val) { <ide> this.options[opt] = val; <ide> }; <ide> <del> this.getOption = function(opt) { <add> this.getOption = function (opt) { <ide> return this.options[opt]; <ide> }; <ide> <del> this.unsetDataBy = function(key) { <add> this.unsetDataBy = function (key) { <ide> delete this.options.data[key]; <ide> }; <ide> <del> this.removeDataElement = function(key) { <add> this.removeDataElement = function (key) { <ide> this.unsetDataBy(key); <ide> }; <ide> <del> this.clearData = function() { <add> this.clearData = function () { <ide> this.options.data = null; <ide> }; <ide> <del> this.isForm = function() { <add> this.isForm = function () { <ide> return this.isform = this.element ? (this.element.prop('tagName').toString().toLowerCase() === 'form') : false; <ide> }; <ide> <del> this.setForm = function(element) { <add> this.setForm = function (element) { <ide> this.element = element; <ide> this.isForm(); <ide> }; <ide> <del> this.encodeObjects = function() { <add> this.encodeObjects = function () { <ide> var data = {}, name; <ide> <ide> if (this.isform && this.options.processForm) { <del> $('input,select,textarea,.xcombobox', this.element).each(function() { <add> $('input,select,textarea,.xcombobox', this.element).each(function () { <ide> if ($(this).hasClass('xcombobox')) { <ide> name = $.trim($(this).attr('id')); <ide> data[name] = $.trim($(this).xcombobox('getValue')); <ide> return data; <ide> }; <ide> <del> this.setCSRFHeader = function(xhr) { <add> this.setCSRFHeader = function (xhr) { <ide> if (this.csrf) { <ide> var token = this.csrf.attr('content'); <ide>
Java
mit
f49e466eef12924b5afbdf83feadc710f1605f67
0
Cin316/Utilis
package com.utilis; import java.util.ArrayList; import java.util.StringTokenizer; public class WordArrays { public static String seperateWord(String s, int i){ String word = ""; String wordHolder = ""; int wordCount = 0; StringTokenizer token = new StringTokenizer(s); while (token.hasMoreTokens()){ wordCount++; wordHolder = token.nextToken(); if (wordCount==i){ word = wordHolder; } } return word; } public static int numOfWords(String s){ int wordCount = 0; StringTokenizer token = new StringTokenizer(s); while (token.hasMoreTokens()){ wordCount++; token.nextToken(); } return wordCount; } public static String[] arrayOfWords(String s){ String wordHolder = ""; ArrayList<String> al = new ArrayList<String>(); StringTokenizer token = new StringTokenizer(s); while (token.hasMoreTokens()){ wordHolder = token.nextToken(); al.add(wordHolder); } return objectArrayToStringArray(al.toArray()); } public static String[] objectArrayToStringArray(Object[] o){ String[] array = new String[o.length]; for (int i=0;i<o.length;i++){ array[i] = (String)o[i]; } return array; } public static int[] objectArrayToIntArray(Object[] o){ int[] array = new int[o.length]; for (int i=0;i<o.length;i++){ array[i] = (Integer)o[i]; } return array; } public static float[] objectArrayToFloatArray(Object[] o){ float[] array = new float[o.length]; for (int i=0;i<o.length;i++){ array[i] = (Float)o[i]; } return array; } public static char[] objectArrayToCharArray(Object[] o){ char[] array = new char[o.length]; for (int i=0;i<o.length;i++){ array[i] = (Character)o[i]; } return array; } /* public static <T> T[] objectArrayToTypeArray(Object[] o){ T[] array = new T[o.length]; for (int i=0;i<o.length;i++){ array[i] = (T)o[i]; } return array; } */ }
src/com/utilis/WordArrays.java
package com.utilis; import java.util.ArrayList; import java.util.StringTokenizer; public class WordArrays { public static String seperateWord(String s, int i){ String word = ""; String wordHolder = ""; int wordCount = 0; StringTokenizer token = new StringTokenizer(s); while (token.hasMoreTokens()){ wordCount++; wordHolder = token.nextToken(); if (wordCount==i){ word = wordHolder; } } return word; } public static int numOfWords(String s){ int wordCount = 0; StringTokenizer token = new StringTokenizer(s); while (token.hasMoreTokens()){ wordCount++; token.nextToken(); } return wordCount; } public static String[] arrayOfWords(String s){ String wordHolder = ""; ArrayList<String> al = new ArrayList<String>(); StringTokenizer token = new StringTokenizer(s); while (token.hasMoreTokens()){ wordHolder = token.nextToken(); al.add(wordHolder); } return objectArrayToStringArray(al.toArray()); } public static String[] objectArrayToStringArray(Object[] o){ String[] array = new String[o.length]; for (int i=0;i<o.length;i++){ array[i] = (String)o[i]; } return array; } public static int[] objectArrayToIntArray(Object[] o){ int[] array = new int[o.length]; for (int i=0;i<o.length;i++){ array[i] = (Integer)o[i]; } return array; } public static float[] objectArrayToFloatArray(Object[] o){ float[] array = new float[o.length]; for (int i=0;i<o.length;i++){ array[i] = (Float)o[i]; } return array; } public static char[] objectArrayToCharArray(Object[] o){ char[] array = new char[o.length]; for (int i=0;i<o.length;i++){ array[i] = (Character)o[i]; } return array; } }
Added broken method objectArrayToTypeArray(Object[]). Need to fix.
src/com/utilis/WordArrays.java
Added broken method objectArrayToTypeArray(Object[]). Need to fix.
<ide><path>rc/com/utilis/WordArrays.java <ide> } <ide> return array; <ide> } <add> /* <add> public static <T> T[] objectArrayToTypeArray(Object[] o){ <add> T[] array = new T[o.length]; <add> for (int i=0;i<o.length;i++){ <add> array[i] = (T)o[i]; <add> } <add> return array; <add> } <add> */ <ide> <ide> }
Java
apache-2.0
4aa11e9cc9bc668361d343a501163e4d76d6e27d
0
bgallz/cordova-plugin-inappbrowser,bgallz/cordova-plugin-inappbrowser,bgallz/cordova-plugin-inappbrowser,bgallz/cordova-plugin-inappbrowser,bgallz/cordova-plugin-inappbrowser
/* 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.cordova.inappbrowser; import android.annotation.SuppressLint; import android.content.Context; import android.content.Intent; import android.provider.Browser; import android.content.res.Resources; import android.graphics.Bitmap; import android.graphics.drawable.Drawable; import android.net.Uri; import android.os.Build; import android.os.Bundle; import android.text.InputType; import android.util.TypedValue; import android.view.Gravity; import android.view.KeyEvent; import android.view.View; import android.view.Window; import android.view.WindowManager; import android.view.WindowManager.LayoutParams; import android.view.inputmethod.EditorInfo; import android.view.inputmethod.InputMethodManager; import android.webkit.CookieManager; import android.webkit.CookieSyncManager; import android.webkit.HttpAuthHandler; import android.webkit.ValueCallback; import android.webkit.WebChromeClient; import android.webkit.WebSettings; import android.webkit.WebView; import android.webkit.WebViewClient; import android.widget.EditText; import android.widget.ImageButton; import android.widget.ImageView; import android.widget.LinearLayout; import android.widget.RelativeLayout; import org.apache.cordova.CallbackContext; import org.apache.cordova.Config; import org.apache.cordova.CordovaArgs; import org.apache.cordova.CordovaHttpAuthHandler; import org.apache.cordova.CordovaPlugin; import org.apache.cordova.CordovaWebView; import org.apache.cordova.LOG; import org.apache.cordova.PluginManager; import org.apache.cordova.PluginResult; import org.json.JSONException; import org.json.JSONObject; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Field; import java.lang.reflect.Method; import java.util.HashMap; import java.util.StringTokenizer; @SuppressLint("SetJavaScriptEnabled") public class InAppBrowser extends CordovaPlugin { private static final String NULL = "null"; protected static final String LOG_TAG = "InAppBrowser"; private static final String SELF = "_self"; private static final String SYSTEM = "_system"; private static final String EXIT_EVENT = "exit"; private static final String LOCATION = "location"; private static final String ZOOM = "zoom"; private static final String HIDDEN = "hidden"; private static final String LOAD_START_EVENT = "loadstart"; private static final String LOAD_STOP_EVENT = "loadstop"; private static final String LOAD_ERROR_EVENT = "loaderror"; private static final String CLEAR_ALL_CACHE = "clearcache"; private static final String CLEAR_SESSION_CACHE = "clearsessioncache"; private static final String HARDWARE_BACK_BUTTON = "hardwareback"; private static final String MEDIA_PLAYBACK_REQUIRES_USER_ACTION = "mediaPlaybackRequiresUserAction"; private static final String SHOULD_PAUSE = "shouldPauseOnSuspend"; private static final Boolean DEFAULT_HARDWARE_BACK = true; private static final String USER_WIDE_VIEW_PORT = "useWideViewPort"; private InAppBrowserDialog dialog; private WebView inAppWebView; private EditText edittext; private CallbackContext callbackContext; private boolean showLocationBar = true; private boolean showZoomControls = true; private boolean openWindowHidden = false; private boolean clearAllCache = false; private boolean clearSessionCache = false; private boolean hadwareBackButton = true; private boolean mediaPlaybackRequiresUserGesture = false; private boolean shouldPauseInAppBrowser = false; private boolean useWideViewPort = true; private ValueCallback<Uri> mUploadCallback; private ValueCallback<Uri[]> mUploadCallbackLollipop; private final static int FILECHOOSER_REQUESTCODE = 1; private final static int FILECHOOSER_REQUESTCODE_LOLLIPOP = 2; /** * Executes the request and returns PluginResult. * * @param action the action to execute. * @param args JSONArry of arguments for the plugin. * @param callbackContext the callbackContext used when calling back into JavaScript. * @return A PluginResult object with a status and message. */ public boolean execute(String action, CordovaArgs args, final CallbackContext callbackContext) throws JSONException { if (action.equals("open")) { this.callbackContext = callbackContext; final String url = args.getString(0); String t = args.optString(1); if (t == null || t.equals("") || t.equals(NULL)) { t = SELF; } final String target = t; final HashMap<String, Boolean> features = parseFeature(args.optString(2)); LOG.d(LOG_TAG, "target = " + target); this.cordova.getActivity().runOnUiThread(new Runnable() { @Override public void run() { String result = ""; // SELF if (SELF.equals(target)) { LOG.d(LOG_TAG, "in self"); /* This code exists for compatibility between 3.x and 4.x versions of Cordova. * Previously the Config class had a static method, isUrlWhitelisted(). That * responsibility has been moved to the plugins, with an aggregating method in * PluginManager. */ Boolean shouldAllowNavigation = null; if (url.startsWith("javascript:")) { shouldAllowNavigation = true; } if (shouldAllowNavigation == null) { try { Method iuw = Config.class.getMethod("isUrlWhiteListed", String.class); shouldAllowNavigation = (Boolean)iuw.invoke(null, url); } catch (NoSuchMethodException e) { LOG.d(LOG_TAG, e.getLocalizedMessage()); } catch (IllegalAccessException e) { LOG.d(LOG_TAG, e.getLocalizedMessage()); } catch (InvocationTargetException e) { LOG.d(LOG_TAG, e.getLocalizedMessage()); } } if (shouldAllowNavigation == null) { try { Method gpm = webView.getClass().getMethod("getPluginManager"); PluginManager pm = (PluginManager)gpm.invoke(webView); Method san = pm.getClass().getMethod("shouldAllowNavigation", String.class); shouldAllowNavigation = (Boolean)san.invoke(pm, url); } catch (NoSuchMethodException e) { LOG.d(LOG_TAG, e.getLocalizedMessage()); } catch (IllegalAccessException e) { LOG.d(LOG_TAG, e.getLocalizedMessage()); } catch (InvocationTargetException e) { LOG.d(LOG_TAG, e.getLocalizedMessage()); } } // load in webview if (Boolean.TRUE.equals(shouldAllowNavigation)) { LOG.d(LOG_TAG, "loading in webview"); webView.loadUrl(url); } //Load the dialer else if (url.startsWith(WebView.SCHEME_TEL)) { try { LOG.d(LOG_TAG, "loading in dialer"); Intent intent = new Intent(Intent.ACTION_DIAL); intent.setData(Uri.parse(url)); cordova.getActivity().startActivity(intent); } catch (android.content.ActivityNotFoundException e) { LOG.e(LOG_TAG, "Error dialing " + url + ": " + e.toString()); } } // load in InAppBrowser else { LOG.d(LOG_TAG, "loading in InAppBrowser"); result = showWebPage(url, features); } } // SYSTEM else if (SYSTEM.equals(target)) { LOG.d(LOG_TAG, "in system"); result = openExternal(url); } // BLANK - or anything else else { LOG.d(LOG_TAG, "in blank"); result = showWebPage(url, features); } PluginResult pluginResult = new PluginResult(PluginResult.Status.OK, result); pluginResult.setKeepCallback(true); callbackContext.sendPluginResult(pluginResult); } }); } else if (action.equals("close")) { closeDialog(); } else if (action.equals("injectScriptCode")) { String jsWrapper = null; if (args.getBoolean(1)) { jsWrapper = String.format("(function(){prompt(JSON.stringify([eval(%%s)]), 'gap-iab://%s')})()", callbackContext.getCallbackId()); } injectDeferredObject(args.getString(0), jsWrapper); } else if (action.equals("injectScriptFile")) { String jsWrapper; if (args.getBoolean(1)) { jsWrapper = String.format("(function(d) { var c = d.createElement('script'); c.src = %%s; c.onload = function() { prompt('', 'gap-iab://%s'); }; d.body.appendChild(c); })(document)", callbackContext.getCallbackId()); } else { jsWrapper = "(function(d) { var c = d.createElement('script'); c.src = %s; d.body.appendChild(c); })(document)"; } injectDeferredObject(args.getString(0), jsWrapper); } else if (action.equals("injectStyleCode")) { String jsWrapper; if (args.getBoolean(1)) { jsWrapper = String.format("(function(d) { var c = d.createElement('style'); c.innerHTML = %%s; d.body.appendChild(c); prompt('', 'gap-iab://%s');})(document)", callbackContext.getCallbackId()); } else { jsWrapper = "(function(d) { var c = d.createElement('style'); c.innerHTML = %s; d.body.appendChild(c); })(document)"; } injectDeferredObject(args.getString(0), jsWrapper); } else if (action.equals("injectStyleFile")) { String jsWrapper; if (args.getBoolean(1)) { jsWrapper = String.format("(function(d) { var c = d.createElement('link'); c.rel='stylesheet'; c.type='text/css'; c.href = %%s; d.head.appendChild(c); prompt('', 'gap-iab://%s');})(document)", callbackContext.getCallbackId()); } else { jsWrapper = "(function(d) { var c = d.createElement('link'); c.rel='stylesheet'; c.type='text/css'; c.href = %s; d.head.appendChild(c); })(document)"; } injectDeferredObject(args.getString(0), jsWrapper); } else if (action.equals("show")) { this.cordova.getActivity().runOnUiThread(new Runnable() { @Override public void run() { dialog.show(); /** * 2017-07-11 Brian Gall: * Added success callback here */ callbackContext.success(); } }); PluginResult pluginResult = new PluginResult(PluginResult.Status.OK); pluginResult.setKeepCallback(true); this.callbackContext.sendPluginResult(pluginResult); } else if (action.equals("hide")) { this.cordova.getActivity().runOnUiThread(new Runnable() { @Override public void run() { dialog.hide(); /** * 2017-07-11 Brian Gall: * Added success callback here */ callbackContext.success(); } }); PluginResult pluginResult = new PluginResult(PluginResult.Status.OK); pluginResult.setKeepCallback(true); this.callbackContext.sendPluginResult(pluginResult); } else { return false; } return true; } /** * Called when the view navigates. */ @Override public void onReset() { closeDialog(); } /** * Called when the system is about to start resuming a previous activity. */ @Override public void onPause(boolean multitasking) { if (shouldPauseInAppBrowser) { inAppWebView.onPause(); } } /** * Called when the activity will start interacting with the user. */ @Override public void onResume(boolean multitasking) { if (shouldPauseInAppBrowser) { inAppWebView.onResume(); } } /** * Called by AccelBroker when listener is to be shut down. * Stop listener. */ public void onDestroy() { closeDialog(); } /** * Inject an object (script or style) into the InAppBrowser WebView. * * This is a helper method for the inject{Script|Style}{Code|File} API calls, which * provides a consistent method for injecting JavaScript code into the document. * * If a wrapper string is supplied, then the source string will be JSON-encoded (adding * quotes) and wrapped using string formatting. (The wrapper string should have a single * '%s' marker) * * @param source The source object (filename or script/style text) to inject into * the document. * @param jsWrapper A JavaScript string to wrap the source string in, so that the object * is properly injected, or null if the source string is JavaScript text * which should be executed directly. */ private void injectDeferredObject(String source, String jsWrapper) { if (inAppWebView!=null) { String scriptToInject; if (jsWrapper != null) { org.json.JSONArray jsonEsc = new org.json.JSONArray(); jsonEsc.put(source); String jsonRepr = jsonEsc.toString(); String jsonSourceString = jsonRepr.substring(1, jsonRepr.length()-1); scriptToInject = String.format(jsWrapper, jsonSourceString); } else { scriptToInject = source; } final String finalScriptToInject = scriptToInject; this.cordova.getActivity().runOnUiThread(new Runnable() { @SuppressLint("NewApi") @Override public void run() { if (Build.VERSION.SDK_INT < Build.VERSION_CODES.KITKAT) { // This action will have the side-effect of blurring the currently focused element inAppWebView.loadUrl("javascript:" + finalScriptToInject); } else { inAppWebView.evaluateJavascript(finalScriptToInject, null); } } }); } else { LOG.d(LOG_TAG, "Can't inject code into the system browser"); } } /** * Put the list of features into a hash map * * @param optString * @return */ private HashMap<String, Boolean> parseFeature(String optString) { if (optString.equals(NULL)) { return null; } else { HashMap<String, Boolean> map = new HashMap<String, Boolean>(); StringTokenizer features = new StringTokenizer(optString, ","); StringTokenizer option; while(features.hasMoreElements()) { option = new StringTokenizer(features.nextToken(), "="); if (option.hasMoreElements()) { String key = option.nextToken(); Boolean value = option.nextToken().equals("no") ? Boolean.FALSE : Boolean.TRUE; map.put(key, value); } } return map; } } /** * Display a new browser with the specified URL. * * @param url the url to load. * @return "" if ok, or error message. */ public String openExternal(String url) { try { Intent intent = null; intent = new Intent(Intent.ACTION_VIEW); // Omitting the MIME type for file: URLs causes "No Activity found to handle Intent". // Adding the MIME type to http: URLs causes them to not be handled by the downloader. Uri uri = Uri.parse(url); if ("file".equals(uri.getScheme())) { intent.setDataAndType(uri, webView.getResourceApi().getMimeType(uri)); } else { intent.setData(uri); } intent.putExtra(Browser.EXTRA_APPLICATION_ID, cordova.getActivity().getPackageName()); this.cordova.getActivity().startActivity(intent); return ""; // not catching FileUriExposedException explicitly because buildtools<24 doesn't know about it } catch (java.lang.RuntimeException e) { LOG.d(LOG_TAG, "InAppBrowser: Error loading url "+url+":"+ e.toString()); return e.toString(); } } /** * Closes the dialog */ public void closeDialog() { this.cordova.getActivity().runOnUiThread(new Runnable() { @Override public void run() { final WebView childView = inAppWebView; // The JS protects against multiple calls, so this should happen only when // closeDialog() is called by other native code. if (childView == null) { return; } childView.setWebViewClient(new WebViewClient() { // NB: wait for about:blank before dismissing public void onPageFinished(WebView view, String url) { if (dialog != null) { dialog.dismiss(); dialog = null; } } }); // NB: From SDK 19: "If you call methods on WebView from any thread // other than your app's UI thread, it can cause unexpected results." // http://developer.android.com/guide/webapps/migrating.html#Threads childView.loadUrl("about:blank"); try { JSONObject obj = new JSONObject(); obj.put("type", EXIT_EVENT); sendUpdate(obj, false); } catch (JSONException ex) { LOG.d(LOG_TAG, "Should never happen"); } } }); } /** * Checks to see if it is possible to go back one page in history, then does so. */ public void goBack() { if (this.inAppWebView.canGoBack()) { this.inAppWebView.goBack(); } } /** * Can the web browser go back? * @return boolean */ public boolean canGoBack() { return this.inAppWebView.canGoBack(); } /** * Has the user set the hardware back button to go back * @return boolean */ public boolean hardwareBack() { return hadwareBackButton; } /** * Checks to see if it is possible to go forward one page in history, then does so. */ private void goForward() { if (this.inAppWebView.canGoForward()) { this.inAppWebView.goForward(); } } /** * Navigate to the new page * * @param url to load */ private void navigate(String url) { InputMethodManager imm = (InputMethodManager)this.cordova.getActivity().getSystemService(Context.INPUT_METHOD_SERVICE); imm.hideSoftInputFromWindow(edittext.getWindowToken(), 0); if (!url.startsWith("http") && !url.startsWith("file:")) { this.inAppWebView.loadUrl("http://" + url); } else { this.inAppWebView.loadUrl(url); } this.inAppWebView.requestFocus(); } /** * Should we show the location bar? * * @return boolean */ private boolean getShowLocationBar() { return this.showLocationBar; } private InAppBrowser getInAppBrowser(){ return this; } /** * Display a new browser with the specified URL. * * @param url the url to load. * @param features jsonObject */ public String showWebPage(final String url, HashMap<String, Boolean> features) { // Determine if we should hide the location bar. showLocationBar = true; showZoomControls = true; openWindowHidden = false; mediaPlaybackRequiresUserGesture = false; if (features != null) { Boolean show = features.get(LOCATION); if (show != null) { showLocationBar = show.booleanValue(); } Boolean zoom = features.get(ZOOM); if (zoom != null) { showZoomControls = zoom.booleanValue(); } Boolean hidden = features.get(HIDDEN); if (hidden != null) { openWindowHidden = hidden.booleanValue(); } Boolean hardwareBack = features.get(HARDWARE_BACK_BUTTON); if (hardwareBack != null) { hadwareBackButton = hardwareBack.booleanValue(); } else { hadwareBackButton = DEFAULT_HARDWARE_BACK; } Boolean mediaPlayback = features.get(MEDIA_PLAYBACK_REQUIRES_USER_ACTION); if (mediaPlayback != null) { mediaPlaybackRequiresUserGesture = mediaPlayback.booleanValue(); } Boolean cache = features.get(CLEAR_ALL_CACHE); if (cache != null) { clearAllCache = cache.booleanValue(); } else { cache = features.get(CLEAR_SESSION_CACHE); if (cache != null) { clearSessionCache = cache.booleanValue(); } } Boolean shouldPause = features.get(SHOULD_PAUSE); if (shouldPause != null) { shouldPauseInAppBrowser = shouldPause.booleanValue(); } Boolean wideViewPort = features.get(USER_WIDE_VIEW_PORT); if (wideViewPort != null ) { useWideViewPort = wideViewPort.booleanValue(); } } final CordovaWebView thatWebView = this.webView; // Create dialog in new thread Runnable runnable = new Runnable() { /** * Convert our DIP units to Pixels * * @return int */ private int dpToPixels(int dipValue) { int value = (int) TypedValue.applyDimension( TypedValue.COMPLEX_UNIT_DIP, (float) dipValue, cordova.getActivity().getResources().getDisplayMetrics() ); return value; } @SuppressLint("NewApi") public void run() { // CB-6702 InAppBrowser hangs when opening more than one instance if (dialog != null) { dialog.dismiss(); }; // Let's create the main dialog dialog = new InAppBrowserDialog(cordova.getActivity(), android.R.style.Theme_NoTitleBar); dialog.getWindow().getAttributes().windowAnimations = android.R.style.Animation_Dialog; dialog.requestWindowFeature(Window.FEATURE_NO_TITLE); dialog.setCancelable(true); dialog.setInAppBroswer(getInAppBrowser()); // Main container layout LinearLayout main = new LinearLayout(cordova.getActivity()); main.setOrientation(LinearLayout.VERTICAL); // Toolbar layout RelativeLayout toolbar = new RelativeLayout(cordova.getActivity()); //Please, no more black! toolbar.setBackgroundColor(android.graphics.Color.LTGRAY); toolbar.setLayoutParams(new RelativeLayout.LayoutParams(LayoutParams.MATCH_PARENT, this.dpToPixels(44))); toolbar.setPadding(this.dpToPixels(2), this.dpToPixels(2), this.dpToPixels(2), this.dpToPixels(2)); toolbar.setHorizontalGravity(Gravity.LEFT); toolbar.setVerticalGravity(Gravity.TOP); // Action Button Container layout RelativeLayout actionButtonContainer = new RelativeLayout(cordova.getActivity()); actionButtonContainer.setLayoutParams(new RelativeLayout.LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT)); actionButtonContainer.setHorizontalGravity(Gravity.LEFT); actionButtonContainer.setVerticalGravity(Gravity.CENTER_VERTICAL); actionButtonContainer.setId(Integer.valueOf(1)); // Back button ImageButton back = new ImageButton(cordova.getActivity()); RelativeLayout.LayoutParams backLayoutParams = new RelativeLayout.LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.MATCH_PARENT); backLayoutParams.addRule(RelativeLayout.ALIGN_LEFT); back.setLayoutParams(backLayoutParams); back.setContentDescription("Back Button"); back.setId(Integer.valueOf(2)); Resources activityRes = cordova.getActivity().getResources(); int backResId = activityRes.getIdentifier("ic_action_previous_item", "drawable", cordova.getActivity().getPackageName()); Drawable backIcon = activityRes.getDrawable(backResId); if (Build.VERSION.SDK_INT >= 16) back.setBackground(null); else back.setBackgroundDrawable(null); back.setImageDrawable(backIcon); back.setScaleType(ImageView.ScaleType.FIT_CENTER); back.setPadding(0, this.dpToPixels(10), 0, this.dpToPixels(10)); if (Build.VERSION.SDK_INT >= 16) back.getAdjustViewBounds(); back.setOnClickListener(new View.OnClickListener() { public void onClick(View v) { goBack(); } }); // Forward button ImageButton forward = new ImageButton(cordova.getActivity()); RelativeLayout.LayoutParams forwardLayoutParams = new RelativeLayout.LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.MATCH_PARENT); forwardLayoutParams.addRule(RelativeLayout.RIGHT_OF, 2); forward.setLayoutParams(forwardLayoutParams); forward.setContentDescription("Forward Button"); forward.setId(Integer.valueOf(3)); int fwdResId = activityRes.getIdentifier("ic_action_next_item", "drawable", cordova.getActivity().getPackageName()); Drawable fwdIcon = activityRes.getDrawable(fwdResId); if (Build.VERSION.SDK_INT >= 16) forward.setBackground(null); else forward.setBackgroundDrawable(null); forward.setImageDrawable(fwdIcon); forward.setScaleType(ImageView.ScaleType.FIT_CENTER); forward.setPadding(0, this.dpToPixels(10), 0, this.dpToPixels(10)); if (Build.VERSION.SDK_INT >= 16) forward.getAdjustViewBounds(); forward.setOnClickListener(new View.OnClickListener() { public void onClick(View v) { goForward(); } }); // Edit Text Box edittext = new EditText(cordova.getActivity()); RelativeLayout.LayoutParams textLayoutParams = new RelativeLayout.LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT); textLayoutParams.addRule(RelativeLayout.RIGHT_OF, 1); textLayoutParams.addRule(RelativeLayout.LEFT_OF, 5); edittext.setLayoutParams(textLayoutParams); edittext.setId(Integer.valueOf(4)); edittext.setSingleLine(true); edittext.setText(url); edittext.setInputType(InputType.TYPE_TEXT_VARIATION_URI); edittext.setImeOptions(EditorInfo.IME_ACTION_GO); edittext.setInputType(InputType.TYPE_NULL); // Will not except input... Makes the text NON-EDITABLE edittext.setOnKeyListener(new View.OnKeyListener() { public boolean onKey(View v, int keyCode, KeyEvent event) { // If the event is a key-down event on the "enter" button if ((event.getAction() == KeyEvent.ACTION_DOWN) && (keyCode == KeyEvent.KEYCODE_ENTER)) { navigate(edittext.getText().toString()); return true; } return false; } }); // Close/Done button ImageButton close = new ImageButton(cordova.getActivity()); RelativeLayout.LayoutParams closeLayoutParams = new RelativeLayout.LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.MATCH_PARENT); closeLayoutParams.addRule(RelativeLayout.ALIGN_PARENT_RIGHT); close.setLayoutParams(closeLayoutParams); close.setContentDescription("Close Button"); close.setId(Integer.valueOf(5)); int closeResId = activityRes.getIdentifier("ic_action_remove", "drawable", cordova.getActivity().getPackageName()); Drawable closeIcon = activityRes.getDrawable(closeResId); if (Build.VERSION.SDK_INT >= 16) close.setBackground(null); else close.setBackgroundDrawable(null); close.setImageDrawable(closeIcon); close.setScaleType(ImageView.ScaleType.FIT_CENTER); back.setPadding(0, this.dpToPixels(10), 0, this.dpToPixels(10)); if (Build.VERSION.SDK_INT >= 16) close.getAdjustViewBounds(); close.setOnClickListener(new View.OnClickListener() { public void onClick(View v) { closeDialog(); } }); // WebView inAppWebView = new WebView(cordova.getActivity()); inAppWebView.setLayoutParams(new LinearLayout.LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT)); inAppWebView.setId(Integer.valueOf(6)); // File Chooser Implemented ChromeClient inAppWebView.setWebChromeClient(new InAppChromeClient(thatWebView) { // For Android 5.0+ public boolean onShowFileChooser (WebView webView, ValueCallback<Uri[]> filePathCallback, WebChromeClient.FileChooserParams fileChooserParams) { LOG.d(LOG_TAG, "File Chooser 5.0+"); // If callback exists, finish it. if(mUploadCallbackLollipop != null) { mUploadCallbackLollipop.onReceiveValue(null); } mUploadCallbackLollipop = filePathCallback; // Create File Chooser Intent Intent content = new Intent(Intent.ACTION_GET_CONTENT); content.addCategory(Intent.CATEGORY_OPENABLE); content.setType("*/*"); // Run cordova startActivityForResult cordova.startActivityForResult(InAppBrowser.this, Intent.createChooser(content, "Select File"), FILECHOOSER_REQUESTCODE_LOLLIPOP); return true; } // For Android 4.1+ public void openFileChooser(ValueCallback<Uri> uploadMsg, String acceptType, String capture) { LOG.d(LOG_TAG, "File Chooser 4.1+"); // Call file chooser for Android 3.0+ openFileChooser(uploadMsg, acceptType); } // For Android 3.0+ public void openFileChooser(ValueCallback<Uri> uploadMsg, String acceptType) { LOG.d(LOG_TAG, "File Chooser 3.0+"); mUploadCallback = uploadMsg; Intent content = new Intent(Intent.ACTION_GET_CONTENT); content.addCategory(Intent.CATEGORY_OPENABLE); // run startActivityForResult cordova.startActivityForResult(InAppBrowser.this, Intent.createChooser(content, "Select File"), FILECHOOSER_REQUESTCODE); } }); WebViewClient client = new InAppBrowserClient(thatWebView, edittext); inAppWebView.setWebViewClient(client); WebSettings settings = inAppWebView.getSettings(); settings.setJavaScriptEnabled(true); settings.setJavaScriptCanOpenWindowsAutomatically(true); settings.setBuiltInZoomControls(showZoomControls); settings.setPluginState(android.webkit.WebSettings.PluginState.ON); if(android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.JELLY_BEAN_MR1) { settings.setMediaPlaybackRequiresUserGesture(mediaPlaybackRequiresUserGesture); } String overrideUserAgent = preferences.getString("OverrideUserAgent", null); String appendUserAgent = preferences.getString("AppendUserAgent", null); if (overrideUserAgent != null) { settings.setUserAgentString(overrideUserAgent); } if (appendUserAgent != null) { settings.setUserAgentString(settings.getUserAgentString() + appendUserAgent); } //Toggle whether this is enabled or not! Bundle appSettings = cordova.getActivity().getIntent().getExtras(); boolean enableDatabase = appSettings == null ? true : appSettings.getBoolean("InAppBrowserStorageEnabled", true); if (enableDatabase) { String databasePath = cordova.getActivity().getApplicationContext().getDir("inAppBrowserDB", Context.MODE_PRIVATE).getPath(); settings.setDatabasePath(databasePath); settings.setDatabaseEnabled(true); } settings.setDomStorageEnabled(true); if (clearAllCache) { CookieManager.getInstance().removeAllCookie(); } else if (clearSessionCache) { CookieManager.getInstance().removeSessionCookie(); } inAppWebView.loadUrl(url); inAppWebView.setId(Integer.valueOf(6)); inAppWebView.getSettings().setLoadWithOverviewMode(true); inAppWebView.getSettings().setUseWideViewPort(useWideViewPort); inAppWebView.requestFocus(); inAppWebView.requestFocusFromTouch(); // Add the back and forward buttons to our action button container layout actionButtonContainer.addView(back); actionButtonContainer.addView(forward); // Add the views to our toolbar toolbar.addView(actionButtonContainer); toolbar.addView(edittext); toolbar.addView(close); // Don't add the toolbar if its been disabled if (getShowLocationBar()) { // Add our toolbar to our main view/layout main.addView(toolbar); } // Add our webview to our main view/layout main.addView(inAppWebView); WindowManager.LayoutParams lp = new WindowManager.LayoutParams(); lp.copyFrom(dialog.getWindow().getAttributes()); lp.width = WindowManager.LayoutParams.MATCH_PARENT; lp.height = WindowManager.LayoutParams.MATCH_PARENT; dialog.setContentView(main); dialog.show(); dialog.getWindow().setAttributes(lp); // the goal of openhidden is to load the url and not display it // Show() needs to be called to cause the URL to be loaded if(openWindowHidden) { dialog.hide(); } } }; this.cordova.getActivity().runOnUiThread(runnable); return ""; } /** * Create a new plugin success result and send it back to JavaScript * * @param obj a JSONObject contain event payload information */ private void sendUpdate(JSONObject obj, boolean keepCallback) { sendUpdate(obj, keepCallback, PluginResult.Status.OK); } /** * Create a new plugin result and send it back to JavaScript * * @param obj a JSONObject contain event payload information * @param status the status code to return to the JavaScript environment */ private void sendUpdate(JSONObject obj, boolean keepCallback, PluginResult.Status status) { if (callbackContext != null) { PluginResult result = new PluginResult(status, obj); result.setKeepCallback(keepCallback); callbackContext.sendPluginResult(result); if (!keepCallback) { callbackContext = null; } } } /** * Receive File Data from File Chooser * * @param requestCode the requested code from chromeclient * @param resultCode the result code returned from android system * @param intent the data from android file chooser */ public void onActivityResult(int requestCode, int resultCode, Intent intent) { // For Android >= 5.0 if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) { LOG.d(LOG_TAG, "onActivityResult (For Android >= 5.0)"); // If RequestCode or Callback is Invalid if(requestCode != FILECHOOSER_REQUESTCODE_LOLLIPOP || mUploadCallbackLollipop == null) { super.onActivityResult(requestCode, resultCode, intent); return; } mUploadCallbackLollipop.onReceiveValue(WebChromeClient.FileChooserParams.parseResult(resultCode, intent)); mUploadCallbackLollipop = null; } // For Android < 5.0 else { LOG.d(LOG_TAG, "onActivityResult (For Android < 5.0)"); // If RequestCode or Callback is Invalid if(requestCode != FILECHOOSER_REQUESTCODE || mUploadCallback == null) { super.onActivityResult(requestCode, resultCode, intent); return; } if (null == mUploadCallback) return; Uri result = intent == null || resultCode != cordova.getActivity().RESULT_OK ? null : intent.getData(); mUploadCallback.onReceiveValue(result); mUploadCallback = null; } } /** * The webview client receives notifications about appView */ public class InAppBrowserClient extends WebViewClient { EditText edittext; CordovaWebView webView; /** * Constructor. * * @param webView * @param mEditText */ public InAppBrowserClient(CordovaWebView webView, EditText mEditText) { this.webView = webView; this.edittext = mEditText; } /** * Override the URL that should be loaded * * This handles a small subset of all the URIs that would be encountered. * * @param webView * @param url */ @Override public boolean shouldOverrideUrlLoading(WebView webView, String url) { if (url.startsWith(WebView.SCHEME_TEL)) { try { Intent intent = new Intent(Intent.ACTION_DIAL); intent.setData(Uri.parse(url)); cordova.getActivity().startActivity(intent); return true; } catch (android.content.ActivityNotFoundException e) { LOG.e(LOG_TAG, "Error dialing " + url + ": " + e.toString()); } } else if (url.startsWith("geo:") || url.startsWith(WebView.SCHEME_MAILTO) || url.startsWith("market:") || url.startsWith("intent:")) { try { Intent intent = new Intent(Intent.ACTION_VIEW); intent.setData(Uri.parse(url)); cordova.getActivity().startActivity(intent); return true; } catch (android.content.ActivityNotFoundException e) { LOG.e(LOG_TAG, "Error with " + url + ": " + e.toString()); } } // If sms:5551212?body=This is the message else if (url.startsWith("sms:")) { try { Intent intent = new Intent(Intent.ACTION_VIEW); // Get address String address = null; int parmIndex = url.indexOf('?'); if (parmIndex == -1) { address = url.substring(4); } else { address = url.substring(4, parmIndex); // If body, then set sms body Uri uri = Uri.parse(url); String query = uri.getQuery(); if (query != null) { if (query.startsWith("body=")) { intent.putExtra("sms_body", query.substring(5)); } } } intent.setData(Uri.parse("sms:" + address)); intent.putExtra("address", address); intent.setType("vnd.android-dir/mms-sms"); cordova.getActivity().startActivity(intent); return true; } catch (android.content.ActivityNotFoundException e) { LOG.e(LOG_TAG, "Error sending sms " + url + ":" + e.toString()); } } return false; } /* * onPageStarted fires the LOAD_START_EVENT * * @param view * @param url * @param favicon */ @Override public void onPageStarted(WebView view, String url, Bitmap favicon) { super.onPageStarted(view, url, favicon); String newloc = ""; if (url.startsWith("http:") || url.startsWith("https:") || url.startsWith("file:")) { newloc = url; } else { // Assume that everything is HTTP at this point, because if we don't specify, // it really should be. Complain loudly about this!!! LOG.e(LOG_TAG, "Possible Uncaught/Unknown URI"); newloc = "http://" + url; } // Update the UI if we haven't already if (!newloc.equals(edittext.getText().toString())) { edittext.setText(newloc); } try { JSONObject obj = new JSONObject(); obj.put("type", LOAD_START_EVENT); obj.put("url", newloc); sendUpdate(obj, true); } catch (JSONException ex) { LOG.e(LOG_TAG, "URI passed in has caused a JSON error."); } } public void onPageFinished(WebView view, String url) { super.onPageFinished(view, url); // CB-10395 InAppBrowser's WebView not storing cookies reliable to local device storage if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.LOLLIPOP) { CookieManager.getInstance().flush(); } else { CookieSyncManager.getInstance().sync(); } try { JSONObject obj = new JSONObject(); obj.put("type", LOAD_STOP_EVENT); obj.put("url", url); sendUpdate(obj, true); } catch (JSONException ex) { LOG.d(LOG_TAG, "Should never happen"); } } public void onReceivedError(WebView view, int errorCode, String description, String failingUrl) { super.onReceivedError(view, errorCode, description, failingUrl); try { JSONObject obj = new JSONObject(); obj.put("type", LOAD_ERROR_EVENT); obj.put("url", failingUrl); obj.put("code", errorCode); obj.put("message", description); sendUpdate(obj, true, PluginResult.Status.ERROR); } catch (JSONException ex) { LOG.d(LOG_TAG, "Should never happen"); } } /** * On received http auth request. */ @Override public void onReceivedHttpAuthRequest(WebView view, HttpAuthHandler handler, String host, String realm) { // Check if there is some plugin which can resolve this auth challenge PluginManager pluginManager = null; try { Method gpm = webView.getClass().getMethod("getPluginManager"); pluginManager = (PluginManager)gpm.invoke(webView); } catch (NoSuchMethodException e) { LOG.d(LOG_TAG, e.getLocalizedMessage()); } catch (IllegalAccessException e) { LOG.d(LOG_TAG, e.getLocalizedMessage()); } catch (InvocationTargetException e) { LOG.d(LOG_TAG, e.getLocalizedMessage()); } if (pluginManager == null) { try { Field pmf = webView.getClass().getField("pluginManager"); pluginManager = (PluginManager)pmf.get(webView); } catch (NoSuchFieldException e) { LOG.d(LOG_TAG, e.getLocalizedMessage()); } catch (IllegalAccessException e) { LOG.d(LOG_TAG, e.getLocalizedMessage()); } } if (pluginManager != null && pluginManager.onReceivedHttpAuthRequest(webView, new CordovaHttpAuthHandler(handler), host, realm)) { return; } // By default handle 401 like we'd normally do! super.onReceivedHttpAuthRequest(view, handler, host, realm); } } }
src/android/InAppBrowser.java
/* Licensed to the Apache Software Foundation (ASF) under one or more contributor license agreements. See the NOTICE file distributed with this work for additional information regarding copyright ownership. The ASF licenses this file to you under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ package org.apache.cordova.inappbrowser; import android.annotation.SuppressLint; import android.content.Context; import android.content.Intent; import android.provider.Browser; import android.content.res.Resources; import android.graphics.Bitmap; import android.graphics.drawable.Drawable; import android.net.Uri; import android.os.Build; import android.os.Bundle; import android.text.InputType; import android.util.TypedValue; import android.view.Gravity; import android.view.KeyEvent; import android.view.View; import android.view.Window; import android.view.WindowManager; import android.view.WindowManager.LayoutParams; import android.view.inputmethod.EditorInfo; import android.view.inputmethod.InputMethodManager; import android.webkit.CookieManager; import android.webkit.CookieSyncManager; import android.webkit.HttpAuthHandler; import android.webkit.ValueCallback; import android.webkit.WebChromeClient; import android.webkit.WebSettings; import android.webkit.WebView; import android.webkit.WebViewClient; import android.widget.EditText; import android.widget.ImageButton; import android.widget.ImageView; import android.widget.LinearLayout; import android.widget.RelativeLayout; import org.apache.cordova.CallbackContext; import org.apache.cordova.Config; import org.apache.cordova.CordovaArgs; import org.apache.cordova.CordovaHttpAuthHandler; import org.apache.cordova.CordovaPlugin; import org.apache.cordova.CordovaWebView; import org.apache.cordova.LOG; import org.apache.cordova.PluginManager; import org.apache.cordova.PluginResult; import org.json.JSONException; import org.json.JSONObject; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Field; import java.lang.reflect.Method; import java.util.HashMap; import java.util.StringTokenizer; @SuppressLint("SetJavaScriptEnabled") public class InAppBrowser extends CordovaPlugin { private static final String NULL = "null"; protected static final String LOG_TAG = "InAppBrowser"; private static final String SELF = "_self"; private static final String SYSTEM = "_system"; private static final String EXIT_EVENT = "exit"; private static final String LOCATION = "location"; private static final String ZOOM = "zoom"; private static final String HIDDEN = "hidden"; private static final String LOAD_START_EVENT = "loadstart"; private static final String LOAD_STOP_EVENT = "loadstop"; private static final String LOAD_ERROR_EVENT = "loaderror"; private static final String CLEAR_ALL_CACHE = "clearcache"; private static final String CLEAR_SESSION_CACHE = "clearsessioncache"; private static final String HARDWARE_BACK_BUTTON = "hardwareback"; private static final String MEDIA_PLAYBACK_REQUIRES_USER_ACTION = "mediaPlaybackRequiresUserAction"; private static final String SHOULD_PAUSE = "shouldPauseOnSuspend"; private static final Boolean DEFAULT_HARDWARE_BACK = true; private static final String USER_WIDE_VIEW_PORT = "useWideViewPort"; private InAppBrowserDialog dialog; private WebView inAppWebView; private EditText edittext; private CallbackContext callbackContext; private boolean showLocationBar = true; private boolean showZoomControls = true; private boolean openWindowHidden = false; private boolean clearAllCache = false; private boolean clearSessionCache = false; private boolean hadwareBackButton = true; private boolean mediaPlaybackRequiresUserGesture = false; private boolean shouldPauseInAppBrowser = false; private boolean useWideViewPort = true; private ValueCallback<Uri> mUploadCallback; private ValueCallback<Uri[]> mUploadCallbackLollipop; private final static int FILECHOOSER_REQUESTCODE = 1; private final static int FILECHOOSER_REQUESTCODE_LOLLIPOP = 2; /** * Executes the request and returns PluginResult. * * @param action the action to execute. * @param args JSONArry of arguments for the plugin. * @param callbackContext the callbackContext used when calling back into JavaScript. * @return A PluginResult object with a status and message. */ public boolean execute(String action, CordovaArgs args, final CallbackContext callbackContext) throws JSONException { if (action.equals("open")) { this.callbackContext = callbackContext; final String url = args.getString(0); String t = args.optString(1); if (t == null || t.equals("") || t.equals(NULL)) { t = SELF; } final String target = t; final HashMap<String, Boolean> features = parseFeature(args.optString(2)); LOG.d(LOG_TAG, "target = " + target); this.cordova.getActivity().runOnUiThread(new Runnable() { @Override public void run() { String result = ""; // SELF if (SELF.equals(target)) { LOG.d(LOG_TAG, "in self"); /* This code exists for compatibility between 3.x and 4.x versions of Cordova. * Previously the Config class had a static method, isUrlWhitelisted(). That * responsibility has been moved to the plugins, with an aggregating method in * PluginManager. */ Boolean shouldAllowNavigation = null; if (url.startsWith("javascript:")) { shouldAllowNavigation = true; } if (shouldAllowNavigation == null) { try { Method iuw = Config.class.getMethod("isUrlWhiteListed", String.class); shouldAllowNavigation = (Boolean)iuw.invoke(null, url); } catch (NoSuchMethodException e) { LOG.d(LOG_TAG, e.getLocalizedMessage()); } catch (IllegalAccessException e) { LOG.d(LOG_TAG, e.getLocalizedMessage()); } catch (InvocationTargetException e) { LOG.d(LOG_TAG, e.getLocalizedMessage()); } } if (shouldAllowNavigation == null) { try { Method gpm = webView.getClass().getMethod("getPluginManager"); PluginManager pm = (PluginManager)gpm.invoke(webView); Method san = pm.getClass().getMethod("shouldAllowNavigation", String.class); shouldAllowNavigation = (Boolean)san.invoke(pm, url); } catch (NoSuchMethodException e) { LOG.d(LOG_TAG, e.getLocalizedMessage()); } catch (IllegalAccessException e) { LOG.d(LOG_TAG, e.getLocalizedMessage()); } catch (InvocationTargetException e) { LOG.d(LOG_TAG, e.getLocalizedMessage()); } } // load in webview if (Boolean.TRUE.equals(shouldAllowNavigation)) { LOG.d(LOG_TAG, "loading in webview"); webView.loadUrl(url); } //Load the dialer else if (url.startsWith(WebView.SCHEME_TEL)) { try { LOG.d(LOG_TAG, "loading in dialer"); Intent intent = new Intent(Intent.ACTION_DIAL); intent.setData(Uri.parse(url)); cordova.getActivity().startActivity(intent); } catch (android.content.ActivityNotFoundException e) { LOG.e(LOG_TAG, "Error dialing " + url + ": " + e.toString()); } } // load in InAppBrowser else { LOG.d(LOG_TAG, "loading in InAppBrowser"); result = showWebPage(url, features); } } // SYSTEM else if (SYSTEM.equals(target)) { LOG.d(LOG_TAG, "in system"); result = openExternal(url); } // BLANK - or anything else else { LOG.d(LOG_TAG, "in blank"); result = showWebPage(url, features); } PluginResult pluginResult = new PluginResult(PluginResult.Status.OK, result); pluginResult.setKeepCallback(true); callbackContext.sendPluginResult(pluginResult); } }); } else if (action.equals("close")) { closeDialog(); } else if (action.equals("injectScriptCode")) { String jsWrapper = null; if (args.getBoolean(1)) { jsWrapper = String.format("(function(){prompt(JSON.stringify([eval(%%s)]), 'gap-iab://%s')})()", callbackContext.getCallbackId()); } injectDeferredObject(args.getString(0), jsWrapper); } else if (action.equals("injectScriptFile")) { String jsWrapper; if (args.getBoolean(1)) { jsWrapper = String.format("(function(d) { var c = d.createElement('script'); c.src = %%s; c.onload = function() { prompt('', 'gap-iab://%s'); }; d.body.appendChild(c); })(document)", callbackContext.getCallbackId()); } else { jsWrapper = "(function(d) { var c = d.createElement('script'); c.src = %s; d.body.appendChild(c); })(document)"; } injectDeferredObject(args.getString(0), jsWrapper); } else if (action.equals("injectStyleCode")) { String jsWrapper; if (args.getBoolean(1)) { jsWrapper = String.format("(function(d) { var c = d.createElement('style'); c.innerHTML = %%s; d.body.appendChild(c); prompt('', 'gap-iab://%s');})(document)", callbackContext.getCallbackId()); } else { jsWrapper = "(function(d) { var c = d.createElement('style'); c.innerHTML = %s; d.body.appendChild(c); })(document)"; } injectDeferredObject(args.getString(0), jsWrapper); } else if (action.equals("injectStyleFile")) { String jsWrapper; if (args.getBoolean(1)) { jsWrapper = String.format("(function(d) { var c = d.createElement('link'); c.rel='stylesheet'; c.type='text/css'; c.href = %%s; d.head.appendChild(c); prompt('', 'gap-iab://%s');})(document)", callbackContext.getCallbackId()); } else { jsWrapper = "(function(d) { var c = d.createElement('link'); c.rel='stylesheet'; c.type='text/css'; c.href = %s; d.head.appendChild(c); })(document)"; } injectDeferredObject(args.getString(0), jsWrapper); } else if (action.equals("show")) { this.cordova.getActivity().runOnUiThread(new Runnable() { @Override public void run() { dialog.show(); /** * 2017-07-11 Brian Gall: * Added success callback here */ callbackContext.success(); } }); /** * PluginResult pluginResult = new PluginResult(PluginResult.Status.OK); * pluginResult.setKeepCallback(true); * this.callbackContext.sendPluginResult(pluginResult); */ } else if (action.equals("hide")) { this.cordova.getActivity().runOnUiThread(new Runnable() { @Override public void run() { dialog.hide(); /** * 2017-07-11 Brian Gall: * Added success callback here */ callbackContext.success(); } }); /** * PluginResult pluginResult = new PluginResult(PluginResult.Status.OK); * pluginResult.setKeepCallback(true); * this.callbackContext.sendPluginResult(pluginResult); */ } else { return false; } return true; } /** * Called when the view navigates. */ @Override public void onReset() { closeDialog(); } /** * Called when the system is about to start resuming a previous activity. */ @Override public void onPause(boolean multitasking) { if (shouldPauseInAppBrowser) { inAppWebView.onPause(); } } /** * Called when the activity will start interacting with the user. */ @Override public void onResume(boolean multitasking) { if (shouldPauseInAppBrowser) { inAppWebView.onResume(); } } /** * Called by AccelBroker when listener is to be shut down. * Stop listener. */ public void onDestroy() { closeDialog(); } /** * Inject an object (script or style) into the InAppBrowser WebView. * * This is a helper method for the inject{Script|Style}{Code|File} API calls, which * provides a consistent method for injecting JavaScript code into the document. * * If a wrapper string is supplied, then the source string will be JSON-encoded (adding * quotes) and wrapped using string formatting. (The wrapper string should have a single * '%s' marker) * * @param source The source object (filename or script/style text) to inject into * the document. * @param jsWrapper A JavaScript string to wrap the source string in, so that the object * is properly injected, or null if the source string is JavaScript text * which should be executed directly. */ private void injectDeferredObject(String source, String jsWrapper) { if (inAppWebView!=null) { String scriptToInject; if (jsWrapper != null) { org.json.JSONArray jsonEsc = new org.json.JSONArray(); jsonEsc.put(source); String jsonRepr = jsonEsc.toString(); String jsonSourceString = jsonRepr.substring(1, jsonRepr.length()-1); scriptToInject = String.format(jsWrapper, jsonSourceString); } else { scriptToInject = source; } final String finalScriptToInject = scriptToInject; this.cordova.getActivity().runOnUiThread(new Runnable() { @SuppressLint("NewApi") @Override public void run() { if (Build.VERSION.SDK_INT < Build.VERSION_CODES.KITKAT) { // This action will have the side-effect of blurring the currently focused element inAppWebView.loadUrl("javascript:" + finalScriptToInject); } else { inAppWebView.evaluateJavascript(finalScriptToInject, null); } } }); } else { LOG.d(LOG_TAG, "Can't inject code into the system browser"); } } /** * Put the list of features into a hash map * * @param optString * @return */ private HashMap<String, Boolean> parseFeature(String optString) { if (optString.equals(NULL)) { return null; } else { HashMap<String, Boolean> map = new HashMap<String, Boolean>(); StringTokenizer features = new StringTokenizer(optString, ","); StringTokenizer option; while(features.hasMoreElements()) { option = new StringTokenizer(features.nextToken(), "="); if (option.hasMoreElements()) { String key = option.nextToken(); Boolean value = option.nextToken().equals("no") ? Boolean.FALSE : Boolean.TRUE; map.put(key, value); } } return map; } } /** * Display a new browser with the specified URL. * * @param url the url to load. * @return "" if ok, or error message. */ public String openExternal(String url) { try { Intent intent = null; intent = new Intent(Intent.ACTION_VIEW); // Omitting the MIME type for file: URLs causes "No Activity found to handle Intent". // Adding the MIME type to http: URLs causes them to not be handled by the downloader. Uri uri = Uri.parse(url); if ("file".equals(uri.getScheme())) { intent.setDataAndType(uri, webView.getResourceApi().getMimeType(uri)); } else { intent.setData(uri); } intent.putExtra(Browser.EXTRA_APPLICATION_ID, cordova.getActivity().getPackageName()); this.cordova.getActivity().startActivity(intent); return ""; // not catching FileUriExposedException explicitly because buildtools<24 doesn't know about it } catch (java.lang.RuntimeException e) { LOG.d(LOG_TAG, "InAppBrowser: Error loading url "+url+":"+ e.toString()); return e.toString(); } } /** * Closes the dialog */ public void closeDialog() { this.cordova.getActivity().runOnUiThread(new Runnable() { @Override public void run() { final WebView childView = inAppWebView; // The JS protects against multiple calls, so this should happen only when // closeDialog() is called by other native code. if (childView == null) { return; } childView.setWebViewClient(new WebViewClient() { // NB: wait for about:blank before dismissing public void onPageFinished(WebView view, String url) { if (dialog != null) { dialog.dismiss(); dialog = null; } } }); // NB: From SDK 19: "If you call methods on WebView from any thread // other than your app's UI thread, it can cause unexpected results." // http://developer.android.com/guide/webapps/migrating.html#Threads childView.loadUrl("about:blank"); try { JSONObject obj = new JSONObject(); obj.put("type", EXIT_EVENT); sendUpdate(obj, false); } catch (JSONException ex) { LOG.d(LOG_TAG, "Should never happen"); } } }); } /** * Checks to see if it is possible to go back one page in history, then does so. */ public void goBack() { if (this.inAppWebView.canGoBack()) { this.inAppWebView.goBack(); } } /** * Can the web browser go back? * @return boolean */ public boolean canGoBack() { return this.inAppWebView.canGoBack(); } /** * Has the user set the hardware back button to go back * @return boolean */ public boolean hardwareBack() { return hadwareBackButton; } /** * Checks to see if it is possible to go forward one page in history, then does so. */ private void goForward() { if (this.inAppWebView.canGoForward()) { this.inAppWebView.goForward(); } } /** * Navigate to the new page * * @param url to load */ private void navigate(String url) { InputMethodManager imm = (InputMethodManager)this.cordova.getActivity().getSystemService(Context.INPUT_METHOD_SERVICE); imm.hideSoftInputFromWindow(edittext.getWindowToken(), 0); if (!url.startsWith("http") && !url.startsWith("file:")) { this.inAppWebView.loadUrl("http://" + url); } else { this.inAppWebView.loadUrl(url); } this.inAppWebView.requestFocus(); } /** * Should we show the location bar? * * @return boolean */ private boolean getShowLocationBar() { return this.showLocationBar; } private InAppBrowser getInAppBrowser(){ return this; } /** * Display a new browser with the specified URL. * * @param url the url to load. * @param features jsonObject */ public String showWebPage(final String url, HashMap<String, Boolean> features) { // Determine if we should hide the location bar. showLocationBar = true; showZoomControls = true; openWindowHidden = false; mediaPlaybackRequiresUserGesture = false; if (features != null) { Boolean show = features.get(LOCATION); if (show != null) { showLocationBar = show.booleanValue(); } Boolean zoom = features.get(ZOOM); if (zoom != null) { showZoomControls = zoom.booleanValue(); } Boolean hidden = features.get(HIDDEN); if (hidden != null) { openWindowHidden = hidden.booleanValue(); } Boolean hardwareBack = features.get(HARDWARE_BACK_BUTTON); if (hardwareBack != null) { hadwareBackButton = hardwareBack.booleanValue(); } else { hadwareBackButton = DEFAULT_HARDWARE_BACK; } Boolean mediaPlayback = features.get(MEDIA_PLAYBACK_REQUIRES_USER_ACTION); if (mediaPlayback != null) { mediaPlaybackRequiresUserGesture = mediaPlayback.booleanValue(); } Boolean cache = features.get(CLEAR_ALL_CACHE); if (cache != null) { clearAllCache = cache.booleanValue(); } else { cache = features.get(CLEAR_SESSION_CACHE); if (cache != null) { clearSessionCache = cache.booleanValue(); } } Boolean shouldPause = features.get(SHOULD_PAUSE); if (shouldPause != null) { shouldPauseInAppBrowser = shouldPause.booleanValue(); } Boolean wideViewPort = features.get(USER_WIDE_VIEW_PORT); if (wideViewPort != null ) { useWideViewPort = wideViewPort.booleanValue(); } } final CordovaWebView thatWebView = this.webView; // Create dialog in new thread Runnable runnable = new Runnable() { /** * Convert our DIP units to Pixels * * @return int */ private int dpToPixels(int dipValue) { int value = (int) TypedValue.applyDimension( TypedValue.COMPLEX_UNIT_DIP, (float) dipValue, cordova.getActivity().getResources().getDisplayMetrics() ); return value; } @SuppressLint("NewApi") public void run() { // CB-6702 InAppBrowser hangs when opening more than one instance if (dialog != null) { dialog.dismiss(); }; // Let's create the main dialog dialog = new InAppBrowserDialog(cordova.getActivity(), android.R.style.Theme_NoTitleBar); dialog.getWindow().getAttributes().windowAnimations = android.R.style.Animation_Dialog; dialog.requestWindowFeature(Window.FEATURE_NO_TITLE); dialog.setCancelable(true); dialog.setInAppBroswer(getInAppBrowser()); // Main container layout LinearLayout main = new LinearLayout(cordova.getActivity()); main.setOrientation(LinearLayout.VERTICAL); // Toolbar layout RelativeLayout toolbar = new RelativeLayout(cordova.getActivity()); //Please, no more black! toolbar.setBackgroundColor(android.graphics.Color.LTGRAY); toolbar.setLayoutParams(new RelativeLayout.LayoutParams(LayoutParams.MATCH_PARENT, this.dpToPixels(44))); toolbar.setPadding(this.dpToPixels(2), this.dpToPixels(2), this.dpToPixels(2), this.dpToPixels(2)); toolbar.setHorizontalGravity(Gravity.LEFT); toolbar.setVerticalGravity(Gravity.TOP); // Action Button Container layout RelativeLayout actionButtonContainer = new RelativeLayout(cordova.getActivity()); actionButtonContainer.setLayoutParams(new RelativeLayout.LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT)); actionButtonContainer.setHorizontalGravity(Gravity.LEFT); actionButtonContainer.setVerticalGravity(Gravity.CENTER_VERTICAL); actionButtonContainer.setId(Integer.valueOf(1)); // Back button ImageButton back = new ImageButton(cordova.getActivity()); RelativeLayout.LayoutParams backLayoutParams = new RelativeLayout.LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.MATCH_PARENT); backLayoutParams.addRule(RelativeLayout.ALIGN_LEFT); back.setLayoutParams(backLayoutParams); back.setContentDescription("Back Button"); back.setId(Integer.valueOf(2)); Resources activityRes = cordova.getActivity().getResources(); int backResId = activityRes.getIdentifier("ic_action_previous_item", "drawable", cordova.getActivity().getPackageName()); Drawable backIcon = activityRes.getDrawable(backResId); if (Build.VERSION.SDK_INT >= 16) back.setBackground(null); else back.setBackgroundDrawable(null); back.setImageDrawable(backIcon); back.setScaleType(ImageView.ScaleType.FIT_CENTER); back.setPadding(0, this.dpToPixels(10), 0, this.dpToPixels(10)); if (Build.VERSION.SDK_INT >= 16) back.getAdjustViewBounds(); back.setOnClickListener(new View.OnClickListener() { public void onClick(View v) { goBack(); } }); // Forward button ImageButton forward = new ImageButton(cordova.getActivity()); RelativeLayout.LayoutParams forwardLayoutParams = new RelativeLayout.LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.MATCH_PARENT); forwardLayoutParams.addRule(RelativeLayout.RIGHT_OF, 2); forward.setLayoutParams(forwardLayoutParams); forward.setContentDescription("Forward Button"); forward.setId(Integer.valueOf(3)); int fwdResId = activityRes.getIdentifier("ic_action_next_item", "drawable", cordova.getActivity().getPackageName()); Drawable fwdIcon = activityRes.getDrawable(fwdResId); if (Build.VERSION.SDK_INT >= 16) forward.setBackground(null); else forward.setBackgroundDrawable(null); forward.setImageDrawable(fwdIcon); forward.setScaleType(ImageView.ScaleType.FIT_CENTER); forward.setPadding(0, this.dpToPixels(10), 0, this.dpToPixels(10)); if (Build.VERSION.SDK_INT >= 16) forward.getAdjustViewBounds(); forward.setOnClickListener(new View.OnClickListener() { public void onClick(View v) { goForward(); } }); // Edit Text Box edittext = new EditText(cordova.getActivity()); RelativeLayout.LayoutParams textLayoutParams = new RelativeLayout.LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT); textLayoutParams.addRule(RelativeLayout.RIGHT_OF, 1); textLayoutParams.addRule(RelativeLayout.LEFT_OF, 5); edittext.setLayoutParams(textLayoutParams); edittext.setId(Integer.valueOf(4)); edittext.setSingleLine(true); edittext.setText(url); edittext.setInputType(InputType.TYPE_TEXT_VARIATION_URI); edittext.setImeOptions(EditorInfo.IME_ACTION_GO); edittext.setInputType(InputType.TYPE_NULL); // Will not except input... Makes the text NON-EDITABLE edittext.setOnKeyListener(new View.OnKeyListener() { public boolean onKey(View v, int keyCode, KeyEvent event) { // If the event is a key-down event on the "enter" button if ((event.getAction() == KeyEvent.ACTION_DOWN) && (keyCode == KeyEvent.KEYCODE_ENTER)) { navigate(edittext.getText().toString()); return true; } return false; } }); // Close/Done button ImageButton close = new ImageButton(cordova.getActivity()); RelativeLayout.LayoutParams closeLayoutParams = new RelativeLayout.LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.MATCH_PARENT); closeLayoutParams.addRule(RelativeLayout.ALIGN_PARENT_RIGHT); close.setLayoutParams(closeLayoutParams); close.setContentDescription("Close Button"); close.setId(Integer.valueOf(5)); int closeResId = activityRes.getIdentifier("ic_action_remove", "drawable", cordova.getActivity().getPackageName()); Drawable closeIcon = activityRes.getDrawable(closeResId); if (Build.VERSION.SDK_INT >= 16) close.setBackground(null); else close.setBackgroundDrawable(null); close.setImageDrawable(closeIcon); close.setScaleType(ImageView.ScaleType.FIT_CENTER); back.setPadding(0, this.dpToPixels(10), 0, this.dpToPixels(10)); if (Build.VERSION.SDK_INT >= 16) close.getAdjustViewBounds(); close.setOnClickListener(new View.OnClickListener() { public void onClick(View v) { closeDialog(); } }); // WebView inAppWebView = new WebView(cordova.getActivity()); inAppWebView.setLayoutParams(new LinearLayout.LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT)); inAppWebView.setId(Integer.valueOf(6)); // File Chooser Implemented ChromeClient inAppWebView.setWebChromeClient(new InAppChromeClient(thatWebView) { // For Android 5.0+ public boolean onShowFileChooser (WebView webView, ValueCallback<Uri[]> filePathCallback, WebChromeClient.FileChooserParams fileChooserParams) { LOG.d(LOG_TAG, "File Chooser 5.0+"); // If callback exists, finish it. if(mUploadCallbackLollipop != null) { mUploadCallbackLollipop.onReceiveValue(null); } mUploadCallbackLollipop = filePathCallback; // Create File Chooser Intent Intent content = new Intent(Intent.ACTION_GET_CONTENT); content.addCategory(Intent.CATEGORY_OPENABLE); content.setType("*/*"); // Run cordova startActivityForResult cordova.startActivityForResult(InAppBrowser.this, Intent.createChooser(content, "Select File"), FILECHOOSER_REQUESTCODE_LOLLIPOP); return true; } // For Android 4.1+ public void openFileChooser(ValueCallback<Uri> uploadMsg, String acceptType, String capture) { LOG.d(LOG_TAG, "File Chooser 4.1+"); // Call file chooser for Android 3.0+ openFileChooser(uploadMsg, acceptType); } // For Android 3.0+ public void openFileChooser(ValueCallback<Uri> uploadMsg, String acceptType) { LOG.d(LOG_TAG, "File Chooser 3.0+"); mUploadCallback = uploadMsg; Intent content = new Intent(Intent.ACTION_GET_CONTENT); content.addCategory(Intent.CATEGORY_OPENABLE); // run startActivityForResult cordova.startActivityForResult(InAppBrowser.this, Intent.createChooser(content, "Select File"), FILECHOOSER_REQUESTCODE); } }); WebViewClient client = new InAppBrowserClient(thatWebView, edittext); inAppWebView.setWebViewClient(client); WebSettings settings = inAppWebView.getSettings(); settings.setJavaScriptEnabled(true); settings.setJavaScriptCanOpenWindowsAutomatically(true); settings.setBuiltInZoomControls(showZoomControls); settings.setPluginState(android.webkit.WebSettings.PluginState.ON); if(android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.JELLY_BEAN_MR1) { settings.setMediaPlaybackRequiresUserGesture(mediaPlaybackRequiresUserGesture); } String overrideUserAgent = preferences.getString("OverrideUserAgent", null); String appendUserAgent = preferences.getString("AppendUserAgent", null); if (overrideUserAgent != null) { settings.setUserAgentString(overrideUserAgent); } if (appendUserAgent != null) { settings.setUserAgentString(settings.getUserAgentString() + appendUserAgent); } //Toggle whether this is enabled or not! Bundle appSettings = cordova.getActivity().getIntent().getExtras(); boolean enableDatabase = appSettings == null ? true : appSettings.getBoolean("InAppBrowserStorageEnabled", true); if (enableDatabase) { String databasePath = cordova.getActivity().getApplicationContext().getDir("inAppBrowserDB", Context.MODE_PRIVATE).getPath(); settings.setDatabasePath(databasePath); settings.setDatabaseEnabled(true); } settings.setDomStorageEnabled(true); if (clearAllCache) { CookieManager.getInstance().removeAllCookie(); } else if (clearSessionCache) { CookieManager.getInstance().removeSessionCookie(); } inAppWebView.loadUrl(url); inAppWebView.setId(Integer.valueOf(6)); inAppWebView.getSettings().setLoadWithOverviewMode(true); inAppWebView.getSettings().setUseWideViewPort(useWideViewPort); inAppWebView.requestFocus(); inAppWebView.requestFocusFromTouch(); // Add the back and forward buttons to our action button container layout actionButtonContainer.addView(back); actionButtonContainer.addView(forward); // Add the views to our toolbar toolbar.addView(actionButtonContainer); toolbar.addView(edittext); toolbar.addView(close); // Don't add the toolbar if its been disabled if (getShowLocationBar()) { // Add our toolbar to our main view/layout main.addView(toolbar); } // Add our webview to our main view/layout main.addView(inAppWebView); WindowManager.LayoutParams lp = new WindowManager.LayoutParams(); lp.copyFrom(dialog.getWindow().getAttributes()); lp.width = WindowManager.LayoutParams.MATCH_PARENT; lp.height = WindowManager.LayoutParams.MATCH_PARENT; dialog.setContentView(main); dialog.show(); dialog.getWindow().setAttributes(lp); // the goal of openhidden is to load the url and not display it // Show() needs to be called to cause the URL to be loaded if(openWindowHidden) { dialog.hide(); } } }; this.cordova.getActivity().runOnUiThread(runnable); return ""; } /** * Create a new plugin success result and send it back to JavaScript * * @param obj a JSONObject contain event payload information */ private void sendUpdate(JSONObject obj, boolean keepCallback) { sendUpdate(obj, keepCallback, PluginResult.Status.OK); } /** * Create a new plugin result and send it back to JavaScript * * @param obj a JSONObject contain event payload information * @param status the status code to return to the JavaScript environment */ private void sendUpdate(JSONObject obj, boolean keepCallback, PluginResult.Status status) { if (callbackContext != null) { PluginResult result = new PluginResult(status, obj); result.setKeepCallback(keepCallback); callbackContext.sendPluginResult(result); if (!keepCallback) { callbackContext = null; } } } /** * Receive File Data from File Chooser * * @param requestCode the requested code from chromeclient * @param resultCode the result code returned from android system * @param intent the data from android file chooser */ public void onActivityResult(int requestCode, int resultCode, Intent intent) { // For Android >= 5.0 if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) { LOG.d(LOG_TAG, "onActivityResult (For Android >= 5.0)"); // If RequestCode or Callback is Invalid if(requestCode != FILECHOOSER_REQUESTCODE_LOLLIPOP || mUploadCallbackLollipop == null) { super.onActivityResult(requestCode, resultCode, intent); return; } mUploadCallbackLollipop.onReceiveValue(WebChromeClient.FileChooserParams.parseResult(resultCode, intent)); mUploadCallbackLollipop = null; } // For Android < 5.0 else { LOG.d(LOG_TAG, "onActivityResult (For Android < 5.0)"); // If RequestCode or Callback is Invalid if(requestCode != FILECHOOSER_REQUESTCODE || mUploadCallback == null) { super.onActivityResult(requestCode, resultCode, intent); return; } if (null == mUploadCallback) return; Uri result = intent == null || resultCode != cordova.getActivity().RESULT_OK ? null : intent.getData(); mUploadCallback.onReceiveValue(result); mUploadCallback = null; } } /** * The webview client receives notifications about appView */ public class InAppBrowserClient extends WebViewClient { EditText edittext; CordovaWebView webView; /** * Constructor. * * @param webView * @param mEditText */ public InAppBrowserClient(CordovaWebView webView, EditText mEditText) { this.webView = webView; this.edittext = mEditText; } /** * Override the URL that should be loaded * * This handles a small subset of all the URIs that would be encountered. * * @param webView * @param url */ @Override public boolean shouldOverrideUrlLoading(WebView webView, String url) { if (url.startsWith(WebView.SCHEME_TEL)) { try { Intent intent = new Intent(Intent.ACTION_DIAL); intent.setData(Uri.parse(url)); cordova.getActivity().startActivity(intent); return true; } catch (android.content.ActivityNotFoundException e) { LOG.e(LOG_TAG, "Error dialing " + url + ": " + e.toString()); } } else if (url.startsWith("geo:") || url.startsWith(WebView.SCHEME_MAILTO) || url.startsWith("market:") || url.startsWith("intent:")) { try { Intent intent = new Intent(Intent.ACTION_VIEW); intent.setData(Uri.parse(url)); cordova.getActivity().startActivity(intent); return true; } catch (android.content.ActivityNotFoundException e) { LOG.e(LOG_TAG, "Error with " + url + ": " + e.toString()); } } // If sms:5551212?body=This is the message else if (url.startsWith("sms:")) { try { Intent intent = new Intent(Intent.ACTION_VIEW); // Get address String address = null; int parmIndex = url.indexOf('?'); if (parmIndex == -1) { address = url.substring(4); } else { address = url.substring(4, parmIndex); // If body, then set sms body Uri uri = Uri.parse(url); String query = uri.getQuery(); if (query != null) { if (query.startsWith("body=")) { intent.putExtra("sms_body", query.substring(5)); } } } intent.setData(Uri.parse("sms:" + address)); intent.putExtra("address", address); intent.setType("vnd.android-dir/mms-sms"); cordova.getActivity().startActivity(intent); return true; } catch (android.content.ActivityNotFoundException e) { LOG.e(LOG_TAG, "Error sending sms " + url + ":" + e.toString()); } } return false; } /* * onPageStarted fires the LOAD_START_EVENT * * @param view * @param url * @param favicon */ @Override public void onPageStarted(WebView view, String url, Bitmap favicon) { super.onPageStarted(view, url, favicon); String newloc = ""; if (url.startsWith("http:") || url.startsWith("https:") || url.startsWith("file:")) { newloc = url; } else { // Assume that everything is HTTP at this point, because if we don't specify, // it really should be. Complain loudly about this!!! LOG.e(LOG_TAG, "Possible Uncaught/Unknown URI"); newloc = "http://" + url; } // Update the UI if we haven't already if (!newloc.equals(edittext.getText().toString())) { edittext.setText(newloc); } try { JSONObject obj = new JSONObject(); obj.put("type", LOAD_START_EVENT); obj.put("url", newloc); sendUpdate(obj, true); } catch (JSONException ex) { LOG.e(LOG_TAG, "URI passed in has caused a JSON error."); } } public void onPageFinished(WebView view, String url) { super.onPageFinished(view, url); // CB-10395 InAppBrowser's WebView not storing cookies reliable to local device storage if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.LOLLIPOP) { CookieManager.getInstance().flush(); } else { CookieSyncManager.getInstance().sync(); } try { JSONObject obj = new JSONObject(); obj.put("type", LOAD_STOP_EVENT); obj.put("url", url); sendUpdate(obj, true); } catch (JSONException ex) { LOG.d(LOG_TAG, "Should never happen"); } } public void onReceivedError(WebView view, int errorCode, String description, String failingUrl) { super.onReceivedError(view, errorCode, description, failingUrl); try { JSONObject obj = new JSONObject(); obj.put("type", LOAD_ERROR_EVENT); obj.put("url", failingUrl); obj.put("code", errorCode); obj.put("message", description); sendUpdate(obj, true, PluginResult.Status.ERROR); } catch (JSONException ex) { LOG.d(LOG_TAG, "Should never happen"); } } /** * On received http auth request. */ @Override public void onReceivedHttpAuthRequest(WebView view, HttpAuthHandler handler, String host, String realm) { // Check if there is some plugin which can resolve this auth challenge PluginManager pluginManager = null; try { Method gpm = webView.getClass().getMethod("getPluginManager"); pluginManager = (PluginManager)gpm.invoke(webView); } catch (NoSuchMethodException e) { LOG.d(LOG_TAG, e.getLocalizedMessage()); } catch (IllegalAccessException e) { LOG.d(LOG_TAG, e.getLocalizedMessage()); } catch (InvocationTargetException e) { LOG.d(LOG_TAG, e.getLocalizedMessage()); } if (pluginManager == null) { try { Field pmf = webView.getClass().getField("pluginManager"); pluginManager = (PluginManager)pmf.get(webView); } catch (NoSuchFieldException e) { LOG.d(LOG_TAG, e.getLocalizedMessage()); } catch (IllegalAccessException e) { LOG.d(LOG_TAG, e.getLocalizedMessage()); } } if (pluginManager != null && pluginManager.onReceivedHttpAuthRequest(webView, new CordovaHttpAuthHandler(handler), host, realm)) { return; } // By default handle 401 like we'd normally do! super.onReceivedHttpAuthRequest(view, handler, host, realm); } } }
Updated Android show and hide methods to use both success callback and send plugin result.
src/android/InAppBrowser.java
Updated Android show and hide methods to use both success callback and send plugin result.
<ide><path>rc/android/InAppBrowser.java <ide> callbackContext.success(); <ide> } <ide> }); <del> /** <del> * PluginResult pluginResult = new PluginResult(PluginResult.Status.OK); <del> * pluginResult.setKeepCallback(true); <del> * this.callbackContext.sendPluginResult(pluginResult); <del> */ <add> PluginResult pluginResult = new PluginResult(PluginResult.Status.OK); <add> pluginResult.setKeepCallback(true); <add> this.callbackContext.sendPluginResult(pluginResult); <ide> } <ide> else if (action.equals("hide")) { <ide> this.cordova.getActivity().runOnUiThread(new Runnable() { <ide> callbackContext.success(); <ide> } <ide> }); <del> /** <del> * PluginResult pluginResult = new PluginResult(PluginResult.Status.OK); <del> * pluginResult.setKeepCallback(true); <del> * this.callbackContext.sendPluginResult(pluginResult); <del> */ <add> PluginResult pluginResult = new PluginResult(PluginResult.Status.OK); <add> pluginResult.setKeepCallback(true); <add> this.callbackContext.sendPluginResult(pluginResult); <ide> } <ide> else { <ide> return false;
Java
apache-2.0
c55617656a42f78dab8cf50be27b727857e12a52
0
donglua/JZAndroidChart,donglua/JZAndroidChart
package cn.jingzhuan.lib.chart2.renderer; import android.graphics.Bitmap; import android.graphics.Canvas; import android.graphics.Color; import android.graphics.Paint; import android.graphics.RectF; import android.support.annotation.NonNull; import android.view.MotionEvent; import org.jetbrains.annotations.NotNull; import java.util.List; import cn.jingzhuan.lib.chart.Viewport; import cn.jingzhuan.lib.chart.component.Highlight; import cn.jingzhuan.lib.chart.data.CandlestickData; import cn.jingzhuan.lib.chart.data.CandlestickDataSet; import cn.jingzhuan.lib.chart.data.CandlestickValue; import cn.jingzhuan.lib.chart.data.ChartData; import cn.jingzhuan.lib.chart.event.OnViewportChangeListener; import cn.jingzhuan.lib.chart2.base.Chart; /** * 区间统计Renderer */ public class RangeRenderer extends AbstractDataRenderer<CandlestickDataSet> { private CandlestickData chartData; /** * 绘制左侧的ico x的坐标 */ float mStartX = 0; /** * 绘制右侧ico 的x坐标 */ float mEndX = 0; /** * 绘制的ico */ Bitmap icoBitmap; /** * 左侧的ico的矩形区域 */ RectF mStartRect; /** * 右侧ico的矩形区域 */ RectF mEndRect; /** * 用于划线 */ Paint paint = new Paint(); /** * 中间阴影 */ Paint shadowPaint = new Paint(); Chart chart; private OnRangeListener mOnRangeListener; private OnRangeKLineVisibleListener mOnRangeKLineVisibleListener; private OnRangeKLineListener mOnRangeKLineListener; private CandlestickValue mStartCandlestickValue; private CandlestickValue mEndCandlestickValue; //线条颜色 默认蓝色 private int mLineColor = Color.parseColor("#216FE1"); //区间颜色 private int mRangeColor = Color.parseColor("#66D8F2FD"); //开始的index private int mStartIndex; //结束的index private int mEndIndex; public RangeRenderer(Chart chart) { super(chart); this.chart = chart; initPaint(); chart.setInternalViewportChangeListener(new OnViewportChangeListener() { @Override public void onViewportChange(Viewport viewport) { mViewport.set(viewport); calcDataSetMinMax(); } }); } @Override protected void renderDataSet(Canvas canvas, ChartData<CandlestickDataSet> chartData) { drawCanvas(canvas); } public void initPaint() { paint.setAntiAlias(true); paint.setColor(getLineColor()); paint.setSubpixelText(true); paint.setStrokeWidth(3); shadowPaint = new Paint(paint); shadowPaint.setStyle(Paint.Style.FILL); shadowPaint.setColor(getRangeColor()); } @Override public void renderHighlighted(Canvas canvas, @NonNull @NotNull Highlight[] highlights) { } public void drawCanvas(Canvas canvas) { CandlestickDataSet candlestickDataSet = dataVaild(); if (candlestickDataSet == null) return; //默认选中数据中最后10个K线作为统计范围 if (mStartCandlestickValue == null || mEndCandlestickValue == null) { List<CandlestickValue> visiblePoints = candlestickDataSet.getVisiblePoints(mViewport); CandlestickValue startVisible = visiblePoints.get(visiblePoints.size() - 10); CandlestickValue endVisible = visiblePoints.get(visiblePoints.size() - 1); float startVisibleX = startVisible.getX(); float startVisibleY = startVisible.getY(); float endVisibleX = endVisible.getX(); float endVisibleY = endVisible.getY(); mStartIndex = getEntryIndexByCoordinate(startVisibleX, startVisibleY); mEndIndex = getEntryIndexByCoordinate(endVisibleX, endVisibleY); } mStartCandlestickValue = candlestickDataSet.getEntryForIndex(mStartIndex); mEndCandlestickValue = candlestickDataSet.getEntryForIndex(mEndIndex); if (mStartIndex >= candlestickDataSet.getValues().size() || mEndIndex >= candlestickDataSet.getValues().size()) return; /* 获取区间统计开始的K线坐标 */ mStartX = getScaleCoordinateByIndex(mStartIndex); /* * 获取区间统计结束的K线坐标 */ mEndX = getScaleCoordinateByIndex(mEndIndex); float bitmapSpanX = icoBitmap.getWidth() / 2f; float bitmapSpanY = icoBitmap.getHeight() / 2f; RectF rect = new RectF(mStartX, 0, mEndX, chart.getContentRect().height()); // System.out.println("9529 mStartX :" + mStartX + candlestickDataSet); //绘制区间统计的选择区域 canvas.drawRect(rect, shadowPaint); /* * 根据K线数据的中点绘制线条 */ canvas.drawLine(mStartX, 0, mStartX, chart.getContentRect().height(), paint); canvas.drawLine(mEndX, 0, mEndX, chart.getContentRect().height(), paint); // System.out.println("9529 current drawLine " + currentViewport.left + "," + currentViewport.right); // System.out.println("9529 mContent left : " + mContentRect.left + " , right : " + mContentRect.right); /* * 绘制ico */ if (icoBitmap != null){ canvas.drawBitmap(icoBitmap, mStartX - bitmapSpanX, chart.getContentRect().height() / 2f - bitmapSpanY, paint); canvas.drawBitmap(icoBitmap, mEndX - bitmapSpanX, chart.getContentRect().height() / 2f - bitmapSpanY, paint); } /* *为了更好的能拖动区间 加大了触发拖动的范围 */ float defaultSpanX = 0; float defaultSpanY = 0; /* * 创建开始&结束矩阵 用于判断触摸点是否在该区域内 * true -> 改变区间统计范围 * false -> 不作反应 */ mStartRect = new RectF( mStartX - bitmapSpanX - defaultSpanX, chart.getContentRect().height() / 2f - bitmapSpanY - defaultSpanY, mStartX + bitmapSpanX + defaultSpanX, chart.getContentRect().height() / 2f + bitmapSpanY + defaultSpanY); mEndRect = new RectF( mEndX - bitmapSpanX - defaultSpanX, chart.getContentRect().height() / 2f - bitmapSpanY - defaultSpanY, mEndX + bitmapSpanX + defaultSpanX, chart.getContentRect().height() / 2f + bitmapSpanY + defaultSpanY); //回调区间X轴坐标的范围 if (mOnRangeListener != null) mOnRangeListener.onRange(mStartX, mEndX); /* * 缩放限制 * 当K线被缩放到屏幕外(不可见)的情况下 关闭缩放 */ if (mOnRangeKLineVisibleListener != null) { mOnRangeKLineVisibleListener.onRangeKLineVisible((mStartX > (mContentRect.left + icoBitmap.getWidth()) && mEndX < (mContentRect.width() - icoBitmap.getWidth()))); } if (mOnRangeKLineListener!=null) mOnRangeKLineListener.onRangeKLine(mStartIndex,mEndIndex); } public void onTouchEvent(@NotNull MotionEvent event) { float currentX; float currentY; switch (event.getAction()) { case MotionEvent.ACTION_DOWN: case MotionEvent.ACTION_MOVE: case MotionEvent.ACTION_UP: case MotionEvent.ACTION_CANCEL: currentX = event.getX(); currentY = event.getY(); //根据当前触摸点定位对应的K线 //拖动ico 改变开始的K线 if (mStartRect.contains(currentX, currentY)) { mStartIndex = getEntryIndexByCoordinate(currentX, currentY); if (Math.abs(mEndIndex - mStartIndex) == 2){ mEndIndex++; } chart.postInvalidate(); // System.out.println("9528 我点到了左边 " + mStartIndex); } //拖动ico 改变结束的K线 if (mEndRect.contains(currentX, currentY)) { mEndIndex = getEntryIndexByCoordinate(currentX, currentY); if (mEndIndex - mStartIndex == 2){ mStartIndex--; } chart.postInvalidate(); } } } /** * 根据子当前Kline在数据集合的index获得缩放后对应的X轴坐标 * @param index 数据集合的index * @return X轴坐标 */ public float getScaleCoordinateByIndex(int index) { CandlestickDataSet candlestickDataSet = dataVaild(); int valueCount = candlestickDataSet.getEntryCount(); final float scale = 1.0f / mViewport.width(); float candleWidth = candlestickDataSet.getCandleWidth(); final float visibleRange = candlestickDataSet.getVisibleRange(mViewport); if (candlestickDataSet.isAutoWidth()) { candleWidth = mContentRect.width() / Math.max(visibleRange, candlestickDataSet.getMinValueCount()); } final float step = mContentRect.width() * scale / valueCount; final float startX = mContentRect.left - mViewport.left * mContentRect.width() * scale; float startXPosition = startX + step * (index + candlestickDataSet.getStartIndexOffset()); return startXPosition + candleWidth * 0.5f; } /** * 数据有效且数据量大于6那么返回对应的数据集合,否则不返回 */ public CandlestickDataSet dataVaild() { List<CandlestickDataSet> dataSet = getDataSet(); if (getChartData() == null || dataSet == null || dataSet.size() <= 0) { return null; } else { CandlestickDataSet candlestickDataSet = dataSet.get(0); if (candlestickDataSet.getValues().size() < 6) { return null; } else { return dataSet.get(0); } } } @Override public void removeDataSet(CandlestickDataSet dataSet) { getChartData().remove(dataSet); calcDataSetMinMax(); } @Override public void clearDataSet() { getChartData().clear(); getChartData().calcMaxMin(mViewport, mContentRect); } @Override protected List<CandlestickDataSet> getDataSet() { return chartData.getDataSets(); } @Override public ChartData<CandlestickDataSet> getChartData() { if (chartData == null) chartData = new CandlestickData(); return chartData; } /** * 重置数据 */ public void resetData() { if (mStartCandlestickValue != null && mEndCandlestickValue != null) { mStartCandlestickValue = null; mEndCandlestickValue = null; } } /** * @return 线条颜色 */ public int getLineColor() { return mLineColor; } /** * @param mLineColor 设置线条指定的颜色 */ public void setLineColor(int mLineColor) { this.mLineColor = mLineColor; } /** * @return 区间统计颜色 */ public int getRangeColor() { return mRangeColor; } /** * @param mRangeColor 设置区间统计指定的颜色 */ public void setRangeColor(int mRangeColor) { this.mRangeColor = mRangeColor; } /** * 设置区间统计ico图标 * * @param ico 设置指定的Bitmap */ public void setRangeIcoBitmap(Bitmap ico) { this.icoBitmap = ico; } /** * 区间统计监听器 */ public interface OnRangeListener { /** * 区间统计坐标 * * @param startX 开始的X坐标 * @param endX 结束的X坐标 */ void onRange(float startX, float endX); } /** * 设置区间统计范围的监听器 用于更新关闭按钮的所在位置(X轴坐标) * * @param listener 监听器 */ public void setOnRangeListener(OnRangeListener listener) { this.mOnRangeListener = listener; } /** * 监听K线是否可见 */ public interface OnRangeKLineVisibleListener { /** * @param visible true为可见 */ void onRangeKLineVisible(boolean visible); } /** * 设置区间统计可见KLine监听器 * * @param listener 监听器 */ public void setOnRangeKLineVisibleListener(OnRangeKLineVisibleListener listener) { this.mOnRangeKLineVisibleListener = listener; } /** * 监听K线是否可见 */ public interface OnRangeKLineListener { /** * * @param startIndex 开始的index * @param endIndex 结束的index */ void onRangeKLine(int startIndex , int endIndex); } /** * 设置区间统计可见KLine监听器 * * @param listener 监听器 */ public void setOnRangeKLineListener(OnRangeKLineListener listener) { this.mOnRangeKLineListener = listener; } }
chart/src/main/java/cn/jingzhuan/lib/chart2/renderer/RangeRenderer.java
package cn.jingzhuan.lib.chart2.renderer; import android.graphics.Bitmap; import android.graphics.Canvas; import android.graphics.Color; import android.graphics.Paint; import android.graphics.RectF; import android.support.annotation.NonNull; import android.view.MotionEvent; import org.jetbrains.annotations.NotNull; import java.util.List; import cn.jingzhuan.lib.chart.Viewport; import cn.jingzhuan.lib.chart.component.Highlight; import cn.jingzhuan.lib.chart.data.CandlestickData; import cn.jingzhuan.lib.chart.data.CandlestickDataSet; import cn.jingzhuan.lib.chart.data.CandlestickValue; import cn.jingzhuan.lib.chart.data.ChartData; import cn.jingzhuan.lib.chart.event.OnViewportChangeListener; import cn.jingzhuan.lib.chart2.base.Chart; /** * 区间统计Renderer */ public class RangeRenderer extends AbstractDataRenderer<CandlestickDataSet> { private CandlestickData chartData; /** * 绘制左侧的ico x的坐标 */ float mStartX = 0; /** * 绘制右侧ico 的x坐标 */ float mEndX = 0; /** * 绘制的ico */ Bitmap icoBitmap; /** * 左侧的ico的矩形区域 */ RectF mStartRect; /** * 右侧ico的矩形区域 */ RectF mEndRect; /** * 用于划线 */ Paint paint = new Paint(); /** * 中间阴影 */ Paint shadowPaint = new Paint(); Chart chart; private OnRangeListener mOnRangeListener; private OnRangeKLineVisibleListener mOnRangeKLineVisibleListener; private OnRangeKLineListener mOnRangeKLineListener; private CandlestickValue mStartCandlestickValue; private CandlestickValue mEndCandlestickValue; //线条颜色 默认蓝色 private int mLineColor = Color.parseColor("#216FE1"); //区间颜色 private int mRangeColor = Color.parseColor("#66D8F2FD"); //开始的index private int mStartIndex; //结束的index private int mEndIndex; public RangeRenderer(Chart chart) { super(chart); this.chart = chart; initPaint(); chart.setInternalViewportChangeListener(new OnViewportChangeListener() { @Override public void onViewportChange(Viewport viewport) { mViewport.set(viewport); calcDataSetMinMax(); } }); } @Override protected void renderDataSet(Canvas canvas, ChartData<CandlestickDataSet> chartData) { drawCanvas(canvas); } public void initPaint() { paint.setAntiAlias(true); paint.setColor(getLineColor()); paint.setSubpixelText(true); paint.setStrokeWidth(3); shadowPaint = new Paint(paint); shadowPaint.setStyle(Paint.Style.FILL); shadowPaint.setColor(getRangeColor()); } @Override public void renderHighlighted(Canvas canvas, @NonNull @NotNull Highlight[] highlights) { } public void drawCanvas(Canvas canvas) { CandlestickDataSet candlestickDataSet = dataVaild(); if (candlestickDataSet == null) return; //默认选中数据中最后10个K线作为统计范围 if (mStartCandlestickValue == null || mEndCandlestickValue == null) { List<CandlestickValue> visiblePoints = candlestickDataSet.getVisiblePoints(mViewport); CandlestickValue startVisible = visiblePoints.get(visiblePoints.size() - 10); CandlestickValue endVisible = visiblePoints.get(visiblePoints.size() - 1); float startVisibleX = startVisible.getX(); float startVisibleY = startVisible.getY(); float endVisibleX = endVisible.getX(); float endVisibleY = endVisible.getY(); mStartIndex = getEntryIndexByCoordinate(startVisibleX, startVisibleY); mEndIndex = getEntryIndexByCoordinate(endVisibleX, endVisibleY); } mStartCandlestickValue = candlestickDataSet.getEntryForIndex(mStartIndex); mEndCandlestickValue = candlestickDataSet.getEntryForIndex(mEndIndex); /* 获取区间统计开始的K线坐标 */ mStartX = getScaleCoordinateByIndex(mStartIndex); /* * 获取区间统计结束的K线坐标 */ mEndX = getScaleCoordinateByIndex(mEndIndex); float bitmapSpanX = icoBitmap.getWidth() / 2f; float bitmapSpanY = icoBitmap.getHeight() / 2f; RectF rect = new RectF(mStartX, 0, mEndX, chart.getContentRect().height()); // System.out.println("9529 mStartX :" + mStartX + candlestickDataSet); //绘制区间统计的选择区域 canvas.drawRect(rect, shadowPaint); /* * 根据K线数据的中点绘制线条 */ canvas.drawLine(mStartX, 0, mStartX, chart.getContentRect().height(), paint); canvas.drawLine(mEndX, 0, mEndX, chart.getContentRect().height(), paint); // System.out.println("9529 current drawLine " + currentViewport.left + "," + currentViewport.right); // System.out.println("9529 mContent left : " + mContentRect.left + " , right : " + mContentRect.right); /* * 绘制ico */ if (icoBitmap != null){ canvas.drawBitmap(icoBitmap, mStartX - bitmapSpanX, chart.getContentRect().height() / 2f - bitmapSpanY, paint); canvas.drawBitmap(icoBitmap, mEndX - bitmapSpanX, chart.getContentRect().height() / 2f - bitmapSpanY, paint); } /* *为了更好的能拖动区间 加大了触发拖动的范围 */ float defaultSpanX = 0; float defaultSpanY = 0; /* * 创建开始&结束矩阵 用于判断触摸点是否在该区域内 * true -> 改变区间统计范围 * false -> 不作反应 */ mStartRect = new RectF( mStartX - bitmapSpanX - defaultSpanX, chart.getContentRect().height() / 2f - bitmapSpanY - defaultSpanY, mStartX + bitmapSpanX + defaultSpanX, chart.getContentRect().height() / 2f + bitmapSpanY + defaultSpanY); mEndRect = new RectF( mEndX - bitmapSpanX - defaultSpanX, chart.getContentRect().height() / 2f - bitmapSpanY - defaultSpanY, mEndX + bitmapSpanX + defaultSpanX, chart.getContentRect().height() / 2f + bitmapSpanY + defaultSpanY); //回调区间X轴坐标的范围 if (mOnRangeListener != null) mOnRangeListener.onRange(mStartX, mEndX); /* * 缩放限制 * 当K线被缩放到屏幕外(不可见)的情况下 关闭缩放 */ if (mOnRangeKLineVisibleListener != null) { mOnRangeKLineVisibleListener.onRangeKLineVisible((mStartX > (mContentRect.left + icoBitmap.getWidth()) && mEndX < (mContentRect.width() - icoBitmap.getWidth()))); } if (mOnRangeKLineListener!=null) mOnRangeKLineListener.onRangeKLine(mStartIndex,mEndIndex); } public void onTouchEvent(@NotNull MotionEvent event) { float currentX; float currentY; switch (event.getAction()) { case MotionEvent.ACTION_DOWN: case MotionEvent.ACTION_MOVE: case MotionEvent.ACTION_UP: case MotionEvent.ACTION_CANCEL: currentX = event.getX(); currentY = event.getY(); //根据当前触摸点定位对应的K线 //拖动ico 改变开始的K线 if (mStartRect.contains(currentX, currentY)) { mStartIndex = getEntryIndexByCoordinate(currentX, currentY); if (Math.abs(mEndIndex - mStartIndex) == 2){ mEndIndex++; } chart.postInvalidate(); // System.out.println("9528 我点到了左边 " + mStartIndex); } //拖动ico 改变结束的K线 if (mEndRect.contains(currentX, currentY)) { mEndIndex = getEntryIndexByCoordinate(currentX, currentY); if (mEndIndex - mStartIndex == 2){ mStartIndex--; } chart.postInvalidate(); } } } /** * 根据子当前Kline在数据集合的index获得缩放后对应的X轴坐标 * @param index 数据集合的index * @return X轴坐标 */ public float getScaleCoordinateByIndex(int index) { CandlestickDataSet candlestickDataSet = dataVaild(); int valueCount = candlestickDataSet.getEntryCount(); final float scale = 1.0f / mViewport.width(); float candleWidth = candlestickDataSet.getCandleWidth(); final float visibleRange = candlestickDataSet.getVisibleRange(mViewport); if (candlestickDataSet.isAutoWidth()) { candleWidth = mContentRect.width() / Math.max(visibleRange, candlestickDataSet.getMinValueCount()); } final float step = mContentRect.width() * scale / valueCount; final float startX = mContentRect.left - mViewport.left * mContentRect.width() * scale; float startXPosition = startX + step * (index + candlestickDataSet.getStartIndexOffset()); return startXPosition + candleWidth * 0.5f; } /** * 数据有效且数据量大于6那么返回对应的数据集合,否则不返回 */ public CandlestickDataSet dataVaild() { List<CandlestickDataSet> dataSet = getDataSet(); if (getChartData() == null || dataSet == null || dataSet.size() <= 0) { return null; } else { CandlestickDataSet candlestickDataSet = dataSet.get(0); if (candlestickDataSet.getValues().size() < 6) { return null; } else { return dataSet.get(0); } } } @Override public void removeDataSet(CandlestickDataSet dataSet) { getChartData().remove(dataSet); calcDataSetMinMax(); } @Override public void clearDataSet() { getChartData().clear(); getChartData().calcMaxMin(mViewport, mContentRect); } @Override protected List<CandlestickDataSet> getDataSet() { return chartData.getDataSets(); } @Override public ChartData<CandlestickDataSet> getChartData() { if (chartData == null) chartData = new CandlestickData(); return chartData; } /** * 重置数据 */ public void resetData() { if (mStartCandlestickValue != null && mEndCandlestickValue != null) { mStartCandlestickValue = null; mEndCandlestickValue = null; } } /** * @return 线条颜色 */ public int getLineColor() { return mLineColor; } /** * @param mLineColor 设置线条指定的颜色 */ public void setLineColor(int mLineColor) { this.mLineColor = mLineColor; } /** * @return 区间统计颜色 */ public int getRangeColor() { return mRangeColor; } /** * @param mRangeColor 设置区间统计指定的颜色 */ public void setRangeColor(int mRangeColor) { this.mRangeColor = mRangeColor; } /** * 设置区间统计ico图标 * * @param ico 设置指定的Bitmap */ public void setRangeIcoBitmap(Bitmap ico) { this.icoBitmap = ico; } /** * 区间统计监听器 */ public interface OnRangeListener { /** * 区间统计坐标 * * @param startX 开始的X坐标 * @param endX 结束的X坐标 */ void onRange(float startX, float endX); } /** * 设置区间统计范围的监听器 用于更新关闭按钮的所在位置(X轴坐标) * * @param listener 监听器 */ public void setOnRangeListener(OnRangeListener listener) { this.mOnRangeListener = listener; } /** * 监听K线是否可见 */ public interface OnRangeKLineVisibleListener { /** * @param visible true为可见 */ void onRangeKLineVisible(boolean visible); } /** * 设置区间统计可见KLine监听器 * * @param listener 监听器 */ public void setOnRangeKLineVisibleListener(OnRangeKLineVisibleListener listener) { this.mOnRangeKLineVisibleListener = listener; } /** * 监听K线是否可见 */ public interface OnRangeKLineListener { /** * * @param startIndex 开始的index * @param endIndex 结束的index */ void onRangeKLine(int startIndex , int endIndex); } /** * 设置区间统计可见KLine监听器 * * @param listener 监听器 */ public void setOnRangeKLineListener(OnRangeKLineListener listener) { this.mOnRangeKLineListener = listener; } }
添加index坐标判断防报错
chart/src/main/java/cn/jingzhuan/lib/chart2/renderer/RangeRenderer.java
添加index坐标判断防报错
<ide><path>hart/src/main/java/cn/jingzhuan/lib/chart2/renderer/RangeRenderer.java <ide> } <ide> mStartCandlestickValue = candlestickDataSet.getEntryForIndex(mStartIndex); <ide> mEndCandlestickValue = candlestickDataSet.getEntryForIndex(mEndIndex); <del> <add> if (mStartIndex >= candlestickDataSet.getValues().size() || mEndIndex >= candlestickDataSet.getValues().size()) <add> return; <ide> /* <ide> 获取区间统计开始的K线坐标 <ide> */
Java
mit
5788f234fd4778c067bc82d1a22e5d83e5c7746b
0
Maferdelgado/TravisCIMafer
package traviscimafer; import javax.swing.*; /** * * Autora:Mafer Delgado */ public class TravisCIMafer { public static void main(String[] args) { System.out.println("Universidad Laica Eloy Alfaro de Manabí"); System.out.println("Práctica TravisCI"); System.out.println("Integración Continua con TravisCI y GitHUB"); System.out.println("Calculadora Básica"); System.out.println("Ingeniería de Software"); System.out.println("Ing. Diego Toala"); System.out.println("María Fernanda"); System.out.println("Delgado Guerrero"); int op=0; double n1,n2,multiplicacion,suma,division,resta; do{ op=Integer.parseInt(JOptionPane.showInputDialog("nCalculadoran"+ "************n"+ "[1] SUMARn"+ "[2] RESTARn"+ "[3] MULTIPLICARn"+ "[4] DIVIDIRn"+ "[5] SALIRn"+ "Ingresa una opción:")); switch(op) { case 1: n1=Double.parseDouble(JOptionPane.showInputDialog("Ingrese número 1")); n2=Double.parseDouble(JOptionPane.showInputDialog("Ingrese número 2")); suma=n1+n2; JOptionPane.showMessageDialog(null,"La suma es:"+suma); break; case 2: n1=Double.parseDouble(JOptionPane.showInputDialog("Ingrese número 1")); n2=Double.parseDouble(JOptionPane.showInputDialog("Ingrese número 2")); resta=n1-n2; JOptionPane.showMessageDialog(null,"La resta es:"+resta); break; case 3: n1=Double.parseDouble(JOptionPane.showInputDialog("Ingrese número 1")); n2=Double.parseDouble(JOptionPane.showInputDialog("Ingrese número 2")); multiplicacion=n1*n2; JOptionPane.showMessageDialog(null,"La multiplicación es:"+multiplicacion); break; case 4: n1=Double.parseDouble(JOptionPane.showInputDialog("Ingrese número 1")); n2=Double.parseDouble(JOptionPane.showInputDialog("Ingrese número 2")); division=n1/n2; JOptionPane.showMessageDialog(null,"La división es:"+division); break; } }while(op!=5); } }
src/traviscimafer/TravisCIMafer.java
package traviscimafer; import javax.swing.*; /** * * Autora:Mafer Delgado */ public class TravisCIMafer { public static void main(String[] args) { System.out.println("Universidad Laica Eloy Alfaro de Manabí"); System.out.println("Práctica TravisCI"); System.out.println("Integración Continua con TravisCI y GitHUB"); System.out.println("Calculadora Básica"); System.out.println("Ingeniería de Software"); System.out.println("Ing. Diego Toala"); System.out.println("María Fernanda"); int op=0; double n1,n2,multiplicacion,suma,division,resta; do{ op=Integer.parseInt(JOptionPane.showInputDialog("nCalculadoran"+ "************n"+ "[1] SUMARn"+ "[2] RESTARn"+ "[3] MULTIPLICARn"+ "[4] DIVIDIRn"+ "[5] SALIRn"+ "Ingresa una opción:")); switch(op) { case 1: n1=Double.parseDouble(JOptionPane.showInputDialog("Ingrese número 1")); n2=Double.parseDouble(JOptionPane.showInputDialog("Ingrese número 2")); suma=n1+n2; JOptionPane.showMessageDialog(null,"La suma es:"+suma); break; case 2: n1=Double.parseDouble(JOptionPane.showInputDialog("Ingrese número 1")); n2=Double.parseDouble(JOptionPane.showInputDialog("Ingrese número 2")); resta=n1-n2; JOptionPane.showMessageDialog(null,"La resta es:"+resta); break; case 3: n1=Double.parseDouble(JOptionPane.showInputDialog("Ingrese número 1")); n2=Double.parseDouble(JOptionPane.showInputDialog("Ingrese número 2")); multiplicacion=n1*n2; JOptionPane.showMessageDialog(null,"La multiplicación es:"+multiplicacion); break; case 4: n1=Double.parseDouble(JOptionPane.showInputDialog("Ingrese número 1")); n2=Double.parseDouble(JOptionPane.showInputDialog("Ingrese número 2")); division=n1/n2; JOptionPane.showMessageDialog(null,"La división es:"+division); break; } }while(op!=5); } }
Hola TravisCI....
src/traviscimafer/TravisCIMafer.java
Hola TravisCI....
<ide><path>rc/traviscimafer/TravisCIMafer.java <ide> System.out.println("Ingeniería de Software"); <ide> System.out.println("Ing. Diego Toala"); <ide> System.out.println("María Fernanda"); <add> System.out.println("Delgado Guerrero"); <ide> int op=0; <ide> double n1,n2,multiplicacion,suma,division,resta; <ide> do{
Java
apache-2.0
a3752178de307e003e2eee41ed0b5caae8f527ac
0
arconsis/droitatedDB,arconsis/datarobot
/* * Copyright (C) 2014 The droitated DB Authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.droitateddb; import android.content.Context; import android.database.Cursor; import android.database.sqlite.SQLiteDatabase; import org.droitateddb.cursor.CombinedCursorImpl; import org.droitateddb.schema.AbstractAttribute; import org.droitateddb.schema.ToManyAssociation; import org.droitateddb.schema.ToOneAssociation; import java.lang.reflect.Field; import java.util.*; import static org.droitateddb.CursorOperation.tryOnCursor; import static org.droitateddb.SchemaUtil.*; import static org.droitateddb.Utilities.*; import static org.droitateddb.schema.SchemaConstants.*; /** * Resolves entity object graphs from the db. * * @author Falk Appel * @author Alexander Frank */ class DatabaseResolver { private final Map<String, Object> loadedObjects; private final Context context; private final SQLiteDatabase database; public DatabaseResolver(final Context context, final SQLiteDatabase database) { this.context = context; this.database = database; loadedObjects = new HashMap<String, Object>(); } public void resolve(final Object data, final int currentDepth, final int maxDepth) { // 1. load associated ids for data // 2. check if (Type/id) tuple is in map if yes 5. else 3. // 3. load object from db // 4. put loaded object into map // 5. set object to data // 6. resolve associations of loaded object to given depth if (currentDepth >= maxDepth) { return; } EntityData entityData = EntityData.getEntityData(data); if (entityData.allAssociations.size() > 0) { Class<?> associationsDeclaration = getAssociationsSchema(data.getClass(), context.getPackageName()); Number id = getPrimaryKey(data, entityData); if (id != null) { loadedObjects.put("class " + data.getClass().getCanonicalName() + "#" + id, data); for (Field associationField : entityData.allAssociations) { Object declaration = getDeclaration(associationsDeclaration, associationField); if (declaration instanceof ToOneAssociation) { handleToOneAssociation(id, data, associationField, (ToOneAssociation) declaration, currentDepth, maxDepth); } else { handleToManyAssociation(id, data, associationField, (ToManyAssociation) declaration, currentDepth, maxDepth); } } } } } private void handleToOneAssociation(final Number idRequestingObject, final Object requestingObject, final Field associationField, final ToOneAssociation toOneAssociation, final int currentDepth, final int maxDepth) { String keyName = EntityData.getEntityData(requestingObject).primaryKey.getName(); Cursor fkCursor = database.query(getTableName(requestingObject.getClass(), context.getPackageName()), new String[]{ toOneAssociation.getAssociationAttribute().columnName()}, keyName + " = ?", new String[]{idRequestingObject.toString()}, null, null, null); tryOnCursor(fkCursor, new CursorOperation<Void>() { @Override public Void execute(final Cursor cursor) throws Exception { if (cursor.moveToFirst() && cursor.getType(0) != Cursor.FIELD_TYPE_NULL) { attachAssociation(cursor.getInt(0), associationField, requestingObject, toOneAssociation, currentDepth, maxDepth); } return null; } }); } private void attachAssociation(final int id, final Field associationField, final Object requestingObject, final ToOneAssociation declaration, final int currentDepth, final int maxDepth) { String mixedId = "class " + declaration.getAssociatedType().getCanonicalName() + "#" + id; if (loadedObjects.containsKey(mixedId)) { setFieldValue(associationField, requestingObject, loadedObjects.get(mixedId)); } else { loadFromDatabase(id, associationField, requestingObject, declaration, currentDepth, maxDepth); } } private void loadFromDatabase(final int id, final Field associationField, final Object requestingObject, final ToOneAssociation declaration, final int currentDepth, final int maxDepth) { Cursor associationCursor = database.query(getTableName(declaration.getAssociatedType(), context.getPackageName()), null, EntityData.getEntityData(declaration.getAssociatedType()).primaryKey.getName() + "=?", new String[]{Integer.toString(id)}, null, null, null); tryOnCursor(associationCursor, new CursorOperation<Void>() { @Override public Void execute(final Cursor cursor) { if (cursor.moveToFirst()) { Object association = CombinedCursorImpl.create(context, cursor, getEntityInfo(declaration.getAssociatedType(), context.getPackageName()), declaration .getAssociatedType()).getCurrent(); setFieldValue(associationField, requestingObject, association); loadedObjects.put(declaration.getAssociatedType().getCanonicalName() + "#" + id, association); resolve(association, currentDepth + 1, maxDepth); } return null; } }); } private void handleToManyAssociation(final Number primaryKeyData, final Object data, final Field associationField, final ToManyAssociation toMany, final int currentDepth, final int maxDepth) { final AbstractAttribute foreignAttribute = getForeignAttribute(toMany); if (foreignAttribute != null) { EntityData entityData = EntityData.getEntityData(foreignAttribute.type()); if (getFieldValue(data, associationField) != null) { for (Object object : getCollection(data, associationField)) { resolve(object, currentDepth + 1, maxDepth); loadedObjects.put(foreignAttribute.type() + "#" + getPrimaryKey(object, entityData), object); } } Collection<Object> target = new ArrayList<Object>(); setFieldValue(associationField, data, target); List<Number> ids = loadIdsFromLinkTable(primaryKeyData, data.getClass(), foreignAttribute, toMany); for (final Number id : ids) { final String mixedId = foreignAttribute.type() + "#" + id; if (loadedObjects.containsKey(mixedId)) { target.add(loadedObjects.get(mixedId)); } else { String primaryKeyName = entityData.primaryKey.getName(); Cursor cursor = database.query(getTableName(foreignAttribute.type(), context.getPackageName()), null, primaryKeyName + "= ?", new String[]{id.toString()}, null, null, null); Object linkedObject = tryOnCursor(cursor, new CursorOperation<Object>() { @Override public Object execute(final Cursor cursor) { if (cursor.getCount() > 0) { Object loaded = CombinedCursorImpl.create(context, cursor, getEntityInfo(foreignAttribute.type(), context.getPackageName()), foreignAttribute .type()).getOne(); loadedObjects.put(mixedId, loaded); resolve(loaded, currentDepth + 1, maxDepth); return loaded; } else { return null; } } }); if (linkedObject != null) { target.add(linkedObject); } } } } } @SuppressWarnings("unchecked") private Collection<Object> getCollection(final Object data, final Field associationField) { return new ArrayList<Object>((Collection<Object>) getFieldValue(data, associationField)); } private AbstractAttribute getForeignAttribute(final ToManyAssociation toMany) { for (AbstractAttribute attribute : getLinkTableColumns(toMany.getLinkTableSchema())) { if (attribute.columnName().endsWith(TO_SUFFIX)) { return attribute; } } return null; } private List<Number> loadIdsFromLinkTable( final Number primaryKeyData, final Class<?> dataClass, final AbstractAttribute foreignAttribute, final ToManyAssociation toMany) { String tableName = getLinkTableName(toMany.getLinkTableSchema()); String columnName = FOREIGN_KEY + dataClass.getSimpleName().toLowerCase(Locale.getDefault()) + FROM_SUFFIX; Cursor cursor = database.query(tableName, null, columnName + " = ?", new String[]{primaryKeyData.toString()}, null, null, null); return tryOnCursor( cursor, new CursorOperation<List<Number>>() { @Override public List<Number> execute(final Cursor cursor) throws Exception { LinkedList<Number> ids = new LinkedList<Number>(); while (cursor.moveToNext()) { ids.add((Number) foreignAttribute.getValueFromCursor(cursor)); } return ids; } }); } private static Object getDeclaration(final Class<?> associationsDeclaration, final Field associationField) { try { return associationsDeclaration.getField(associationField.getName().toUpperCase(Locale.getDefault())).get(null); } catch (Exception e) { throw handle(e); } } }
droitatedDB/src/main/java/org/droitateddb/DatabaseResolver.java
/* * Copyright (C) 2014 The droitated DB Authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.droitateddb; import android.content.Context; import android.database.Cursor; import android.database.sqlite.SQLiteDatabase; import org.droitateddb.cursor.CombinedCursorImpl; import org.droitateddb.schema.AbstractAttribute; import org.droitateddb.schema.ToManyAssociation; import org.droitateddb.schema.ToOneAssociation; import java.lang.reflect.Field; import java.util.*; import static org.droitateddb.CursorOperation.tryOnCursor; import static org.droitateddb.SchemaUtil.*; import static org.droitateddb.Utilities.*; import static org.droitateddb.schema.SchemaConstants.*; /** * Resolves entity object graphs from the db. * * @author Falk Appel * @author Alexander Frank */ class DatabaseResolver { private final Map<String, Object> loadedObjects; private final Context context; private final SQLiteDatabase database; public DatabaseResolver(final Context context, final SQLiteDatabase database) { this.context = context; this.database = database; loadedObjects = new HashMap<String, Object>(); } public void resolve(final Object data, final int currentDepth, final int maxDepth) { // 1. load associated ids for data // 2. check if (Type/id) tuple is in map if yes 5. else 3. // 3. load object from db // 4. put loaded object into map // 5. set object to data // 6. resolve associations of loaded object to given depth if (currentDepth >= maxDepth) { return; } EntityData entityData = EntityData.getEntityData(data); if (entityData.allAssociations.size() > 0) { Class<?> associationsDeclaration = getAssociationsSchema(data.getClass(), context.getPackageName()); Number id = getPrimaryKey(data, entityData); if (id != null) { loadedObjects.put("class " + data.getClass().getCanonicalName() + "#" + id, data); for (Field associationField : entityData.allAssociations) { Object declaration = getDeclaration(associationsDeclaration, associationField); if (declaration instanceof ToOneAssociation) { handleToOneAssociation(id, data, associationField, (ToOneAssociation) declaration, currentDepth, maxDepth); } else { handleToManyAssociation(id, data, associationField, (ToManyAssociation) declaration, currentDepth, maxDepth); } } } } } private void handleToOneAssociation(final Number idRequestingObject, final Object requestingObject, final Field associationField, final ToOneAssociation toOneAssociation, final int currentDepth, final int maxDepth) { String keyName = EntityData.getEntityData(requestingObject).primaryKey.getName(); Cursor fkCursor = database.query(getTableName(requestingObject.getClass(), context.getPackageName()), new String[]{ toOneAssociation.getAssociationAttribute().columnName()}, keyName + " = ?", new String[]{idRequestingObject.toString()}, null, null, null); tryOnCursor(fkCursor, new CursorOperation<Void>() { @Override public Void execute(final Cursor cursor) throws Exception { if (cursor.moveToFirst() && cursor.getType(0) != Cursor.FIELD_TYPE_NULL) { attachAssociation(cursor.getInt(0), associationField, requestingObject, toOneAssociation, currentDepth, maxDepth); } return null; } }); } private void attachAssociation(final int id, final Field associationField, final Object requestingObject, final ToOneAssociation declaration, final int currentDepth, final int maxDepth) { String mixedId = "class " + declaration.getAssociatedType().getCanonicalName() + "#" + id; if (loadedObjects.containsKey(mixedId)) { setFieldValue(associationField, requestingObject, loadedObjects.get(mixedId)); } else { loadFromDatabase(id, associationField, requestingObject, declaration, currentDepth, maxDepth); } } private void loadFromDatabase(final int id, final Field associationField, final Object requestingObject, final ToOneAssociation declaration, final int currentDepth, final int maxDepth) { Cursor associationCursor = database.query(getTableName(declaration.getAssociatedType(), context.getPackageName()), null, EntityData.getEntityData(declaration.getAssociatedType()).primaryKey.getName() + "=?", new String[]{Integer.toString(id)}, null, null, null); tryOnCursor(associationCursor, new CursorOperation<Void>() { @Override public Void execute(final Cursor cursor) { if (cursor.moveToFirst()) { Object association = CombinedCursorImpl.create(context, cursor, getEntityInfo(declaration.getAssociatedType(), context.getPackageName()), declaration .getAssociatedType()).getCurrent(); setFieldValue(associationField, requestingObject, association); loadedObjects.put(declaration.getAssociatedType().getCanonicalName() + "#" + id, association); resolve(association, currentDepth + 1, maxDepth); } return null; } }); } private void handleToManyAssociation(final Number primaryKeyData, final Object data, final Field associationField, final ToManyAssociation toMany, final int currentDepth, final int maxDepth) { final AbstractAttribute foreignAttribute = getForeignAttribute(toMany); if (foreignAttribute != null) { EntityData entityData = EntityData.getEntityData(foreignAttribute.type()); if (getFieldValue(data, associationField) != null) { for (Object object : getCollection(data, associationField)) { resolve(object, currentDepth + 1, maxDepth); loadedObjects.put(foreignAttribute.type() + "#" + getPrimaryKey(object, entityData), object); } } Collection<Object> target = new ArrayList<Object>(); setFieldValue(associationField, data, target); List<Integer> ids = loadIdsFromLinkTable(primaryKeyData, data.getClass(), foreignAttribute, toMany); for (final Integer id : ids) { final String mixedId = foreignAttribute.type() + "#" + id; if (loadedObjects.containsKey(mixedId)) { target.add(loadedObjects.get(mixedId)); } else { String primaryKeyName = entityData.primaryKey.getName(); Cursor cursor = database.query(getTableName(foreignAttribute.type(), context.getPackageName()), null, primaryKeyName + "= ?", new String[]{Integer.toString(id)}, null, null, null); Object linkedObject = tryOnCursor(cursor, new CursorOperation<Object>() { @Override public Object execute(final Cursor cursor) { if (cursor.getCount() > 0) { Object loaded = CombinedCursorImpl.create(context, cursor, getEntityInfo(foreignAttribute.type(), context.getPackageName()), foreignAttribute .type()).getOne(); loadedObjects.put(mixedId, loaded); resolve(loaded, currentDepth + 1, maxDepth); return loaded; } else { return null; } } }); if (linkedObject != null) { target.add(linkedObject); } } } } } @SuppressWarnings("unchecked") private Collection<Object> getCollection(final Object data, final Field associationField) { return new ArrayList<Object>((Collection<Object>) getFieldValue(data, associationField)); } private AbstractAttribute getForeignAttribute(final ToManyAssociation toMany) { for (AbstractAttribute attribute : getLinkTableColumns(toMany.getLinkTableSchema())) { if (attribute.columnName().endsWith(TO_SUFFIX)) { return attribute; } } return null; } private List<Integer> loadIdsFromLinkTable(final Number primaryKeyData, final Class<?> dataClass, final AbstractAttribute foreignAttribute, final ToManyAssociation toMany) { String tableName = getLinkTableName(toMany.getLinkTableSchema()); String columnName = FOREIGN_KEY + dataClass.getSimpleName().toLowerCase(Locale.getDefault()) + FROM_SUFFIX; Cursor cursor = database.query(tableName, null, columnName + " = ?", new String[]{primaryKeyData.toString()}, null, null, null); return tryOnCursor(cursor, new CursorOperation<List<Integer>>() { @Override public List<Integer> execute(final Cursor cursor) throws Exception { LinkedList<Integer> ids = new LinkedList<Integer>(); while (cursor.moveToNext()) { ids.add((Integer) foreignAttribute.getValueFromCursor(cursor)); } return ids; } }); } private static Object getDeclaration(final Class<?> associationsDeclaration, final Field associationField) { try { return associationsDeclaration.getField(associationField.getName().toUpperCase(Locale.getDefault())).get(null); } catch (Exception e) { throw handle(e); } } }
take care of long when resolving dependencies
droitatedDB/src/main/java/org/droitateddb/DatabaseResolver.java
take care of long when resolving dependencies
<ide><path>roitatedDB/src/main/java/org/droitateddb/DatabaseResolver.java <ide> Collection<Object> target = new ArrayList<Object>(); <ide> setFieldValue(associationField, data, target); <ide> <del> List<Integer> ids = loadIdsFromLinkTable(primaryKeyData, data.getClass(), foreignAttribute, toMany); <del> for (final Integer id : ids) { <add> List<Number> ids = loadIdsFromLinkTable(primaryKeyData, data.getClass(), foreignAttribute, toMany); <add> for (final Number id : ids) { <ide> final String mixedId = foreignAttribute.type() + "#" + id; <ide> if (loadedObjects.containsKey(mixedId)) { <ide> target.add(loadedObjects.get(mixedId)); <ide> String primaryKeyName = entityData.primaryKey.getName(); <ide> <ide> Cursor cursor = database.query(getTableName(foreignAttribute.type(), context.getPackageName()), null, <del> primaryKeyName + "= ?", new String[]{Integer.toString(id)}, null, null, null); <add> primaryKeyName + "= ?", new String[]{id.toString()}, null, null, null); <ide> Object linkedObject = tryOnCursor(cursor, new CursorOperation<Object>() { <ide> @Override <ide> public Object execute(final Cursor cursor) { <ide> return null; <ide> } <ide> <del> private List<Integer> loadIdsFromLinkTable(final Number primaryKeyData, final Class<?> dataClass, final AbstractAttribute foreignAttribute, final <del> ToManyAssociation toMany) { <add> private List<Number> loadIdsFromLinkTable( <add> final Number primaryKeyData, final Class<?> dataClass, final AbstractAttribute foreignAttribute, final ToManyAssociation toMany) { <ide> String tableName = getLinkTableName(toMany.getLinkTableSchema()); <ide> String columnName = FOREIGN_KEY + dataClass.getSimpleName().toLowerCase(Locale.getDefault()) + FROM_SUFFIX; <ide> <ide> Cursor cursor = database.query(tableName, null, columnName + " = ?", new String[]{primaryKeyData.toString()}, null, null, null); <del> return tryOnCursor(cursor, new CursorOperation<List<Integer>>() { <add> return tryOnCursor( <add> cursor, new CursorOperation<List<Number>>() { <ide> @Override <del> public List<Integer> execute(final Cursor cursor) throws Exception { <del> LinkedList<Integer> ids = new LinkedList<Integer>(); <add> public List<Number> execute(final Cursor cursor) throws Exception { <add> LinkedList<Number> ids = new LinkedList<Number>(); <ide> while (cursor.moveToNext()) { <del> ids.add((Integer) foreignAttribute.getValueFromCursor(cursor)); <add> ids.add((Number) foreignAttribute.getValueFromCursor(cursor)); <ide> } <ide> return ids; <ide> }
JavaScript
apache-2.0
cfee53e59606b3ce7e9b96ce59a851a0510c99dd
0
ebdrup/nodebase
describe("When running tests", function () { it("should have sinon defined", function () { expect(sinon).to.be.ok; }); it("should have expect defined", function () { expect(expect).to.be.ok; }); });
test/unit/globals.spec.js
"use strict"; describe("When running tests", function () { it("should have sinon defined", function () { expect(sinon).to.be.ok; }); it("should have expect defined", function () { expect(expect).to.be.ok; }); });
Update globals.spec.js
test/unit/globals.spec.js
Update globals.spec.js
<ide><path>est/unit/globals.spec.js <del>"use strict"; <ide> describe("When running tests", function () { <ide> <ide> it("should have sinon defined", function () {
Java
apache-2.0
error: pathspec 'drools-core/src/main/java/org/drools/workflow/core/node/EventNode.java' did not match any file(s) known to git
93f22a15994deb87b26945bf8a70a133e8516f54
1
amckee23/drools,ngs-mtech/drools,TonnyFeng/drools,jomarko/drools,Buble1981/MyDroolsFork,iambic69/drools,mrrodriguez/drools,winklerm/drools,kevinpeterson/drools,sutaakar/drools,mrrodriguez/drools,rajashekharmunthakewill/drools,romartin/drools,lanceleverich/drools,manstis/drools,lanceleverich/drools,sotty/drools,reynoldsm88/drools,amckee23/drools,sotty/drools,iambic69/drools,ngs-mtech/drools,HHzzhz/drools,prabasn/drools,kedzie/drools-android,lanceleverich/drools,droolsjbpm/drools,yurloc/drools,TonnyFeng/drools,ThiagoGarciaAlves/drools,iambic69/drools,292388900/drools,Buble1981/MyDroolsFork,OnePaaS/drools,mrietveld/drools,ngs-mtech/drools,ThomasLau/drools,jiripetrlik/drools,jomarko/drools,manstis/drools,droolsjbpm/drools,iambic69/drools,iambic69/drools,ChallenHB/drools,HHzzhz/drools,rajashekharmunthakewill/drools,vinodkiran/drools,jiripetrlik/drools,romartin/drools,manstis/drools,liupugong/drools,lanceleverich/drools,kedzie/drools-android,Buble1981/MyDroolsFork,sotty/drools,pperboires/PocDrools,ThomasLau/drools,292388900/drools,vinodkiran/drools,HHzzhz/drools,mrrodriguez/drools,HHzzhz/drools,amckee23/drools,prabasn/drools,manstis/drools,winklerm/drools,TonnyFeng/drools,sutaakar/drools,liupugong/drools,kedzie/drools-android,292388900/drools,ChallenHB/drools,ChallenHB/drools,ThomasLau/drools,jiripetrlik/drools,psiroky/drools,liupugong/drools,mrietveld/drools,mrrodriguez/drools,rajashekharmunthakewill/drools,liupugong/drools,TonnyFeng/drools,vinodkiran/drools,mrietveld/drools,reynoldsm88/drools,jiripetrlik/drools,reynoldsm88/drools,winklerm/drools,ngs-mtech/drools,jomarko/drools,sotty/drools,winklerm/drools,ngs-mtech/drools,yurloc/drools,droolsjbpm/drools,ChallenHB/drools,kedzie/drools-android,kevinpeterson/drools,romartin/drools,sutaakar/drools,kevinpeterson/drools,mrietveld/drools,pperboires/PocDrools,ThomasLau/drools,lanceleverich/drools,mswiderski/drools,prabasn/drools,sutaakar/drools,sutaakar/drools,ThiagoGarciaAlves/drools,ThiagoGarciaAlves/drools,psiroky/drools,OnePaaS/drools,sotty/drools,TonnyFeng/drools,ThiagoGarciaAlves/drools,psiroky/drools,romartin/drools,pperboires/PocDrools,romartin/drools,pperboires/PocDrools,pwachira/droolsexamples,winklerm/drools,rajashekharmunthakewill/drools,psiroky/drools,manstis/drools,OnePaaS/drools,HHzzhz/drools,OnePaaS/drools,kedzie/drools-android,OnePaaS/drools,292388900/drools,ThiagoGarciaAlves/drools,yurloc/drools,prabasn/drools,yurloc/drools,mswiderski/drools,vinodkiran/drools,prabasn/drools,reynoldsm88/drools,Buble1981/MyDroolsFork,kevinpeterson/drools,jomarko/drools,liupugong/drools,mswiderski/drools,jiripetrlik/drools,mswiderski/drools,mrietveld/drools,kevinpeterson/drools,droolsjbpm/drools,mrrodriguez/drools,ThomasLau/drools,ChallenHB/drools,droolsjbpm/drools,292388900/drools,reynoldsm88/drools,vinodkiran/drools,amckee23/drools,rajashekharmunthakewill/drools,amckee23/drools,jomarko/drools
package org.drools.workflow.core.node; import java.util.ArrayList; import java.util.List; import org.drools.process.core.event.EventFilter; import org.drools.workflow.core.Connection; import org.drools.workflow.core.Node; import org.drools.workflow.core.impl.NodeImpl; public class EventNode extends NodeImpl { private static final long serialVersionUID = 4L; private List<EventFilter> filters = new ArrayList<EventFilter>(); private String variableName; public String getVariableName() { return variableName; } public void setVariableName(String variableName) { this.variableName = variableName; } public void addEventFilter(EventFilter eventFilter) { filters.add(eventFilter); } public void removeEventFilter(EventFilter eventFilter) { filters.remove(eventFilter); } public List<EventFilter> getEventFilters() { return filters; } public void setEventFilters(List<EventFilter> filters) { this.filters = filters; } public void validateAddIncomingConnection(final String type, final Connection connection) { throw new UnsupportedOperationException( "An event node does not have an incoming connection!"); } public void validateRemoveIncomingConnection(final String type, final Connection connection) { throw new UnsupportedOperationException( "An event node does not have an incoming connection!"); } public void validateAddOutgoingConnection(final String type, final Connection connection) { super.validateAddOutgoingConnection(type, connection); if (!Node.CONNECTION_DEFAULT_TYPE.equals(type)) { throw new IllegalArgumentException( "This type of node only accepts default outgoing connection type!"); } if (getOutgoingConnections(Node.CONNECTION_DEFAULT_TYPE) != null && !getOutgoingConnections(Node.CONNECTION_DEFAULT_TYPE).isEmpty()) { throw new IllegalArgumentException( "This type of node cannot have more than one outgoing connection!"); } } }
drools-core/src/main/java/org/drools/workflow/core/node/EventNode.java
JBRULES-1691: Event Node - added basic event node git-svn-id: a243bed356d289ca0d1b6d299a0597bdc4ecaa09@21195 c60d74c8-e8f6-0310-9e8f-d4a2fc68ab70
drools-core/src/main/java/org/drools/workflow/core/node/EventNode.java
JBRULES-1691: Event Node - added basic event node
<ide><path>rools-core/src/main/java/org/drools/workflow/core/node/EventNode.java <add>package org.drools.workflow.core.node; <add> <add>import java.util.ArrayList; <add>import java.util.List; <add> <add>import org.drools.process.core.event.EventFilter; <add>import org.drools.workflow.core.Connection; <add>import org.drools.workflow.core.Node; <add>import org.drools.workflow.core.impl.NodeImpl; <add> <add>public class EventNode extends NodeImpl { <add> <add> private static final long serialVersionUID = 4L; <add> <add> private List<EventFilter> filters = new ArrayList<EventFilter>(); <add> private String variableName; <add> <add> public String getVariableName() { <add> return variableName; <add> } <add> <add> public void setVariableName(String variableName) { <add> this.variableName = variableName; <add> } <add> <add> public void addEventFilter(EventFilter eventFilter) { <add> filters.add(eventFilter); <add> } <add> <add> public void removeEventFilter(EventFilter eventFilter) { <add> filters.remove(eventFilter); <add> } <add> <add> public List<EventFilter> getEventFilters() { <add> return filters; <add> } <add> <add> public void setEventFilters(List<EventFilter> filters) { <add> this.filters = filters; <add> } <add> <add> public void validateAddIncomingConnection(final String type, final Connection connection) { <add> throw new UnsupportedOperationException( <add> "An event node does not have an incoming connection!"); <add> } <add> <add> public void validateRemoveIncomingConnection(final String type, final Connection connection) { <add> throw new UnsupportedOperationException( <add> "An event node does not have an incoming connection!"); <add> } <add> <add> public void validateAddOutgoingConnection(final String type, final Connection connection) { <add> super.validateAddOutgoingConnection(type, connection); <add> if (!Node.CONNECTION_DEFAULT_TYPE.equals(type)) { <add> throw new IllegalArgumentException( <add> "This type of node only accepts default outgoing connection type!"); <add> } <add> if (getOutgoingConnections(Node.CONNECTION_DEFAULT_TYPE) != null <add> && !getOutgoingConnections(Node.CONNECTION_DEFAULT_TYPE).isEmpty()) { <add> throw new IllegalArgumentException( <add> "This type of node cannot have more than one outgoing connection!"); <add> } <add> } <add> <add>}
Java
apache-2.0
d6ebe7c35096ba9c75f993b7e731f79f035ba8c6
0
apache/commons-exec,apache/commons-exec,sgoeschl/commons-exec,sgoeschl/commons-exec
/* * 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.commons.exec.issues; import org.apache.commons.exec.*; import org.junit.Test; import java.io.File; /** * Test to show that watchdog can destroy 'sudo' and 'sleep'. * * @see <a href="https://issues.apache.org/jira/browse/EXEC-65">EXEC-65</a> */ public class Exec65Test { private static final int TIMEOUT = 3000; private final File testDir = new File("src/test/scripts"); @Test(expected = ExecuteException.class, timeout = 2*TIMEOUT) public void testExec65WitSleepUsingCommandLine() throws Exception { if(OS.isFamilyUnix()) { final DefaultExecutor executor = new DefaultExecutor(); executor.setStreamHandler(new PumpStreamHandler(System.out, System.err)); final ExecuteWatchdog watchdog = new ExecuteWatchdog(TIMEOUT); executor.setWatchdog(watchdog); final CommandLine command = new CommandLine("sleep"); command.addArgument("60"); executor.execute(command); } } @Test(expected = ExecuteException.class, timeout = 2*TIMEOUT) public void testExec65WithSleepUsingShellScript() throws Exception { final DefaultExecutor executor = new DefaultExecutor(); executor.setStreamHandler(new PumpStreamHandler(System.out, System.err)); final ExecuteWatchdog watchdog = new ExecuteWatchdog(TIMEOUT); executor.setWatchdog(watchdog); final CommandLine command = new CommandLine(TestUtil.resolveScriptForOS(testDir + "/sleep")); executor.execute(command); } /** * Please note that this tests make assumptions about the environment. It assumes * that user "root" exists and that the current user is not a "sudoer" already. */ @Test(expected = ExecuteException.class, timeout = 2*TIMEOUT) public void testExec65WithSudoUsingShellScript() throws Exception { if(OS.isFamilyUnix()) { final DefaultExecutor executor = new DefaultExecutor(); executor.setStreamHandler(new PumpStreamHandler(System.out, System.err, System.in)); final ExecuteWatchdog watchdog = new ExecuteWatchdog(TIMEOUT); executor.setWatchdog(watchdog); final CommandLine command = new CommandLine(TestUtil.resolveScriptForOS(testDir + "/issues/exec-65")); executor.execute(command); } } }
src/test/java/org/apache/commons/exec/issues/Exec65Test.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.exec.issues; import org.apache.commons.exec.*; import org.junit.Test; import java.io.File; /** * Test to show that watchdog can destroy 'sudo' and 'sleep'. * * @see <a href="https://issues.apache.org/jira/browse/EXEC-65">EXEC-65</a> */ public class Exec65Test { private static final int TIMEOUT = 3000; private final File testDir = new File("src/test/scripts"); @Test(expected = ExecuteException.class, timeout = 2*TIMEOUT) public void testExec65WitSleepUsingCommandLine() throws Exception { if(OS.isFamilyUnix()) { final DefaultExecutor executor = new DefaultExecutor(); executor.setStreamHandler(new PumpStreamHandler(System.out, System.err)); final ExecuteWatchdog watchdog = new ExecuteWatchdog(TIMEOUT); executor.setWatchdog(watchdog); final CommandLine command = new CommandLine("sleep"); command.addArgument("900"); executor.execute(command); } } @Test(expected = ExecuteException.class, timeout = 2*TIMEOUT) public void testExec65WithSleepUsingShellScript() throws Exception { final DefaultExecutor executor = new DefaultExecutor(); executor.setStreamHandler(new PumpStreamHandler(System.out, System.err)); final ExecuteWatchdog watchdog = new ExecuteWatchdog(TIMEOUT); executor.setWatchdog(watchdog); final CommandLine command = new CommandLine(TestUtil.resolveScriptForOS(testDir + "/sleep")); executor.execute(command); } /** * Please note that this tests make assumptions about the environment. It assumes * that user "root" exists and that the current user is not a "sudoer" already. */ @Test(expected = ExecuteException.class, timeout = 2*TIMEOUT) public void testExec65WithSudoUsingShellScript() throws Exception { if(OS.isFamilyUnix()) { final DefaultExecutor executor = new DefaultExecutor(); executor.setStreamHandler(new PumpStreamHandler(System.out, System.err, System.in)); final ExecuteWatchdog watchdog = new ExecuteWatchdog(TIMEOUT); executor.setWatchdog(watchdog); final CommandLine command = new CommandLine(TestUtil.resolveScriptForOS(testDir + "/issues/exec-65")); executor.execute(command); } } }
[EXEC-65] Watchdog can't destroy 'sudo' and 'sleep' - add unit test to ensure that the functionality works git-svn-id: 152f48a1866dc7886cc2b83d2001e6645df26423@1723261 13f79535-47bb-0310-9956-ffa450edef68
src/test/java/org/apache/commons/exec/issues/Exec65Test.java
[EXEC-65] Watchdog can't destroy 'sudo' and 'sleep' - add unit test to ensure that the functionality works
<ide><path>rc/test/java/org/apache/commons/exec/issues/Exec65Test.java <ide> final ExecuteWatchdog watchdog = new ExecuteWatchdog(TIMEOUT); <ide> executor.setWatchdog(watchdog); <ide> final CommandLine command = new CommandLine("sleep"); <del> command.addArgument("900"); <add> command.addArgument("60"); <ide> <ide> executor.execute(command); <ide> }
Java
apache-2.0
89d8c0dddf2439aeeef68a4b126f7c08aa1228f8
0
noughts/Garum,operando/Garum
package com.os.operando.garum.utils; import android.content.Context; import com.os.operando.garum.Configuration; import com.os.operando.garum.ModelInfo; import com.os.operando.garum.PrefInfo; import com.os.operando.garum.models.PrefModel; import com.os.operando.garum.serializers.TypeSerializer; import java.io.IOException; import java.util.Collection; public final class Cache { private static Context context; private static ModelInfo modelInfo; private static boolean isInitialized = false; private Cache() { } public static synchronized void initialize(Configuration configuration) { if (isInitialized) { GarumLog.v("Garum already initialized."); return; } context = configuration.getContext(); try { modelInfo = new ModelInfo(configuration); } catch (IOException e) { e.printStackTrace(); } isInitialized = true; GarumLog.v("Garum initialized successfully."); } public static synchronized void dispose() { modelInfo = null; isInitialized = false; GarumLog.v("Garum disposed. Call initialize to use library."); } public static boolean isInitialized() { return isInitialized; } public static Context getContext() { return context; } public static synchronized Collection<PrefInfo> getPrefInfos() { return modelInfo.getPrefInfos(); } public static synchronized PrefInfo getPrefInfo(Class<? extends PrefModel> type) { return modelInfo.getPrefInfo(type); } public static synchronized String getPrefName(Class<? extends PrefModel> type) { return modelInfo.getPrefInfo(type).getPrefName(); } public static synchronized TypeSerializer getParserForType(Class<?> type) { return modelInfo.getTypeSerializer(type); } }
garum/src/main/java/com/os/operando/garum/utils/Cache.java
package com.os.operando.garum.utils; import android.content.Context; import android.support.v4.util.LruCache; import com.os.operando.garum.Configuration; import com.os.operando.garum.ModelInfo; import com.os.operando.garum.PrefInfo; import com.os.operando.garum.models.PrefModel; import com.os.operando.garum.serializers.TypeSerializer; import java.io.IOException; import java.util.Collection; public final class Cache { public static final int DEFAULT_CACHE_SIZE = 1024; private static Context context; private static ModelInfo modelInfo; private static LruCache<String, PrefModel> entities; private static boolean isInitialized = false; private Cache() { } public static synchronized void initialize(Configuration configuration) { if (isInitialized) { GarumLog.v("Garum already initialized."); return; } context = configuration.getContext(); try { modelInfo = new ModelInfo(configuration); } catch (IOException e) { e.printStackTrace(); } entities = new LruCache<String, PrefModel>(DEFAULT_CACHE_SIZE); isInitialized = true; GarumLog.v("Garum initialized successfully."); } public static synchronized void dispose() { entities = null; modelInfo = null; isInitialized = false; GarumLog.v("Garum disposed. Call initialize to use library."); } public static boolean isInitialized() { return isInitialized; } public static Context getContext() { return context; } public static synchronized Collection<PrefInfo> getPrefInfos() { return modelInfo.getPrefInfos(); } public static synchronized PrefInfo getPrefInfo(Class<? extends PrefModel> type) { return modelInfo.getPrefInfo(type); } public static synchronized String getPrefName(Class<? extends PrefModel> type) { return modelInfo.getPrefInfo(type).getPrefName(); } public static synchronized TypeSerializer getParserForType(Class<?> type) { return modelInfo.getTypeSerializer(type); } }
Delete LruCache
garum/src/main/java/com/os/operando/garum/utils/Cache.java
Delete LruCache
<ide><path>arum/src/main/java/com/os/operando/garum/utils/Cache.java <ide> package com.os.operando.garum.utils; <ide> <ide> import android.content.Context; <del>import android.support.v4.util.LruCache; <ide> <ide> import com.os.operando.garum.Configuration; <ide> import com.os.operando.garum.ModelInfo; <ide> <ide> public final class Cache { <ide> <del> public static final int DEFAULT_CACHE_SIZE = 1024; <ide> private static Context context; <ide> private static ModelInfo modelInfo; <del> private static LruCache<String, PrefModel> entities; <ide> private static boolean isInitialized = false; <ide> <ide> private Cache() { <ide> } catch (IOException e) { <ide> e.printStackTrace(); <ide> } <del> entities = new LruCache<String, PrefModel>(DEFAULT_CACHE_SIZE); <ide> isInitialized = true; <ide> GarumLog.v("Garum initialized successfully."); <ide> } <ide> <ide> <ide> public static synchronized void dispose() { <del> entities = null; <ide> modelInfo = null; <ide> isInitialized = false; <ide> GarumLog.v("Garum disposed. Call initialize to use library.");
Java
bsd-3-clause
b0cff4343e24eecef69b7fbdbe945dc77bba834a
0
InShadow/jmonkeyengine,atomixnmc/jmonkeyengine,d235j/jmonkeyengine,mbenson/jmonkeyengine,weilichuang/jmonkeyengine,bsmr-java/jmonkeyengine,OpenGrabeso/jmonkeyengine,rbottema/jmonkeyengine,nickschot/jmonkeyengine,sandervdo/jmonkeyengine,sandervdo/jmonkeyengine,olafmaas/jmonkeyengine,mbenson/jmonkeyengine,InShadow/jmonkeyengine,atomixnmc/jmonkeyengine,d235j/jmonkeyengine,skapi1992/jmonkeyengine,skapi1992/jmonkeyengine,tr0k/jmonkeyengine,d235j/jmonkeyengine,Georgeto/jmonkeyengine,davidB/jmonkeyengine,shurun19851206/jMonkeyEngine,bertleft/jmonkeyengine,GreenCubes/jmonkeyengine,olafmaas/jmonkeyengine,phr00t/jmonkeyengine,wrvangeest/jmonkeyengine,Georgeto/jmonkeyengine,OpenGrabeso/jmonkeyengine,mbenson/jmonkeyengine,bertleft/jmonkeyengine,amit2103/jmonkeyengine,bsmr-java/jmonkeyengine,rbottema/jmonkeyengine,bertleft/jmonkeyengine,shurun19851206/jMonkeyEngine,g-rocket/jmonkeyengine,shurun19851206/jMonkeyEngine,bertleft/jmonkeyengine,danteinforno/jmonkeyengine,aaronang/jmonkeyengine,g-rocket/jmonkeyengine,davidB/jmonkeyengine,jMonkeyEngine/jmonkeyengine,zzuegg/jmonkeyengine,mbenson/jmonkeyengine,wrvangeest/jmonkeyengine,danteinforno/jmonkeyengine,aaronang/jmonkeyengine,bsmr-java/jmonkeyengine,delftsre/jmonkeyengine,yetanotherindie/jMonkey-Engine,yetanotherindie/jMonkey-Engine,jMonkeyEngine/jmonkeyengine,d235j/jmonkeyengine,sandervdo/jmonkeyengine,weilichuang/jmonkeyengine,delftsre/jmonkeyengine,amit2103/jmonkeyengine,Georgeto/jmonkeyengine,mbenson/jmonkeyengine,GreenCubes/jmonkeyengine,wrvangeest/jmonkeyengine,weilichuang/jmonkeyengine,OpenGrabeso/jmonkeyengine,g-rocket/jmonkeyengine,zzuegg/jmonkeyengine,shurun19851206/jMonkeyEngine,tr0k/jmonkeyengine,Georgeto/jmonkeyengine,g-rocket/jmonkeyengine,zzuegg/jmonkeyengine,weilichuang/jmonkeyengine,amit2103/jmonkeyengine,InShadow/jmonkeyengine,OpenGrabeso/jmonkeyengine,atomixnmc/jmonkeyengine,mbenson/jmonkeyengine,shurun19851206/jMonkeyEngine,yetanotherindie/jMonkey-Engine,danteinforno/jmonkeyengine,phr00t/jmonkeyengine,skapi1992/jmonkeyengine,tr0k/jmonkeyengine,olafmaas/jmonkeyengine,davidB/jmonkeyengine,GreenCubes/jmonkeyengine,Georgeto/jmonkeyengine,delftsre/jmonkeyengine,nickschot/jmonkeyengine,tr0k/jmonkeyengine,danteinforno/jmonkeyengine,skapi1992/jmonkeyengine,sandervdo/jmonkeyengine,danteinforno/jmonkeyengine,nickschot/jmonkeyengine,zzuegg/jmonkeyengine,d235j/jmonkeyengine,olafmaas/jmonkeyengine,jMonkeyEngine/jmonkeyengine,d235j/jmonkeyengine,rbottema/jmonkeyengine,amit2103/jmonkeyengine,InShadow/jmonkeyengine,OpenGrabeso/jmonkeyengine,amit2103/jmonkeyengine,jMonkeyEngine/jmonkeyengine,wrvangeest/jmonkeyengine,yetanotherindie/jMonkey-Engine,phr00t/jmonkeyengine,weilichuang/jmonkeyengine,shurun19851206/jMonkeyEngine,davidB/jmonkeyengine,danteinforno/jmonkeyengine,GreenCubes/jmonkeyengine,rbottema/jmonkeyengine,OpenGrabeso/jmonkeyengine,phr00t/jmonkeyengine,davidB/jmonkeyengine,bsmr-java/jmonkeyengine,amit2103/jmonkeyengine,yetanotherindie/jMonkey-Engine,nickschot/jmonkeyengine,aaronang/jmonkeyengine,aaronang/jmonkeyengine,Georgeto/jmonkeyengine,atomixnmc/jmonkeyengine,weilichuang/jmonkeyengine,atomixnmc/jmonkeyengine,g-rocket/jmonkeyengine,delftsre/jmonkeyengine,atomixnmc/jmonkeyengine,yetanotherindie/jMonkey-Engine,davidB/jmonkeyengine,g-rocket/jmonkeyengine
/* * Copyright (c) 2009-2010 jMonkeyEngine * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are * met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * * Neither the name of 'jMonkeyEngine' nor the names of its contributors * may be used to endorse or promote products derived from this software * without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED * TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ package com.jme3.shader; public enum UniformBinding { /** * The world matrix. Converts Model space to World space. * Type: mat4 */ WorldMatrix, /** * The view matrix. Converts World space to View space. * Type: mat4 */ ViewMatrix, /** * The projection matrix. Converts View space to Clip/Projection space. * Type: mat4 */ ProjectionMatrix, /** * The world view matrix. Converts Model space to View space. * Type: mat4 */ WorldViewMatrix, /** * The normal matrix. The inverse transpose of the worldview matrix. * Converts normals from model space to view space. * Type: mat3 */ NormalMatrix, /** * The world view projection matrix. Converts Model space to Clip/Projection * space. * Type: mat4 */ WorldViewProjectionMatrix, /** * The view projection matrix. Converts Model space to Clip/Projection * space. * Type: mat4 */ ViewProjectionMatrix, WorldMatrixInverse, ViewMatrixInverse, ProjectionMatrixInverse, ViewProjectionMatrixInverse, WorldViewMatrixInverse, NormalMatrixInverse, WorldViewProjectionMatrixInverse, /** * Contains the four viewport parameters in this order: * X = Left, * Y = Top, * Z = Right, * W = Bottom. * Type: vec4 */ ViewPort, /** * The near and far values for the camera frustum. * X = Near * Y = Far. * Type: vec2 */ FrustumNearFar, /** * The width and height of the camera. * Type: vec2 */ Resolution, /** * Aspect ratio of the resolution currently set. Width/Height. * Type: float */ Aspect, /** * Camera position in world space. * Type: vec3 */ CameraPosition, /** * Direction of the camera. * Type: vec3 */ CameraDirection, /** * Left vector of the camera. * Type: vec3 */ CameraLeft, /** * Up vector of the camera. * Type: vec3 */ CameraUp, /** * Time in seconds since the application was started. * Type: float */ Time, /** * Time in seconds that the last frame took. * Type: float */ Tpf, /** * Frames per second. * Type: float */ FrameRate, }
engine/src/core/com/jme3/shader/UniformBinding.java
/* * Copyright (c) 2009-2010 jMonkeyEngine * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are * met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * * Neither the name of 'jMonkeyEngine' nor the names of its contributors * may be used to endorse or promote products derived from this software * without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED * TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ package com.jme3.shader; public enum UniformBinding { /** * The world matrix. Converts Model space to World space. * Type: mat4 */ WorldMatrix, /** * The view matrix. Converts World space to View space. * Type: mat4 */ ViewMatrix, /** * The projection matrix. Converts View space to Clip/Projection space. * Type: mat4 */ ProjectionMatrix, /** * The world view matrix. Converts Model space to View space. * Type: mat4 */ WorldViewMatrix, /** * The normal matrix. The inverse transpose of the worldview matrix. * Converts normals from model space to view space. * Type: mat3 */ NormalMatrix, /** * The world view projection matrix. Converts Model space to Clip/Projection * space. * Type: mat4 */ WorldViewProjectionMatrix, /** * The view projection matrix. Converts View space to Clip/Projection * space. * Type: mat4 */ ViewProjectionMatrix, WorldMatrixInverse, ViewMatrixInverse, ProjectionMatrixInverse, ViewProjectionMatrixInverse, WorldViewMatrixInverse, NormalMatrixInverse, WorldViewProjectionMatrixInverse, /** * Contains the four viewport parameters in this order: * X = Left, * Y = Top, * Z = Right, * W = Bottom. * Type: vec4 */ ViewPort, /** * The near and far values for the camera frustum. * X = Near * Y = Far. * Type: vec2 */ FrustumNearFar, /** * The width and height of the camera. * Type: vec2 */ Resolution, /** * Aspect ratio of the resolution currently set. Width/Height. * Type: float */ Aspect, /** * Camera position in world space. * Type: vec3 */ CameraPosition, /** * Direction of the camera. * Type: vec3 */ CameraDirection, /** * Left vector of the camera. * Type: vec3 */ CameraLeft, /** * Up vector of the camera. * Type: vec3 */ CameraUp, /** * Time in seconds since the application was started. * Type: float */ Time, /** * Time in seconds that the last frame took. * Type: float */ Tpf, /** * Frames per second. * Type: float */ FrameRate, }
* Fix View -> Model space for ViewProjectionMatrix git-svn-id: f9411aee4f13664f2fc428a5b3e824fe43a079a3@9137 75d07b2b-3a1a-0410-a2c5-0572b91ccdca
engine/src/core/com/jme3/shader/UniformBinding.java
* Fix View -> Model space for ViewProjectionMatrix
<ide><path>ngine/src/core/com/jme3/shader/UniformBinding.java <ide> WorldViewProjectionMatrix, <ide> <ide> /** <del> * The view projection matrix. Converts View space to Clip/Projection <add> * The view projection matrix. Converts Model space to Clip/Projection <ide> * space. <ide> * Type: mat4 <ide> */
Java
mit
812c8ffe1d600256d4ac3a5fecb4ac153c88078d
0
petergeneric/stdlib,petergeneric/stdlib,petergeneric/stdlib
package com.peterphi.std.guice.web.rest.auth.oauth2; import com.google.inject.Inject; import com.google.inject.name.Named; import com.peterphi.std.annotation.Doc; import com.peterphi.std.guice.apploader.GuiceProperties; import com.peterphi.std.guice.web.rest.scoping.SessionScoped; import com.peterphi.std.types.SimpleId; import com.peterphi.usermanager.rest.iface.oauth2server.UserManagerOAuthService; import com.peterphi.usermanager.rest.iface.oauth2server.types.OAuth2TokenResponse; import com.peterphi.usermanager.rest.type.UserManagerUser; import org.apache.commons.lang.StringUtils; import org.apache.log4j.Logger; import javax.ws.rs.core.UriBuilder; import java.net.URI; import java.util.Base64; /** * Holds the OAuth2 callback information for this session; will start unpopulated (see {@link #isValid()}) and then be populated * once the OAuth2 callback completes. It will switch back to unpopulated when the OAuth2 session expires. * <p> * While populated the session ref can be used to query for the currently active <code>token</code> assigned by the server, as * well as querying side-channel information on the user associated with that token (when the OAuth2 provider is the User * Manager) */ @SessionScoped public class OAuth2SessionRef { private static final Logger log = Logger.getLogger(OAuth2SessionRef.class); public final UserManagerOAuthService authService; public final String oauthServiceEndpoint; @Inject(optional=true) @Doc("If specified, this value will be used instead of service.oauth2.endpoint when redirecting the client to the oauth2 server (e.g. for separate internal and external endpoints)") @Named("service.oauth2.redirect-endpoint") public String oauthServiceRedirectEndpoint; @Inject(optional = true) @Doc("If specified, this value will be used instead of local endpoint when telling the oauth2 server where to send the oauth2 reply (e.g. to allow a relative response). Will have the following added to it: /oauth2/client/cb") @Named("service.oauth2.self-endpoint") public String oauthSelfEndpoint; private final URI localEndpoint; /** * A nonce value used to make sure that authorisation flows originated from this session ref */ private final String callbackNonce = SimpleId.alphanumeric(20); public final String clientId; private final String clientSecret; private OAuth2TokenResponse response; private UserManagerUser cachedInfo; @Inject public OAuth2SessionRef(final UserManagerOAuthService authService, @Named("service.oauth2.endpoint") final String oauthServiceEndpoint, @Named("service.oauth2.client_id") final String clientId, @Named("service.oauth2.client_secret") final String clientSecret, @Named(GuiceProperties.LOCAL_REST_SERVICES_ENDPOINT) URI localEndpoint) { this.authService = authService; this.oauthServiceEndpoint = oauthServiceEndpoint; this.clientId = clientId; this.clientSecret = clientSecret; this.localEndpoint = localEndpoint; if (response != null) load(response); } public boolean isValid() { try { getToken(); } catch (Throwable e) { // ignore } return response != null; } /** * Return the URI for this service's callback resource * * @return */ public URI getOwnCallbackUri() { String localEndpointStr = (oauthSelfEndpoint != null) ? oauthSelfEndpoint : localEndpoint.toString(); if (!localEndpointStr.endsWith("/")) localEndpointStr += "/"; return URI.create(localEndpointStr + "oauth2/client/cb"); } /** * Get the endpoint to redirect a client to in order to start an OAuth2 Authorisation Flow * * @param returnTo * The URI to redirect the user back to once the authorisation flow completes successfully. If not specified then the user * will be directed to the root of this webapp. * * @return */ public URI getAuthFlowStartEndpoint(final String returnTo, final String scope) { final String oauthServiceRoot = (oauthServiceRedirectEndpoint != null) ? oauthServiceRedirectEndpoint : oauthServiceEndpoint; final String endpoint = oauthServiceRoot + "/oauth2/authorize"; UriBuilder builder = UriBuilder.fromUri(endpoint); builder.replaceQueryParam("response_type", "code"); builder.replaceQueryParam("client_id", clientId); builder.replaceQueryParam("redirect_uri", getOwnCallbackUri()); if (scope != null) builder.replaceQueryParam("scope", scope); if (returnTo != null) builder.replaceQueryParam("state", encodeState(callbackNonce + " " + returnTo)); return builder.build(); } /** * Encode the state value into RFC $648 URL-safe base64 * @param src * @return */ private String encodeState(final String src) { return Base64.getUrlEncoder().encodeToString(src.getBytes()); } /** * Decode the state value (which should be encoded as RFC 4648 URL-safe base64) * @param src * @return */ private String decodeState(final String src) { return new String(Base64.getUrlDecoder().decode(src)); } /** * Decode the state to retrieve the redirectTo value * * @param state * * @return */ public URI getRedirectToFromState(final String state) { final String[] pieces = decodeState(state).split(" ", 2); if (!StringUtils.equals(callbackNonce, pieces[0])) throw new IllegalArgumentException("WARNING: This service received an authorisation approval which it did not initiate, someone may be trying to compromise your account security"); if (pieces.length == 2) return URI.create(pieces[1]); else return null; } public synchronized String getToken() { if (response == null) throw new IllegalArgumentException("Not loaded yet!"); // If the token has expired then we must use the refresh token to refresh it if (response.expires != null && System.currentTimeMillis() > response.expires.getTime()) { log.debug("OAuth token has expired for " + ((cachedInfo != null) ? cachedInfo.email : "OAuth session " + response.refresh_token) + " and must be refreshed"); // Will throw an exception if the token acquisition fails refreshToken(); } if (this.response != null && this.response.access_token != null) return this.response.access_token; else throw new IllegalArgumentException("Could not acquire token!"); } /** * Use the refresh token to get a new token with a longer lifespan */ public synchronized void refreshToken() { final String refreshToken = this.response.refresh_token; this.response = null; this.cachedInfo = null; final String responseStr = authService.getToken("refresh_token", null, null, clientId, clientSecret, refreshToken, null, null); final OAuth2TokenResponse response = OAuth2TokenResponse.decode(responseStr); load(response); } public synchronized void refreshUserInfo() { this.cachedInfo = null; this.cachedInfo = authService.get(getToken(), clientId); } public synchronized UserManagerUser getUserInfo() { if (!isValid()) throw new IllegalArgumentException("No OAuth2 session information!"); // Make sure we refresh the token if necessary (also makes sure we invalidate the user info cache if necessary getToken(); if (this.cachedInfo == null) { refreshUserInfo(); } return this.cachedInfo; } public void load(final OAuth2TokenResponse response) { this.cachedInfo = null; if (StringUtils.isNotBlank(response.error)) { throw new IllegalArgumentException("OAuth2 token acquisition failed with error: " + response.error); } else { this.response = response; } } }
guice/webapp/src/main/java/com/peterphi/std/guice/web/rest/auth/oauth2/OAuth2SessionRef.java
package com.peterphi.std.guice.web.rest.auth.oauth2; import com.google.inject.Inject; import com.google.inject.name.Named; import com.peterphi.std.guice.apploader.GuiceProperties; import com.peterphi.std.guice.web.rest.scoping.SessionScoped; import com.peterphi.std.types.SimpleId; import com.peterphi.usermanager.rest.iface.oauth2server.UserManagerOAuthService; import com.peterphi.usermanager.rest.iface.oauth2server.types.OAuth2TokenResponse; import com.peterphi.usermanager.rest.type.UserManagerUser; import org.apache.commons.lang.StringUtils; import org.apache.log4j.Logger; import javax.ws.rs.core.UriBuilder; import java.net.URI; import java.util.Base64; /** * Holds the OAuth2 callback information for this session; will start unpopulated (see {@link #isValid()}) and then be populated * once the OAuth2 callback completes. It will switch back to unpopulated when the OAuth2 session expires. * <p> * While populated the session ref can be used to query for the currently active <code>token</code> assigned by the server, as * well as querying side-channel information on the user associated with that token (when the OAuth2 provider is the User * Manager) */ @SessionScoped public class OAuth2SessionRef { private static final Logger log = Logger.getLogger(OAuth2SessionRef.class); public final UserManagerOAuthService authService; public final String oauthServiceEndpoint; private final URI localEndpoint; /** * A nonce value used to make sure that authorisation flows originated from this session ref */ private final String callbackNonce = SimpleId.alphanumeric(20); public final String clientId; private final String clientSecret; private OAuth2TokenResponse response; private UserManagerUser cachedInfo; @Inject public OAuth2SessionRef(final UserManagerOAuthService authService, @Named("service.oauth2.endpoint") final String oauthServiceEndpoint, @Named("service.oauth2.client_id") final String clientId, @Named("service.oauth2.client_secret") final String clientSecret, @Named(GuiceProperties.LOCAL_REST_SERVICES_ENDPOINT) URI localEndpoint) { this.authService = authService; this.oauthServiceEndpoint = oauthServiceEndpoint; this.clientId = clientId; this.clientSecret = clientSecret; this.localEndpoint = localEndpoint; if (response != null) load(response); } public boolean isValid() { try { getToken(); } catch (Throwable e) { // ignore } return response != null; } /** * Return the URI for this service's callback resource * * @return */ public URI getOwnCallbackUri() { String localEndpointStr = localEndpoint.toString(); if (!localEndpointStr.endsWith("/")) localEndpointStr += "/"; return URI.create(localEndpointStr + "oauth2/client/cb"); } /** * Get the endpoint to redirect a client to in order to start an OAuth2 Authorisation Flow * * @param returnTo * The URI to redirect the user back to once the authorisation flow completes successfully. If not specified then the user * will be directed to the root of this webapp. * * @return */ public URI getAuthFlowStartEndpoint(final String returnTo, final String scope) { final String endpoint = oauthServiceEndpoint + "/oauth2/authorize"; UriBuilder builder = UriBuilder.fromUri(endpoint); builder.replaceQueryParam("response_type", "code"); builder.replaceQueryParam("client_id", clientId); builder.replaceQueryParam("redirect_uri", getOwnCallbackUri()); if (scope != null) builder.replaceQueryParam("scope", scope); if (returnTo != null) builder.replaceQueryParam("state", encodeState(callbackNonce + " " + returnTo)); return builder.build(); } /** * Encode the state value into RFC $648 URL-safe base64 * @param src * @return */ private String encodeState(final String src) { return Base64.getUrlEncoder().encodeToString(src.getBytes()); } /** * Decode the state value (which should be encoded as RFC 4648 URL-safe base64) * @param src * @return */ private String decodeState(final String src) { return new String(Base64.getUrlDecoder().decode(src)); } /** * Decode the state to retrieve the redirectTo value * * @param state * * @return */ public URI getRedirectToFromState(final String state) { final String[] pieces = decodeState(state).split(" ", 2); if (!StringUtils.equals(callbackNonce, pieces[0])) throw new IllegalArgumentException("WARNING: This service received an authorisation approval which it did not initiate, someone may be trying to compromise your account security"); if (pieces.length == 2) return URI.create(pieces[1]); else return null; } public synchronized String getToken() { if (response == null) throw new IllegalArgumentException("Not loaded yet!"); // If the token has expired then we must use the refresh token to refresh it if (response.expires != null && System.currentTimeMillis() > response.expires.getTime()) { log.debug("OAuth token has expired for " + ((cachedInfo != null) ? cachedInfo.email : "OAuth session " + response.refresh_token) + " and must be refreshed"); // Will throw an exception if the token acquisition fails refreshToken(); } if (this.response != null && this.response.access_token != null) return this.response.access_token; else throw new IllegalArgumentException("Could not acquire token!"); } /** * Use the refresh token to get a new token with a longer lifespan */ public synchronized void refreshToken() { final String refreshToken = this.response.refresh_token; this.response = null; this.cachedInfo = null; final String responseStr = authService.getToken("refresh_token", null, null, clientId, clientSecret, refreshToken, null, null); final OAuth2TokenResponse response = OAuth2TokenResponse.decode(responseStr); load(response); } public synchronized void refreshUserInfo() { this.cachedInfo = null; this.cachedInfo = authService.get(getToken(), clientId); } public synchronized UserManagerUser getUserInfo() { if (!isValid()) throw new IllegalArgumentException("No OAuth2 session information!"); // Make sure we refresh the token if necessary (also makes sure we invalidate the user info cache if necessary getToken(); if (this.cachedInfo == null) { refreshUserInfo(); } return this.cachedInfo; } public void load(final OAuth2TokenResponse response) { this.cachedInfo = null; if (StringUtils.isNotBlank(response.error)) { throw new IllegalArgumentException("OAuth2 token acquisition failed with error: " + response.error); } else { this.response = response; } } }
Introduce service.oauth2.redirect-endpoint and service.oauth2.self-endpoint, primarily to allow user-manager redirects to use relative URIs (this means we can run the user-manager without knowing our own absolute URI, assuming the user-manager and application are both available via the same reverse proxy at the same hostname by some well-known relative path)
guice/webapp/src/main/java/com/peterphi/std/guice/web/rest/auth/oauth2/OAuth2SessionRef.java
Introduce service.oauth2.redirect-endpoint and service.oauth2.self-endpoint, primarily to allow user-manager redirects to use relative URIs (this means we can run the user-manager without knowing our own absolute URI, assuming the user-manager and application are both available via the same reverse proxy at the same hostname by some well-known relative path)
<ide><path>uice/webapp/src/main/java/com/peterphi/std/guice/web/rest/auth/oauth2/OAuth2SessionRef.java <ide> <ide> import com.google.inject.Inject; <ide> import com.google.inject.name.Named; <add>import com.peterphi.std.annotation.Doc; <ide> import com.peterphi.std.guice.apploader.GuiceProperties; <ide> import com.peterphi.std.guice.web.rest.scoping.SessionScoped; <ide> import com.peterphi.std.types.SimpleId; <ide> <ide> public final UserManagerOAuthService authService; <ide> public final String oauthServiceEndpoint; <add> <add> @Inject(optional=true) <add> @Doc("If specified, this value will be used instead of service.oauth2.endpoint when redirecting the client to the oauth2 server (e.g. for separate internal and external endpoints)") <add> @Named("service.oauth2.redirect-endpoint") <add> public String oauthServiceRedirectEndpoint; <add> <add> @Inject(optional = true) <add> @Doc("If specified, this value will be used instead of local endpoint when telling the oauth2 server where to send the oauth2 reply (e.g. to allow a relative response). Will have the following added to it: /oauth2/client/cb") <add> @Named("service.oauth2.self-endpoint") <add> public String oauthSelfEndpoint; <add> <ide> private final URI localEndpoint; <ide> <ide> /** <ide> */ <ide> public URI getOwnCallbackUri() <ide> { <del> String localEndpointStr = localEndpoint.toString(); <add> String localEndpointStr = (oauthSelfEndpoint != null) ? oauthSelfEndpoint : localEndpoint.toString(); <ide> <ide> if (!localEndpointStr.endsWith("/")) <ide> localEndpointStr += "/"; <ide> */ <ide> public URI getAuthFlowStartEndpoint(final String returnTo, final String scope) <ide> { <del> final String endpoint = oauthServiceEndpoint + "/oauth2/authorize"; <add> final String oauthServiceRoot = (oauthServiceRedirectEndpoint != null) ? oauthServiceRedirectEndpoint : oauthServiceEndpoint; <add> final String endpoint = oauthServiceRoot + "/oauth2/authorize"; <ide> <ide> UriBuilder builder = UriBuilder.fromUri(endpoint); <ide>
Java
apache-2.0
f77881f1c1d0d124552361fda6d11571f57ef91c
0
sebasbaumh/gwt-three.js,akjava/gwt-three.js-test,akjava/gwt-three.js-test,akjava/gwt-three.js-test,sebasbaumh/gwt-three.js,sebasbaumh/gwt-three.js
/* * gwt-wrap three.js * * Copyright (c) 2011 [email protected] 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. based Three.js r45 https://github.com/mrdoob/three.js The MIT License Copyright (c) 2010-2011 three.js Authors. All rights reserved. Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ package com.akjava.gwt.three.client.js.core; import com.akjava.gwt.three.client.gwt.animation.AnimationBone; import com.akjava.gwt.three.client.gwt.animation.AnimationData; import com.akjava.gwt.three.client.gwt.core.BoundingBox; import com.akjava.gwt.three.client.gwt.core.MorphTarget; import com.akjava.gwt.three.client.js.math.Color; import com.akjava.gwt.three.client.js.math.Matrix4; import com.akjava.gwt.three.client.js.math.Vector2; import com.akjava.gwt.three.client.js.math.Vector3; import com.akjava.gwt.three.client.js.math.Vector4; import com.google.gwt.core.client.JavaScriptObject; import com.google.gwt.core.client.JsArray; import com.google.gwt.core.client.JsArrayNumber; public class Geometry extends EventDispatcher{ protected Geometry(){} public final native JsArray<Face3> faces()/*-{ return this.faces; }-*/; public final native JsArray<Vector3> vertices()/*-{ return this.vertices; }-*/; /** * should call computeBoundingBox * @return */ public final native BoundingBox getBoundingBox()/*-{ return this.boundingBox; }-*/; public final native void computeBoundingSphere()/*-{ this.computeBoundingSphere(); }-*/; public final native void computeFaceNormals()/*-{ this.computeFaceNormals(); }-*/; public final native void computeCentroids()/*-{ this.computeFaceNormals(); }-*/; public final native void computeVertexNormals()/*-{ this.computeVertexNormals(); }-*/; public final native void computeBoundingBox()/*-{ this.computeBoundingBox(); }-*/; /** * @deprecated * @return */ public final native boolean getDirtyVertices()/*-{ return this.verticesNeedUpdate; }-*/; /** * @deprecated * @param bool */ public final native void setDirtyVertices(boolean bool)/*-{ this.verticesNeedUpdate=bool; }-*/; public final native boolean isVerticesNeedUpdate()/*-{ return this.verticesNeedUpdate; }-*/; public final native void setVerticesNeedUpdate(boolean bool)/*-{ this.verticesNeedUpdate=bool; }-*/; public final native void setElementsNeedUpdate (boolean bool)/*-{ this.elementsNeedUpdate =bool; }-*/; public final native boolean isElementsNeedUpdate()/*-{ return this.elementsNeedUpdate ; }-*/; public final native void setMorphTargetsNeedUpdate (boolean bool)/*-{ this.morphTargetsNeedUpdate =bool; }-*/; public final native boolean isMorphTargetsNeedUpdate ()/*-{ return this.morphTargetsNeedUpdate ; }-*/; public final native void setUvsNeedUpdate (boolean bool)/*-{ this.uvsNeedUpdate =bool; }-*/; public final native boolean isUvsNeedUpdate ()/*-{ return this.uvsNeedUpdate ; }-*/; public final native void setNormalsNeedUpdate (boolean bool)/*-{ this.normalsNeedUpdate =bool; }-*/; public final native boolean isNormalsNeedUpdate ()/*-{ return this.normalsNeedUpdate ; }-*/; public final native void setColorsNeedUpdate (boolean bool)/*-{ this.colorsNeedUpdate =bool; }-*/; public final native boolean isColorsNeedUpdate ()/*-{ return this.colorsNeedUpdate ; }-*/; public final native void setTangentsNeedUpdate (boolean bool)/*-{ this.tangentsNeedUpdate =bool; }-*/; public final native boolean isTangentsNeedUpdate ()/*-{ return this.tangentsNeedUpdate ; }-*/; public final native boolean getDynamic()/*-{ return this.dynamic; }-*/; public final native void setDynamic(boolean bool)/*-{ this.dynamic=bool; }-*/; public final native void applyMatrix(Matrix4 matrix)/*-{ this.applyMatrix(matrix); }-*/; public final native void computeTangents()/*-{ this.computeTangents(); }-*/; public final native JsArray<MorphTarget> getMorphTargets()/*-{ return this.morphTargets; }-*/; public final native JsArray<AnimationData> getAnimations()/*-{ return this.animation; }-*/; public final native AnimationData getAnimation()/*-{ return this.animation; }-*/; public final native JsArray<AnimationBone> getBones()/*-{ return this.bones; }-*/; public final native void setBones(JsArray<AnimationBone> bones)/*-{ this.bones=bones; }-*/; //dont't call after meshed geometry /** @deprecated */ public final native JsArrayNumber getSkinIndicesAsRaw()/*-{ return this.skinIndices; }-*/; //dont't call after meshed geometry /** @deprecated */ public final native JsArrayNumber getSkinWeightAsRaw()/*-{ return this.skinWeights; }-*/; //dont't call after meshed geometry public final native void setSkinIndices(JsArray<Vector4> skinIndices)/*-{ this.skinIndices=skinIndices; }-*/; public final native void setSkinWeight(JsArray<Vector4> skinWeights)/*-{ this.skinWeights=skinWeights; }-*/; //dont't call after meshed geometry public final native JsArray<Vector4> getSkinIndices()/*-{ return this.skinIndices; }-*/; public final native JsArray<Vector4> getSkinWeight()/*-{ return this.skinWeights; }-*/; //maybe public native final JsArray<JsArray<Vector2>> getFaceVertexUvs ()/*-{ return this["faceVertexUvs"][0]; }-*/; public native final Geometry clone()/*-{ return this.clone(); }-*/; public final native JsArray<Vector3> getVertices()/*-{ return this.vertices; }-*/; public final native void setVertices(JsArray<Vector3> vertices)/*-{ this.vertices = vertices; }-*/; public final native JsArray<Color> getColors()/*-{ return this.colors; }-*/; public final native void setColors(JsArray<Color> colors)/*-{ this.colors = colors; }-*/; public final native JsArray<Face3> getFaces()/*-{ return this.faces; }-*/; public final native void setFaces(JsArray<Face3> faces)/*-{ this.faces = faces; }-*/; public final native void setFaceVertexUvs(JsArray<JavaScriptObject> faceVertexUvs)/*-{ this.faceVertexUvs = faceVertexUvs; }-*/; public final native void setMorphTargets(JsArray<MorphTarget> morphTargets)/*-{ this.morphTargets = morphTargets; }-*/; public final native JsArray<Color> getMorphColors()/*-{ return this.morphColors; }-*/; public final native void setMorphColors(JsArray<Color> morphColors)/*-{ this.morphColors = morphColors; }-*/; public final native JsArray<Vector3> getMorphNormals()/*-{ return this.morphNormals; }-*/; public final native void setMorphNormals(JsArray<Vector3> morphNormals)/*-{ this.morphNormals = morphNormals; }-*/; public final native JsArray<Vector4> getSkinWeights()/*-{ return this.skinWeights; }-*/; public final native void setSkinWeights(JsArray<Vector4> skinWeights)/*-{ this.skinWeights = skinWeights; }-*/; public final native JsArrayNumber getLineDistances()/*-{ return this.lineDistances; }-*/; public final native void setLineDistances(JsArrayNumber lineDistances)/*-{ this.lineDistances = lineDistances; }-*/; public final native void setBoundingBox(Object boundingBox)/*-{ this.boundingBox = boundingBox; }-*/; public final native Object getBoundingSphere()/*-{ return this.boundingSphere; }-*/; public final native void setBoundingSphere(Object boundingSphere)/*-{ this.boundingSphere = boundingSphere; }-*/; public final native boolean isHasTangents()/*-{ return this.hasTangents; }-*/; public final native void setHasTangents(boolean hasTangents)/*-{ this.hasTangents = hasTangents; }-*/; public final native void setDynamic(Object dynamic)/*-{ this.dynamic = dynamic; }-*/; public final native boolean isLineDistancesNeedUpdate()/*-{ return this.lineDistancesNeedUpdate; }-*/; public final native void setLineDistancesNeedUpdate(boolean lineDistancesNeedUpdate)/*-{ this.lineDistancesNeedUpdate = lineDistancesNeedUpdate; }-*/; public final native boolean isBuffersNeedUpdate()/*-{ return this.buffersNeedUpdate; }-*/; public final native void setBuffersNeedUpdate(boolean buffersNeedUpdate)/*-{ this.buffersNeedUpdate = buffersNeedUpdate; }-*/; public final native void applyMatrix(Object matrix)/*-{ this.applyMatrix(matrix); }-*/; public final native void computeVertexNormals(boolean areaWeighted)/*-{ this.computeVertexNormals(areaWeighted); }-*/; public final native void computeMorphNormals()/*-{ this.computeMorphNormals(); }-*/; public final native Object mergeVertices()/*-{ return this.mergeVertices(); }-*/; public final native void dispose()/*-{ this.dispose(); }-*/; }
src/com/akjava/gwt/three/client/js/core/Geometry.java
/* * gwt-wrap three.js * * Copyright (c) 2011 [email protected] 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. based Three.js r45 https://github.com/mrdoob/three.js The MIT License Copyright (c) 2010-2011 three.js Authors. All rights reserved. Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ package com.akjava.gwt.three.client.js.core; import com.akjava.gwt.three.client.gwt.animation.AnimationBone; import com.akjava.gwt.three.client.gwt.animation.AnimationData; import com.akjava.gwt.three.client.gwt.core.BoundingBox; import com.akjava.gwt.three.client.gwt.core.MorphTarget; import com.akjava.gwt.three.client.js.math.Color; import com.akjava.gwt.three.client.js.math.Matrix4; import com.akjava.gwt.three.client.js.math.Vector2; import com.akjava.gwt.three.client.js.math.Vector3; import com.akjava.gwt.three.client.js.math.Vector4; import com.google.gwt.core.client.JavaScriptObject; import com.google.gwt.core.client.JsArray; import com.google.gwt.core.client.JsArrayNumber; public class Geometry extends EventDispatcher{ protected Geometry(){} public final native JsArray<Face3> faces()/*-{ return this.faces; }-*/; public final native JsArray<Vector3> vertices()/*-{ return this.vertices; }-*/; /** * should call computeBoundingBox * @return */ public final native BoundingBox getBoundingBox()/*-{ return this.boundingBox; }-*/; public final native void computeBoundingSphere()/*-{ this.computeBoundingSphere(); }-*/; public final native void computeFaceNormals()/*-{ this.computeFaceNormals(); }-*/; public final native void computeCentroids()/*-{ this.computeFaceNormals(); }-*/; public final native void computeVertexNormals()/*-{ this.computeVertexNormals(); }-*/; public final native void computeBoundingBox()/*-{ this.computeBoundingBox(); }-*/; /** * @deprecated * @return */ public final native boolean getDirtyVertices()/*-{ return this.verticesNeedUpdate; }-*/; /** * @deprecated * @param bool */ public final native void setDirtyVertices(boolean bool)/*-{ this.verticesNeedUpdate=bool; }-*/; public final native boolean isVerticesNeedUpdate()/*-{ return this.verticesNeedUpdate; }-*/; public final native void setVerticesNeedUpdate(boolean bool)/*-{ this.verticesNeedUpdate=bool; }-*/; public final native void setElementsNeedUpdate (boolean bool)/*-{ this.elementsNeedUpdate =bool; }-*/; public final native boolean isElementsNeedUpdate()/*-{ return this.elementsNeedUpdate ; }-*/; public final native void setMorphTargetsNeedUpdate (boolean bool)/*-{ this.morphTargetsNeedUpdate =bool; }-*/; public final native boolean isMorphTargetsNeedUpdate ()/*-{ return this.morphTargetsNeedUpdate ; }-*/; public final native void setUvsNeedUpdate (boolean bool)/*-{ this.uvsNeedUpdate =bool; }-*/; public final native boolean isUvsNeedUpdate ()/*-{ return this.uvsNeedUpdate ; }-*/; public final native void setNormalsNeedUpdate (boolean bool)/*-{ this.normalsNeedUpdate =bool; }-*/; public final native boolean isNormalsNeedUpdate ()/*-{ return this.normalsNeedUpdate ; }-*/; public final native void setColorsNeedUpdate (boolean bool)/*-{ this.colorsNeedUpdate =bool; }-*/; public final native boolean isColorsNeedUpdate ()/*-{ return this.colorsNeedUpdate ; }-*/; public final native void setTangentsNeedUpdate (boolean bool)/*-{ this.tangentsNeedUpdate =bool; }-*/; public final native boolean isTangentsNeedUpdate ()/*-{ return this.tangentsNeedUpdate ; }-*/; public final native boolean getDynamic()/*-{ return this.dynamic; }-*/; public final native void setDynamic(boolean bool)/*-{ this.dynamic=bool; }-*/; public final native void applyMatrix(Matrix4 matrix)/*-{ this.applyMatrix(matrix); }-*/; public final native void computeTangents()/*-{ this.computeTangents(); }-*/; public final native JsArray<MorphTarget> getMorphTargets()/*-{ return this.morphTargets; }-*/; public final native AnimationData getAnimation()/*-{ return this.animation; }-*/; public final native JsArray<AnimationBone> getBones()/*-{ return this.bones; }-*/; public final native void setBones(JsArray<AnimationBone> bones)/*-{ this.bones=bones; }-*/; //dont't call after meshed geometry /** @deprecated */ public final native JsArrayNumber getSkinIndicesAsRaw()/*-{ return this.skinIndices; }-*/; //dont't call after meshed geometry /** @deprecated */ public final native JsArrayNumber getSkinWeightAsRaw()/*-{ return this.skinWeights; }-*/; //dont't call after meshed geometry public final native void setSkinIndices(JsArray<Vector4> skinIndices)/*-{ this.skinIndices=skinIndices; }-*/; public final native void setSkinWeight(JsArray<Vector4> skinWeights)/*-{ this.skinWeights=skinWeights; }-*/; //dont't call after meshed geometry public final native JsArray<Vector4> getSkinIndices()/*-{ return this.skinIndices; }-*/; public final native JsArray<Vector4> getSkinWeight()/*-{ return this.skinWeights; }-*/; //maybe public native final JsArray<JsArray<Vector2>> getFaceVertexUvs ()/*-{ return this["faceVertexUvs"][0]; }-*/; public native final Geometry clone()/*-{ return this.clone(); }-*/; public final native JsArray<Vector3> getVertices()/*-{ return this.vertices; }-*/; public final native void setVertices(JsArray<Vector3> vertices)/*-{ this.vertices = vertices; }-*/; public final native JsArray<Color> getColors()/*-{ return this.colors; }-*/; public final native void setColors(JsArray<Color> colors)/*-{ this.colors = colors; }-*/; public final native JsArray<Face3> getFaces()/*-{ return this.faces; }-*/; public final native void setFaces(JsArray<Face3> faces)/*-{ this.faces = faces; }-*/; public final native void setFaceVertexUvs(JsArray<JavaScriptObject> faceVertexUvs)/*-{ this.faceVertexUvs = faceVertexUvs; }-*/; public final native void setMorphTargets(JsArray<MorphTarget> morphTargets)/*-{ this.morphTargets = morphTargets; }-*/; public final native JsArray<Color> getMorphColors()/*-{ return this.morphColors; }-*/; public final native void setMorphColors(JsArray<Color> morphColors)/*-{ this.morphColors = morphColors; }-*/; public final native JsArray<Vector3> getMorphNormals()/*-{ return this.morphNormals; }-*/; public final native void setMorphNormals(JsArray<Vector3> morphNormals)/*-{ this.morphNormals = morphNormals; }-*/; public final native JsArray<Vector4> getSkinWeights()/*-{ return this.skinWeights; }-*/; public final native void setSkinWeights(JsArray<Vector4> skinWeights)/*-{ this.skinWeights = skinWeights; }-*/; public final native JsArrayNumber getLineDistances()/*-{ return this.lineDistances; }-*/; public final native void setLineDistances(JsArrayNumber lineDistances)/*-{ this.lineDistances = lineDistances; }-*/; public final native void setBoundingBox(Object boundingBox)/*-{ this.boundingBox = boundingBox; }-*/; public final native Object getBoundingSphere()/*-{ return this.boundingSphere; }-*/; public final native void setBoundingSphere(Object boundingSphere)/*-{ this.boundingSphere = boundingSphere; }-*/; public final native boolean isHasTangents()/*-{ return this.hasTangents; }-*/; public final native void setHasTangents(boolean hasTangents)/*-{ this.hasTangents = hasTangents; }-*/; public final native void setDynamic(Object dynamic)/*-{ this.dynamic = dynamic; }-*/; public final native boolean isLineDistancesNeedUpdate()/*-{ return this.lineDistancesNeedUpdate; }-*/; public final native void setLineDistancesNeedUpdate(boolean lineDistancesNeedUpdate)/*-{ this.lineDistancesNeedUpdate = lineDistancesNeedUpdate; }-*/; public final native boolean isBuffersNeedUpdate()/*-{ return this.buffersNeedUpdate; }-*/; public final native void setBuffersNeedUpdate(boolean buffersNeedUpdate)/*-{ this.buffersNeedUpdate = buffersNeedUpdate; }-*/; public final native void applyMatrix(Object matrix)/*-{ this.applyMatrix(matrix); }-*/; public final native void computeVertexNormals(boolean areaWeighted)/*-{ this.computeVertexNormals(areaWeighted); }-*/; public final native void computeMorphNormals()/*-{ this.computeMorphNormals(); }-*/; public final native Object mergeVertices()/*-{ return this.mergeVertices(); }-*/; public final native void dispose()/*-{ this.dispose(); }-*/; }
support animations
src/com/akjava/gwt/three/client/js/core/Geometry.java
support animations
<ide><path>rc/com/akjava/gwt/three/client/js/core/Geometry.java <ide> }-*/; <ide> <ide> <add>public final native JsArray<AnimationData> getAnimations()/*-{ <add>return this.animation; <add>}-*/; <add> <ide> public final native AnimationData getAnimation()/*-{ <ide> return this.animation; <ide> }-*/;
Java
mit
1de107ca6686fbcd75eefdb92fc120ad18915fc4
0
i-net-software/jlessc,i-net-software/jlessc
/** * MIT License (MIT) * * Copyright (c) 2014 - 2018 Volker Berlin * * 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, * UT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. * * @author Volker Berlin * @license: The MIT license <http://opensource.org/licenses/MIT> */ package com.inet.lib.less; import java.util.ArrayList; import java.util.Collections; import java.util.HashMap; import java.util.LinkedHashMap; import java.util.List; import java.util.Map; import javax.annotation.Nullable; /** * A single CSS rule or mixin. */ class Rule extends LessObject implements Formattable, FormattableContainer { private static final HashMap<String, Expression> NO_MATCH = new HashMap<>(); private FormattableContainer parent; private String[] selectors; private final List<Expression> params; private VariableExpression varArg; private Expression guard; private List<Formattable> properties = new ArrayList<>(); private List<Rule> subrules = new ArrayList<>(); private HashMap<String, Expression> variables = new HashMap<>(); private HashMultimap<String, Rule> mixins; /** * Create new instance. * * @param obj another LessObject with parse position. * @param parent the parent in the hierarchy * @param selectors the selectors of the rule * @param params the parameter if the rule is a mixin. * @param guard a guard condition for the mixin or CSS rule */ Rule( LessObject obj, FormattableContainer parent, String selectors, @Nullable Operation params, Expression guard ) { super( obj ); this.parent = parent; this.mixins = new HashMultimap<>( parent.getMixins() ); this.selectors = SelectorUtils.split( selectors ); if( params == null ) { this.params = null; } else { this.params = params.getOperands(); int count = this.params.size(); if( count > 0 ) { Expression lastEx = this.params.get( count-1 ); if( lastEx.getClass() == VariableExpression.class || lastEx.getClass() == ValueExpression.class ) { String name = lastEx.toString(); if( name.endsWith( "..." ) ) { varArg = new VariableExpression( lastEx, name.substring( 0, name.length() - 3 ) ); this.params.remove( count-1 ); } } } } this.guard = guard; } /** * {@inheritDoc} */ @Override public final int getType() { return RULE; } /** * {@inheritDoc} */ @Override public void prepare( CssFormatter formatter ) { for( Formattable prop : properties ) { prop.prepare( formatter ); } } /** * {@inheritDoc} */ @Override public void add( Formattable formattable ) { properties.add( formattable ); if( formattable instanceof Rule ) { subrules.add( (Rule)formattable ); } } /** * {@inheritDoc} */ @Override public void appendTo( CssFormatter formatter ) { if( isValidCSS( formatter ) ) { try { appendTo( null, formatter ); } catch( LessException ex ) { ex.addPosition( filename, line, column ); throw ex; } } } /** * Append this rule the formatter. * * @param mainSelector optional selectors of the calling rule if this is a mixin. * @param formatter current formatter */ void appendTo( @Nullable String[] mainSelector, CssFormatter formatter ) { try { String[] sel = selectors; for( int s = 0; s < sel.length; s++ ) { final String selector = sel[s]; String str = SelectorUtils.replacePlaceHolder( formatter, selector, this ); if( selector != str ) { if( sel == selectors ) { sel = sel.clone(); // we does not want change the declaration of this selectors } sel[s] = str; } } if( mainSelector == null ) { // main ruls for( int i = 0; i < sel.length; i++ ) { sel[i] = SelectorUtils.fastReplace( sel[i], "&", "" ); } } else if( sel[0].charAt( 0 ) == '@' ) { // media bubbling( sel, mainSelector, formatter ); return; } else { sel = SelectorUtils.merge( mainSelector, sel ); } formatter.addMixin( this, null, variables ); if( sel[0].startsWith( "@" ) ) { ruleset( sel, formatter ); } else { if( properties.size() > 0 ) { int size0 = formatter.getOutputSize(); CssFormatter block = formatter.startBlock( sel ); int size1 = block.getOutputSize(); appendPropertiesTo( block ); int size2 = block.getOutputSize(); block.endBlock(); if( block == formatter && size1 == size2 ) { formatter.setOutputSize( size0 ); } } for( Formattable prop : properties ) { if( prop instanceof Mixin ) { ((Mixin)prop).appendSubRules( sel, formatter ); } } for( Rule rule : subrules ) { if( rule.isValidCSS( formatter ) && !rule.isInlineRule( formatter) ) { rule.appendTo( params != null ? mainSelector : sel, formatter ); } } } formatter.removeMixin(); } catch( LessException ex ) { ex.addPosition( filename, line, column ); throw ex; } catch( Exception ex ) { throw createException( ex ); } } /** * Nested Directives are bubbling. * * @param mediaSelector * the selector of the media, must start with an @ * @param blockSelector * current block selector * @param formatter * current formatter */ private void bubbling( String[] mediaSelector, String[] blockSelector, CssFormatter formatter ) { if( properties.size() > 0 ) { String media = mediaSelector[0]; if( media.startsWith( "@media" ) || media.startsWith( "@supports" ) || media.startsWith( "@document" ) ) { // conditional directives int size0 = formatter.getOutputSize(); CssFormatter block = formatter.startBlock( mediaSelector ); if( block != formatter ) { size0 = block.getOutputSize(); } CssFormatter block2 = block.startBlock( blockSelector ); int size1 = block2.getOutputSize(); appendPropertiesTo( block2 ); int size2 = block2.getOutputSize(); block2.endBlock(); int size3 = block.getOutputSize(); for( Formattable prop : properties ) { if( prop instanceof Mixin ) { ((Mixin)prop).appendSubRules( blockSelector, block ); } } int size4 = block.getOutputSize(); block.endBlock(); if( size1 == size2 && size3 == size4 ) { block.setOutputSize( size0 ); } } else { // non-conditional directives for example @font-face or @keyframes CssFormatter block = formatter.startBlock( mediaSelector ); appendPropertiesTo( block ); for( Rule rule : subrules ) { rule.appendTo( null, block ); } block.endBlock(); return; } } for( Rule rule : subrules ) { final String[] ruleSelector = rule.getSelectors(); String name = ruleSelector[0]; name = SelectorUtils.replacePlaceHolder( formatter, name, this ); if( name.startsWith( "@media" ) ) { rule.bubbling( new String[]{mediaSelector[0] + " and " + name.substring( 6 ).trim()}, blockSelector, formatter ); } else { rule.bubbling( mediaSelector, SelectorUtils.merge( blockSelector, ruleSelector ), formatter ); } } } /** * Directives like @media in the root. * * @param sel the selectors * @param formatter current formatter */ private void ruleset( String[] sel, CssFormatter formatter ) { formatter = formatter.startBlock( sel ); appendPropertiesTo( formatter ); for( Formattable prop : properties ) { if( prop instanceof Mixin ) { ((Mixin)prop).appendSubRules( null, formatter ); } } for( Rule rule : subrules ) { rule.appendTo( formatter ); } formatter.endBlock(); } /** * Append the mixins of this rule to current output. * * @param parentSelector the resulting parent selector * @param formatter current formatter */ void appendMixinsTo( String[] parentSelector, CssFormatter formatter ) { for( Formattable prop : properties ) { switch( prop.getType()) { case MIXIN: ((Mixin)prop).appendSubRules( parentSelector, formatter ); break; case CSS_AT_RULE: case COMMENT: prop.appendTo( formatter ); break; } } } /** * Append the properties of the rule. * * @param formatter current formatter */ void appendPropertiesTo( CssFormatter formatter ) { if( properties.isEmpty() ) { return; } formatter.addVariables( variables ); for( Formattable prop : properties ) { switch( prop.getType() ) { case Formattable.RULE: Rule rule = (Rule)prop; // inline rules if( rule.isValidCSS( formatter ) && rule.isInlineRule( formatter) ) { rule.appendPropertiesTo( formatter ); } break; default: prop.appendTo( formatter ); } } formatter.removeVariables( variables ); } /** * Get the mixin parameters as map if the given param values match to this rule. * @param formatter current formatter * @param paramValues the values of the caller * @return null, if empty list match; NO_MATCH, if the values not match to the params of this list, Or the map with the parameters */ private Map<String, Expression> getMixinParams( CssFormatter formatter, List<Expression> paramValues ) { if( (params == null && paramValues == null) || (paramValues == null && params.size() == 0) || (params == null && paramValues.size() == 0) ) { return null; } if( params == null && paramValues != null ) { return NO_MATCH; } if( paramValues == null ) { paramValues = Collections.emptyList(); } if( params.size() < paramValues.size() && varArg == null ) { return NO_MATCH; } try { Map<String, Expression> vars = new LinkedHashMap<>(); // Set the parameters with default values first int paramsCount = params.size(); for( int i = 0; i < paramsCount; i++ ) { Expression param = params.get( i ); Class<?> paramType = param.getClass(); if( paramType == Operation.class && ((Operation)param).getOperator() == ':' && ((Operation)param).getOperands().size() == 2 ) { ArrayList<Expression> keyValue = ((Operation)param).getOperands(); String name = keyValue.get( 0 ).toString(); vars.put( name, ValueExpression.eval( formatter, keyValue.get( 1 ) ) ); } } // Set the calling values as parameters paramsCount = Math.min( paramsCount, paramValues.size() ); for( int i = 0; i < paramsCount; i++ ) { Expression value = paramValues.get( i ); Class<?> valueType = value.getClass(); // First check if it is a named parameter if( valueType == Operation.class && ((Operation)value).getOperator() == ':' && ((Operation)value).getOperands().size() == 2 ) { ArrayList<Expression> keyValue = ((Operation)value).getOperands(); vars.put( keyValue.get( 0 ).toString(), ValueExpression.eval( formatter, keyValue.get( 1 ) ) ); } else { Expression param = params.get( i ); Class<?> paramType = param.getClass(); if( paramType == VariableExpression.class ) { vars.put( param.toString(), ValueExpression.eval( formatter, value ) ); } else if( paramType == Operation.class && ((Operation)param).getOperator() == ':' && ((Operation)param).getOperands().size() == 2 ) { ArrayList<Expression> keyValue = ((Operation)param).getOperands(); vars.put( keyValue.get( 0 ).toString(), ValueExpression.eval( formatter, value ) ); } else if( paramType == ValueExpression.class ) { //pseudo guard, mixin with static parameter final Operation op = new Operation( param, param, '=' ); op.addOperand( value ); if( !op.booleanValue( formatter ) ) { return NO_MATCH; } vars.put( " " + i, value ); } else { throw createException( "Wrong formatted parameters: " + params ); } } } if( varArg != null ) { Operation value = new Operation( varArg ); for( int i = params.size(); i < paramValues.size(); i++ ) { value.addOperand( ValueExpression.eval( formatter, paramValues.get( i ) ) ); } if( vars.size() == params.size() ) { vars.put( varArg.toString(), value ); return vars; } return NO_MATCH; } if( vars.size() == params.size() ) { return vars; } return NO_MATCH; } catch( LessException ex ) { ex.addPosition( filename, line, column ); throw ex; } } /** * The selectors of the rule. * * @return the selectors */ String[] getSelectors() { return selectors; } /** * {@inheritDoc} */ @Override public HashMap<String, Expression> getVariables() { return variables; } /** * {@inheritDoc} */ @Override public HashMultimap<String, Rule> getMixins() { return mixins; } /** * get the subrules if there any. * @return the rules or an empty list. */ List<Rule> getSubrules() { return subrules; } /** * Get a nested mixin of this rule. * * @param name * the name of the mixin * @return the mixin or null */ List<Rule> getMixin( String name ) { ArrayList<Rule> rules = null; for( Rule rule : subrules ) { for( String sel : rule.selectors ) { if( name.equals( sel ) ) { if( rules == null ) { rules = new ArrayList<>(); } rules.add( rule ); break; } } } return rules; } /** * String only for debugging. * * @return the debug info */ @Override public String toString() { CssFormatter formatter = new CssFormatter(); try { appendTo( null, formatter ); } catch( Exception ex ) { formatter.getOutput(); formatter.append( ex.toString() ); } return formatter.releaseOutput(); } /** * If this mixin match the calling parameters. * * @param formatter current formatter * @param paramValues calling parameters * @param isDefault the value of the keyword "default" in guard. * @return the match or null if there is no match of the parameter lists */ MixinMatch match( CssFormatter formatter, List<Expression> paramValues, boolean isDefault ) { if( guard == null && formatter.containsRule( this ) ) { return null; } Map<String, Expression> mixinParameters = getMixinParams( formatter, paramValues ); if( mixinParameters == NO_MATCH ) { return null; } boolean matching = true; if( guard != null ) { formatter.addGuardParameters( mixinParameters, isDefault ); matching = guard.booleanValue( formatter ); formatter.removeGuardParameters( mixinParameters ); } return new MixinMatch( this, mixinParameters, matching, formatter.wasDefaultFunction() ); } /** * If this is a mixin or a CSS rule. * * @return true, if it is a mixin. */ boolean isMixin() { return params != null; } /** * If this rule is a CSS rule (not a mixin declaration) and if an guard exists if it true. * * @param formatter the CCS target * @return true, if a CSS rule */ private boolean isValidCSS( CssFormatter formatter ) { if( params == null ) { if( guard != null ) { //CSS Guards // guard = ValueExpression.eval( formatter, guard ); return guard.booleanValue( formatter ); } return true; } return false; } /** * If there is only a special selector "&" and also all subrules have only this special selector. * * @param formatter current formatter * @return true, if selector is "&" */ boolean isInlineRule( CssFormatter formatter ) { if( selectors.length == 1 && selectors[0].equals( "&" ) ) { return hasOnlyInlineProperties( formatter ); } return false; } /** * If there are only properties that should be inlined. * * @param formatter current formatter * @return true, if only inline */ boolean hasOnlyInlineProperties( CssFormatter formatter ) { for( Formattable prop : properties ) { if( prop instanceof Mixin ) { return false; } } for( Rule rule : subrules ) { if( rule.isValidCSS( formatter ) /*&& !rule.isInlineRule( formatter)*/ ) { return false; } } return true; } }
src/com/inet/lib/less/Rule.java
/** * MIT License (MIT) * * Copyright (c) 2014 - 2018 Volker Berlin * * 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, * UT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. * * @author Volker Berlin * @license: The MIT license <http://opensource.org/licenses/MIT> */ package com.inet.lib.less; import java.util.ArrayList; import java.util.Collections; import java.util.HashMap; import java.util.LinkedHashMap; import java.util.List; import java.util.Map; import javax.annotation.Nullable; /** * A single CSS rule or mixin. */ class Rule extends LessObject implements Formattable, FormattableContainer { private static final HashMap<String, Expression> NO_MATCH = new HashMap<>(); private FormattableContainer parent; private String[] selectors; private final List<Expression> params; private VariableExpression varArg; private Expression guard; private List<Formattable> properties = new ArrayList<>(); private List<Rule> subrules = new ArrayList<>(); private HashMap<String, Expression> variables = new HashMap<>(); private HashMultimap<String, Rule> mixins; /** * Create new instance. * * @param obj another LessObject with parse position. * @param parent the parent in the hierarchy * @param selectors the selectors of the rule * @param params the parameter if the rule is a mixin. * @param guard a guard condition for the mixin or CSS rule */ Rule( LessObject obj, FormattableContainer parent, String selectors, @Nullable Operation params, Expression guard ) { super( obj ); this.parent = parent; this.mixins = new HashMultimap<>( parent.getMixins() ); this.selectors = SelectorUtils.split( selectors ); if( params == null ) { this.params = null; } else { this.params = params.getOperands(); int count = this.params.size(); if( count > 0 ) { Expression lastEx = this.params.get( count-1 ); if( lastEx.getClass() == VariableExpression.class || lastEx.getClass() == ValueExpression.class ) { String name = lastEx.toString(); if( name.endsWith( "..." ) ) { varArg = new VariableExpression( lastEx, name.substring( 0, name.length() - 3 ) ); this.params.remove( count-1 ); } } } } this.guard = guard; } /** * {@inheritDoc} */ @Override public final int getType() { return RULE; } /** * {@inheritDoc} */ @Override public void prepare( CssFormatter formatter ) { for( Formattable prop : properties ) { prop.prepare( formatter ); } } /** * {@inheritDoc} */ @Override public void add( Formattable formattable ) { properties.add( formattable ); if( formattable instanceof Rule ) { subrules.add( (Rule)formattable ); } } /** * {@inheritDoc} */ @Override public void appendTo( CssFormatter formatter ) { if( isValidCSS( formatter ) ) { try { appendTo( null, formatter ); } catch( LessException ex ) { ex.addPosition( filename, line, column ); throw ex; } } } /** * Append this rule the formatter. * * @param mainSelector optional selectors of the calling rule if this is a mixin. * @param formatter current formatter */ void appendTo( @Nullable String[] mainSelector, CssFormatter formatter ) { try { String[] sel = selectors; for( int s = 0; s < sel.length; s++ ) { final String selector = sel[s]; String str = SelectorUtils.replacePlaceHolder( formatter, selector, this ); if( selector != str ) { if( sel == selectors ) { sel = sel.clone(); // we does not want change the declaration of this selectors } sel[s] = str; } } if( mainSelector == null ) { // main ruls for( int i = 0; i < sel.length; i++ ) { sel[i] = SelectorUtils.fastReplace( sel[i], "&", "" ); } } else if( sel[0].charAt( 0 ) == '@' ) { // media bubbling( sel, mainSelector, formatter ); return; } else { sel = SelectorUtils.merge( mainSelector, sel ); } formatter.addMixin( this, null, variables ); if( sel[0].startsWith( "@" ) ) { ruleset( sel, formatter ); } else { if( properties.size() > 0 ) { int size0 = formatter.getOutputSize(); CssFormatter block = formatter.startBlock( sel ); int size1 = block.getOutputSize(); appendPropertiesTo( block ); int size2 = block.getOutputSize(); block.endBlock(); if( block == formatter && size1 == size2 ) { formatter.setOutputSize( size0 ); } } for( Formattable prop : properties ) { if( prop instanceof Mixin ) { ((Mixin)prop).appendSubRules( sel, formatter ); } } for( Rule rule : subrules ) { if( rule.isValidCSS( formatter ) && !rule.isInlineRule( formatter) ) { rule.appendTo( params != null ? mainSelector : sel, formatter ); } } } formatter.removeMixin(); } catch( LessException ex ) { ex.addPosition( filename, line, column ); throw ex; } catch( Exception ex ) { throw createException( ex ); } } /** * Nested Directives are bubbling. * * @param mediaSelector * the selector of the media, must start with an @ * @param blockSelector * current block selector * @param formatter * current formatter */ private void bubbling( String[] mediaSelector, String[] blockSelector, CssFormatter formatter ) { if( properties.size() > 0 ) { String media = mediaSelector[0]; if( media.startsWith( "@media" ) || media.startsWith( "@supports" ) || media.startsWith( "@document" ) ) { // conditional directives int size0 = formatter.getOutputSize(); CssFormatter block = formatter.startBlock( mediaSelector ); if( block != formatter ) { size0 = block.getOutputSize(); } CssFormatter block2 = block.startBlock( blockSelector ); int size1 = block2.getOutputSize(); appendPropertiesTo( block2 ); int size2 = block2.getOutputSize(); block2.endBlock(); int size3 = block.getOutputSize(); for( Formattable prop : properties ) { if( prop instanceof Mixin ) { ((Mixin)prop).appendSubRules( blockSelector, block ); } } int size4 = block.getOutputSize(); block.endBlock(); if( size1 == size2 && size3 == size4 ) { block.setOutputSize( size0 ); } } else { // non-conditional directives for example @font-face or @keyframes CssFormatter block = formatter.startBlock( mediaSelector ); appendPropertiesTo( block ); for( Rule rule : subrules ) { rule.appendTo( null, block ); } block.endBlock(); return; } } for( Rule rule : subrules ) { final String[] ruleSelector = rule.getSelectors(); String name = ruleSelector[0]; name = SelectorUtils.replacePlaceHolder( formatter, name, this ); if( name.startsWith( "@media" ) ) { rule.bubbling( new String[]{mediaSelector[0] + " and " + name.substring( 6 ).trim()}, blockSelector, formatter ); } else { rule.bubbling( mediaSelector, SelectorUtils.merge( blockSelector, ruleSelector ), formatter ); } } } /** * Directives like @media in the root. * * @param sel the selectors * @param formatter current formatter */ private void ruleset( String[] sel, CssFormatter formatter ) { formatter = formatter.startBlock( sel ); appendPropertiesTo( formatter ); for( Formattable prop : properties ) { if( prop instanceof Mixin ) { ((Mixin)prop).appendSubRules( null, formatter ); } } for( Rule rule : subrules ) { rule.appendTo( formatter ); } formatter.endBlock(); } /** * Append the mixins of this rule to current output. * * @param parentSelector the resulting parent selector * @param formatter current formatter */ void appendMixinsTo( String[] parentSelector, CssFormatter formatter ) { for( Formattable prop : properties ) { switch( prop.getType()) { case MIXIN: ((Mixin)prop).appendSubRules( parentSelector, formatter ); break; case CSS_AT_RULE: case COMMENT: prop.appendTo( formatter ); break; } } } /** * Append the properties of the rule. * * @param formatter current formatter */ void appendPropertiesTo( CssFormatter formatter ) { if( properties.isEmpty() ) { return; } formatter.addVariables( variables ); for( Formattable prop : properties ) { switch( prop.getType() ) { case Formattable.RULE: Rule rule = (Rule)prop; // inline rules if( rule.isValidCSS( formatter ) && rule.isInlineRule( formatter) ) { rule.appendPropertiesTo( formatter ); } break; default: prop.appendTo( formatter ); } } formatter.removeVariables( variables ); } /** * Get the mixin parameters as map if the given param values match to this rule. * @param formatter current formatter * @param paramValues the values of the caller * @return null, if empty list match; NO_MATCH, if the values not match to the params of this list, Or the map with the parameters */ private Map<String, Expression> getMixinParams( CssFormatter formatter, List<Expression> paramValues ) { if( (params == null && paramValues == null) || (paramValues == null && params.size() == 0) || (params == null && paramValues.size() == 0) ) { return null; } if( params == null && paramValues != null ) { return NO_MATCH; } if( paramValues == null ) { paramValues = Collections.emptyList(); } if( params.size() < paramValues.size() && varArg == null ) { return NO_MATCH; } try { Map<String, Expression> vars = new LinkedHashMap<>(); // Set the parameters with default values first int paramsCount = params.size(); for( int i = 0; i < paramsCount; i++ ) { Expression param = params.get( i ); Class<?> paramType = param.getClass(); if( paramType == Operation.class && ((Operation)param).getOperator() == ':' && ((Operation)param).getOperands().size() == 2 ) { ArrayList<Expression> keyValue = ((Operation)param).getOperands(); String name = keyValue.get( 0 ).toString(); vars.put( name, ValueExpression.eval( formatter, keyValue.get( 1 ) ) ); } } // Set the calling values as parameters paramsCount = Math.min( paramsCount, paramValues.size() ); for( int i = 0; i < paramsCount; i++ ) { Expression value = paramValues.get( i ); Class<?> valueType = value.getClass(); // First check if it is a named parameter if( valueType == Operation.class && ((Operation)value).getOperator() == ':' && ((Operation)value).getOperands().size() == 2 ) { ArrayList<Expression> keyValue = ((Operation)value).getOperands(); vars.put( keyValue.get( 0 ).toString(), ValueExpression.eval( formatter, keyValue.get( 1 ) ) ); } else { Expression param = params.get( i ); Class<?> paramType = param.getClass(); if( paramType == VariableExpression.class ) { vars.put( param.toString(), ValueExpression.eval( formatter, value ) ); } else if( paramType == Operation.class && ((Operation)param).getOperator() == ':' && ((Operation)param).getOperands().size() == 2 ) { ArrayList<Expression> keyValue = ((Operation)param).getOperands(); vars.put( keyValue.get( 0 ).toString(), ValueExpression.eval( formatter, value ) ); } else if( paramType == ValueExpression.class ) { //pseudo guard, mixin with static parameter final Operation op = new Operation( param, param, '=' ); op.addOperand( value ); if( !op.booleanValue( formatter ) ) { return NO_MATCH; } vars.put( " " + i, value ); } else { throw createException( "Wrong formatted parameters: " + params ); } } } if( varArg != null ) { Operation value = new Operation( varArg ); for( int i = params.size(); i < paramValues.size(); i++ ) { value.addOperand( ValueExpression.eval( formatter, paramValues.get( i ) ) ); } if( vars.size() == params.size() ) { vars.put( varArg.toString(), value ); return vars; } return NO_MATCH; } if( vars.size() == params.size() ) { return vars; } return NO_MATCH; } catch( LessException ex ) { ex.addPosition( filename, line, column ); throw ex; } } /** * The selectors of the rule. * * @return the selectors */ String[] getSelectors() { return selectors; } /** * {@inheritDoc} */ @Override public HashMap<String, Expression> getVariables() { return variables; } /** * {@inheritDoc} */ @Override public HashMultimap<String, Rule> getMixins() { return mixins; } /** * get the subrules if there any. * @return the rules or an empty list. */ List<Rule> getSubrules() { return subrules; } /** * Get a nested mixin of this rule. * * @param name * the name of the mixin * @return the mixin or null */ List<Rule> getMixin( String name ) { ArrayList<Rule> rules = null; for( Rule rule : subrules ) { for( String sel : rule.selectors ) { if( name.equals( sel ) ) { if( rules == null ) { rules = new ArrayList<>(); } rules.add( rule ); break; } } } return rules; } /** * String only for debugging. * * @return the debug info */ @Override public String toString() { CssFormatter formatter = new CssFormatter(); try { appendTo( null, formatter ); } catch( Exception ex ) { formatter.getOutput(); formatter.append( ex.toString() ); } return formatter.releaseOutput(); } /** * If this mixin match the calling parameters. * * @param formatter current formatter * @param paramValues calling parameters * @param isDefault the value of the keyword "default" in guard. * @return the match or null if there is no match of the parameter lists */ MixinMatch match( CssFormatter formatter, List<Expression> paramValues, boolean isDefault ) { if( guard == null && formatter.containsRule( this ) ) { return null; } Map<String, Expression> mixinParameters = getMixinParams( formatter, paramValues ); if( mixinParameters == NO_MATCH ) { return null; } boolean matching = true; if( guard != null ) { formatter.addGuardParameters( mixinParameters, isDefault ); matching = guard.booleanValue( formatter ); formatter.removeGuardParameters( mixinParameters ); } return new MixinMatch( this, mixinParameters, matching, formatter.wasDefaultFunction() ); } /** * If this is a mixin or a CSS rule. * * @return true, if it is a mixin. */ boolean isMixin() { return params != null; } /** * If this rule is a CSS rule (not a mixin declaration) and if an guard exists if it true. * * @param formatter the CCS target * @return true, if a CSS rule */ private boolean isValidCSS( CssFormatter formatter ) { if( params == null ) { if( guard != null ) { //CSS Guards // guard = ValueExpression.eval( formatter, guard ); return guard.booleanValue( formatter ); } return true; } return false; } /** * If there is only a special selector "&" and also all subrules have only this special selector. * * @param formatter current formatter * @return true, if selector is "&" */ boolean isInlineRule( CssFormatter formatter ) { if( selectors.length == 1 && selectors[0].equals( "&" ) ) { return hasOnlyInlineProperties( formatter ); } return false; } /** * If there are only properties that should be inlined. * * @param formatter current formatter * @return true, if only inline */ boolean hasOnlyInlineProperties( CssFormatter formatter ) { for( Formattable prop : properties ) { if( prop instanceof Mixin ) { return false; } } for( Rule rule : subrules ) { if( rule.isValidCSS( formatter ) && !rule.isInlineRule( formatter) ) { return false; } } return true; } }
remove not needed check. see #58
src/com/inet/lib/less/Rule.java
remove not needed check. see #58
<ide><path>rc/com/inet/lib/less/Rule.java <ide> } <ide> <ide> for( Rule rule : subrules ) { <del> if( rule.isValidCSS( formatter ) && !rule.isInlineRule( formatter) ) { <add> if( rule.isValidCSS( formatter ) /*&& !rule.isInlineRule( formatter)*/ ) { <ide> return false; <ide> } <ide> }
Java
apache-2.0
405a3a50d2e9979a40d294f1ce9ef87187fa8f33
0
jamescross91/dynamic-ad-feed-converter
package output.feed; import lombok.Data; import java.util.Currency; import java.util.Map; @Data public class GoogleFeed extends AdFeed { private String title; private String description; private String link; private String image_link; private String availability; private String google_product_category; private String price; public GoogleFeed(Map<String, String> data) { String id = data.get("id"); String title = data.get("title"); String description = data.get("description"); String link = data.get("link"); String image_link = data.get("image_link"); String availability = data.get("availability"); String price = data.get("price"); String google_product_category = data.get("google_product_category"); validateAndAssign(id, title, description, link, image_link, availability, price, google_product_category); } private void validateAndAssign(String id, String title, String description, String link, String imageLink, String availability, String price, String google_product_category) { validateLength(id, 50); this.id = id; validateLength(title, 150); this.title = title; validateLength(description, 5000); this.description = description; validateLength(link, 2000); this.link = link; validateLength(imageLink, 2000); this.image_link = imageLink; validateAvailability(availability); this.availability = availability; this.google_product_category = google_product_category; validatePrice(price); this.price = price; } private void validateLength(String value, int maxLength) { if (value.length() > maxLength) { throw new IllegalArgumentException("String of value " + value + " longer than " + maxLength); } } private void validateAvailability(String value) { if (!(value.equals("in stock") || value.equals("out of stock") || value.equals("preorder"))) { throw new IllegalArgumentException("Value " + value + " not valid for availability field"); } } private void validatePrice(String value) { String currCode = value.substring(value.length() - 3, value.length()); if (Currency.getInstance(currCode) == null) { throw new IllegalArgumentException("Invalid currency code " + currCode + " in price string " + value); } } }
src/main/java/output/feed/GoogleFeed.java
package output.feed; import lombok.Data; import java.util.Map; @Data public class GoogleFeed extends AdFeed { private String title; private String description; private String link; private String image_link; private String availability; private String google_product_category; private String price; public GoogleFeed( String id, String title, String description, String link, String image_link, String availability, String price, String google_product_category) { validateAndAssign(id, title, description, link, image_link, availability, price, google_product_category); } public GoogleFeed(Map<String, String> data) { String id = data.get("id"); String title = data.get("title"); String description = data.get("description"); String link = data.get("link"); String image_link = data.get("image_link"); String availability = data.get("availability"); String price = data.get("price"); String google_product_category = data.get("google_product_category"); validateAndAssign(id, title, description, link, image_link, availability, price, google_product_category); } private void validateAndAssign(String id, String title, String description, String link, String imageLink, String availability, String price, String google_product_category) { validateLength(id, 50); this.id = id; validateLength(title, 150); this.title = title; validateLength(description, 5000); this.description = description; validateLength(link, 2000); this.link = link; validateLength(imageLink, 2000); this.image_link = imageLink; validateAvailability(availability); this.availability = availability; this.google_product_category = google_product_category; validatePrice(price); this.price = price; } private void validateLength(String value, int maxLength) { // if(value.length() > maxLength) { // throw new IllegalArgumentException("String of value " + value + " longer than " + maxLength); // } } private void validateAvailability(String value) { // if (!value.equals("in stock") || !value.equals("out of stock") || !value.equals("preorder")) { // throw new IllegalArgumentException("Value " + value + " not valid for availability field"); // } } private void validatePrice(String value) { // String currCode = value.substring(value.length() - 3, value.length() - 1); // if(Currency.getInstance(currCode) == null) { // throw new IllegalArgumentException("Invalid currency code " + currCode + " in price string " + value); // } } }
Add ability to statically define data
src/main/java/output/feed/GoogleFeed.java
Add ability to statically define data
<ide><path>rc/main/java/output/feed/GoogleFeed.java <ide> <ide> import lombok.Data; <ide> <add>import java.util.Currency; <ide> import java.util.Map; <ide> <ide> @Data <ide> private String availability; <ide> private String google_product_category; <ide> private String price; <del> <del> public GoogleFeed( <del> String id, <del> String title, <del> String description, <del> String link, <del> String image_link, <del> String availability, <del> String price, <del> String google_product_category) { <del> <del> validateAndAssign(id, title, description, link, image_link, availability, price, google_product_category); <del> } <ide> <ide> public GoogleFeed(Map<String, String> data) { <ide> String id = data.get("id"); <ide> } <ide> <ide> private void validateLength(String value, int maxLength) { <del>// if(value.length() > maxLength) { <del>// throw new IllegalArgumentException("String of value " + value + " longer than " + maxLength); <del>// } <add> if (value.length() > maxLength) { <add> throw new IllegalArgumentException("String of value " + value + " longer than " + maxLength); <add> } <ide> } <ide> <ide> private void validateAvailability(String value) { <del>// if (!value.equals("in stock") || !value.equals("out of stock") || !value.equals("preorder")) { <del>// throw new IllegalArgumentException("Value " + value + " not valid for availability field"); <del>// } <add> if (!(value.equals("in stock") || value.equals("out of stock") || value.equals("preorder"))) { <add> throw new IllegalArgumentException("Value " + value + " not valid for availability field"); <add> } <ide> } <ide> <ide> private void validatePrice(String value) { <del>// String currCode = value.substring(value.length() - 3, value.length() - 1); <del>// if(Currency.getInstance(currCode) == null) { <del>// throw new IllegalArgumentException("Invalid currency code " + currCode + " in price string " + value); <del>// } <add> String currCode = value.substring(value.length() - 3, value.length()); <add> if (Currency.getInstance(currCode) == null) { <add> throw new IllegalArgumentException("Invalid currency code " + currCode + " in price string " + value); <add> } <ide> } <ide> }