repo_name stringlengths 7 104 | file_path stringlengths 13 198 | context stringlengths 67 7.15k | import_statement stringlengths 16 4.43k | code stringlengths 40 6.98k | prompt stringlengths 227 8.27k | next_line stringlengths 8 795 |
|---|---|---|---|---|---|---|
chrisipa/cloud-portal | modules/cloud-portal-server/src/main/java/de/papke/cloud/portal/service/MenuService.java | // Path: modules/cloud-portal-server/src/main/java/de/papke/cloud/portal/pojo/Menu.java
// public class Menu {
//
// private String title;
// private String path;
// private String icon;
// private boolean secure;
// private List<Menu> menus;
//
// public String getTitle() {
// return title;
// }
// public void setTitle(String title) {
// this.title = title;
// }
// public String getPath() {
// return path;
// }
// public void setPath(String path) {
// this.path = path;
// }
// public String getIcon() {
// return icon;
// }
// public void setIcon(String icon) {
// this.icon = icon;
// }
// public boolean isSecure() {
// return secure;
// }
// public void setSecure(boolean secure) {
// this.secure = secure;
// }
// public List<Menu> getMenus() {
// return menus;
// }
// public void setMenus(List<Menu> menus) {
// this.menus = menus;
// }
// }
| import java.io.InputStream;
import javax.annotation.PostConstruct;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;
import org.yaml.snakeyaml.Yaml;
import de.papke.cloud.portal.pojo.Menu; | package de.papke.cloud.portal.service;
@Service
public class MenuService {
private static final String MENU_CONFIG_FILE_PATH = "/menu/structure.yml";
private static final Logger LOG = LoggerFactory.getLogger(MenuService.class);
| // Path: modules/cloud-portal-server/src/main/java/de/papke/cloud/portal/pojo/Menu.java
// public class Menu {
//
// private String title;
// private String path;
// private String icon;
// private boolean secure;
// private List<Menu> menus;
//
// public String getTitle() {
// return title;
// }
// public void setTitle(String title) {
// this.title = title;
// }
// public String getPath() {
// return path;
// }
// public void setPath(String path) {
// this.path = path;
// }
// public String getIcon() {
// return icon;
// }
// public void setIcon(String icon) {
// this.icon = icon;
// }
// public boolean isSecure() {
// return secure;
// }
// public void setSecure(boolean secure) {
// this.secure = secure;
// }
// public List<Menu> getMenus() {
// return menus;
// }
// public void setMenus(List<Menu> menus) {
// this.menus = menus;
// }
// }
// Path: modules/cloud-portal-server/src/main/java/de/papke/cloud/portal/service/MenuService.java
import java.io.InputStream;
import javax.annotation.PostConstruct;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;
import org.yaml.snakeyaml.Yaml;
import de.papke.cloud.portal.pojo.Menu;
package de.papke.cloud.portal.service;
@Service
public class MenuService {
private static final String MENU_CONFIG_FILE_PATH = "/menu/structure.yml";
private static final Logger LOG = LoggerFactory.getLogger(MenuService.class);
| private Menu menu; |
chrisipa/cloud-portal | modules/cloud-portal-server/src/main/java/de/papke/cloud/portal/service/SessionUserService.java | // Path: modules/cloud-portal-server/src/main/java/de/papke/cloud/portal/pojo/ProvisionLog.java
// public class ProvisionLog {
//
// @Id
// private String id;
// private Date date;
// private Date expirationDate;
// private String username;
// private String group;
// private String command;
// private String useCaseId;
// private String provider;
// private Boolean success;
// private Map<String, Object> variableMap;
// private byte[] privateKey;
// private byte[] result;
//
// public ProvisionLog() {}
//
// public ProvisionLog(Date date, Date expirationDate, String username, String group, String command, String useCaseId, String provider, Boolean success, Map<String, Object> variableMap, byte[] privateKey, byte[] result) {
// super();
// this.date = date;
// this.expirationDate = expirationDate;
// this.username = username;
// this.group = group;
// this.command = command;
// this.useCaseId = useCaseId;
// this.provider = provider;
// this.success = success;
// this.variableMap = variableMap;
// this.privateKey = privateKey;
// this.result = result;
// }
//
// public String getId() {
// return id;
// }
//
// public void setId(String id) {
// this.id = id;
// }
//
// public Date getDate() {
// return date;
// }
//
// public void setDate(Date date) {
// this.date = date;
// }
//
// public Date getExpirationDate() {
// return expirationDate;
// }
//
// public void setExpirationDate(Date expirationDate) {
// this.expirationDate = expirationDate;
// }
//
// public String getUsername() {
// return username;
// }
//
// public void setUsername(String username) {
// this.username = username;
// }
//
// public String getGroup() {
// return group;
// }
//
// public void setGroup(String group) {
// this.group = group;
// }
//
// public String getCommand() {
// return command;
// }
//
// public void setCommand(String command) {
// this.command = command;
// }
//
// public String getUseCaseId() {
// return useCaseId;
// }
//
// public void setUseCaseId(String useCaseId) {
// this.useCaseId = useCaseId;
// }
//
// public String getProvider() {
// return provider;
// }
//
// public void setProvider(String provider) {
// this.provider = provider;
// }
//
// public Boolean getSuccess() {
// return success;
// }
//
// public void setSuccess(Boolean success) {
// this.success = success;
// }
//
// public Map<String, Object> getVariableMap() {
// return variableMap;
// }
//
// public void setVariableMap(Map<String, Object> variableMap) {
// this.variableMap = variableMap;
// }
//
// public byte[] getPrivateKey() {
// return privateKey;
// }
//
// public void setPrivateKey(byte[] privateKey) {
// this.privateKey = privateKey;
// }
//
// public byte[] getResult() {
// return result;
// }
//
// public void setResult(byte[] result) {
// this.result = result;
// }
// }
//
// Path: modules/cloud-portal-server/src/main/java/de/papke/cloud/portal/pojo/User.java
// public class User implements Serializable {
//
// private static final long serialVersionUID = 1L;
//
// private String username;
// private String givenName;
// private String surName;
// private String email;
// private List<String> groups;
// private boolean admin;
//
// public User() {}
//
// public User(String username, String givenName, String surName, String email, List<String> groups, boolean admin) {
// super();
// this.givenName = givenName;
// this.surName = surName;
// this.username = username;
// this.email = email;
// this.groups = groups;
// this.admin = admin;
// }
//
// public String getUsername() {
// return username;
// }
//
// public void setUsername(String username) {
// this.username = username;
// }
//
// public String getGivenName() {
// return givenName;
// }
//
// public void setGivenName(String givenName) {
// this.givenName = givenName;
// }
//
// public String getSurName() {
// return surName;
// }
//
// public void setSurName(String surName) {
// this.surName = surName;
// }
//
// public String getEmail() {
// return email;
// }
//
// public void setEmail(String email) {
// this.email = email;
// }
//
// public List<String> getGroups() {
// return groups;
// }
//
// public void setGroups(List<String> groups) {
// this.groups = groups;
// }
//
// public boolean isAdmin() {
// return admin;
// }
//
// public void setAdmin(boolean admin) {
// this.admin = admin;
// }
// }
| import java.util.ArrayList;
import javax.servlet.http.HttpSession;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import de.papke.cloud.portal.pojo.ProvisionLog;
import de.papke.cloud.portal.pojo.User; | package de.papke.cloud.portal.service;
@Service
public class SessionUserService {
private static final String SESSION_ATTRIBUTE_USER = "user"; | // Path: modules/cloud-portal-server/src/main/java/de/papke/cloud/portal/pojo/ProvisionLog.java
// public class ProvisionLog {
//
// @Id
// private String id;
// private Date date;
// private Date expirationDate;
// private String username;
// private String group;
// private String command;
// private String useCaseId;
// private String provider;
// private Boolean success;
// private Map<String, Object> variableMap;
// private byte[] privateKey;
// private byte[] result;
//
// public ProvisionLog() {}
//
// public ProvisionLog(Date date, Date expirationDate, String username, String group, String command, String useCaseId, String provider, Boolean success, Map<String, Object> variableMap, byte[] privateKey, byte[] result) {
// super();
// this.date = date;
// this.expirationDate = expirationDate;
// this.username = username;
// this.group = group;
// this.command = command;
// this.useCaseId = useCaseId;
// this.provider = provider;
// this.success = success;
// this.variableMap = variableMap;
// this.privateKey = privateKey;
// this.result = result;
// }
//
// public String getId() {
// return id;
// }
//
// public void setId(String id) {
// this.id = id;
// }
//
// public Date getDate() {
// return date;
// }
//
// public void setDate(Date date) {
// this.date = date;
// }
//
// public Date getExpirationDate() {
// return expirationDate;
// }
//
// public void setExpirationDate(Date expirationDate) {
// this.expirationDate = expirationDate;
// }
//
// public String getUsername() {
// return username;
// }
//
// public void setUsername(String username) {
// this.username = username;
// }
//
// public String getGroup() {
// return group;
// }
//
// public void setGroup(String group) {
// this.group = group;
// }
//
// public String getCommand() {
// return command;
// }
//
// public void setCommand(String command) {
// this.command = command;
// }
//
// public String getUseCaseId() {
// return useCaseId;
// }
//
// public void setUseCaseId(String useCaseId) {
// this.useCaseId = useCaseId;
// }
//
// public String getProvider() {
// return provider;
// }
//
// public void setProvider(String provider) {
// this.provider = provider;
// }
//
// public Boolean getSuccess() {
// return success;
// }
//
// public void setSuccess(Boolean success) {
// this.success = success;
// }
//
// public Map<String, Object> getVariableMap() {
// return variableMap;
// }
//
// public void setVariableMap(Map<String, Object> variableMap) {
// this.variableMap = variableMap;
// }
//
// public byte[] getPrivateKey() {
// return privateKey;
// }
//
// public void setPrivateKey(byte[] privateKey) {
// this.privateKey = privateKey;
// }
//
// public byte[] getResult() {
// return result;
// }
//
// public void setResult(byte[] result) {
// this.result = result;
// }
// }
//
// Path: modules/cloud-portal-server/src/main/java/de/papke/cloud/portal/pojo/User.java
// public class User implements Serializable {
//
// private static final long serialVersionUID = 1L;
//
// private String username;
// private String givenName;
// private String surName;
// private String email;
// private List<String> groups;
// private boolean admin;
//
// public User() {}
//
// public User(String username, String givenName, String surName, String email, List<String> groups, boolean admin) {
// super();
// this.givenName = givenName;
// this.surName = surName;
// this.username = username;
// this.email = email;
// this.groups = groups;
// this.admin = admin;
// }
//
// public String getUsername() {
// return username;
// }
//
// public void setUsername(String username) {
// this.username = username;
// }
//
// public String getGivenName() {
// return givenName;
// }
//
// public void setGivenName(String givenName) {
// this.givenName = givenName;
// }
//
// public String getSurName() {
// return surName;
// }
//
// public void setSurName(String surName) {
// this.surName = surName;
// }
//
// public String getEmail() {
// return email;
// }
//
// public void setEmail(String email) {
// this.email = email;
// }
//
// public List<String> getGroups() {
// return groups;
// }
//
// public void setGroups(List<String> groups) {
// this.groups = groups;
// }
//
// public boolean isAdmin() {
// return admin;
// }
//
// public void setAdmin(boolean admin) {
// this.admin = admin;
// }
// }
// Path: modules/cloud-portal-server/src/main/java/de/papke/cloud/portal/service/SessionUserService.java
import java.util.ArrayList;
import javax.servlet.http.HttpSession;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import de.papke.cloud.portal.pojo.ProvisionLog;
import de.papke.cloud.portal.pojo.User;
package de.papke.cloud.portal.service;
@Service
public class SessionUserService {
private static final String SESSION_ATTRIBUTE_USER = "user"; | private static final User DUMMY_USER = new User("anonymous", "Anonymous", "User", "dummy@dummy.com", new ArrayList<>(), false); |
chrisipa/cloud-portal | modules/cloud-portal-server/src/main/java/de/papke/cloud/portal/service/ScriptingConsoleService.java | // Path: modules/cloud-portal-server/src/main/java/de/papke/cloud/portal/constants/Constants.java
// public class Constants {
//
// public static final String CHAR_EMPTY = "";
// public static final String CHAR_STAR = "*";
// public static final String CHAR_DIAMOND = "#";
// public static final String CHAR_EQUAL = "=";
// public static final String CHAR_DASH = "-";
// public static final String CHAR_UNDERSCORE = "_";
// public static final String CHAR_WHITESPACE = " ";
// public static final String CHAR_DOUBLE_QUOTE = "\"";
// public static final String CHAR_SINGLE_QUOTE = "'";
// public static final String CHAR_NEW_LINE = "\n";
// public static final String CHAR_TAB = "\t";
// public static final String CHAR_DOT = ".";
// public static final String CHAR_DOUBLE_DOT = ":";
// public static final String CHAR_BRACE_OPEN = "{";
// public static final String CHAR_BRACE_CLOSE = "}";
// public static final String CHAR_BRAKET_OPEN = "[";
// public static final String CHAR_BRAKET_CLOSE = "]";
// public static final String CHAR_COMMA = ",";
// public static final String CHAR_PARENTHESES_OPEN = "(";
// public static final String CHAR_PARENTHESES_CLOSE = ")";
//
// public static final String ACTION_INIT = "init";
// public static final String ACTION_APPLY = "apply";
// public static final String ACTION_PLAN = "plan";
// public static final String ACTION_DESTROY = "destroy";
//
// public static final String VM_EXPIRATION_DAYS_STRING = "expiration_days";
//
// public static final String KEY_FILE_PREFIX = "id_rsa";
// public static final String KEY_FILE_PUBLIC_SUFFIX = ".pub";
// public static final String KEY_FILE_PRIVATE_SUFFIX = ".pem";
//
// public static final String RESULT_FILE_PREFIX = "result";
// public static final String RESULT_FILE_SUFFIX = ".zip";
//
// public static final String TMP_FOLDER_PREFIX = System.getProperty("java.io.tmpdir") + "/tmp-";
//
// public static final String FOLDER_CONSOLE = "console";
// public static final String FOLDER_USE_CASE = "usecase";
// public static final String FOLDER_PROVISIONER = "provisioner";
// public static final String FOLDER_TERRAFORM = "terraform";
//
// public static final String VAR_TYPE_SECRET = "secret";
//
// public static final String PROVISIONER_ESXI = "esxi";
//
// public static final String RESPONSE_CONTENT_TYPE_TEXT_PLAIN = "text/plain; charset=utf-8";
//
// private Constants() {}
// }
| import java.io.File;
import java.io.PrintWriter;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import javax.annotation.PostConstruct;
import org.apache.commons.io.FileUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.stereotype.Service;
import de.papke.cloud.portal.constants.Constants; | package de.papke.cloud.portal.service;
@Service
public class ScriptingConsoleService {
private static final Logger LOG = LoggerFactory.getLogger(ScriptingConsoleService.class);
private static final String FILE_EXAMPLE = "example.groovy";
private String exampleFileString;
private Map<String, Object> variableMap;
private List<String> variableList;
@Autowired
private ApplicationContext applicationContext;
@Autowired
private GroovyService groovyService;
@Autowired
private ResourceService resourceService;
@PostConstruct
private void init() {
try {
// get example file as string | // Path: modules/cloud-portal-server/src/main/java/de/papke/cloud/portal/constants/Constants.java
// public class Constants {
//
// public static final String CHAR_EMPTY = "";
// public static final String CHAR_STAR = "*";
// public static final String CHAR_DIAMOND = "#";
// public static final String CHAR_EQUAL = "=";
// public static final String CHAR_DASH = "-";
// public static final String CHAR_UNDERSCORE = "_";
// public static final String CHAR_WHITESPACE = " ";
// public static final String CHAR_DOUBLE_QUOTE = "\"";
// public static final String CHAR_SINGLE_QUOTE = "'";
// public static final String CHAR_NEW_LINE = "\n";
// public static final String CHAR_TAB = "\t";
// public static final String CHAR_DOT = ".";
// public static final String CHAR_DOUBLE_DOT = ":";
// public static final String CHAR_BRACE_OPEN = "{";
// public static final String CHAR_BRACE_CLOSE = "}";
// public static final String CHAR_BRAKET_OPEN = "[";
// public static final String CHAR_BRAKET_CLOSE = "]";
// public static final String CHAR_COMMA = ",";
// public static final String CHAR_PARENTHESES_OPEN = "(";
// public static final String CHAR_PARENTHESES_CLOSE = ")";
//
// public static final String ACTION_INIT = "init";
// public static final String ACTION_APPLY = "apply";
// public static final String ACTION_PLAN = "plan";
// public static final String ACTION_DESTROY = "destroy";
//
// public static final String VM_EXPIRATION_DAYS_STRING = "expiration_days";
//
// public static final String KEY_FILE_PREFIX = "id_rsa";
// public static final String KEY_FILE_PUBLIC_SUFFIX = ".pub";
// public static final String KEY_FILE_PRIVATE_SUFFIX = ".pem";
//
// public static final String RESULT_FILE_PREFIX = "result";
// public static final String RESULT_FILE_SUFFIX = ".zip";
//
// public static final String TMP_FOLDER_PREFIX = System.getProperty("java.io.tmpdir") + "/tmp-";
//
// public static final String FOLDER_CONSOLE = "console";
// public static final String FOLDER_USE_CASE = "usecase";
// public static final String FOLDER_PROVISIONER = "provisioner";
// public static final String FOLDER_TERRAFORM = "terraform";
//
// public static final String VAR_TYPE_SECRET = "secret";
//
// public static final String PROVISIONER_ESXI = "esxi";
//
// public static final String RESPONSE_CONTENT_TYPE_TEXT_PLAIN = "text/plain; charset=utf-8";
//
// private Constants() {}
// }
// Path: modules/cloud-portal-server/src/main/java/de/papke/cloud/portal/service/ScriptingConsoleService.java
import java.io.File;
import java.io.PrintWriter;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import javax.annotation.PostConstruct;
import org.apache.commons.io.FileUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.stereotype.Service;
import de.papke.cloud.portal.constants.Constants;
package de.papke.cloud.portal.service;
@Service
public class ScriptingConsoleService {
private static final Logger LOG = LoggerFactory.getLogger(ScriptingConsoleService.class);
private static final String FILE_EXAMPLE = "example.groovy";
private String exampleFileString;
private Map<String, Object> variableMap;
private List<String> variableList;
@Autowired
private ApplicationContext applicationContext;
@Autowired
private GroovyService groovyService;
@Autowired
private ResourceService resourceService;
@PostConstruct
private void init() {
try {
// get example file as string | File exampleFile = resourceService.getClasspathResource(Constants.FOLDER_CONSOLE + File.separator + FILE_EXAMPLE); |
chrisipa/cloud-portal | modules/cloud-portal-server/src/main/java/de/papke/cloud/portal/auth/DirectoryAuthenticationProvider.java | // Path: modules/cloud-portal-server/src/main/java/de/papke/cloud/portal/pojo/User.java
// public class User implements Serializable {
//
// private static final long serialVersionUID = 1L;
//
// private String username;
// private String givenName;
// private String surName;
// private String email;
// private List<String> groups;
// private boolean admin;
//
// public User() {}
//
// public User(String username, String givenName, String surName, String email, List<String> groups, boolean admin) {
// super();
// this.givenName = givenName;
// this.surName = surName;
// this.username = username;
// this.email = email;
// this.groups = groups;
// this.admin = admin;
// }
//
// public String getUsername() {
// return username;
// }
//
// public void setUsername(String username) {
// this.username = username;
// }
//
// public String getGivenName() {
// return givenName;
// }
//
// public void setGivenName(String givenName) {
// this.givenName = givenName;
// }
//
// public String getSurName() {
// return surName;
// }
//
// public void setSurName(String surName) {
// this.surName = surName;
// }
//
// public String getEmail() {
// return email;
// }
//
// public void setEmail(String email) {
// this.email = email;
// }
//
// public List<String> getGroups() {
// return groups;
// }
//
// public void setGroups(List<String> groups) {
// this.groups = groups;
// }
//
// public boolean isAdmin() {
// return admin;
// }
//
// public void setAdmin(boolean admin) {
// this.admin = admin;
// }
// }
//
// Path: modules/cloud-portal-server/src/main/java/de/papke/cloud/portal/service/SessionUserService.java
// @Service
// public class SessionUserService {
//
// private static final String SESSION_ATTRIBUTE_USER = "user";
// private static final User DUMMY_USER = new User("anonymous", "Anonymous", "User", "dummy@dummy.com", new ArrayList<>(), false);
//
// @Autowired
// private HttpSession session;
//
// public User getUser() {
//
// User user = (User) session.getAttribute(SESSION_ATTRIBUTE_USER);
//
// if (user == null) {
// user = DUMMY_USER;
// }
//
// return user;
// }
//
// public boolean isAdmin() {
// return getUser().isAdmin();
// }
//
// public boolean isAllowed() {
// return isAdmin();
// }
//
// public boolean isAllowed(ProvisionLog provisionLog) {
// return isAdmin() || getUser().getGroups().contains(provisionLog.getGroup());
// }
//
// public void setUser(User user) {
// session.setAttribute(SESSION_ATTRIBUTE_USER, user);
// }
// }
//
// Path: modules/cloud-portal-server/src/main/java/de/papke/cloud/portal/service/UserService.java
// @Service
// public class UserService {
//
// private static final Logger LOG = LoggerFactory.getLogger(UserService.class);
//
// @Value("${APPLICATION_ADMIN_GROUP}")
// private String adminGroup;
//
// @Autowired
// private DirectoryService directoryService;
//
// public User getUser(String username) {
//
// User user = null;
//
// try {
//
// user = directoryService.getUser(username);
//
// if (user.getGroups() != null) {
// for (String group : user.getGroups()) {
// if (group.equals(adminGroup)) {
// user.setAdmin(true);
// break;
// }
// }
// }
// }
// catch(Exception e) {
// LOG.error(e.getMessage(), e);
// }
//
// return user;
// }
//
// public boolean authenticate(String username, String password) {
// return directoryService.authenticate(username, password);
// }
// }
| import java.util.ArrayList;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.AuthenticationProvider;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.stereotype.Component;
import de.papke.cloud.portal.pojo.User;
import de.papke.cloud.portal.service.SessionUserService;
import de.papke.cloud.portal.service.UserService; | package de.papke.cloud.portal.auth;
@Component
public class DirectoryAuthenticationProvider implements AuthenticationProvider {
@Autowired | // Path: modules/cloud-portal-server/src/main/java/de/papke/cloud/portal/pojo/User.java
// public class User implements Serializable {
//
// private static final long serialVersionUID = 1L;
//
// private String username;
// private String givenName;
// private String surName;
// private String email;
// private List<String> groups;
// private boolean admin;
//
// public User() {}
//
// public User(String username, String givenName, String surName, String email, List<String> groups, boolean admin) {
// super();
// this.givenName = givenName;
// this.surName = surName;
// this.username = username;
// this.email = email;
// this.groups = groups;
// this.admin = admin;
// }
//
// public String getUsername() {
// return username;
// }
//
// public void setUsername(String username) {
// this.username = username;
// }
//
// public String getGivenName() {
// return givenName;
// }
//
// public void setGivenName(String givenName) {
// this.givenName = givenName;
// }
//
// public String getSurName() {
// return surName;
// }
//
// public void setSurName(String surName) {
// this.surName = surName;
// }
//
// public String getEmail() {
// return email;
// }
//
// public void setEmail(String email) {
// this.email = email;
// }
//
// public List<String> getGroups() {
// return groups;
// }
//
// public void setGroups(List<String> groups) {
// this.groups = groups;
// }
//
// public boolean isAdmin() {
// return admin;
// }
//
// public void setAdmin(boolean admin) {
// this.admin = admin;
// }
// }
//
// Path: modules/cloud-portal-server/src/main/java/de/papke/cloud/portal/service/SessionUserService.java
// @Service
// public class SessionUserService {
//
// private static final String SESSION_ATTRIBUTE_USER = "user";
// private static final User DUMMY_USER = new User("anonymous", "Anonymous", "User", "dummy@dummy.com", new ArrayList<>(), false);
//
// @Autowired
// private HttpSession session;
//
// public User getUser() {
//
// User user = (User) session.getAttribute(SESSION_ATTRIBUTE_USER);
//
// if (user == null) {
// user = DUMMY_USER;
// }
//
// return user;
// }
//
// public boolean isAdmin() {
// return getUser().isAdmin();
// }
//
// public boolean isAllowed() {
// return isAdmin();
// }
//
// public boolean isAllowed(ProvisionLog provisionLog) {
// return isAdmin() || getUser().getGroups().contains(provisionLog.getGroup());
// }
//
// public void setUser(User user) {
// session.setAttribute(SESSION_ATTRIBUTE_USER, user);
// }
// }
//
// Path: modules/cloud-portal-server/src/main/java/de/papke/cloud/portal/service/UserService.java
// @Service
// public class UserService {
//
// private static final Logger LOG = LoggerFactory.getLogger(UserService.class);
//
// @Value("${APPLICATION_ADMIN_GROUP}")
// private String adminGroup;
//
// @Autowired
// private DirectoryService directoryService;
//
// public User getUser(String username) {
//
// User user = null;
//
// try {
//
// user = directoryService.getUser(username);
//
// if (user.getGroups() != null) {
// for (String group : user.getGroups()) {
// if (group.equals(adminGroup)) {
// user.setAdmin(true);
// break;
// }
// }
// }
// }
// catch(Exception e) {
// LOG.error(e.getMessage(), e);
// }
//
// return user;
// }
//
// public boolean authenticate(String username, String password) {
// return directoryService.authenticate(username, password);
// }
// }
// Path: modules/cloud-portal-server/src/main/java/de/papke/cloud/portal/auth/DirectoryAuthenticationProvider.java
import java.util.ArrayList;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.AuthenticationProvider;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.stereotype.Component;
import de.papke.cloud.portal.pojo.User;
import de.papke.cloud.portal.service.SessionUserService;
import de.papke.cloud.portal.service.UserService;
package de.papke.cloud.portal.auth;
@Component
public class DirectoryAuthenticationProvider implements AuthenticationProvider {
@Autowired | private UserService userService; |
chrisipa/cloud-portal | modules/cloud-portal-server/src/main/java/de/papke/cloud/portal/auth/DirectoryAuthenticationProvider.java | // Path: modules/cloud-portal-server/src/main/java/de/papke/cloud/portal/pojo/User.java
// public class User implements Serializable {
//
// private static final long serialVersionUID = 1L;
//
// private String username;
// private String givenName;
// private String surName;
// private String email;
// private List<String> groups;
// private boolean admin;
//
// public User() {}
//
// public User(String username, String givenName, String surName, String email, List<String> groups, boolean admin) {
// super();
// this.givenName = givenName;
// this.surName = surName;
// this.username = username;
// this.email = email;
// this.groups = groups;
// this.admin = admin;
// }
//
// public String getUsername() {
// return username;
// }
//
// public void setUsername(String username) {
// this.username = username;
// }
//
// public String getGivenName() {
// return givenName;
// }
//
// public void setGivenName(String givenName) {
// this.givenName = givenName;
// }
//
// public String getSurName() {
// return surName;
// }
//
// public void setSurName(String surName) {
// this.surName = surName;
// }
//
// public String getEmail() {
// return email;
// }
//
// public void setEmail(String email) {
// this.email = email;
// }
//
// public List<String> getGroups() {
// return groups;
// }
//
// public void setGroups(List<String> groups) {
// this.groups = groups;
// }
//
// public boolean isAdmin() {
// return admin;
// }
//
// public void setAdmin(boolean admin) {
// this.admin = admin;
// }
// }
//
// Path: modules/cloud-portal-server/src/main/java/de/papke/cloud/portal/service/SessionUserService.java
// @Service
// public class SessionUserService {
//
// private static final String SESSION_ATTRIBUTE_USER = "user";
// private static final User DUMMY_USER = new User("anonymous", "Anonymous", "User", "dummy@dummy.com", new ArrayList<>(), false);
//
// @Autowired
// private HttpSession session;
//
// public User getUser() {
//
// User user = (User) session.getAttribute(SESSION_ATTRIBUTE_USER);
//
// if (user == null) {
// user = DUMMY_USER;
// }
//
// return user;
// }
//
// public boolean isAdmin() {
// return getUser().isAdmin();
// }
//
// public boolean isAllowed() {
// return isAdmin();
// }
//
// public boolean isAllowed(ProvisionLog provisionLog) {
// return isAdmin() || getUser().getGroups().contains(provisionLog.getGroup());
// }
//
// public void setUser(User user) {
// session.setAttribute(SESSION_ATTRIBUTE_USER, user);
// }
// }
//
// Path: modules/cloud-portal-server/src/main/java/de/papke/cloud/portal/service/UserService.java
// @Service
// public class UserService {
//
// private static final Logger LOG = LoggerFactory.getLogger(UserService.class);
//
// @Value("${APPLICATION_ADMIN_GROUP}")
// private String adminGroup;
//
// @Autowired
// private DirectoryService directoryService;
//
// public User getUser(String username) {
//
// User user = null;
//
// try {
//
// user = directoryService.getUser(username);
//
// if (user.getGroups() != null) {
// for (String group : user.getGroups()) {
// if (group.equals(adminGroup)) {
// user.setAdmin(true);
// break;
// }
// }
// }
// }
// catch(Exception e) {
// LOG.error(e.getMessage(), e);
// }
//
// return user;
// }
//
// public boolean authenticate(String username, String password) {
// return directoryService.authenticate(username, password);
// }
// }
| import java.util.ArrayList;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.AuthenticationProvider;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.stereotype.Component;
import de.papke.cloud.portal.pojo.User;
import de.papke.cloud.portal.service.SessionUserService;
import de.papke.cloud.portal.service.UserService; | package de.papke.cloud.portal.auth;
@Component
public class DirectoryAuthenticationProvider implements AuthenticationProvider {
@Autowired
private UserService userService;
@Autowired | // Path: modules/cloud-portal-server/src/main/java/de/papke/cloud/portal/pojo/User.java
// public class User implements Serializable {
//
// private static final long serialVersionUID = 1L;
//
// private String username;
// private String givenName;
// private String surName;
// private String email;
// private List<String> groups;
// private boolean admin;
//
// public User() {}
//
// public User(String username, String givenName, String surName, String email, List<String> groups, boolean admin) {
// super();
// this.givenName = givenName;
// this.surName = surName;
// this.username = username;
// this.email = email;
// this.groups = groups;
// this.admin = admin;
// }
//
// public String getUsername() {
// return username;
// }
//
// public void setUsername(String username) {
// this.username = username;
// }
//
// public String getGivenName() {
// return givenName;
// }
//
// public void setGivenName(String givenName) {
// this.givenName = givenName;
// }
//
// public String getSurName() {
// return surName;
// }
//
// public void setSurName(String surName) {
// this.surName = surName;
// }
//
// public String getEmail() {
// return email;
// }
//
// public void setEmail(String email) {
// this.email = email;
// }
//
// public List<String> getGroups() {
// return groups;
// }
//
// public void setGroups(List<String> groups) {
// this.groups = groups;
// }
//
// public boolean isAdmin() {
// return admin;
// }
//
// public void setAdmin(boolean admin) {
// this.admin = admin;
// }
// }
//
// Path: modules/cloud-portal-server/src/main/java/de/papke/cloud/portal/service/SessionUserService.java
// @Service
// public class SessionUserService {
//
// private static final String SESSION_ATTRIBUTE_USER = "user";
// private static final User DUMMY_USER = new User("anonymous", "Anonymous", "User", "dummy@dummy.com", new ArrayList<>(), false);
//
// @Autowired
// private HttpSession session;
//
// public User getUser() {
//
// User user = (User) session.getAttribute(SESSION_ATTRIBUTE_USER);
//
// if (user == null) {
// user = DUMMY_USER;
// }
//
// return user;
// }
//
// public boolean isAdmin() {
// return getUser().isAdmin();
// }
//
// public boolean isAllowed() {
// return isAdmin();
// }
//
// public boolean isAllowed(ProvisionLog provisionLog) {
// return isAdmin() || getUser().getGroups().contains(provisionLog.getGroup());
// }
//
// public void setUser(User user) {
// session.setAttribute(SESSION_ATTRIBUTE_USER, user);
// }
// }
//
// Path: modules/cloud-portal-server/src/main/java/de/papke/cloud/portal/service/UserService.java
// @Service
// public class UserService {
//
// private static final Logger LOG = LoggerFactory.getLogger(UserService.class);
//
// @Value("${APPLICATION_ADMIN_GROUP}")
// private String adminGroup;
//
// @Autowired
// private DirectoryService directoryService;
//
// public User getUser(String username) {
//
// User user = null;
//
// try {
//
// user = directoryService.getUser(username);
//
// if (user.getGroups() != null) {
// for (String group : user.getGroups()) {
// if (group.equals(adminGroup)) {
// user.setAdmin(true);
// break;
// }
// }
// }
// }
// catch(Exception e) {
// LOG.error(e.getMessage(), e);
// }
//
// return user;
// }
//
// public boolean authenticate(String username, String password) {
// return directoryService.authenticate(username, password);
// }
// }
// Path: modules/cloud-portal-server/src/main/java/de/papke/cloud/portal/auth/DirectoryAuthenticationProvider.java
import java.util.ArrayList;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.AuthenticationProvider;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.stereotype.Component;
import de.papke.cloud.portal.pojo.User;
import de.papke.cloud.portal.service.SessionUserService;
import de.papke.cloud.portal.service.UserService;
package de.papke.cloud.portal.auth;
@Component
public class DirectoryAuthenticationProvider implements AuthenticationProvider {
@Autowired
private UserService userService;
@Autowired | private SessionUserService sessionUserService; |
chrisipa/cloud-portal | modules/cloud-portal-server/src/main/java/de/papke/cloud/portal/auth/DirectoryAuthenticationProvider.java | // Path: modules/cloud-portal-server/src/main/java/de/papke/cloud/portal/pojo/User.java
// public class User implements Serializable {
//
// private static final long serialVersionUID = 1L;
//
// private String username;
// private String givenName;
// private String surName;
// private String email;
// private List<String> groups;
// private boolean admin;
//
// public User() {}
//
// public User(String username, String givenName, String surName, String email, List<String> groups, boolean admin) {
// super();
// this.givenName = givenName;
// this.surName = surName;
// this.username = username;
// this.email = email;
// this.groups = groups;
// this.admin = admin;
// }
//
// public String getUsername() {
// return username;
// }
//
// public void setUsername(String username) {
// this.username = username;
// }
//
// public String getGivenName() {
// return givenName;
// }
//
// public void setGivenName(String givenName) {
// this.givenName = givenName;
// }
//
// public String getSurName() {
// return surName;
// }
//
// public void setSurName(String surName) {
// this.surName = surName;
// }
//
// public String getEmail() {
// return email;
// }
//
// public void setEmail(String email) {
// this.email = email;
// }
//
// public List<String> getGroups() {
// return groups;
// }
//
// public void setGroups(List<String> groups) {
// this.groups = groups;
// }
//
// public boolean isAdmin() {
// return admin;
// }
//
// public void setAdmin(boolean admin) {
// this.admin = admin;
// }
// }
//
// Path: modules/cloud-portal-server/src/main/java/de/papke/cloud/portal/service/SessionUserService.java
// @Service
// public class SessionUserService {
//
// private static final String SESSION_ATTRIBUTE_USER = "user";
// private static final User DUMMY_USER = new User("anonymous", "Anonymous", "User", "dummy@dummy.com", new ArrayList<>(), false);
//
// @Autowired
// private HttpSession session;
//
// public User getUser() {
//
// User user = (User) session.getAttribute(SESSION_ATTRIBUTE_USER);
//
// if (user == null) {
// user = DUMMY_USER;
// }
//
// return user;
// }
//
// public boolean isAdmin() {
// return getUser().isAdmin();
// }
//
// public boolean isAllowed() {
// return isAdmin();
// }
//
// public boolean isAllowed(ProvisionLog provisionLog) {
// return isAdmin() || getUser().getGroups().contains(provisionLog.getGroup());
// }
//
// public void setUser(User user) {
// session.setAttribute(SESSION_ATTRIBUTE_USER, user);
// }
// }
//
// Path: modules/cloud-portal-server/src/main/java/de/papke/cloud/portal/service/UserService.java
// @Service
// public class UserService {
//
// private static final Logger LOG = LoggerFactory.getLogger(UserService.class);
//
// @Value("${APPLICATION_ADMIN_GROUP}")
// private String adminGroup;
//
// @Autowired
// private DirectoryService directoryService;
//
// public User getUser(String username) {
//
// User user = null;
//
// try {
//
// user = directoryService.getUser(username);
//
// if (user.getGroups() != null) {
// for (String group : user.getGroups()) {
// if (group.equals(adminGroup)) {
// user.setAdmin(true);
// break;
// }
// }
// }
// }
// catch(Exception e) {
// LOG.error(e.getMessage(), e);
// }
//
// return user;
// }
//
// public boolean authenticate(String username, String password) {
// return directoryService.authenticate(username, password);
// }
// }
| import java.util.ArrayList;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.AuthenticationProvider;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.stereotype.Component;
import de.papke.cloud.portal.pojo.User;
import de.papke.cloud.portal.service.SessionUserService;
import de.papke.cloud.portal.service.UserService; | package de.papke.cloud.portal.auth;
@Component
public class DirectoryAuthenticationProvider implements AuthenticationProvider {
@Autowired
private UserService userService;
@Autowired
private SessionUserService sessionUserService;
@Override
public Authentication authenticate(Authentication authentication) {
Authentication auth = null;
// get username and password from authentication object
String username = (String) authentication.getPrincipal();
String password = (String) authentication.getCredentials();
// authenticate user
if (userService.authenticate(username, password)) {
// get user | // Path: modules/cloud-portal-server/src/main/java/de/papke/cloud/portal/pojo/User.java
// public class User implements Serializable {
//
// private static final long serialVersionUID = 1L;
//
// private String username;
// private String givenName;
// private String surName;
// private String email;
// private List<String> groups;
// private boolean admin;
//
// public User() {}
//
// public User(String username, String givenName, String surName, String email, List<String> groups, boolean admin) {
// super();
// this.givenName = givenName;
// this.surName = surName;
// this.username = username;
// this.email = email;
// this.groups = groups;
// this.admin = admin;
// }
//
// public String getUsername() {
// return username;
// }
//
// public void setUsername(String username) {
// this.username = username;
// }
//
// public String getGivenName() {
// return givenName;
// }
//
// public void setGivenName(String givenName) {
// this.givenName = givenName;
// }
//
// public String getSurName() {
// return surName;
// }
//
// public void setSurName(String surName) {
// this.surName = surName;
// }
//
// public String getEmail() {
// return email;
// }
//
// public void setEmail(String email) {
// this.email = email;
// }
//
// public List<String> getGroups() {
// return groups;
// }
//
// public void setGroups(List<String> groups) {
// this.groups = groups;
// }
//
// public boolean isAdmin() {
// return admin;
// }
//
// public void setAdmin(boolean admin) {
// this.admin = admin;
// }
// }
//
// Path: modules/cloud-portal-server/src/main/java/de/papke/cloud/portal/service/SessionUserService.java
// @Service
// public class SessionUserService {
//
// private static final String SESSION_ATTRIBUTE_USER = "user";
// private static final User DUMMY_USER = new User("anonymous", "Anonymous", "User", "dummy@dummy.com", new ArrayList<>(), false);
//
// @Autowired
// private HttpSession session;
//
// public User getUser() {
//
// User user = (User) session.getAttribute(SESSION_ATTRIBUTE_USER);
//
// if (user == null) {
// user = DUMMY_USER;
// }
//
// return user;
// }
//
// public boolean isAdmin() {
// return getUser().isAdmin();
// }
//
// public boolean isAllowed() {
// return isAdmin();
// }
//
// public boolean isAllowed(ProvisionLog provisionLog) {
// return isAdmin() || getUser().getGroups().contains(provisionLog.getGroup());
// }
//
// public void setUser(User user) {
// session.setAttribute(SESSION_ATTRIBUTE_USER, user);
// }
// }
//
// Path: modules/cloud-portal-server/src/main/java/de/papke/cloud/portal/service/UserService.java
// @Service
// public class UserService {
//
// private static final Logger LOG = LoggerFactory.getLogger(UserService.class);
//
// @Value("${APPLICATION_ADMIN_GROUP}")
// private String adminGroup;
//
// @Autowired
// private DirectoryService directoryService;
//
// public User getUser(String username) {
//
// User user = null;
//
// try {
//
// user = directoryService.getUser(username);
//
// if (user.getGroups() != null) {
// for (String group : user.getGroups()) {
// if (group.equals(adminGroup)) {
// user.setAdmin(true);
// break;
// }
// }
// }
// }
// catch(Exception e) {
// LOG.error(e.getMessage(), e);
// }
//
// return user;
// }
//
// public boolean authenticate(String username, String password) {
// return directoryService.authenticate(username, password);
// }
// }
// Path: modules/cloud-portal-server/src/main/java/de/papke/cloud/portal/auth/DirectoryAuthenticationProvider.java
import java.util.ArrayList;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.AuthenticationProvider;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.stereotype.Component;
import de.papke.cloud.portal.pojo.User;
import de.papke.cloud.portal.service.SessionUserService;
import de.papke.cloud.portal.service.UserService;
package de.papke.cloud.portal.auth;
@Component
public class DirectoryAuthenticationProvider implements AuthenticationProvider {
@Autowired
private UserService userService;
@Autowired
private SessionUserService sessionUserService;
@Override
public Authentication authenticate(Authentication authentication) {
Authentication auth = null;
// get username and password from authentication object
String username = (String) authentication.getPrincipal();
String password = (String) authentication.getCredentials();
// authenticate user
if (userService.authenticate(username, password)) {
// get user | User user = userService.getUser(username); |
chrisipa/cloud-portal | modules/cloud-portal-server/src/main/java/de/papke/cloud/portal/util/ZipUtil.java | // Path: modules/cloud-portal-server/src/main/java/de/papke/cloud/portal/constants/Constants.java
// public class Constants {
//
// public static final String CHAR_EMPTY = "";
// public static final String CHAR_STAR = "*";
// public static final String CHAR_DIAMOND = "#";
// public static final String CHAR_EQUAL = "=";
// public static final String CHAR_DASH = "-";
// public static final String CHAR_UNDERSCORE = "_";
// public static final String CHAR_WHITESPACE = " ";
// public static final String CHAR_DOUBLE_QUOTE = "\"";
// public static final String CHAR_SINGLE_QUOTE = "'";
// public static final String CHAR_NEW_LINE = "\n";
// public static final String CHAR_TAB = "\t";
// public static final String CHAR_DOT = ".";
// public static final String CHAR_DOUBLE_DOT = ":";
// public static final String CHAR_BRACE_OPEN = "{";
// public static final String CHAR_BRACE_CLOSE = "}";
// public static final String CHAR_BRAKET_OPEN = "[";
// public static final String CHAR_BRAKET_CLOSE = "]";
// public static final String CHAR_COMMA = ",";
// public static final String CHAR_PARENTHESES_OPEN = "(";
// public static final String CHAR_PARENTHESES_CLOSE = ")";
//
// public static final String ACTION_INIT = "init";
// public static final String ACTION_APPLY = "apply";
// public static final String ACTION_PLAN = "plan";
// public static final String ACTION_DESTROY = "destroy";
//
// public static final String VM_EXPIRATION_DAYS_STRING = "expiration_days";
//
// public static final String KEY_FILE_PREFIX = "id_rsa";
// public static final String KEY_FILE_PUBLIC_SUFFIX = ".pub";
// public static final String KEY_FILE_PRIVATE_SUFFIX = ".pem";
//
// public static final String RESULT_FILE_PREFIX = "result";
// public static final String RESULT_FILE_SUFFIX = ".zip";
//
// public static final String TMP_FOLDER_PREFIX = System.getProperty("java.io.tmpdir") + "/tmp-";
//
// public static final String FOLDER_CONSOLE = "console";
// public static final String FOLDER_USE_CASE = "usecase";
// public static final String FOLDER_PROVISIONER = "provisioner";
// public static final String FOLDER_TERRAFORM = "terraform";
//
// public static final String VAR_TYPE_SECRET = "secret";
//
// public static final String PROVISIONER_ESXI = "esxi";
//
// public static final String RESPONSE_CONTENT_TYPE_TEXT_PLAIN = "text/plain; charset=utf-8";
//
// private Constants() {}
// }
| import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.Enumeration;
import java.util.zip.ZipEntry;
import java.util.zip.ZipFile;
import java.util.zip.ZipOutputStream;
import org.apache.commons.io.IOUtils;
import de.papke.cloud.portal.constants.Constants; | package de.papke.cloud.portal.util;
public class ZipUtil {
private ZipUtil() {}
public static void zip(File sourceDir, File outputFile) throws IOException {
ZipOutputStream zipFile = new ZipOutputStream(new FileOutputStream(outputFile));
Path srcPath = Paths.get(sourceDir.toURI());
zipFolder(srcPath.getParent().toString(), srcPath.getFileName().toString(), zipFile);
IOUtils.closeQuietly(zipFile);
}
private static void zipFolder(String rootDir, String sourceDir, ZipOutputStream out) throws IOException {
String dir = Paths.get(rootDir, sourceDir).toString();
for (File file : new File(dir).listFiles()) {
| // Path: modules/cloud-portal-server/src/main/java/de/papke/cloud/portal/constants/Constants.java
// public class Constants {
//
// public static final String CHAR_EMPTY = "";
// public static final String CHAR_STAR = "*";
// public static final String CHAR_DIAMOND = "#";
// public static final String CHAR_EQUAL = "=";
// public static final String CHAR_DASH = "-";
// public static final String CHAR_UNDERSCORE = "_";
// public static final String CHAR_WHITESPACE = " ";
// public static final String CHAR_DOUBLE_QUOTE = "\"";
// public static final String CHAR_SINGLE_QUOTE = "'";
// public static final String CHAR_NEW_LINE = "\n";
// public static final String CHAR_TAB = "\t";
// public static final String CHAR_DOT = ".";
// public static final String CHAR_DOUBLE_DOT = ":";
// public static final String CHAR_BRACE_OPEN = "{";
// public static final String CHAR_BRACE_CLOSE = "}";
// public static final String CHAR_BRAKET_OPEN = "[";
// public static final String CHAR_BRAKET_CLOSE = "]";
// public static final String CHAR_COMMA = ",";
// public static final String CHAR_PARENTHESES_OPEN = "(";
// public static final String CHAR_PARENTHESES_CLOSE = ")";
//
// public static final String ACTION_INIT = "init";
// public static final String ACTION_APPLY = "apply";
// public static final String ACTION_PLAN = "plan";
// public static final String ACTION_DESTROY = "destroy";
//
// public static final String VM_EXPIRATION_DAYS_STRING = "expiration_days";
//
// public static final String KEY_FILE_PREFIX = "id_rsa";
// public static final String KEY_FILE_PUBLIC_SUFFIX = ".pub";
// public static final String KEY_FILE_PRIVATE_SUFFIX = ".pem";
//
// public static final String RESULT_FILE_PREFIX = "result";
// public static final String RESULT_FILE_SUFFIX = ".zip";
//
// public static final String TMP_FOLDER_PREFIX = System.getProperty("java.io.tmpdir") + "/tmp-";
//
// public static final String FOLDER_CONSOLE = "console";
// public static final String FOLDER_USE_CASE = "usecase";
// public static final String FOLDER_PROVISIONER = "provisioner";
// public static final String FOLDER_TERRAFORM = "terraform";
//
// public static final String VAR_TYPE_SECRET = "secret";
//
// public static final String PROVISIONER_ESXI = "esxi";
//
// public static final String RESPONSE_CONTENT_TYPE_TEXT_PLAIN = "text/plain; charset=utf-8";
//
// private Constants() {}
// }
// Path: modules/cloud-portal-server/src/main/java/de/papke/cloud/portal/util/ZipUtil.java
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.Enumeration;
import java.util.zip.ZipEntry;
import java.util.zip.ZipFile;
import java.util.zip.ZipOutputStream;
import org.apache.commons.io.IOUtils;
import de.papke.cloud.portal.constants.Constants;
package de.papke.cloud.portal.util;
public class ZipUtil {
private ZipUtil() {}
public static void zip(File sourceDir, File outputFile) throws IOException {
ZipOutputStream zipFile = new ZipOutputStream(new FileOutputStream(outputFile));
Path srcPath = Paths.get(sourceDir.toURI());
zipFolder(srcPath.getParent().toString(), srcPath.getFileName().toString(), zipFile);
IOUtils.closeQuietly(zipFile);
}
private static void zipFolder(String rootDir, String sourceDir, ZipOutputStream out) throws IOException {
String dir = Paths.get(rootDir, sourceDir).toString();
for (File file : new File(dir).listFiles()) {
| if (!file.getName().startsWith(Constants.CHAR_DOT)) { |
chrisipa/cloud-portal | modules/cloud-portal-server/src/main/java/de/papke/cloud/portal/service/CredentialsService.java | // Path: modules/cloud-portal-server/src/main/java/de/papke/cloud/portal/dao/CredentialsDao.java
// public interface CredentialsDao extends MongoRepository<Credentials, String> {
// public List<Credentials> findByProvider(String provider);
// public Credentials findByGroupAndProvider(String group, String provider);
// }
//
// Path: modules/cloud-portal-server/src/main/java/de/papke/cloud/portal/pojo/Credentials.java
// public class Credentials {
//
// @Id
// private String id;
// private String group;
// private String provider;
// private Map<String, String> secretMap = new HashMap<>();
//
// public Credentials() {}
//
// public Credentials(String group, String provider, Map<String, String> secretMap) {
// this.group = group;
// this.provider = provider;
// this.secretMap = secretMap;
// }
//
// public String getId() {
// return id;
// }
//
// public void setId(String id) {
// this.id = id;
// }
//
// public String getGroup() {
// return group;
// }
//
// public void setGroup(String group) {
// this.group = group;
// }
//
// public String getProvider() {
// return provider;
// }
//
// public void setProvider(String provider) {
// this.provider = provider;
// }
//
// public Map<String, String> getSecretMap() {
// return secretMap;
// }
//
// public void setSecretMap(Map<String, String> secretMap) {
// this.secretMap = secretMap;
// }
// }
//
// Path: modules/cloud-portal-server/src/main/java/de/papke/cloud/portal/pojo/User.java
// public class User implements Serializable {
//
// private static final long serialVersionUID = 1L;
//
// private String username;
// private String givenName;
// private String surName;
// private String email;
// private List<String> groups;
// private boolean admin;
//
// public User() {}
//
// public User(String username, String givenName, String surName, String email, List<String> groups, boolean admin) {
// super();
// this.givenName = givenName;
// this.surName = surName;
// this.username = username;
// this.email = email;
// this.groups = groups;
// this.admin = admin;
// }
//
// public String getUsername() {
// return username;
// }
//
// public void setUsername(String username) {
// this.username = username;
// }
//
// public String getGivenName() {
// return givenName;
// }
//
// public void setGivenName(String givenName) {
// this.givenName = givenName;
// }
//
// public String getSurName() {
// return surName;
// }
//
// public void setSurName(String surName) {
// this.surName = surName;
// }
//
// public String getEmail() {
// return email;
// }
//
// public void setEmail(String email) {
// this.email = email;
// }
//
// public List<String> getGroups() {
// return groups;
// }
//
// public void setGroups(List<String> groups) {
// this.groups = groups;
// }
//
// public boolean isAdmin() {
// return admin;
// }
//
// public void setAdmin(boolean admin) {
// this.admin = admin;
// }
// }
| import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import de.papke.cloud.portal.dao.CredentialsDao;
import de.papke.cloud.portal.pojo.Credentials;
import de.papke.cloud.portal.pojo.User; | package de.papke.cloud.portal.service;
@Service
public class CredentialsService {
@Autowired
private EncryptionService encryptionService;
@Autowired
private SessionUserService sessionUserService;
@Autowired | // Path: modules/cloud-portal-server/src/main/java/de/papke/cloud/portal/dao/CredentialsDao.java
// public interface CredentialsDao extends MongoRepository<Credentials, String> {
// public List<Credentials> findByProvider(String provider);
// public Credentials findByGroupAndProvider(String group, String provider);
// }
//
// Path: modules/cloud-portal-server/src/main/java/de/papke/cloud/portal/pojo/Credentials.java
// public class Credentials {
//
// @Id
// private String id;
// private String group;
// private String provider;
// private Map<String, String> secretMap = new HashMap<>();
//
// public Credentials() {}
//
// public Credentials(String group, String provider, Map<String, String> secretMap) {
// this.group = group;
// this.provider = provider;
// this.secretMap = secretMap;
// }
//
// public String getId() {
// return id;
// }
//
// public void setId(String id) {
// this.id = id;
// }
//
// public String getGroup() {
// return group;
// }
//
// public void setGroup(String group) {
// this.group = group;
// }
//
// public String getProvider() {
// return provider;
// }
//
// public void setProvider(String provider) {
// this.provider = provider;
// }
//
// public Map<String, String> getSecretMap() {
// return secretMap;
// }
//
// public void setSecretMap(Map<String, String> secretMap) {
// this.secretMap = secretMap;
// }
// }
//
// Path: modules/cloud-portal-server/src/main/java/de/papke/cloud/portal/pojo/User.java
// public class User implements Serializable {
//
// private static final long serialVersionUID = 1L;
//
// private String username;
// private String givenName;
// private String surName;
// private String email;
// private List<String> groups;
// private boolean admin;
//
// public User() {}
//
// public User(String username, String givenName, String surName, String email, List<String> groups, boolean admin) {
// super();
// this.givenName = givenName;
// this.surName = surName;
// this.username = username;
// this.email = email;
// this.groups = groups;
// this.admin = admin;
// }
//
// public String getUsername() {
// return username;
// }
//
// public void setUsername(String username) {
// this.username = username;
// }
//
// public String getGivenName() {
// return givenName;
// }
//
// public void setGivenName(String givenName) {
// this.givenName = givenName;
// }
//
// public String getSurName() {
// return surName;
// }
//
// public void setSurName(String surName) {
// this.surName = surName;
// }
//
// public String getEmail() {
// return email;
// }
//
// public void setEmail(String email) {
// this.email = email;
// }
//
// public List<String> getGroups() {
// return groups;
// }
//
// public void setGroups(List<String> groups) {
// this.groups = groups;
// }
//
// public boolean isAdmin() {
// return admin;
// }
//
// public void setAdmin(boolean admin) {
// this.admin = admin;
// }
// }
// Path: modules/cloud-portal-server/src/main/java/de/papke/cloud/portal/service/CredentialsService.java
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import de.papke.cloud.portal.dao.CredentialsDao;
import de.papke.cloud.portal.pojo.Credentials;
import de.papke.cloud.portal.pojo.User;
package de.papke.cloud.portal.service;
@Service
public class CredentialsService {
@Autowired
private EncryptionService encryptionService;
@Autowired
private SessionUserService sessionUserService;
@Autowired | private CredentialsDao credentialsDao; |
chrisipa/cloud-portal | modules/cloud-portal-server/src/main/java/de/papke/cloud/portal/service/CredentialsService.java | // Path: modules/cloud-portal-server/src/main/java/de/papke/cloud/portal/dao/CredentialsDao.java
// public interface CredentialsDao extends MongoRepository<Credentials, String> {
// public List<Credentials> findByProvider(String provider);
// public Credentials findByGroupAndProvider(String group, String provider);
// }
//
// Path: modules/cloud-portal-server/src/main/java/de/papke/cloud/portal/pojo/Credentials.java
// public class Credentials {
//
// @Id
// private String id;
// private String group;
// private String provider;
// private Map<String, String> secretMap = new HashMap<>();
//
// public Credentials() {}
//
// public Credentials(String group, String provider, Map<String, String> secretMap) {
// this.group = group;
// this.provider = provider;
// this.secretMap = secretMap;
// }
//
// public String getId() {
// return id;
// }
//
// public void setId(String id) {
// this.id = id;
// }
//
// public String getGroup() {
// return group;
// }
//
// public void setGroup(String group) {
// this.group = group;
// }
//
// public String getProvider() {
// return provider;
// }
//
// public void setProvider(String provider) {
// this.provider = provider;
// }
//
// public Map<String, String> getSecretMap() {
// return secretMap;
// }
//
// public void setSecretMap(Map<String, String> secretMap) {
// this.secretMap = secretMap;
// }
// }
//
// Path: modules/cloud-portal-server/src/main/java/de/papke/cloud/portal/pojo/User.java
// public class User implements Serializable {
//
// private static final long serialVersionUID = 1L;
//
// private String username;
// private String givenName;
// private String surName;
// private String email;
// private List<String> groups;
// private boolean admin;
//
// public User() {}
//
// public User(String username, String givenName, String surName, String email, List<String> groups, boolean admin) {
// super();
// this.givenName = givenName;
// this.surName = surName;
// this.username = username;
// this.email = email;
// this.groups = groups;
// this.admin = admin;
// }
//
// public String getUsername() {
// return username;
// }
//
// public void setUsername(String username) {
// this.username = username;
// }
//
// public String getGivenName() {
// return givenName;
// }
//
// public void setGivenName(String givenName) {
// this.givenName = givenName;
// }
//
// public String getSurName() {
// return surName;
// }
//
// public void setSurName(String surName) {
// this.surName = surName;
// }
//
// public String getEmail() {
// return email;
// }
//
// public void setEmail(String email) {
// this.email = email;
// }
//
// public List<String> getGroups() {
// return groups;
// }
//
// public void setGroups(List<String> groups) {
// this.groups = groups;
// }
//
// public boolean isAdmin() {
// return admin;
// }
//
// public void setAdmin(boolean admin) {
// this.admin = admin;
// }
// }
| import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import de.papke.cloud.portal.dao.CredentialsDao;
import de.papke.cloud.portal.pojo.Credentials;
import de.papke.cloud.portal.pojo.User; | package de.papke.cloud.portal.service;
@Service
public class CredentialsService {
@Autowired
private EncryptionService encryptionService;
@Autowired
private SessionUserService sessionUserService;
@Autowired
private CredentialsDao credentialsDao;
| // Path: modules/cloud-portal-server/src/main/java/de/papke/cloud/portal/dao/CredentialsDao.java
// public interface CredentialsDao extends MongoRepository<Credentials, String> {
// public List<Credentials> findByProvider(String provider);
// public Credentials findByGroupAndProvider(String group, String provider);
// }
//
// Path: modules/cloud-portal-server/src/main/java/de/papke/cloud/portal/pojo/Credentials.java
// public class Credentials {
//
// @Id
// private String id;
// private String group;
// private String provider;
// private Map<String, String> secretMap = new HashMap<>();
//
// public Credentials() {}
//
// public Credentials(String group, String provider, Map<String, String> secretMap) {
// this.group = group;
// this.provider = provider;
// this.secretMap = secretMap;
// }
//
// public String getId() {
// return id;
// }
//
// public void setId(String id) {
// this.id = id;
// }
//
// public String getGroup() {
// return group;
// }
//
// public void setGroup(String group) {
// this.group = group;
// }
//
// public String getProvider() {
// return provider;
// }
//
// public void setProvider(String provider) {
// this.provider = provider;
// }
//
// public Map<String, String> getSecretMap() {
// return secretMap;
// }
//
// public void setSecretMap(Map<String, String> secretMap) {
// this.secretMap = secretMap;
// }
// }
//
// Path: modules/cloud-portal-server/src/main/java/de/papke/cloud/portal/pojo/User.java
// public class User implements Serializable {
//
// private static final long serialVersionUID = 1L;
//
// private String username;
// private String givenName;
// private String surName;
// private String email;
// private List<String> groups;
// private boolean admin;
//
// public User() {}
//
// public User(String username, String givenName, String surName, String email, List<String> groups, boolean admin) {
// super();
// this.givenName = givenName;
// this.surName = surName;
// this.username = username;
// this.email = email;
// this.groups = groups;
// this.admin = admin;
// }
//
// public String getUsername() {
// return username;
// }
//
// public void setUsername(String username) {
// this.username = username;
// }
//
// public String getGivenName() {
// return givenName;
// }
//
// public void setGivenName(String givenName) {
// this.givenName = givenName;
// }
//
// public String getSurName() {
// return surName;
// }
//
// public void setSurName(String surName) {
// this.surName = surName;
// }
//
// public String getEmail() {
// return email;
// }
//
// public void setEmail(String email) {
// this.email = email;
// }
//
// public List<String> getGroups() {
// return groups;
// }
//
// public void setGroups(List<String> groups) {
// this.groups = groups;
// }
//
// public boolean isAdmin() {
// return admin;
// }
//
// public void setAdmin(boolean admin) {
// this.admin = admin;
// }
// }
// Path: modules/cloud-portal-server/src/main/java/de/papke/cloud/portal/service/CredentialsService.java
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import de.papke.cloud.portal.dao.CredentialsDao;
import de.papke.cloud.portal.pojo.Credentials;
import de.papke.cloud.portal.pojo.User;
package de.papke.cloud.portal.service;
@Service
public class CredentialsService {
@Autowired
private EncryptionService encryptionService;
@Autowired
private SessionUserService sessionUserService;
@Autowired
private CredentialsDao credentialsDao;
| public List<Credentials> getCredentialList(String provider) { |
chrisipa/cloud-portal | modules/cloud-portal-server/src/main/java/de/papke/cloud/portal/service/CredentialsService.java | // Path: modules/cloud-portal-server/src/main/java/de/papke/cloud/portal/dao/CredentialsDao.java
// public interface CredentialsDao extends MongoRepository<Credentials, String> {
// public List<Credentials> findByProvider(String provider);
// public Credentials findByGroupAndProvider(String group, String provider);
// }
//
// Path: modules/cloud-portal-server/src/main/java/de/papke/cloud/portal/pojo/Credentials.java
// public class Credentials {
//
// @Id
// private String id;
// private String group;
// private String provider;
// private Map<String, String> secretMap = new HashMap<>();
//
// public Credentials() {}
//
// public Credentials(String group, String provider, Map<String, String> secretMap) {
// this.group = group;
// this.provider = provider;
// this.secretMap = secretMap;
// }
//
// public String getId() {
// return id;
// }
//
// public void setId(String id) {
// this.id = id;
// }
//
// public String getGroup() {
// return group;
// }
//
// public void setGroup(String group) {
// this.group = group;
// }
//
// public String getProvider() {
// return provider;
// }
//
// public void setProvider(String provider) {
// this.provider = provider;
// }
//
// public Map<String, String> getSecretMap() {
// return secretMap;
// }
//
// public void setSecretMap(Map<String, String> secretMap) {
// this.secretMap = secretMap;
// }
// }
//
// Path: modules/cloud-portal-server/src/main/java/de/papke/cloud/portal/pojo/User.java
// public class User implements Serializable {
//
// private static final long serialVersionUID = 1L;
//
// private String username;
// private String givenName;
// private String surName;
// private String email;
// private List<String> groups;
// private boolean admin;
//
// public User() {}
//
// public User(String username, String givenName, String surName, String email, List<String> groups, boolean admin) {
// super();
// this.givenName = givenName;
// this.surName = surName;
// this.username = username;
// this.email = email;
// this.groups = groups;
// this.admin = admin;
// }
//
// public String getUsername() {
// return username;
// }
//
// public void setUsername(String username) {
// this.username = username;
// }
//
// public String getGivenName() {
// return givenName;
// }
//
// public void setGivenName(String givenName) {
// this.givenName = givenName;
// }
//
// public String getSurName() {
// return surName;
// }
//
// public void setSurName(String surName) {
// this.surName = surName;
// }
//
// public String getEmail() {
// return email;
// }
//
// public void setEmail(String email) {
// this.email = email;
// }
//
// public List<String> getGroups() {
// return groups;
// }
//
// public void setGroups(List<String> groups) {
// this.groups = groups;
// }
//
// public boolean isAdmin() {
// return admin;
// }
//
// public void setAdmin(boolean admin) {
// this.admin = admin;
// }
// }
| import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import de.papke.cloud.portal.dao.CredentialsDao;
import de.papke.cloud.portal.pojo.Credentials;
import de.papke.cloud.portal.pojo.User; | package de.papke.cloud.portal.service;
@Service
public class CredentialsService {
@Autowired
private EncryptionService encryptionService;
@Autowired
private SessionUserService sessionUserService;
@Autowired
private CredentialsDao credentialsDao;
public List<Credentials> getCredentialList(String provider) {
List<Credentials> credentialsList = credentialsDao.findByProvider(provider);
for (Credentials credentials : credentialsList) {
Map<String, String> secretMap = credentials.getSecretMap();
Map<String, String> decryptedSecretMap = decryptSecretMap(secretMap);
credentials.setSecretMap(decryptedSecretMap);
}
return credentialsList;
}
public Credentials getCredentials(String provider) {
return getCredentials(sessionUserService.getUser(), provider);
}
| // Path: modules/cloud-portal-server/src/main/java/de/papke/cloud/portal/dao/CredentialsDao.java
// public interface CredentialsDao extends MongoRepository<Credentials, String> {
// public List<Credentials> findByProvider(String provider);
// public Credentials findByGroupAndProvider(String group, String provider);
// }
//
// Path: modules/cloud-portal-server/src/main/java/de/papke/cloud/portal/pojo/Credentials.java
// public class Credentials {
//
// @Id
// private String id;
// private String group;
// private String provider;
// private Map<String, String> secretMap = new HashMap<>();
//
// public Credentials() {}
//
// public Credentials(String group, String provider, Map<String, String> secretMap) {
// this.group = group;
// this.provider = provider;
// this.secretMap = secretMap;
// }
//
// public String getId() {
// return id;
// }
//
// public void setId(String id) {
// this.id = id;
// }
//
// public String getGroup() {
// return group;
// }
//
// public void setGroup(String group) {
// this.group = group;
// }
//
// public String getProvider() {
// return provider;
// }
//
// public void setProvider(String provider) {
// this.provider = provider;
// }
//
// public Map<String, String> getSecretMap() {
// return secretMap;
// }
//
// public void setSecretMap(Map<String, String> secretMap) {
// this.secretMap = secretMap;
// }
// }
//
// Path: modules/cloud-portal-server/src/main/java/de/papke/cloud/portal/pojo/User.java
// public class User implements Serializable {
//
// private static final long serialVersionUID = 1L;
//
// private String username;
// private String givenName;
// private String surName;
// private String email;
// private List<String> groups;
// private boolean admin;
//
// public User() {}
//
// public User(String username, String givenName, String surName, String email, List<String> groups, boolean admin) {
// super();
// this.givenName = givenName;
// this.surName = surName;
// this.username = username;
// this.email = email;
// this.groups = groups;
// this.admin = admin;
// }
//
// public String getUsername() {
// return username;
// }
//
// public void setUsername(String username) {
// this.username = username;
// }
//
// public String getGivenName() {
// return givenName;
// }
//
// public void setGivenName(String givenName) {
// this.givenName = givenName;
// }
//
// public String getSurName() {
// return surName;
// }
//
// public void setSurName(String surName) {
// this.surName = surName;
// }
//
// public String getEmail() {
// return email;
// }
//
// public void setEmail(String email) {
// this.email = email;
// }
//
// public List<String> getGroups() {
// return groups;
// }
//
// public void setGroups(List<String> groups) {
// this.groups = groups;
// }
//
// public boolean isAdmin() {
// return admin;
// }
//
// public void setAdmin(boolean admin) {
// this.admin = admin;
// }
// }
// Path: modules/cloud-portal-server/src/main/java/de/papke/cloud/portal/service/CredentialsService.java
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import de.papke.cloud.portal.dao.CredentialsDao;
import de.papke.cloud.portal.pojo.Credentials;
import de.papke.cloud.portal.pojo.User;
package de.papke.cloud.portal.service;
@Service
public class CredentialsService {
@Autowired
private EncryptionService encryptionService;
@Autowired
private SessionUserService sessionUserService;
@Autowired
private CredentialsDao credentialsDao;
public List<Credentials> getCredentialList(String provider) {
List<Credentials> credentialsList = credentialsDao.findByProvider(provider);
for (Credentials credentials : credentialsList) {
Map<String, String> secretMap = credentials.getSecretMap();
Map<String, String> decryptedSecretMap = decryptSecretMap(secretMap);
credentials.setSecretMap(decryptedSecretMap);
}
return credentialsList;
}
public Credentials getCredentials(String provider) {
return getCredentials(sessionUserService.getUser(), provider);
}
| public Credentials getCredentials(User user, String provider) { |
isstac/spf-wca | src/main/wcanalysis/heuristic/PolicyGeneratorListener.java | // Path: src/main/wcanalysis/heuristic/util/Util.java
// public class Util {
//
// public static File createDirIfNotExist(File root, String subDir) {
// File sub = new File(root, subDir);
// if(!sub.exists())
// sub.mkdirs();
// return sub;
// }
//
// public static File createDirIfNotExist(String root) {
// File sub = new File(root);
// if(!sub.exists())
// sub.mkdirs();
// return sub;
// }
//
// public static File createDirIfNotExist(File dir) {
// if(!dir.exists())
// dir.mkdirs();
// return dir;
// }
//
// public static String normalizeJPFMethodName(MethodInfo methInfo) {
// int methBeginIdx = methInfo.getBaseName().lastIndexOf('.') + 1;
// String fullName = methInfo.getFullName();
// return fullName.substring(methBeginIdx, fullName.length());
// }
//
// public static Set<String> extractSimpleMethodNames(String[] jpfMethodSpecs) {
// //FIXME: This also means that we do not distinguish between overloaded methods
// String[] processedMethods = new String[jpfMethodSpecs.length];
// System.arraycopy(jpfMethodSpecs, 0, processedMethods, 0, jpfMethodSpecs.length);
// for(int i = 0; i < jpfMethodSpecs.length; i++) {
// String meth = jpfMethodSpecs[i];
// int sigBegin = meth.indexOf('(');
// if(sigBegin >= 0)
// processedMethods[i] = meth.substring(0, sigBegin);
// }
// return new HashSet<String>(Arrays.asList(processedMethods));
// }
// }
| import gov.nasa.jpf.symbc.numeric.PCChoiceGenerator;
import gov.nasa.jpf.vm.ChoiceGenerator;
import wcanalysis.heuristic.util.Util;
import java.io.File;
import gov.nasa.jpf.Config;
import gov.nasa.jpf.JPF;
import gov.nasa.jpf.search.Search; | /*
* MIT License
*
* Copyright (c) 2017 The ISSTAC Authors
*
* 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 wcanalysis.heuristic;
/**
* @author Kasper Luckow
*/
public class PolicyGeneratorListener extends PathListener {
public static final String UNIFY_POLICIES_CONF = "symbolic.wc.policy.unifypolicies";
public static final boolean UNIFY_POLICIES_CONF_DEF = false;
public static final String VIS_OUTPUT_PATH_CONF = "symbolic.wc.policy.visualizer.outputpath";
public static final String SER_OUTPUT_PATH_CONF = "symbolic.wc.policy.serializer.outputpath";
public static final String SERIALIZE_CONF = "symbolic.wc.policy.serialize";
public static final String SER_OUTPUT_PATH_DEF = "./ser/policy";
//for statistics
private long newChoices = 0;
public PolicyGeneratorListener(Config jpfConf, JPF jpf) {
super(jpfConf, jpf);
}
@Override
public void stateAdvanced(Search search) {
super.stateAdvanced(search);
ChoiceGenerator<?> cg = search.getVM().getSystemState().getChoiceGenerator();
if(cg instanceof PCChoiceGenerator) {
this.newChoices++;
}
}
public long getNumberOfNewChoices() {
return newChoices;
}
@Override
public boolean visualize(Config jpfConf) {
return jpfConf.hasValue(VIS_OUTPUT_PATH_CONF);
}
@Override
public File getVisualizationDir(Config jpfConf) { | // Path: src/main/wcanalysis/heuristic/util/Util.java
// public class Util {
//
// public static File createDirIfNotExist(File root, String subDir) {
// File sub = new File(root, subDir);
// if(!sub.exists())
// sub.mkdirs();
// return sub;
// }
//
// public static File createDirIfNotExist(String root) {
// File sub = new File(root);
// if(!sub.exists())
// sub.mkdirs();
// return sub;
// }
//
// public static File createDirIfNotExist(File dir) {
// if(!dir.exists())
// dir.mkdirs();
// return dir;
// }
//
// public static String normalizeJPFMethodName(MethodInfo methInfo) {
// int methBeginIdx = methInfo.getBaseName().lastIndexOf('.') + 1;
// String fullName = methInfo.getFullName();
// return fullName.substring(methBeginIdx, fullName.length());
// }
//
// public static Set<String> extractSimpleMethodNames(String[] jpfMethodSpecs) {
// //FIXME: This also means that we do not distinguish between overloaded methods
// String[] processedMethods = new String[jpfMethodSpecs.length];
// System.arraycopy(jpfMethodSpecs, 0, processedMethods, 0, jpfMethodSpecs.length);
// for(int i = 0; i < jpfMethodSpecs.length; i++) {
// String meth = jpfMethodSpecs[i];
// int sigBegin = meth.indexOf('(');
// if(sigBegin >= 0)
// processedMethods[i] = meth.substring(0, sigBegin);
// }
// return new HashSet<String>(Arrays.asList(processedMethods));
// }
// }
// Path: src/main/wcanalysis/heuristic/PolicyGeneratorListener.java
import gov.nasa.jpf.symbc.numeric.PCChoiceGenerator;
import gov.nasa.jpf.vm.ChoiceGenerator;
import wcanalysis.heuristic.util.Util;
import java.io.File;
import gov.nasa.jpf.Config;
import gov.nasa.jpf.JPF;
import gov.nasa.jpf.search.Search;
/*
* MIT License
*
* Copyright (c) 2017 The ISSTAC Authors
*
* 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 wcanalysis.heuristic;
/**
* @author Kasper Luckow
*/
public class PolicyGeneratorListener extends PathListener {
public static final String UNIFY_POLICIES_CONF = "symbolic.wc.policy.unifypolicies";
public static final boolean UNIFY_POLICIES_CONF_DEF = false;
public static final String VIS_OUTPUT_PATH_CONF = "symbolic.wc.policy.visualizer.outputpath";
public static final String SER_OUTPUT_PATH_CONF = "symbolic.wc.policy.serializer.outputpath";
public static final String SERIALIZE_CONF = "symbolic.wc.policy.serialize";
public static final String SER_OUTPUT_PATH_DEF = "./ser/policy";
//for statistics
private long newChoices = 0;
public PolicyGeneratorListener(Config jpfConf, JPF jpf) {
super(jpfConf, jpf);
}
@Override
public void stateAdvanced(Search search) {
super.stateAdvanced(search);
ChoiceGenerator<?> cg = search.getVM().getSystemState().getChoiceGenerator();
if(cg instanceof PCChoiceGenerator) {
this.newChoices++;
}
}
public long getNumberOfNewChoices() {
return newChoices;
}
@Override
public boolean visualize(Config jpfConf) {
return jpfConf.hasValue(VIS_OUTPUT_PATH_CONF);
}
@Override
public File getVisualizationDir(Config jpfConf) { | File out = Util.createDirIfNotExist(jpfConf.getString(VIS_OUTPUT_PATH_CONF, "./vis/policy")); |
isstac/spf-wca | src/main/wcanalysis/heuristic/PolicyResultsPublisher.java | // Path: src/main/wcanalysis/heuristic/util/Util.java
// public class Util {
//
// public static File createDirIfNotExist(File root, String subDir) {
// File sub = new File(root, subDir);
// if(!sub.exists())
// sub.mkdirs();
// return sub;
// }
//
// public static File createDirIfNotExist(String root) {
// File sub = new File(root);
// if(!sub.exists())
// sub.mkdirs();
// return sub;
// }
//
// public static File createDirIfNotExist(File dir) {
// if(!dir.exists())
// dir.mkdirs();
// return dir;
// }
//
// public static String normalizeJPFMethodName(MethodInfo methInfo) {
// int methBeginIdx = methInfo.getBaseName().lastIndexOf('.') + 1;
// String fullName = methInfo.getFullName();
// return fullName.substring(methBeginIdx, fullName.length());
// }
//
// public static Set<String> extractSimpleMethodNames(String[] jpfMethodSpecs) {
// //FIXME: This also means that we do not distinguish between overloaded methods
// String[] processedMethods = new String[jpfMethodSpecs.length];
// System.arraycopy(jpfMethodSpecs, 0, processedMethods, 0, jpfMethodSpecs.length);
// for(int i = 0; i < jpfMethodSpecs.length; i++) {
// String meth = jpfMethodSpecs[i];
// int sigBegin = meth.indexOf('(');
// if(sigBegin >= 0)
// processedMethods[i] = meth.substring(0, sigBegin);
// }
// return new HashSet<String>(Arrays.asList(processedMethods));
// }
// }
| import java.io.File;
import gov.nasa.jpf.Config;
import gov.nasa.jpf.report.Reporter;
import wcanalysis.heuristic.util.Util; | /*
* MIT License
*
* Copyright (c) 2017 The ISSTAC Authors
*
* 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 wcanalysis.heuristic;
/**
* @author Kasper Luckow
*
*/
public class PolicyResultsPublisher extends ResultsPublisher {
public static final String RESULTS_DIR_CONF = "report.console.wc.policy.resultsdir";
public PolicyResultsPublisher(Config conf, Reporter reporter) {
super(conf, reporter);
}
@Override
protected String getCustomCSVColumnHeader() {
return "newChoicesNum";
}
@Override
protected String getCustomCSVColumnData() {
PolicyGeneratorListener listener = reporter.getVM().getNextListenerOfType(PolicyGeneratorListener.class, null);
if(listener == null)
return "";
return Long.toString(listener.getNumberOfNewChoices());
}
@Override
protected File getResultsDir(Config conf) { | // Path: src/main/wcanalysis/heuristic/util/Util.java
// public class Util {
//
// public static File createDirIfNotExist(File root, String subDir) {
// File sub = new File(root, subDir);
// if(!sub.exists())
// sub.mkdirs();
// return sub;
// }
//
// public static File createDirIfNotExist(String root) {
// File sub = new File(root);
// if(!sub.exists())
// sub.mkdirs();
// return sub;
// }
//
// public static File createDirIfNotExist(File dir) {
// if(!dir.exists())
// dir.mkdirs();
// return dir;
// }
//
// public static String normalizeJPFMethodName(MethodInfo methInfo) {
// int methBeginIdx = methInfo.getBaseName().lastIndexOf('.') + 1;
// String fullName = methInfo.getFullName();
// return fullName.substring(methBeginIdx, fullName.length());
// }
//
// public static Set<String> extractSimpleMethodNames(String[] jpfMethodSpecs) {
// //FIXME: This also means that we do not distinguish between overloaded methods
// String[] processedMethods = new String[jpfMethodSpecs.length];
// System.arraycopy(jpfMethodSpecs, 0, processedMethods, 0, jpfMethodSpecs.length);
// for(int i = 0; i < jpfMethodSpecs.length; i++) {
// String meth = jpfMethodSpecs[i];
// int sigBegin = meth.indexOf('(');
// if(sigBegin >= 0)
// processedMethods[i] = meth.substring(0, sigBegin);
// }
// return new HashSet<String>(Arrays.asList(processedMethods));
// }
// }
// Path: src/main/wcanalysis/heuristic/PolicyResultsPublisher.java
import java.io.File;
import gov.nasa.jpf.Config;
import gov.nasa.jpf.report.Reporter;
import wcanalysis.heuristic.util.Util;
/*
* MIT License
*
* Copyright (c) 2017 The ISSTAC Authors
*
* 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 wcanalysis.heuristic;
/**
* @author Kasper Luckow
*
*/
public class PolicyResultsPublisher extends ResultsPublisher {
public static final String RESULTS_DIR_CONF = "report.console.wc.policy.resultsdir";
public PolicyResultsPublisher(Config conf, Reporter reporter) {
super(conf, reporter);
}
@Override
protected String getCustomCSVColumnHeader() {
return "newChoicesNum";
}
@Override
protected String getCustomCSVColumnData() {
PolicyGeneratorListener listener = reporter.getVM().getNextListenerOfType(PolicyGeneratorListener.class, null);
if(listener == null)
return "";
return Long.toString(listener.getNumberOfNewChoices());
}
@Override
protected File getResultsDir(Config conf) { | return Util.createDirIfNotExist(conf.getString(RESULTS_DIR_CONF, "./results/policy")); |
isstac/spf-wca | src/main/wcanalysis/heuristic/policy/Policy.java | // Path: src/main/wcanalysis/heuristic/ContextManager.java
// public class ContextManager {
//
// static class CGContext {
// final StackFrame stackFrame;
// final StateBuilder stateBuilder;
//
// public CGContext(StackFrame sf, StateBuilder stateBuilder) {
// this.stackFrame = sf;
// this.stateBuilder = stateBuilder;
// }
// }
//
// private Map<Integer, CGContext> contextMap = new HashMap<>();
//
// public void addContext(ChoiceGenerator<?> cg, StackFrame caller, StateBuilder stateBuilder) {
// if(contextMap.containsKey(cg.getStateId()))
// throw new IllegalStateException("Attempt to override context map");
// this.contextMap.put(cg.getStateId(), new CGContext(caller, stateBuilder));
// }
//
// public CGContext getContext(ChoiceGenerator<?> cg) {
// return this.contextMap.get(cg.getStateId());
// }
// }
//
// Path: src/main/wcanalysis/heuristic/Resolution.java
// public class Resolution implements Serializable {
// public static enum ResolutionType implements Serializable {
// PERFECT,
// HISTORY,
// INVARIANT,
// UNRESOLVED,
// NEW_CHOICE;
// }
//
// private static final long serialVersionUID = 2247935610676857227L;
// public final ResolutionType type;
// public final int choice;
// public Resolution(int choice, ResolutionType type) {
// this.choice = choice;
// this.type = type;
// }
// }
| import java.util.Set;
import gov.nasa.jpf.vm.ChoiceGenerator;
import wcanalysis.heuristic.ContextManager;
import wcanalysis.heuristic.Resolution;
import java.io.IOException;
import java.io.InputStream;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.OutputStream;
import java.io.Serializable; | /*
* MIT License
*
* Copyright (c) 2017 The ISSTAC Authors
*
* 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 wcanalysis.heuristic.policy;
/**
* @author Kasper Luckow
*
*/
public abstract class Policy implements Serializable {
private static final long serialVersionUID = -2247935610676857237L;
private final Set<String> measuredMethods;
public Policy(Set<String> measuredMethods) {
this.measuredMethods = measuredMethods;
}
public Set<String> getMeasuredMethods() {
return this.measuredMethods;
}
| // Path: src/main/wcanalysis/heuristic/ContextManager.java
// public class ContextManager {
//
// static class CGContext {
// final StackFrame stackFrame;
// final StateBuilder stateBuilder;
//
// public CGContext(StackFrame sf, StateBuilder stateBuilder) {
// this.stackFrame = sf;
// this.stateBuilder = stateBuilder;
// }
// }
//
// private Map<Integer, CGContext> contextMap = new HashMap<>();
//
// public void addContext(ChoiceGenerator<?> cg, StackFrame caller, StateBuilder stateBuilder) {
// if(contextMap.containsKey(cg.getStateId()))
// throw new IllegalStateException("Attempt to override context map");
// this.contextMap.put(cg.getStateId(), new CGContext(caller, stateBuilder));
// }
//
// public CGContext getContext(ChoiceGenerator<?> cg) {
// return this.contextMap.get(cg.getStateId());
// }
// }
//
// Path: src/main/wcanalysis/heuristic/Resolution.java
// public class Resolution implements Serializable {
// public static enum ResolutionType implements Serializable {
// PERFECT,
// HISTORY,
// INVARIANT,
// UNRESOLVED,
// NEW_CHOICE;
// }
//
// private static final long serialVersionUID = 2247935610676857227L;
// public final ResolutionType type;
// public final int choice;
// public Resolution(int choice, ResolutionType type) {
// this.choice = choice;
// this.type = type;
// }
// }
// Path: src/main/wcanalysis/heuristic/policy/Policy.java
import java.util.Set;
import gov.nasa.jpf.vm.ChoiceGenerator;
import wcanalysis.heuristic.ContextManager;
import wcanalysis.heuristic.Resolution;
import java.io.IOException;
import java.io.InputStream;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.OutputStream;
import java.io.Serializable;
/*
* MIT License
*
* Copyright (c) 2017 The ISSTAC Authors
*
* 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 wcanalysis.heuristic.policy;
/**
* @author Kasper Luckow
*
*/
public abstract class Policy implements Serializable {
private static final long serialVersionUID = -2247935610676857237L;
private final Set<String> measuredMethods;
public Policy(Set<String> measuredMethods) {
this.measuredMethods = measuredMethods;
}
public Set<String> getMeasuredMethods() {
return this.measuredMethods;
}
| public abstract Resolution resolve(ChoiceGenerator<?> cg, ContextManager ctxManager); |
isstac/spf-wca | src/main/wcanalysis/heuristic/policy/Policy.java | // Path: src/main/wcanalysis/heuristic/ContextManager.java
// public class ContextManager {
//
// static class CGContext {
// final StackFrame stackFrame;
// final StateBuilder stateBuilder;
//
// public CGContext(StackFrame sf, StateBuilder stateBuilder) {
// this.stackFrame = sf;
// this.stateBuilder = stateBuilder;
// }
// }
//
// private Map<Integer, CGContext> contextMap = new HashMap<>();
//
// public void addContext(ChoiceGenerator<?> cg, StackFrame caller, StateBuilder stateBuilder) {
// if(contextMap.containsKey(cg.getStateId()))
// throw new IllegalStateException("Attempt to override context map");
// this.contextMap.put(cg.getStateId(), new CGContext(caller, stateBuilder));
// }
//
// public CGContext getContext(ChoiceGenerator<?> cg) {
// return this.contextMap.get(cg.getStateId());
// }
// }
//
// Path: src/main/wcanalysis/heuristic/Resolution.java
// public class Resolution implements Serializable {
// public static enum ResolutionType implements Serializable {
// PERFECT,
// HISTORY,
// INVARIANT,
// UNRESOLVED,
// NEW_CHOICE;
// }
//
// private static final long serialVersionUID = 2247935610676857227L;
// public final ResolutionType type;
// public final int choice;
// public Resolution(int choice, ResolutionType type) {
// this.choice = choice;
// this.type = type;
// }
// }
| import java.util.Set;
import gov.nasa.jpf.vm.ChoiceGenerator;
import wcanalysis.heuristic.ContextManager;
import wcanalysis.heuristic.Resolution;
import java.io.IOException;
import java.io.InputStream;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.OutputStream;
import java.io.Serializable; | /*
* MIT License
*
* Copyright (c) 2017 The ISSTAC Authors
*
* 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 wcanalysis.heuristic.policy;
/**
* @author Kasper Luckow
*
*/
public abstract class Policy implements Serializable {
private static final long serialVersionUID = -2247935610676857237L;
private final Set<String> measuredMethods;
public Policy(Set<String> measuredMethods) {
this.measuredMethods = measuredMethods;
}
public Set<String> getMeasuredMethods() {
return this.measuredMethods;
}
| // Path: src/main/wcanalysis/heuristic/ContextManager.java
// public class ContextManager {
//
// static class CGContext {
// final StackFrame stackFrame;
// final StateBuilder stateBuilder;
//
// public CGContext(StackFrame sf, StateBuilder stateBuilder) {
// this.stackFrame = sf;
// this.stateBuilder = stateBuilder;
// }
// }
//
// private Map<Integer, CGContext> contextMap = new HashMap<>();
//
// public void addContext(ChoiceGenerator<?> cg, StackFrame caller, StateBuilder stateBuilder) {
// if(contextMap.containsKey(cg.getStateId()))
// throw new IllegalStateException("Attempt to override context map");
// this.contextMap.put(cg.getStateId(), new CGContext(caller, stateBuilder));
// }
//
// public CGContext getContext(ChoiceGenerator<?> cg) {
// return this.contextMap.get(cg.getStateId());
// }
// }
//
// Path: src/main/wcanalysis/heuristic/Resolution.java
// public class Resolution implements Serializable {
// public static enum ResolutionType implements Serializable {
// PERFECT,
// HISTORY,
// INVARIANT,
// UNRESOLVED,
// NEW_CHOICE;
// }
//
// private static final long serialVersionUID = 2247935610676857227L;
// public final ResolutionType type;
// public final int choice;
// public Resolution(int choice, ResolutionType type) {
// this.choice = choice;
// this.type = type;
// }
// }
// Path: src/main/wcanalysis/heuristic/policy/Policy.java
import java.util.Set;
import gov.nasa.jpf.vm.ChoiceGenerator;
import wcanalysis.heuristic.ContextManager;
import wcanalysis.heuristic.Resolution;
import java.io.IOException;
import java.io.InputStream;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.OutputStream;
import java.io.Serializable;
/*
* MIT License
*
* Copyright (c) 2017 The ISSTAC Authors
*
* 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 wcanalysis.heuristic.policy;
/**
* @author Kasper Luckow
*
*/
public abstract class Policy implements Serializable {
private static final long serialVersionUID = -2247935610676857237L;
private final Set<String> measuredMethods;
public Policy(Set<String> measuredMethods) {
this.measuredMethods = measuredMethods;
}
public Set<String> getMeasuredMethods() {
return this.measuredMethods;
}
| public abstract Resolution resolve(ChoiceGenerator<?> cg, ContextManager ctxManager); |
isstac/spf-wca | src/main/wcanalysis/heuristic/util/SMTLibConverter.java | // Path: src/main/wcanalysis/util/SymbolicVariableCollector.java
// public class SymbolicVariableCollector extends ConstraintExpressionVisitor {
//
// public HashSet<String> setOfSymVar;
//
// public SymbolicVariableCollector(HashSet<String> set){
// setOfSymVar = set;
// }
//
// @Override
// public void preVisit(SymbolicInteger expr) {
// String name = cleanSymbol(expr.toString());
// setOfSymVar.add(name);
// }
//
// public void collectVariables(PathCondition pc){
// Constraint c = pc.header;
// while(c != null){
// c.accept(this);
// c = c.getTail();
// }
// }
//
// private static String cleanSymbol(String str) {
// return str.replaceAll("\\[(.*?)\\]", ""); // remove e.g. [-1000000]
// }
//
// public Set<String> getListOfVariables(){
// return setOfSymVar;
// }
//
// public int size(){
// return setOfSymVar.size();
// }
// }
| import java.util.HashSet;
import gov.nasa.jpf.symbc.numeric.PathCondition;
import wcanalysis.util.SymbolicVariableCollector; | /*
* MIT License
*
* Copyright (c) 2017 The ISSTAC Authors
*
* 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 wcanalysis.heuristic.util;
/**
* @author Kasper Luckow
*/
public class SMTLibConverter implements ConstraintsConverter {
@Override
public String convert(PathCondition pc) {
if(pc == null || pc.header == null)
return "";
StringBuilder smtLib = new StringBuilder();
HashSet<String> setOfSymVar = new HashSet<String>(); | // Path: src/main/wcanalysis/util/SymbolicVariableCollector.java
// public class SymbolicVariableCollector extends ConstraintExpressionVisitor {
//
// public HashSet<String> setOfSymVar;
//
// public SymbolicVariableCollector(HashSet<String> set){
// setOfSymVar = set;
// }
//
// @Override
// public void preVisit(SymbolicInteger expr) {
// String name = cleanSymbol(expr.toString());
// setOfSymVar.add(name);
// }
//
// public void collectVariables(PathCondition pc){
// Constraint c = pc.header;
// while(c != null){
// c.accept(this);
// c = c.getTail();
// }
// }
//
// private static String cleanSymbol(String str) {
// return str.replaceAll("\\[(.*?)\\]", ""); // remove e.g. [-1000000]
// }
//
// public Set<String> getListOfVariables(){
// return setOfSymVar;
// }
//
// public int size(){
// return setOfSymVar.size();
// }
// }
// Path: src/main/wcanalysis/heuristic/util/SMTLibConverter.java
import java.util.HashSet;
import gov.nasa.jpf.symbc.numeric.PathCondition;
import wcanalysis.util.SymbolicVariableCollector;
/*
* MIT License
*
* Copyright (c) 2017 The ISSTAC Authors
*
* 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 wcanalysis.heuristic.util;
/**
* @author Kasper Luckow
*/
public class SMTLibConverter implements ConstraintsConverter {
@Override
public String convert(PathCondition pc) {
if(pc == null || pc.header == null)
return "";
StringBuilder smtLib = new StringBuilder();
HashSet<String> setOfSymVar = new HashSet<String>(); | SymbolicVariableCollector collector = new SymbolicVariableCollector(setOfSymVar); |
isstac/spf-wca | src/main/wcanalysis/heuristic/WorstCasePath.java | // Path: src/main/wcanalysis/heuristic/PathMeasureComputation.java
// public static class Result {
// private final int resolutions;
// private final int memorylessResolution;
//
// public Result(int resolutions, int memorylessResolutions) {
// this.resolutions = resolutions;
// this.memorylessResolution = memorylessResolutions;
// }
//
// public int getMemorylessResolution() {
// return memorylessResolution;
// }
//
// public int getResolutions() {
// return resolutions;
// }
// }
//
// Path: src/main/wcanalysis/heuristic/model/State.java
// public abstract class State implements CSVable, Comparable<State> {
// private final PathCondition pc;
//
// public State(PathCondition pc) {
// this.pc = pc;
// }
//
// public PathCondition getPathCondition() {
// return this.pc;
// }
//
// // Should this return a double, or would we like to parameterize this (e.g. to subclasses of Number)?
// public abstract double getWC();
// }
| import gov.nasa.jpf.vm.ChoiceGenerator;
import wcanalysis.heuristic.PathMeasureComputation.Result;
import wcanalysis.heuristic.model.State;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.ListIterator;
import java.util.Map;
import java.util.Set; | /*
* MIT License
*
* Copyright (c) 2017 The ISSTAC Authors
*
* 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 wcanalysis.heuristic;
/**
* @author Kasper Luckow
*
*/
public class WorstCasePath extends Path implements Comparable<WorstCasePath> {
private static final long serialVersionUID = -6739423849594132561L;
public static class Builder {
private final ContextManager ctxManager;
private final PathMeasureComputation pathMeasureComp;
public Builder(ContextManager ctxManager, int maxHistory) {
this.pathMeasureComp = new DefaultPathMeasure(new FixedLengthCtxHistoryGenerator(maxHistory));
this.ctxManager = ctxManager;
}
public Builder(ContextManager ctxManager) {
this.pathMeasureComp = new DefaultPathMeasure(new MaxLengthCtxHistoryGenerator());
this.ctxManager = ctxManager;
}
| // Path: src/main/wcanalysis/heuristic/PathMeasureComputation.java
// public static class Result {
// private final int resolutions;
// private final int memorylessResolution;
//
// public Result(int resolutions, int memorylessResolutions) {
// this.resolutions = resolutions;
// this.memorylessResolution = memorylessResolutions;
// }
//
// public int getMemorylessResolution() {
// return memorylessResolution;
// }
//
// public int getResolutions() {
// return resolutions;
// }
// }
//
// Path: src/main/wcanalysis/heuristic/model/State.java
// public abstract class State implements CSVable, Comparable<State> {
// private final PathCondition pc;
//
// public State(PathCondition pc) {
// this.pc = pc;
// }
//
// public PathCondition getPathCondition() {
// return this.pc;
// }
//
// // Should this return a double, or would we like to parameterize this (e.g. to subclasses of Number)?
// public abstract double getWC();
// }
// Path: src/main/wcanalysis/heuristic/WorstCasePath.java
import gov.nasa.jpf.vm.ChoiceGenerator;
import wcanalysis.heuristic.PathMeasureComputation.Result;
import wcanalysis.heuristic.model.State;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.ListIterator;
import java.util.Map;
import java.util.Set;
/*
* MIT License
*
* Copyright (c) 2017 The ISSTAC Authors
*
* 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 wcanalysis.heuristic;
/**
* @author Kasper Luckow
*
*/
public class WorstCasePath extends Path implements Comparable<WorstCasePath> {
private static final long serialVersionUID = -6739423849594132561L;
public static class Builder {
private final ContextManager ctxManager;
private final PathMeasureComputation pathMeasureComp;
public Builder(ContextManager ctxManager, int maxHistory) {
this.pathMeasureComp = new DefaultPathMeasure(new FixedLengthCtxHistoryGenerator(maxHistory));
this.ctxManager = ctxManager;
}
public Builder(ContextManager ctxManager) {
this.pathMeasureComp = new DefaultPathMeasure(new MaxLengthCtxHistoryGenerator());
this.ctxManager = ctxManager;
}
| public WorstCasePath build(State endState, ChoiceGenerator<?> endCG) { |
isstac/spf-wca | src/main/wcanalysis/heuristic/WorstCasePath.java | // Path: src/main/wcanalysis/heuristic/PathMeasureComputation.java
// public static class Result {
// private final int resolutions;
// private final int memorylessResolution;
//
// public Result(int resolutions, int memorylessResolutions) {
// this.resolutions = resolutions;
// this.memorylessResolution = memorylessResolutions;
// }
//
// public int getMemorylessResolution() {
// return memorylessResolution;
// }
//
// public int getResolutions() {
// return resolutions;
// }
// }
//
// Path: src/main/wcanalysis/heuristic/model/State.java
// public abstract class State implements CSVable, Comparable<State> {
// private final PathCondition pc;
//
// public State(PathCondition pc) {
// this.pc = pc;
// }
//
// public PathCondition getPathCondition() {
// return this.pc;
// }
//
// // Should this return a double, or would we like to parameterize this (e.g. to subclasses of Number)?
// public abstract double getWC();
// }
| import gov.nasa.jpf.vm.ChoiceGenerator;
import wcanalysis.heuristic.PathMeasureComputation.Result;
import wcanalysis.heuristic.model.State;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.ListIterator;
import java.util.Map;
import java.util.Set; | /*
* MIT License
*
* Copyright (c) 2017 The ISSTAC Authors
*
* 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 wcanalysis.heuristic;
/**
* @author Kasper Luckow
*
*/
public class WorstCasePath extends Path implements Comparable<WorstCasePath> {
private static final long serialVersionUID = -6739423849594132561L;
public static class Builder {
private final ContextManager ctxManager;
private final PathMeasureComputation pathMeasureComp;
public Builder(ContextManager ctxManager, int maxHistory) {
this.pathMeasureComp = new DefaultPathMeasure(new FixedLengthCtxHistoryGenerator(maxHistory));
this.ctxManager = ctxManager;
}
public Builder(ContextManager ctxManager) {
this.pathMeasureComp = new DefaultPathMeasure(new MaxLengthCtxHistoryGenerator());
this.ctxManager = ctxManager;
}
public WorstCasePath build(State endState, ChoiceGenerator<?> endCG) {
return new WorstCasePath(endState, endCG, ctxManager, pathMeasureComp);
}
}
private final State finalState; | // Path: src/main/wcanalysis/heuristic/PathMeasureComputation.java
// public static class Result {
// private final int resolutions;
// private final int memorylessResolution;
//
// public Result(int resolutions, int memorylessResolutions) {
// this.resolutions = resolutions;
// this.memorylessResolution = memorylessResolutions;
// }
//
// public int getMemorylessResolution() {
// return memorylessResolution;
// }
//
// public int getResolutions() {
// return resolutions;
// }
// }
//
// Path: src/main/wcanalysis/heuristic/model/State.java
// public abstract class State implements CSVable, Comparable<State> {
// private final PathCondition pc;
//
// public State(PathCondition pc) {
// this.pc = pc;
// }
//
// public PathCondition getPathCondition() {
// return this.pc;
// }
//
// // Should this return a double, or would we like to parameterize this (e.g. to subclasses of Number)?
// public abstract double getWC();
// }
// Path: src/main/wcanalysis/heuristic/WorstCasePath.java
import gov.nasa.jpf.vm.ChoiceGenerator;
import wcanalysis.heuristic.PathMeasureComputation.Result;
import wcanalysis.heuristic.model.State;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.ListIterator;
import java.util.Map;
import java.util.Set;
/*
* MIT License
*
* Copyright (c) 2017 The ISSTAC Authors
*
* 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 wcanalysis.heuristic;
/**
* @author Kasper Luckow
*
*/
public class WorstCasePath extends Path implements Comparable<WorstCasePath> {
private static final long serialVersionUID = -6739423849594132561L;
public static class Builder {
private final ContextManager ctxManager;
private final PathMeasureComputation pathMeasureComp;
public Builder(ContextManager ctxManager, int maxHistory) {
this.pathMeasureComp = new DefaultPathMeasure(new FixedLengthCtxHistoryGenerator(maxHistory));
this.ctxManager = ctxManager;
}
public Builder(ContextManager ctxManager) {
this.pathMeasureComp = new DefaultPathMeasure(new MaxLengthCtxHistoryGenerator());
this.ctxManager = ctxManager;
}
public WorstCasePath build(State endState, ChoiceGenerator<?> endCG) {
return new WorstCasePath(endState, endCG, ctxManager, pathMeasureComp);
}
}
private final State finalState; | private Result pathMeasure = null; |
isstac/spf-wca | src/main/wcanalysis/heuristic/ContextManager.java | // Path: src/main/wcanalysis/heuristic/model/StateBuilder.java
// public interface StateBuilder {
// public StateBuilder copy();
//
// public void handleChoiceGeneratorAdvanced(VM vm, ChoiceGenerator<?> currentCG);
// public void handleExecuteInstruction(VM vm, ThreadInfo currentThread, Instruction instructionToExecute);
// public void handleInstructionExecuted(VM vm, ThreadInfo currentThread, Instruction nextInstruction, Instruction executedInstruction);
//
// public void handleObjectCreated(VM vm, ThreadInfo ti, ElementInfo ei);
// public void handleObjectReleased(VM vm, ThreadInfo ti, ElementInfo ei);
// public void handleMethodEntered(VM vm, ThreadInfo ti, MethodInfo ei);
// public void handleMethodExited(VM vm, ThreadInfo ti, MethodInfo ei);
//
// public State build(PathCondition resultingPC);
// }
| import java.util.HashMap;
import java.util.Map;
import gov.nasa.jpf.vm.ChoiceGenerator;
import gov.nasa.jpf.vm.StackFrame;
import wcanalysis.heuristic.model.StateBuilder; | /*
* MIT License
*
* Copyright (c) 2017 The ISSTAC Authors
*
* 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 wcanalysis.heuristic;
/**
* @author Kasper Luckow
* TODO: maybe we can just use threadinfo on the ChoiceGenerator
* instead of explicitly storing a reference to the stackframe
*/
public class ContextManager {
static class CGContext {
final StackFrame stackFrame; | // Path: src/main/wcanalysis/heuristic/model/StateBuilder.java
// public interface StateBuilder {
// public StateBuilder copy();
//
// public void handleChoiceGeneratorAdvanced(VM vm, ChoiceGenerator<?> currentCG);
// public void handleExecuteInstruction(VM vm, ThreadInfo currentThread, Instruction instructionToExecute);
// public void handleInstructionExecuted(VM vm, ThreadInfo currentThread, Instruction nextInstruction, Instruction executedInstruction);
//
// public void handleObjectCreated(VM vm, ThreadInfo ti, ElementInfo ei);
// public void handleObjectReleased(VM vm, ThreadInfo ti, ElementInfo ei);
// public void handleMethodEntered(VM vm, ThreadInfo ti, MethodInfo ei);
// public void handleMethodExited(VM vm, ThreadInfo ti, MethodInfo ei);
//
// public State build(PathCondition resultingPC);
// }
// Path: src/main/wcanalysis/heuristic/ContextManager.java
import java.util.HashMap;
import java.util.Map;
import gov.nasa.jpf.vm.ChoiceGenerator;
import gov.nasa.jpf.vm.StackFrame;
import wcanalysis.heuristic.model.StateBuilder;
/*
* MIT License
*
* Copyright (c) 2017 The ISSTAC Authors
*
* 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 wcanalysis.heuristic;
/**
* @author Kasper Luckow
* TODO: maybe we can just use threadinfo on the ChoiceGenerator
* instead of explicitly storing a reference to the stackframe
*/
public class ContextManager {
static class CGContext {
final StackFrame stackFrame; | final StateBuilder stateBuilder; |
isstac/spf-wca | src/main/wcanalysis/heuristic/BranchInstruction.java | // Path: src/main/wcanalysis/heuristic/util/Util.java
// public class Util {
//
// public static File createDirIfNotExist(File root, String subDir) {
// File sub = new File(root, subDir);
// if(!sub.exists())
// sub.mkdirs();
// return sub;
// }
//
// public static File createDirIfNotExist(String root) {
// File sub = new File(root);
// if(!sub.exists())
// sub.mkdirs();
// return sub;
// }
//
// public static File createDirIfNotExist(File dir) {
// if(!dir.exists())
// dir.mkdirs();
// return dir;
// }
//
// public static String normalizeJPFMethodName(MethodInfo methInfo) {
// int methBeginIdx = methInfo.getBaseName().lastIndexOf('.') + 1;
// String fullName = methInfo.getFullName();
// return fullName.substring(methBeginIdx, fullName.length());
// }
//
// public static Set<String> extractSimpleMethodNames(String[] jpfMethodSpecs) {
// //FIXME: This also means that we do not distinguish between overloaded methods
// String[] processedMethods = new String[jpfMethodSpecs.length];
// System.arraycopy(jpfMethodSpecs, 0, processedMethods, 0, jpfMethodSpecs.length);
// for(int i = 0; i < jpfMethodSpecs.length; i++) {
// String meth = jpfMethodSpecs[i];
// int sigBegin = meth.indexOf('(');
// if(sigBegin >= 0)
// processedMethods[i] = meth.substring(0, sigBegin);
// }
// return new HashSet<String>(Arrays.asList(processedMethods));
// }
// }
| import wcanalysis.heuristic.util.Util;
import java.io.Serializable;
import org.apache.commons.lang3.builder.EqualsBuilder;
import org.apache.commons.lang3.builder.HashCodeBuilder;
import gov.nasa.jpf.vm.Instruction; | /*
* MIT License
*
* Copyright (c) 2017 The ISSTAC Authors
*
* 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 wcanalysis.heuristic;
/**
* @author Kasper Luckow
* This is ugly, but we need a separate instructions class, because JPF's
* is not serializable
*/
public class BranchInstruction implements Serializable {
private static final long serialVersionUID = 7705704224210468320L;
private final String mnemonic;
private final int index;
private final int lineNumber;
private final String methodName;
private final String className;
public BranchInstruction(Instruction jpfInstruction) {
this(jpfInstruction.getMnemonic(),
jpfInstruction.getMethodInfo().getClassName(), | // Path: src/main/wcanalysis/heuristic/util/Util.java
// public class Util {
//
// public static File createDirIfNotExist(File root, String subDir) {
// File sub = new File(root, subDir);
// if(!sub.exists())
// sub.mkdirs();
// return sub;
// }
//
// public static File createDirIfNotExist(String root) {
// File sub = new File(root);
// if(!sub.exists())
// sub.mkdirs();
// return sub;
// }
//
// public static File createDirIfNotExist(File dir) {
// if(!dir.exists())
// dir.mkdirs();
// return dir;
// }
//
// public static String normalizeJPFMethodName(MethodInfo methInfo) {
// int methBeginIdx = methInfo.getBaseName().lastIndexOf('.') + 1;
// String fullName = methInfo.getFullName();
// return fullName.substring(methBeginIdx, fullName.length());
// }
//
// public static Set<String> extractSimpleMethodNames(String[] jpfMethodSpecs) {
// //FIXME: This also means that we do not distinguish between overloaded methods
// String[] processedMethods = new String[jpfMethodSpecs.length];
// System.arraycopy(jpfMethodSpecs, 0, processedMethods, 0, jpfMethodSpecs.length);
// for(int i = 0; i < jpfMethodSpecs.length; i++) {
// String meth = jpfMethodSpecs[i];
// int sigBegin = meth.indexOf('(');
// if(sigBegin >= 0)
// processedMethods[i] = meth.substring(0, sigBegin);
// }
// return new HashSet<String>(Arrays.asList(processedMethods));
// }
// }
// Path: src/main/wcanalysis/heuristic/BranchInstruction.java
import wcanalysis.heuristic.util.Util;
import java.io.Serializable;
import org.apache.commons.lang3.builder.EqualsBuilder;
import org.apache.commons.lang3.builder.HashCodeBuilder;
import gov.nasa.jpf.vm.Instruction;
/*
* MIT License
*
* Copyright (c) 2017 The ISSTAC Authors
*
* 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 wcanalysis.heuristic;
/**
* @author Kasper Luckow
* This is ugly, but we need a separate instructions class, because JPF's
* is not serializable
*/
public class BranchInstruction implements Serializable {
private static final long serialVersionUID = 7705704224210468320L;
private final String mnemonic;
private final int index;
private final int lineNumber;
private final String methodName;
private final String className;
public BranchInstruction(Instruction jpfInstruction) {
this(jpfInstruction.getMnemonic(),
jpfInstruction.getMethodInfo().getClassName(), | Util.normalizeJPFMethodName(jpfInstruction.getMethodInfo()), |
isstac/spf-wca | src/main/wcanalysis/heuristic/HeuristicResultsPublisher.java | // Path: src/main/wcanalysis/heuristic/util/Util.java
// public class Util {
//
// public static File createDirIfNotExist(File root, String subDir) {
// File sub = new File(root, subDir);
// if(!sub.exists())
// sub.mkdirs();
// return sub;
// }
//
// public static File createDirIfNotExist(String root) {
// File sub = new File(root);
// if(!sub.exists())
// sub.mkdirs();
// return sub;
// }
//
// public static File createDirIfNotExist(File dir) {
// if(!dir.exists())
// dir.mkdirs();
// return dir;
// }
//
// public static String normalizeJPFMethodName(MethodInfo methInfo) {
// int methBeginIdx = methInfo.getBaseName().lastIndexOf('.') + 1;
// String fullName = methInfo.getFullName();
// return fullName.substring(methBeginIdx, fullName.length());
// }
//
// public static Set<String> extractSimpleMethodNames(String[] jpfMethodSpecs) {
// //FIXME: This also means that we do not distinguish between overloaded methods
// String[] processedMethods = new String[jpfMethodSpecs.length];
// System.arraycopy(jpfMethodSpecs, 0, processedMethods, 0, jpfMethodSpecs.length);
// for(int i = 0; i < jpfMethodSpecs.length; i++) {
// String meth = jpfMethodSpecs[i];
// int sigBegin = meth.indexOf('(');
// if(sigBegin >= 0)
// processedMethods[i] = meth.substring(0, sigBegin);
// }
// return new HashSet<String>(Arrays.asList(processedMethods));
// }
// }
| import java.io.File;
import gov.nasa.jpf.Config;
import gov.nasa.jpf.report.Reporter;
import wcanalysis.heuristic.util.Util; | /*
* MIT License
*
* Copyright (c) 2017 The ISSTAC Authors
*
* 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 wcanalysis.heuristic;
/**
* @author Kasper Luckow
*/
public class HeuristicResultsPublisher extends ResultsPublisher {
public static final String RESULTS_DIR_CONF = "report.console.wc.heuristic.resultsdir";
public HeuristicResultsPublisher(Config conf, Reporter reporter) {
super(conf, reporter);
}
@Override
protected String getCustomCSVColumnHeader() {
return "resolvedChoicesNum,resolvedPerfectChoicesNum,resolvedHistoryChoicesNum,resolvedInvariantChoicesNum,unresolvedChoicesNum,newChoicesNum";
}
@Override
protected String getCustomCSVColumnData() {
HeuristicListener listener = reporter.getVM().getNextListenerOfType(HeuristicListener.class, null);
if(listener == null)
return "";
HeuristicStatistics statistics = listener.getStatistics();
String out = (statistics.resolvedHistoryChoices + statistics.resolvedInvariantChoices +
statistics.resolvedPerfectChoices) + "," +
statistics.resolvedPerfectChoices + "," +
statistics.resolvedHistoryChoices + "," +
statistics.resolvedInvariantChoices + "," +
statistics.unresolvedChoices + "," +
statistics.newChoices;
return out;
}
@Override
protected File getResultsDir(Config conf) { | // Path: src/main/wcanalysis/heuristic/util/Util.java
// public class Util {
//
// public static File createDirIfNotExist(File root, String subDir) {
// File sub = new File(root, subDir);
// if(!sub.exists())
// sub.mkdirs();
// return sub;
// }
//
// public static File createDirIfNotExist(String root) {
// File sub = new File(root);
// if(!sub.exists())
// sub.mkdirs();
// return sub;
// }
//
// public static File createDirIfNotExist(File dir) {
// if(!dir.exists())
// dir.mkdirs();
// return dir;
// }
//
// public static String normalizeJPFMethodName(MethodInfo methInfo) {
// int methBeginIdx = methInfo.getBaseName().lastIndexOf('.') + 1;
// String fullName = methInfo.getFullName();
// return fullName.substring(methBeginIdx, fullName.length());
// }
//
// public static Set<String> extractSimpleMethodNames(String[] jpfMethodSpecs) {
// //FIXME: This also means that we do not distinguish between overloaded methods
// String[] processedMethods = new String[jpfMethodSpecs.length];
// System.arraycopy(jpfMethodSpecs, 0, processedMethods, 0, jpfMethodSpecs.length);
// for(int i = 0; i < jpfMethodSpecs.length; i++) {
// String meth = jpfMethodSpecs[i];
// int sigBegin = meth.indexOf('(');
// if(sigBegin >= 0)
// processedMethods[i] = meth.substring(0, sigBegin);
// }
// return new HashSet<String>(Arrays.asList(processedMethods));
// }
// }
// Path: src/main/wcanalysis/heuristic/HeuristicResultsPublisher.java
import java.io.File;
import gov.nasa.jpf.Config;
import gov.nasa.jpf.report.Reporter;
import wcanalysis.heuristic.util.Util;
/*
* MIT License
*
* Copyright (c) 2017 The ISSTAC Authors
*
* 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 wcanalysis.heuristic;
/**
* @author Kasper Luckow
*/
public class HeuristicResultsPublisher extends ResultsPublisher {
public static final String RESULTS_DIR_CONF = "report.console.wc.heuristic.resultsdir";
public HeuristicResultsPublisher(Config conf, Reporter reporter) {
super(conf, reporter);
}
@Override
protected String getCustomCSVColumnHeader() {
return "resolvedChoicesNum,resolvedPerfectChoicesNum,resolvedHistoryChoicesNum,resolvedInvariantChoicesNum,unresolvedChoicesNum,newChoicesNum";
}
@Override
protected String getCustomCSVColumnData() {
HeuristicListener listener = reporter.getVM().getNextListenerOfType(HeuristicListener.class, null);
if(listener == null)
return "";
HeuristicStatistics statistics = listener.getStatistics();
String out = (statistics.resolvedHistoryChoices + statistics.resolvedInvariantChoices +
statistics.resolvedPerfectChoices) + "," +
statistics.resolvedPerfectChoices + "," +
statistics.resolvedHistoryChoices + "," +
statistics.resolvedInvariantChoices + "," +
statistics.unresolvedChoices + "," +
statistics.newChoices;
return out;
}
@Override
protected File getResultsDir(Config conf) { | return Util.createDirIfNotExist(conf.getString(RESULTS_DIR_CONF, "./results/heuristic")); |
isstac/spf-wca | src/main/wcanalysis/heuristic/ResultsPublisher.java | // Path: src/main/wcanalysis/heuristic/model/State.java
// public abstract class State implements CSVable, Comparable<State> {
// private final PathCondition pc;
//
// public State(PathCondition pc) {
// this.pc = pc;
// }
//
// public PathCondition getPathCondition() {
// return this.pc;
// }
//
// // Should this return a double, or would we like to parameterize this (e.g. to subclasses of Number)?
// public abstract double getWC();
// }
//
// Path: src/main/wcanalysis/heuristic/util/OmegaConverter.java
// public class OmegaConverter implements ConstraintsConverter {
//
// @Override
// public String convert(PathCondition pc) {
// if(pc == null)
// return "";
// PathCondition convertPc = pc.make_copy(); //probably not necessary...
//
// HashSet<String> vars = new HashSet<>();
// //TODO: does the collector *only* collect integer vars? That's weird
// SymbolicVariableCollector collector = new SymbolicVariableCollector(vars);
// collector.collectVariables(convertPc);
//
// StringBuilder omegaVarDecl = new StringBuilder();
// Iterator<String> iter = vars.iterator();
// while(iter.hasNext()) {
// omegaVarDecl.append(clean(iter.next()));
// if(iter.hasNext())
// omegaVarDecl.append(',');
// }
//
// StringBuilder omegaStr = new StringBuilder();
// omegaStr.append("{[").append(omegaVarDecl.toString()).append("] : ").append(clean(convertPc)).append("};");
//
// return omegaStr.toString();
// }
//
// private static String clean(PathCondition pc) {
// return (pc.header == null) ? "TRUE" : clean(pc.header.toString());
// }
//
// private static String clean(String constraintsString) {
// String clean = constraintsString.replaceAll("\\s+", "");
// clean = clean.replaceAll("CONST_(\\d+)", "$1");
// clean = clean.replaceAll("CONST_-(\\d+)", "-$1");
// clean = clean.replaceAll("[a-zA-Z]", "s");
// return clean;
// }
// }
//
// Path: src/main/wcanalysis/heuristic/util/SMTLibConverter.java
// public class SMTLibConverter implements ConstraintsConverter {
//
// @Override
// public String convert(PathCondition pc) {
// if(pc == null || pc.header == null)
// return "";
// StringBuilder smtLib = new StringBuilder();
// HashSet<String> setOfSymVar = new HashSet<String>();
// SymbolicVariableCollector collector = new SymbolicVariableCollector(setOfSymVar);
// collector.collectVariables(pc);
// //Add declarations
// for (String var : collector.getListOfVariables())
// smtLib.append("(declare-const " + var + " Int)\n");
// //make assertion
// smtLib.append('\n');
// smtLib.append("(assert ").append(pc.header.prefix_notation()).append(")\n\n");
// smtLib.append("(check-sat)\n");
// smtLib.append("(get-model)");
// return smtLib.toString();
// }
// }
| import java.io.IOException;
import java.io.PrintWriter;
import java.util.logging.Logger;
import gov.nasa.jpf.Config;
import gov.nasa.jpf.JPF;
import gov.nasa.jpf.report.Publisher;
import gov.nasa.jpf.report.Reporter;
import gov.nasa.jpf.report.Statistics;
import gov.nasa.jpf.symbc.numeric.PathCondition;
import wcanalysis.heuristic.model.State;
import wcanalysis.heuristic.util.OmegaConverter;
import wcanalysis.heuristic.util.SMTLibConverter;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.FileReader;
import java.io.FileWriter; |
}
@Override
public void publishStatistics() {
}
private static boolean isFileEmpty(File file) {
try(BufferedReader br = new BufferedReader(new FileReader(file))) {
if(br.readLine() == null) {
return true;
} else
return false;
} catch (IOException e1) {
e1.printStackTrace();
return false;
}
}
@Override
public void publishResult() {
PathListener pathListener = getListener();
if(pathListener != null) {
Statistics stat = reporter.getStatistics();
WorstCasePath wcPath = pathListener.getWcPath();
if(wcPath == null)
return; | // Path: src/main/wcanalysis/heuristic/model/State.java
// public abstract class State implements CSVable, Comparable<State> {
// private final PathCondition pc;
//
// public State(PathCondition pc) {
// this.pc = pc;
// }
//
// public PathCondition getPathCondition() {
// return this.pc;
// }
//
// // Should this return a double, or would we like to parameterize this (e.g. to subclasses of Number)?
// public abstract double getWC();
// }
//
// Path: src/main/wcanalysis/heuristic/util/OmegaConverter.java
// public class OmegaConverter implements ConstraintsConverter {
//
// @Override
// public String convert(PathCondition pc) {
// if(pc == null)
// return "";
// PathCondition convertPc = pc.make_copy(); //probably not necessary...
//
// HashSet<String> vars = new HashSet<>();
// //TODO: does the collector *only* collect integer vars? That's weird
// SymbolicVariableCollector collector = new SymbolicVariableCollector(vars);
// collector.collectVariables(convertPc);
//
// StringBuilder omegaVarDecl = new StringBuilder();
// Iterator<String> iter = vars.iterator();
// while(iter.hasNext()) {
// omegaVarDecl.append(clean(iter.next()));
// if(iter.hasNext())
// omegaVarDecl.append(',');
// }
//
// StringBuilder omegaStr = new StringBuilder();
// omegaStr.append("{[").append(omegaVarDecl.toString()).append("] : ").append(clean(convertPc)).append("};");
//
// return omegaStr.toString();
// }
//
// private static String clean(PathCondition pc) {
// return (pc.header == null) ? "TRUE" : clean(pc.header.toString());
// }
//
// private static String clean(String constraintsString) {
// String clean = constraintsString.replaceAll("\\s+", "");
// clean = clean.replaceAll("CONST_(\\d+)", "$1");
// clean = clean.replaceAll("CONST_-(\\d+)", "-$1");
// clean = clean.replaceAll("[a-zA-Z]", "s");
// return clean;
// }
// }
//
// Path: src/main/wcanalysis/heuristic/util/SMTLibConverter.java
// public class SMTLibConverter implements ConstraintsConverter {
//
// @Override
// public String convert(PathCondition pc) {
// if(pc == null || pc.header == null)
// return "";
// StringBuilder smtLib = new StringBuilder();
// HashSet<String> setOfSymVar = new HashSet<String>();
// SymbolicVariableCollector collector = new SymbolicVariableCollector(setOfSymVar);
// collector.collectVariables(pc);
// //Add declarations
// for (String var : collector.getListOfVariables())
// smtLib.append("(declare-const " + var + " Int)\n");
// //make assertion
// smtLib.append('\n');
// smtLib.append("(assert ").append(pc.header.prefix_notation()).append(")\n\n");
// smtLib.append("(check-sat)\n");
// smtLib.append("(get-model)");
// return smtLib.toString();
// }
// }
// Path: src/main/wcanalysis/heuristic/ResultsPublisher.java
import java.io.IOException;
import java.io.PrintWriter;
import java.util.logging.Logger;
import gov.nasa.jpf.Config;
import gov.nasa.jpf.JPF;
import gov.nasa.jpf.report.Publisher;
import gov.nasa.jpf.report.Reporter;
import gov.nasa.jpf.report.Statistics;
import gov.nasa.jpf.symbc.numeric.PathCondition;
import wcanalysis.heuristic.model.State;
import wcanalysis.heuristic.util.OmegaConverter;
import wcanalysis.heuristic.util.SMTLibConverter;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.FileReader;
import java.io.FileWriter;
}
@Override
public void publishStatistics() {
}
private static boolean isFileEmpty(File file) {
try(BufferedReader br = new BufferedReader(new FileReader(file))) {
if(br.readLine() == null) {
return true;
} else
return false;
} catch (IOException e1) {
e1.printStackTrace();
return false;
}
}
@Override
public void publishResult() {
PathListener pathListener = getListener();
if(pathListener != null) {
Statistics stat = reporter.getStatistics();
WorstCasePath wcPath = pathListener.getWcPath();
if(wcPath == null)
return; | State wcState = wcPath.getWCState(); |
isstac/spf-wca | src/main/wcanalysis/heuristic/ResultsPublisher.java | // Path: src/main/wcanalysis/heuristic/model/State.java
// public abstract class State implements CSVable, Comparable<State> {
// private final PathCondition pc;
//
// public State(PathCondition pc) {
// this.pc = pc;
// }
//
// public PathCondition getPathCondition() {
// return this.pc;
// }
//
// // Should this return a double, or would we like to parameterize this (e.g. to subclasses of Number)?
// public abstract double getWC();
// }
//
// Path: src/main/wcanalysis/heuristic/util/OmegaConverter.java
// public class OmegaConverter implements ConstraintsConverter {
//
// @Override
// public String convert(PathCondition pc) {
// if(pc == null)
// return "";
// PathCondition convertPc = pc.make_copy(); //probably not necessary...
//
// HashSet<String> vars = new HashSet<>();
// //TODO: does the collector *only* collect integer vars? That's weird
// SymbolicVariableCollector collector = new SymbolicVariableCollector(vars);
// collector.collectVariables(convertPc);
//
// StringBuilder omegaVarDecl = new StringBuilder();
// Iterator<String> iter = vars.iterator();
// while(iter.hasNext()) {
// omegaVarDecl.append(clean(iter.next()));
// if(iter.hasNext())
// omegaVarDecl.append(',');
// }
//
// StringBuilder omegaStr = new StringBuilder();
// omegaStr.append("{[").append(omegaVarDecl.toString()).append("] : ").append(clean(convertPc)).append("};");
//
// return omegaStr.toString();
// }
//
// private static String clean(PathCondition pc) {
// return (pc.header == null) ? "TRUE" : clean(pc.header.toString());
// }
//
// private static String clean(String constraintsString) {
// String clean = constraintsString.replaceAll("\\s+", "");
// clean = clean.replaceAll("CONST_(\\d+)", "$1");
// clean = clean.replaceAll("CONST_-(\\d+)", "-$1");
// clean = clean.replaceAll("[a-zA-Z]", "s");
// return clean;
// }
// }
//
// Path: src/main/wcanalysis/heuristic/util/SMTLibConverter.java
// public class SMTLibConverter implements ConstraintsConverter {
//
// @Override
// public String convert(PathCondition pc) {
// if(pc == null || pc.header == null)
// return "";
// StringBuilder smtLib = new StringBuilder();
// HashSet<String> setOfSymVar = new HashSet<String>();
// SymbolicVariableCollector collector = new SymbolicVariableCollector(setOfSymVar);
// collector.collectVariables(pc);
// //Add declarations
// for (String var : collector.getListOfVariables())
// smtLib.append("(declare-const " + var + " Int)\n");
// //make assertion
// smtLib.append('\n');
// smtLib.append("(assert ").append(pc.header.prefix_notation()).append(")\n\n");
// smtLib.append("(check-sat)\n");
// smtLib.append("(get-model)");
// return smtLib.toString();
// }
// }
| import java.io.IOException;
import java.io.PrintWriter;
import java.util.logging.Logger;
import gov.nasa.jpf.Config;
import gov.nasa.jpf.JPF;
import gov.nasa.jpf.report.Publisher;
import gov.nasa.jpf.report.Reporter;
import gov.nasa.jpf.report.Statistics;
import gov.nasa.jpf.symbc.numeric.PathCondition;
import wcanalysis.heuristic.model.State;
import wcanalysis.heuristic.util.OmegaConverter;
import wcanalysis.heuristic.util.SMTLibConverter;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.FileReader;
import java.io.FileWriter; | if(!stateCSVHeader.endsWith(","))
stateCSVHeader += ",";
String header = "inputSize," +
((this.cfgInputSize >= 0) ? "cfgInputSize," : "") +
stateCSVHeader +
"analysisTime,mem,paths," +
getCustomCSVColumnHeader() +
",wcConstraint";
out.println(header);
}
out.print(conf.getString("target.args") + ",");
if(cfgInputSize >= 0)
out.print(cfgInputSize + ",");
String stateCSVRes = wcState.getCSV();
if(!stateCSVRes.endsWith(","))
stateCSVRes += ",";
out.print(stateCSVRes);
out.print((reporter.getElapsedTime()/1000) + ",");
out.print((stat.maxUsed >> 20) + ",");
out.print(stat.endStates + ",");
out.print(this.getCustomCSVColumnData() + ",");
if(wcState.getPathCondition() == null) {
logger.severe("Worst case result state does not have associated constraints! Is it the worst case state at all?");
out.println("CONSTRAINT N/A");
} else {
PathCondition pc = wcState.getPathCondition();
if(generateSMTLibFormat) { | // Path: src/main/wcanalysis/heuristic/model/State.java
// public abstract class State implements CSVable, Comparable<State> {
// private final PathCondition pc;
//
// public State(PathCondition pc) {
// this.pc = pc;
// }
//
// public PathCondition getPathCondition() {
// return this.pc;
// }
//
// // Should this return a double, or would we like to parameterize this (e.g. to subclasses of Number)?
// public abstract double getWC();
// }
//
// Path: src/main/wcanalysis/heuristic/util/OmegaConverter.java
// public class OmegaConverter implements ConstraintsConverter {
//
// @Override
// public String convert(PathCondition pc) {
// if(pc == null)
// return "";
// PathCondition convertPc = pc.make_copy(); //probably not necessary...
//
// HashSet<String> vars = new HashSet<>();
// //TODO: does the collector *only* collect integer vars? That's weird
// SymbolicVariableCollector collector = new SymbolicVariableCollector(vars);
// collector.collectVariables(convertPc);
//
// StringBuilder omegaVarDecl = new StringBuilder();
// Iterator<String> iter = vars.iterator();
// while(iter.hasNext()) {
// omegaVarDecl.append(clean(iter.next()));
// if(iter.hasNext())
// omegaVarDecl.append(',');
// }
//
// StringBuilder omegaStr = new StringBuilder();
// omegaStr.append("{[").append(omegaVarDecl.toString()).append("] : ").append(clean(convertPc)).append("};");
//
// return omegaStr.toString();
// }
//
// private static String clean(PathCondition pc) {
// return (pc.header == null) ? "TRUE" : clean(pc.header.toString());
// }
//
// private static String clean(String constraintsString) {
// String clean = constraintsString.replaceAll("\\s+", "");
// clean = clean.replaceAll("CONST_(\\d+)", "$1");
// clean = clean.replaceAll("CONST_-(\\d+)", "-$1");
// clean = clean.replaceAll("[a-zA-Z]", "s");
// return clean;
// }
// }
//
// Path: src/main/wcanalysis/heuristic/util/SMTLibConverter.java
// public class SMTLibConverter implements ConstraintsConverter {
//
// @Override
// public String convert(PathCondition pc) {
// if(pc == null || pc.header == null)
// return "";
// StringBuilder smtLib = new StringBuilder();
// HashSet<String> setOfSymVar = new HashSet<String>();
// SymbolicVariableCollector collector = new SymbolicVariableCollector(setOfSymVar);
// collector.collectVariables(pc);
// //Add declarations
// for (String var : collector.getListOfVariables())
// smtLib.append("(declare-const " + var + " Int)\n");
// //make assertion
// smtLib.append('\n');
// smtLib.append("(assert ").append(pc.header.prefix_notation()).append(")\n\n");
// smtLib.append("(check-sat)\n");
// smtLib.append("(get-model)");
// return smtLib.toString();
// }
// }
// Path: src/main/wcanalysis/heuristic/ResultsPublisher.java
import java.io.IOException;
import java.io.PrintWriter;
import java.util.logging.Logger;
import gov.nasa.jpf.Config;
import gov.nasa.jpf.JPF;
import gov.nasa.jpf.report.Publisher;
import gov.nasa.jpf.report.Reporter;
import gov.nasa.jpf.report.Statistics;
import gov.nasa.jpf.symbc.numeric.PathCondition;
import wcanalysis.heuristic.model.State;
import wcanalysis.heuristic.util.OmegaConverter;
import wcanalysis.heuristic.util.SMTLibConverter;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.FileReader;
import java.io.FileWriter;
if(!stateCSVHeader.endsWith(","))
stateCSVHeader += ",";
String header = "inputSize," +
((this.cfgInputSize >= 0) ? "cfgInputSize," : "") +
stateCSVHeader +
"analysisTime,mem,paths," +
getCustomCSVColumnHeader() +
",wcConstraint";
out.println(header);
}
out.print(conf.getString("target.args") + ",");
if(cfgInputSize >= 0)
out.print(cfgInputSize + ",");
String stateCSVRes = wcState.getCSV();
if(!stateCSVRes.endsWith(","))
stateCSVRes += ",";
out.print(stateCSVRes);
out.print((reporter.getElapsedTime()/1000) + ",");
out.print((stat.maxUsed >> 20) + ",");
out.print(stat.endStates + ",");
out.print(this.getCustomCSVColumnData() + ",");
if(wcState.getPathCondition() == null) {
logger.severe("Worst case result state does not have associated constraints! Is it the worst case state at all?");
out.println("CONSTRAINT N/A");
} else {
PathCondition pc = wcState.getPathCondition();
if(generateSMTLibFormat) { | String smtLibPc = new SMTLibConverter().convert(pc); |
isstac/spf-wca | src/main/wcanalysis/heuristic/ResultsPublisher.java | // Path: src/main/wcanalysis/heuristic/model/State.java
// public abstract class State implements CSVable, Comparable<State> {
// private final PathCondition pc;
//
// public State(PathCondition pc) {
// this.pc = pc;
// }
//
// public PathCondition getPathCondition() {
// return this.pc;
// }
//
// // Should this return a double, or would we like to parameterize this (e.g. to subclasses of Number)?
// public abstract double getWC();
// }
//
// Path: src/main/wcanalysis/heuristic/util/OmegaConverter.java
// public class OmegaConverter implements ConstraintsConverter {
//
// @Override
// public String convert(PathCondition pc) {
// if(pc == null)
// return "";
// PathCondition convertPc = pc.make_copy(); //probably not necessary...
//
// HashSet<String> vars = new HashSet<>();
// //TODO: does the collector *only* collect integer vars? That's weird
// SymbolicVariableCollector collector = new SymbolicVariableCollector(vars);
// collector.collectVariables(convertPc);
//
// StringBuilder omegaVarDecl = new StringBuilder();
// Iterator<String> iter = vars.iterator();
// while(iter.hasNext()) {
// omegaVarDecl.append(clean(iter.next()));
// if(iter.hasNext())
// omegaVarDecl.append(',');
// }
//
// StringBuilder omegaStr = new StringBuilder();
// omegaStr.append("{[").append(omegaVarDecl.toString()).append("] : ").append(clean(convertPc)).append("};");
//
// return omegaStr.toString();
// }
//
// private static String clean(PathCondition pc) {
// return (pc.header == null) ? "TRUE" : clean(pc.header.toString());
// }
//
// private static String clean(String constraintsString) {
// String clean = constraintsString.replaceAll("\\s+", "");
// clean = clean.replaceAll("CONST_(\\d+)", "$1");
// clean = clean.replaceAll("CONST_-(\\d+)", "-$1");
// clean = clean.replaceAll("[a-zA-Z]", "s");
// return clean;
// }
// }
//
// Path: src/main/wcanalysis/heuristic/util/SMTLibConverter.java
// public class SMTLibConverter implements ConstraintsConverter {
//
// @Override
// public String convert(PathCondition pc) {
// if(pc == null || pc.header == null)
// return "";
// StringBuilder smtLib = new StringBuilder();
// HashSet<String> setOfSymVar = new HashSet<String>();
// SymbolicVariableCollector collector = new SymbolicVariableCollector(setOfSymVar);
// collector.collectVariables(pc);
// //Add declarations
// for (String var : collector.getListOfVariables())
// smtLib.append("(declare-const " + var + " Int)\n");
// //make assertion
// smtLib.append('\n');
// smtLib.append("(assert ").append(pc.header.prefix_notation()).append(")\n\n");
// smtLib.append("(check-sat)\n");
// smtLib.append("(get-model)");
// return smtLib.toString();
// }
// }
| import java.io.IOException;
import java.io.PrintWriter;
import java.util.logging.Logger;
import gov.nasa.jpf.Config;
import gov.nasa.jpf.JPF;
import gov.nasa.jpf.report.Publisher;
import gov.nasa.jpf.report.Reporter;
import gov.nasa.jpf.report.Statistics;
import gov.nasa.jpf.symbc.numeric.PathCondition;
import wcanalysis.heuristic.model.State;
import wcanalysis.heuristic.util.OmegaConverter;
import wcanalysis.heuristic.util.SMTLibConverter;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.FileReader;
import java.io.FileWriter; | stateCSVHeader +
"analysisTime,mem,paths," +
getCustomCSVColumnHeader() +
",wcConstraint";
out.println(header);
}
out.print(conf.getString("target.args") + ",");
if(cfgInputSize >= 0)
out.print(cfgInputSize + ",");
String stateCSVRes = wcState.getCSV();
if(!stateCSVRes.endsWith(","))
stateCSVRes += ",";
out.print(stateCSVRes);
out.print((reporter.getElapsedTime()/1000) + ",");
out.print((stat.maxUsed >> 20) + ",");
out.print(stat.endStates + ",");
out.print(this.getCustomCSVColumnData() + ",");
if(wcState.getPathCondition() == null) {
logger.severe("Worst case result state does not have associated constraints! Is it the worst case state at all?");
out.println("CONSTRAINT N/A");
} else {
PathCondition pc = wcState.getPathCondition();
if(generateSMTLibFormat) {
String smtLibPc = new SMTLibConverter().convert(pc);
writeConstraintsFile(smtLibPc, ".smt2");
}
if(generateOmegaFormat) { | // Path: src/main/wcanalysis/heuristic/model/State.java
// public abstract class State implements CSVable, Comparable<State> {
// private final PathCondition pc;
//
// public State(PathCondition pc) {
// this.pc = pc;
// }
//
// public PathCondition getPathCondition() {
// return this.pc;
// }
//
// // Should this return a double, or would we like to parameterize this (e.g. to subclasses of Number)?
// public abstract double getWC();
// }
//
// Path: src/main/wcanalysis/heuristic/util/OmegaConverter.java
// public class OmegaConverter implements ConstraintsConverter {
//
// @Override
// public String convert(PathCondition pc) {
// if(pc == null)
// return "";
// PathCondition convertPc = pc.make_copy(); //probably not necessary...
//
// HashSet<String> vars = new HashSet<>();
// //TODO: does the collector *only* collect integer vars? That's weird
// SymbolicVariableCollector collector = new SymbolicVariableCollector(vars);
// collector.collectVariables(convertPc);
//
// StringBuilder omegaVarDecl = new StringBuilder();
// Iterator<String> iter = vars.iterator();
// while(iter.hasNext()) {
// omegaVarDecl.append(clean(iter.next()));
// if(iter.hasNext())
// omegaVarDecl.append(',');
// }
//
// StringBuilder omegaStr = new StringBuilder();
// omegaStr.append("{[").append(omegaVarDecl.toString()).append("] : ").append(clean(convertPc)).append("};");
//
// return omegaStr.toString();
// }
//
// private static String clean(PathCondition pc) {
// return (pc.header == null) ? "TRUE" : clean(pc.header.toString());
// }
//
// private static String clean(String constraintsString) {
// String clean = constraintsString.replaceAll("\\s+", "");
// clean = clean.replaceAll("CONST_(\\d+)", "$1");
// clean = clean.replaceAll("CONST_-(\\d+)", "-$1");
// clean = clean.replaceAll("[a-zA-Z]", "s");
// return clean;
// }
// }
//
// Path: src/main/wcanalysis/heuristic/util/SMTLibConverter.java
// public class SMTLibConverter implements ConstraintsConverter {
//
// @Override
// public String convert(PathCondition pc) {
// if(pc == null || pc.header == null)
// return "";
// StringBuilder smtLib = new StringBuilder();
// HashSet<String> setOfSymVar = new HashSet<String>();
// SymbolicVariableCollector collector = new SymbolicVariableCollector(setOfSymVar);
// collector.collectVariables(pc);
// //Add declarations
// for (String var : collector.getListOfVariables())
// smtLib.append("(declare-const " + var + " Int)\n");
// //make assertion
// smtLib.append('\n');
// smtLib.append("(assert ").append(pc.header.prefix_notation()).append(")\n\n");
// smtLib.append("(check-sat)\n");
// smtLib.append("(get-model)");
// return smtLib.toString();
// }
// }
// Path: src/main/wcanalysis/heuristic/ResultsPublisher.java
import java.io.IOException;
import java.io.PrintWriter;
import java.util.logging.Logger;
import gov.nasa.jpf.Config;
import gov.nasa.jpf.JPF;
import gov.nasa.jpf.report.Publisher;
import gov.nasa.jpf.report.Reporter;
import gov.nasa.jpf.report.Statistics;
import gov.nasa.jpf.symbc.numeric.PathCondition;
import wcanalysis.heuristic.model.State;
import wcanalysis.heuristic.util.OmegaConverter;
import wcanalysis.heuristic.util.SMTLibConverter;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.FileReader;
import java.io.FileWriter;
stateCSVHeader +
"analysisTime,mem,paths," +
getCustomCSVColumnHeader() +
",wcConstraint";
out.println(header);
}
out.print(conf.getString("target.args") + ",");
if(cfgInputSize >= 0)
out.print(cfgInputSize + ",");
String stateCSVRes = wcState.getCSV();
if(!stateCSVRes.endsWith(","))
stateCSVRes += ",";
out.print(stateCSVRes);
out.print((reporter.getElapsedTime()/1000) + ",");
out.print((stat.maxUsed >> 20) + ",");
out.print(stat.endStates + ",");
out.print(this.getCustomCSVColumnData() + ",");
if(wcState.getPathCondition() == null) {
logger.severe("Worst case result state does not have associated constraints! Is it the worst case state at all?");
out.println("CONSTRAINT N/A");
} else {
PathCondition pc = wcState.getPathCondition();
if(generateSMTLibFormat) {
String smtLibPc = new SMTLibConverter().convert(pc);
writeConstraintsFile(smtLibPc, ".smt2");
}
if(generateOmegaFormat) { | String omegaConstraints = new OmegaConverter().convert(pc); |
isstac/spf-wca | src/main/wcanalysis/heuristic/Path.java | // Path: src/main/wcanalysis/heuristic/ContextManager.java
// static class CGContext {
// final StackFrame stackFrame;
// final StateBuilder stateBuilder;
//
// public CGContext(StackFrame sf, StateBuilder stateBuilder) {
// this.stackFrame = sf;
// this.stateBuilder = stateBuilder;
// }
// }
| import gov.nasa.jpf.vm.StackFrame;
import wcanalysis.heuristic.ContextManager.CGContext;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.LinkedList;
import gov.nasa.jpf.symbc.numeric.PCChoiceGenerator;
import gov.nasa.jpf.vm.ChoiceGenerator; | /*
* MIT License
*
* Copyright (c) 2017 The ISSTAC Authors
*
* 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 wcanalysis.heuristic;
/**
* @author Kasper Luckow
* TODO: Clean up how (sub)paths can be generated (static methods, from CGs, ...)
* both context preserving and not context preserving.
*/
public class Path extends ArrayList<Decision> {
private static final long serialVersionUID = -1691414612424473640L;
public Path() { }
public Path(Path other) {
super(other);
}
//TODO: ugly
public static Path generateCtxPreservingHistory(ChoiceGenerator<?> endCG, ContextManager ctxManager, int maxSize) {
Path p = new Path();
if(maxSize <= 0)
return p;
PCChoiceGenerator previousPCcg = endCG.getPreviousChoiceGeneratorOfType(PCChoiceGenerator.class);
generatePath(p, previousPCcg, ctxManager, ctxManager.getContext(endCG), true, maxSize);
return p;
}
| // Path: src/main/wcanalysis/heuristic/ContextManager.java
// static class CGContext {
// final StackFrame stackFrame;
// final StateBuilder stateBuilder;
//
// public CGContext(StackFrame sf, StateBuilder stateBuilder) {
// this.stackFrame = sf;
// this.stateBuilder = stateBuilder;
// }
// }
// Path: src/main/wcanalysis/heuristic/Path.java
import gov.nasa.jpf.vm.StackFrame;
import wcanalysis.heuristic.ContextManager.CGContext;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.LinkedList;
import gov.nasa.jpf.symbc.numeric.PCChoiceGenerator;
import gov.nasa.jpf.vm.ChoiceGenerator;
/*
* MIT License
*
* Copyright (c) 2017 The ISSTAC Authors
*
* 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 wcanalysis.heuristic;
/**
* @author Kasper Luckow
* TODO: Clean up how (sub)paths can be generated (static methods, from CGs, ...)
* both context preserving and not context preserving.
*/
public class Path extends ArrayList<Decision> {
private static final long serialVersionUID = -1691414612424473640L;
public Path() { }
public Path(Path other) {
super(other);
}
//TODO: ugly
public static Path generateCtxPreservingHistory(ChoiceGenerator<?> endCG, ContextManager ctxManager, int maxSize) {
Path p = new Path();
if(maxSize <= 0)
return p;
PCChoiceGenerator previousPCcg = endCG.getPreviousChoiceGeneratorOfType(PCChoiceGenerator.class);
generatePath(p, previousPCcg, ctxManager, ctxManager.getContext(endCG), true, maxSize);
return p;
}
| private static void generatePath(Path path, ChoiceGenerator<?> endCG, ContextManager ctxManager, CGContext ctx, boolean ctxPreserving, int maxSize) { |
isstac/spf-wca | src/main/wcanalysis/heuristic/model/MethodCallCountState.java | // Path: src/main/wcanalysis/heuristic/util/Util.java
// public class Util {
//
// public static File createDirIfNotExist(File root, String subDir) {
// File sub = new File(root, subDir);
// if(!sub.exists())
// sub.mkdirs();
// return sub;
// }
//
// public static File createDirIfNotExist(String root) {
// File sub = new File(root);
// if(!sub.exists())
// sub.mkdirs();
// return sub;
// }
//
// public static File createDirIfNotExist(File dir) {
// if(!dir.exists())
// dir.mkdirs();
// return dir;
// }
//
// public static String normalizeJPFMethodName(MethodInfo methInfo) {
// int methBeginIdx = methInfo.getBaseName().lastIndexOf('.') + 1;
// String fullName = methInfo.getFullName();
// return fullName.substring(methBeginIdx, fullName.length());
// }
//
// public static Set<String> extractSimpleMethodNames(String[] jpfMethodSpecs) {
// //FIXME: This also means that we do not distinguish between overloaded methods
// String[] processedMethods = new String[jpfMethodSpecs.length];
// System.arraycopy(jpfMethodSpecs, 0, processedMethods, 0, jpfMethodSpecs.length);
// for(int i = 0; i < jpfMethodSpecs.length; i++) {
// String meth = jpfMethodSpecs[i];
// int sigBegin = meth.indexOf('(');
// if(sigBegin >= 0)
// processedMethods[i] = meth.substring(0, sigBegin);
// }
// return new HashSet<String>(Arrays.asList(processedMethods));
// }
// }
| import wcanalysis.heuristic.util.Util;
import java.util.Set;
import gov.nasa.jpf.symbc.numeric.PathCondition;
import gov.nasa.jpf.vm.MethodInfo;
import gov.nasa.jpf.vm.ThreadInfo;
import gov.nasa.jpf.vm.VM; | /*
* MIT License
*
* Copyright (c) 2017 The ISSTAC Authors
*
* 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 wcanalysis.heuristic.model;
/**
* @author Rody Kersten
* instruction counting cost model
*/
public final class MethodCallCountState extends State {
public final static class MethodCallCountStateBuilder extends StateBuilderAdapter {
public final static String COUNTED_METHODS = "symbolic.wc.statebuilder.countedmethods";
private long numCalls = 0;
Set<String> countedMethods;
public MethodCallCountStateBuilder() {
String[] countedMeth = VM.getVM().getConfig().getStringArray(COUNTED_METHODS, new String[0]); | // Path: src/main/wcanalysis/heuristic/util/Util.java
// public class Util {
//
// public static File createDirIfNotExist(File root, String subDir) {
// File sub = new File(root, subDir);
// if(!sub.exists())
// sub.mkdirs();
// return sub;
// }
//
// public static File createDirIfNotExist(String root) {
// File sub = new File(root);
// if(!sub.exists())
// sub.mkdirs();
// return sub;
// }
//
// public static File createDirIfNotExist(File dir) {
// if(!dir.exists())
// dir.mkdirs();
// return dir;
// }
//
// public static String normalizeJPFMethodName(MethodInfo methInfo) {
// int methBeginIdx = methInfo.getBaseName().lastIndexOf('.') + 1;
// String fullName = methInfo.getFullName();
// return fullName.substring(methBeginIdx, fullName.length());
// }
//
// public static Set<String> extractSimpleMethodNames(String[] jpfMethodSpecs) {
// //FIXME: This also means that we do not distinguish between overloaded methods
// String[] processedMethods = new String[jpfMethodSpecs.length];
// System.arraycopy(jpfMethodSpecs, 0, processedMethods, 0, jpfMethodSpecs.length);
// for(int i = 0; i < jpfMethodSpecs.length; i++) {
// String meth = jpfMethodSpecs[i];
// int sigBegin = meth.indexOf('(');
// if(sigBegin >= 0)
// processedMethods[i] = meth.substring(0, sigBegin);
// }
// return new HashSet<String>(Arrays.asList(processedMethods));
// }
// }
// Path: src/main/wcanalysis/heuristic/model/MethodCallCountState.java
import wcanalysis.heuristic.util.Util;
import java.util.Set;
import gov.nasa.jpf.symbc.numeric.PathCondition;
import gov.nasa.jpf.vm.MethodInfo;
import gov.nasa.jpf.vm.ThreadInfo;
import gov.nasa.jpf.vm.VM;
/*
* MIT License
*
* Copyright (c) 2017 The ISSTAC Authors
*
* 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 wcanalysis.heuristic.model;
/**
* @author Rody Kersten
* instruction counting cost model
*/
public final class MethodCallCountState extends State {
public final static class MethodCallCountStateBuilder extends StateBuilderAdapter {
public final static String COUNTED_METHODS = "symbolic.wc.statebuilder.countedmethods";
private long numCalls = 0;
Set<String> countedMethods;
public MethodCallCountStateBuilder() {
String[] countedMeth = VM.getVM().getConfig().getStringArray(COUNTED_METHODS, new String[0]); | countedMethods = Util.extractSimpleMethodNames(countedMeth); |
isstac/spf-wca | src/main/wcanalysis/fitting/FunctionFitter.java | // Path: src/main/wcanalysis/charting/DataSeries.java
// public class DataSeries {
// private final double[] xs;
// private final double[] ys;
// int idx = 0;
//
// private final String seriesName;
// private String r2;
// private String function;
//
// public DataSeries(String seriesName, int size) {
// this.seriesName = seriesName;
// this.xs = new double[size];
// this.ys = new double[size];
// }
//
//
// public String getSeriesName() {
// return seriesName;
// }
//
// public void add(double x, double y) {
// xs[idx] = x;
// ys[idx] = y;
// idx++;
// }
//
// public double[] getY() {
// return this.ys;
// }
//
// public double[] getX() {
// return this.xs;
// }
//
// public int size() {
// return this.xs.length;
// }
//
// public String getR2() {
// return r2;
// }
//
// public void setR2(String r2) {
// this.r2 = r2;
// }
//
// public String getFunction() {
// return function;
// }
//
// public void setFunction(String function) {
// this.function = function;
// }
// }
| import java.util.Iterator;
import java.util.List;
import java.util.logging.Logger;
import gov.nasa.jpf.util.JPFLogger;
import wcanalysis.charting.DataSeries;
import org.apache.commons.math3.exception.MathIllegalArgumentException;
import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap; | /*
* MIT License
*
* Copyright (c) 2017 The ISSTAC Authors
*
* 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 wcanalysis.fitting;
/**
* @author Kasper Luckow
*
*/
public class FunctionFitter {
public static final Logger logger = JPFLogger.getLogger(FunctionFitter.class.getName());
| // Path: src/main/wcanalysis/charting/DataSeries.java
// public class DataSeries {
// private final double[] xs;
// private final double[] ys;
// int idx = 0;
//
// private final String seriesName;
// private String r2;
// private String function;
//
// public DataSeries(String seriesName, int size) {
// this.seriesName = seriesName;
// this.xs = new double[size];
// this.ys = new double[size];
// }
//
//
// public String getSeriesName() {
// return seriesName;
// }
//
// public void add(double x, double y) {
// xs[idx] = x;
// ys[idx] = y;
// idx++;
// }
//
// public double[] getY() {
// return this.ys;
// }
//
// public double[] getX() {
// return this.xs;
// }
//
// public int size() {
// return this.xs.length;
// }
//
// public String getR2() {
// return r2;
// }
//
// public void setR2(String r2) {
// this.r2 = r2;
// }
//
// public String getFunction() {
// return function;
// }
//
// public void setFunction(String function) {
// this.function = function;
// }
// }
// Path: src/main/wcanalysis/fitting/FunctionFitter.java
import java.util.Iterator;
import java.util.List;
import java.util.logging.Logger;
import gov.nasa.jpf.util.JPFLogger;
import wcanalysis.charting.DataSeries;
import org.apache.commons.math3.exception.MathIllegalArgumentException;
import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
/*
* MIT License
*
* Copyright (c) 2017 The ISSTAC Authors
*
* 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 wcanalysis.fitting;
/**
* @author Kasper Luckow
*
*/
public class FunctionFitter {
public static final Logger logger = JPFLogger.getLogger(FunctionFitter.class.getName());
| public static Collection<DataSeries> computePredictionSeries(double[] xs, double[] ys, |
isstac/spf-wca | src/main/wcanalysis/heuristic/util/OmegaConverter.java | // Path: src/main/wcanalysis/util/SymbolicVariableCollector.java
// public class SymbolicVariableCollector extends ConstraintExpressionVisitor {
//
// public HashSet<String> setOfSymVar;
//
// public SymbolicVariableCollector(HashSet<String> set){
// setOfSymVar = set;
// }
//
// @Override
// public void preVisit(SymbolicInteger expr) {
// String name = cleanSymbol(expr.toString());
// setOfSymVar.add(name);
// }
//
// public void collectVariables(PathCondition pc){
// Constraint c = pc.header;
// while(c != null){
// c.accept(this);
// c = c.getTail();
// }
// }
//
// private static String cleanSymbol(String str) {
// return str.replaceAll("\\[(.*?)\\]", ""); // remove e.g. [-1000000]
// }
//
// public Set<String> getListOfVariables(){
// return setOfSymVar;
// }
//
// public int size(){
// return setOfSymVar.size();
// }
// }
| import java.util.HashSet;
import java.util.Iterator;
import gov.nasa.jpf.symbc.numeric.PathCondition;
import wcanalysis.util.SymbolicVariableCollector; | /*
* MIT License
*
* Copyright (c) 2017 The ISSTAC Authors
*
* 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 wcanalysis.heuristic.util;
/**
* @author Kasper Luckow
* Omega crashes (core dump, syntax errors,...) when the constraints string
* becomes "too" large (in terms of characters). Strange.
* Can we split up the constraints?
*/
public class OmegaConverter implements ConstraintsConverter {
@Override
public String convert(PathCondition pc) {
if(pc == null)
return "";
PathCondition convertPc = pc.make_copy(); //probably not necessary...
HashSet<String> vars = new HashSet<>();
//TODO: does the collector *only* collect integer vars? That's weird | // Path: src/main/wcanalysis/util/SymbolicVariableCollector.java
// public class SymbolicVariableCollector extends ConstraintExpressionVisitor {
//
// public HashSet<String> setOfSymVar;
//
// public SymbolicVariableCollector(HashSet<String> set){
// setOfSymVar = set;
// }
//
// @Override
// public void preVisit(SymbolicInteger expr) {
// String name = cleanSymbol(expr.toString());
// setOfSymVar.add(name);
// }
//
// public void collectVariables(PathCondition pc){
// Constraint c = pc.header;
// while(c != null){
// c.accept(this);
// c = c.getTail();
// }
// }
//
// private static String cleanSymbol(String str) {
// return str.replaceAll("\\[(.*?)\\]", ""); // remove e.g. [-1000000]
// }
//
// public Set<String> getListOfVariables(){
// return setOfSymVar;
// }
//
// public int size(){
// return setOfSymVar.size();
// }
// }
// Path: src/main/wcanalysis/heuristic/util/OmegaConverter.java
import java.util.HashSet;
import java.util.Iterator;
import gov.nasa.jpf.symbc.numeric.PathCondition;
import wcanalysis.util.SymbolicVariableCollector;
/*
* MIT License
*
* Copyright (c) 2017 The ISSTAC Authors
*
* 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 wcanalysis.heuristic.util;
/**
* @author Kasper Luckow
* Omega crashes (core dump, syntax errors,...) when the constraints string
* becomes "too" large (in terms of characters). Strange.
* Can we split up the constraints?
*/
public class OmegaConverter implements ConstraintsConverter {
@Override
public String convert(PathCondition pc) {
if(pc == null)
return "";
PathCondition convertPc = pc.make_copy(); //probably not necessary...
HashSet<String> vars = new HashSet<>();
//TODO: does the collector *only* collect integer vars? That's weird | SymbolicVariableCollector collector = new SymbolicVariableCollector(vars); |
isstac/spf-wca | src/main/wcanalysis/heuristic/model/OutputStreamState.java | // Path: src/main/wcanalysis/heuristic/util/Util.java
// public class Util {
//
// public static File createDirIfNotExist(File root, String subDir) {
// File sub = new File(root, subDir);
// if(!sub.exists())
// sub.mkdirs();
// return sub;
// }
//
// public static File createDirIfNotExist(String root) {
// File sub = new File(root);
// if(!sub.exists())
// sub.mkdirs();
// return sub;
// }
//
// public static File createDirIfNotExist(File dir) {
// if(!dir.exists())
// dir.mkdirs();
// return dir;
// }
//
// public static String normalizeJPFMethodName(MethodInfo methInfo) {
// int methBeginIdx = methInfo.getBaseName().lastIndexOf('.') + 1;
// String fullName = methInfo.getFullName();
// return fullName.substring(methBeginIdx, fullName.length());
// }
//
// public static Set<String> extractSimpleMethodNames(String[] jpfMethodSpecs) {
// //FIXME: This also means that we do not distinguish between overloaded methods
// String[] processedMethods = new String[jpfMethodSpecs.length];
// System.arraycopy(jpfMethodSpecs, 0, processedMethods, 0, jpfMethodSpecs.length);
// for(int i = 0; i < jpfMethodSpecs.length; i++) {
// String meth = jpfMethodSpecs[i];
// int sigBegin = meth.indexOf('(');
// if(sigBegin >= 0)
// processedMethods[i] = meth.substring(0, sigBegin);
// }
// return new HashSet<String>(Arrays.asList(processedMethods));
// }
// }
| import gov.nasa.jpf.vm.StackFrame;
import gov.nasa.jpf.vm.ThreadInfo;
import gov.nasa.jpf.vm.VM;
import wcanalysis.heuristic.util.Util;
import java.util.List;
import java.util.Set;
import gov.nasa.jpf.symbc.numeric.PathCondition;
import gov.nasa.jpf.vm.LocalVarInfo;
import gov.nasa.jpf.vm.MethodInfo; | /*
* MIT License
*
* Copyright (c) 2017 The ISSTAC Authors
*
* 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 wcanalysis.heuristic.model;
/**
* @author Rody Kersten
* output stream bytes written cost model
*/
public final class OutputStreamState extends State {
public final static class OutputStreamStateBuilder extends StateBuilderAdapter {
public final static String MEASURED_STREAMS = "symbolic.wc.statebuilder.measuredstreams";
private long bytesWritten = 0;
Set<String> measuredStreams;
public OutputStreamStateBuilder() {
String[] def = {"java.io.OutputStream"};
String[] meas = VM.getVM().getConfig().getStringArray(MEASURED_STREAMS, def); | // Path: src/main/wcanalysis/heuristic/util/Util.java
// public class Util {
//
// public static File createDirIfNotExist(File root, String subDir) {
// File sub = new File(root, subDir);
// if(!sub.exists())
// sub.mkdirs();
// return sub;
// }
//
// public static File createDirIfNotExist(String root) {
// File sub = new File(root);
// if(!sub.exists())
// sub.mkdirs();
// return sub;
// }
//
// public static File createDirIfNotExist(File dir) {
// if(!dir.exists())
// dir.mkdirs();
// return dir;
// }
//
// public static String normalizeJPFMethodName(MethodInfo methInfo) {
// int methBeginIdx = methInfo.getBaseName().lastIndexOf('.') + 1;
// String fullName = methInfo.getFullName();
// return fullName.substring(methBeginIdx, fullName.length());
// }
//
// public static Set<String> extractSimpleMethodNames(String[] jpfMethodSpecs) {
// //FIXME: This also means that we do not distinguish between overloaded methods
// String[] processedMethods = new String[jpfMethodSpecs.length];
// System.arraycopy(jpfMethodSpecs, 0, processedMethods, 0, jpfMethodSpecs.length);
// for(int i = 0; i < jpfMethodSpecs.length; i++) {
// String meth = jpfMethodSpecs[i];
// int sigBegin = meth.indexOf('(');
// if(sigBegin >= 0)
// processedMethods[i] = meth.substring(0, sigBegin);
// }
// return new HashSet<String>(Arrays.asList(processedMethods));
// }
// }
// Path: src/main/wcanalysis/heuristic/model/OutputStreamState.java
import gov.nasa.jpf.vm.StackFrame;
import gov.nasa.jpf.vm.ThreadInfo;
import gov.nasa.jpf.vm.VM;
import wcanalysis.heuristic.util.Util;
import java.util.List;
import java.util.Set;
import gov.nasa.jpf.symbc.numeric.PathCondition;
import gov.nasa.jpf.vm.LocalVarInfo;
import gov.nasa.jpf.vm.MethodInfo;
/*
* MIT License
*
* Copyright (c) 2017 The ISSTAC Authors
*
* 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 wcanalysis.heuristic.model;
/**
* @author Rody Kersten
* output stream bytes written cost model
*/
public final class OutputStreamState extends State {
public final static class OutputStreamStateBuilder extends StateBuilderAdapter {
public final static String MEASURED_STREAMS = "symbolic.wc.statebuilder.measuredstreams";
private long bytesWritten = 0;
Set<String> measuredStreams;
public OutputStreamStateBuilder() {
String[] def = {"java.io.OutputStream"};
String[] meas = VM.getVM().getConfig().getStringArray(MEASURED_STREAMS, def); | measuredStreams = Util.extractSimpleMethodNames(meas); |
garretyoder/Cluttr | app/src/main/java/org/polaric/cluttr/comparators/AlbumMediaCount.java | // Path: app/src/main/java/org/polaric/cluttr/data/Album.java
// public class Album extends RealmObject {
// @PrimaryKey private String path;
// private RealmList<MediaItem> photos = new RealmList<>();
// private int size;
// private String name;
// private String coverPath;
// private long lastModified;
// private boolean hidden=false;
//
// public Album() {
// }
//
// public Album(String path, int size, String name, String coverPath, long lastModified) {
// this.path = path;
// this.size=size;
// this.name=name;
// this.coverPath=coverPath;
// this.lastModified=lastModified;
// hidden = new File(path + "/", ".nomedia").exists();
// }
//
// public boolean isHidden() {
// return hidden;
// }
//
// public void setHidden(boolean hidden) {
// this.hidden = hidden;
// }
//
// public void clearMedia() {
// photos.clear();
// }
//
// public List<Integer> getFilteredIndex(String query) {
// List<Integer> filter = new ArrayList<>();
// for (int index=0; index<photos.size(); index++) {
// if (photos.get(index).getName().contains(query)) {
// filter.add(index);
// }
// }
// return filter;
// }
//
// public boolean needsReload() {
// Log.d(Util.LOG_TAG, "Checking if " + getName() + " has been changed");
// Long modified = new File(path).lastModified();
// if (photos.size() < 1 || modified>lastModified) {
// Log.d(Util.LOG_TAG, "Album " + getName() + " has been modified, reloading");
// return true;
// }
// return false;
// }
//
// public long getLastModified() {
// return lastModified;
// }
//
// public void setLastModified(long lastModified) {
// this.lastModified = lastModified;
// }
//
// public int countSelected() {
// int selected=0;
// for (MediaItem i : photos) {
// if (i.isSelected()) {
// selected++;
// }
// }
// return selected;
// }
//
// public List<MediaItem> getSelected() {
// ArrayList<MediaItem> selected = new ArrayList<>();
// for (MediaItem item : photos) {
// if (item.isSelected()) {
// selected.add(item);
// }
// }
// return selected;
// }
//
// public void clearMediaSelection() {
// for (MediaItem i : photos) {
// i.setSelected(false);
// }
// Log.d(Util.LOG_TAG, "Clearing media selection");
// }
//
// public RealmList<MediaItem> getMedia() {
// return photos;
// }
//
// public void addMediaItem(MediaItem item) {
// photos.add(item);
// }
//
// public String getPath() {
// return path;
// }
//
// public String getName() {
// return name;
// }
//
// public void remove(int index) {
// photos.remove(index);
// }
//
// public int getSize() {
// if (photos.size()>0) {
// return photos.size();
// }
// return size;
// }
//
// public void setCoverPath(String coverPath) {
// this.coverPath = coverPath;
// }
//
// public String getCoverPath() {
// return coverPath;
// }
//
// @Override
// public boolean equals(Object obj) {
// return path.equals(((Album) obj).path);
// }
// }
| import org.polaric.cluttr.data.Album; | package org.polaric.cluttr.comparators;
public class AlbumMediaCount extends AlbumComparator {
private boolean ascending = true;
public AlbumMediaCount(boolean ascending) {
this.ascending = ascending;
}
@Override | // Path: app/src/main/java/org/polaric/cluttr/data/Album.java
// public class Album extends RealmObject {
// @PrimaryKey private String path;
// private RealmList<MediaItem> photos = new RealmList<>();
// private int size;
// private String name;
// private String coverPath;
// private long lastModified;
// private boolean hidden=false;
//
// public Album() {
// }
//
// public Album(String path, int size, String name, String coverPath, long lastModified) {
// this.path = path;
// this.size=size;
// this.name=name;
// this.coverPath=coverPath;
// this.lastModified=lastModified;
// hidden = new File(path + "/", ".nomedia").exists();
// }
//
// public boolean isHidden() {
// return hidden;
// }
//
// public void setHidden(boolean hidden) {
// this.hidden = hidden;
// }
//
// public void clearMedia() {
// photos.clear();
// }
//
// public List<Integer> getFilteredIndex(String query) {
// List<Integer> filter = new ArrayList<>();
// for (int index=0; index<photos.size(); index++) {
// if (photos.get(index).getName().contains(query)) {
// filter.add(index);
// }
// }
// return filter;
// }
//
// public boolean needsReload() {
// Log.d(Util.LOG_TAG, "Checking if " + getName() + " has been changed");
// Long modified = new File(path).lastModified();
// if (photos.size() < 1 || modified>lastModified) {
// Log.d(Util.LOG_TAG, "Album " + getName() + " has been modified, reloading");
// return true;
// }
// return false;
// }
//
// public long getLastModified() {
// return lastModified;
// }
//
// public void setLastModified(long lastModified) {
// this.lastModified = lastModified;
// }
//
// public int countSelected() {
// int selected=0;
// for (MediaItem i : photos) {
// if (i.isSelected()) {
// selected++;
// }
// }
// return selected;
// }
//
// public List<MediaItem> getSelected() {
// ArrayList<MediaItem> selected = new ArrayList<>();
// for (MediaItem item : photos) {
// if (item.isSelected()) {
// selected.add(item);
// }
// }
// return selected;
// }
//
// public void clearMediaSelection() {
// for (MediaItem i : photos) {
// i.setSelected(false);
// }
// Log.d(Util.LOG_TAG, "Clearing media selection");
// }
//
// public RealmList<MediaItem> getMedia() {
// return photos;
// }
//
// public void addMediaItem(MediaItem item) {
// photos.add(item);
// }
//
// public String getPath() {
// return path;
// }
//
// public String getName() {
// return name;
// }
//
// public void remove(int index) {
// photos.remove(index);
// }
//
// public int getSize() {
// if (photos.size()>0) {
// return photos.size();
// }
// return size;
// }
//
// public void setCoverPath(String coverPath) {
// this.coverPath = coverPath;
// }
//
// public String getCoverPath() {
// return coverPath;
// }
//
// @Override
// public boolean equals(Object obj) {
// return path.equals(((Album) obj).path);
// }
// }
// Path: app/src/main/java/org/polaric/cluttr/comparators/AlbumMediaCount.java
import org.polaric.cluttr.data.Album;
package org.polaric.cluttr.comparators;
public class AlbumMediaCount extends AlbumComparator {
private boolean ascending = true;
public AlbumMediaCount(boolean ascending) {
this.ascending = ascending;
}
@Override | public int compare(Album album, Album t1) { |
garretyoder/Cluttr | app/src/main/java/org/polaric/cluttr/Util.java | // Path: app/src/main/java/org/polaric/cluttr/dialogs/ActionMessageDialog.java
// public class ActionMessageDialog extends Dialog {
// @BindView(R.id.action_dialog_toolbar) Toolbar toolbar;
// @BindView(R.id.action_dialog_message) TextView msg;
// @BindView(R.id.action_dialog_ok) Button ok;
// @BindView(R.id.action_dialog_cancel) Button cancel;
//
// private String buttonText=null, negativeText, titleText;
// private Spanned msgText;
//
// private OnPositiveListener listener;
//
// public ActionMessageDialog(Context context) {
// super(context);
// }
//
// @Override
// protected void onCreate(Bundle savedInstanceState) {
// super.onCreate(savedInstanceState);
// requestWindowFeature(Window.FEATURE_NO_TITLE);
// setContentView(R.layout.dialog_action_message);
// ButterKnife.bind(this);
//
// WindowManager.LayoutParams lp = new WindowManager.LayoutParams();
// Window window = getWindow();
// lp.copyFrom(window.getAttributes());
// lp.width = WindowManager.LayoutParams.MATCH_PARENT;
// lp.height = WindowManager.LayoutParams.WRAP_CONTENT;
// window.setAttributes(lp);
//
// toolbar.setNavigationIcon(R.drawable.ic_arrow_back_white_48px);
// toolbar.setNavigationOnClickListener(new View.OnClickListener() {
// @Override
// public void onClick(View view) {
// dismiss();
// }
// });
//
// toolbar.setTitle(titleText);
// msg.setText(msgText);
// if (buttonText==null) {
// ok.setVisibility(View.GONE);
// } else {
// ok.setText(buttonText);
// }
// if (negativeText!=null) {
// cancel.setText(negativeText);
// }
// }
//
// public void setMsgText(String text) {
// msgText= SpannedString.valueOf(text);
// }
//
// public void setMsgText(Spanned text) {
// msgText = text;
// }
//
// public void setTitleText(String text) {
// titleText=text;
// }
//
//
// public void setPositiveButtonMsg(String msg) {
// buttonText=msg;
// }
//
//
// public void setNegativeButtonMsg(String msg) {
// negativeText=msg;
// }
//
// @OnClick(R.id.action_dialog_cancel)
// public void close() {
// dismiss();
// }
//
// @OnClick(R.id.action_dialog_ok)
// public void click() {
// if (listener!=null) {
// listener.onPositive();
// dismiss();
// }
// }
//
// public void setOnPositiveListener(OnPositiveListener listener) {
// this.listener = listener;
// }
//
// public interface OnPositiveListener {
// void onPositive();
// }
// }
| import android.animation.Animator;
import android.annotation.TargetApi;
import android.app.Activity;
import android.content.ContentUris;
import android.content.Context;
import android.database.Cursor;
import android.graphics.PorterDuff;
import android.graphics.PorterDuffColorFilter;
import android.net.Uri;
import android.os.Build;
import android.os.Environment;
import android.provider.DocumentsContract;
import android.provider.MediaStore;
import android.support.v7.view.menu.ActionMenuItemView;
import android.support.v7.widget.ActionMenuView;
import android.support.v7.widget.Toolbar;
import android.text.Html;
import android.util.Log;
import android.view.View;
import android.view.ViewAnimationUtils;
import android.view.animation.AlphaAnimation;
import android.view.animation.Animation;
import android.widget.ImageButton;
import org.polaric.cluttr.dialogs.ActionMessageDialog;
import java.util.Arrays;
import java.util.Collections;
import java.util.List; | public static void colorizeToolbar(Toolbar toolbarView, int toolbarIconsColor) {
final PorterDuffColorFilter colorFilter = new PorterDuffColorFilter(toolbarIconsColor, PorterDuff.Mode.MULTIPLY);
for(int i = 0; i < toolbarView.getChildCount(); i++) {
final View v = toolbarView.getChildAt(i);
if(v instanceof ImageButton) {
((ImageButton)v).getDrawable().setColorFilter(colorFilter);
}
if(v instanceof ActionMenuView) {
for(int j = 0; j < ((ActionMenuView)v).getChildCount(); j++) {
final View innerView = ((ActionMenuView)v).getChildAt(j);
if(innerView instanceof ActionMenuItemView) {
int drawablesCount = ((ActionMenuItemView)innerView).getCompoundDrawables().length;
for(int k = 0; k < drawablesCount; k++) {
if(((ActionMenuItemView)innerView).getCompoundDrawables()[k] != null) {
final int finalK = k;
innerView.post(new Runnable() {
@Override
public void run() {
((ActionMenuItemView) innerView).getCompoundDrawables()[finalK].setColorFilter(colorFilter);
}
});
}
}
}
}
}
}
}
public static void showChangelogDialog(Context context) { | // Path: app/src/main/java/org/polaric/cluttr/dialogs/ActionMessageDialog.java
// public class ActionMessageDialog extends Dialog {
// @BindView(R.id.action_dialog_toolbar) Toolbar toolbar;
// @BindView(R.id.action_dialog_message) TextView msg;
// @BindView(R.id.action_dialog_ok) Button ok;
// @BindView(R.id.action_dialog_cancel) Button cancel;
//
// private String buttonText=null, negativeText, titleText;
// private Spanned msgText;
//
// private OnPositiveListener listener;
//
// public ActionMessageDialog(Context context) {
// super(context);
// }
//
// @Override
// protected void onCreate(Bundle savedInstanceState) {
// super.onCreate(savedInstanceState);
// requestWindowFeature(Window.FEATURE_NO_TITLE);
// setContentView(R.layout.dialog_action_message);
// ButterKnife.bind(this);
//
// WindowManager.LayoutParams lp = new WindowManager.LayoutParams();
// Window window = getWindow();
// lp.copyFrom(window.getAttributes());
// lp.width = WindowManager.LayoutParams.MATCH_PARENT;
// lp.height = WindowManager.LayoutParams.WRAP_CONTENT;
// window.setAttributes(lp);
//
// toolbar.setNavigationIcon(R.drawable.ic_arrow_back_white_48px);
// toolbar.setNavigationOnClickListener(new View.OnClickListener() {
// @Override
// public void onClick(View view) {
// dismiss();
// }
// });
//
// toolbar.setTitle(titleText);
// msg.setText(msgText);
// if (buttonText==null) {
// ok.setVisibility(View.GONE);
// } else {
// ok.setText(buttonText);
// }
// if (negativeText!=null) {
// cancel.setText(negativeText);
// }
// }
//
// public void setMsgText(String text) {
// msgText= SpannedString.valueOf(text);
// }
//
// public void setMsgText(Spanned text) {
// msgText = text;
// }
//
// public void setTitleText(String text) {
// titleText=text;
// }
//
//
// public void setPositiveButtonMsg(String msg) {
// buttonText=msg;
// }
//
//
// public void setNegativeButtonMsg(String msg) {
// negativeText=msg;
// }
//
// @OnClick(R.id.action_dialog_cancel)
// public void close() {
// dismiss();
// }
//
// @OnClick(R.id.action_dialog_ok)
// public void click() {
// if (listener!=null) {
// listener.onPositive();
// dismiss();
// }
// }
//
// public void setOnPositiveListener(OnPositiveListener listener) {
// this.listener = listener;
// }
//
// public interface OnPositiveListener {
// void onPositive();
// }
// }
// Path: app/src/main/java/org/polaric/cluttr/Util.java
import android.animation.Animator;
import android.annotation.TargetApi;
import android.app.Activity;
import android.content.ContentUris;
import android.content.Context;
import android.database.Cursor;
import android.graphics.PorterDuff;
import android.graphics.PorterDuffColorFilter;
import android.net.Uri;
import android.os.Build;
import android.os.Environment;
import android.provider.DocumentsContract;
import android.provider.MediaStore;
import android.support.v7.view.menu.ActionMenuItemView;
import android.support.v7.widget.ActionMenuView;
import android.support.v7.widget.Toolbar;
import android.text.Html;
import android.util.Log;
import android.view.View;
import android.view.ViewAnimationUtils;
import android.view.animation.AlphaAnimation;
import android.view.animation.Animation;
import android.widget.ImageButton;
import org.polaric.cluttr.dialogs.ActionMessageDialog;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
public static void colorizeToolbar(Toolbar toolbarView, int toolbarIconsColor) {
final PorterDuffColorFilter colorFilter = new PorterDuffColorFilter(toolbarIconsColor, PorterDuff.Mode.MULTIPLY);
for(int i = 0; i < toolbarView.getChildCount(); i++) {
final View v = toolbarView.getChildAt(i);
if(v instanceof ImageButton) {
((ImageButton)v).getDrawable().setColorFilter(colorFilter);
}
if(v instanceof ActionMenuView) {
for(int j = 0; j < ((ActionMenuView)v).getChildCount(); j++) {
final View innerView = ((ActionMenuView)v).getChildAt(j);
if(innerView instanceof ActionMenuItemView) {
int drawablesCount = ((ActionMenuItemView)innerView).getCompoundDrawables().length;
for(int k = 0; k < drawablesCount; k++) {
if(((ActionMenuItemView)innerView).getCompoundDrawables()[k] != null) {
final int finalK = k;
innerView.post(new Runnable() {
@Override
public void run() {
((ActionMenuItemView) innerView).getCompoundDrawables()[finalK].setColorFilter(colorFilter);
}
});
}
}
}
}
}
}
}
public static void showChangelogDialog(Context context) { | ActionMessageDialog d = new ActionMessageDialog(context); |
garretyoder/Cluttr | app/src/main/java/org/polaric/cluttr/comparators/AlbumAlphabetical.java | // Path: app/src/main/java/org/polaric/cluttr/data/Album.java
// public class Album extends RealmObject {
// @PrimaryKey private String path;
// private RealmList<MediaItem> photos = new RealmList<>();
// private int size;
// private String name;
// private String coverPath;
// private long lastModified;
// private boolean hidden=false;
//
// public Album() {
// }
//
// public Album(String path, int size, String name, String coverPath, long lastModified) {
// this.path = path;
// this.size=size;
// this.name=name;
// this.coverPath=coverPath;
// this.lastModified=lastModified;
// hidden = new File(path + "/", ".nomedia").exists();
// }
//
// public boolean isHidden() {
// return hidden;
// }
//
// public void setHidden(boolean hidden) {
// this.hidden = hidden;
// }
//
// public void clearMedia() {
// photos.clear();
// }
//
// public List<Integer> getFilteredIndex(String query) {
// List<Integer> filter = new ArrayList<>();
// for (int index=0; index<photos.size(); index++) {
// if (photos.get(index).getName().contains(query)) {
// filter.add(index);
// }
// }
// return filter;
// }
//
// public boolean needsReload() {
// Log.d(Util.LOG_TAG, "Checking if " + getName() + " has been changed");
// Long modified = new File(path).lastModified();
// if (photos.size() < 1 || modified>lastModified) {
// Log.d(Util.LOG_TAG, "Album " + getName() + " has been modified, reloading");
// return true;
// }
// return false;
// }
//
// public long getLastModified() {
// return lastModified;
// }
//
// public void setLastModified(long lastModified) {
// this.lastModified = lastModified;
// }
//
// public int countSelected() {
// int selected=0;
// for (MediaItem i : photos) {
// if (i.isSelected()) {
// selected++;
// }
// }
// return selected;
// }
//
// public List<MediaItem> getSelected() {
// ArrayList<MediaItem> selected = new ArrayList<>();
// for (MediaItem item : photos) {
// if (item.isSelected()) {
// selected.add(item);
// }
// }
// return selected;
// }
//
// public void clearMediaSelection() {
// for (MediaItem i : photos) {
// i.setSelected(false);
// }
// Log.d(Util.LOG_TAG, "Clearing media selection");
// }
//
// public RealmList<MediaItem> getMedia() {
// return photos;
// }
//
// public void addMediaItem(MediaItem item) {
// photos.add(item);
// }
//
// public String getPath() {
// return path;
// }
//
// public String getName() {
// return name;
// }
//
// public void remove(int index) {
// photos.remove(index);
// }
//
// public int getSize() {
// if (photos.size()>0) {
// return photos.size();
// }
// return size;
// }
//
// public void setCoverPath(String coverPath) {
// this.coverPath = coverPath;
// }
//
// public String getCoverPath() {
// return coverPath;
// }
//
// @Override
// public boolean equals(Object obj) {
// return path.equals(((Album) obj).path);
// }
// }
| import org.polaric.cluttr.data.Album; | package org.polaric.cluttr.comparators;
public class AlbumAlphabetical extends AlbumComparator {
private boolean ascending = true;
public AlbumAlphabetical(boolean ascending) {
this.ascending = ascending;
}
@Override | // Path: app/src/main/java/org/polaric/cluttr/data/Album.java
// public class Album extends RealmObject {
// @PrimaryKey private String path;
// private RealmList<MediaItem> photos = new RealmList<>();
// private int size;
// private String name;
// private String coverPath;
// private long lastModified;
// private boolean hidden=false;
//
// public Album() {
// }
//
// public Album(String path, int size, String name, String coverPath, long lastModified) {
// this.path = path;
// this.size=size;
// this.name=name;
// this.coverPath=coverPath;
// this.lastModified=lastModified;
// hidden = new File(path + "/", ".nomedia").exists();
// }
//
// public boolean isHidden() {
// return hidden;
// }
//
// public void setHidden(boolean hidden) {
// this.hidden = hidden;
// }
//
// public void clearMedia() {
// photos.clear();
// }
//
// public List<Integer> getFilteredIndex(String query) {
// List<Integer> filter = new ArrayList<>();
// for (int index=0; index<photos.size(); index++) {
// if (photos.get(index).getName().contains(query)) {
// filter.add(index);
// }
// }
// return filter;
// }
//
// public boolean needsReload() {
// Log.d(Util.LOG_TAG, "Checking if " + getName() + " has been changed");
// Long modified = new File(path).lastModified();
// if (photos.size() < 1 || modified>lastModified) {
// Log.d(Util.LOG_TAG, "Album " + getName() + " has been modified, reloading");
// return true;
// }
// return false;
// }
//
// public long getLastModified() {
// return lastModified;
// }
//
// public void setLastModified(long lastModified) {
// this.lastModified = lastModified;
// }
//
// public int countSelected() {
// int selected=0;
// for (MediaItem i : photos) {
// if (i.isSelected()) {
// selected++;
// }
// }
// return selected;
// }
//
// public List<MediaItem> getSelected() {
// ArrayList<MediaItem> selected = new ArrayList<>();
// for (MediaItem item : photos) {
// if (item.isSelected()) {
// selected.add(item);
// }
// }
// return selected;
// }
//
// public void clearMediaSelection() {
// for (MediaItem i : photos) {
// i.setSelected(false);
// }
// Log.d(Util.LOG_TAG, "Clearing media selection");
// }
//
// public RealmList<MediaItem> getMedia() {
// return photos;
// }
//
// public void addMediaItem(MediaItem item) {
// photos.add(item);
// }
//
// public String getPath() {
// return path;
// }
//
// public String getName() {
// return name;
// }
//
// public void remove(int index) {
// photos.remove(index);
// }
//
// public int getSize() {
// if (photos.size()>0) {
// return photos.size();
// }
// return size;
// }
//
// public void setCoverPath(String coverPath) {
// this.coverPath = coverPath;
// }
//
// public String getCoverPath() {
// return coverPath;
// }
//
// @Override
// public boolean equals(Object obj) {
// return path.equals(((Album) obj).path);
// }
// }
// Path: app/src/main/java/org/polaric/cluttr/comparators/AlbumAlphabetical.java
import org.polaric.cluttr.data.Album;
package org.polaric.cluttr.comparators;
public class AlbumAlphabetical extends AlbumComparator {
private boolean ascending = true;
public AlbumAlphabetical(boolean ascending) {
this.ascending = ascending;
}
@Override | public int compare(Album album, Album t1) { |
garretyoder/Cluttr | app/src/main/java/org/polaric/cluttr/Cluttr.java | // Path: app/src/main/java/org/polaric/cluttr/io/ExtSdHelper.java
// public class ExtSdHelper {
// public static final String PATH_KEY="extsdpath";
// private static File sd;
// public static final int SAF_REQUEST=93;
//
// private static String sdPath=null;
//
// public static void init() {
// sdPath = PreferenceManager.getDefaultSharedPreferences(Cluttr.getApplication()).getString(PATH_KEY, null);
// if (sdPath!=null) {
// sd = new File(FileUtil.getFullPathFromTreeUri(getSdUri()));
// }
// }
//
// public static void clear() {
// PreferenceManager.getDefaultSharedPreferences(Cluttr.getApplication()).edit().putString(PATH_KEY, null).apply();
// sdPath=null;
// sd=null;
// //TODO: CLEAR CACHE
// }
//
// public static boolean hasExtSd() {
// return sdPath!=null;
// }
//
// public static void setSdPath(String path) {
// sdPath=path;
// PreferenceManager.getDefaultSharedPreferences(Cluttr.getApplication()).edit().putString(PATH_KEY, path).apply();
// sd = new File(FileUtil.getFullPathFromTreeUri(getSdUri()));
// Log.d(Util.LOG_TAG, "SAF External SD Directory set to " + path);
// //TODO: CLEAR CACHE
// }
//
// public static String getSdPath() {
// return sdPath;
// }
//
// public static Uri getSdUri() {
// return Uri.parse(getSdPath());
// }
//
// public static File getRootFile() {
// return sd;
// }
// }
| import android.app.Application;
import android.content.Intent;
import android.content.SharedPreferences;
import android.support.v7.preference.PreferenceManager;
import android.util.Log;
import org.polaric.cluttr.io.ExtSdHelper;
import org.polaric.colorful.Colorful;
import io.realm.Realm;
import io.realm.RealmConfiguration; | package org.polaric.cluttr;
public class Cluttr extends Application {
private static Cluttr cluttr;
private SharedPreferences prefs;
private boolean newRelease=false;
private Thread.UncaughtExceptionHandler defaultUEH;
public Cluttr() {
defaultUEH = Thread.getDefaultUncaughtExceptionHandler();
Thread.setDefaultUncaughtExceptionHandler (new Thread.UncaughtExceptionHandler() {
@Override
public void uncaughtException (Thread thread, Throwable e) {
handleUncaughtException (thread, e);
}
});
}
@Override
public void onCreate() {
super.onCreate();
cluttr=this;
Colorful.defaults().translucent(true);
Colorful.init(this); | // Path: app/src/main/java/org/polaric/cluttr/io/ExtSdHelper.java
// public class ExtSdHelper {
// public static final String PATH_KEY="extsdpath";
// private static File sd;
// public static final int SAF_REQUEST=93;
//
// private static String sdPath=null;
//
// public static void init() {
// sdPath = PreferenceManager.getDefaultSharedPreferences(Cluttr.getApplication()).getString(PATH_KEY, null);
// if (sdPath!=null) {
// sd = new File(FileUtil.getFullPathFromTreeUri(getSdUri()));
// }
// }
//
// public static void clear() {
// PreferenceManager.getDefaultSharedPreferences(Cluttr.getApplication()).edit().putString(PATH_KEY, null).apply();
// sdPath=null;
// sd=null;
// //TODO: CLEAR CACHE
// }
//
// public static boolean hasExtSd() {
// return sdPath!=null;
// }
//
// public static void setSdPath(String path) {
// sdPath=path;
// PreferenceManager.getDefaultSharedPreferences(Cluttr.getApplication()).edit().putString(PATH_KEY, path).apply();
// sd = new File(FileUtil.getFullPathFromTreeUri(getSdUri()));
// Log.d(Util.LOG_TAG, "SAF External SD Directory set to " + path);
// //TODO: CLEAR CACHE
// }
//
// public static String getSdPath() {
// return sdPath;
// }
//
// public static Uri getSdUri() {
// return Uri.parse(getSdPath());
// }
//
// public static File getRootFile() {
// return sd;
// }
// }
// Path: app/src/main/java/org/polaric/cluttr/Cluttr.java
import android.app.Application;
import android.content.Intent;
import android.content.SharedPreferences;
import android.support.v7.preference.PreferenceManager;
import android.util.Log;
import org.polaric.cluttr.io.ExtSdHelper;
import org.polaric.colorful.Colorful;
import io.realm.Realm;
import io.realm.RealmConfiguration;
package org.polaric.cluttr;
public class Cluttr extends Application {
private static Cluttr cluttr;
private SharedPreferences prefs;
private boolean newRelease=false;
private Thread.UncaughtExceptionHandler defaultUEH;
public Cluttr() {
defaultUEH = Thread.getDefaultUncaughtExceptionHandler();
Thread.setDefaultUncaughtExceptionHandler (new Thread.UncaughtExceptionHandler() {
@Override
public void uncaughtException (Thread thread, Throwable e) {
handleUncaughtException (thread, e);
}
});
}
@Override
public void onCreate() {
super.onCreate();
cluttr=this;
Colorful.defaults().translucent(true);
Colorful.init(this); | ExtSdHelper.init(); |
garretyoder/Cluttr | app/src/main/java/org/polaric/cluttr/comparators/MediaAlphabetical.java | // Path: app/src/main/java/org/polaric/cluttr/data/Album.java
// public class Album extends RealmObject {
// @PrimaryKey private String path;
// private RealmList<MediaItem> photos = new RealmList<>();
// private int size;
// private String name;
// private String coverPath;
// private long lastModified;
// private boolean hidden=false;
//
// public Album() {
// }
//
// public Album(String path, int size, String name, String coverPath, long lastModified) {
// this.path = path;
// this.size=size;
// this.name=name;
// this.coverPath=coverPath;
// this.lastModified=lastModified;
// hidden = new File(path + "/", ".nomedia").exists();
// }
//
// public boolean isHidden() {
// return hidden;
// }
//
// public void setHidden(boolean hidden) {
// this.hidden = hidden;
// }
//
// public void clearMedia() {
// photos.clear();
// }
//
// public List<Integer> getFilteredIndex(String query) {
// List<Integer> filter = new ArrayList<>();
// for (int index=0; index<photos.size(); index++) {
// if (photos.get(index).getName().contains(query)) {
// filter.add(index);
// }
// }
// return filter;
// }
//
// public boolean needsReload() {
// Log.d(Util.LOG_TAG, "Checking if " + getName() + " has been changed");
// Long modified = new File(path).lastModified();
// if (photos.size() < 1 || modified>lastModified) {
// Log.d(Util.LOG_TAG, "Album " + getName() + " has been modified, reloading");
// return true;
// }
// return false;
// }
//
// public long getLastModified() {
// return lastModified;
// }
//
// public void setLastModified(long lastModified) {
// this.lastModified = lastModified;
// }
//
// public int countSelected() {
// int selected=0;
// for (MediaItem i : photos) {
// if (i.isSelected()) {
// selected++;
// }
// }
// return selected;
// }
//
// public List<MediaItem> getSelected() {
// ArrayList<MediaItem> selected = new ArrayList<>();
// for (MediaItem item : photos) {
// if (item.isSelected()) {
// selected.add(item);
// }
// }
// return selected;
// }
//
// public void clearMediaSelection() {
// for (MediaItem i : photos) {
// i.setSelected(false);
// }
// Log.d(Util.LOG_TAG, "Clearing media selection");
// }
//
// public RealmList<MediaItem> getMedia() {
// return photos;
// }
//
// public void addMediaItem(MediaItem item) {
// photos.add(item);
// }
//
// public String getPath() {
// return path;
// }
//
// public String getName() {
// return name;
// }
//
// public void remove(int index) {
// photos.remove(index);
// }
//
// public int getSize() {
// if (photos.size()>0) {
// return photos.size();
// }
// return size;
// }
//
// public void setCoverPath(String coverPath) {
// this.coverPath = coverPath;
// }
//
// public String getCoverPath() {
// return coverPath;
// }
//
// @Override
// public boolean equals(Object obj) {
// return path.equals(((Album) obj).path);
// }
// }
//
// Path: app/src/main/java/org/polaric/cluttr/data/MediaItem.java
// public class MediaItem extends RealmObject {
// @PrimaryKey private String path;
// private long date;
// private String mime;
// private boolean isSelected;
// private float aspectRatio=-1;
// private String name;
//
// public MediaItem() {
// }
//
// public MediaItem(String path, long date) {
// this.path = path;
// this.date = date;
// setMIME();
// name = getName();
// }
//
// public MediaItem(File file) {
// path=file.getAbsolutePath();
// date=file.lastModified();
// setMIME();
// name = getName();
// }
//
// public float getAspectRatio() {
// return aspectRatio;
// }
//
// public void setAspectRatio(float aspectRatio) {
// this.aspectRatio = aspectRatio;
// }
//
// public boolean isSelected() {
// return isSelected;
// }
//
// public void setSelected(boolean selected) {
// isSelected = selected;
// }
//
// public String getPath() {
// return path;
// }
//
// public String getName() {
// return new File(path).getName();
// }
//
// public String getFileExtension() {
// return path.substring(path.lastIndexOf(".")+1);
// }
//
// public Media.MediaTypes getMediaType() {
// if (mime.endsWith("gif")) {
// return Media.MediaTypes.GIF;
// } else if (mime.startsWith("image")) {
// return Media.MediaTypes.IMAGE;
// } else if (mime.startsWith("video")) {
// return Media.MediaTypes.VIDEO;
// }
// return Media.MediaTypes.UNKNOWN;
// }
//
// public String getMime() {
// return mime;
// }
//
// private void setMIME() {
// mime = MimeTypeMap.getSingleton().getMimeTypeFromExtension(getFileExtension().toLowerCase());
// if (mime == null) mime="unknown";
// }
//
// public long getDate() {
// return date;
// }
//
// @Override
// public boolean equals(Object obj) {
// return path.equals(((MediaItem) obj).path);
// }
// }
| import org.polaric.cluttr.data.Album;
import org.polaric.cluttr.data.MediaItem; | package org.polaric.cluttr.comparators;
public class MediaAlphabetical extends MediaComparator {
private boolean ascending = true;
public MediaAlphabetical(boolean ascending) {
this.ascending = ascending;
}
@Override | // Path: app/src/main/java/org/polaric/cluttr/data/Album.java
// public class Album extends RealmObject {
// @PrimaryKey private String path;
// private RealmList<MediaItem> photos = new RealmList<>();
// private int size;
// private String name;
// private String coverPath;
// private long lastModified;
// private boolean hidden=false;
//
// public Album() {
// }
//
// public Album(String path, int size, String name, String coverPath, long lastModified) {
// this.path = path;
// this.size=size;
// this.name=name;
// this.coverPath=coverPath;
// this.lastModified=lastModified;
// hidden = new File(path + "/", ".nomedia").exists();
// }
//
// public boolean isHidden() {
// return hidden;
// }
//
// public void setHidden(boolean hidden) {
// this.hidden = hidden;
// }
//
// public void clearMedia() {
// photos.clear();
// }
//
// public List<Integer> getFilteredIndex(String query) {
// List<Integer> filter = new ArrayList<>();
// for (int index=0; index<photos.size(); index++) {
// if (photos.get(index).getName().contains(query)) {
// filter.add(index);
// }
// }
// return filter;
// }
//
// public boolean needsReload() {
// Log.d(Util.LOG_TAG, "Checking if " + getName() + " has been changed");
// Long modified = new File(path).lastModified();
// if (photos.size() < 1 || modified>lastModified) {
// Log.d(Util.LOG_TAG, "Album " + getName() + " has been modified, reloading");
// return true;
// }
// return false;
// }
//
// public long getLastModified() {
// return lastModified;
// }
//
// public void setLastModified(long lastModified) {
// this.lastModified = lastModified;
// }
//
// public int countSelected() {
// int selected=0;
// for (MediaItem i : photos) {
// if (i.isSelected()) {
// selected++;
// }
// }
// return selected;
// }
//
// public List<MediaItem> getSelected() {
// ArrayList<MediaItem> selected = new ArrayList<>();
// for (MediaItem item : photos) {
// if (item.isSelected()) {
// selected.add(item);
// }
// }
// return selected;
// }
//
// public void clearMediaSelection() {
// for (MediaItem i : photos) {
// i.setSelected(false);
// }
// Log.d(Util.LOG_TAG, "Clearing media selection");
// }
//
// public RealmList<MediaItem> getMedia() {
// return photos;
// }
//
// public void addMediaItem(MediaItem item) {
// photos.add(item);
// }
//
// public String getPath() {
// return path;
// }
//
// public String getName() {
// return name;
// }
//
// public void remove(int index) {
// photos.remove(index);
// }
//
// public int getSize() {
// if (photos.size()>0) {
// return photos.size();
// }
// return size;
// }
//
// public void setCoverPath(String coverPath) {
// this.coverPath = coverPath;
// }
//
// public String getCoverPath() {
// return coverPath;
// }
//
// @Override
// public boolean equals(Object obj) {
// return path.equals(((Album) obj).path);
// }
// }
//
// Path: app/src/main/java/org/polaric/cluttr/data/MediaItem.java
// public class MediaItem extends RealmObject {
// @PrimaryKey private String path;
// private long date;
// private String mime;
// private boolean isSelected;
// private float aspectRatio=-1;
// private String name;
//
// public MediaItem() {
// }
//
// public MediaItem(String path, long date) {
// this.path = path;
// this.date = date;
// setMIME();
// name = getName();
// }
//
// public MediaItem(File file) {
// path=file.getAbsolutePath();
// date=file.lastModified();
// setMIME();
// name = getName();
// }
//
// public float getAspectRatio() {
// return aspectRatio;
// }
//
// public void setAspectRatio(float aspectRatio) {
// this.aspectRatio = aspectRatio;
// }
//
// public boolean isSelected() {
// return isSelected;
// }
//
// public void setSelected(boolean selected) {
// isSelected = selected;
// }
//
// public String getPath() {
// return path;
// }
//
// public String getName() {
// return new File(path).getName();
// }
//
// public String getFileExtension() {
// return path.substring(path.lastIndexOf(".")+1);
// }
//
// public Media.MediaTypes getMediaType() {
// if (mime.endsWith("gif")) {
// return Media.MediaTypes.GIF;
// } else if (mime.startsWith("image")) {
// return Media.MediaTypes.IMAGE;
// } else if (mime.startsWith("video")) {
// return Media.MediaTypes.VIDEO;
// }
// return Media.MediaTypes.UNKNOWN;
// }
//
// public String getMime() {
// return mime;
// }
//
// private void setMIME() {
// mime = MimeTypeMap.getSingleton().getMimeTypeFromExtension(getFileExtension().toLowerCase());
// if (mime == null) mime="unknown";
// }
//
// public long getDate() {
// return date;
// }
//
// @Override
// public boolean equals(Object obj) {
// return path.equals(((MediaItem) obj).path);
// }
// }
// Path: app/src/main/java/org/polaric/cluttr/comparators/MediaAlphabetical.java
import org.polaric.cluttr.data.Album;
import org.polaric.cluttr.data.MediaItem;
package org.polaric.cluttr.comparators;
public class MediaAlphabetical extends MediaComparator {
private boolean ascending = true;
public MediaAlphabetical(boolean ascending) {
this.ascending = ascending;
}
@Override | public int compare(MediaItem mediaItem, MediaItem t1) { |
garretyoder/Cluttr | app/src/main/java/org/polaric/cluttr/comparators/MediaDate.java | // Path: app/src/main/java/org/polaric/cluttr/data/MediaItem.java
// public class MediaItem extends RealmObject {
// @PrimaryKey private String path;
// private long date;
// private String mime;
// private boolean isSelected;
// private float aspectRatio=-1;
// private String name;
//
// public MediaItem() {
// }
//
// public MediaItem(String path, long date) {
// this.path = path;
// this.date = date;
// setMIME();
// name = getName();
// }
//
// public MediaItem(File file) {
// path=file.getAbsolutePath();
// date=file.lastModified();
// setMIME();
// name = getName();
// }
//
// public float getAspectRatio() {
// return aspectRatio;
// }
//
// public void setAspectRatio(float aspectRatio) {
// this.aspectRatio = aspectRatio;
// }
//
// public boolean isSelected() {
// return isSelected;
// }
//
// public void setSelected(boolean selected) {
// isSelected = selected;
// }
//
// public String getPath() {
// return path;
// }
//
// public String getName() {
// return new File(path).getName();
// }
//
// public String getFileExtension() {
// return path.substring(path.lastIndexOf(".")+1);
// }
//
// public Media.MediaTypes getMediaType() {
// if (mime.endsWith("gif")) {
// return Media.MediaTypes.GIF;
// } else if (mime.startsWith("image")) {
// return Media.MediaTypes.IMAGE;
// } else if (mime.startsWith("video")) {
// return Media.MediaTypes.VIDEO;
// }
// return Media.MediaTypes.UNKNOWN;
// }
//
// public String getMime() {
// return mime;
// }
//
// private void setMIME() {
// mime = MimeTypeMap.getSingleton().getMimeTypeFromExtension(getFileExtension().toLowerCase());
// if (mime == null) mime="unknown";
// }
//
// public long getDate() {
// return date;
// }
//
// @Override
// public boolean equals(Object obj) {
// return path.equals(((MediaItem) obj).path);
// }
// }
| import org.polaric.cluttr.data.MediaItem; | package org.polaric.cluttr.comparators;
public class MediaDate extends MediaComparator {
private boolean ascending = true;
public MediaDate(boolean ascending) {
this.ascending = ascending;
}
@Override | // Path: app/src/main/java/org/polaric/cluttr/data/MediaItem.java
// public class MediaItem extends RealmObject {
// @PrimaryKey private String path;
// private long date;
// private String mime;
// private boolean isSelected;
// private float aspectRatio=-1;
// private String name;
//
// public MediaItem() {
// }
//
// public MediaItem(String path, long date) {
// this.path = path;
// this.date = date;
// setMIME();
// name = getName();
// }
//
// public MediaItem(File file) {
// path=file.getAbsolutePath();
// date=file.lastModified();
// setMIME();
// name = getName();
// }
//
// public float getAspectRatio() {
// return aspectRatio;
// }
//
// public void setAspectRatio(float aspectRatio) {
// this.aspectRatio = aspectRatio;
// }
//
// public boolean isSelected() {
// return isSelected;
// }
//
// public void setSelected(boolean selected) {
// isSelected = selected;
// }
//
// public String getPath() {
// return path;
// }
//
// public String getName() {
// return new File(path).getName();
// }
//
// public String getFileExtension() {
// return path.substring(path.lastIndexOf(".")+1);
// }
//
// public Media.MediaTypes getMediaType() {
// if (mime.endsWith("gif")) {
// return Media.MediaTypes.GIF;
// } else if (mime.startsWith("image")) {
// return Media.MediaTypes.IMAGE;
// } else if (mime.startsWith("video")) {
// return Media.MediaTypes.VIDEO;
// }
// return Media.MediaTypes.UNKNOWN;
// }
//
// public String getMime() {
// return mime;
// }
//
// private void setMIME() {
// mime = MimeTypeMap.getSingleton().getMimeTypeFromExtension(getFileExtension().toLowerCase());
// if (mime == null) mime="unknown";
// }
//
// public long getDate() {
// return date;
// }
//
// @Override
// public boolean equals(Object obj) {
// return path.equals(((MediaItem) obj).path);
// }
// }
// Path: app/src/main/java/org/polaric/cluttr/comparators/MediaDate.java
import org.polaric.cluttr.data.MediaItem;
package org.polaric.cluttr.comparators;
public class MediaDate extends MediaComparator {
private boolean ascending = true;
public MediaDate(boolean ascending) {
this.ascending = ascending;
}
@Override | public int compare(MediaItem mediaItem, MediaItem t1) { |
knutwalker/rx-redis | examples/java/src/main/java/com/example/Person.java | // Path: language-bindings/java/src/main/java/rx/redis/japi/format/BytesFormat.java
// public interface BytesFormat<T> extends BytesReader<T>, BytesWriter<T> {
//
// default <U> BytesFormat<U> xmap(final Function<T, U> f, final Function<U, T> g) {
// return fromScala(this.asScala().xmap(func(f::apply), func(g::apply)));
// }
//
// default <U> BytesFormat<U> xflatMap(final Function<T, U> f, final Function<U, Iterable<T>> g) {
// final ByteBufFormat<U> xByteBufFormat = this.asScala().xflatMap(
// func(f::apply),
// func(x -> iterableAsScalaIterableConverter(g.apply(x)).asScala()));
// return fromScala(xByteBufFormat);
// }
//
// default <U> BytesPairFormat<T, U> and(final BytesFormat<U> f) {
// return BytesPairFormat.fromScala(this.asScala().and(f.asScala()));
// }
//
// // TODO: EitherFormat
// default <U> BytesFormat<Either<T, U>> or(final BytesFormat<U> f) {
// return fromScala(this.asScala().or(f.asScala()));
// }
//
// default ByteBufFormat<T> asScala() {
// return ByteBufFormat$.MODULE$.from(asScalaReader(), asScalaWriter());
// }
//
// static <A> BytesFormat<A> fromScala(final ByteBufFormat<A> delegate) {
// return new FromScalaFormat<>(delegate);
// }
//
// static <A> BytesFormat<A> fromReaderAndWriter(final BytesReader<A> reader, final BytesWriter<A> writer) {
// return new BytesFormat<A>() {
// @Override
// public A fromByteBuf(final ByteBuf bb) {
// return reader.fromByteBuf(bb);
// }
//
// @Override
// public ByteBuf toByteBuf(final ByteBuf bb, final A value) {
// return writer.toByteBuf(bb, value);
// }
// };
// }
//
// final class FromScalaFormat<T> implements BytesFormat<T> {
// private final ByteBufFormat<T> delegate;
//
// FromScalaFormat(final ByteBufFormat<T> delegate) {
// this.delegate = Objects.requireNonNull(delegate, "delegate must not be null");
// }
//
// @Override
// public T fromByteBuf(final ByteBuf bb) {
// return delegate.fromByteBuf(bb);
// }
//
// @Override
// public ByteBuf toByteBuf(final ByteBuf bb, final T value) {
// return delegate.toByteBuf(bb, value);
// }
//
// @Override
// public ByteBufFormat<T> asScala() {
// return delegate;
// }
//
// @Override
// public ByteBufReader<T> asScalaReader() {
// return delegate;
// }
//
// @Override
// public ByteBufWriter<T> asScalaWriter() {
// return delegate;
// }
// }
// }
//
// Path: language-bindings/java/src/main/java/rx/redis/japi/DefaultBytes.java
// @SuppressWarnings("UnusedDeclaration")
// public final class DefaultBytes {
//
// private DefaultBytes() {}
//
// public final static BytesFormat<String> STRING =
// BytesFormat.fromScala(ByteBufFormat$.MODULE$.formatString());
//
// public final static BytesFormat<String> FRAMELESS_STRING =
// BytesFormat.fromScala(ByteBufFormat$.MODULE$.formatFramelessString());
//
// public final static BytesFormat<byte[]> BYTES =
// BytesFormat.fromScala(ByteBufFormat$.MODULE$.formatByteArray());
//
// public final static BytesFormat<byte[]> FRAMELESS_BYTES =
// BytesFormat.fromScala(ByteBufFormat$.MODULE$.formatFramelessByteArray());
//
// public final static BytesFormat<Integer> INT =
// BytesFormat.fromScala(ByteBufFormat$.MODULE$.formatInt()
// .xmap(func(x -> (Integer) x), func(x -> x)));
//
// public final static BytesFormat<Long> LONG =
// BytesFormat.fromScala(ByteBufFormat$.MODULE$.formatLong()
// .xmap(func(x -> (Long) x), func(x -> x)));
// }
| import rx.redis.japi.format.BytesFormat;
import rx.redis.japi.DefaultBytes; | public String getName() {
return name;
}
public int getAge() {
return age;
}
@Override
public boolean equals(final Object o) {
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}
final Person person = (Person) o;
return age == person.age && name.equals(person.name);
}
@Override
public int hashCode() {
return 31 * name.hashCode() + age;
}
@Override
public String toString() {
return String.format("Person(%s, %d)", name, age);
}
| // Path: language-bindings/java/src/main/java/rx/redis/japi/format/BytesFormat.java
// public interface BytesFormat<T> extends BytesReader<T>, BytesWriter<T> {
//
// default <U> BytesFormat<U> xmap(final Function<T, U> f, final Function<U, T> g) {
// return fromScala(this.asScala().xmap(func(f::apply), func(g::apply)));
// }
//
// default <U> BytesFormat<U> xflatMap(final Function<T, U> f, final Function<U, Iterable<T>> g) {
// final ByteBufFormat<U> xByteBufFormat = this.asScala().xflatMap(
// func(f::apply),
// func(x -> iterableAsScalaIterableConverter(g.apply(x)).asScala()));
// return fromScala(xByteBufFormat);
// }
//
// default <U> BytesPairFormat<T, U> and(final BytesFormat<U> f) {
// return BytesPairFormat.fromScala(this.asScala().and(f.asScala()));
// }
//
// // TODO: EitherFormat
// default <U> BytesFormat<Either<T, U>> or(final BytesFormat<U> f) {
// return fromScala(this.asScala().or(f.asScala()));
// }
//
// default ByteBufFormat<T> asScala() {
// return ByteBufFormat$.MODULE$.from(asScalaReader(), asScalaWriter());
// }
//
// static <A> BytesFormat<A> fromScala(final ByteBufFormat<A> delegate) {
// return new FromScalaFormat<>(delegate);
// }
//
// static <A> BytesFormat<A> fromReaderAndWriter(final BytesReader<A> reader, final BytesWriter<A> writer) {
// return new BytesFormat<A>() {
// @Override
// public A fromByteBuf(final ByteBuf bb) {
// return reader.fromByteBuf(bb);
// }
//
// @Override
// public ByteBuf toByteBuf(final ByteBuf bb, final A value) {
// return writer.toByteBuf(bb, value);
// }
// };
// }
//
// final class FromScalaFormat<T> implements BytesFormat<T> {
// private final ByteBufFormat<T> delegate;
//
// FromScalaFormat(final ByteBufFormat<T> delegate) {
// this.delegate = Objects.requireNonNull(delegate, "delegate must not be null");
// }
//
// @Override
// public T fromByteBuf(final ByteBuf bb) {
// return delegate.fromByteBuf(bb);
// }
//
// @Override
// public ByteBuf toByteBuf(final ByteBuf bb, final T value) {
// return delegate.toByteBuf(bb, value);
// }
//
// @Override
// public ByteBufFormat<T> asScala() {
// return delegate;
// }
//
// @Override
// public ByteBufReader<T> asScalaReader() {
// return delegate;
// }
//
// @Override
// public ByteBufWriter<T> asScalaWriter() {
// return delegate;
// }
// }
// }
//
// Path: language-bindings/java/src/main/java/rx/redis/japi/DefaultBytes.java
// @SuppressWarnings("UnusedDeclaration")
// public final class DefaultBytes {
//
// private DefaultBytes() {}
//
// public final static BytesFormat<String> STRING =
// BytesFormat.fromScala(ByteBufFormat$.MODULE$.formatString());
//
// public final static BytesFormat<String> FRAMELESS_STRING =
// BytesFormat.fromScala(ByteBufFormat$.MODULE$.formatFramelessString());
//
// public final static BytesFormat<byte[]> BYTES =
// BytesFormat.fromScala(ByteBufFormat$.MODULE$.formatByteArray());
//
// public final static BytesFormat<byte[]> FRAMELESS_BYTES =
// BytesFormat.fromScala(ByteBufFormat$.MODULE$.formatFramelessByteArray());
//
// public final static BytesFormat<Integer> INT =
// BytesFormat.fromScala(ByteBufFormat$.MODULE$.formatInt()
// .xmap(func(x -> (Integer) x), func(x -> x)));
//
// public final static BytesFormat<Long> LONG =
// BytesFormat.fromScala(ByteBufFormat$.MODULE$.formatLong()
// .xmap(func(x -> (Long) x), func(x -> x)));
// }
// Path: examples/java/src/main/java/com/example/Person.java
import rx.redis.japi.format.BytesFormat;
import rx.redis.japi.DefaultBytes;
public String getName() {
return name;
}
public int getAge() {
return age;
}
@Override
public boolean equals(final Object o) {
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}
final Person person = (Person) o;
return age == person.age && name.equals(person.name);
}
@Override
public int hashCode() {
return 31 * name.hashCode() + age;
}
@Override
public String toString() {
return String.format("Person(%s, %d)", name, age);
}
| public static final BytesFormat<Person> BYTES_FORMAT = |
knutwalker/rx-redis | examples/java/src/main/java/com/example/Person.java | // Path: language-bindings/java/src/main/java/rx/redis/japi/format/BytesFormat.java
// public interface BytesFormat<T> extends BytesReader<T>, BytesWriter<T> {
//
// default <U> BytesFormat<U> xmap(final Function<T, U> f, final Function<U, T> g) {
// return fromScala(this.asScala().xmap(func(f::apply), func(g::apply)));
// }
//
// default <U> BytesFormat<U> xflatMap(final Function<T, U> f, final Function<U, Iterable<T>> g) {
// final ByteBufFormat<U> xByteBufFormat = this.asScala().xflatMap(
// func(f::apply),
// func(x -> iterableAsScalaIterableConverter(g.apply(x)).asScala()));
// return fromScala(xByteBufFormat);
// }
//
// default <U> BytesPairFormat<T, U> and(final BytesFormat<U> f) {
// return BytesPairFormat.fromScala(this.asScala().and(f.asScala()));
// }
//
// // TODO: EitherFormat
// default <U> BytesFormat<Either<T, U>> or(final BytesFormat<U> f) {
// return fromScala(this.asScala().or(f.asScala()));
// }
//
// default ByteBufFormat<T> asScala() {
// return ByteBufFormat$.MODULE$.from(asScalaReader(), asScalaWriter());
// }
//
// static <A> BytesFormat<A> fromScala(final ByteBufFormat<A> delegate) {
// return new FromScalaFormat<>(delegate);
// }
//
// static <A> BytesFormat<A> fromReaderAndWriter(final BytesReader<A> reader, final BytesWriter<A> writer) {
// return new BytesFormat<A>() {
// @Override
// public A fromByteBuf(final ByteBuf bb) {
// return reader.fromByteBuf(bb);
// }
//
// @Override
// public ByteBuf toByteBuf(final ByteBuf bb, final A value) {
// return writer.toByteBuf(bb, value);
// }
// };
// }
//
// final class FromScalaFormat<T> implements BytesFormat<T> {
// private final ByteBufFormat<T> delegate;
//
// FromScalaFormat(final ByteBufFormat<T> delegate) {
// this.delegate = Objects.requireNonNull(delegate, "delegate must not be null");
// }
//
// @Override
// public T fromByteBuf(final ByteBuf bb) {
// return delegate.fromByteBuf(bb);
// }
//
// @Override
// public ByteBuf toByteBuf(final ByteBuf bb, final T value) {
// return delegate.toByteBuf(bb, value);
// }
//
// @Override
// public ByteBufFormat<T> asScala() {
// return delegate;
// }
//
// @Override
// public ByteBufReader<T> asScalaReader() {
// return delegate;
// }
//
// @Override
// public ByteBufWriter<T> asScalaWriter() {
// return delegate;
// }
// }
// }
//
// Path: language-bindings/java/src/main/java/rx/redis/japi/DefaultBytes.java
// @SuppressWarnings("UnusedDeclaration")
// public final class DefaultBytes {
//
// private DefaultBytes() {}
//
// public final static BytesFormat<String> STRING =
// BytesFormat.fromScala(ByteBufFormat$.MODULE$.formatString());
//
// public final static BytesFormat<String> FRAMELESS_STRING =
// BytesFormat.fromScala(ByteBufFormat$.MODULE$.formatFramelessString());
//
// public final static BytesFormat<byte[]> BYTES =
// BytesFormat.fromScala(ByteBufFormat$.MODULE$.formatByteArray());
//
// public final static BytesFormat<byte[]> FRAMELESS_BYTES =
// BytesFormat.fromScala(ByteBufFormat$.MODULE$.formatFramelessByteArray());
//
// public final static BytesFormat<Integer> INT =
// BytesFormat.fromScala(ByteBufFormat$.MODULE$.formatInt()
// .xmap(func(x -> (Integer) x), func(x -> x)));
//
// public final static BytesFormat<Long> LONG =
// BytesFormat.fromScala(ByteBufFormat$.MODULE$.formatLong()
// .xmap(func(x -> (Long) x), func(x -> x)));
// }
| import rx.redis.japi.format.BytesFormat;
import rx.redis.japi.DefaultBytes; | return name;
}
public int getAge() {
return age;
}
@Override
public boolean equals(final Object o) {
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}
final Person person = (Person) o;
return age == person.age && name.equals(person.name);
}
@Override
public int hashCode() {
return 31 * name.hashCode() + age;
}
@Override
public String toString() {
return String.format("Person(%s, %d)", name, age);
}
public static final BytesFormat<Person> BYTES_FORMAT = | // Path: language-bindings/java/src/main/java/rx/redis/japi/format/BytesFormat.java
// public interface BytesFormat<T> extends BytesReader<T>, BytesWriter<T> {
//
// default <U> BytesFormat<U> xmap(final Function<T, U> f, final Function<U, T> g) {
// return fromScala(this.asScala().xmap(func(f::apply), func(g::apply)));
// }
//
// default <U> BytesFormat<U> xflatMap(final Function<T, U> f, final Function<U, Iterable<T>> g) {
// final ByteBufFormat<U> xByteBufFormat = this.asScala().xflatMap(
// func(f::apply),
// func(x -> iterableAsScalaIterableConverter(g.apply(x)).asScala()));
// return fromScala(xByteBufFormat);
// }
//
// default <U> BytesPairFormat<T, U> and(final BytesFormat<U> f) {
// return BytesPairFormat.fromScala(this.asScala().and(f.asScala()));
// }
//
// // TODO: EitherFormat
// default <U> BytesFormat<Either<T, U>> or(final BytesFormat<U> f) {
// return fromScala(this.asScala().or(f.asScala()));
// }
//
// default ByteBufFormat<T> asScala() {
// return ByteBufFormat$.MODULE$.from(asScalaReader(), asScalaWriter());
// }
//
// static <A> BytesFormat<A> fromScala(final ByteBufFormat<A> delegate) {
// return new FromScalaFormat<>(delegate);
// }
//
// static <A> BytesFormat<A> fromReaderAndWriter(final BytesReader<A> reader, final BytesWriter<A> writer) {
// return new BytesFormat<A>() {
// @Override
// public A fromByteBuf(final ByteBuf bb) {
// return reader.fromByteBuf(bb);
// }
//
// @Override
// public ByteBuf toByteBuf(final ByteBuf bb, final A value) {
// return writer.toByteBuf(bb, value);
// }
// };
// }
//
// final class FromScalaFormat<T> implements BytesFormat<T> {
// private final ByteBufFormat<T> delegate;
//
// FromScalaFormat(final ByteBufFormat<T> delegate) {
// this.delegate = Objects.requireNonNull(delegate, "delegate must not be null");
// }
//
// @Override
// public T fromByteBuf(final ByteBuf bb) {
// return delegate.fromByteBuf(bb);
// }
//
// @Override
// public ByteBuf toByteBuf(final ByteBuf bb, final T value) {
// return delegate.toByteBuf(bb, value);
// }
//
// @Override
// public ByteBufFormat<T> asScala() {
// return delegate;
// }
//
// @Override
// public ByteBufReader<T> asScalaReader() {
// return delegate;
// }
//
// @Override
// public ByteBufWriter<T> asScalaWriter() {
// return delegate;
// }
// }
// }
//
// Path: language-bindings/java/src/main/java/rx/redis/japi/DefaultBytes.java
// @SuppressWarnings("UnusedDeclaration")
// public final class DefaultBytes {
//
// private DefaultBytes() {}
//
// public final static BytesFormat<String> STRING =
// BytesFormat.fromScala(ByteBufFormat$.MODULE$.formatString());
//
// public final static BytesFormat<String> FRAMELESS_STRING =
// BytesFormat.fromScala(ByteBufFormat$.MODULE$.formatFramelessString());
//
// public final static BytesFormat<byte[]> BYTES =
// BytesFormat.fromScala(ByteBufFormat$.MODULE$.formatByteArray());
//
// public final static BytesFormat<byte[]> FRAMELESS_BYTES =
// BytesFormat.fromScala(ByteBufFormat$.MODULE$.formatFramelessByteArray());
//
// public final static BytesFormat<Integer> INT =
// BytesFormat.fromScala(ByteBufFormat$.MODULE$.formatInt()
// .xmap(func(x -> (Integer) x), func(x -> x)));
//
// public final static BytesFormat<Long> LONG =
// BytesFormat.fromScala(ByteBufFormat$.MODULE$.formatLong()
// .xmap(func(x -> (Long) x), func(x -> x)));
// }
// Path: examples/java/src/main/java/com/example/Person.java
import rx.redis.japi.format.BytesFormat;
import rx.redis.japi.DefaultBytes;
return name;
}
public int getAge() {
return age;
}
@Override
public boolean equals(final Object o) {
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}
final Person person = (Person) o;
return age == person.age && name.equals(person.name);
}
@Override
public int hashCode() {
return 31 * name.hashCode() + age;
}
@Override
public String toString() {
return String.format("Person(%s, %d)", name, age);
}
public static final BytesFormat<Person> BYTES_FORMAT = | DefaultBytes.INT.and(DefaultBytes.STRING) |
knutwalker/rx-redis | language-bindings/java/src/main/java/rx/redis/japi/DefaultBytes.java | // Path: language-bindings/java/src/main/java/rx/redis/japi/format/BytesFormat.java
// public interface BytesFormat<T> extends BytesReader<T>, BytesWriter<T> {
//
// default <U> BytesFormat<U> xmap(final Function<T, U> f, final Function<U, T> g) {
// return fromScala(this.asScala().xmap(func(f::apply), func(g::apply)));
// }
//
// default <U> BytesFormat<U> xflatMap(final Function<T, U> f, final Function<U, Iterable<T>> g) {
// final ByteBufFormat<U> xByteBufFormat = this.asScala().xflatMap(
// func(f::apply),
// func(x -> iterableAsScalaIterableConverter(g.apply(x)).asScala()));
// return fromScala(xByteBufFormat);
// }
//
// default <U> BytesPairFormat<T, U> and(final BytesFormat<U> f) {
// return BytesPairFormat.fromScala(this.asScala().and(f.asScala()));
// }
//
// // TODO: EitherFormat
// default <U> BytesFormat<Either<T, U>> or(final BytesFormat<U> f) {
// return fromScala(this.asScala().or(f.asScala()));
// }
//
// default ByteBufFormat<T> asScala() {
// return ByteBufFormat$.MODULE$.from(asScalaReader(), asScalaWriter());
// }
//
// static <A> BytesFormat<A> fromScala(final ByteBufFormat<A> delegate) {
// return new FromScalaFormat<>(delegate);
// }
//
// static <A> BytesFormat<A> fromReaderAndWriter(final BytesReader<A> reader, final BytesWriter<A> writer) {
// return new BytesFormat<A>() {
// @Override
// public A fromByteBuf(final ByteBuf bb) {
// return reader.fromByteBuf(bb);
// }
//
// @Override
// public ByteBuf toByteBuf(final ByteBuf bb, final A value) {
// return writer.toByteBuf(bb, value);
// }
// };
// }
//
// final class FromScalaFormat<T> implements BytesFormat<T> {
// private final ByteBufFormat<T> delegate;
//
// FromScalaFormat(final ByteBufFormat<T> delegate) {
// this.delegate = Objects.requireNonNull(delegate, "delegate must not be null");
// }
//
// @Override
// public T fromByteBuf(final ByteBuf bb) {
// return delegate.fromByteBuf(bb);
// }
//
// @Override
// public ByteBuf toByteBuf(final ByteBuf bb, final T value) {
// return delegate.toByteBuf(bb, value);
// }
//
// @Override
// public ByteBufFormat<T> asScala() {
// return delegate;
// }
//
// @Override
// public ByteBufReader<T> asScalaReader() {
// return delegate;
// }
//
// @Override
// public ByteBufWriter<T> asScalaWriter() {
// return delegate;
// }
// }
// }
| import rx.redis.japi.format.BytesFormat;
import rx.redis.serialization.ByteBufFormat$;
import static scala.compat.java8.JFunction.func; | /*
* Copyright 2014 – 2015 Paul Horn
*
* 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 rx.redis.japi;
@SuppressWarnings("UnusedDeclaration")
public final class DefaultBytes {
private DefaultBytes() {}
| // Path: language-bindings/java/src/main/java/rx/redis/japi/format/BytesFormat.java
// public interface BytesFormat<T> extends BytesReader<T>, BytesWriter<T> {
//
// default <U> BytesFormat<U> xmap(final Function<T, U> f, final Function<U, T> g) {
// return fromScala(this.asScala().xmap(func(f::apply), func(g::apply)));
// }
//
// default <U> BytesFormat<U> xflatMap(final Function<T, U> f, final Function<U, Iterable<T>> g) {
// final ByteBufFormat<U> xByteBufFormat = this.asScala().xflatMap(
// func(f::apply),
// func(x -> iterableAsScalaIterableConverter(g.apply(x)).asScala()));
// return fromScala(xByteBufFormat);
// }
//
// default <U> BytesPairFormat<T, U> and(final BytesFormat<U> f) {
// return BytesPairFormat.fromScala(this.asScala().and(f.asScala()));
// }
//
// // TODO: EitherFormat
// default <U> BytesFormat<Either<T, U>> or(final BytesFormat<U> f) {
// return fromScala(this.asScala().or(f.asScala()));
// }
//
// default ByteBufFormat<T> asScala() {
// return ByteBufFormat$.MODULE$.from(asScalaReader(), asScalaWriter());
// }
//
// static <A> BytesFormat<A> fromScala(final ByteBufFormat<A> delegate) {
// return new FromScalaFormat<>(delegate);
// }
//
// static <A> BytesFormat<A> fromReaderAndWriter(final BytesReader<A> reader, final BytesWriter<A> writer) {
// return new BytesFormat<A>() {
// @Override
// public A fromByteBuf(final ByteBuf bb) {
// return reader.fromByteBuf(bb);
// }
//
// @Override
// public ByteBuf toByteBuf(final ByteBuf bb, final A value) {
// return writer.toByteBuf(bb, value);
// }
// };
// }
//
// final class FromScalaFormat<T> implements BytesFormat<T> {
// private final ByteBufFormat<T> delegate;
//
// FromScalaFormat(final ByteBufFormat<T> delegate) {
// this.delegate = Objects.requireNonNull(delegate, "delegate must not be null");
// }
//
// @Override
// public T fromByteBuf(final ByteBuf bb) {
// return delegate.fromByteBuf(bb);
// }
//
// @Override
// public ByteBuf toByteBuf(final ByteBuf bb, final T value) {
// return delegate.toByteBuf(bb, value);
// }
//
// @Override
// public ByteBufFormat<T> asScala() {
// return delegate;
// }
//
// @Override
// public ByteBufReader<T> asScalaReader() {
// return delegate;
// }
//
// @Override
// public ByteBufWriter<T> asScalaWriter() {
// return delegate;
// }
// }
// }
// Path: language-bindings/java/src/main/java/rx/redis/japi/DefaultBytes.java
import rx.redis.japi.format.BytesFormat;
import rx.redis.serialization.ByteBufFormat$;
import static scala.compat.java8.JFunction.func;
/*
* Copyright 2014 – 2015 Paul Horn
*
* 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 rx.redis.japi;
@SuppressWarnings("UnusedDeclaration")
public final class DefaultBytes {
private DefaultBytes() {}
| public final static BytesFormat<String> STRING = |
winks/cinder | src/org/art_core/dev/cinder/input/IInputHandler.java | // Path: src/org/art_core/dev/cinder/model/IItem.java
// public interface IItem extends IAdaptable {
// String getName();
//
// String getLocation();
//
// String getMessage();
//
// int getLine();
//
// int getOffset();
//
// int getTimestamp();
//
// ItemStatus getStatus();
//
// ItemSource getSource();
//
// HashMap<String, String> getDetails();
//
// ItemType getType();
//
// void setStatus(ItemStatus status);
//
// IItem[] NONE = new IItem[] {};
// }
| import java.util.Collection;
import org.art_core.dev.cinder.model.IItem; | package org.art_core.dev.cinder.input;
public interface IInputHandler {
boolean isReadable();
void readFromLocalFile(String sFile);
void readFromUri(String sFile);
void readFromWorkspaceFile(String sFile);
| // Path: src/org/art_core/dev/cinder/model/IItem.java
// public interface IItem extends IAdaptable {
// String getName();
//
// String getLocation();
//
// String getMessage();
//
// int getLine();
//
// int getOffset();
//
// int getTimestamp();
//
// ItemStatus getStatus();
//
// ItemSource getSource();
//
// HashMap<String, String> getDetails();
//
// ItemType getType();
//
// void setStatus(ItemStatus status);
//
// IItem[] NONE = new IItem[] {};
// }
// Path: src/org/art_core/dev/cinder/input/IInputHandler.java
import java.util.Collection;
import org.art_core.dev.cinder.model.IItem;
package org.art_core.dev.cinder.input;
public interface IInputHandler {
boolean isReadable();
void readFromLocalFile(String sFile);
void readFromUri(String sFile);
void readFromWorkspaceFile(String sFile);
| Collection<IItem> getItems(); |
winks/cinder | assets/builder/CreatePropertyKeyResolution.java | // Path: src/org/art_core/dev/cinder/CinderLog.java
// public final class CinderLog {
// public final int OK = IStatus.OK;
// public final int INFO = IStatus.INFO;
// public final int WARNING = IStatus.WARNING;
// public final int ERROR = IStatus.ERROR;
//
// private CinderLog() {}
//
// /**
// * Logs debug messages if the config allows it.
// * @param message
// */
// public static void logDebug(final String message) {
// IPreferenceStore ipsPref = CinderPlugin.getDefault().getPreferenceStore();
// String sPrefKey = CinderPrefPage.P_BOOLEAN + "_show_debug";
// boolean bDebug = ipsPref.getBoolean(sPrefKey);
// if (bDebug) {
// logInfo(message);
// }
// }
//
// /**
// * Logs a non-critical exception as information.
// * @param message
// * @param exception
// */
// public static void logErrorInfo(final String message, final Throwable exception) {
// IPreferenceStore ipsPref = CinderPlugin.getDefault().getPreferenceStore();
// String sPrefKey = CinderPrefPage.P_BOOLEAN + "_show_debug";
// boolean bDebug = ipsPref.getBoolean(sPrefKey);
// if (bDebug) {
// log (IStatus.INFO, IStatus.OK, message, exception);
// }
// }
//
// /**
// * Log the specified information.
// *
// * @param message, a human-readable message, localized to the
// * current locale.
// */
// public static void logInfo(final String message) {
// log(IStatus.INFO, IStatus.OK, message, null);
// }
//
// /**
// * Log the specified error.
// *
// * @param exception, a low-level exception.
// */
// public static void logError(final Throwable exception) {
// logError("Unexpected Exception", exception);
// }
//
// /**
// * Log the specified error.
// *
// * @param message, a human-readable message, localized to the
// * current locale.
// * @param exception, a low-level exception, or <code>null</code>
// * if not applicable.
// */
// public static void logError(final String message, final Throwable exception) {
// log(IStatus.ERROR, IStatus.OK, message, exception);
// }
//
// /**
// * Log the specified information.
// *
// * @param severity, the severity; one of the following:
// * <code>IStatus.OK</code>,
// * <code>IStatus.ERROR</code>,
// * <code>IStatus.INFO</code>, or
// * <code>IStatus.WARNING</code>.
// * @param pluginId. the unique identifier of the relevant
// * plug-in.
// * @param code, the plug-in-specific status code, or
// * <code>OK</code>.
// * @param message, a human-readable message, localized to the
// * current locale.
// * @param exception, a low-level exception, or <code>null</code>
// * if not applicable.
// */
// public static void log(final int severity, final int code, final String message,
// final Throwable exception) {
// log(createStatus(severity, code, message, exception));
// }
//
// /**
// * Create a status object representing the specified information.
// *
// * @param severity, the severity; one of the following:
// * <code>IStatus.OK</code>,
// * <code>IStatus.ERROR</code>,
// * <code>IStatus.INFO</code>, or
// * <code>IStatus.WARNING</code>.
// * @param pluginId, the unique identifier of the relevant
// * plug-in.
// * @param code, the plug-in-specific status code, or
// * <code>OK</code>.
// * @param message, a human-readable message, localized to the
// * current locale.
// * @param exception, a low-level exception, or <code>null</code>
// * if not applicable.
// * @return, the status object (not <code>null</code>).
// */
// public static IStatus createStatus(final int severity, final int code, final String message,
// final Throwable exception) {
// return new Status(severity, CinderPlugin.PLUGIN_ID, code,
// message, exception);
// }
//
// /**
// * Log the given status.
// *
// * @param status, the status to log.
// */
// public static void log(final IStatus status) {
// CinderPlugin.getDefault().getLog().log(status);
// }
// }
| import java.io.ByteArrayInputStream;
import org.eclipse.core.resources.IFile;
import org.eclipse.core.resources.IMarker;
import org.eclipse.core.runtime.CoreException;
import org.eclipse.core.runtime.Path;
import org.eclipse.jface.text.BadLocationException;
import org.eclipse.jface.text.IDocument;
import org.eclipse.swt.graphics.Image;
import org.eclipse.ui.IEditorPart;
import org.eclipse.ui.IMarkerResolution2;
import org.eclipse.ui.IWorkbenchPage;
import org.eclipse.ui.PartInitException;
import org.eclipse.ui.PlatformUI;
import org.eclipse.ui.ide.IDE;
import org.eclipse.ui.part.FileEditorInput;
import org.eclipse.ui.texteditor.ITextEditor;
import org.art_core.dev.cinder.CinderLog; | package org.art_core.dev.cinder.builder;
/**
* An instance of CreatePropertyKeyResolution is returned for missing property
* key violations. If the user selects this resolution, the run() method is
* executed, opening or activating the properties editor and appending a new
* property key/value pair.
*/
public class CreatePropertyKeyResolution
implements IMarkerResolution2
{
public String getDescription() {
return "Append a new property key/value pair" + " to the plugin.properties file";
}
public Image getImage() {
return null;
}
public String getLabel() {
return "Create a new property key";
}
public void run(final IMarker marker) {
//Get the corresponding plugin.properties.
final IFile file =
marker.getResource().getParent().getFile(new Path("plugin.properties"));
if (!file.exists()) {
final ByteArrayInputStream stream = new ByteArrayInputStream(new byte[] {});
try {
file.create(stream, false, null);
}
catch (CoreException e) { | // Path: src/org/art_core/dev/cinder/CinderLog.java
// public final class CinderLog {
// public final int OK = IStatus.OK;
// public final int INFO = IStatus.INFO;
// public final int WARNING = IStatus.WARNING;
// public final int ERROR = IStatus.ERROR;
//
// private CinderLog() {}
//
// /**
// * Logs debug messages if the config allows it.
// * @param message
// */
// public static void logDebug(final String message) {
// IPreferenceStore ipsPref = CinderPlugin.getDefault().getPreferenceStore();
// String sPrefKey = CinderPrefPage.P_BOOLEAN + "_show_debug";
// boolean bDebug = ipsPref.getBoolean(sPrefKey);
// if (bDebug) {
// logInfo(message);
// }
// }
//
// /**
// * Logs a non-critical exception as information.
// * @param message
// * @param exception
// */
// public static void logErrorInfo(final String message, final Throwable exception) {
// IPreferenceStore ipsPref = CinderPlugin.getDefault().getPreferenceStore();
// String sPrefKey = CinderPrefPage.P_BOOLEAN + "_show_debug";
// boolean bDebug = ipsPref.getBoolean(sPrefKey);
// if (bDebug) {
// log (IStatus.INFO, IStatus.OK, message, exception);
// }
// }
//
// /**
// * Log the specified information.
// *
// * @param message, a human-readable message, localized to the
// * current locale.
// */
// public static void logInfo(final String message) {
// log(IStatus.INFO, IStatus.OK, message, null);
// }
//
// /**
// * Log the specified error.
// *
// * @param exception, a low-level exception.
// */
// public static void logError(final Throwable exception) {
// logError("Unexpected Exception", exception);
// }
//
// /**
// * Log the specified error.
// *
// * @param message, a human-readable message, localized to the
// * current locale.
// * @param exception, a low-level exception, or <code>null</code>
// * if not applicable.
// */
// public static void logError(final String message, final Throwable exception) {
// log(IStatus.ERROR, IStatus.OK, message, exception);
// }
//
// /**
// * Log the specified information.
// *
// * @param severity, the severity; one of the following:
// * <code>IStatus.OK</code>,
// * <code>IStatus.ERROR</code>,
// * <code>IStatus.INFO</code>, or
// * <code>IStatus.WARNING</code>.
// * @param pluginId. the unique identifier of the relevant
// * plug-in.
// * @param code, the plug-in-specific status code, or
// * <code>OK</code>.
// * @param message, a human-readable message, localized to the
// * current locale.
// * @param exception, a low-level exception, or <code>null</code>
// * if not applicable.
// */
// public static void log(final int severity, final int code, final String message,
// final Throwable exception) {
// log(createStatus(severity, code, message, exception));
// }
//
// /**
// * Create a status object representing the specified information.
// *
// * @param severity, the severity; one of the following:
// * <code>IStatus.OK</code>,
// * <code>IStatus.ERROR</code>,
// * <code>IStatus.INFO</code>, or
// * <code>IStatus.WARNING</code>.
// * @param pluginId, the unique identifier of the relevant
// * plug-in.
// * @param code, the plug-in-specific status code, or
// * <code>OK</code>.
// * @param message, a human-readable message, localized to the
// * current locale.
// * @param exception, a low-level exception, or <code>null</code>
// * if not applicable.
// * @return, the status object (not <code>null</code>).
// */
// public static IStatus createStatus(final int severity, final int code, final String message,
// final Throwable exception) {
// return new Status(severity, CinderPlugin.PLUGIN_ID, code,
// message, exception);
// }
//
// /**
// * Log the given status.
// *
// * @param status, the status to log.
// */
// public static void log(final IStatus status) {
// CinderPlugin.getDefault().getLog().log(status);
// }
// }
// Path: assets/builder/CreatePropertyKeyResolution.java
import java.io.ByteArrayInputStream;
import org.eclipse.core.resources.IFile;
import org.eclipse.core.resources.IMarker;
import org.eclipse.core.runtime.CoreException;
import org.eclipse.core.runtime.Path;
import org.eclipse.jface.text.BadLocationException;
import org.eclipse.jface.text.IDocument;
import org.eclipse.swt.graphics.Image;
import org.eclipse.ui.IEditorPart;
import org.eclipse.ui.IMarkerResolution2;
import org.eclipse.ui.IWorkbenchPage;
import org.eclipse.ui.PartInitException;
import org.eclipse.ui.PlatformUI;
import org.eclipse.ui.ide.IDE;
import org.eclipse.ui.part.FileEditorInput;
import org.eclipse.ui.texteditor.ITextEditor;
import org.art_core.dev.cinder.CinderLog;
package org.art_core.dev.cinder.builder;
/**
* An instance of CreatePropertyKeyResolution is returned for missing property
* key violations. If the user selects this resolution, the run() method is
* executed, opening or activating the properties editor and appending a new
* property key/value pair.
*/
public class CreatePropertyKeyResolution
implements IMarkerResolution2
{
public String getDescription() {
return "Append a new property key/value pair" + " to the plugin.properties file";
}
public Image getImage() {
return null;
}
public String getLabel() {
return "Create a new property key";
}
public void run(final IMarker marker) {
//Get the corresponding plugin.properties.
final IFile file =
marker.getResource().getParent().getFile(new Path("plugin.properties"));
if (!file.exists()) {
final ByteArrayInputStream stream = new ByteArrayInputStream(new byte[] {});
try {
file.create(stream, false, null);
}
catch (CoreException e) { | CinderLog.logError(e); |
winks/cinder | src/org/art_core/dev/cinder/controller/CheckFilesTask.java | // Path: src/org/art_core/dev/cinder/CinderLog.java
// public final class CinderLog {
// public final int OK = IStatus.OK;
// public final int INFO = IStatus.INFO;
// public final int WARNING = IStatus.WARNING;
// public final int ERROR = IStatus.ERROR;
//
// private CinderLog() {}
//
// /**
// * Logs debug messages if the config allows it.
// * @param message
// */
// public static void logDebug(final String message) {
// IPreferenceStore ipsPref = CinderPlugin.getDefault().getPreferenceStore();
// String sPrefKey = CinderPrefPage.P_BOOLEAN + "_show_debug";
// boolean bDebug = ipsPref.getBoolean(sPrefKey);
// if (bDebug) {
// logInfo(message);
// }
// }
//
// /**
// * Logs a non-critical exception as information.
// * @param message
// * @param exception
// */
// public static void logErrorInfo(final String message, final Throwable exception) {
// IPreferenceStore ipsPref = CinderPlugin.getDefault().getPreferenceStore();
// String sPrefKey = CinderPrefPage.P_BOOLEAN + "_show_debug";
// boolean bDebug = ipsPref.getBoolean(sPrefKey);
// if (bDebug) {
// log (IStatus.INFO, IStatus.OK, message, exception);
// }
// }
//
// /**
// * Log the specified information.
// *
// * @param message, a human-readable message, localized to the
// * current locale.
// */
// public static void logInfo(final String message) {
// log(IStatus.INFO, IStatus.OK, message, null);
// }
//
// /**
// * Log the specified error.
// *
// * @param exception, a low-level exception.
// */
// public static void logError(final Throwable exception) {
// logError("Unexpected Exception", exception);
// }
//
// /**
// * Log the specified error.
// *
// * @param message, a human-readable message, localized to the
// * current locale.
// * @param exception, a low-level exception, or <code>null</code>
// * if not applicable.
// */
// public static void logError(final String message, final Throwable exception) {
// log(IStatus.ERROR, IStatus.OK, message, exception);
// }
//
// /**
// * Log the specified information.
// *
// * @param severity, the severity; one of the following:
// * <code>IStatus.OK</code>,
// * <code>IStatus.ERROR</code>,
// * <code>IStatus.INFO</code>, or
// * <code>IStatus.WARNING</code>.
// * @param pluginId. the unique identifier of the relevant
// * plug-in.
// * @param code, the plug-in-specific status code, or
// * <code>OK</code>.
// * @param message, a human-readable message, localized to the
// * current locale.
// * @param exception, a low-level exception, or <code>null</code>
// * if not applicable.
// */
// public static void log(final int severity, final int code, final String message,
// final Throwable exception) {
// log(createStatus(severity, code, message, exception));
// }
//
// /**
// * Create a status object representing the specified information.
// *
// * @param severity, the severity; one of the following:
// * <code>IStatus.OK</code>,
// * <code>IStatus.ERROR</code>,
// * <code>IStatus.INFO</code>, or
// * <code>IStatus.WARNING</code>.
// * @param pluginId, the unique identifier of the relevant
// * plug-in.
// * @param code, the plug-in-specific status code, or
// * <code>OK</code>.
// * @param message, a human-readable message, localized to the
// * current locale.
// * @param exception, a low-level exception, or <code>null</code>
// * if not applicable.
// * @return, the status object (not <code>null</code>).
// */
// public static IStatus createStatus(final int severity, final int code, final String message,
// final Throwable exception) {
// return new Status(severity, CinderPlugin.PLUGIN_ID, code,
// message, exception);
// }
//
// /**
// * Log the given status.
// *
// * @param status, the status to log.
// */
// public static void log(final IStatus status) {
// CinderPlugin.getDefault().getLog().log(status);
// }
// }
| import java.util.ResourceBundle;
import java.util.TimerTask;
import org.art_core.dev.cinder.CinderLog;
import org.eclipse.swt.widgets.Display; | package org.art_core.dev.cinder.controller;
public class CheckFilesTask extends TimerTask {
private MainController parent;
private String sFilename;
private int iFileLocation;
public CheckFilesTask(MainController mc, String sFile, int iFileLocation) {
this.parent = mc;
this.sFilename = sFile;
this.iFileLocation = iFileLocation;
}
@Override
public void run() { | // Path: src/org/art_core/dev/cinder/CinderLog.java
// public final class CinderLog {
// public final int OK = IStatus.OK;
// public final int INFO = IStatus.INFO;
// public final int WARNING = IStatus.WARNING;
// public final int ERROR = IStatus.ERROR;
//
// private CinderLog() {}
//
// /**
// * Logs debug messages if the config allows it.
// * @param message
// */
// public static void logDebug(final String message) {
// IPreferenceStore ipsPref = CinderPlugin.getDefault().getPreferenceStore();
// String sPrefKey = CinderPrefPage.P_BOOLEAN + "_show_debug";
// boolean bDebug = ipsPref.getBoolean(sPrefKey);
// if (bDebug) {
// logInfo(message);
// }
// }
//
// /**
// * Logs a non-critical exception as information.
// * @param message
// * @param exception
// */
// public static void logErrorInfo(final String message, final Throwable exception) {
// IPreferenceStore ipsPref = CinderPlugin.getDefault().getPreferenceStore();
// String sPrefKey = CinderPrefPage.P_BOOLEAN + "_show_debug";
// boolean bDebug = ipsPref.getBoolean(sPrefKey);
// if (bDebug) {
// log (IStatus.INFO, IStatus.OK, message, exception);
// }
// }
//
// /**
// * Log the specified information.
// *
// * @param message, a human-readable message, localized to the
// * current locale.
// */
// public static void logInfo(final String message) {
// log(IStatus.INFO, IStatus.OK, message, null);
// }
//
// /**
// * Log the specified error.
// *
// * @param exception, a low-level exception.
// */
// public static void logError(final Throwable exception) {
// logError("Unexpected Exception", exception);
// }
//
// /**
// * Log the specified error.
// *
// * @param message, a human-readable message, localized to the
// * current locale.
// * @param exception, a low-level exception, or <code>null</code>
// * if not applicable.
// */
// public static void logError(final String message, final Throwable exception) {
// log(IStatus.ERROR, IStatus.OK, message, exception);
// }
//
// /**
// * Log the specified information.
// *
// * @param severity, the severity; one of the following:
// * <code>IStatus.OK</code>,
// * <code>IStatus.ERROR</code>,
// * <code>IStatus.INFO</code>, or
// * <code>IStatus.WARNING</code>.
// * @param pluginId. the unique identifier of the relevant
// * plug-in.
// * @param code, the plug-in-specific status code, or
// * <code>OK</code>.
// * @param message, a human-readable message, localized to the
// * current locale.
// * @param exception, a low-level exception, or <code>null</code>
// * if not applicable.
// */
// public static void log(final int severity, final int code, final String message,
// final Throwable exception) {
// log(createStatus(severity, code, message, exception));
// }
//
// /**
// * Create a status object representing the specified information.
// *
// * @param severity, the severity; one of the following:
// * <code>IStatus.OK</code>,
// * <code>IStatus.ERROR</code>,
// * <code>IStatus.INFO</code>, or
// * <code>IStatus.WARNING</code>.
// * @param pluginId, the unique identifier of the relevant
// * plug-in.
// * @param code, the plug-in-specific status code, or
// * <code>OK</code>.
// * @param message, a human-readable message, localized to the
// * current locale.
// * @param exception, a low-level exception, or <code>null</code>
// * if not applicable.
// * @return, the status object (not <code>null</code>).
// */
// public static IStatus createStatus(final int severity, final int code, final String message,
// final Throwable exception) {
// return new Status(severity, CinderPlugin.PLUGIN_ID, code,
// message, exception);
// }
//
// /**
// * Log the given status.
// *
// * @param status, the status to log.
// */
// public static void log(final IStatus status) {
// CinderPlugin.getDefault().getLog().log(status);
// }
// }
// Path: src/org/art_core/dev/cinder/controller/CheckFilesTask.java
import java.util.ResourceBundle;
import java.util.TimerTask;
import org.art_core.dev.cinder.CinderLog;
import org.eclipse.swt.widgets.Display;
package org.art_core.dev.cinder.controller;
public class CheckFilesTask extends TimerTask {
private MainController parent;
private String sFilename;
private int iFileLocation;
public CheckFilesTask(MainController mc, String sFile, int iFileLocation) {
this.parent = mc;
this.sFilename = sFile;
this.iFileLocation = iFileLocation;
}
@Override
public void run() { | CinderLog.logDebug("running CheckFilesTask on " + sFilename); |
winks/cinder | src/org/art_core/dev/cinder/prefs/CinderPrefInit.java | // Path: src/org/art_core/dev/cinder/CinderPlugin.java
// public class CinderPlugin extends AbstractUIPlugin {
//
// // The plug-in ID
// public static final String PLUGIN_ID = "org.art_core.dev.cinder";
//
// // The shared instance
// private static CinderPlugin plugin;
//
// /*
// * (non-Javadoc)
// * @see org.eclipse.ui.plugin.AbstractUIPlugin#start(org.osgi.framework.BundleContext)
// */
// public void start(BundleContext context) throws Exception {
// super.start(context);
// plugin = this;
// }
//
// /*
// * (non-Javadoc)
// * @see org.eclipse.ui.plugin.AbstractUIPlugin#stop(org.osgi.framework.BundleContext)
// */
// public void stop(BundleContext context) throws Exception {
// plugin = null;
// super.stop(context);
// }
//
// /**
// * Returns the shared instance
// *
// * @return the shared instance
// */
// public static CinderPlugin getDefault() {
// return plugin;
// }
//
// /**
// * Returns an image descriptor for the image file at the given
// * plug-in relative path
// *
// * @param path the path
// * @return the image descriptor
// */
// public static ImageDescriptor getImageDescriptor(final String path) {
// return imageDescriptorFromPlugin(PLUGIN_ID, path);
// }
// }
| import org.art_core.dev.cinder.CinderPlugin;
import org.eclipse.core.runtime.preferences.AbstractPreferenceInitializer;
import org.eclipse.jface.preference.IPreferenceStore; | package org.art_core.dev.cinder.prefs;
/**
* Class used to initialize default preference values.
*/
public class CinderPrefInit extends AbstractPreferenceInitializer {
/*
* (non-Javadoc)
*
* @seeorg.eclipse.core.runtime.preferences.AbstractPreferenceInitializer#
* initializeDefaultPreferences()
*/
public void initializeDefaultPreferences() { | // Path: src/org/art_core/dev/cinder/CinderPlugin.java
// public class CinderPlugin extends AbstractUIPlugin {
//
// // The plug-in ID
// public static final String PLUGIN_ID = "org.art_core.dev.cinder";
//
// // The shared instance
// private static CinderPlugin plugin;
//
// /*
// * (non-Javadoc)
// * @see org.eclipse.ui.plugin.AbstractUIPlugin#start(org.osgi.framework.BundleContext)
// */
// public void start(BundleContext context) throws Exception {
// super.start(context);
// plugin = this;
// }
//
// /*
// * (non-Javadoc)
// * @see org.eclipse.ui.plugin.AbstractUIPlugin#stop(org.osgi.framework.BundleContext)
// */
// public void stop(BundleContext context) throws Exception {
// plugin = null;
// super.stop(context);
// }
//
// /**
// * Returns the shared instance
// *
// * @return the shared instance
// */
// public static CinderPlugin getDefault() {
// return plugin;
// }
//
// /**
// * Returns an image descriptor for the image file at the given
// * plug-in relative path
// *
// * @param path the path
// * @return the image descriptor
// */
// public static ImageDescriptor getImageDescriptor(final String path) {
// return imageDescriptorFromPlugin(PLUGIN_ID, path);
// }
// }
// Path: src/org/art_core/dev/cinder/prefs/CinderPrefInit.java
import org.art_core.dev.cinder.CinderPlugin;
import org.eclipse.core.runtime.preferences.AbstractPreferenceInitializer;
import org.eclipse.jface.preference.IPreferenceStore;
package org.art_core.dev.cinder.prefs;
/**
* Class used to initialize default preference values.
*/
public class CinderPrefInit extends AbstractPreferenceInitializer {
/*
* (non-Javadoc)
*
* @seeorg.eclipse.core.runtime.preferences.AbstractPreferenceInitializer#
* initializeDefaultPreferences()
*/
public void initializeDefaultPreferences() { | IPreferenceStore store = CinderPlugin.getDefault().getPreferenceStore(); |
winks/cinder | src/org/art_core/dev/cinder/views/JFSorter.java | // Path: src/org/art_core/dev/cinder/model/IItem.java
// public interface IItem extends IAdaptable {
// String getName();
//
// String getLocation();
//
// String getMessage();
//
// int getLine();
//
// int getOffset();
//
// int getTimestamp();
//
// ItemStatus getStatus();
//
// ItemSource getSource();
//
// HashMap<String, String> getDetails();
//
// ItemType getType();
//
// void setStatus(ItemStatus status);
//
// IItem[] NONE = new IItem[] {};
// }
| import org.art_core.dev.cinder.model.IItem;
import org.eclipse.jface.viewers.Viewer;
import org.eclipse.jface.viewers.ViewerSorter; | package org.art_core.dev.cinder.views;
/**
* A custom sorter for a content provider.
*/
public class JFSorter extends ViewerSorter {
private int propertyIndex;
private int direction;
//private static int ASC = 0;
private static int DESC = 1;
/**
* Constructor.
*/
public JFSorter() {
this.propertyIndex = 0;
direction = DESC;
}
/**
* Set column to be sorted.
* @param col
*/
public void setColumn(int col) {
if (col == this.propertyIndex) {
direction = 1 - direction;
} else {
this.propertyIndex = col;
direction = DESC;
}
}
/**
* Compare to determine sort order.
*/
public int compare(Viewer viewer, Object o1, Object o2) { | // Path: src/org/art_core/dev/cinder/model/IItem.java
// public interface IItem extends IAdaptable {
// String getName();
//
// String getLocation();
//
// String getMessage();
//
// int getLine();
//
// int getOffset();
//
// int getTimestamp();
//
// ItemStatus getStatus();
//
// ItemSource getSource();
//
// HashMap<String, String> getDetails();
//
// ItemType getType();
//
// void setStatus(ItemStatus status);
//
// IItem[] NONE = new IItem[] {};
// }
// Path: src/org/art_core/dev/cinder/views/JFSorter.java
import org.art_core.dev.cinder.model.IItem;
import org.eclipse.jface.viewers.Viewer;
import org.eclipse.jface.viewers.ViewerSorter;
package org.art_core.dev.cinder.views;
/**
* A custom sorter for a content provider.
*/
public class JFSorter extends ViewerSorter {
private int propertyIndex;
private int direction;
//private static int ASC = 0;
private static int DESC = 1;
/**
* Constructor.
*/
public JFSorter() {
this.propertyIndex = 0;
direction = DESC;
}
/**
* Set column to be sorted.
* @param col
*/
public void setColumn(int col) {
if (col == this.propertyIndex) {
direction = 1 - direction;
} else {
this.propertyIndex = col;
direction = DESC;
}
}
/**
* Compare to determine sort order.
*/
public int compare(Viewer viewer, Object o1, Object o2) { | IItem item1 = (IItem) o1; |
winks/cinder | src/org/art_core/dev/cinder/prefs/CinderPrefPage.java | // Path: src/org/art_core/dev/cinder/CinderPlugin.java
// public class CinderPlugin extends AbstractUIPlugin {
//
// // The plug-in ID
// public static final String PLUGIN_ID = "org.art_core.dev.cinder";
//
// // The shared instance
// private static CinderPlugin plugin;
//
// /*
// * (non-Javadoc)
// * @see org.eclipse.ui.plugin.AbstractUIPlugin#start(org.osgi.framework.BundleContext)
// */
// public void start(BundleContext context) throws Exception {
// super.start(context);
// plugin = this;
// }
//
// /*
// * (non-Javadoc)
// * @see org.eclipse.ui.plugin.AbstractUIPlugin#stop(org.osgi.framework.BundleContext)
// */
// public void stop(BundleContext context) throws Exception {
// plugin = null;
// super.stop(context);
// }
//
// /**
// * Returns the shared instance
// *
// * @return the shared instance
// */
// public static CinderPlugin getDefault() {
// return plugin;
// }
//
// /**
// * Returns an image descriptor for the image file at the given
// * plug-in relative path
// *
// * @param path the path
// * @return the image descriptor
// */
// public static ImageDescriptor getImageDescriptor(final String path) {
// return imageDescriptorFromPlugin(PLUGIN_ID, path);
// }
// }
| import java.util.ResourceBundle;
import org.eclipse.jface.preference.*;
import org.eclipse.ui.IWorkbenchPreferencePage;
import org.eclipse.ui.IWorkbench;
import org.art_core.dev.cinder.CinderPlugin; | package org.art_core.dev.cinder.prefs;
/**
* This class represents a preference page that is contributed to the
* Preferences dialog. By subclassing <samp>FieldEditorPreferencePage</samp>, we
* can use the field support built into JFace that allows us to create a page
* that is small and knows how to save, restore and apply itself.
* <p>
* This page is used to modify preferences only. They are stored in the
* preference store that belongs to the main plug-in class. That way,
* preferences can be accessed directly via the preference store.
*/
public class CinderPrefPage extends FieldEditorPreferencePage implements
IWorkbenchPreferencePage {
private ResourceBundle cRes = ResourceBundle.getBundle("org.art_core.dev.cinder.CinderResource");
public static final String P_PATH = "pathPreference";
public static final String P_BOOLEAN = "booleanPreference";
public static final String P_CHOICE = "choicePreference";
public static final String P_STRING = "stringPreference";
public static final String P_COLOR = "colorPreference";
public static final String P_INTEGER = "integerPreference";
public static final int STRING_FIELD = 1;
public static final int FILE_FIELD = 2;
public CinderPrefPage() {
super(GRID); | // Path: src/org/art_core/dev/cinder/CinderPlugin.java
// public class CinderPlugin extends AbstractUIPlugin {
//
// // The plug-in ID
// public static final String PLUGIN_ID = "org.art_core.dev.cinder";
//
// // The shared instance
// private static CinderPlugin plugin;
//
// /*
// * (non-Javadoc)
// * @see org.eclipse.ui.plugin.AbstractUIPlugin#start(org.osgi.framework.BundleContext)
// */
// public void start(BundleContext context) throws Exception {
// super.start(context);
// plugin = this;
// }
//
// /*
// * (non-Javadoc)
// * @see org.eclipse.ui.plugin.AbstractUIPlugin#stop(org.osgi.framework.BundleContext)
// */
// public void stop(BundleContext context) throws Exception {
// plugin = null;
// super.stop(context);
// }
//
// /**
// * Returns the shared instance
// *
// * @return the shared instance
// */
// public static CinderPlugin getDefault() {
// return plugin;
// }
//
// /**
// * Returns an image descriptor for the image file at the given
// * plug-in relative path
// *
// * @param path the path
// * @return the image descriptor
// */
// public static ImageDescriptor getImageDescriptor(final String path) {
// return imageDescriptorFromPlugin(PLUGIN_ID, path);
// }
// }
// Path: src/org/art_core/dev/cinder/prefs/CinderPrefPage.java
import java.util.ResourceBundle;
import org.eclipse.jface.preference.*;
import org.eclipse.ui.IWorkbenchPreferencePage;
import org.eclipse.ui.IWorkbench;
import org.art_core.dev.cinder.CinderPlugin;
package org.art_core.dev.cinder.prefs;
/**
* This class represents a preference page that is contributed to the
* Preferences dialog. By subclassing <samp>FieldEditorPreferencePage</samp>, we
* can use the field support built into JFace that allows us to create a page
* that is small and knows how to save, restore and apply itself.
* <p>
* This page is used to modify preferences only. They are stored in the
* preference store that belongs to the main plug-in class. That way,
* preferences can be accessed directly via the preference store.
*/
public class CinderPrefPage extends FieldEditorPreferencePage implements
IWorkbenchPreferencePage {
private ResourceBundle cRes = ResourceBundle.getBundle("org.art_core.dev.cinder.CinderResource");
public static final String P_PATH = "pathPreference";
public static final String P_BOOLEAN = "booleanPreference";
public static final String P_CHOICE = "choicePreference";
public static final String P_STRING = "stringPreference";
public static final String P_COLOR = "colorPreference";
public static final String P_INTEGER = "integerPreference";
public static final int STRING_FIELD = 1;
public static final int FILE_FIELD = 2;
public CinderPrefPage() {
super(GRID); | setPreferenceStore(CinderPlugin.getDefault().getPreferenceStore()); |
winks/cinder | src/org/art_core/dev/cinder/input/XmlInputReader.java | // Path: src/org/art_core/dev/cinder/CinderLog.java
// public final class CinderLog {
// public final int OK = IStatus.OK;
// public final int INFO = IStatus.INFO;
// public final int WARNING = IStatus.WARNING;
// public final int ERROR = IStatus.ERROR;
//
// private CinderLog() {}
//
// /**
// * Logs debug messages if the config allows it.
// * @param message
// */
// public static void logDebug(final String message) {
// IPreferenceStore ipsPref = CinderPlugin.getDefault().getPreferenceStore();
// String sPrefKey = CinderPrefPage.P_BOOLEAN + "_show_debug";
// boolean bDebug = ipsPref.getBoolean(sPrefKey);
// if (bDebug) {
// logInfo(message);
// }
// }
//
// /**
// * Logs a non-critical exception as information.
// * @param message
// * @param exception
// */
// public static void logErrorInfo(final String message, final Throwable exception) {
// IPreferenceStore ipsPref = CinderPlugin.getDefault().getPreferenceStore();
// String sPrefKey = CinderPrefPage.P_BOOLEAN + "_show_debug";
// boolean bDebug = ipsPref.getBoolean(sPrefKey);
// if (bDebug) {
// log (IStatus.INFO, IStatus.OK, message, exception);
// }
// }
//
// /**
// * Log the specified information.
// *
// * @param message, a human-readable message, localized to the
// * current locale.
// */
// public static void logInfo(final String message) {
// log(IStatus.INFO, IStatus.OK, message, null);
// }
//
// /**
// * Log the specified error.
// *
// * @param exception, a low-level exception.
// */
// public static void logError(final Throwable exception) {
// logError("Unexpected Exception", exception);
// }
//
// /**
// * Log the specified error.
// *
// * @param message, a human-readable message, localized to the
// * current locale.
// * @param exception, a low-level exception, or <code>null</code>
// * if not applicable.
// */
// public static void logError(final String message, final Throwable exception) {
// log(IStatus.ERROR, IStatus.OK, message, exception);
// }
//
// /**
// * Log the specified information.
// *
// * @param severity, the severity; one of the following:
// * <code>IStatus.OK</code>,
// * <code>IStatus.ERROR</code>,
// * <code>IStatus.INFO</code>, or
// * <code>IStatus.WARNING</code>.
// * @param pluginId. the unique identifier of the relevant
// * plug-in.
// * @param code, the plug-in-specific status code, or
// * <code>OK</code>.
// * @param message, a human-readable message, localized to the
// * current locale.
// * @param exception, a low-level exception, or <code>null</code>
// * if not applicable.
// */
// public static void log(final int severity, final int code, final String message,
// final Throwable exception) {
// log(createStatus(severity, code, message, exception));
// }
//
// /**
// * Create a status object representing the specified information.
// *
// * @param severity, the severity; one of the following:
// * <code>IStatus.OK</code>,
// * <code>IStatus.ERROR</code>,
// * <code>IStatus.INFO</code>, or
// * <code>IStatus.WARNING</code>.
// * @param pluginId, the unique identifier of the relevant
// * plug-in.
// * @param code, the plug-in-specific status code, or
// * <code>OK</code>.
// * @param message, a human-readable message, localized to the
// * current locale.
// * @param exception, a low-level exception, or <code>null</code>
// * if not applicable.
// * @return, the status object (not <code>null</code>).
// */
// public static IStatus createStatus(final int severity, final int code, final String message,
// final Throwable exception) {
// return new Status(severity, CinderPlugin.PLUGIN_ID, code,
// message, exception);
// }
//
// /**
// * Log the given status.
// *
// * @param status, the status to log.
// */
// public static void log(final IStatus status) {
// CinderPlugin.getDefault().getLog().log(status);
// }
// }
//
// Path: src/org/art_core/dev/cinder/model/IItem.java
// public interface IItem extends IAdaptable {
// String getName();
//
// String getLocation();
//
// String getMessage();
//
// int getLine();
//
// int getOffset();
//
// int getTimestamp();
//
// ItemStatus getStatus();
//
// ItemSource getSource();
//
// HashMap<String, String> getDetails();
//
// ItemType getType();
//
// void setStatus(ItemStatus status);
//
// IItem[] NONE = new IItem[] {};
// }
| import java.io.File;
import java.util.ArrayList;
import java.util.Collection;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import org.art_core.dev.cinder.CinderLog;
import org.art_core.dev.cinder.model.IItem;
import org.eclipse.core.resources.IWorkspaceRoot;
import org.eclipse.core.resources.ResourcesPlugin;
import org.w3c.dom.Document;
import org.w3c.dom.NodeList; | package org.art_core.dev.cinder.input;
/**
* XML Reader for CruiseControl / phpUnderControl XML files
* @author Florian Anderiasch
*
*/
public class XmlInputReader implements IInputHandler {
private String sFilename = null; | // Path: src/org/art_core/dev/cinder/CinderLog.java
// public final class CinderLog {
// public final int OK = IStatus.OK;
// public final int INFO = IStatus.INFO;
// public final int WARNING = IStatus.WARNING;
// public final int ERROR = IStatus.ERROR;
//
// private CinderLog() {}
//
// /**
// * Logs debug messages if the config allows it.
// * @param message
// */
// public static void logDebug(final String message) {
// IPreferenceStore ipsPref = CinderPlugin.getDefault().getPreferenceStore();
// String sPrefKey = CinderPrefPage.P_BOOLEAN + "_show_debug";
// boolean bDebug = ipsPref.getBoolean(sPrefKey);
// if (bDebug) {
// logInfo(message);
// }
// }
//
// /**
// * Logs a non-critical exception as information.
// * @param message
// * @param exception
// */
// public static void logErrorInfo(final String message, final Throwable exception) {
// IPreferenceStore ipsPref = CinderPlugin.getDefault().getPreferenceStore();
// String sPrefKey = CinderPrefPage.P_BOOLEAN + "_show_debug";
// boolean bDebug = ipsPref.getBoolean(sPrefKey);
// if (bDebug) {
// log (IStatus.INFO, IStatus.OK, message, exception);
// }
// }
//
// /**
// * Log the specified information.
// *
// * @param message, a human-readable message, localized to the
// * current locale.
// */
// public static void logInfo(final String message) {
// log(IStatus.INFO, IStatus.OK, message, null);
// }
//
// /**
// * Log the specified error.
// *
// * @param exception, a low-level exception.
// */
// public static void logError(final Throwable exception) {
// logError("Unexpected Exception", exception);
// }
//
// /**
// * Log the specified error.
// *
// * @param message, a human-readable message, localized to the
// * current locale.
// * @param exception, a low-level exception, or <code>null</code>
// * if not applicable.
// */
// public static void logError(final String message, final Throwable exception) {
// log(IStatus.ERROR, IStatus.OK, message, exception);
// }
//
// /**
// * Log the specified information.
// *
// * @param severity, the severity; one of the following:
// * <code>IStatus.OK</code>,
// * <code>IStatus.ERROR</code>,
// * <code>IStatus.INFO</code>, or
// * <code>IStatus.WARNING</code>.
// * @param pluginId. the unique identifier of the relevant
// * plug-in.
// * @param code, the plug-in-specific status code, or
// * <code>OK</code>.
// * @param message, a human-readable message, localized to the
// * current locale.
// * @param exception, a low-level exception, or <code>null</code>
// * if not applicable.
// */
// public static void log(final int severity, final int code, final String message,
// final Throwable exception) {
// log(createStatus(severity, code, message, exception));
// }
//
// /**
// * Create a status object representing the specified information.
// *
// * @param severity, the severity; one of the following:
// * <code>IStatus.OK</code>,
// * <code>IStatus.ERROR</code>,
// * <code>IStatus.INFO</code>, or
// * <code>IStatus.WARNING</code>.
// * @param pluginId, the unique identifier of the relevant
// * plug-in.
// * @param code, the plug-in-specific status code, or
// * <code>OK</code>.
// * @param message, a human-readable message, localized to the
// * current locale.
// * @param exception, a low-level exception, or <code>null</code>
// * if not applicable.
// * @return, the status object (not <code>null</code>).
// */
// public static IStatus createStatus(final int severity, final int code, final String message,
// final Throwable exception) {
// return new Status(severity, CinderPlugin.PLUGIN_ID, code,
// message, exception);
// }
//
// /**
// * Log the given status.
// *
// * @param status, the status to log.
// */
// public static void log(final IStatus status) {
// CinderPlugin.getDefault().getLog().log(status);
// }
// }
//
// Path: src/org/art_core/dev/cinder/model/IItem.java
// public interface IItem extends IAdaptable {
// String getName();
//
// String getLocation();
//
// String getMessage();
//
// int getLine();
//
// int getOffset();
//
// int getTimestamp();
//
// ItemStatus getStatus();
//
// ItemSource getSource();
//
// HashMap<String, String> getDetails();
//
// ItemType getType();
//
// void setStatus(ItemStatus status);
//
// IItem[] NONE = new IItem[] {};
// }
// Path: src/org/art_core/dev/cinder/input/XmlInputReader.java
import java.io.File;
import java.util.ArrayList;
import java.util.Collection;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import org.art_core.dev.cinder.CinderLog;
import org.art_core.dev.cinder.model.IItem;
import org.eclipse.core.resources.IWorkspaceRoot;
import org.eclipse.core.resources.ResourcesPlugin;
import org.w3c.dom.Document;
import org.w3c.dom.NodeList;
package org.art_core.dev.cinder.input;
/**
* XML Reader for CruiseControl / phpUnderControl XML files
* @author Florian Anderiasch
*
*/
public class XmlInputReader implements IInputHandler {
private String sFilename = null; | private final Collection<IItem> items = new ArrayList<IItem>(); |
winks/cinder | src/org/art_core/dev/cinder/CinderLog.java | // Path: src/org/art_core/dev/cinder/prefs/CinderPrefPage.java
// public class CinderPrefPage extends FieldEditorPreferencePage implements
// IWorkbenchPreferencePage {
//
// private ResourceBundle cRes = ResourceBundle.getBundle("org.art_core.dev.cinder.CinderResource");
//
// public static final String P_PATH = "pathPreference";
// public static final String P_BOOLEAN = "booleanPreference";
// public static final String P_CHOICE = "choicePreference";
// public static final String P_STRING = "stringPreference";
// public static final String P_COLOR = "colorPreference";
// public static final String P_INTEGER = "integerPreference";
//
// public static final int STRING_FIELD = 1;
// public static final int FILE_FIELD = 2;
//
// public CinderPrefPage() {
// super(GRID);
// setPreferenceStore(CinderPlugin.getDefault().getPreferenceStore());
// setDescription(cRes.getString("GENERAL_SETTINGS"));
// setMessage(cRes.getString("PREFERENCES"));
// }
//
// /**
// * Creates the field editors. Field editors are abstractions of the common
// * GUI blocks needed to manipulate various types of preferences. Each field
// * editor knows how to save and restore itself.
// */
// public void createFieldEditors() {
// addImportSource(STRING_FIELD, "xml_url", 1);
// addImportSource(STRING_FIELD, "xml_url", 2);
// addImportSource(STRING_FIELD, "xml_url", 3);
// addImportSource(FILE_FIELD, "xml_file", 1);
// addImportSource(FILE_FIELD, "xml_file", 2);
// addImportSource(FILE_FIELD, "xml_file", 3);
//
// addField(new BooleanFieldEditor(CinderPrefPage.P_BOOLEAN + "_show_debug",
// cRes.getString("SHOW_DEBUG"), getFieldEditorParent()));
// }
//
// private void addImportSource(int iMode, String sIdentifier, int iNumber) {
// String sNameString = CinderPrefPage.P_STRING + "_" + sIdentifier + "_" + iNumber;
// String sNameInt = CinderPrefPage.P_INTEGER + "_" + sIdentifier + "_" + iNumber;
// String sNameBool = CinderPrefPage.P_BOOLEAN + "_" + sIdentifier + "_" + iNumber;
//
// if (iMode == FILE_FIELD) {
// addField(new FileFieldEditor(sNameString,
// cRes.getString("XML_FILE"), getFieldEditorParent()));
// } else {
// addField(new StringFieldEditor(sNameString,
// cRes.getString("XML_URL"), getFieldEditorParent()));
// }
// addField(new BooleanFieldEditor(sNameBool + "_check",
// cRes.getString("CHECK_PERIODICALLY"), getFieldEditorParent()));
// IntegerFieldEditor ifeUrl = new IntegerFieldEditor(sNameInt + "_time",
// cRes.getString("INTERVAL_IN_MINUTES"), getFieldEditorParent());
// ifeUrl.setTextLimit(3);
// ifeUrl.setValidRange(1, 999);
// addField(ifeUrl);
// }
//
// /*
// * (non-Javadoc)
// *
// * @see
// * org.eclipse.ui.IWorkbenchPreferencePage#init(org.eclipse.ui.IWorkbench)
// */
// public void init(IWorkbench workbench) {
// }
//
// }
| import org.art_core.dev.cinder.prefs.CinderPrefPage;
import org.eclipse.core.runtime.IStatus;
import org.eclipse.core.runtime.Status;
import org.eclipse.jface.preference.IPreferenceStore; | package org.art_core.dev.cinder;
/**
* The logger of convenience for the Cinder plug-in.
*/
public final class CinderLog {
public final int OK = IStatus.OK;
public final int INFO = IStatus.INFO;
public final int WARNING = IStatus.WARNING;
public final int ERROR = IStatus.ERROR;
private CinderLog() {}
/**
* Logs debug messages if the config allows it.
* @param message
*/
public static void logDebug(final String message) {
IPreferenceStore ipsPref = CinderPlugin.getDefault().getPreferenceStore(); | // Path: src/org/art_core/dev/cinder/prefs/CinderPrefPage.java
// public class CinderPrefPage extends FieldEditorPreferencePage implements
// IWorkbenchPreferencePage {
//
// private ResourceBundle cRes = ResourceBundle.getBundle("org.art_core.dev.cinder.CinderResource");
//
// public static final String P_PATH = "pathPreference";
// public static final String P_BOOLEAN = "booleanPreference";
// public static final String P_CHOICE = "choicePreference";
// public static final String P_STRING = "stringPreference";
// public static final String P_COLOR = "colorPreference";
// public static final String P_INTEGER = "integerPreference";
//
// public static final int STRING_FIELD = 1;
// public static final int FILE_FIELD = 2;
//
// public CinderPrefPage() {
// super(GRID);
// setPreferenceStore(CinderPlugin.getDefault().getPreferenceStore());
// setDescription(cRes.getString("GENERAL_SETTINGS"));
// setMessage(cRes.getString("PREFERENCES"));
// }
//
// /**
// * Creates the field editors. Field editors are abstractions of the common
// * GUI blocks needed to manipulate various types of preferences. Each field
// * editor knows how to save and restore itself.
// */
// public void createFieldEditors() {
// addImportSource(STRING_FIELD, "xml_url", 1);
// addImportSource(STRING_FIELD, "xml_url", 2);
// addImportSource(STRING_FIELD, "xml_url", 3);
// addImportSource(FILE_FIELD, "xml_file", 1);
// addImportSource(FILE_FIELD, "xml_file", 2);
// addImportSource(FILE_FIELD, "xml_file", 3);
//
// addField(new BooleanFieldEditor(CinderPrefPage.P_BOOLEAN + "_show_debug",
// cRes.getString("SHOW_DEBUG"), getFieldEditorParent()));
// }
//
// private void addImportSource(int iMode, String sIdentifier, int iNumber) {
// String sNameString = CinderPrefPage.P_STRING + "_" + sIdentifier + "_" + iNumber;
// String sNameInt = CinderPrefPage.P_INTEGER + "_" + sIdentifier + "_" + iNumber;
// String sNameBool = CinderPrefPage.P_BOOLEAN + "_" + sIdentifier + "_" + iNumber;
//
// if (iMode == FILE_FIELD) {
// addField(new FileFieldEditor(sNameString,
// cRes.getString("XML_FILE"), getFieldEditorParent()));
// } else {
// addField(new StringFieldEditor(sNameString,
// cRes.getString("XML_URL"), getFieldEditorParent()));
// }
// addField(new BooleanFieldEditor(sNameBool + "_check",
// cRes.getString("CHECK_PERIODICALLY"), getFieldEditorParent()));
// IntegerFieldEditor ifeUrl = new IntegerFieldEditor(sNameInt + "_time",
// cRes.getString("INTERVAL_IN_MINUTES"), getFieldEditorParent());
// ifeUrl.setTextLimit(3);
// ifeUrl.setValidRange(1, 999);
// addField(ifeUrl);
// }
//
// /*
// * (non-Javadoc)
// *
// * @see
// * org.eclipse.ui.IWorkbenchPreferencePage#init(org.eclipse.ui.IWorkbench)
// */
// public void init(IWorkbench workbench) {
// }
//
// }
// Path: src/org/art_core/dev/cinder/CinderLog.java
import org.art_core.dev.cinder.prefs.CinderPrefPage;
import org.eclipse.core.runtime.IStatus;
import org.eclipse.core.runtime.Status;
import org.eclipse.jface.preference.IPreferenceStore;
package org.art_core.dev.cinder;
/**
* The logger of convenience for the Cinder plug-in.
*/
public final class CinderLog {
public final int OK = IStatus.OK;
public final int INFO = IStatus.INFO;
public final int WARNING = IStatus.WARNING;
public final int ERROR = IStatus.ERROR;
private CinderLog() {}
/**
* Logs debug messages if the config allows it.
* @param message
*/
public static void logDebug(final String message) {
IPreferenceStore ipsPref = CinderPlugin.getDefault().getPreferenceStore(); | String sPrefKey = CinderPrefPage.P_BOOLEAN + "_show_debug"; |
cwan/im-log-stats | im-log-stats-project/src/main/java/net/mikaboshi/intra_mart/tools/log_stats/parser/ParserErrorCounter.java | // Path: im-log-stats-project/src/main/java/net/mikaboshi/intra_mart/tools/log_stats/exception/ParserErrorLimitException.java
// public class ParserErrorLimitException extends RuntimeException {
//
// private static final long serialVersionUID = -1794287316225077318L;
//
// public ParserErrorLimitException(int n) {
// super("Pasing is aborted due to too many errors (" + n + ")");
// }
// }
| import net.mikaboshi.intra_mart.tools.log_stats.exception.ParserErrorLimitException; | /*
* Licensed under the public 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.mikaboshi.intra_mart.tools.log_stats.parser;
/**
* パーサエラーの件数を数えるクラス。
*
* @version 1.0.10
* @since 1.0.10
* @author <a href="https://github.com/cwan">cwan</a>
*/
public class ParserErrorCounter {
private int limit = 1000;
private int count = 0;
/**
* デフォルトのコンストラクタ。
* 上限 = 1000 が適用される。
*/
public ParserErrorCounter() {
}
/**
* 上限を明示的に指定するコンストラクタ。
* limit に0以下を指定した場合、上限なしとなる。
*
* @param limit
*/
public ParserErrorCounter(int limit) {
this.limit = limit;
}
/**
* エラー数を1カウントアップする。
* エラーの上限を超えた場合、ParserErrorLimitException をスローする。
*
* @throws ParserErrorLimitException
*/ | // Path: im-log-stats-project/src/main/java/net/mikaboshi/intra_mart/tools/log_stats/exception/ParserErrorLimitException.java
// public class ParserErrorLimitException extends RuntimeException {
//
// private static final long serialVersionUID = -1794287316225077318L;
//
// public ParserErrorLimitException(int n) {
// super("Pasing is aborted due to too many errors (" + n + ")");
// }
// }
// Path: im-log-stats-project/src/main/java/net/mikaboshi/intra_mart/tools/log_stats/parser/ParserErrorCounter.java
import net.mikaboshi.intra_mart.tools.log_stats.exception.ParserErrorLimitException;
/*
* Licensed under the public 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.mikaboshi.intra_mart.tools.log_stats.parser;
/**
* パーサエラーの件数を数えるクラス。
*
* @version 1.0.10
* @since 1.0.10
* @author <a href="https://github.com/cwan">cwan</a>
*/
public class ParserErrorCounter {
private int limit = 1000;
private int count = 0;
/**
* デフォルトのコンストラクタ。
* 上限 = 1000 が適用される。
*/
public ParserErrorCounter() {
}
/**
* 上限を明示的に指定するコンストラクタ。
* limit に0以下を指定した場合、上限なしとなる。
*
* @param limit
*/
public ParserErrorCounter(int limit) {
this.limit = limit;
}
/**
* エラー数を1カウントアップする。
* エラーの上限を超えた場合、ParserErrorLimitException をスローする。
*
* @throws ParserErrorLimitException
*/ | public synchronized void increment() throws ParserErrorLimitException { |
cwan/im-log-stats | im-log-stats-project/src/main/java/net/mikaboshi/intra_mart/tools/log_stats/report/TenantStatistics.java | // Path: im-log-stats-project/src/main/java/net/mikaboshi/intra_mart/tools/log_stats/entity/ConcurrentRequest.java
// public class ConcurrentRequest {
//
// public enum EventType {
//
// /** 受信時刻 */
// ACCEPT_TIME,
//
// /** 返信時刻 */
// RESPONSE_TIME;
// }
//
// private final EventType type;
//
// private final long time;
//
// private int count = 0;
//
// private String tenantId;
//
// public ConcurrentRequest(EventType type, long time, String tenantId) {
// this.type = type;
// this.time = time;
// this.tenantId = tenantId;
// }
//
// public EventType getType() {
// return type;
// }
//
// public long getTime() {
// return time;
// }
//
// public void setCount(int count) {
// this.count = count;
// }
//
// public int getCount() {
// return count;
// }
//
// /**
// * テナントIDを取得する。
// * @since 1.0.16
// * @return
// */
// public String getTenantId() {
// return tenantId;
// }
// }
| import java.util.List;
import net.mikaboshi.intra_mart.tools.log_stats.entity.ConcurrentRequest; | /*
* 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.mikaboshi.intra_mart.tools.log_stats.report;
/**
* テナント別統計
*
* @version 1.0.16
* @since 1.0.16
* @author <a href="https://github.com/cwan">cwan</a>
*/
public class TenantStatistics extends BasicStatistics {
/**
* テナントID
*/
private String tenantId;
/**
* コンストラクタ
* @param transitionLogOnly 画面遷移ログのみ(リクエストログなし)かどうか
*/
public TenantStatistics(boolean transitionLogOnly) {
super(transitionLogOnly);
}
public String getTenantId() {
return tenantId;
}
public void setTenantId(String tenantId) {
this.tenantId = tenantId;
}
/**
* 同時リクエスト数の最大値を調べる。
* @param concurrentRequestList
*/ | // Path: im-log-stats-project/src/main/java/net/mikaboshi/intra_mart/tools/log_stats/entity/ConcurrentRequest.java
// public class ConcurrentRequest {
//
// public enum EventType {
//
// /** 受信時刻 */
// ACCEPT_TIME,
//
// /** 返信時刻 */
// RESPONSE_TIME;
// }
//
// private final EventType type;
//
// private final long time;
//
// private int count = 0;
//
// private String tenantId;
//
// public ConcurrentRequest(EventType type, long time, String tenantId) {
// this.type = type;
// this.time = time;
// this.tenantId = tenantId;
// }
//
// public EventType getType() {
// return type;
// }
//
// public long getTime() {
// return time;
// }
//
// public void setCount(int count) {
// this.count = count;
// }
//
// public int getCount() {
// return count;
// }
//
// /**
// * テナントIDを取得する。
// * @since 1.0.16
// * @return
// */
// public String getTenantId() {
// return tenantId;
// }
// }
// Path: im-log-stats-project/src/main/java/net/mikaboshi/intra_mart/tools/log_stats/report/TenantStatistics.java
import java.util.List;
import net.mikaboshi.intra_mart.tools.log_stats.entity.ConcurrentRequest;
/*
* 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.mikaboshi.intra_mart.tools.log_stats.report;
/**
* テナント別統計
*
* @version 1.0.16
* @since 1.0.16
* @author <a href="https://github.com/cwan">cwan</a>
*/
public class TenantStatistics extends BasicStatistics {
/**
* テナントID
*/
private String tenantId;
/**
* コンストラクタ
* @param transitionLogOnly 画面遷移ログのみ(リクエストログなし)かどうか
*/
public TenantStatistics(boolean transitionLogOnly) {
super(transitionLogOnly);
}
public String getTenantId() {
return tenantId;
}
public void setTenantId(String tenantId) {
this.tenantId = tenantId;
}
/**
* 同時リクエスト数の最大値を調べる。
* @param concurrentRequestList
*/ | public void countMaxConcurrentRequest(List<ConcurrentRequest> concurrentRequestList) { |
cwan/im-log-stats | im-log-stats-project/src/main/java/net/mikaboshi/intra_mart/tools/log_stats/report/TimeSpanStatistics.java | // Path: im-log-stats-project/src/main/java/net/mikaboshi/intra_mart/tools/log_stats/entity/ConcurrentRequest.java
// public class ConcurrentRequest {
//
// public enum EventType {
//
// /** 受信時刻 */
// ACCEPT_TIME,
//
// /** 返信時刻 */
// RESPONSE_TIME;
// }
//
// private final EventType type;
//
// private final long time;
//
// private int count = 0;
//
// private String tenantId;
//
// public ConcurrentRequest(EventType type, long time, String tenantId) {
// this.type = type;
// this.time = time;
// this.tenantId = tenantId;
// }
//
// public EventType getType() {
// return type;
// }
//
// public long getTime() {
// return time;
// }
//
// public void setCount(int count) {
// this.count = count;
// }
//
// public int getCount() {
// return count;
// }
//
// /**
// * テナントIDを取得する。
// * @since 1.0.16
// * @return
// */
// public String getTenantId() {
// return tenantId;
// }
// }
| import java.util.Date;
import java.util.List;
import net.mikaboshi.intra_mart.tools.log_stats.entity.ConcurrentRequest; | /*
* 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.mikaboshi.intra_mart.tools.log_stats.report;
/**
* 時間分割統計
*
* @version 1.0.16
* @author <a href="https://github.com/cwan">cwan</a>
*/
public class TimeSpanStatistics extends BasicStatistics {
/**
* スパン開始日時
*/
private Date startDate = null;
/**
* スパン終了日時
* @since 1.0.13
*/
private Date endDate = null;
/**
* コンストラクタ
* @param transitionLogOnly 画面遷移ログのみ(リクエストログなし)かどうか
*/
public TimeSpanStatistics(boolean transitionLogOnly) {
super(transitionLogOnly);
}
/**
* スパン開始日時を設定する。
* @param startDate スパン開始日時
*/
public void setStartDate(Date startDate) {
this.startDate = startDate;
}
/**
* スパン開始日時を取得する。
* @return
*/
public Date getStartDate() {
return startDate;
}
/**
* スパン終了日時を設定する。
* @param endDate スパン終了日時
*/
public void setEndDate(Date endDate) {
this.endDate = endDate;
}
/**
* スパン終了日時を取得する。
* @return
* @since 1.0.13
*/
public Date getEndDate() {
return endDate;
}
/**
* 同時リクエスト数の最大値を調べる。
* @param concurrentRequestList
* @since 1.0.13
*/ | // Path: im-log-stats-project/src/main/java/net/mikaboshi/intra_mart/tools/log_stats/entity/ConcurrentRequest.java
// public class ConcurrentRequest {
//
// public enum EventType {
//
// /** 受信時刻 */
// ACCEPT_TIME,
//
// /** 返信時刻 */
// RESPONSE_TIME;
// }
//
// private final EventType type;
//
// private final long time;
//
// private int count = 0;
//
// private String tenantId;
//
// public ConcurrentRequest(EventType type, long time, String tenantId) {
// this.type = type;
// this.time = time;
// this.tenantId = tenantId;
// }
//
// public EventType getType() {
// return type;
// }
//
// public long getTime() {
// return time;
// }
//
// public void setCount(int count) {
// this.count = count;
// }
//
// public int getCount() {
// return count;
// }
//
// /**
// * テナントIDを取得する。
// * @since 1.0.16
// * @return
// */
// public String getTenantId() {
// return tenantId;
// }
// }
// Path: im-log-stats-project/src/main/java/net/mikaboshi/intra_mart/tools/log_stats/report/TimeSpanStatistics.java
import java.util.Date;
import java.util.List;
import net.mikaboshi.intra_mart.tools.log_stats.entity.ConcurrentRequest;
/*
* 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.mikaboshi.intra_mart.tools.log_stats.report;
/**
* 時間分割統計
*
* @version 1.0.16
* @author <a href="https://github.com/cwan">cwan</a>
*/
public class TimeSpanStatistics extends BasicStatistics {
/**
* スパン開始日時
*/
private Date startDate = null;
/**
* スパン終了日時
* @since 1.0.13
*/
private Date endDate = null;
/**
* コンストラクタ
* @param transitionLogOnly 画面遷移ログのみ(リクエストログなし)かどうか
*/
public TimeSpanStatistics(boolean transitionLogOnly) {
super(transitionLogOnly);
}
/**
* スパン開始日時を設定する。
* @param startDate スパン開始日時
*/
public void setStartDate(Date startDate) {
this.startDate = startDate;
}
/**
* スパン開始日時を取得する。
* @return
*/
public Date getStartDate() {
return startDate;
}
/**
* スパン終了日時を設定する。
* @param endDate スパン終了日時
*/
public void setEndDate(Date endDate) {
this.endDate = endDate;
}
/**
* スパン終了日時を取得する。
* @return
* @since 1.0.13
*/
public Date getEndDate() {
return endDate;
}
/**
* 同時リクエスト数の最大値を調べる。
* @param concurrentRequestList
* @since 1.0.13
*/ | public void countMaxConcurrentRequest(List<ConcurrentRequest> concurrentRequestList) { |
cwan/im-log-stats | im-log-stats-project/src/main/java/net/mikaboshi/intra_mart/tools/log_stats/report/SessionMap.java | // Path: im-log-stats-project/src/main/java/net/mikaboshi/intra_mart/tools/log_stats/util/LogStringUtil.java
// public final class LogStringUtil {
//
// private static final Pattern LINE_SPLIT_PATTERN = Pattern.compile("\\r?\\n");
//
// private static final String[] ENPTY_STRING_ARRAY = new String[0];
//
// private static final Pattern TRUNCATE_URL_PATTERN = Pattern.compile("(?:[^(\\:/)]+\\:)?//(?:[^(\\:/)]+)(?:\\:\\d+)?(/.+)");
//
// private LogStringUtil() {}
//
// /**
// * 引数を改行コードで分割する。
// *
// * @param s
// * @return 引数を分割した文字列の配列。引数がnullの場合は、空の配列を返す。
// */
// public static String[] lines(CharSequence s) {
//
// if (s == null) {
// return ENPTY_STRING_ARRAY;
// }
//
// return LINE_SPLIT_PATTERN.split(s);
// }
//
// /**
// * URLからスキーム、ホスト、ポートを削除する。
// * @param url
// * @return
// */
// public static String truncateUrl(String url) {
//
// if (url == null) {
// return StringUtils.EMPTY;
// }
//
// Matcher matcher = TRUNCATE_URL_PATTERN.matcher(url);
//
// if (matcher.matches()) {
// return matcher.group(1);
// } else {
// return url;
// }
// }
//
// /**
// * セッションID、ユーザIDが有効ならばtrueを返す。
// * @since 1.0.21
// * @param id
// * @return
// */
// public static boolean isValidId(String id) {
// return StringUtils.isNotBlank(id) && !"-".equals(id.trim());
// }
//
// }
//
// Path: im-log-stats-project/src/main/java/net/mikaboshi/intra_mart/tools/log_stats/util/LongListFactory.java
// public final class LongListFactory implements Factory {
//
// public static LongListFactory INSTANCE = new LongListFactory();
//
// private LongListFactory() {}
//
// public Object create() {
// return new ArrayList<Long>();
// }
// }
| import static net.mikaboshi.intra_mart.tools.log_stats.util.LogStringUtil.*;
import java.util.Date;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import org.apache.commons.collections.map.LazyMap;
import net.mikaboshi.intra_mart.tools.log_stats.util.LongListFactory; | /*
* 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.mikaboshi.intra_mart.tools.log_stats.report;
/**
* セッション情報
*
* @version 1.0.21
* @author <a href="https://github.com/cwan">cwan</a>
*/
public class SessionMap {
/**
* セッションID => 処理時間
*/
@SuppressWarnings("unchecked")
private Map<String, List<Long>> sessionPageTimesMap = LazyMap.decorate(
new HashMap<String, List<Long>>(), | // Path: im-log-stats-project/src/main/java/net/mikaboshi/intra_mart/tools/log_stats/util/LogStringUtil.java
// public final class LogStringUtil {
//
// private static final Pattern LINE_SPLIT_PATTERN = Pattern.compile("\\r?\\n");
//
// private static final String[] ENPTY_STRING_ARRAY = new String[0];
//
// private static final Pattern TRUNCATE_URL_PATTERN = Pattern.compile("(?:[^(\\:/)]+\\:)?//(?:[^(\\:/)]+)(?:\\:\\d+)?(/.+)");
//
// private LogStringUtil() {}
//
// /**
// * 引数を改行コードで分割する。
// *
// * @param s
// * @return 引数を分割した文字列の配列。引数がnullの場合は、空の配列を返す。
// */
// public static String[] lines(CharSequence s) {
//
// if (s == null) {
// return ENPTY_STRING_ARRAY;
// }
//
// return LINE_SPLIT_PATTERN.split(s);
// }
//
// /**
// * URLからスキーム、ホスト、ポートを削除する。
// * @param url
// * @return
// */
// public static String truncateUrl(String url) {
//
// if (url == null) {
// return StringUtils.EMPTY;
// }
//
// Matcher matcher = TRUNCATE_URL_PATTERN.matcher(url);
//
// if (matcher.matches()) {
// return matcher.group(1);
// } else {
// return url;
// }
// }
//
// /**
// * セッションID、ユーザIDが有効ならばtrueを返す。
// * @since 1.0.21
// * @param id
// * @return
// */
// public static boolean isValidId(String id) {
// return StringUtils.isNotBlank(id) && !"-".equals(id.trim());
// }
//
// }
//
// Path: im-log-stats-project/src/main/java/net/mikaboshi/intra_mart/tools/log_stats/util/LongListFactory.java
// public final class LongListFactory implements Factory {
//
// public static LongListFactory INSTANCE = new LongListFactory();
//
// private LongListFactory() {}
//
// public Object create() {
// return new ArrayList<Long>();
// }
// }
// Path: im-log-stats-project/src/main/java/net/mikaboshi/intra_mart/tools/log_stats/report/SessionMap.java
import static net.mikaboshi.intra_mart.tools.log_stats.util.LogStringUtil.*;
import java.util.Date;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import org.apache.commons.collections.map.LazyMap;
import net.mikaboshi.intra_mart.tools.log_stats.util.LongListFactory;
/*
* 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.mikaboshi.intra_mart.tools.log_stats.report;
/**
* セッション情報
*
* @version 1.0.21
* @author <a href="https://github.com/cwan">cwan</a>
*/
public class SessionMap {
/**
* セッションID => 処理時間
*/
@SuppressWarnings("unchecked")
private Map<String, List<Long>> sessionPageTimesMap = LazyMap.decorate(
new HashMap<String, List<Long>>(), | LongListFactory.INSTANCE); |
cwan/im-log-stats | im-log-stats-project/src/main/java/net/mikaboshi/intra_mart/tools/log_stats/report/ReportParameter.java | // Path: im-log-stats-project/src/main/java/net/mikaboshi/intra_mart/tools/log_stats/parser/Version.java
// public enum Version {
//
// V60("6.0"),
//
// V61("6.1"),
//
// V70("7.0"),
//
// V71("7.1"),
//
// V72("7.2"),
//
// V80("8.0"),
//
// V800("8.0.0"),
//
// V801("8.0.1"),
//
// V802("8.0.2"),
//
// V803("8.0.3"),
//
// V804("8.0.4"),
//
// V805("8.0.5"),
//
// V806("8.0.6"),
//
// V807("8.0.7"), // 2014 Spring
//
// V808("8.0.8"), // 2014 Summer
//
// V809("8.0.9"), // 2014 Winter
//
// V8010("8.0.10"), // 2015 Spring
//
// V8011("8.0.11"), // 2015 Summer
//
// V8012("8.0.12"), // 2015 Winter
//
// V8013("8.0.13"), // 2016 Spring
//
// V8014("8.0.14"), // 2016 Summer
//
// V8015("8.0.15"), // 2016 Winter
//
// V8016("8.0.16"); // 2017 Spring
//
//
// private final String name;
//
// private Version(String name) {
// this.name = name;
// }
//
// public static Version toEnum(String name) {
//
// for (Version version : Version.values()) {
// if (version.name.equals(name)) {
// return version;
// }
// }
//
// return null;
// }
//
// public boolean isVersion6() {
// return this == V60 || this == V61;
// }
//
// public boolean isVersion7() {
// return !isVersion6();
// }
//
// public String getName() {
// return name;
// }
// }
| import net.mikaboshi.intra_mart.tools.log_stats.parser.Version; | /*
* 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.mikaboshi.intra_mart.tools.log_stats.report;
/**
* レポートパラメータ
*
* @version 1.0.15
* @author <a href="https://github.com/cwan">cwan</a>
*/
public class ReportParameter {
/**
* 解析間隔(分)
*/
private long span = 5L;
/**
* セッションタイムアウト時間(分)
*/
private int sessionTimeout = 10;
/**
* リクエスト処理時間ランクの出力件数
*/
private int requestPageTimeRankSize = 20;
/**
* リクエスト処理時間ランクの閾値(ミリ秒)
* @since 1.0.11
*/
private long requestPageTimeRankThresholdMillis = -1L;
/**
* リクエストURLランクの出力件数
*/
private int requestUrlRankSize = 20;
/**
* セッションランクの出力件数
*/
private int sessionRankSize = 20;
/**
* JSSPページパスを表示するかどうか
* @since 1.0.11
*/
private boolean jsspPath = false;
/**
* 最大同時リクエスト数を表示するかどうか
* @since 1.0.13
*/
private boolean maxConcurrentRequest = true;
/**
* レポート名
*/
private String name = "intra-mart ログ統計レポート";
/**
* 署名
*/
private String signature = "";
/** バージョン */ | // Path: im-log-stats-project/src/main/java/net/mikaboshi/intra_mart/tools/log_stats/parser/Version.java
// public enum Version {
//
// V60("6.0"),
//
// V61("6.1"),
//
// V70("7.0"),
//
// V71("7.1"),
//
// V72("7.2"),
//
// V80("8.0"),
//
// V800("8.0.0"),
//
// V801("8.0.1"),
//
// V802("8.0.2"),
//
// V803("8.0.3"),
//
// V804("8.0.4"),
//
// V805("8.0.5"),
//
// V806("8.0.6"),
//
// V807("8.0.7"), // 2014 Spring
//
// V808("8.0.8"), // 2014 Summer
//
// V809("8.0.9"), // 2014 Winter
//
// V8010("8.0.10"), // 2015 Spring
//
// V8011("8.0.11"), // 2015 Summer
//
// V8012("8.0.12"), // 2015 Winter
//
// V8013("8.0.13"), // 2016 Spring
//
// V8014("8.0.14"), // 2016 Summer
//
// V8015("8.0.15"), // 2016 Winter
//
// V8016("8.0.16"); // 2017 Spring
//
//
// private final String name;
//
// private Version(String name) {
// this.name = name;
// }
//
// public static Version toEnum(String name) {
//
// for (Version version : Version.values()) {
// if (version.name.equals(name)) {
// return version;
// }
// }
//
// return null;
// }
//
// public boolean isVersion6() {
// return this == V60 || this == V61;
// }
//
// public boolean isVersion7() {
// return !isVersion6();
// }
//
// public String getName() {
// return name;
// }
// }
// Path: im-log-stats-project/src/main/java/net/mikaboshi/intra_mart/tools/log_stats/report/ReportParameter.java
import net.mikaboshi.intra_mart.tools.log_stats.parser.Version;
/*
* 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.mikaboshi.intra_mart.tools.log_stats.report;
/**
* レポートパラメータ
*
* @version 1.0.15
* @author <a href="https://github.com/cwan">cwan</a>
*/
public class ReportParameter {
/**
* 解析間隔(分)
*/
private long span = 5L;
/**
* セッションタイムアウト時間(分)
*/
private int sessionTimeout = 10;
/**
* リクエスト処理時間ランクの出力件数
*/
private int requestPageTimeRankSize = 20;
/**
* リクエスト処理時間ランクの閾値(ミリ秒)
* @since 1.0.11
*/
private long requestPageTimeRankThresholdMillis = -1L;
/**
* リクエストURLランクの出力件数
*/
private int requestUrlRankSize = 20;
/**
* セッションランクの出力件数
*/
private int sessionRankSize = 20;
/**
* JSSPページパスを表示するかどうか
* @since 1.0.11
*/
private boolean jsspPath = false;
/**
* 最大同時リクエスト数を表示するかどうか
* @since 1.0.13
*/
private boolean maxConcurrentRequest = true;
/**
* レポート名
*/
private String name = "intra-mart ログ統計レポート";
/**
* 署名
*/
private String signature = "";
/** バージョン */ | private Version version = Version.V72; |
cwan/im-log-stats | im-log-stats-project/src/main/java/net/mikaboshi/intra_mart/tools/log_stats/entity/ExceptionLog.java | // Path: im-log-stats-project/src/main/java/net/mikaboshi/intra_mart/tools/log_stats/util/LogStringUtil.java
// public final class LogStringUtil {
//
// private static final Pattern LINE_SPLIT_PATTERN = Pattern.compile("\\r?\\n");
//
// private static final String[] ENPTY_STRING_ARRAY = new String[0];
//
// private static final Pattern TRUNCATE_URL_PATTERN = Pattern.compile("(?:[^(\\:/)]+\\:)?//(?:[^(\\:/)]+)(?:\\:\\d+)?(/.+)");
//
// private LogStringUtil() {}
//
// /**
// * 引数を改行コードで分割する。
// *
// * @param s
// * @return 引数を分割した文字列の配列。引数がnullの場合は、空の配列を返す。
// */
// public static String[] lines(CharSequence s) {
//
// if (s == null) {
// return ENPTY_STRING_ARRAY;
// }
//
// return LINE_SPLIT_PATTERN.split(s);
// }
//
// /**
// * URLからスキーム、ホスト、ポートを削除する。
// * @param url
// * @return
// */
// public static String truncateUrl(String url) {
//
// if (url == null) {
// return StringUtils.EMPTY;
// }
//
// Matcher matcher = TRUNCATE_URL_PATTERN.matcher(url);
//
// if (matcher.matches()) {
// return matcher.group(1);
// } else {
// return url;
// }
// }
//
// /**
// * セッションID、ユーザIDが有効ならばtrueを返す。
// * @since 1.0.21
// * @param id
// * @return
// */
// public static boolean isValidId(String id) {
// return StringUtils.isNotBlank(id) && !"-".equals(id.trim());
// }
//
// }
| import net.mikaboshi.intra_mart.tools.log_stats.util.LogStringUtil;
import org.apache.commons.lang.builder.EqualsBuilder;
import org.apache.commons.lang.builder.HashCodeBuilder; | /*
* 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.mikaboshi.intra_mart.tools.log_stats.entity;
/**
* 例外ログ
*
* @version 1.0.9
* @author <a href="https://github.com/cwan">cwan</a>
*/
public class ExceptionLog extends Log {
/**
* 例外のグルーピングを何で行うか
*
* @since 1.0.8
*/
public static enum GroupingType {
/** スタックトレースの1行目 */
FIEST_LINE,
/** スタックトレースの一番下のCaused by */
CAUSE;
}
/**
* スタックトレース
*/
public String stackTrace = null;
/**
* 例外のグルーピングを何で行うか
*/
public GroupingType groupingType = GroupingType.CAUSE;
/**
* スタックトレースの1行目を取得する。
* @return
*/
public String getFirstLineOfStackTrace() {
if (this.stackTrace == null) {
return null;
}
for (int i = 0; i < this.stackTrace.length(); i++) {
char c = this.stackTrace.charAt(i);
if (c == '\r' || c == '\n' || c == '\t') {
return this.stackTrace.substring(0, i);
}
}
return this.stackTrace;
}
/**
* スタックトレースの発端のCause行を取得する。
* @return
* @since 1.0.8
*/
public String getCauseLineOfStackTrace() {
if (this.stackTrace == null) {
return null;
}
String cause = null;
final String prefix = "Caused by: ";
| // Path: im-log-stats-project/src/main/java/net/mikaboshi/intra_mart/tools/log_stats/util/LogStringUtil.java
// public final class LogStringUtil {
//
// private static final Pattern LINE_SPLIT_PATTERN = Pattern.compile("\\r?\\n");
//
// private static final String[] ENPTY_STRING_ARRAY = new String[0];
//
// private static final Pattern TRUNCATE_URL_PATTERN = Pattern.compile("(?:[^(\\:/)]+\\:)?//(?:[^(\\:/)]+)(?:\\:\\d+)?(/.+)");
//
// private LogStringUtil() {}
//
// /**
// * 引数を改行コードで分割する。
// *
// * @param s
// * @return 引数を分割した文字列の配列。引数がnullの場合は、空の配列を返す。
// */
// public static String[] lines(CharSequence s) {
//
// if (s == null) {
// return ENPTY_STRING_ARRAY;
// }
//
// return LINE_SPLIT_PATTERN.split(s);
// }
//
// /**
// * URLからスキーム、ホスト、ポートを削除する。
// * @param url
// * @return
// */
// public static String truncateUrl(String url) {
//
// if (url == null) {
// return StringUtils.EMPTY;
// }
//
// Matcher matcher = TRUNCATE_URL_PATTERN.matcher(url);
//
// if (matcher.matches()) {
// return matcher.group(1);
// } else {
// return url;
// }
// }
//
// /**
// * セッションID、ユーザIDが有効ならばtrueを返す。
// * @since 1.0.21
// * @param id
// * @return
// */
// public static boolean isValidId(String id) {
// return StringUtils.isNotBlank(id) && !"-".equals(id.trim());
// }
//
// }
// Path: im-log-stats-project/src/main/java/net/mikaboshi/intra_mart/tools/log_stats/entity/ExceptionLog.java
import net.mikaboshi.intra_mart.tools.log_stats.util.LogStringUtil;
import org.apache.commons.lang.builder.EqualsBuilder;
import org.apache.commons.lang.builder.HashCodeBuilder;
/*
* 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.mikaboshi.intra_mart.tools.log_stats.entity;
/**
* 例外ログ
*
* @version 1.0.9
* @author <a href="https://github.com/cwan">cwan</a>
*/
public class ExceptionLog extends Log {
/**
* 例外のグルーピングを何で行うか
*
* @since 1.0.8
*/
public static enum GroupingType {
/** スタックトレースの1行目 */
FIEST_LINE,
/** スタックトレースの一番下のCaused by */
CAUSE;
}
/**
* スタックトレース
*/
public String stackTrace = null;
/**
* 例外のグルーピングを何で行うか
*/
public GroupingType groupingType = GroupingType.CAUSE;
/**
* スタックトレースの1行目を取得する。
* @return
*/
public String getFirstLineOfStackTrace() {
if (this.stackTrace == null) {
return null;
}
for (int i = 0; i < this.stackTrace.length(); i++) {
char c = this.stackTrace.charAt(i);
if (c == '\r' || c == '\n' || c == '\t') {
return this.stackTrace.substring(0, i);
}
}
return this.stackTrace;
}
/**
* スタックトレースの発端のCause行を取得する。
* @return
* @since 1.0.8
*/
public String getCauseLineOfStackTrace() {
if (this.stackTrace == null) {
return null;
}
String cause = null;
final String prefix = "Caused by: ";
| for (String line : LogStringUtil.lines(this.stackTrace)) { |
Nurdok/Jools | src/com/rachum/amir/util/index/test/IndexTest.java | // Path: src/com/rachum/amir/util/index/IndexedElement.java
// public class IndexedElement<T> {
// private final T element;
// private final int index;
//
// public IndexedElement(final T element, final int index) {
// this.element = element;
// this.index = index;
// }
//
// /**
// * @return the element
// */
// public T getElement() {
// return element;
// }
//
// /**
// * @return the index
// */
// public int getIndex() {
// return index;
// }
//
// }
//
// Path: src/com/rachum/amir/util/index/Indexer.java
// public class Indexer<T> implements Iterable<IndexedElement<T>>, Iterator<IndexedElement<T>> {
// private int index = 0;
// private final Iterator<T> iterator;
//
// public Indexer(final Iterable<T> wrapped) {
// super();
// this.iterator = wrapped.iterator();
// }
//
// @Override
// public Iterator<IndexedElement<T>> iterator() {
// return this;
// }
//
// @Override
// public boolean hasNext() {
// return iterator.hasNext();
// }
//
// @Override
// public IndexedElement<T> next() {
// return new IndexedElement<T>(iterator.next(), index++);
// }
//
// @Override
// public void remove() {
// //TODO: index?
// //TODO: throw exception?
// iterator.remove();
// }
//
// }
| import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;
import java.util.Arrays;
import java.util.Iterator;
import java.util.List;
import org.junit.Test;
import com.rachum.amir.util.index.IndexedElement;
import com.rachum.amir.util.index.Indexer; | /**
*
*/
package com.rachum.amir.util.index.test;
/**
* @author Rachum
*
*/
public class IndexTest {
@Test
public void loopTest() {
int i=0;
final List<String> list = Arrays.asList("A", "B", "C", "D", "E");
final Iterator<String> it = list.iterator(); | // Path: src/com/rachum/amir/util/index/IndexedElement.java
// public class IndexedElement<T> {
// private final T element;
// private final int index;
//
// public IndexedElement(final T element, final int index) {
// this.element = element;
// this.index = index;
// }
//
// /**
// * @return the element
// */
// public T getElement() {
// return element;
// }
//
// /**
// * @return the index
// */
// public int getIndex() {
// return index;
// }
//
// }
//
// Path: src/com/rachum/amir/util/index/Indexer.java
// public class Indexer<T> implements Iterable<IndexedElement<T>>, Iterator<IndexedElement<T>> {
// private int index = 0;
// private final Iterator<T> iterator;
//
// public Indexer(final Iterable<T> wrapped) {
// super();
// this.iterator = wrapped.iterator();
// }
//
// @Override
// public Iterator<IndexedElement<T>> iterator() {
// return this;
// }
//
// @Override
// public boolean hasNext() {
// return iterator.hasNext();
// }
//
// @Override
// public IndexedElement<T> next() {
// return new IndexedElement<T>(iterator.next(), index++);
// }
//
// @Override
// public void remove() {
// //TODO: index?
// //TODO: throw exception?
// iterator.remove();
// }
//
// }
// Path: src/com/rachum/amir/util/index/test/IndexTest.java
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;
import java.util.Arrays;
import java.util.Iterator;
import java.util.List;
import org.junit.Test;
import com.rachum.amir.util.index.IndexedElement;
import com.rachum.amir.util.index.Indexer;
/**
*
*/
package com.rachum.amir.util.index.test;
/**
* @author Rachum
*
*/
public class IndexTest {
@Test
public void loopTest() {
int i=0;
final List<String> list = Arrays.asList("A", "B", "C", "D", "E");
final Iterator<String> it = list.iterator(); | for (final IndexedElement<String> element : new Indexer<String>(list)) { |
Nurdok/Jools | src/com/rachum/amir/util/index/test/IndexTest.java | // Path: src/com/rachum/amir/util/index/IndexedElement.java
// public class IndexedElement<T> {
// private final T element;
// private final int index;
//
// public IndexedElement(final T element, final int index) {
// this.element = element;
// this.index = index;
// }
//
// /**
// * @return the element
// */
// public T getElement() {
// return element;
// }
//
// /**
// * @return the index
// */
// public int getIndex() {
// return index;
// }
//
// }
//
// Path: src/com/rachum/amir/util/index/Indexer.java
// public class Indexer<T> implements Iterable<IndexedElement<T>>, Iterator<IndexedElement<T>> {
// private int index = 0;
// private final Iterator<T> iterator;
//
// public Indexer(final Iterable<T> wrapped) {
// super();
// this.iterator = wrapped.iterator();
// }
//
// @Override
// public Iterator<IndexedElement<T>> iterator() {
// return this;
// }
//
// @Override
// public boolean hasNext() {
// return iterator.hasNext();
// }
//
// @Override
// public IndexedElement<T> next() {
// return new IndexedElement<T>(iterator.next(), index++);
// }
//
// @Override
// public void remove() {
// //TODO: index?
// //TODO: throw exception?
// iterator.remove();
// }
//
// }
| import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;
import java.util.Arrays;
import java.util.Iterator;
import java.util.List;
import org.junit.Test;
import com.rachum.amir.util.index.IndexedElement;
import com.rachum.amir.util.index.Indexer; | /**
*
*/
package com.rachum.amir.util.index.test;
/**
* @author Rachum
*
*/
public class IndexTest {
@Test
public void loopTest() {
int i=0;
final List<String> list = Arrays.asList("A", "B", "C", "D", "E");
final Iterator<String> it = list.iterator(); | // Path: src/com/rachum/amir/util/index/IndexedElement.java
// public class IndexedElement<T> {
// private final T element;
// private final int index;
//
// public IndexedElement(final T element, final int index) {
// this.element = element;
// this.index = index;
// }
//
// /**
// * @return the element
// */
// public T getElement() {
// return element;
// }
//
// /**
// * @return the index
// */
// public int getIndex() {
// return index;
// }
//
// }
//
// Path: src/com/rachum/amir/util/index/Indexer.java
// public class Indexer<T> implements Iterable<IndexedElement<T>>, Iterator<IndexedElement<T>> {
// private int index = 0;
// private final Iterator<T> iterator;
//
// public Indexer(final Iterable<T> wrapped) {
// super();
// this.iterator = wrapped.iterator();
// }
//
// @Override
// public Iterator<IndexedElement<T>> iterator() {
// return this;
// }
//
// @Override
// public boolean hasNext() {
// return iterator.hasNext();
// }
//
// @Override
// public IndexedElement<T> next() {
// return new IndexedElement<T>(iterator.next(), index++);
// }
//
// @Override
// public void remove() {
// //TODO: index?
// //TODO: throw exception?
// iterator.remove();
// }
//
// }
// Path: src/com/rachum/amir/util/index/test/IndexTest.java
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;
import java.util.Arrays;
import java.util.Iterator;
import java.util.List;
import org.junit.Test;
import com.rachum.amir.util.index.IndexedElement;
import com.rachum.amir.util.index.Indexer;
/**
*
*/
package com.rachum.amir.util.index.test;
/**
* @author Rachum
*
*/
public class IndexTest {
@Test
public void loopTest() {
int i=0;
final List<String> list = Arrays.asList("A", "B", "C", "D", "E");
final Iterator<String> it = list.iterator(); | for (final IndexedElement<String> element : new Indexer<String>(list)) { |
Nurdok/Jools | src/com/rachum/amir/util/range/example/Example.java | // Path: src/com/rachum/amir/util/range/Range.java
// public class Range implements Iterable<Integer>, Iterator<Integer> {
// final int start, stop, step;
// int next;
//
//
// public Range(final Integer stop) {
// this(0, stop, 1);
// }
//
// public Range(final Integer start, final Integer stop) {
// this(start, stop, 1);
// }
//
// public Range(final Integer start, final Integer stop, final Integer step) {
// if (step.equals(0)) {
// throw new IllegalArgumentException();
// }
// this.start = start;
// this.stop = stop;
// this.step = step;
// this.next = start;
// }
//
// public List<Integer> toList() {
// final List<Integer> list = new ArrayList<Integer>();
// for (int i=start; (step > 0) ? i<stop : i>stop; i+=step) {
// list.add(i);
// }
// return list;
// }
//
// @Override
// public boolean hasNext() {
// return (next != stop);
// }
//
// @Override
// public Integer next() {
// if (next == stop) {
// throw new NoSuchElementException();
// }
// final Integer ret = next;
// next += step;
// return ret;
// }
//
// @Override
// public void remove() {
// throw new UnsupportedOperationException();
// }
//
// @Override
// public Iterator<Integer> iterator() {
// return this;
// }
//
// }
| import com.rachum.amir.util.range.Range; | /**
*
*/
package com.rachum.amir.util.range.example;
/**
* @author Rachum
*
*/
public class Example {
/**
* @param args
*/
public static void main(final String[] args) { | // Path: src/com/rachum/amir/util/range/Range.java
// public class Range implements Iterable<Integer>, Iterator<Integer> {
// final int start, stop, step;
// int next;
//
//
// public Range(final Integer stop) {
// this(0, stop, 1);
// }
//
// public Range(final Integer start, final Integer stop) {
// this(start, stop, 1);
// }
//
// public Range(final Integer start, final Integer stop, final Integer step) {
// if (step.equals(0)) {
// throw new IllegalArgumentException();
// }
// this.start = start;
// this.stop = stop;
// this.step = step;
// this.next = start;
// }
//
// public List<Integer> toList() {
// final List<Integer> list = new ArrayList<Integer>();
// for (int i=start; (step > 0) ? i<stop : i>stop; i+=step) {
// list.add(i);
// }
// return list;
// }
//
// @Override
// public boolean hasNext() {
// return (next != stop);
// }
//
// @Override
// public Integer next() {
// if (next == stop) {
// throw new NoSuchElementException();
// }
// final Integer ret = next;
// next += step;
// return ret;
// }
//
// @Override
// public void remove() {
// throw new UnsupportedOperationException();
// }
//
// @Override
// public Iterator<Integer> iterator() {
// return this;
// }
//
// }
// Path: src/com/rachum/amir/util/range/example/Example.java
import com.rachum.amir.util.range.Range;
/**
*
*/
package com.rachum.amir.util.range.example;
/**
* @author Rachum
*
*/
public class Example {
/**
* @param args
*/
public static void main(final String[] args) { | for (final int i : new Range(0,10,2)) { |
Nurdok/Jools | src/com/rachum/amir/util/index/example/Example.java | // Path: src/com/rachum/amir/util/index/IndexedElement.java
// public class IndexedElement<T> {
// private final T element;
// private final int index;
//
// public IndexedElement(final T element, final int index) {
// this.element = element;
// this.index = index;
// }
//
// /**
// * @return the element
// */
// public T getElement() {
// return element;
// }
//
// /**
// * @return the index
// */
// public int getIndex() {
// return index;
// }
//
// }
//
// Path: src/com/rachum/amir/util/index/Indexer.java
// public class Indexer<T> implements Iterable<IndexedElement<T>>, Iterator<IndexedElement<T>> {
// private int index = 0;
// private final Iterator<T> iterator;
//
// public Indexer(final Iterable<T> wrapped) {
// super();
// this.iterator = wrapped.iterator();
// }
//
// @Override
// public Iterator<IndexedElement<T>> iterator() {
// return this;
// }
//
// @Override
// public boolean hasNext() {
// return iterator.hasNext();
// }
//
// @Override
// public IndexedElement<T> next() {
// return new IndexedElement<T>(iterator.next(), index++);
// }
//
// @Override
// public void remove() {
// //TODO: index?
// //TODO: throw exception?
// iterator.remove();
// }
//
// }
| import com.rachum.amir.util.index.IndexedElement;
import com.rachum.amir.util.index.Indexer;
import java.util.Arrays;
import java.util.List; | /**
*
*/
package com.rachum.amir.util.index.example;
/**
* @author Rachum
*
*/
public class Example {
/**
* @param args
*/
public static void main(final String[] args) {
final List<String> list = Arrays.asList("A", "B", "C", "D", "E", "F", "G"); | // Path: src/com/rachum/amir/util/index/IndexedElement.java
// public class IndexedElement<T> {
// private final T element;
// private final int index;
//
// public IndexedElement(final T element, final int index) {
// this.element = element;
// this.index = index;
// }
//
// /**
// * @return the element
// */
// public T getElement() {
// return element;
// }
//
// /**
// * @return the index
// */
// public int getIndex() {
// return index;
// }
//
// }
//
// Path: src/com/rachum/amir/util/index/Indexer.java
// public class Indexer<T> implements Iterable<IndexedElement<T>>, Iterator<IndexedElement<T>> {
// private int index = 0;
// private final Iterator<T> iterator;
//
// public Indexer(final Iterable<T> wrapped) {
// super();
// this.iterator = wrapped.iterator();
// }
//
// @Override
// public Iterator<IndexedElement<T>> iterator() {
// return this;
// }
//
// @Override
// public boolean hasNext() {
// return iterator.hasNext();
// }
//
// @Override
// public IndexedElement<T> next() {
// return new IndexedElement<T>(iterator.next(), index++);
// }
//
// @Override
// public void remove() {
// //TODO: index?
// //TODO: throw exception?
// iterator.remove();
// }
//
// }
// Path: src/com/rachum/amir/util/index/example/Example.java
import com.rachum.amir.util.index.IndexedElement;
import com.rachum.amir.util.index.Indexer;
import java.util.Arrays;
import java.util.List;
/**
*
*/
package com.rachum.amir.util.index.example;
/**
* @author Rachum
*
*/
public class Example {
/**
* @param args
*/
public static void main(final String[] args) {
final List<String> list = Arrays.asList("A", "B", "C", "D", "E", "F", "G"); | for (final IndexedElement<String> element : new Indexer<String>(list)) { |
Nurdok/Jools | src/com/rachum/amir/util/index/example/Example.java | // Path: src/com/rachum/amir/util/index/IndexedElement.java
// public class IndexedElement<T> {
// private final T element;
// private final int index;
//
// public IndexedElement(final T element, final int index) {
// this.element = element;
// this.index = index;
// }
//
// /**
// * @return the element
// */
// public T getElement() {
// return element;
// }
//
// /**
// * @return the index
// */
// public int getIndex() {
// return index;
// }
//
// }
//
// Path: src/com/rachum/amir/util/index/Indexer.java
// public class Indexer<T> implements Iterable<IndexedElement<T>>, Iterator<IndexedElement<T>> {
// private int index = 0;
// private final Iterator<T> iterator;
//
// public Indexer(final Iterable<T> wrapped) {
// super();
// this.iterator = wrapped.iterator();
// }
//
// @Override
// public Iterator<IndexedElement<T>> iterator() {
// return this;
// }
//
// @Override
// public boolean hasNext() {
// return iterator.hasNext();
// }
//
// @Override
// public IndexedElement<T> next() {
// return new IndexedElement<T>(iterator.next(), index++);
// }
//
// @Override
// public void remove() {
// //TODO: index?
// //TODO: throw exception?
// iterator.remove();
// }
//
// }
| import com.rachum.amir.util.index.IndexedElement;
import com.rachum.amir.util.index.Indexer;
import java.util.Arrays;
import java.util.List; | /**
*
*/
package com.rachum.amir.util.index.example;
/**
* @author Rachum
*
*/
public class Example {
/**
* @param args
*/
public static void main(final String[] args) {
final List<String> list = Arrays.asList("A", "B", "C", "D", "E", "F", "G"); | // Path: src/com/rachum/amir/util/index/IndexedElement.java
// public class IndexedElement<T> {
// private final T element;
// private final int index;
//
// public IndexedElement(final T element, final int index) {
// this.element = element;
// this.index = index;
// }
//
// /**
// * @return the element
// */
// public T getElement() {
// return element;
// }
//
// /**
// * @return the index
// */
// public int getIndex() {
// return index;
// }
//
// }
//
// Path: src/com/rachum/amir/util/index/Indexer.java
// public class Indexer<T> implements Iterable<IndexedElement<T>>, Iterator<IndexedElement<T>> {
// private int index = 0;
// private final Iterator<T> iterator;
//
// public Indexer(final Iterable<T> wrapped) {
// super();
// this.iterator = wrapped.iterator();
// }
//
// @Override
// public Iterator<IndexedElement<T>> iterator() {
// return this;
// }
//
// @Override
// public boolean hasNext() {
// return iterator.hasNext();
// }
//
// @Override
// public IndexedElement<T> next() {
// return new IndexedElement<T>(iterator.next(), index++);
// }
//
// @Override
// public void remove() {
// //TODO: index?
// //TODO: throw exception?
// iterator.remove();
// }
//
// }
// Path: src/com/rachum/amir/util/index/example/Example.java
import com.rachum.amir.util.index.IndexedElement;
import com.rachum.amir.util.index.Indexer;
import java.util.Arrays;
import java.util.List;
/**
*
*/
package com.rachum.amir.util.index.example;
/**
* @author Rachum
*
*/
public class Example {
/**
* @param args
*/
public static void main(final String[] args) {
final List<String> list = Arrays.asList("A", "B", "C", "D", "E", "F", "G"); | for (final IndexedElement<String> element : new Indexer<String>(list)) { |
uiuc-ischool-scanr/SAIL | src/sentinets/ParseTweet.java | // Path: src/sentinets/DictionaryFeatures.java
// public static class TweetObject{
// private List<String> tokens;
// private HashMap<String, Integer> lexicalScores;
// public TweetObject(String text) {
// // TODO Auto-generated constructor stub
// text = text.replaceAll("[^ -~]", "");
// this.tokens = Twokenize.tokenizeRawTweetText(text);
// //this.tokens = Arrays.asList(text.split("\\s"));
// }
// public void setTokens(List<String> tokens){
// this.tokens = tokens;
// }
//
// public List<String> getTokens(){
// return tokens;
// }
//
// public String getText(){
// return StringUtils.join(this.tokens, " ");
// }
// /**
// * @return the lexicalScores
// */
// public HashMap<String, Integer> getLexicalScores() {
// return lexicalScores;
// }
// /**
// * @param lexicalScores the lexicalScores to set
// */
// public void setLexicalScores(HashMap<String, Integer> lexicalScores) {
// this.lexicalScores = lexicalScores;
// }
//
// }
| import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.regex.Matcher;
import sentinets.DictionaryFeatures.TweetObject;
import twitter4j.Status;
import com.twitter.Extractor;
import com.twitter.Extractor.Entity; | /*******************************************************************************
* Copyright (c) 2015 University of Illinois Board of Trustees, All rights reserved.
* Developed at GSLIS/ the iSchool, by Dr. Jana Diesner, Shubhanshu Mishra, Liang Tao, and Chieh-Li Chin.
* 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 any later version.
* This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details.
* You should have received a copy of the GNU General Public License along with this program; if not, see <http://www.gnu.org/licenses>.
*******************************************************************************/
package sentinets;
public class ParseTweet {
Status tweet;
String parsed_text, tweet_text, url, user, published_date;
int length,c_emo,c_hash,c_url,c_mention,c_quote;
ArrayList<String> m_emo, m_hash, m_url, m_mention;
POSFeatures pf; | // Path: src/sentinets/DictionaryFeatures.java
// public static class TweetObject{
// private List<String> tokens;
// private HashMap<String, Integer> lexicalScores;
// public TweetObject(String text) {
// // TODO Auto-generated constructor stub
// text = text.replaceAll("[^ -~]", "");
// this.tokens = Twokenize.tokenizeRawTweetText(text);
// //this.tokens = Arrays.asList(text.split("\\s"));
// }
// public void setTokens(List<String> tokens){
// this.tokens = tokens;
// }
//
// public List<String> getTokens(){
// return tokens;
// }
//
// public String getText(){
// return StringUtils.join(this.tokens, " ");
// }
// /**
// * @return the lexicalScores
// */
// public HashMap<String, Integer> getLexicalScores() {
// return lexicalScores;
// }
// /**
// * @param lexicalScores the lexicalScores to set
// */
// public void setLexicalScores(HashMap<String, Integer> lexicalScores) {
// this.lexicalScores = lexicalScores;
// }
//
// }
// Path: src/sentinets/ParseTweet.java
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.regex.Matcher;
import sentinets.DictionaryFeatures.TweetObject;
import twitter4j.Status;
import com.twitter.Extractor;
import com.twitter.Extractor.Entity;
/*******************************************************************************
* Copyright (c) 2015 University of Illinois Board of Trustees, All rights reserved.
* Developed at GSLIS/ the iSchool, by Dr. Jana Diesner, Shubhanshu Mishra, Liang Tao, and Chieh-Li Chin.
* 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 any later version.
* This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details.
* You should have received a copy of the GNU General Public License along with this program; if not, see <http://www.gnu.org/licenses>.
*******************************************************************************/
package sentinets;
public class ParseTweet {
Status tweet;
String parsed_text, tweet_text, url, user, published_date;
int length,c_emo,c_hash,c_url,c_mention,c_quote;
ArrayList<String> m_emo, m_hash, m_url, m_mention;
POSFeatures pf; | TweetObject to; |
kyleduo/Rabbits | Rabbits/rabbits/src/main/java/com/kyleduo/rabbits/Rabbit.java | // Path: Rabbits/rabbits/src/main/java/com/kyleduo/rabbits/rules/Rule.java
// public interface Rule {
// enum Operator {
// IS, STARTS_WITH, ENDS_WITH, IN, CONTAINS, EXISTS
// }
//
// boolean verify(Action action);
// }
| import android.app.Activity;
import android.content.Context;
import android.support.v4.app.Fragment;
import android.util.SparseArray;
import com.kyleduo.rabbits.rules.Rule;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.List; | throw new IllegalArgumentException("From object must be whether an Context or a Fragment instance.");
}
return new Builder(from);
}
/**
* Add an interceptor used for this navigation. This is useful when you want to check whether a
* uri matches a specific page using method.
*
* @param interceptor Interceptor instance.
* @return Rabbit instance.
*/
public Rabbit addInterceptor(Interceptor interceptor) {
if (mInterceptors == null) {
mInterceptors = new ArrayList<>();
}
mInterceptors.add(interceptor);
return this;
}
public Rabbit registerNavigator(int type, Navigator navigator) {
mNavigators.put(type, navigator);
return this;
}
public Rabbit registerFallbackNavigator(Navigator navigator) {
mNavigators.put(TargetInfo.TYPE_NONE, navigator);
return this;
}
| // Path: Rabbits/rabbits/src/main/java/com/kyleduo/rabbits/rules/Rule.java
// public interface Rule {
// enum Operator {
// IS, STARTS_WITH, ENDS_WITH, IN, CONTAINS, EXISTS
// }
//
// boolean verify(Action action);
// }
// Path: Rabbits/rabbits/src/main/java/com/kyleduo/rabbits/Rabbit.java
import android.app.Activity;
import android.content.Context;
import android.support.v4.app.Fragment;
import android.util.SparseArray;
import com.kyleduo.rabbits.rules.Rule;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.List;
throw new IllegalArgumentException("From object must be whether an Context or a Fragment instance.");
}
return new Builder(from);
}
/**
* Add an interceptor used for this navigation. This is useful when you want to check whether a
* uri matches a specific page using method.
*
* @param interceptor Interceptor instance.
* @return Rabbit instance.
*/
public Rabbit addInterceptor(Interceptor interceptor) {
if (mInterceptors == null) {
mInterceptors = new ArrayList<>();
}
mInterceptors.add(interceptor);
return this;
}
public Rabbit registerNavigator(int type, Navigator navigator) {
mNavigators.put(type, navigator);
return this;
}
public Rabbit registerFallbackNavigator(Navigator navigator) {
mNavigators.put(TargetInfo.TYPE_NONE, navigator);
return this;
}
| public Rabbit addInterceptor(Interceptor interceptor, Rule rule) { |
kyleduo/Rabbits | Rabbits/rabbits/src/main/java/com/kyleduo/rabbits/Navigation.java | // Path: Rabbits/rabbits/src/main/java/com/kyleduo/rabbits/rules/Rule.java
// public interface Rule {
// enum Operator {
// IS, STARTS_WITH, ENDS_WITH, IN, CONTAINS, EXISTS
// }
//
// boolean verify(Action action);
// }
| import android.os.Bundle;
import android.support.annotation.NonNull;
import com.kyleduo.rabbits.rules.Rule;
import java.util.Map; | package com.kyleduo.rabbits;
/**
* Represent a Navigation into which the caller put extras and configures and perform the navigation.
*
* Created by kyle on 26/01/2018.
*/
@SuppressWarnings("unused")
public interface Navigation {
Navigation addIntentFlags(int flags);
Navigation setIntentFlags(int flags);
Navigation newTask();
Navigation clearTop();
Navigation singleTop();
Navigation putExtra(@NonNull String key, Object value);
Navigation putExtras(Bundle bundle);
Navigation putExtras(Map<String, Object> extras);
Navigation addInterceptor(Interceptor interceptor);
| // Path: Rabbits/rabbits/src/main/java/com/kyleduo/rabbits/rules/Rule.java
// public interface Rule {
// enum Operator {
// IS, STARTS_WITH, ENDS_WITH, IN, CONTAINS, EXISTS
// }
//
// boolean verify(Action action);
// }
// Path: Rabbits/rabbits/src/main/java/com/kyleduo/rabbits/Navigation.java
import android.os.Bundle;
import android.support.annotation.NonNull;
import com.kyleduo.rabbits.rules.Rule;
import java.util.Map;
package com.kyleduo.rabbits;
/**
* Represent a Navigation into which the caller put extras and configures and perform the navigation.
*
* Created by kyle on 26/01/2018.
*/
@SuppressWarnings("unused")
public interface Navigation {
Navigation addIntentFlags(int flags);
Navigation setIntentFlags(int flags);
Navigation newTask();
Navigation clearTop();
Navigation singleTop();
Navigation putExtra(@NonNull String key, Object value);
Navigation putExtras(Bundle bundle);
Navigation putExtras(Map<String, Object> extras);
Navigation addInterceptor(Interceptor interceptor);
| Navigation addInterceptor(Interceptor interceptor, Rule rule); |
kyleduo/Rabbits | Rabbits/rabbits/src/main/java/com/kyleduo/rabbits/AbstractNavigation.java | // Path: Rabbits/rabbits/src/main/java/com/kyleduo/rabbits/rules/Rule.java
// public interface Rule {
// enum Operator {
// IS, STARTS_WITH, ENDS_WITH, IN, CONTAINS, EXISTS
// }
//
// boolean verify(Action action);
// }
| import android.content.Intent;
import android.os.Build;
import android.os.Bundle;
import android.os.Parcelable;
import android.support.annotation.NonNull;
import android.text.ParcelableSpan;
import android.util.Size;
import android.util.SizeF;
import android.util.SparseArray;
import com.kyleduo.rabbits.rules.Rule;
import java.io.Serializable;
import java.lang.reflect.Type;
import java.util.ArrayList;
import java.util.List;
import java.util.Map; | putExtra(e.getKey(), e.getValue());
}
}
return this;
}
@Override
public Navigation ignoreInterceptors() {
mAction.setIgnoreInterceptors(true);
return this;
}
@Override
public Navigation ignoreFallback() {
mAction.setIgnoreFallback(true);
return this;
}
@Override
public Navigation addInterceptor(Interceptor interceptor) {
List<Interceptor> l = action().getInterceptors();
if (l == null) {
l = new ArrayList<>();
action().setInterceptors(l);
}
l.add(interceptor);
return this;
}
@Override | // Path: Rabbits/rabbits/src/main/java/com/kyleduo/rabbits/rules/Rule.java
// public interface Rule {
// enum Operator {
// IS, STARTS_WITH, ENDS_WITH, IN, CONTAINS, EXISTS
// }
//
// boolean verify(Action action);
// }
// Path: Rabbits/rabbits/src/main/java/com/kyleduo/rabbits/AbstractNavigation.java
import android.content.Intent;
import android.os.Build;
import android.os.Bundle;
import android.os.Parcelable;
import android.support.annotation.NonNull;
import android.text.ParcelableSpan;
import android.util.Size;
import android.util.SizeF;
import android.util.SparseArray;
import com.kyleduo.rabbits.rules.Rule;
import java.io.Serializable;
import java.lang.reflect.Type;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
putExtra(e.getKey(), e.getValue());
}
}
return this;
}
@Override
public Navigation ignoreInterceptors() {
mAction.setIgnoreInterceptors(true);
return this;
}
@Override
public Navigation ignoreFallback() {
mAction.setIgnoreFallback(true);
return this;
}
@Override
public Navigation addInterceptor(Interceptor interceptor) {
List<Interceptor> l = action().getInterceptors();
if (l == null) {
l = new ArrayList<>();
action().setInterceptors(l);
}
l.add(interceptor);
return this;
}
@Override | public Navigation addInterceptor(Interceptor interceptor, Rule rule) { |
kyleduo/Rabbits | Rabbits/rabbits/src/main/java/com/kyleduo/rabbits/PatternInterceptor.java | // Path: Rabbits/rabbits/src/main/java/com/kyleduo/rabbits/rules/Rule.java
// public interface Rule {
// enum Operator {
// IS, STARTS_WITH, ENDS_WITH, IN, CONTAINS, EXISTS
// }
//
// boolean verify(Action action);
// }
| import com.kyleduo.rabbits.rules.Rule; | package com.kyleduo.rabbits;
/**
* Used for Interceptor which wants to be invoked when the url match the pattern
*
* Created by kyle on 30/01/2018.
*/
final class PatternInterceptor implements Interceptor {
private Interceptor mInterceptor; | // Path: Rabbits/rabbits/src/main/java/com/kyleduo/rabbits/rules/Rule.java
// public interface Rule {
// enum Operator {
// IS, STARTS_WITH, ENDS_WITH, IN, CONTAINS, EXISTS
// }
//
// boolean verify(Action action);
// }
// Path: Rabbits/rabbits/src/main/java/com/kyleduo/rabbits/PatternInterceptor.java
import com.kyleduo.rabbits.rules.Rule;
package com.kyleduo.rabbits;
/**
* Used for Interceptor which wants to be invoked when the url match the pattern
*
* Created by kyle on 30/01/2018.
*/
final class PatternInterceptor implements Interceptor {
private Interceptor mInterceptor; | private Rule mRule; |
jasonwyatt/SQLite-Performance | app/src/main/java/co/jasonwyatt/sqliteperf/inserts/tracks/InsertsTestCase.java | // Path: app/src/main/java/co/jasonwyatt/sqliteperf/App.java
// public class App extends Application {
// private static App sInstance;
//
// @Override
// public void onCreate() {
// super.onCreate();
// sInstance = this;
// }
//
// public static App getInstance() {
// return sInstance;
// }
// }
//
// Path: app/src/main/java/co/jasonwyatt/sqliteperf/TestCase.java
// public interface TestCase {
// void resetCase();
// Metrics runCase();
//
// class Metrics {
// private final String mName;
// private final float mVariable;
// private int mIterations = 1;
// private long mStartTime;
// private long mEndTime;
// private long mElapsedTime;
//
// public Metrics(String name, float variable) {
// mName = name;
// mVariable = variable;
// }
//
// Metrics(List<Metrics> iterations) {
// mName = iterations.get(0).mName;
// mVariable = iterations.get(0).mVariable;
// mIterations = iterations.size();
// mElapsedTime = 0;
// for (Metrics m : iterations) {
// mElapsedTime += m.mElapsedTime;
// }
// mElapsedTime = (long) (mElapsedTime*1.0f / iterations.size());
// }
//
// public void started() {
// mStartTime = System.nanoTime();
// }
//
// public void finished() {
// mEndTime = System.nanoTime();
// mElapsedTime = mEndTime - mStartTime;
// }
//
// @Override
// public String toString() {
// StringBuilder sb = new StringBuilder();
// sb.append(mName);
// sb.append(":\n");
// if (mIterations > 1) {
// sb.append(mIterations);
// sb.append(" iterations, each averaged ");
// } else {
// sb.append("took ");
// }
// sb.append(((float) mElapsedTime / mIterations) / 1000000f);
// sb.append(" seconds");
// return sb.toString();
// }
//
// public float getVariable() {
// return mVariable;
// }
//
// public long getElapsedTime() {
// return mElapsedTime;
// }
// }
//
// }
//
// Path: app/src/main/java/co/jasonwyatt/sqliteperf/inserts/DbHelper.java
// public class DbHelper extends SQLiteOpenHelper {
// public DbHelper(Context context, String name) {
// super(context, name, null, 1);
// }
//
// @Override
// public void onCreate(SQLiteDatabase db) {
// db.execSQL("CREATE TABLE inserts_1 (val INTEGER)");
// db.execSQL("CREATE TABLE tracks (id INTEGER PRIMARY KEY, title TEXT, band_id INTEGER, duration FLOAT, url TEXT, lyrics TEXT, about TEXT, release_date INTEGER, mod_date INTEGER)");
// }
//
// @Override
// public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {}
// }
| import android.content.ContentValues;
import android.database.sqlite.SQLiteDatabase;
import java.nio.charset.Charset;
import java.util.Random;
import co.jasonwyatt.sqliteperf.App;
import co.jasonwyatt.sqliteperf.TestCase;
import co.jasonwyatt.sqliteperf.inserts.DbHelper; | package co.jasonwyatt.sqliteperf.inserts.tracks;
/**
* @author jason
*/
public class InsertsTestCase implements TestCase {
private DbHelper mDbHelper;
private final Random mRandom;
private final int mInsertions;
private final int mTestSizeIndex;
public InsertsTestCase(int insertions, int testSizeIndex) {
mRandom = new Random(System.currentTimeMillis());
mInsertions = insertions;
mTestSizeIndex = testSizeIndex;
}
@Override
public void resetCase() {
mDbHelper.getWritableDatabase().execSQL("delete from tracks");
mDbHelper.close();
}
@Override
public Metrics runCase() { | // Path: app/src/main/java/co/jasonwyatt/sqliteperf/App.java
// public class App extends Application {
// private static App sInstance;
//
// @Override
// public void onCreate() {
// super.onCreate();
// sInstance = this;
// }
//
// public static App getInstance() {
// return sInstance;
// }
// }
//
// Path: app/src/main/java/co/jasonwyatt/sqliteperf/TestCase.java
// public interface TestCase {
// void resetCase();
// Metrics runCase();
//
// class Metrics {
// private final String mName;
// private final float mVariable;
// private int mIterations = 1;
// private long mStartTime;
// private long mEndTime;
// private long mElapsedTime;
//
// public Metrics(String name, float variable) {
// mName = name;
// mVariable = variable;
// }
//
// Metrics(List<Metrics> iterations) {
// mName = iterations.get(0).mName;
// mVariable = iterations.get(0).mVariable;
// mIterations = iterations.size();
// mElapsedTime = 0;
// for (Metrics m : iterations) {
// mElapsedTime += m.mElapsedTime;
// }
// mElapsedTime = (long) (mElapsedTime*1.0f / iterations.size());
// }
//
// public void started() {
// mStartTime = System.nanoTime();
// }
//
// public void finished() {
// mEndTime = System.nanoTime();
// mElapsedTime = mEndTime - mStartTime;
// }
//
// @Override
// public String toString() {
// StringBuilder sb = new StringBuilder();
// sb.append(mName);
// sb.append(":\n");
// if (mIterations > 1) {
// sb.append(mIterations);
// sb.append(" iterations, each averaged ");
// } else {
// sb.append("took ");
// }
// sb.append(((float) mElapsedTime / mIterations) / 1000000f);
// sb.append(" seconds");
// return sb.toString();
// }
//
// public float getVariable() {
// return mVariable;
// }
//
// public long getElapsedTime() {
// return mElapsedTime;
// }
// }
//
// }
//
// Path: app/src/main/java/co/jasonwyatt/sqliteperf/inserts/DbHelper.java
// public class DbHelper extends SQLiteOpenHelper {
// public DbHelper(Context context, String name) {
// super(context, name, null, 1);
// }
//
// @Override
// public void onCreate(SQLiteDatabase db) {
// db.execSQL("CREATE TABLE inserts_1 (val INTEGER)");
// db.execSQL("CREATE TABLE tracks (id INTEGER PRIMARY KEY, title TEXT, band_id INTEGER, duration FLOAT, url TEXT, lyrics TEXT, about TEXT, release_date INTEGER, mod_date INTEGER)");
// }
//
// @Override
// public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {}
// }
// Path: app/src/main/java/co/jasonwyatt/sqliteperf/inserts/tracks/InsertsTestCase.java
import android.content.ContentValues;
import android.database.sqlite.SQLiteDatabase;
import java.nio.charset.Charset;
import java.util.Random;
import co.jasonwyatt.sqliteperf.App;
import co.jasonwyatt.sqliteperf.TestCase;
import co.jasonwyatt.sqliteperf.inserts.DbHelper;
package co.jasonwyatt.sqliteperf.inserts.tracks;
/**
* @author jason
*/
public class InsertsTestCase implements TestCase {
private DbHelper mDbHelper;
private final Random mRandom;
private final int mInsertions;
private final int mTestSizeIndex;
public InsertsTestCase(int insertions, int testSizeIndex) {
mRandom = new Random(System.currentTimeMillis());
mInsertions = insertions;
mTestSizeIndex = testSizeIndex;
}
@Override
public void resetCase() {
mDbHelper.getWritableDatabase().execSQL("delete from tracks");
mDbHelper.close();
}
@Override
public Metrics runCase() { | mDbHelper = new DbHelper(App.getInstance(), getClass().getName()); |
jasonwyatt/SQLite-Performance | app/src/main/java/co/jasonwyatt/sqliteperf/blobs/cases/QueryTestCase.java | // Path: app/src/main/java/co/jasonwyatt/sqliteperf/App.java
// public class App extends Application {
// private static App sInstance;
//
// @Override
// public void onCreate() {
// super.onCreate();
// sInstance = this;
// }
//
// public static App getInstance() {
// return sInstance;
// }
// }
//
// Path: app/src/main/java/co/jasonwyatt/sqliteperf/TestCase.java
// public interface TestCase {
// void resetCase();
// Metrics runCase();
//
// class Metrics {
// private final String mName;
// private final float mVariable;
// private int mIterations = 1;
// private long mStartTime;
// private long mEndTime;
// private long mElapsedTime;
//
// public Metrics(String name, float variable) {
// mName = name;
// mVariable = variable;
// }
//
// Metrics(List<Metrics> iterations) {
// mName = iterations.get(0).mName;
// mVariable = iterations.get(0).mVariable;
// mIterations = iterations.size();
// mElapsedTime = 0;
// for (Metrics m : iterations) {
// mElapsedTime += m.mElapsedTime;
// }
// mElapsedTime = (long) (mElapsedTime*1.0f / iterations.size());
// }
//
// public void started() {
// mStartTime = System.nanoTime();
// }
//
// public void finished() {
// mEndTime = System.nanoTime();
// mElapsedTime = mEndTime - mStartTime;
// }
//
// @Override
// public String toString() {
// StringBuilder sb = new StringBuilder();
// sb.append(mName);
// sb.append(":\n");
// if (mIterations > 1) {
// sb.append(mIterations);
// sb.append(" iterations, each averaged ");
// } else {
// sb.append("took ");
// }
// sb.append(((float) mElapsedTime / mIterations) / 1000000f);
// sb.append(" seconds");
// return sb.toString();
// }
//
// public float getVariable() {
// return mVariable;
// }
//
// public long getElapsedTime() {
// return mElapsedTime;
// }
// }
//
// }
//
// Path: app/src/main/java/co/jasonwyatt/sqliteperf/blobs/DbHelper.java
// public class DbHelper extends SQLiteOpenHelper {
// private final int mFileSize;
// private final int mFiles;
// private String[] mFileNames;
//
// public DbHelper(Context context, String name, int fileSize, int files) {
// super(context, name, null, 1);
// mFileSize = fileSize;
// mFiles = files;
// }
//
// @Override
// public void onCreate(SQLiteDatabase db) {
// db.execSQL("CREATE TABLE files (filename TEXT PRIMARY KEY, data BLOB NOT NULL)");
//
// db.beginTransaction();
// try {
// createFiles(db);
// db.setTransactionSuccessful();
// } finally {
// db.endTransaction();
// }
// }
//
// private void createFiles(SQLiteDatabase db) {
// mFileNames = new String[mFiles];
// byte[] rawData = new byte[mFileSize+mFiles];
// Random random = new Random();
// random.nextBytes(rawData);
//
// ByteArrayOutputStream[] streams = new ByteArrayOutputStream[mFiles];
// for (int i = 0; i < mFiles; i++) {
// streams[i] = new ByteArrayOutputStream(mFileSize);
// streams[i].write(rawData, i, mFileSize);
// mFileNames[i] = String.valueOf(i);
// }
//
// SQLiteStatement insert = db.compileStatement("INSERT INTO files (filename, data) VALUES (?, ?)");
// for (int i = 0; i < mFiles; i++) {
// insert.bindString(1, mFileNames[i]);
// insert.bindBlob(2, streams[i].toByteArray());
//
// insert.execute();
// }
// }
//
// @Override
// public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {}
//
// public String[] getFileNames() {
// return mFileNames;
// }
// }
| import android.content.ContentValues;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import java.util.Random;
import co.jasonwyatt.sqliteperf.App;
import co.jasonwyatt.sqliteperf.TestCase;
import co.jasonwyatt.sqliteperf.blobs.DbHelper; | package co.jasonwyatt.sqliteperf.blobs.cases;
/**
* @author jason
*/
public class QueryTestCase implements TestCase {
private final int mTestSizeIndex; | // Path: app/src/main/java/co/jasonwyatt/sqliteperf/App.java
// public class App extends Application {
// private static App sInstance;
//
// @Override
// public void onCreate() {
// super.onCreate();
// sInstance = this;
// }
//
// public static App getInstance() {
// return sInstance;
// }
// }
//
// Path: app/src/main/java/co/jasonwyatt/sqliteperf/TestCase.java
// public interface TestCase {
// void resetCase();
// Metrics runCase();
//
// class Metrics {
// private final String mName;
// private final float mVariable;
// private int mIterations = 1;
// private long mStartTime;
// private long mEndTime;
// private long mElapsedTime;
//
// public Metrics(String name, float variable) {
// mName = name;
// mVariable = variable;
// }
//
// Metrics(List<Metrics> iterations) {
// mName = iterations.get(0).mName;
// mVariable = iterations.get(0).mVariable;
// mIterations = iterations.size();
// mElapsedTime = 0;
// for (Metrics m : iterations) {
// mElapsedTime += m.mElapsedTime;
// }
// mElapsedTime = (long) (mElapsedTime*1.0f / iterations.size());
// }
//
// public void started() {
// mStartTime = System.nanoTime();
// }
//
// public void finished() {
// mEndTime = System.nanoTime();
// mElapsedTime = mEndTime - mStartTime;
// }
//
// @Override
// public String toString() {
// StringBuilder sb = new StringBuilder();
// sb.append(mName);
// sb.append(":\n");
// if (mIterations > 1) {
// sb.append(mIterations);
// sb.append(" iterations, each averaged ");
// } else {
// sb.append("took ");
// }
// sb.append(((float) mElapsedTime / mIterations) / 1000000f);
// sb.append(" seconds");
// return sb.toString();
// }
//
// public float getVariable() {
// return mVariable;
// }
//
// public long getElapsedTime() {
// return mElapsedTime;
// }
// }
//
// }
//
// Path: app/src/main/java/co/jasonwyatt/sqliteperf/blobs/DbHelper.java
// public class DbHelper extends SQLiteOpenHelper {
// private final int mFileSize;
// private final int mFiles;
// private String[] mFileNames;
//
// public DbHelper(Context context, String name, int fileSize, int files) {
// super(context, name, null, 1);
// mFileSize = fileSize;
// mFiles = files;
// }
//
// @Override
// public void onCreate(SQLiteDatabase db) {
// db.execSQL("CREATE TABLE files (filename TEXT PRIMARY KEY, data BLOB NOT NULL)");
//
// db.beginTransaction();
// try {
// createFiles(db);
// db.setTransactionSuccessful();
// } finally {
// db.endTransaction();
// }
// }
//
// private void createFiles(SQLiteDatabase db) {
// mFileNames = new String[mFiles];
// byte[] rawData = new byte[mFileSize+mFiles];
// Random random = new Random();
// random.nextBytes(rawData);
//
// ByteArrayOutputStream[] streams = new ByteArrayOutputStream[mFiles];
// for (int i = 0; i < mFiles; i++) {
// streams[i] = new ByteArrayOutputStream(mFileSize);
// streams[i].write(rawData, i, mFileSize);
// mFileNames[i] = String.valueOf(i);
// }
//
// SQLiteStatement insert = db.compileStatement("INSERT INTO files (filename, data) VALUES (?, ?)");
// for (int i = 0; i < mFiles; i++) {
// insert.bindString(1, mFileNames[i]);
// insert.bindBlob(2, streams[i].toByteArray());
//
// insert.execute();
// }
// }
//
// @Override
// public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {}
//
// public String[] getFileNames() {
// return mFileNames;
// }
// }
// Path: app/src/main/java/co/jasonwyatt/sqliteperf/blobs/cases/QueryTestCase.java
import android.content.ContentValues;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import java.util.Random;
import co.jasonwyatt.sqliteperf.App;
import co.jasonwyatt.sqliteperf.TestCase;
import co.jasonwyatt.sqliteperf.blobs.DbHelper;
package co.jasonwyatt.sqliteperf.blobs.cases;
/**
* @author jason
*/
public class QueryTestCase implements TestCase {
private final int mTestSizeIndex; | private DbHelper mDbHelper; |
jasonwyatt/SQLite-Performance | app/src/main/java/co/jasonwyatt/sqliteperf/blobs/cases/QueryTestCase.java | // Path: app/src/main/java/co/jasonwyatt/sqliteperf/App.java
// public class App extends Application {
// private static App sInstance;
//
// @Override
// public void onCreate() {
// super.onCreate();
// sInstance = this;
// }
//
// public static App getInstance() {
// return sInstance;
// }
// }
//
// Path: app/src/main/java/co/jasonwyatt/sqliteperf/TestCase.java
// public interface TestCase {
// void resetCase();
// Metrics runCase();
//
// class Metrics {
// private final String mName;
// private final float mVariable;
// private int mIterations = 1;
// private long mStartTime;
// private long mEndTime;
// private long mElapsedTime;
//
// public Metrics(String name, float variable) {
// mName = name;
// mVariable = variable;
// }
//
// Metrics(List<Metrics> iterations) {
// mName = iterations.get(0).mName;
// mVariable = iterations.get(0).mVariable;
// mIterations = iterations.size();
// mElapsedTime = 0;
// for (Metrics m : iterations) {
// mElapsedTime += m.mElapsedTime;
// }
// mElapsedTime = (long) (mElapsedTime*1.0f / iterations.size());
// }
//
// public void started() {
// mStartTime = System.nanoTime();
// }
//
// public void finished() {
// mEndTime = System.nanoTime();
// mElapsedTime = mEndTime - mStartTime;
// }
//
// @Override
// public String toString() {
// StringBuilder sb = new StringBuilder();
// sb.append(mName);
// sb.append(":\n");
// if (mIterations > 1) {
// sb.append(mIterations);
// sb.append(" iterations, each averaged ");
// } else {
// sb.append("took ");
// }
// sb.append(((float) mElapsedTime / mIterations) / 1000000f);
// sb.append(" seconds");
// return sb.toString();
// }
//
// public float getVariable() {
// return mVariable;
// }
//
// public long getElapsedTime() {
// return mElapsedTime;
// }
// }
//
// }
//
// Path: app/src/main/java/co/jasonwyatt/sqliteperf/blobs/DbHelper.java
// public class DbHelper extends SQLiteOpenHelper {
// private final int mFileSize;
// private final int mFiles;
// private String[] mFileNames;
//
// public DbHelper(Context context, String name, int fileSize, int files) {
// super(context, name, null, 1);
// mFileSize = fileSize;
// mFiles = files;
// }
//
// @Override
// public void onCreate(SQLiteDatabase db) {
// db.execSQL("CREATE TABLE files (filename TEXT PRIMARY KEY, data BLOB NOT NULL)");
//
// db.beginTransaction();
// try {
// createFiles(db);
// db.setTransactionSuccessful();
// } finally {
// db.endTransaction();
// }
// }
//
// private void createFiles(SQLiteDatabase db) {
// mFileNames = new String[mFiles];
// byte[] rawData = new byte[mFileSize+mFiles];
// Random random = new Random();
// random.nextBytes(rawData);
//
// ByteArrayOutputStream[] streams = new ByteArrayOutputStream[mFiles];
// for (int i = 0; i < mFiles; i++) {
// streams[i] = new ByteArrayOutputStream(mFileSize);
// streams[i].write(rawData, i, mFileSize);
// mFileNames[i] = String.valueOf(i);
// }
//
// SQLiteStatement insert = db.compileStatement("INSERT INTO files (filename, data) VALUES (?, ?)");
// for (int i = 0; i < mFiles; i++) {
// insert.bindString(1, mFileNames[i]);
// insert.bindBlob(2, streams[i].toByteArray());
//
// insert.execute();
// }
// }
//
// @Override
// public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {}
//
// public String[] getFileNames() {
// return mFileNames;
// }
// }
| import android.content.ContentValues;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import java.util.Random;
import co.jasonwyatt.sqliteperf.App;
import co.jasonwyatt.sqliteperf.TestCase;
import co.jasonwyatt.sqliteperf.blobs.DbHelper; | package co.jasonwyatt.sqliteperf.blobs.cases;
/**
* @author jason
*/
public class QueryTestCase implements TestCase {
private final int mTestSizeIndex;
private DbHelper mDbHelper;
private final int mFileSize;
private final int mFiles;
public QueryTestCase(int fileSize, int files, int testSizeIndex) {
mFileSize = fileSize;
mFiles = files;
mTestSizeIndex = testSizeIndex;
}
@Override
public void resetCase() {
mDbHelper.close(); | // Path: app/src/main/java/co/jasonwyatt/sqliteperf/App.java
// public class App extends Application {
// private static App sInstance;
//
// @Override
// public void onCreate() {
// super.onCreate();
// sInstance = this;
// }
//
// public static App getInstance() {
// return sInstance;
// }
// }
//
// Path: app/src/main/java/co/jasonwyatt/sqliteperf/TestCase.java
// public interface TestCase {
// void resetCase();
// Metrics runCase();
//
// class Metrics {
// private final String mName;
// private final float mVariable;
// private int mIterations = 1;
// private long mStartTime;
// private long mEndTime;
// private long mElapsedTime;
//
// public Metrics(String name, float variable) {
// mName = name;
// mVariable = variable;
// }
//
// Metrics(List<Metrics> iterations) {
// mName = iterations.get(0).mName;
// mVariable = iterations.get(0).mVariable;
// mIterations = iterations.size();
// mElapsedTime = 0;
// for (Metrics m : iterations) {
// mElapsedTime += m.mElapsedTime;
// }
// mElapsedTime = (long) (mElapsedTime*1.0f / iterations.size());
// }
//
// public void started() {
// mStartTime = System.nanoTime();
// }
//
// public void finished() {
// mEndTime = System.nanoTime();
// mElapsedTime = mEndTime - mStartTime;
// }
//
// @Override
// public String toString() {
// StringBuilder sb = new StringBuilder();
// sb.append(mName);
// sb.append(":\n");
// if (mIterations > 1) {
// sb.append(mIterations);
// sb.append(" iterations, each averaged ");
// } else {
// sb.append("took ");
// }
// sb.append(((float) mElapsedTime / mIterations) / 1000000f);
// sb.append(" seconds");
// return sb.toString();
// }
//
// public float getVariable() {
// return mVariable;
// }
//
// public long getElapsedTime() {
// return mElapsedTime;
// }
// }
//
// }
//
// Path: app/src/main/java/co/jasonwyatt/sqliteperf/blobs/DbHelper.java
// public class DbHelper extends SQLiteOpenHelper {
// private final int mFileSize;
// private final int mFiles;
// private String[] mFileNames;
//
// public DbHelper(Context context, String name, int fileSize, int files) {
// super(context, name, null, 1);
// mFileSize = fileSize;
// mFiles = files;
// }
//
// @Override
// public void onCreate(SQLiteDatabase db) {
// db.execSQL("CREATE TABLE files (filename TEXT PRIMARY KEY, data BLOB NOT NULL)");
//
// db.beginTransaction();
// try {
// createFiles(db);
// db.setTransactionSuccessful();
// } finally {
// db.endTransaction();
// }
// }
//
// private void createFiles(SQLiteDatabase db) {
// mFileNames = new String[mFiles];
// byte[] rawData = new byte[mFileSize+mFiles];
// Random random = new Random();
// random.nextBytes(rawData);
//
// ByteArrayOutputStream[] streams = new ByteArrayOutputStream[mFiles];
// for (int i = 0; i < mFiles; i++) {
// streams[i] = new ByteArrayOutputStream(mFileSize);
// streams[i].write(rawData, i, mFileSize);
// mFileNames[i] = String.valueOf(i);
// }
//
// SQLiteStatement insert = db.compileStatement("INSERT INTO files (filename, data) VALUES (?, ?)");
// for (int i = 0; i < mFiles; i++) {
// insert.bindString(1, mFileNames[i]);
// insert.bindBlob(2, streams[i].toByteArray());
//
// insert.execute();
// }
// }
//
// @Override
// public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {}
//
// public String[] getFileNames() {
// return mFileNames;
// }
// }
// Path: app/src/main/java/co/jasonwyatt/sqliteperf/blobs/cases/QueryTestCase.java
import android.content.ContentValues;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import java.util.Random;
import co.jasonwyatt.sqliteperf.App;
import co.jasonwyatt.sqliteperf.TestCase;
import co.jasonwyatt.sqliteperf.blobs.DbHelper;
package co.jasonwyatt.sqliteperf.blobs.cases;
/**
* @author jason
*/
public class QueryTestCase implements TestCase {
private final int mTestSizeIndex;
private DbHelper mDbHelper;
private final int mFileSize;
private final int mFiles;
public QueryTestCase(int fileSize, int files, int testSizeIndex) {
mFileSize = fileSize;
mFiles = files;
mTestSizeIndex = testSizeIndex;
}
@Override
public void resetCase() {
mDbHelper.close(); | App.getInstance().deleteDatabase(getClass().getSimpleName()); |
jasonwyatt/SQLite-Performance | app/src/main/java/co/jasonwyatt/sqliteperf/blobs/cases/RawQueryTestCase.java | // Path: app/src/main/java/co/jasonwyatt/sqliteperf/App.java
// public class App extends Application {
// private static App sInstance;
//
// @Override
// public void onCreate() {
// super.onCreate();
// sInstance = this;
// }
//
// public static App getInstance() {
// return sInstance;
// }
// }
//
// Path: app/src/main/java/co/jasonwyatt/sqliteperf/TestCase.java
// public interface TestCase {
// void resetCase();
// Metrics runCase();
//
// class Metrics {
// private final String mName;
// private final float mVariable;
// private int mIterations = 1;
// private long mStartTime;
// private long mEndTime;
// private long mElapsedTime;
//
// public Metrics(String name, float variable) {
// mName = name;
// mVariable = variable;
// }
//
// Metrics(List<Metrics> iterations) {
// mName = iterations.get(0).mName;
// mVariable = iterations.get(0).mVariable;
// mIterations = iterations.size();
// mElapsedTime = 0;
// for (Metrics m : iterations) {
// mElapsedTime += m.mElapsedTime;
// }
// mElapsedTime = (long) (mElapsedTime*1.0f / iterations.size());
// }
//
// public void started() {
// mStartTime = System.nanoTime();
// }
//
// public void finished() {
// mEndTime = System.nanoTime();
// mElapsedTime = mEndTime - mStartTime;
// }
//
// @Override
// public String toString() {
// StringBuilder sb = new StringBuilder();
// sb.append(mName);
// sb.append(":\n");
// if (mIterations > 1) {
// sb.append(mIterations);
// sb.append(" iterations, each averaged ");
// } else {
// sb.append("took ");
// }
// sb.append(((float) mElapsedTime / mIterations) / 1000000f);
// sb.append(" seconds");
// return sb.toString();
// }
//
// public float getVariable() {
// return mVariable;
// }
//
// public long getElapsedTime() {
// return mElapsedTime;
// }
// }
//
// }
//
// Path: app/src/main/java/co/jasonwyatt/sqliteperf/blobs/DbHelper.java
// public class DbHelper extends SQLiteOpenHelper {
// private final int mFileSize;
// private final int mFiles;
// private String[] mFileNames;
//
// public DbHelper(Context context, String name, int fileSize, int files) {
// super(context, name, null, 1);
// mFileSize = fileSize;
// mFiles = files;
// }
//
// @Override
// public void onCreate(SQLiteDatabase db) {
// db.execSQL("CREATE TABLE files (filename TEXT PRIMARY KEY, data BLOB NOT NULL)");
//
// db.beginTransaction();
// try {
// createFiles(db);
// db.setTransactionSuccessful();
// } finally {
// db.endTransaction();
// }
// }
//
// private void createFiles(SQLiteDatabase db) {
// mFileNames = new String[mFiles];
// byte[] rawData = new byte[mFileSize+mFiles];
// Random random = new Random();
// random.nextBytes(rawData);
//
// ByteArrayOutputStream[] streams = new ByteArrayOutputStream[mFiles];
// for (int i = 0; i < mFiles; i++) {
// streams[i] = new ByteArrayOutputStream(mFileSize);
// streams[i].write(rawData, i, mFileSize);
// mFileNames[i] = String.valueOf(i);
// }
//
// SQLiteStatement insert = db.compileStatement("INSERT INTO files (filename, data) VALUES (?, ?)");
// for (int i = 0; i < mFiles; i++) {
// insert.bindString(1, mFileNames[i]);
// insert.bindBlob(2, streams[i].toByteArray());
//
// insert.execute();
// }
// }
//
// @Override
// public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {}
//
// public String[] getFileNames() {
// return mFileNames;
// }
// }
| import android.content.ContentValues;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import java.util.Random;
import co.jasonwyatt.sqliteperf.App;
import co.jasonwyatt.sqliteperf.TestCase;
import co.jasonwyatt.sqliteperf.blobs.DbHelper; | package co.jasonwyatt.sqliteperf.blobs.cases;
/**
* @author jason
*/
public class RawQueryTestCase implements TestCase {
private final int mTestSizeIndex; | // Path: app/src/main/java/co/jasonwyatt/sqliteperf/App.java
// public class App extends Application {
// private static App sInstance;
//
// @Override
// public void onCreate() {
// super.onCreate();
// sInstance = this;
// }
//
// public static App getInstance() {
// return sInstance;
// }
// }
//
// Path: app/src/main/java/co/jasonwyatt/sqliteperf/TestCase.java
// public interface TestCase {
// void resetCase();
// Metrics runCase();
//
// class Metrics {
// private final String mName;
// private final float mVariable;
// private int mIterations = 1;
// private long mStartTime;
// private long mEndTime;
// private long mElapsedTime;
//
// public Metrics(String name, float variable) {
// mName = name;
// mVariable = variable;
// }
//
// Metrics(List<Metrics> iterations) {
// mName = iterations.get(0).mName;
// mVariable = iterations.get(0).mVariable;
// mIterations = iterations.size();
// mElapsedTime = 0;
// for (Metrics m : iterations) {
// mElapsedTime += m.mElapsedTime;
// }
// mElapsedTime = (long) (mElapsedTime*1.0f / iterations.size());
// }
//
// public void started() {
// mStartTime = System.nanoTime();
// }
//
// public void finished() {
// mEndTime = System.nanoTime();
// mElapsedTime = mEndTime - mStartTime;
// }
//
// @Override
// public String toString() {
// StringBuilder sb = new StringBuilder();
// sb.append(mName);
// sb.append(":\n");
// if (mIterations > 1) {
// sb.append(mIterations);
// sb.append(" iterations, each averaged ");
// } else {
// sb.append("took ");
// }
// sb.append(((float) mElapsedTime / mIterations) / 1000000f);
// sb.append(" seconds");
// return sb.toString();
// }
//
// public float getVariable() {
// return mVariable;
// }
//
// public long getElapsedTime() {
// return mElapsedTime;
// }
// }
//
// }
//
// Path: app/src/main/java/co/jasonwyatt/sqliteperf/blobs/DbHelper.java
// public class DbHelper extends SQLiteOpenHelper {
// private final int mFileSize;
// private final int mFiles;
// private String[] mFileNames;
//
// public DbHelper(Context context, String name, int fileSize, int files) {
// super(context, name, null, 1);
// mFileSize = fileSize;
// mFiles = files;
// }
//
// @Override
// public void onCreate(SQLiteDatabase db) {
// db.execSQL("CREATE TABLE files (filename TEXT PRIMARY KEY, data BLOB NOT NULL)");
//
// db.beginTransaction();
// try {
// createFiles(db);
// db.setTransactionSuccessful();
// } finally {
// db.endTransaction();
// }
// }
//
// private void createFiles(SQLiteDatabase db) {
// mFileNames = new String[mFiles];
// byte[] rawData = new byte[mFileSize+mFiles];
// Random random = new Random();
// random.nextBytes(rawData);
//
// ByteArrayOutputStream[] streams = new ByteArrayOutputStream[mFiles];
// for (int i = 0; i < mFiles; i++) {
// streams[i] = new ByteArrayOutputStream(mFileSize);
// streams[i].write(rawData, i, mFileSize);
// mFileNames[i] = String.valueOf(i);
// }
//
// SQLiteStatement insert = db.compileStatement("INSERT INTO files (filename, data) VALUES (?, ?)");
// for (int i = 0; i < mFiles; i++) {
// insert.bindString(1, mFileNames[i]);
// insert.bindBlob(2, streams[i].toByteArray());
//
// insert.execute();
// }
// }
//
// @Override
// public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {}
//
// public String[] getFileNames() {
// return mFileNames;
// }
// }
// Path: app/src/main/java/co/jasonwyatt/sqliteperf/blobs/cases/RawQueryTestCase.java
import android.content.ContentValues;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import java.util.Random;
import co.jasonwyatt.sqliteperf.App;
import co.jasonwyatt.sqliteperf.TestCase;
import co.jasonwyatt.sqliteperf.blobs.DbHelper;
package co.jasonwyatt.sqliteperf.blobs.cases;
/**
* @author jason
*/
public class RawQueryTestCase implements TestCase {
private final int mTestSizeIndex; | private DbHelper mDbHelper; |
jasonwyatt/SQLite-Performance | app/src/main/java/co/jasonwyatt/sqliteperf/blobs/cases/RawQueryTestCase.java | // Path: app/src/main/java/co/jasonwyatt/sqliteperf/App.java
// public class App extends Application {
// private static App sInstance;
//
// @Override
// public void onCreate() {
// super.onCreate();
// sInstance = this;
// }
//
// public static App getInstance() {
// return sInstance;
// }
// }
//
// Path: app/src/main/java/co/jasonwyatt/sqliteperf/TestCase.java
// public interface TestCase {
// void resetCase();
// Metrics runCase();
//
// class Metrics {
// private final String mName;
// private final float mVariable;
// private int mIterations = 1;
// private long mStartTime;
// private long mEndTime;
// private long mElapsedTime;
//
// public Metrics(String name, float variable) {
// mName = name;
// mVariable = variable;
// }
//
// Metrics(List<Metrics> iterations) {
// mName = iterations.get(0).mName;
// mVariable = iterations.get(0).mVariable;
// mIterations = iterations.size();
// mElapsedTime = 0;
// for (Metrics m : iterations) {
// mElapsedTime += m.mElapsedTime;
// }
// mElapsedTime = (long) (mElapsedTime*1.0f / iterations.size());
// }
//
// public void started() {
// mStartTime = System.nanoTime();
// }
//
// public void finished() {
// mEndTime = System.nanoTime();
// mElapsedTime = mEndTime - mStartTime;
// }
//
// @Override
// public String toString() {
// StringBuilder sb = new StringBuilder();
// sb.append(mName);
// sb.append(":\n");
// if (mIterations > 1) {
// sb.append(mIterations);
// sb.append(" iterations, each averaged ");
// } else {
// sb.append("took ");
// }
// sb.append(((float) mElapsedTime / mIterations) / 1000000f);
// sb.append(" seconds");
// return sb.toString();
// }
//
// public float getVariable() {
// return mVariable;
// }
//
// public long getElapsedTime() {
// return mElapsedTime;
// }
// }
//
// }
//
// Path: app/src/main/java/co/jasonwyatt/sqliteperf/blobs/DbHelper.java
// public class DbHelper extends SQLiteOpenHelper {
// private final int mFileSize;
// private final int mFiles;
// private String[] mFileNames;
//
// public DbHelper(Context context, String name, int fileSize, int files) {
// super(context, name, null, 1);
// mFileSize = fileSize;
// mFiles = files;
// }
//
// @Override
// public void onCreate(SQLiteDatabase db) {
// db.execSQL("CREATE TABLE files (filename TEXT PRIMARY KEY, data BLOB NOT NULL)");
//
// db.beginTransaction();
// try {
// createFiles(db);
// db.setTransactionSuccessful();
// } finally {
// db.endTransaction();
// }
// }
//
// private void createFiles(SQLiteDatabase db) {
// mFileNames = new String[mFiles];
// byte[] rawData = new byte[mFileSize+mFiles];
// Random random = new Random();
// random.nextBytes(rawData);
//
// ByteArrayOutputStream[] streams = new ByteArrayOutputStream[mFiles];
// for (int i = 0; i < mFiles; i++) {
// streams[i] = new ByteArrayOutputStream(mFileSize);
// streams[i].write(rawData, i, mFileSize);
// mFileNames[i] = String.valueOf(i);
// }
//
// SQLiteStatement insert = db.compileStatement("INSERT INTO files (filename, data) VALUES (?, ?)");
// for (int i = 0; i < mFiles; i++) {
// insert.bindString(1, mFileNames[i]);
// insert.bindBlob(2, streams[i].toByteArray());
//
// insert.execute();
// }
// }
//
// @Override
// public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {}
//
// public String[] getFileNames() {
// return mFileNames;
// }
// }
| import android.content.ContentValues;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import java.util.Random;
import co.jasonwyatt.sqliteperf.App;
import co.jasonwyatt.sqliteperf.TestCase;
import co.jasonwyatt.sqliteperf.blobs.DbHelper; | package co.jasonwyatt.sqliteperf.blobs.cases;
/**
* @author jason
*/
public class RawQueryTestCase implements TestCase {
private final int mTestSizeIndex;
private DbHelper mDbHelper;
private final int mFileSize;
private final int mFiles;
public RawQueryTestCase(int fileSize, int files, int testSizeIndex) {
mFileSize = fileSize;
mFiles = files;
mTestSizeIndex = testSizeIndex;
}
@Override
public void resetCase() {
mDbHelper.close(); | // Path: app/src/main/java/co/jasonwyatt/sqliteperf/App.java
// public class App extends Application {
// private static App sInstance;
//
// @Override
// public void onCreate() {
// super.onCreate();
// sInstance = this;
// }
//
// public static App getInstance() {
// return sInstance;
// }
// }
//
// Path: app/src/main/java/co/jasonwyatt/sqliteperf/TestCase.java
// public interface TestCase {
// void resetCase();
// Metrics runCase();
//
// class Metrics {
// private final String mName;
// private final float mVariable;
// private int mIterations = 1;
// private long mStartTime;
// private long mEndTime;
// private long mElapsedTime;
//
// public Metrics(String name, float variable) {
// mName = name;
// mVariable = variable;
// }
//
// Metrics(List<Metrics> iterations) {
// mName = iterations.get(0).mName;
// mVariable = iterations.get(0).mVariable;
// mIterations = iterations.size();
// mElapsedTime = 0;
// for (Metrics m : iterations) {
// mElapsedTime += m.mElapsedTime;
// }
// mElapsedTime = (long) (mElapsedTime*1.0f / iterations.size());
// }
//
// public void started() {
// mStartTime = System.nanoTime();
// }
//
// public void finished() {
// mEndTime = System.nanoTime();
// mElapsedTime = mEndTime - mStartTime;
// }
//
// @Override
// public String toString() {
// StringBuilder sb = new StringBuilder();
// sb.append(mName);
// sb.append(":\n");
// if (mIterations > 1) {
// sb.append(mIterations);
// sb.append(" iterations, each averaged ");
// } else {
// sb.append("took ");
// }
// sb.append(((float) mElapsedTime / mIterations) / 1000000f);
// sb.append(" seconds");
// return sb.toString();
// }
//
// public float getVariable() {
// return mVariable;
// }
//
// public long getElapsedTime() {
// return mElapsedTime;
// }
// }
//
// }
//
// Path: app/src/main/java/co/jasonwyatt/sqliteperf/blobs/DbHelper.java
// public class DbHelper extends SQLiteOpenHelper {
// private final int mFileSize;
// private final int mFiles;
// private String[] mFileNames;
//
// public DbHelper(Context context, String name, int fileSize, int files) {
// super(context, name, null, 1);
// mFileSize = fileSize;
// mFiles = files;
// }
//
// @Override
// public void onCreate(SQLiteDatabase db) {
// db.execSQL("CREATE TABLE files (filename TEXT PRIMARY KEY, data BLOB NOT NULL)");
//
// db.beginTransaction();
// try {
// createFiles(db);
// db.setTransactionSuccessful();
// } finally {
// db.endTransaction();
// }
// }
//
// private void createFiles(SQLiteDatabase db) {
// mFileNames = new String[mFiles];
// byte[] rawData = new byte[mFileSize+mFiles];
// Random random = new Random();
// random.nextBytes(rawData);
//
// ByteArrayOutputStream[] streams = new ByteArrayOutputStream[mFiles];
// for (int i = 0; i < mFiles; i++) {
// streams[i] = new ByteArrayOutputStream(mFileSize);
// streams[i].write(rawData, i, mFileSize);
// mFileNames[i] = String.valueOf(i);
// }
//
// SQLiteStatement insert = db.compileStatement("INSERT INTO files (filename, data) VALUES (?, ?)");
// for (int i = 0; i < mFiles; i++) {
// insert.bindString(1, mFileNames[i]);
// insert.bindBlob(2, streams[i].toByteArray());
//
// insert.execute();
// }
// }
//
// @Override
// public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {}
//
// public String[] getFileNames() {
// return mFileNames;
// }
// }
// Path: app/src/main/java/co/jasonwyatt/sqliteperf/blobs/cases/RawQueryTestCase.java
import android.content.ContentValues;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import java.util.Random;
import co.jasonwyatt.sqliteperf.App;
import co.jasonwyatt.sqliteperf.TestCase;
import co.jasonwyatt.sqliteperf.blobs.DbHelper;
package co.jasonwyatt.sqliteperf.blobs.cases;
/**
* @author jason
*/
public class RawQueryTestCase implements TestCase {
private final int mTestSizeIndex;
private DbHelper mDbHelper;
private final int mFileSize;
private final int mFiles;
public RawQueryTestCase(int fileSize, int files, int testSizeIndex) {
mFileSize = fileSize;
mFiles = files;
mTestSizeIndex = testSizeIndex;
}
@Override
public void resetCase() {
mDbHelper.close(); | App.getInstance().deleteDatabase(getClass().getSimpleName()); |
jasonwyatt/SQLite-Performance | app/src/main/java/co/jasonwyatt/sqliteperf/inserts/integers/IntegerInsertsRawTransactionCase.java | // Path: app/src/main/java/co/jasonwyatt/sqliteperf/App.java
// public class App extends Application {
// private static App sInstance;
//
// @Override
// public void onCreate() {
// super.onCreate();
// sInstance = this;
// }
//
// public static App getInstance() {
// return sInstance;
// }
// }
//
// Path: app/src/main/java/co/jasonwyatt/sqliteperf/TestCase.java
// public interface TestCase {
// void resetCase();
// Metrics runCase();
//
// class Metrics {
// private final String mName;
// private final float mVariable;
// private int mIterations = 1;
// private long mStartTime;
// private long mEndTime;
// private long mElapsedTime;
//
// public Metrics(String name, float variable) {
// mName = name;
// mVariable = variable;
// }
//
// Metrics(List<Metrics> iterations) {
// mName = iterations.get(0).mName;
// mVariable = iterations.get(0).mVariable;
// mIterations = iterations.size();
// mElapsedTime = 0;
// for (Metrics m : iterations) {
// mElapsedTime += m.mElapsedTime;
// }
// mElapsedTime = (long) (mElapsedTime*1.0f / iterations.size());
// }
//
// public void started() {
// mStartTime = System.nanoTime();
// }
//
// public void finished() {
// mEndTime = System.nanoTime();
// mElapsedTime = mEndTime - mStartTime;
// }
//
// @Override
// public String toString() {
// StringBuilder sb = new StringBuilder();
// sb.append(mName);
// sb.append(":\n");
// if (mIterations > 1) {
// sb.append(mIterations);
// sb.append(" iterations, each averaged ");
// } else {
// sb.append("took ");
// }
// sb.append(((float) mElapsedTime / mIterations) / 1000000f);
// sb.append(" seconds");
// return sb.toString();
// }
//
// public float getVariable() {
// return mVariable;
// }
//
// public long getElapsedTime() {
// return mElapsedTime;
// }
// }
//
// }
//
// Path: app/src/main/java/co/jasonwyatt/sqliteperf/inserts/DbHelper.java
// public class DbHelper extends SQLiteOpenHelper {
// public DbHelper(Context context, String name) {
// super(context, name, null, 1);
// }
//
// @Override
// public void onCreate(SQLiteDatabase db) {
// db.execSQL("CREATE TABLE inserts_1 (val INTEGER)");
// db.execSQL("CREATE TABLE tracks (id INTEGER PRIMARY KEY, title TEXT, band_id INTEGER, duration FLOAT, url TEXT, lyrics TEXT, about TEXT, release_date INTEGER, mod_date INTEGER)");
// }
//
// @Override
// public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {}
// }
| import android.database.sqlite.SQLiteDatabase;
import android.util.Log;
import java.util.Random;
import co.jasonwyatt.sqliteperf.App;
import co.jasonwyatt.sqliteperf.TestCase;
import co.jasonwyatt.sqliteperf.inserts.DbHelper; | package co.jasonwyatt.sqliteperf.inserts.integers;
/**
* @author jason
*/
public class IntegerInsertsRawTransactionCase implements TestCase {
private DbHelper mDbHelper;
private final Random mRandom;
private final int mInsertions;
private final int mTestSizeIndex;
public IntegerInsertsRawTransactionCase(int insertions, int testSizeIndex) {
mRandom = new Random(System.currentTimeMillis());
mInsertions = insertions;
mTestSizeIndex = testSizeIndex;
}
@Override
public void resetCase() {
mDbHelper.getWritableDatabase().execSQL("delete from inserts_1");
mDbHelper.close();
}
@Override
public Metrics runCase() { | // Path: app/src/main/java/co/jasonwyatt/sqliteperf/App.java
// public class App extends Application {
// private static App sInstance;
//
// @Override
// public void onCreate() {
// super.onCreate();
// sInstance = this;
// }
//
// public static App getInstance() {
// return sInstance;
// }
// }
//
// Path: app/src/main/java/co/jasonwyatt/sqliteperf/TestCase.java
// public interface TestCase {
// void resetCase();
// Metrics runCase();
//
// class Metrics {
// private final String mName;
// private final float mVariable;
// private int mIterations = 1;
// private long mStartTime;
// private long mEndTime;
// private long mElapsedTime;
//
// public Metrics(String name, float variable) {
// mName = name;
// mVariable = variable;
// }
//
// Metrics(List<Metrics> iterations) {
// mName = iterations.get(0).mName;
// mVariable = iterations.get(0).mVariable;
// mIterations = iterations.size();
// mElapsedTime = 0;
// for (Metrics m : iterations) {
// mElapsedTime += m.mElapsedTime;
// }
// mElapsedTime = (long) (mElapsedTime*1.0f / iterations.size());
// }
//
// public void started() {
// mStartTime = System.nanoTime();
// }
//
// public void finished() {
// mEndTime = System.nanoTime();
// mElapsedTime = mEndTime - mStartTime;
// }
//
// @Override
// public String toString() {
// StringBuilder sb = new StringBuilder();
// sb.append(mName);
// sb.append(":\n");
// if (mIterations > 1) {
// sb.append(mIterations);
// sb.append(" iterations, each averaged ");
// } else {
// sb.append("took ");
// }
// sb.append(((float) mElapsedTime / mIterations) / 1000000f);
// sb.append(" seconds");
// return sb.toString();
// }
//
// public float getVariable() {
// return mVariable;
// }
//
// public long getElapsedTime() {
// return mElapsedTime;
// }
// }
//
// }
//
// Path: app/src/main/java/co/jasonwyatt/sqliteperf/inserts/DbHelper.java
// public class DbHelper extends SQLiteOpenHelper {
// public DbHelper(Context context, String name) {
// super(context, name, null, 1);
// }
//
// @Override
// public void onCreate(SQLiteDatabase db) {
// db.execSQL("CREATE TABLE inserts_1 (val INTEGER)");
// db.execSQL("CREATE TABLE tracks (id INTEGER PRIMARY KEY, title TEXT, band_id INTEGER, duration FLOAT, url TEXT, lyrics TEXT, about TEXT, release_date INTEGER, mod_date INTEGER)");
// }
//
// @Override
// public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {}
// }
// Path: app/src/main/java/co/jasonwyatt/sqliteperf/inserts/integers/IntegerInsertsRawTransactionCase.java
import android.database.sqlite.SQLiteDatabase;
import android.util.Log;
import java.util.Random;
import co.jasonwyatt.sqliteperf.App;
import co.jasonwyatt.sqliteperf.TestCase;
import co.jasonwyatt.sqliteperf.inserts.DbHelper;
package co.jasonwyatt.sqliteperf.inserts.integers;
/**
* @author jason
*/
public class IntegerInsertsRawTransactionCase implements TestCase {
private DbHelper mDbHelper;
private final Random mRandom;
private final int mInsertions;
private final int mTestSizeIndex;
public IntegerInsertsRawTransactionCase(int insertions, int testSizeIndex) {
mRandom = new Random(System.currentTimeMillis());
mInsertions = insertions;
mTestSizeIndex = testSizeIndex;
}
@Override
public void resetCase() {
mDbHelper.getWritableDatabase().execSQL("delete from inserts_1");
mDbHelper.close();
}
@Override
public Metrics runCase() { | mDbHelper = new DbHelper(App.getInstance(), IntegerInsertsRawTransactionCase.class.getSimpleName()); |
jasonwyatt/SQLite-Performance | app/src/main/java/co/jasonwyatt/sqliteperf/inserts/integers/IntegerSQLiteStatementBatchTransactionCase.java | // Path: app/src/main/java/co/jasonwyatt/sqliteperf/App.java
// public class App extends Application {
// private static App sInstance;
//
// @Override
// public void onCreate() {
// super.onCreate();
// sInstance = this;
// }
//
// public static App getInstance() {
// return sInstance;
// }
// }
//
// Path: app/src/main/java/co/jasonwyatt/sqliteperf/TestCase.java
// public interface TestCase {
// void resetCase();
// Metrics runCase();
//
// class Metrics {
// private final String mName;
// private final float mVariable;
// private int mIterations = 1;
// private long mStartTime;
// private long mEndTime;
// private long mElapsedTime;
//
// public Metrics(String name, float variable) {
// mName = name;
// mVariable = variable;
// }
//
// Metrics(List<Metrics> iterations) {
// mName = iterations.get(0).mName;
// mVariable = iterations.get(0).mVariable;
// mIterations = iterations.size();
// mElapsedTime = 0;
// for (Metrics m : iterations) {
// mElapsedTime += m.mElapsedTime;
// }
// mElapsedTime = (long) (mElapsedTime*1.0f / iterations.size());
// }
//
// public void started() {
// mStartTime = System.nanoTime();
// }
//
// public void finished() {
// mEndTime = System.nanoTime();
// mElapsedTime = mEndTime - mStartTime;
// }
//
// @Override
// public String toString() {
// StringBuilder sb = new StringBuilder();
// sb.append(mName);
// sb.append(":\n");
// if (mIterations > 1) {
// sb.append(mIterations);
// sb.append(" iterations, each averaged ");
// } else {
// sb.append("took ");
// }
// sb.append(((float) mElapsedTime / mIterations) / 1000000f);
// sb.append(" seconds");
// return sb.toString();
// }
//
// public float getVariable() {
// return mVariable;
// }
//
// public long getElapsedTime() {
// return mElapsedTime;
// }
// }
//
// }
//
// Path: app/src/main/java/co/jasonwyatt/sqliteperf/inserts/DbHelper.java
// public class DbHelper extends SQLiteOpenHelper {
// public DbHelper(Context context, String name) {
// super(context, name, null, 1);
// }
//
// @Override
// public void onCreate(SQLiteDatabase db) {
// db.execSQL("CREATE TABLE inserts_1 (val INTEGER)");
// db.execSQL("CREATE TABLE tracks (id INTEGER PRIMARY KEY, title TEXT, band_id INTEGER, duration FLOAT, url TEXT, lyrics TEXT, about TEXT, release_date INTEGER, mod_date INTEGER)");
// }
//
// @Override
// public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {}
// }
| import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteStatement;
import android.util.Log;
import java.util.HashMap;
import java.util.Map;
import java.util.Random;
import co.jasonwyatt.sqliteperf.App;
import co.jasonwyatt.sqliteperf.TestCase;
import co.jasonwyatt.sqliteperf.inserts.DbHelper; | package co.jasonwyatt.sqliteperf.inserts.integers;
/**
* @author jason
*/
public class IntegerSQLiteStatementBatchTransactionCase implements TestCase {
private DbHelper mDbHelper;
private final Random mRandom;
private final int mInsertions;
private final int mTestSizeIndex;
public IntegerSQLiteStatementBatchTransactionCase(int insertions, int testSizeIndex) {
mRandom = new Random(System.currentTimeMillis());
mInsertions = insertions;
mTestSizeIndex = testSizeIndex;
}
@Override
public void resetCase() {
mDbHelper.getWritableDatabase().execSQL("delete from inserts_1");
mDbHelper.close();
}
@Override
public Metrics runCase() { | // Path: app/src/main/java/co/jasonwyatt/sqliteperf/App.java
// public class App extends Application {
// private static App sInstance;
//
// @Override
// public void onCreate() {
// super.onCreate();
// sInstance = this;
// }
//
// public static App getInstance() {
// return sInstance;
// }
// }
//
// Path: app/src/main/java/co/jasonwyatt/sqliteperf/TestCase.java
// public interface TestCase {
// void resetCase();
// Metrics runCase();
//
// class Metrics {
// private final String mName;
// private final float mVariable;
// private int mIterations = 1;
// private long mStartTime;
// private long mEndTime;
// private long mElapsedTime;
//
// public Metrics(String name, float variable) {
// mName = name;
// mVariable = variable;
// }
//
// Metrics(List<Metrics> iterations) {
// mName = iterations.get(0).mName;
// mVariable = iterations.get(0).mVariable;
// mIterations = iterations.size();
// mElapsedTime = 0;
// for (Metrics m : iterations) {
// mElapsedTime += m.mElapsedTime;
// }
// mElapsedTime = (long) (mElapsedTime*1.0f / iterations.size());
// }
//
// public void started() {
// mStartTime = System.nanoTime();
// }
//
// public void finished() {
// mEndTime = System.nanoTime();
// mElapsedTime = mEndTime - mStartTime;
// }
//
// @Override
// public String toString() {
// StringBuilder sb = new StringBuilder();
// sb.append(mName);
// sb.append(":\n");
// if (mIterations > 1) {
// sb.append(mIterations);
// sb.append(" iterations, each averaged ");
// } else {
// sb.append("took ");
// }
// sb.append(((float) mElapsedTime / mIterations) / 1000000f);
// sb.append(" seconds");
// return sb.toString();
// }
//
// public float getVariable() {
// return mVariable;
// }
//
// public long getElapsedTime() {
// return mElapsedTime;
// }
// }
//
// }
//
// Path: app/src/main/java/co/jasonwyatt/sqliteperf/inserts/DbHelper.java
// public class DbHelper extends SQLiteOpenHelper {
// public DbHelper(Context context, String name) {
// super(context, name, null, 1);
// }
//
// @Override
// public void onCreate(SQLiteDatabase db) {
// db.execSQL("CREATE TABLE inserts_1 (val INTEGER)");
// db.execSQL("CREATE TABLE tracks (id INTEGER PRIMARY KEY, title TEXT, band_id INTEGER, duration FLOAT, url TEXT, lyrics TEXT, about TEXT, release_date INTEGER, mod_date INTEGER)");
// }
//
// @Override
// public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {}
// }
// Path: app/src/main/java/co/jasonwyatt/sqliteperf/inserts/integers/IntegerSQLiteStatementBatchTransactionCase.java
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteStatement;
import android.util.Log;
import java.util.HashMap;
import java.util.Map;
import java.util.Random;
import co.jasonwyatt.sqliteperf.App;
import co.jasonwyatt.sqliteperf.TestCase;
import co.jasonwyatt.sqliteperf.inserts.DbHelper;
package co.jasonwyatt.sqliteperf.inserts.integers;
/**
* @author jason
*/
public class IntegerSQLiteStatementBatchTransactionCase implements TestCase {
private DbHelper mDbHelper;
private final Random mRandom;
private final int mInsertions;
private final int mTestSizeIndex;
public IntegerSQLiteStatementBatchTransactionCase(int insertions, int testSizeIndex) {
mRandom = new Random(System.currentTimeMillis());
mInsertions = insertions;
mTestSizeIndex = testSizeIndex;
}
@Override
public void resetCase() {
mDbHelper.getWritableDatabase().execSQL("delete from inserts_1");
mDbHelper.close();
}
@Override
public Metrics runCase() { | mDbHelper = new DbHelper(App.getInstance(), IntegerSQLiteStatementBatchTransactionCase.class.getSimpleName()); |
jasonwyatt/SQLite-Performance | app/src/main/java/co/jasonwyatt/sqliteperf/inserts/tracks/InsertsTransactionTestCase.java | // Path: app/src/main/java/co/jasonwyatt/sqliteperf/App.java
// public class App extends Application {
// private static App sInstance;
//
// @Override
// public void onCreate() {
// super.onCreate();
// sInstance = this;
// }
//
// public static App getInstance() {
// return sInstance;
// }
// }
//
// Path: app/src/main/java/co/jasonwyatt/sqliteperf/TestCase.java
// public interface TestCase {
// void resetCase();
// Metrics runCase();
//
// class Metrics {
// private final String mName;
// private final float mVariable;
// private int mIterations = 1;
// private long mStartTime;
// private long mEndTime;
// private long mElapsedTime;
//
// public Metrics(String name, float variable) {
// mName = name;
// mVariable = variable;
// }
//
// Metrics(List<Metrics> iterations) {
// mName = iterations.get(0).mName;
// mVariable = iterations.get(0).mVariable;
// mIterations = iterations.size();
// mElapsedTime = 0;
// for (Metrics m : iterations) {
// mElapsedTime += m.mElapsedTime;
// }
// mElapsedTime = (long) (mElapsedTime*1.0f / iterations.size());
// }
//
// public void started() {
// mStartTime = System.nanoTime();
// }
//
// public void finished() {
// mEndTime = System.nanoTime();
// mElapsedTime = mEndTime - mStartTime;
// }
//
// @Override
// public String toString() {
// StringBuilder sb = new StringBuilder();
// sb.append(mName);
// sb.append(":\n");
// if (mIterations > 1) {
// sb.append(mIterations);
// sb.append(" iterations, each averaged ");
// } else {
// sb.append("took ");
// }
// sb.append(((float) mElapsedTime / mIterations) / 1000000f);
// sb.append(" seconds");
// return sb.toString();
// }
//
// public float getVariable() {
// return mVariable;
// }
//
// public long getElapsedTime() {
// return mElapsedTime;
// }
// }
//
// }
//
// Path: app/src/main/java/co/jasonwyatt/sqliteperf/inserts/DbHelper.java
// public class DbHelper extends SQLiteOpenHelper {
// public DbHelper(Context context, String name) {
// super(context, name, null, 1);
// }
//
// @Override
// public void onCreate(SQLiteDatabase db) {
// db.execSQL("CREATE TABLE inserts_1 (val INTEGER)");
// db.execSQL("CREATE TABLE tracks (id INTEGER PRIMARY KEY, title TEXT, band_id INTEGER, duration FLOAT, url TEXT, lyrics TEXT, about TEXT, release_date INTEGER, mod_date INTEGER)");
// }
//
// @Override
// public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {}
// }
| import android.content.ContentValues;
import android.database.sqlite.SQLiteDatabase;
import java.nio.charset.Charset;
import java.util.Random;
import co.jasonwyatt.sqliteperf.App;
import co.jasonwyatt.sqliteperf.TestCase;
import co.jasonwyatt.sqliteperf.inserts.DbHelper; | package co.jasonwyatt.sqliteperf.inserts.tracks;
/**
* @author jason
*/
public class InsertsTransactionTestCase implements TestCase {
private DbHelper mDbHelper;
private final Random mRandom;
private final int mInsertions;
private final int mTestSizeIndex;
public InsertsTransactionTestCase(int insertions, int testSizeIndex) {
mRandom = new Random(System.currentTimeMillis());
mInsertions = insertions;
mTestSizeIndex = testSizeIndex;
}
@Override
public void resetCase() {
mDbHelper.getWritableDatabase().execSQL("delete from tracks");
mDbHelper.close();
}
@Override
public Metrics runCase() { | // Path: app/src/main/java/co/jasonwyatt/sqliteperf/App.java
// public class App extends Application {
// private static App sInstance;
//
// @Override
// public void onCreate() {
// super.onCreate();
// sInstance = this;
// }
//
// public static App getInstance() {
// return sInstance;
// }
// }
//
// Path: app/src/main/java/co/jasonwyatt/sqliteperf/TestCase.java
// public interface TestCase {
// void resetCase();
// Metrics runCase();
//
// class Metrics {
// private final String mName;
// private final float mVariable;
// private int mIterations = 1;
// private long mStartTime;
// private long mEndTime;
// private long mElapsedTime;
//
// public Metrics(String name, float variable) {
// mName = name;
// mVariable = variable;
// }
//
// Metrics(List<Metrics> iterations) {
// mName = iterations.get(0).mName;
// mVariable = iterations.get(0).mVariable;
// mIterations = iterations.size();
// mElapsedTime = 0;
// for (Metrics m : iterations) {
// mElapsedTime += m.mElapsedTime;
// }
// mElapsedTime = (long) (mElapsedTime*1.0f / iterations.size());
// }
//
// public void started() {
// mStartTime = System.nanoTime();
// }
//
// public void finished() {
// mEndTime = System.nanoTime();
// mElapsedTime = mEndTime - mStartTime;
// }
//
// @Override
// public String toString() {
// StringBuilder sb = new StringBuilder();
// sb.append(mName);
// sb.append(":\n");
// if (mIterations > 1) {
// sb.append(mIterations);
// sb.append(" iterations, each averaged ");
// } else {
// sb.append("took ");
// }
// sb.append(((float) mElapsedTime / mIterations) / 1000000f);
// sb.append(" seconds");
// return sb.toString();
// }
//
// public float getVariable() {
// return mVariable;
// }
//
// public long getElapsedTime() {
// return mElapsedTime;
// }
// }
//
// }
//
// Path: app/src/main/java/co/jasonwyatt/sqliteperf/inserts/DbHelper.java
// public class DbHelper extends SQLiteOpenHelper {
// public DbHelper(Context context, String name) {
// super(context, name, null, 1);
// }
//
// @Override
// public void onCreate(SQLiteDatabase db) {
// db.execSQL("CREATE TABLE inserts_1 (val INTEGER)");
// db.execSQL("CREATE TABLE tracks (id INTEGER PRIMARY KEY, title TEXT, band_id INTEGER, duration FLOAT, url TEXT, lyrics TEXT, about TEXT, release_date INTEGER, mod_date INTEGER)");
// }
//
// @Override
// public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {}
// }
// Path: app/src/main/java/co/jasonwyatt/sqliteperf/inserts/tracks/InsertsTransactionTestCase.java
import android.content.ContentValues;
import android.database.sqlite.SQLiteDatabase;
import java.nio.charset.Charset;
import java.util.Random;
import co.jasonwyatt.sqliteperf.App;
import co.jasonwyatt.sqliteperf.TestCase;
import co.jasonwyatt.sqliteperf.inserts.DbHelper;
package co.jasonwyatt.sqliteperf.inserts.tracks;
/**
* @author jason
*/
public class InsertsTransactionTestCase implements TestCase {
private DbHelper mDbHelper;
private final Random mRandom;
private final int mInsertions;
private final int mTestSizeIndex;
public InsertsTransactionTestCase(int insertions, int testSizeIndex) {
mRandom = new Random(System.currentTimeMillis());
mInsertions = insertions;
mTestSizeIndex = testSizeIndex;
}
@Override
public void resetCase() {
mDbHelper.getWritableDatabase().execSQL("delete from tracks");
mDbHelper.close();
}
@Override
public Metrics runCase() { | mDbHelper = new DbHelper(App.getInstance(), getClass().getName()); |
jasonwyatt/SQLite-Performance | app/src/main/java/co/jasonwyatt/sqliteperf/inserts/tracks/BatchedSQLiteStatementTestCase.java | // Path: app/src/main/java/co/jasonwyatt/sqliteperf/App.java
// public class App extends Application {
// private static App sInstance;
//
// @Override
// public void onCreate() {
// super.onCreate();
// sInstance = this;
// }
//
// public static App getInstance() {
// return sInstance;
// }
// }
//
// Path: app/src/main/java/co/jasonwyatt/sqliteperf/TestCase.java
// public interface TestCase {
// void resetCase();
// Metrics runCase();
//
// class Metrics {
// private final String mName;
// private final float mVariable;
// private int mIterations = 1;
// private long mStartTime;
// private long mEndTime;
// private long mElapsedTime;
//
// public Metrics(String name, float variable) {
// mName = name;
// mVariable = variable;
// }
//
// Metrics(List<Metrics> iterations) {
// mName = iterations.get(0).mName;
// mVariable = iterations.get(0).mVariable;
// mIterations = iterations.size();
// mElapsedTime = 0;
// for (Metrics m : iterations) {
// mElapsedTime += m.mElapsedTime;
// }
// mElapsedTime = (long) (mElapsedTime*1.0f / iterations.size());
// }
//
// public void started() {
// mStartTime = System.nanoTime();
// }
//
// public void finished() {
// mEndTime = System.nanoTime();
// mElapsedTime = mEndTime - mStartTime;
// }
//
// @Override
// public String toString() {
// StringBuilder sb = new StringBuilder();
// sb.append(mName);
// sb.append(":\n");
// if (mIterations > 1) {
// sb.append(mIterations);
// sb.append(" iterations, each averaged ");
// } else {
// sb.append("took ");
// }
// sb.append(((float) mElapsedTime / mIterations) / 1000000f);
// sb.append(" seconds");
// return sb.toString();
// }
//
// public float getVariable() {
// return mVariable;
// }
//
// public long getElapsedTime() {
// return mElapsedTime;
// }
// }
//
// }
//
// Path: app/src/main/java/co/jasonwyatt/sqliteperf/inserts/DbHelper.java
// public class DbHelper extends SQLiteOpenHelper {
// public DbHelper(Context context, String name) {
// super(context, name, null, 1);
// }
//
// @Override
// public void onCreate(SQLiteDatabase db) {
// db.execSQL("CREATE TABLE inserts_1 (val INTEGER)");
// db.execSQL("CREATE TABLE tracks (id INTEGER PRIMARY KEY, title TEXT, band_id INTEGER, duration FLOAT, url TEXT, lyrics TEXT, about TEXT, release_date INTEGER, mod_date INTEGER)");
// }
//
// @Override
// public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {}
// }
| import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteStatement;
import java.nio.charset.Charset;
import java.util.HashMap;
import java.util.Map;
import java.util.Random;
import co.jasonwyatt.sqliteperf.App;
import co.jasonwyatt.sqliteperf.TestCase;
import co.jasonwyatt.sqliteperf.inserts.DbHelper; | package co.jasonwyatt.sqliteperf.inserts.tracks;
/**
* @author jason
*/
public class BatchedSQLiteStatementTestCase implements TestCase {
private DbHelper mDbHelper;
private final Random mRandom;
private final int mInsertions;
private final int mTestSizeIndex;
private int mInsertId;
public BatchedSQLiteStatementTestCase(int insertions, int testSizeIndex) {
mRandom = new Random(System.currentTimeMillis());
mInsertions = insertions;
mTestSizeIndex = testSizeIndex;
}
@Override
public void resetCase() {
mDbHelper.getWritableDatabase().execSQL("delete from tracks");
mDbHelper.close();
}
@Override
public Metrics runCase() { | // Path: app/src/main/java/co/jasonwyatt/sqliteperf/App.java
// public class App extends Application {
// private static App sInstance;
//
// @Override
// public void onCreate() {
// super.onCreate();
// sInstance = this;
// }
//
// public static App getInstance() {
// return sInstance;
// }
// }
//
// Path: app/src/main/java/co/jasonwyatt/sqliteperf/TestCase.java
// public interface TestCase {
// void resetCase();
// Metrics runCase();
//
// class Metrics {
// private final String mName;
// private final float mVariable;
// private int mIterations = 1;
// private long mStartTime;
// private long mEndTime;
// private long mElapsedTime;
//
// public Metrics(String name, float variable) {
// mName = name;
// mVariable = variable;
// }
//
// Metrics(List<Metrics> iterations) {
// mName = iterations.get(0).mName;
// mVariable = iterations.get(0).mVariable;
// mIterations = iterations.size();
// mElapsedTime = 0;
// for (Metrics m : iterations) {
// mElapsedTime += m.mElapsedTime;
// }
// mElapsedTime = (long) (mElapsedTime*1.0f / iterations.size());
// }
//
// public void started() {
// mStartTime = System.nanoTime();
// }
//
// public void finished() {
// mEndTime = System.nanoTime();
// mElapsedTime = mEndTime - mStartTime;
// }
//
// @Override
// public String toString() {
// StringBuilder sb = new StringBuilder();
// sb.append(mName);
// sb.append(":\n");
// if (mIterations > 1) {
// sb.append(mIterations);
// sb.append(" iterations, each averaged ");
// } else {
// sb.append("took ");
// }
// sb.append(((float) mElapsedTime / mIterations) / 1000000f);
// sb.append(" seconds");
// return sb.toString();
// }
//
// public float getVariable() {
// return mVariable;
// }
//
// public long getElapsedTime() {
// return mElapsedTime;
// }
// }
//
// }
//
// Path: app/src/main/java/co/jasonwyatt/sqliteperf/inserts/DbHelper.java
// public class DbHelper extends SQLiteOpenHelper {
// public DbHelper(Context context, String name) {
// super(context, name, null, 1);
// }
//
// @Override
// public void onCreate(SQLiteDatabase db) {
// db.execSQL("CREATE TABLE inserts_1 (val INTEGER)");
// db.execSQL("CREATE TABLE tracks (id INTEGER PRIMARY KEY, title TEXT, band_id INTEGER, duration FLOAT, url TEXT, lyrics TEXT, about TEXT, release_date INTEGER, mod_date INTEGER)");
// }
//
// @Override
// public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {}
// }
// Path: app/src/main/java/co/jasonwyatt/sqliteperf/inserts/tracks/BatchedSQLiteStatementTestCase.java
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteStatement;
import java.nio.charset.Charset;
import java.util.HashMap;
import java.util.Map;
import java.util.Random;
import co.jasonwyatt.sqliteperf.App;
import co.jasonwyatt.sqliteperf.TestCase;
import co.jasonwyatt.sqliteperf.inserts.DbHelper;
package co.jasonwyatt.sqliteperf.inserts.tracks;
/**
* @author jason
*/
public class BatchedSQLiteStatementTestCase implements TestCase {
private DbHelper mDbHelper;
private final Random mRandom;
private final int mInsertions;
private final int mTestSizeIndex;
private int mInsertId;
public BatchedSQLiteStatementTestCase(int insertions, int testSizeIndex) {
mRandom = new Random(System.currentTimeMillis());
mInsertions = insertions;
mTestSizeIndex = testSizeIndex;
}
@Override
public void resetCase() {
mDbHelper.getWritableDatabase().execSQL("delete from tracks");
mDbHelper.close();
}
@Override
public Metrics runCase() { | mDbHelper = new DbHelper(App.getInstance(), getClass().getName()); |
jasonwyatt/SQLite-Performance | app/src/main/java/co/jasonwyatt/sqliteperf/inserts/tracks/TracksRoomTestCase.java | // Path: app/src/main/java/co/jasonwyatt/sqliteperf/App.java
// public class App extends Application {
// private static App sInstance;
//
// @Override
// public void onCreate() {
// super.onCreate();
// sInstance = this;
// }
//
// public static App getInstance() {
// return sInstance;
// }
// }
//
// Path: app/src/main/java/co/jasonwyatt/sqliteperf/TestCase.java
// public interface TestCase {
// void resetCase();
// Metrics runCase();
//
// class Metrics {
// private final String mName;
// private final float mVariable;
// private int mIterations = 1;
// private long mStartTime;
// private long mEndTime;
// private long mElapsedTime;
//
// public Metrics(String name, float variable) {
// mName = name;
// mVariable = variable;
// }
//
// Metrics(List<Metrics> iterations) {
// mName = iterations.get(0).mName;
// mVariable = iterations.get(0).mVariable;
// mIterations = iterations.size();
// mElapsedTime = 0;
// for (Metrics m : iterations) {
// mElapsedTime += m.mElapsedTime;
// }
// mElapsedTime = (long) (mElapsedTime*1.0f / iterations.size());
// }
//
// public void started() {
// mStartTime = System.nanoTime();
// }
//
// public void finished() {
// mEndTime = System.nanoTime();
// mElapsedTime = mEndTime - mStartTime;
// }
//
// @Override
// public String toString() {
// StringBuilder sb = new StringBuilder();
// sb.append(mName);
// sb.append(":\n");
// if (mIterations > 1) {
// sb.append(mIterations);
// sb.append(" iterations, each averaged ");
// } else {
// sb.append("took ");
// }
// sb.append(((float) mElapsedTime / mIterations) / 1000000f);
// sb.append(" seconds");
// return sb.toString();
// }
//
// public float getVariable() {
// return mVariable;
// }
//
// public long getElapsedTime() {
// return mElapsedTime;
// }
// }
//
// }
//
// Path: app/src/main/java/co/jasonwyatt/sqliteperf/inserts/room/Db.java
// @Database(entities = {TrackInfo.class, IntegerInfo.class}, version = 1)
// public abstract class Db extends RoomDatabase {
// public abstract IntegersDao integers();
// public abstract TracksDao tracks();
// }
//
// Path: app/src/main/java/co/jasonwyatt/sqliteperf/inserts/room/TrackInfo.java
// @Entity(tableName = "tracks")
// public class TrackInfo {
// @PrimaryKey
// @ColumnInfo(name = "id")
// private long mId;
// @ColumnInfo(name = "title")
// private String mTitle;
// @ColumnInfo(name = "band_id")
// private long mBandId;
// @ColumnInfo(name = "duration")
// private double mDuration;
// @ColumnInfo(name = "url")
// private String mUrl;
// @ColumnInfo(name = "lyrics")
// private String mLyrics;
// @ColumnInfo(name = "about")
// private String mAbout;
// @ColumnInfo(name = "release_date")
// private long mReleaseDate;
// @ColumnInfo(name = "mod_Date")
// private long mModDate;
//
// public long getId() {
// return mId;
// }
//
// public void setId(long id) {
// mId = id;
// }
//
// public String getTitle() {
// return mTitle;
// }
//
// public void setTitle(String title) {
// mTitle = title;
// }
//
// public long getBandId() {
// return mBandId;
// }
//
// public void setBandId(long bandId) {
// mBandId = bandId;
// }
//
// public double getDuration() {
// return mDuration;
// }
//
// public void setDuration(double duration) {
// mDuration = duration;
// }
//
// public String getUrl() {
// return mUrl;
// }
//
// public void setUrl(String url) {
// mUrl = url;
// }
//
// public String getLyrics() {
// return mLyrics;
// }
//
// public void setLyrics(String lyrics) {
// mLyrics = lyrics;
// }
//
// public String getAbout() {
// return mAbout;
// }
//
// public void setAbout(String about) {
// mAbout = about;
// }
//
// public long getReleaseDate() {
// return mReleaseDate;
// }
//
// public void setReleaseDate(long releaseDate) {
// mReleaseDate = releaseDate;
// }
//
// public long getModDate() {
// return mModDate;
// }
//
// public void setModDate(long modDate) {
// mModDate = modDate;
// }
// }
| import android.arch.persistence.room.Room;
import java.nio.charset.Charset;
import java.util.Random;
import co.jasonwyatt.sqliteperf.App;
import co.jasonwyatt.sqliteperf.TestCase;
import co.jasonwyatt.sqliteperf.inserts.room.Db;
import co.jasonwyatt.sqliteperf.inserts.room.TrackInfo; | package co.jasonwyatt.sqliteperf.inserts.tracks;
/**
* @author jason
*/
public class TracksRoomTestCase implements TestCase {
private final Db mDb;
private final Random mRandom;
private final int mInsertions;
private final int mTestSizeIndex;
public TracksRoomTestCase(int insertions, int testSizeIndex) { | // Path: app/src/main/java/co/jasonwyatt/sqliteperf/App.java
// public class App extends Application {
// private static App sInstance;
//
// @Override
// public void onCreate() {
// super.onCreate();
// sInstance = this;
// }
//
// public static App getInstance() {
// return sInstance;
// }
// }
//
// Path: app/src/main/java/co/jasonwyatt/sqliteperf/TestCase.java
// public interface TestCase {
// void resetCase();
// Metrics runCase();
//
// class Metrics {
// private final String mName;
// private final float mVariable;
// private int mIterations = 1;
// private long mStartTime;
// private long mEndTime;
// private long mElapsedTime;
//
// public Metrics(String name, float variable) {
// mName = name;
// mVariable = variable;
// }
//
// Metrics(List<Metrics> iterations) {
// mName = iterations.get(0).mName;
// mVariable = iterations.get(0).mVariable;
// mIterations = iterations.size();
// mElapsedTime = 0;
// for (Metrics m : iterations) {
// mElapsedTime += m.mElapsedTime;
// }
// mElapsedTime = (long) (mElapsedTime*1.0f / iterations.size());
// }
//
// public void started() {
// mStartTime = System.nanoTime();
// }
//
// public void finished() {
// mEndTime = System.nanoTime();
// mElapsedTime = mEndTime - mStartTime;
// }
//
// @Override
// public String toString() {
// StringBuilder sb = new StringBuilder();
// sb.append(mName);
// sb.append(":\n");
// if (mIterations > 1) {
// sb.append(mIterations);
// sb.append(" iterations, each averaged ");
// } else {
// sb.append("took ");
// }
// sb.append(((float) mElapsedTime / mIterations) / 1000000f);
// sb.append(" seconds");
// return sb.toString();
// }
//
// public float getVariable() {
// return mVariable;
// }
//
// public long getElapsedTime() {
// return mElapsedTime;
// }
// }
//
// }
//
// Path: app/src/main/java/co/jasonwyatt/sqliteperf/inserts/room/Db.java
// @Database(entities = {TrackInfo.class, IntegerInfo.class}, version = 1)
// public abstract class Db extends RoomDatabase {
// public abstract IntegersDao integers();
// public abstract TracksDao tracks();
// }
//
// Path: app/src/main/java/co/jasonwyatt/sqliteperf/inserts/room/TrackInfo.java
// @Entity(tableName = "tracks")
// public class TrackInfo {
// @PrimaryKey
// @ColumnInfo(name = "id")
// private long mId;
// @ColumnInfo(name = "title")
// private String mTitle;
// @ColumnInfo(name = "band_id")
// private long mBandId;
// @ColumnInfo(name = "duration")
// private double mDuration;
// @ColumnInfo(name = "url")
// private String mUrl;
// @ColumnInfo(name = "lyrics")
// private String mLyrics;
// @ColumnInfo(name = "about")
// private String mAbout;
// @ColumnInfo(name = "release_date")
// private long mReleaseDate;
// @ColumnInfo(name = "mod_Date")
// private long mModDate;
//
// public long getId() {
// return mId;
// }
//
// public void setId(long id) {
// mId = id;
// }
//
// public String getTitle() {
// return mTitle;
// }
//
// public void setTitle(String title) {
// mTitle = title;
// }
//
// public long getBandId() {
// return mBandId;
// }
//
// public void setBandId(long bandId) {
// mBandId = bandId;
// }
//
// public double getDuration() {
// return mDuration;
// }
//
// public void setDuration(double duration) {
// mDuration = duration;
// }
//
// public String getUrl() {
// return mUrl;
// }
//
// public void setUrl(String url) {
// mUrl = url;
// }
//
// public String getLyrics() {
// return mLyrics;
// }
//
// public void setLyrics(String lyrics) {
// mLyrics = lyrics;
// }
//
// public String getAbout() {
// return mAbout;
// }
//
// public void setAbout(String about) {
// mAbout = about;
// }
//
// public long getReleaseDate() {
// return mReleaseDate;
// }
//
// public void setReleaseDate(long releaseDate) {
// mReleaseDate = releaseDate;
// }
//
// public long getModDate() {
// return mModDate;
// }
//
// public void setModDate(long modDate) {
// mModDate = modDate;
// }
// }
// Path: app/src/main/java/co/jasonwyatt/sqliteperf/inserts/tracks/TracksRoomTestCase.java
import android.arch.persistence.room.Room;
import java.nio.charset.Charset;
import java.util.Random;
import co.jasonwyatt.sqliteperf.App;
import co.jasonwyatt.sqliteperf.TestCase;
import co.jasonwyatt.sqliteperf.inserts.room.Db;
import co.jasonwyatt.sqliteperf.inserts.room.TrackInfo;
package co.jasonwyatt.sqliteperf.inserts.tracks;
/**
* @author jason
*/
public class TracksRoomTestCase implements TestCase {
private final Db mDb;
private final Random mRandom;
private final int mInsertions;
private final int mTestSizeIndex;
public TracksRoomTestCase(int insertions, int testSizeIndex) { | mDb = Room.databaseBuilder(App.getInstance(), Db.class, "room").build(); |
jasonwyatt/SQLite-Performance | app/src/main/java/co/jasonwyatt/sqliteperf/inserts/integers/IntegerSQLiteStatementTransactionCase.java | // Path: app/src/main/java/co/jasonwyatt/sqliteperf/App.java
// public class App extends Application {
// private static App sInstance;
//
// @Override
// public void onCreate() {
// super.onCreate();
// sInstance = this;
// }
//
// public static App getInstance() {
// return sInstance;
// }
// }
//
// Path: app/src/main/java/co/jasonwyatt/sqliteperf/TestCase.java
// public interface TestCase {
// void resetCase();
// Metrics runCase();
//
// class Metrics {
// private final String mName;
// private final float mVariable;
// private int mIterations = 1;
// private long mStartTime;
// private long mEndTime;
// private long mElapsedTime;
//
// public Metrics(String name, float variable) {
// mName = name;
// mVariable = variable;
// }
//
// Metrics(List<Metrics> iterations) {
// mName = iterations.get(0).mName;
// mVariable = iterations.get(0).mVariable;
// mIterations = iterations.size();
// mElapsedTime = 0;
// for (Metrics m : iterations) {
// mElapsedTime += m.mElapsedTime;
// }
// mElapsedTime = (long) (mElapsedTime*1.0f / iterations.size());
// }
//
// public void started() {
// mStartTime = System.nanoTime();
// }
//
// public void finished() {
// mEndTime = System.nanoTime();
// mElapsedTime = mEndTime - mStartTime;
// }
//
// @Override
// public String toString() {
// StringBuilder sb = new StringBuilder();
// sb.append(mName);
// sb.append(":\n");
// if (mIterations > 1) {
// sb.append(mIterations);
// sb.append(" iterations, each averaged ");
// } else {
// sb.append("took ");
// }
// sb.append(((float) mElapsedTime / mIterations) / 1000000f);
// sb.append(" seconds");
// return sb.toString();
// }
//
// public float getVariable() {
// return mVariable;
// }
//
// public long getElapsedTime() {
// return mElapsedTime;
// }
// }
//
// }
//
// Path: app/src/main/java/co/jasonwyatt/sqliteperf/inserts/DbHelper.java
// public class DbHelper extends SQLiteOpenHelper {
// public DbHelper(Context context, String name) {
// super(context, name, null, 1);
// }
//
// @Override
// public void onCreate(SQLiteDatabase db) {
// db.execSQL("CREATE TABLE inserts_1 (val INTEGER)");
// db.execSQL("CREATE TABLE tracks (id INTEGER PRIMARY KEY, title TEXT, band_id INTEGER, duration FLOAT, url TEXT, lyrics TEXT, about TEXT, release_date INTEGER, mod_date INTEGER)");
// }
//
// @Override
// public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {}
// }
| import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteStatement;
import android.util.Log;
import java.util.Random;
import co.jasonwyatt.sqliteperf.App;
import co.jasonwyatt.sqliteperf.TestCase;
import co.jasonwyatt.sqliteperf.inserts.DbHelper; | package co.jasonwyatt.sqliteperf.inserts.integers;
/**
* @author jason
*/
public class IntegerSQLiteStatementTransactionCase implements TestCase {
private DbHelper mDbHelper;
private final Random mRandom;
private final int mInsertions;
private final int mTestSizeIndex;
public IntegerSQLiteStatementTransactionCase(int insertions, int testSizeIndex) {
mRandom = new Random(System.currentTimeMillis());
mInsertions = insertions;
mTestSizeIndex = testSizeIndex;
}
@Override
public void resetCase() {
mDbHelper.getWritableDatabase().execSQL("delete from inserts_1");
mDbHelper.close();
}
@Override
public Metrics runCase() { | // Path: app/src/main/java/co/jasonwyatt/sqliteperf/App.java
// public class App extends Application {
// private static App sInstance;
//
// @Override
// public void onCreate() {
// super.onCreate();
// sInstance = this;
// }
//
// public static App getInstance() {
// return sInstance;
// }
// }
//
// Path: app/src/main/java/co/jasonwyatt/sqliteperf/TestCase.java
// public interface TestCase {
// void resetCase();
// Metrics runCase();
//
// class Metrics {
// private final String mName;
// private final float mVariable;
// private int mIterations = 1;
// private long mStartTime;
// private long mEndTime;
// private long mElapsedTime;
//
// public Metrics(String name, float variable) {
// mName = name;
// mVariable = variable;
// }
//
// Metrics(List<Metrics> iterations) {
// mName = iterations.get(0).mName;
// mVariable = iterations.get(0).mVariable;
// mIterations = iterations.size();
// mElapsedTime = 0;
// for (Metrics m : iterations) {
// mElapsedTime += m.mElapsedTime;
// }
// mElapsedTime = (long) (mElapsedTime*1.0f / iterations.size());
// }
//
// public void started() {
// mStartTime = System.nanoTime();
// }
//
// public void finished() {
// mEndTime = System.nanoTime();
// mElapsedTime = mEndTime - mStartTime;
// }
//
// @Override
// public String toString() {
// StringBuilder sb = new StringBuilder();
// sb.append(mName);
// sb.append(":\n");
// if (mIterations > 1) {
// sb.append(mIterations);
// sb.append(" iterations, each averaged ");
// } else {
// sb.append("took ");
// }
// sb.append(((float) mElapsedTime / mIterations) / 1000000f);
// sb.append(" seconds");
// return sb.toString();
// }
//
// public float getVariable() {
// return mVariable;
// }
//
// public long getElapsedTime() {
// return mElapsedTime;
// }
// }
//
// }
//
// Path: app/src/main/java/co/jasonwyatt/sqliteperf/inserts/DbHelper.java
// public class DbHelper extends SQLiteOpenHelper {
// public DbHelper(Context context, String name) {
// super(context, name, null, 1);
// }
//
// @Override
// public void onCreate(SQLiteDatabase db) {
// db.execSQL("CREATE TABLE inserts_1 (val INTEGER)");
// db.execSQL("CREATE TABLE tracks (id INTEGER PRIMARY KEY, title TEXT, band_id INTEGER, duration FLOAT, url TEXT, lyrics TEXT, about TEXT, release_date INTEGER, mod_date INTEGER)");
// }
//
// @Override
// public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {}
// }
// Path: app/src/main/java/co/jasonwyatt/sqliteperf/inserts/integers/IntegerSQLiteStatementTransactionCase.java
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteStatement;
import android.util.Log;
import java.util.Random;
import co.jasonwyatt.sqliteperf.App;
import co.jasonwyatt.sqliteperf.TestCase;
import co.jasonwyatt.sqliteperf.inserts.DbHelper;
package co.jasonwyatt.sqliteperf.inserts.integers;
/**
* @author jason
*/
public class IntegerSQLiteStatementTransactionCase implements TestCase {
private DbHelper mDbHelper;
private final Random mRandom;
private final int mInsertions;
private final int mTestSizeIndex;
public IntegerSQLiteStatementTransactionCase(int insertions, int testSizeIndex) {
mRandom = new Random(System.currentTimeMillis());
mInsertions = insertions;
mTestSizeIndex = testSizeIndex;
}
@Override
public void resetCase() {
mDbHelper.getWritableDatabase().execSQL("delete from inserts_1");
mDbHelper.close();
}
@Override
public Metrics runCase() { | mDbHelper = new DbHelper(App.getInstance(), IntegerSQLiteStatementTransactionCase.class.getSimpleName()); |
jasonwyatt/SQLite-Performance | app/src/main/java/co/jasonwyatt/sqliteperf/inserts/integers/IntegerInsertsTransactionCase.java | // Path: app/src/main/java/co/jasonwyatt/sqliteperf/App.java
// public class App extends Application {
// private static App sInstance;
//
// @Override
// public void onCreate() {
// super.onCreate();
// sInstance = this;
// }
//
// public static App getInstance() {
// return sInstance;
// }
// }
//
// Path: app/src/main/java/co/jasonwyatt/sqliteperf/TestCase.java
// public interface TestCase {
// void resetCase();
// Metrics runCase();
//
// class Metrics {
// private final String mName;
// private final float mVariable;
// private int mIterations = 1;
// private long mStartTime;
// private long mEndTime;
// private long mElapsedTime;
//
// public Metrics(String name, float variable) {
// mName = name;
// mVariable = variable;
// }
//
// Metrics(List<Metrics> iterations) {
// mName = iterations.get(0).mName;
// mVariable = iterations.get(0).mVariable;
// mIterations = iterations.size();
// mElapsedTime = 0;
// for (Metrics m : iterations) {
// mElapsedTime += m.mElapsedTime;
// }
// mElapsedTime = (long) (mElapsedTime*1.0f / iterations.size());
// }
//
// public void started() {
// mStartTime = System.nanoTime();
// }
//
// public void finished() {
// mEndTime = System.nanoTime();
// mElapsedTime = mEndTime - mStartTime;
// }
//
// @Override
// public String toString() {
// StringBuilder sb = new StringBuilder();
// sb.append(mName);
// sb.append(":\n");
// if (mIterations > 1) {
// sb.append(mIterations);
// sb.append(" iterations, each averaged ");
// } else {
// sb.append("took ");
// }
// sb.append(((float) mElapsedTime / mIterations) / 1000000f);
// sb.append(" seconds");
// return sb.toString();
// }
//
// public float getVariable() {
// return mVariable;
// }
//
// public long getElapsedTime() {
// return mElapsedTime;
// }
// }
//
// }
//
// Path: app/src/main/java/co/jasonwyatt/sqliteperf/inserts/DbHelper.java
// public class DbHelper extends SQLiteOpenHelper {
// public DbHelper(Context context, String name) {
// super(context, name, null, 1);
// }
//
// @Override
// public void onCreate(SQLiteDatabase db) {
// db.execSQL("CREATE TABLE inserts_1 (val INTEGER)");
// db.execSQL("CREATE TABLE tracks (id INTEGER PRIMARY KEY, title TEXT, band_id INTEGER, duration FLOAT, url TEXT, lyrics TEXT, about TEXT, release_date INTEGER, mod_date INTEGER)");
// }
//
// @Override
// public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {}
// }
| import android.content.ContentValues;
import android.database.sqlite.SQLiteDatabase;
import android.util.Log;
import java.util.Random;
import co.jasonwyatt.sqliteperf.App;
import co.jasonwyatt.sqliteperf.TestCase;
import co.jasonwyatt.sqliteperf.inserts.DbHelper; | package co.jasonwyatt.sqliteperf.inserts.integers;
/**
* @author jason
*/
public class IntegerInsertsTransactionCase implements TestCase {
private DbHelper mDbHelper;
private final Random mRandom;
private final int mInsertions;
private final int mTestSizeIndex;
public IntegerInsertsTransactionCase(int insertions, int testSizeIndex) {
mRandom = new Random(System.currentTimeMillis());
mInsertions = insertions;
mTestSizeIndex = testSizeIndex;
}
@Override
public void resetCase() {
mDbHelper.getWritableDatabase().execSQL("delete from inserts_1");
mDbHelper.close();
}
@Override
public Metrics runCase() { | // Path: app/src/main/java/co/jasonwyatt/sqliteperf/App.java
// public class App extends Application {
// private static App sInstance;
//
// @Override
// public void onCreate() {
// super.onCreate();
// sInstance = this;
// }
//
// public static App getInstance() {
// return sInstance;
// }
// }
//
// Path: app/src/main/java/co/jasonwyatt/sqliteperf/TestCase.java
// public interface TestCase {
// void resetCase();
// Metrics runCase();
//
// class Metrics {
// private final String mName;
// private final float mVariable;
// private int mIterations = 1;
// private long mStartTime;
// private long mEndTime;
// private long mElapsedTime;
//
// public Metrics(String name, float variable) {
// mName = name;
// mVariable = variable;
// }
//
// Metrics(List<Metrics> iterations) {
// mName = iterations.get(0).mName;
// mVariable = iterations.get(0).mVariable;
// mIterations = iterations.size();
// mElapsedTime = 0;
// for (Metrics m : iterations) {
// mElapsedTime += m.mElapsedTime;
// }
// mElapsedTime = (long) (mElapsedTime*1.0f / iterations.size());
// }
//
// public void started() {
// mStartTime = System.nanoTime();
// }
//
// public void finished() {
// mEndTime = System.nanoTime();
// mElapsedTime = mEndTime - mStartTime;
// }
//
// @Override
// public String toString() {
// StringBuilder sb = new StringBuilder();
// sb.append(mName);
// sb.append(":\n");
// if (mIterations > 1) {
// sb.append(mIterations);
// sb.append(" iterations, each averaged ");
// } else {
// sb.append("took ");
// }
// sb.append(((float) mElapsedTime / mIterations) / 1000000f);
// sb.append(" seconds");
// return sb.toString();
// }
//
// public float getVariable() {
// return mVariable;
// }
//
// public long getElapsedTime() {
// return mElapsedTime;
// }
// }
//
// }
//
// Path: app/src/main/java/co/jasonwyatt/sqliteperf/inserts/DbHelper.java
// public class DbHelper extends SQLiteOpenHelper {
// public DbHelper(Context context, String name) {
// super(context, name, null, 1);
// }
//
// @Override
// public void onCreate(SQLiteDatabase db) {
// db.execSQL("CREATE TABLE inserts_1 (val INTEGER)");
// db.execSQL("CREATE TABLE tracks (id INTEGER PRIMARY KEY, title TEXT, band_id INTEGER, duration FLOAT, url TEXT, lyrics TEXT, about TEXT, release_date INTEGER, mod_date INTEGER)");
// }
//
// @Override
// public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {}
// }
// Path: app/src/main/java/co/jasonwyatt/sqliteperf/inserts/integers/IntegerInsertsTransactionCase.java
import android.content.ContentValues;
import android.database.sqlite.SQLiteDatabase;
import android.util.Log;
import java.util.Random;
import co.jasonwyatt.sqliteperf.App;
import co.jasonwyatt.sqliteperf.TestCase;
import co.jasonwyatt.sqliteperf.inserts.DbHelper;
package co.jasonwyatt.sqliteperf.inserts.integers;
/**
* @author jason
*/
public class IntegerInsertsTransactionCase implements TestCase {
private DbHelper mDbHelper;
private final Random mRandom;
private final int mInsertions;
private final int mTestSizeIndex;
public IntegerInsertsTransactionCase(int insertions, int testSizeIndex) {
mRandom = new Random(System.currentTimeMillis());
mInsertions = insertions;
mTestSizeIndex = testSizeIndex;
}
@Override
public void resetCase() {
mDbHelper.getWritableDatabase().execSQL("delete from inserts_1");
mDbHelper.close();
}
@Override
public Metrics runCase() { | mDbHelper = new DbHelper(App.getInstance(), IntegerInsertsTransactionCase.class.getSimpleName()); |
jasonwyatt/SQLite-Performance | app/src/main/java/co/jasonwyatt/sqliteperf/inserts/tracks/BatchedTestCase.java | // Path: app/src/main/java/co/jasonwyatt/sqliteperf/App.java
// public class App extends Application {
// private static App sInstance;
//
// @Override
// public void onCreate() {
// super.onCreate();
// sInstance = this;
// }
//
// public static App getInstance() {
// return sInstance;
// }
// }
//
// Path: app/src/main/java/co/jasonwyatt/sqliteperf/TestCase.java
// public interface TestCase {
// void resetCase();
// Metrics runCase();
//
// class Metrics {
// private final String mName;
// private final float mVariable;
// private int mIterations = 1;
// private long mStartTime;
// private long mEndTime;
// private long mElapsedTime;
//
// public Metrics(String name, float variable) {
// mName = name;
// mVariable = variable;
// }
//
// Metrics(List<Metrics> iterations) {
// mName = iterations.get(0).mName;
// mVariable = iterations.get(0).mVariable;
// mIterations = iterations.size();
// mElapsedTime = 0;
// for (Metrics m : iterations) {
// mElapsedTime += m.mElapsedTime;
// }
// mElapsedTime = (long) (mElapsedTime*1.0f / iterations.size());
// }
//
// public void started() {
// mStartTime = System.nanoTime();
// }
//
// public void finished() {
// mEndTime = System.nanoTime();
// mElapsedTime = mEndTime - mStartTime;
// }
//
// @Override
// public String toString() {
// StringBuilder sb = new StringBuilder();
// sb.append(mName);
// sb.append(":\n");
// if (mIterations > 1) {
// sb.append(mIterations);
// sb.append(" iterations, each averaged ");
// } else {
// sb.append("took ");
// }
// sb.append(((float) mElapsedTime / mIterations) / 1000000f);
// sb.append(" seconds");
// return sb.toString();
// }
//
// public float getVariable() {
// return mVariable;
// }
//
// public long getElapsedTime() {
// return mElapsedTime;
// }
// }
//
// }
//
// Path: app/src/main/java/co/jasonwyatt/sqliteperf/inserts/DbHelper.java
// public class DbHelper extends SQLiteOpenHelper {
// public DbHelper(Context context, String name) {
// super(context, name, null, 1);
// }
//
// @Override
// public void onCreate(SQLiteDatabase db) {
// db.execSQL("CREATE TABLE inserts_1 (val INTEGER)");
// db.execSQL("CREATE TABLE tracks (id INTEGER PRIMARY KEY, title TEXT, band_id INTEGER, duration FLOAT, url TEXT, lyrics TEXT, about TEXT, release_date INTEGER, mod_date INTEGER)");
// }
//
// @Override
// public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {}
// }
| import android.database.sqlite.SQLiteDatabase;
import java.nio.charset.Charset;
import java.util.Random;
import co.jasonwyatt.sqliteperf.App;
import co.jasonwyatt.sqliteperf.TestCase;
import co.jasonwyatt.sqliteperf.inserts.DbHelper; | package co.jasonwyatt.sqliteperf.inserts.tracks;
/**
* @author jason
*/
public class BatchedTestCase implements TestCase {
private DbHelper mDbHelper;
private final Random mRandom;
private final int mInsertions;
private final int mTestSizeIndex;
private int mInsertId;
public BatchedTestCase(int insertions, int testSizeIndex) {
mRandom = new Random(System.currentTimeMillis());
mInsertions = insertions;
mTestSizeIndex = testSizeIndex;
}
@Override
public void resetCase() { | // Path: app/src/main/java/co/jasonwyatt/sqliteperf/App.java
// public class App extends Application {
// private static App sInstance;
//
// @Override
// public void onCreate() {
// super.onCreate();
// sInstance = this;
// }
//
// public static App getInstance() {
// return sInstance;
// }
// }
//
// Path: app/src/main/java/co/jasonwyatt/sqliteperf/TestCase.java
// public interface TestCase {
// void resetCase();
// Metrics runCase();
//
// class Metrics {
// private final String mName;
// private final float mVariable;
// private int mIterations = 1;
// private long mStartTime;
// private long mEndTime;
// private long mElapsedTime;
//
// public Metrics(String name, float variable) {
// mName = name;
// mVariable = variable;
// }
//
// Metrics(List<Metrics> iterations) {
// mName = iterations.get(0).mName;
// mVariable = iterations.get(0).mVariable;
// mIterations = iterations.size();
// mElapsedTime = 0;
// for (Metrics m : iterations) {
// mElapsedTime += m.mElapsedTime;
// }
// mElapsedTime = (long) (mElapsedTime*1.0f / iterations.size());
// }
//
// public void started() {
// mStartTime = System.nanoTime();
// }
//
// public void finished() {
// mEndTime = System.nanoTime();
// mElapsedTime = mEndTime - mStartTime;
// }
//
// @Override
// public String toString() {
// StringBuilder sb = new StringBuilder();
// sb.append(mName);
// sb.append(":\n");
// if (mIterations > 1) {
// sb.append(mIterations);
// sb.append(" iterations, each averaged ");
// } else {
// sb.append("took ");
// }
// sb.append(((float) mElapsedTime / mIterations) / 1000000f);
// sb.append(" seconds");
// return sb.toString();
// }
//
// public float getVariable() {
// return mVariable;
// }
//
// public long getElapsedTime() {
// return mElapsedTime;
// }
// }
//
// }
//
// Path: app/src/main/java/co/jasonwyatt/sqliteperf/inserts/DbHelper.java
// public class DbHelper extends SQLiteOpenHelper {
// public DbHelper(Context context, String name) {
// super(context, name, null, 1);
// }
//
// @Override
// public void onCreate(SQLiteDatabase db) {
// db.execSQL("CREATE TABLE inserts_1 (val INTEGER)");
// db.execSQL("CREATE TABLE tracks (id INTEGER PRIMARY KEY, title TEXT, band_id INTEGER, duration FLOAT, url TEXT, lyrics TEXT, about TEXT, release_date INTEGER, mod_date INTEGER)");
// }
//
// @Override
// public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {}
// }
// Path: app/src/main/java/co/jasonwyatt/sqliteperf/inserts/tracks/BatchedTestCase.java
import android.database.sqlite.SQLiteDatabase;
import java.nio.charset.Charset;
import java.util.Random;
import co.jasonwyatt.sqliteperf.App;
import co.jasonwyatt.sqliteperf.TestCase;
import co.jasonwyatt.sqliteperf.inserts.DbHelper;
package co.jasonwyatt.sqliteperf.inserts.tracks;
/**
* @author jason
*/
public class BatchedTestCase implements TestCase {
private DbHelper mDbHelper;
private final Random mRandom;
private final int mInsertions;
private final int mTestSizeIndex;
private int mInsertId;
public BatchedTestCase(int insertions, int testSizeIndex) {
mRandom = new Random(System.currentTimeMillis());
mInsertions = insertions;
mTestSizeIndex = testSizeIndex;
}
@Override
public void resetCase() { | mDbHelper = new DbHelper(App.getInstance(), getClass().getName()); |
jasonwyatt/SQLite-Performance | app/src/main/java/co/jasonwyatt/sqliteperf/inserts/tracks/SQLiteStatementTestCase.java | // Path: app/src/main/java/co/jasonwyatt/sqliteperf/App.java
// public class App extends Application {
// private static App sInstance;
//
// @Override
// public void onCreate() {
// super.onCreate();
// sInstance = this;
// }
//
// public static App getInstance() {
// return sInstance;
// }
// }
//
// Path: app/src/main/java/co/jasonwyatt/sqliteperf/TestCase.java
// public interface TestCase {
// void resetCase();
// Metrics runCase();
//
// class Metrics {
// private final String mName;
// private final float mVariable;
// private int mIterations = 1;
// private long mStartTime;
// private long mEndTime;
// private long mElapsedTime;
//
// public Metrics(String name, float variable) {
// mName = name;
// mVariable = variable;
// }
//
// Metrics(List<Metrics> iterations) {
// mName = iterations.get(0).mName;
// mVariable = iterations.get(0).mVariable;
// mIterations = iterations.size();
// mElapsedTime = 0;
// for (Metrics m : iterations) {
// mElapsedTime += m.mElapsedTime;
// }
// mElapsedTime = (long) (mElapsedTime*1.0f / iterations.size());
// }
//
// public void started() {
// mStartTime = System.nanoTime();
// }
//
// public void finished() {
// mEndTime = System.nanoTime();
// mElapsedTime = mEndTime - mStartTime;
// }
//
// @Override
// public String toString() {
// StringBuilder sb = new StringBuilder();
// sb.append(mName);
// sb.append(":\n");
// if (mIterations > 1) {
// sb.append(mIterations);
// sb.append(" iterations, each averaged ");
// } else {
// sb.append("took ");
// }
// sb.append(((float) mElapsedTime / mIterations) / 1000000f);
// sb.append(" seconds");
// return sb.toString();
// }
//
// public float getVariable() {
// return mVariable;
// }
//
// public long getElapsedTime() {
// return mElapsedTime;
// }
// }
//
// }
//
// Path: app/src/main/java/co/jasonwyatt/sqliteperf/inserts/DbHelper.java
// public class DbHelper extends SQLiteOpenHelper {
// public DbHelper(Context context, String name) {
// super(context, name, null, 1);
// }
//
// @Override
// public void onCreate(SQLiteDatabase db) {
// db.execSQL("CREATE TABLE inserts_1 (val INTEGER)");
// db.execSQL("CREATE TABLE tracks (id INTEGER PRIMARY KEY, title TEXT, band_id INTEGER, duration FLOAT, url TEXT, lyrics TEXT, about TEXT, release_date INTEGER, mod_date INTEGER)");
// }
//
// @Override
// public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {}
// }
| import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteStatement;
import java.nio.charset.Charset;
import java.util.Random;
import co.jasonwyatt.sqliteperf.App;
import co.jasonwyatt.sqliteperf.TestCase;
import co.jasonwyatt.sqliteperf.inserts.DbHelper; | package co.jasonwyatt.sqliteperf.inserts.tracks;
/**
* @author jason
*/
public class SQLiteStatementTestCase implements TestCase {
private DbHelper mDbHelper;
private final Random mRandom;
private final int mInsertions;
private final int mTestSizeIndex;
public SQLiteStatementTestCase(int insertions, int testSizeIndex) {
mRandom = new Random(System.currentTimeMillis());
mInsertions = insertions;
mTestSizeIndex = testSizeIndex;
}
@Override
public void resetCase() {
mDbHelper.getWritableDatabase().execSQL("delete from tracks");
mDbHelper.close();
}
@Override
public Metrics runCase() { | // Path: app/src/main/java/co/jasonwyatt/sqliteperf/App.java
// public class App extends Application {
// private static App sInstance;
//
// @Override
// public void onCreate() {
// super.onCreate();
// sInstance = this;
// }
//
// public static App getInstance() {
// return sInstance;
// }
// }
//
// Path: app/src/main/java/co/jasonwyatt/sqliteperf/TestCase.java
// public interface TestCase {
// void resetCase();
// Metrics runCase();
//
// class Metrics {
// private final String mName;
// private final float mVariable;
// private int mIterations = 1;
// private long mStartTime;
// private long mEndTime;
// private long mElapsedTime;
//
// public Metrics(String name, float variable) {
// mName = name;
// mVariable = variable;
// }
//
// Metrics(List<Metrics> iterations) {
// mName = iterations.get(0).mName;
// mVariable = iterations.get(0).mVariable;
// mIterations = iterations.size();
// mElapsedTime = 0;
// for (Metrics m : iterations) {
// mElapsedTime += m.mElapsedTime;
// }
// mElapsedTime = (long) (mElapsedTime*1.0f / iterations.size());
// }
//
// public void started() {
// mStartTime = System.nanoTime();
// }
//
// public void finished() {
// mEndTime = System.nanoTime();
// mElapsedTime = mEndTime - mStartTime;
// }
//
// @Override
// public String toString() {
// StringBuilder sb = new StringBuilder();
// sb.append(mName);
// sb.append(":\n");
// if (mIterations > 1) {
// sb.append(mIterations);
// sb.append(" iterations, each averaged ");
// } else {
// sb.append("took ");
// }
// sb.append(((float) mElapsedTime / mIterations) / 1000000f);
// sb.append(" seconds");
// return sb.toString();
// }
//
// public float getVariable() {
// return mVariable;
// }
//
// public long getElapsedTime() {
// return mElapsedTime;
// }
// }
//
// }
//
// Path: app/src/main/java/co/jasonwyatt/sqliteperf/inserts/DbHelper.java
// public class DbHelper extends SQLiteOpenHelper {
// public DbHelper(Context context, String name) {
// super(context, name, null, 1);
// }
//
// @Override
// public void onCreate(SQLiteDatabase db) {
// db.execSQL("CREATE TABLE inserts_1 (val INTEGER)");
// db.execSQL("CREATE TABLE tracks (id INTEGER PRIMARY KEY, title TEXT, band_id INTEGER, duration FLOAT, url TEXT, lyrics TEXT, about TEXT, release_date INTEGER, mod_date INTEGER)");
// }
//
// @Override
// public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {}
// }
// Path: app/src/main/java/co/jasonwyatt/sqliteperf/inserts/tracks/SQLiteStatementTestCase.java
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteStatement;
import java.nio.charset.Charset;
import java.util.Random;
import co.jasonwyatt.sqliteperf.App;
import co.jasonwyatt.sqliteperf.TestCase;
import co.jasonwyatt.sqliteperf.inserts.DbHelper;
package co.jasonwyatt.sqliteperf.inserts.tracks;
/**
* @author jason
*/
public class SQLiteStatementTestCase implements TestCase {
private DbHelper mDbHelper;
private final Random mRandom;
private final int mInsertions;
private final int mTestSizeIndex;
public SQLiteStatementTestCase(int insertions, int testSizeIndex) {
mRandom = new Random(System.currentTimeMillis());
mInsertions = insertions;
mTestSizeIndex = testSizeIndex;
}
@Override
public void resetCase() {
mDbHelper.getWritableDatabase().execSQL("delete from tracks");
mDbHelper.close();
}
@Override
public Metrics runCase() { | mDbHelper = new DbHelper(App.getInstance(), getClass().getName()); |
jasonwyatt/SQLite-Performance | app/src/main/java/co/jasonwyatt/sqliteperf/inserts/integers/IntegerInsertsTestCase.java | // Path: app/src/main/java/co/jasonwyatt/sqliteperf/App.java
// public class App extends Application {
// private static App sInstance;
//
// @Override
// public void onCreate() {
// super.onCreate();
// sInstance = this;
// }
//
// public static App getInstance() {
// return sInstance;
// }
// }
//
// Path: app/src/main/java/co/jasonwyatt/sqliteperf/TestCase.java
// public interface TestCase {
// void resetCase();
// Metrics runCase();
//
// class Metrics {
// private final String mName;
// private final float mVariable;
// private int mIterations = 1;
// private long mStartTime;
// private long mEndTime;
// private long mElapsedTime;
//
// public Metrics(String name, float variable) {
// mName = name;
// mVariable = variable;
// }
//
// Metrics(List<Metrics> iterations) {
// mName = iterations.get(0).mName;
// mVariable = iterations.get(0).mVariable;
// mIterations = iterations.size();
// mElapsedTime = 0;
// for (Metrics m : iterations) {
// mElapsedTime += m.mElapsedTime;
// }
// mElapsedTime = (long) (mElapsedTime*1.0f / iterations.size());
// }
//
// public void started() {
// mStartTime = System.nanoTime();
// }
//
// public void finished() {
// mEndTime = System.nanoTime();
// mElapsedTime = mEndTime - mStartTime;
// }
//
// @Override
// public String toString() {
// StringBuilder sb = new StringBuilder();
// sb.append(mName);
// sb.append(":\n");
// if (mIterations > 1) {
// sb.append(mIterations);
// sb.append(" iterations, each averaged ");
// } else {
// sb.append("took ");
// }
// sb.append(((float) mElapsedTime / mIterations) / 1000000f);
// sb.append(" seconds");
// return sb.toString();
// }
//
// public float getVariable() {
// return mVariable;
// }
//
// public long getElapsedTime() {
// return mElapsedTime;
// }
// }
//
// }
//
// Path: app/src/main/java/co/jasonwyatt/sqliteperf/inserts/DbHelper.java
// public class DbHelper extends SQLiteOpenHelper {
// public DbHelper(Context context, String name) {
// super(context, name, null, 1);
// }
//
// @Override
// public void onCreate(SQLiteDatabase db) {
// db.execSQL("CREATE TABLE inserts_1 (val INTEGER)");
// db.execSQL("CREATE TABLE tracks (id INTEGER PRIMARY KEY, title TEXT, band_id INTEGER, duration FLOAT, url TEXT, lyrics TEXT, about TEXT, release_date INTEGER, mod_date INTEGER)");
// }
//
// @Override
// public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {}
// }
| import android.content.ContentValues;
import android.database.sqlite.SQLiteDatabase;
import android.util.Log;
import java.util.Random;
import co.jasonwyatt.sqliteperf.App;
import co.jasonwyatt.sqliteperf.TestCase;
import co.jasonwyatt.sqliteperf.inserts.DbHelper; | package co.jasonwyatt.sqliteperf.inserts.integers;
/**
* @author jason
*/
public class IntegerInsertsTestCase implements TestCase {
private DbHelper mDbHelper;
private final Random mRandom;
private final int mInsertions;
private final int mTestSizeIndex;
public IntegerInsertsTestCase(int insertions, int testSizeIndex) {
mRandom = new Random(System.currentTimeMillis());
mInsertions = insertions;
mTestSizeIndex = testSizeIndex;
}
@Override
public void resetCase() {
mDbHelper.getWritableDatabase().execSQL("delete from inserts_1");
mDbHelper.close();
}
@Override
public Metrics runCase() { | // Path: app/src/main/java/co/jasonwyatt/sqliteperf/App.java
// public class App extends Application {
// private static App sInstance;
//
// @Override
// public void onCreate() {
// super.onCreate();
// sInstance = this;
// }
//
// public static App getInstance() {
// return sInstance;
// }
// }
//
// Path: app/src/main/java/co/jasonwyatt/sqliteperf/TestCase.java
// public interface TestCase {
// void resetCase();
// Metrics runCase();
//
// class Metrics {
// private final String mName;
// private final float mVariable;
// private int mIterations = 1;
// private long mStartTime;
// private long mEndTime;
// private long mElapsedTime;
//
// public Metrics(String name, float variable) {
// mName = name;
// mVariable = variable;
// }
//
// Metrics(List<Metrics> iterations) {
// mName = iterations.get(0).mName;
// mVariable = iterations.get(0).mVariable;
// mIterations = iterations.size();
// mElapsedTime = 0;
// for (Metrics m : iterations) {
// mElapsedTime += m.mElapsedTime;
// }
// mElapsedTime = (long) (mElapsedTime*1.0f / iterations.size());
// }
//
// public void started() {
// mStartTime = System.nanoTime();
// }
//
// public void finished() {
// mEndTime = System.nanoTime();
// mElapsedTime = mEndTime - mStartTime;
// }
//
// @Override
// public String toString() {
// StringBuilder sb = new StringBuilder();
// sb.append(mName);
// sb.append(":\n");
// if (mIterations > 1) {
// sb.append(mIterations);
// sb.append(" iterations, each averaged ");
// } else {
// sb.append("took ");
// }
// sb.append(((float) mElapsedTime / mIterations) / 1000000f);
// sb.append(" seconds");
// return sb.toString();
// }
//
// public float getVariable() {
// return mVariable;
// }
//
// public long getElapsedTime() {
// return mElapsedTime;
// }
// }
//
// }
//
// Path: app/src/main/java/co/jasonwyatt/sqliteperf/inserts/DbHelper.java
// public class DbHelper extends SQLiteOpenHelper {
// public DbHelper(Context context, String name) {
// super(context, name, null, 1);
// }
//
// @Override
// public void onCreate(SQLiteDatabase db) {
// db.execSQL("CREATE TABLE inserts_1 (val INTEGER)");
// db.execSQL("CREATE TABLE tracks (id INTEGER PRIMARY KEY, title TEXT, band_id INTEGER, duration FLOAT, url TEXT, lyrics TEXT, about TEXT, release_date INTEGER, mod_date INTEGER)");
// }
//
// @Override
// public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {}
// }
// Path: app/src/main/java/co/jasonwyatt/sqliteperf/inserts/integers/IntegerInsertsTestCase.java
import android.content.ContentValues;
import android.database.sqlite.SQLiteDatabase;
import android.util.Log;
import java.util.Random;
import co.jasonwyatt.sqliteperf.App;
import co.jasonwyatt.sqliteperf.TestCase;
import co.jasonwyatt.sqliteperf.inserts.DbHelper;
package co.jasonwyatt.sqliteperf.inserts.integers;
/**
* @author jason
*/
public class IntegerInsertsTestCase implements TestCase {
private DbHelper mDbHelper;
private final Random mRandom;
private final int mInsertions;
private final int mTestSizeIndex;
public IntegerInsertsTestCase(int insertions, int testSizeIndex) {
mRandom = new Random(System.currentTimeMillis());
mInsertions = insertions;
mTestSizeIndex = testSizeIndex;
}
@Override
public void resetCase() {
mDbHelper.getWritableDatabase().execSQL("delete from inserts_1");
mDbHelper.close();
}
@Override
public Metrics runCase() { | mDbHelper = new DbHelper(App.getInstance(), IntegerInsertsTestCase.class.getSimpleName()); |
jasonwyatt/SQLite-Performance | app/src/main/java/co/jasonwyatt/sqliteperf/inserts/integers/IntegerRoomTestCase.java | // Path: app/src/main/java/co/jasonwyatt/sqliteperf/App.java
// public class App extends Application {
// private static App sInstance;
//
// @Override
// public void onCreate() {
// super.onCreate();
// sInstance = this;
// }
//
// public static App getInstance() {
// return sInstance;
// }
// }
//
// Path: app/src/main/java/co/jasonwyatt/sqliteperf/TestCase.java
// public interface TestCase {
// void resetCase();
// Metrics runCase();
//
// class Metrics {
// private final String mName;
// private final float mVariable;
// private int mIterations = 1;
// private long mStartTime;
// private long mEndTime;
// private long mElapsedTime;
//
// public Metrics(String name, float variable) {
// mName = name;
// mVariable = variable;
// }
//
// Metrics(List<Metrics> iterations) {
// mName = iterations.get(0).mName;
// mVariable = iterations.get(0).mVariable;
// mIterations = iterations.size();
// mElapsedTime = 0;
// for (Metrics m : iterations) {
// mElapsedTime += m.mElapsedTime;
// }
// mElapsedTime = (long) (mElapsedTime*1.0f / iterations.size());
// }
//
// public void started() {
// mStartTime = System.nanoTime();
// }
//
// public void finished() {
// mEndTime = System.nanoTime();
// mElapsedTime = mEndTime - mStartTime;
// }
//
// @Override
// public String toString() {
// StringBuilder sb = new StringBuilder();
// sb.append(mName);
// sb.append(":\n");
// if (mIterations > 1) {
// sb.append(mIterations);
// sb.append(" iterations, each averaged ");
// } else {
// sb.append("took ");
// }
// sb.append(((float) mElapsedTime / mIterations) / 1000000f);
// sb.append(" seconds");
// return sb.toString();
// }
//
// public float getVariable() {
// return mVariable;
// }
//
// public long getElapsedTime() {
// return mElapsedTime;
// }
// }
//
// }
//
// Path: app/src/main/java/co/jasonwyatt/sqliteperf/inserts/room/Db.java
// @Database(entities = {TrackInfo.class, IntegerInfo.class}, version = 1)
// public abstract class Db extends RoomDatabase {
// public abstract IntegersDao integers();
// public abstract TracksDao tracks();
// }
//
// Path: app/src/main/java/co/jasonwyatt/sqliteperf/inserts/room/IntegerInfo.java
// @Entity(tableName = "inserts_1")
// public class IntegerInfo {
// @PrimaryKey(autoGenerate = true)
// @ColumnInfo(name = "rowid")
// private int mRowid;
// @ColumnInfo(name = "val")
// private int mVal;
//
// public int getRowid() {
// return mRowid;
// }
//
// public void setRowid(int rowid) {
// mRowid = rowid;
// }
//
// public int getVal() {
// return mVal;
// }
//
// public void setVal(int val) {
// mVal = val;
// }
// }
| import android.arch.persistence.room.Room;
import android.arch.persistence.room.RoomDatabase;
import java.util.Random;
import co.jasonwyatt.sqliteperf.App;
import co.jasonwyatt.sqliteperf.TestCase;
import co.jasonwyatt.sqliteperf.inserts.room.Db;
import co.jasonwyatt.sqliteperf.inserts.room.IntegerInfo; | package co.jasonwyatt.sqliteperf.inserts.integers;
/**
* @author jason
*/
public class IntegerRoomTestCase implements TestCase {
private Db mDb;
private final Random mRandom;
private final int mInsertions;
private final int mTestSizeIndex;
public IntegerRoomTestCase(int insertions, int testSizeIndex) { | // Path: app/src/main/java/co/jasonwyatt/sqliteperf/App.java
// public class App extends Application {
// private static App sInstance;
//
// @Override
// public void onCreate() {
// super.onCreate();
// sInstance = this;
// }
//
// public static App getInstance() {
// return sInstance;
// }
// }
//
// Path: app/src/main/java/co/jasonwyatt/sqliteperf/TestCase.java
// public interface TestCase {
// void resetCase();
// Metrics runCase();
//
// class Metrics {
// private final String mName;
// private final float mVariable;
// private int mIterations = 1;
// private long mStartTime;
// private long mEndTime;
// private long mElapsedTime;
//
// public Metrics(String name, float variable) {
// mName = name;
// mVariable = variable;
// }
//
// Metrics(List<Metrics> iterations) {
// mName = iterations.get(0).mName;
// mVariable = iterations.get(0).mVariable;
// mIterations = iterations.size();
// mElapsedTime = 0;
// for (Metrics m : iterations) {
// mElapsedTime += m.mElapsedTime;
// }
// mElapsedTime = (long) (mElapsedTime*1.0f / iterations.size());
// }
//
// public void started() {
// mStartTime = System.nanoTime();
// }
//
// public void finished() {
// mEndTime = System.nanoTime();
// mElapsedTime = mEndTime - mStartTime;
// }
//
// @Override
// public String toString() {
// StringBuilder sb = new StringBuilder();
// sb.append(mName);
// sb.append(":\n");
// if (mIterations > 1) {
// sb.append(mIterations);
// sb.append(" iterations, each averaged ");
// } else {
// sb.append("took ");
// }
// sb.append(((float) mElapsedTime / mIterations) / 1000000f);
// sb.append(" seconds");
// return sb.toString();
// }
//
// public float getVariable() {
// return mVariable;
// }
//
// public long getElapsedTime() {
// return mElapsedTime;
// }
// }
//
// }
//
// Path: app/src/main/java/co/jasonwyatt/sqliteperf/inserts/room/Db.java
// @Database(entities = {TrackInfo.class, IntegerInfo.class}, version = 1)
// public abstract class Db extends RoomDatabase {
// public abstract IntegersDao integers();
// public abstract TracksDao tracks();
// }
//
// Path: app/src/main/java/co/jasonwyatt/sqliteperf/inserts/room/IntegerInfo.java
// @Entity(tableName = "inserts_1")
// public class IntegerInfo {
// @PrimaryKey(autoGenerate = true)
// @ColumnInfo(name = "rowid")
// private int mRowid;
// @ColumnInfo(name = "val")
// private int mVal;
//
// public int getRowid() {
// return mRowid;
// }
//
// public void setRowid(int rowid) {
// mRowid = rowid;
// }
//
// public int getVal() {
// return mVal;
// }
//
// public void setVal(int val) {
// mVal = val;
// }
// }
// Path: app/src/main/java/co/jasonwyatt/sqliteperf/inserts/integers/IntegerRoomTestCase.java
import android.arch.persistence.room.Room;
import android.arch.persistence.room.RoomDatabase;
import java.util.Random;
import co.jasonwyatt.sqliteperf.App;
import co.jasonwyatt.sqliteperf.TestCase;
import co.jasonwyatt.sqliteperf.inserts.room.Db;
import co.jasonwyatt.sqliteperf.inserts.room.IntegerInfo;
package co.jasonwyatt.sqliteperf.inserts.integers;
/**
* @author jason
*/
public class IntegerRoomTestCase implements TestCase {
private Db mDb;
private final Random mRandom;
private final int mInsertions;
private final int mTestSizeIndex;
public IntegerRoomTestCase(int insertions, int testSizeIndex) { | mDb = Room.databaseBuilder(App.getInstance(), Db.class, "roomdb").build(); |
jasonwyatt/SQLite-Performance | app/src/main/java/co/jasonwyatt/sqliteperf/inserts/integers/IntegerRoomTestCase.java | // Path: app/src/main/java/co/jasonwyatt/sqliteperf/App.java
// public class App extends Application {
// private static App sInstance;
//
// @Override
// public void onCreate() {
// super.onCreate();
// sInstance = this;
// }
//
// public static App getInstance() {
// return sInstance;
// }
// }
//
// Path: app/src/main/java/co/jasonwyatt/sqliteperf/TestCase.java
// public interface TestCase {
// void resetCase();
// Metrics runCase();
//
// class Metrics {
// private final String mName;
// private final float mVariable;
// private int mIterations = 1;
// private long mStartTime;
// private long mEndTime;
// private long mElapsedTime;
//
// public Metrics(String name, float variable) {
// mName = name;
// mVariable = variable;
// }
//
// Metrics(List<Metrics> iterations) {
// mName = iterations.get(0).mName;
// mVariable = iterations.get(0).mVariable;
// mIterations = iterations.size();
// mElapsedTime = 0;
// for (Metrics m : iterations) {
// mElapsedTime += m.mElapsedTime;
// }
// mElapsedTime = (long) (mElapsedTime*1.0f / iterations.size());
// }
//
// public void started() {
// mStartTime = System.nanoTime();
// }
//
// public void finished() {
// mEndTime = System.nanoTime();
// mElapsedTime = mEndTime - mStartTime;
// }
//
// @Override
// public String toString() {
// StringBuilder sb = new StringBuilder();
// sb.append(mName);
// sb.append(":\n");
// if (mIterations > 1) {
// sb.append(mIterations);
// sb.append(" iterations, each averaged ");
// } else {
// sb.append("took ");
// }
// sb.append(((float) mElapsedTime / mIterations) / 1000000f);
// sb.append(" seconds");
// return sb.toString();
// }
//
// public float getVariable() {
// return mVariable;
// }
//
// public long getElapsedTime() {
// return mElapsedTime;
// }
// }
//
// }
//
// Path: app/src/main/java/co/jasonwyatt/sqliteperf/inserts/room/Db.java
// @Database(entities = {TrackInfo.class, IntegerInfo.class}, version = 1)
// public abstract class Db extends RoomDatabase {
// public abstract IntegersDao integers();
// public abstract TracksDao tracks();
// }
//
// Path: app/src/main/java/co/jasonwyatt/sqliteperf/inserts/room/IntegerInfo.java
// @Entity(tableName = "inserts_1")
// public class IntegerInfo {
// @PrimaryKey(autoGenerate = true)
// @ColumnInfo(name = "rowid")
// private int mRowid;
// @ColumnInfo(name = "val")
// private int mVal;
//
// public int getRowid() {
// return mRowid;
// }
//
// public void setRowid(int rowid) {
// mRowid = rowid;
// }
//
// public int getVal() {
// return mVal;
// }
//
// public void setVal(int val) {
// mVal = val;
// }
// }
| import android.arch.persistence.room.Room;
import android.arch.persistence.room.RoomDatabase;
import java.util.Random;
import co.jasonwyatt.sqliteperf.App;
import co.jasonwyatt.sqliteperf.TestCase;
import co.jasonwyatt.sqliteperf.inserts.room.Db;
import co.jasonwyatt.sqliteperf.inserts.room.IntegerInfo; | package co.jasonwyatt.sqliteperf.inserts.integers;
/**
* @author jason
*/
public class IntegerRoomTestCase implements TestCase {
private Db mDb;
private final Random mRandom;
private final int mInsertions;
private final int mTestSizeIndex;
public IntegerRoomTestCase(int insertions, int testSizeIndex) {
mDb = Room.databaseBuilder(App.getInstance(), Db.class, "roomdb").build();
mRandom = new Random(System.currentTimeMillis());
mInsertions = insertions;
mTestSizeIndex = testSizeIndex;
}
@Override
public void resetCase() {
mDb.integers().deleteAll();
}
@Override
public Metrics runCase() {
Metrics result = new Metrics(getClass().getSimpleName()+" ("+mInsertions+" insertions)", mTestSizeIndex);
result.started(); | // Path: app/src/main/java/co/jasonwyatt/sqliteperf/App.java
// public class App extends Application {
// private static App sInstance;
//
// @Override
// public void onCreate() {
// super.onCreate();
// sInstance = this;
// }
//
// public static App getInstance() {
// return sInstance;
// }
// }
//
// Path: app/src/main/java/co/jasonwyatt/sqliteperf/TestCase.java
// public interface TestCase {
// void resetCase();
// Metrics runCase();
//
// class Metrics {
// private final String mName;
// private final float mVariable;
// private int mIterations = 1;
// private long mStartTime;
// private long mEndTime;
// private long mElapsedTime;
//
// public Metrics(String name, float variable) {
// mName = name;
// mVariable = variable;
// }
//
// Metrics(List<Metrics> iterations) {
// mName = iterations.get(0).mName;
// mVariable = iterations.get(0).mVariable;
// mIterations = iterations.size();
// mElapsedTime = 0;
// for (Metrics m : iterations) {
// mElapsedTime += m.mElapsedTime;
// }
// mElapsedTime = (long) (mElapsedTime*1.0f / iterations.size());
// }
//
// public void started() {
// mStartTime = System.nanoTime();
// }
//
// public void finished() {
// mEndTime = System.nanoTime();
// mElapsedTime = mEndTime - mStartTime;
// }
//
// @Override
// public String toString() {
// StringBuilder sb = new StringBuilder();
// sb.append(mName);
// sb.append(":\n");
// if (mIterations > 1) {
// sb.append(mIterations);
// sb.append(" iterations, each averaged ");
// } else {
// sb.append("took ");
// }
// sb.append(((float) mElapsedTime / mIterations) / 1000000f);
// sb.append(" seconds");
// return sb.toString();
// }
//
// public float getVariable() {
// return mVariable;
// }
//
// public long getElapsedTime() {
// return mElapsedTime;
// }
// }
//
// }
//
// Path: app/src/main/java/co/jasonwyatt/sqliteperf/inserts/room/Db.java
// @Database(entities = {TrackInfo.class, IntegerInfo.class}, version = 1)
// public abstract class Db extends RoomDatabase {
// public abstract IntegersDao integers();
// public abstract TracksDao tracks();
// }
//
// Path: app/src/main/java/co/jasonwyatt/sqliteperf/inserts/room/IntegerInfo.java
// @Entity(tableName = "inserts_1")
// public class IntegerInfo {
// @PrimaryKey(autoGenerate = true)
// @ColumnInfo(name = "rowid")
// private int mRowid;
// @ColumnInfo(name = "val")
// private int mVal;
//
// public int getRowid() {
// return mRowid;
// }
//
// public void setRowid(int rowid) {
// mRowid = rowid;
// }
//
// public int getVal() {
// return mVal;
// }
//
// public void setVal(int val) {
// mVal = val;
// }
// }
// Path: app/src/main/java/co/jasonwyatt/sqliteperf/inserts/integers/IntegerRoomTestCase.java
import android.arch.persistence.room.Room;
import android.arch.persistence.room.RoomDatabase;
import java.util.Random;
import co.jasonwyatt.sqliteperf.App;
import co.jasonwyatt.sqliteperf.TestCase;
import co.jasonwyatt.sqliteperf.inserts.room.Db;
import co.jasonwyatt.sqliteperf.inserts.room.IntegerInfo;
package co.jasonwyatt.sqliteperf.inserts.integers;
/**
* @author jason
*/
public class IntegerRoomTestCase implements TestCase {
private Db mDb;
private final Random mRandom;
private final int mInsertions;
private final int mTestSizeIndex;
public IntegerRoomTestCase(int insertions, int testSizeIndex) {
mDb = Room.databaseBuilder(App.getInstance(), Db.class, "roomdb").build();
mRandom = new Random(System.currentTimeMillis());
mInsertions = insertions;
mTestSizeIndex = testSizeIndex;
}
@Override
public void resetCase() {
mDb.integers().deleteAll();
}
@Override
public Metrics runCase() {
Metrics result = new Metrics(getClass().getSimpleName()+" ("+mInsertions+" insertions)", mTestSizeIndex);
result.started(); | IntegerInfo[] data = new IntegerInfo[mInsertions]; |
jasonwyatt/SQLite-Performance | app/src/main/java/co/jasonwyatt/sqliteperf/inserts/tracks/RawTestCase.java | // Path: app/src/main/java/co/jasonwyatt/sqliteperf/App.java
// public class App extends Application {
// private static App sInstance;
//
// @Override
// public void onCreate() {
// super.onCreate();
// sInstance = this;
// }
//
// public static App getInstance() {
// return sInstance;
// }
// }
//
// Path: app/src/main/java/co/jasonwyatt/sqliteperf/TestCase.java
// public interface TestCase {
// void resetCase();
// Metrics runCase();
//
// class Metrics {
// private final String mName;
// private final float mVariable;
// private int mIterations = 1;
// private long mStartTime;
// private long mEndTime;
// private long mElapsedTime;
//
// public Metrics(String name, float variable) {
// mName = name;
// mVariable = variable;
// }
//
// Metrics(List<Metrics> iterations) {
// mName = iterations.get(0).mName;
// mVariable = iterations.get(0).mVariable;
// mIterations = iterations.size();
// mElapsedTime = 0;
// for (Metrics m : iterations) {
// mElapsedTime += m.mElapsedTime;
// }
// mElapsedTime = (long) (mElapsedTime*1.0f / iterations.size());
// }
//
// public void started() {
// mStartTime = System.nanoTime();
// }
//
// public void finished() {
// mEndTime = System.nanoTime();
// mElapsedTime = mEndTime - mStartTime;
// }
//
// @Override
// public String toString() {
// StringBuilder sb = new StringBuilder();
// sb.append(mName);
// sb.append(":\n");
// if (mIterations > 1) {
// sb.append(mIterations);
// sb.append(" iterations, each averaged ");
// } else {
// sb.append("took ");
// }
// sb.append(((float) mElapsedTime / mIterations) / 1000000f);
// sb.append(" seconds");
// return sb.toString();
// }
//
// public float getVariable() {
// return mVariable;
// }
//
// public long getElapsedTime() {
// return mElapsedTime;
// }
// }
//
// }
//
// Path: app/src/main/java/co/jasonwyatt/sqliteperf/inserts/DbHelper.java
// public class DbHelper extends SQLiteOpenHelper {
// public DbHelper(Context context, String name) {
// super(context, name, null, 1);
// }
//
// @Override
// public void onCreate(SQLiteDatabase db) {
// db.execSQL("CREATE TABLE inserts_1 (val INTEGER)");
// db.execSQL("CREATE TABLE tracks (id INTEGER PRIMARY KEY, title TEXT, band_id INTEGER, duration FLOAT, url TEXT, lyrics TEXT, about TEXT, release_date INTEGER, mod_date INTEGER)");
// }
//
// @Override
// public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {}
// }
| import android.content.ContentValues;
import android.database.sqlite.SQLiteDatabase;
import java.nio.charset.Charset;
import java.util.Random;
import co.jasonwyatt.sqliteperf.App;
import co.jasonwyatt.sqliteperf.TestCase;
import co.jasonwyatt.sqliteperf.inserts.DbHelper; | package co.jasonwyatt.sqliteperf.inserts.tracks;
/**
* @author jason
*/
public class RawTestCase implements TestCase {
private DbHelper mDbHelper;
private final Random mRandom;
private final int mInsertions;
private final int mTestSizeIndex;
public RawTestCase(int insertions, int testSizeIndex) { | // Path: app/src/main/java/co/jasonwyatt/sqliteperf/App.java
// public class App extends Application {
// private static App sInstance;
//
// @Override
// public void onCreate() {
// super.onCreate();
// sInstance = this;
// }
//
// public static App getInstance() {
// return sInstance;
// }
// }
//
// Path: app/src/main/java/co/jasonwyatt/sqliteperf/TestCase.java
// public interface TestCase {
// void resetCase();
// Metrics runCase();
//
// class Metrics {
// private final String mName;
// private final float mVariable;
// private int mIterations = 1;
// private long mStartTime;
// private long mEndTime;
// private long mElapsedTime;
//
// public Metrics(String name, float variable) {
// mName = name;
// mVariable = variable;
// }
//
// Metrics(List<Metrics> iterations) {
// mName = iterations.get(0).mName;
// mVariable = iterations.get(0).mVariable;
// mIterations = iterations.size();
// mElapsedTime = 0;
// for (Metrics m : iterations) {
// mElapsedTime += m.mElapsedTime;
// }
// mElapsedTime = (long) (mElapsedTime*1.0f / iterations.size());
// }
//
// public void started() {
// mStartTime = System.nanoTime();
// }
//
// public void finished() {
// mEndTime = System.nanoTime();
// mElapsedTime = mEndTime - mStartTime;
// }
//
// @Override
// public String toString() {
// StringBuilder sb = new StringBuilder();
// sb.append(mName);
// sb.append(":\n");
// if (mIterations > 1) {
// sb.append(mIterations);
// sb.append(" iterations, each averaged ");
// } else {
// sb.append("took ");
// }
// sb.append(((float) mElapsedTime / mIterations) / 1000000f);
// sb.append(" seconds");
// return sb.toString();
// }
//
// public float getVariable() {
// return mVariable;
// }
//
// public long getElapsedTime() {
// return mElapsedTime;
// }
// }
//
// }
//
// Path: app/src/main/java/co/jasonwyatt/sqliteperf/inserts/DbHelper.java
// public class DbHelper extends SQLiteOpenHelper {
// public DbHelper(Context context, String name) {
// super(context, name, null, 1);
// }
//
// @Override
// public void onCreate(SQLiteDatabase db) {
// db.execSQL("CREATE TABLE inserts_1 (val INTEGER)");
// db.execSQL("CREATE TABLE tracks (id INTEGER PRIMARY KEY, title TEXT, band_id INTEGER, duration FLOAT, url TEXT, lyrics TEXT, about TEXT, release_date INTEGER, mod_date INTEGER)");
// }
//
// @Override
// public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {}
// }
// Path: app/src/main/java/co/jasonwyatt/sqliteperf/inserts/tracks/RawTestCase.java
import android.content.ContentValues;
import android.database.sqlite.SQLiteDatabase;
import java.nio.charset.Charset;
import java.util.Random;
import co.jasonwyatt.sqliteperf.App;
import co.jasonwyatt.sqliteperf.TestCase;
import co.jasonwyatt.sqliteperf.inserts.DbHelper;
package co.jasonwyatt.sqliteperf.inserts.tracks;
/**
* @author jason
*/
public class RawTestCase implements TestCase {
private DbHelper mDbHelper;
private final Random mRandom;
private final int mInsertions;
private final int mTestSizeIndex;
public RawTestCase(int insertions, int testSizeIndex) { | mDbHelper = new DbHelper(App.getInstance(), getClass().getName()); |
jasonwyatt/SQLite-Performance | app/src/main/java/co/jasonwyatt/sqliteperf/inserts/integers/IntegerInsertsRawBatchTransactionCase.java | // Path: app/src/main/java/co/jasonwyatt/sqliteperf/App.java
// public class App extends Application {
// private static App sInstance;
//
// @Override
// public void onCreate() {
// super.onCreate();
// sInstance = this;
// }
//
// public static App getInstance() {
// return sInstance;
// }
// }
//
// Path: app/src/main/java/co/jasonwyatt/sqliteperf/TestCase.java
// public interface TestCase {
// void resetCase();
// Metrics runCase();
//
// class Metrics {
// private final String mName;
// private final float mVariable;
// private int mIterations = 1;
// private long mStartTime;
// private long mEndTime;
// private long mElapsedTime;
//
// public Metrics(String name, float variable) {
// mName = name;
// mVariable = variable;
// }
//
// Metrics(List<Metrics> iterations) {
// mName = iterations.get(0).mName;
// mVariable = iterations.get(0).mVariable;
// mIterations = iterations.size();
// mElapsedTime = 0;
// for (Metrics m : iterations) {
// mElapsedTime += m.mElapsedTime;
// }
// mElapsedTime = (long) (mElapsedTime*1.0f / iterations.size());
// }
//
// public void started() {
// mStartTime = System.nanoTime();
// }
//
// public void finished() {
// mEndTime = System.nanoTime();
// mElapsedTime = mEndTime - mStartTime;
// }
//
// @Override
// public String toString() {
// StringBuilder sb = new StringBuilder();
// sb.append(mName);
// sb.append(":\n");
// if (mIterations > 1) {
// sb.append(mIterations);
// sb.append(" iterations, each averaged ");
// } else {
// sb.append("took ");
// }
// sb.append(((float) mElapsedTime / mIterations) / 1000000f);
// sb.append(" seconds");
// return sb.toString();
// }
//
// public float getVariable() {
// return mVariable;
// }
//
// public long getElapsedTime() {
// return mElapsedTime;
// }
// }
//
// }
//
// Path: app/src/main/java/co/jasonwyatt/sqliteperf/inserts/DbHelper.java
// public class DbHelper extends SQLiteOpenHelper {
// public DbHelper(Context context, String name) {
// super(context, name, null, 1);
// }
//
// @Override
// public void onCreate(SQLiteDatabase db) {
// db.execSQL("CREATE TABLE inserts_1 (val INTEGER)");
// db.execSQL("CREATE TABLE tracks (id INTEGER PRIMARY KEY, title TEXT, band_id INTEGER, duration FLOAT, url TEXT, lyrics TEXT, about TEXT, release_date INTEGER, mod_date INTEGER)");
// }
//
// @Override
// public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {}
// }
| import android.database.sqlite.SQLiteDatabase;
import android.util.Log;
import java.util.Random;
import co.jasonwyatt.sqliteperf.App;
import co.jasonwyatt.sqliteperf.TestCase;
import co.jasonwyatt.sqliteperf.inserts.DbHelper; | package co.jasonwyatt.sqliteperf.inserts.integers;
/**
* @author jason
*/
public class IntegerInsertsRawBatchTransactionCase implements TestCase {
private DbHelper mDbHelper;
private final Random mRandom;
private final int mInsertions;
private final int mTestSizeIndex;
public IntegerInsertsRawBatchTransactionCase(int insertions, int testSizeIndex) {
mRandom = new Random(System.currentTimeMillis());
mInsertions = insertions;
mTestSizeIndex = testSizeIndex;
}
@Override
public void resetCase() {
mDbHelper.getWritableDatabase().execSQL("delete from inserts_1");
mDbHelper.close();
}
@Override
public Metrics runCase() { | // Path: app/src/main/java/co/jasonwyatt/sqliteperf/App.java
// public class App extends Application {
// private static App sInstance;
//
// @Override
// public void onCreate() {
// super.onCreate();
// sInstance = this;
// }
//
// public static App getInstance() {
// return sInstance;
// }
// }
//
// Path: app/src/main/java/co/jasonwyatt/sqliteperf/TestCase.java
// public interface TestCase {
// void resetCase();
// Metrics runCase();
//
// class Metrics {
// private final String mName;
// private final float mVariable;
// private int mIterations = 1;
// private long mStartTime;
// private long mEndTime;
// private long mElapsedTime;
//
// public Metrics(String name, float variable) {
// mName = name;
// mVariable = variable;
// }
//
// Metrics(List<Metrics> iterations) {
// mName = iterations.get(0).mName;
// mVariable = iterations.get(0).mVariable;
// mIterations = iterations.size();
// mElapsedTime = 0;
// for (Metrics m : iterations) {
// mElapsedTime += m.mElapsedTime;
// }
// mElapsedTime = (long) (mElapsedTime*1.0f / iterations.size());
// }
//
// public void started() {
// mStartTime = System.nanoTime();
// }
//
// public void finished() {
// mEndTime = System.nanoTime();
// mElapsedTime = mEndTime - mStartTime;
// }
//
// @Override
// public String toString() {
// StringBuilder sb = new StringBuilder();
// sb.append(mName);
// sb.append(":\n");
// if (mIterations > 1) {
// sb.append(mIterations);
// sb.append(" iterations, each averaged ");
// } else {
// sb.append("took ");
// }
// sb.append(((float) mElapsedTime / mIterations) / 1000000f);
// sb.append(" seconds");
// return sb.toString();
// }
//
// public float getVariable() {
// return mVariable;
// }
//
// public long getElapsedTime() {
// return mElapsedTime;
// }
// }
//
// }
//
// Path: app/src/main/java/co/jasonwyatt/sqliteperf/inserts/DbHelper.java
// public class DbHelper extends SQLiteOpenHelper {
// public DbHelper(Context context, String name) {
// super(context, name, null, 1);
// }
//
// @Override
// public void onCreate(SQLiteDatabase db) {
// db.execSQL("CREATE TABLE inserts_1 (val INTEGER)");
// db.execSQL("CREATE TABLE tracks (id INTEGER PRIMARY KEY, title TEXT, band_id INTEGER, duration FLOAT, url TEXT, lyrics TEXT, about TEXT, release_date INTEGER, mod_date INTEGER)");
// }
//
// @Override
// public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {}
// }
// Path: app/src/main/java/co/jasonwyatt/sqliteperf/inserts/integers/IntegerInsertsRawBatchTransactionCase.java
import android.database.sqlite.SQLiteDatabase;
import android.util.Log;
import java.util.Random;
import co.jasonwyatt.sqliteperf.App;
import co.jasonwyatt.sqliteperf.TestCase;
import co.jasonwyatt.sqliteperf.inserts.DbHelper;
package co.jasonwyatt.sqliteperf.inserts.integers;
/**
* @author jason
*/
public class IntegerInsertsRawBatchTransactionCase implements TestCase {
private DbHelper mDbHelper;
private final Random mRandom;
private final int mInsertions;
private final int mTestSizeIndex;
public IntegerInsertsRawBatchTransactionCase(int insertions, int testSizeIndex) {
mRandom = new Random(System.currentTimeMillis());
mInsertions = insertions;
mTestSizeIndex = testSizeIndex;
}
@Override
public void resetCase() {
mDbHelper.getWritableDatabase().execSQL("delete from inserts_1");
mDbHelper.close();
}
@Override
public Metrics runCase() { | mDbHelper = new DbHelper(App.getInstance(), IntegerInsertsRawBatchTransactionCase.class.getSimpleName()); |
zylc369/smali2java | src/main/java/buwai/android/smaliinstruction/SmaliInstruction24.java | // Path: src/main/java/buwai/android/smali2java/Utils.java
// public class Utils {
//
// /**
// * 将smali类型转换为Java的表示形式。
// *
// * @param type
// * @return
// */
// public static String getJavaType(String smaliType) {
// char ch;
// ch = smaliType.charAt(0);
// String javaType;
//
// int index = 0;
// int dimensions = 0;
//
// if ('L' == ch) {
// return smaliType.substring(1, smaliType.lastIndexOf(';')).replace('/', '.');
// } else if ('[' == ch) { // 处理数组的情况。
// for (char c : smaliType.toCharArray()) {
// if ('[' == c) {
// dimensions++;
// index++;
// } else {
// break;
// }
// }
// }
//
// ch = smaliType.charAt(index);
// if ('L' == ch) {
// javaType = smaliType.substring(index + 1, smaliType.lastIndexOf(';')).replace('/', '.');
// } else {
// switch (ch) {
// case 'V':
// javaType = "void";
// break;
// case 'Z':
// javaType = "boolean";
// break;
// case 'B':
// javaType = "byte";
// break;
// case 'S':
// javaType = "short";
// break;
// case 'C':
// javaType = "char";
// break;
// case 'I':
// javaType = "int";
// break;
// case 'J':
// javaType = "long";
// break;
// case 'F':
// javaType = "float";
// break;
// case 'D':
// javaType = "double";
// break;
// default:
// javaType = null;
// break;
// }
// }
//
// for (int i = 0; i < dimensions; i++) {
// javaType += "[]";
// }
//
// return javaType;
// }
//
// /**
// * 数组类型的基础类型。
// *
// * @param type
// * @return
// */
// public static String toArrayTypeSimple(String type) {
// int index = 0;
// for (char c : type.toCharArray()) {
// if ('[' == c) {
// index++;
// } else {
// break;
// }
// }
//
// String arrayType;
// char ch = type.charAt(index);
// if ('L' == ch) {
// arrayType = type.substring(index + 1, type.lastIndexOf(';')).replace('/', '.');
// } else {
// switch (ch) {
// case 'Z':
// arrayType = "boolean";
// break;
// case 'B':
// arrayType = "byte";
// break;
// case 'S':
// arrayType = "short";
// break;
// case 'C':
// arrayType = "char";
// break;
// case 'I':
// arrayType = "int";
// break;
// case 'J':
// arrayType = "long";
// break;
// case 'F':
// arrayType = "float";
// break;
// case 'D':
// arrayType = "double";
// break;
// default:
// arrayType = null;
// break;
// }
// }
// return arrayType;
// }
//
// /**
// * 生成方法参数列表。
// *
// * @param params
// * @return 返回方法参数列表。
// */
// public static List<String> getTypeList(String params) {
// List<String> types = new ArrayList<String>();
// int length = params.length();
//
// for (int i = 0; i < length; ) {
// String type;
// char ch = params.charAt(i);
// if ('L' == ch) {
// int end = params.indexOf(';', i) + 1;
// type = params.substring(i, end);
// i = end;
// } else if ('[' == ch) {
// int end;
// for (end = i + 1; end < length; end++) {
// char c = params.charAt(end);
// if ('[' == c) {
// continue;
// }
// if ('L' == c) {
// end = params.indexOf(';', end) + 1;
// break;
// }
// end += 1;
// break;
// }
// type = params.substring(i, end);
// i = end;
// } else {
// type = "" + ch;
// i++;
// }
// types.add(getJavaType(type));
// }
// return types;
// }
//
// }
| import buwai.android.smali2java.Utils; | package buwai.android.smaliinstruction;
/**
*
60: sget
61: sget-wide
62: sget-object
63: sget-boolean
64: sget-byte
65: sget-char
66: sget-short
* @author buwai
*
*/
public class SmaliInstruction24 {
public static String toJava(int id, String smaliInst) {
int beginIndex, endIndex;
beginIndex = smaliInst.indexOf(' ');
endIndex = smaliInst.indexOf(',', beginIndex + 1);
String vA = smaliInst.substring(beginIndex, endIndex).trim();
beginIndex = endIndex + 1;
endIndex = smaliInst.indexOf("->", beginIndex); | // Path: src/main/java/buwai/android/smali2java/Utils.java
// public class Utils {
//
// /**
// * 将smali类型转换为Java的表示形式。
// *
// * @param type
// * @return
// */
// public static String getJavaType(String smaliType) {
// char ch;
// ch = smaliType.charAt(0);
// String javaType;
//
// int index = 0;
// int dimensions = 0;
//
// if ('L' == ch) {
// return smaliType.substring(1, smaliType.lastIndexOf(';')).replace('/', '.');
// } else if ('[' == ch) { // 处理数组的情况。
// for (char c : smaliType.toCharArray()) {
// if ('[' == c) {
// dimensions++;
// index++;
// } else {
// break;
// }
// }
// }
//
// ch = smaliType.charAt(index);
// if ('L' == ch) {
// javaType = smaliType.substring(index + 1, smaliType.lastIndexOf(';')).replace('/', '.');
// } else {
// switch (ch) {
// case 'V':
// javaType = "void";
// break;
// case 'Z':
// javaType = "boolean";
// break;
// case 'B':
// javaType = "byte";
// break;
// case 'S':
// javaType = "short";
// break;
// case 'C':
// javaType = "char";
// break;
// case 'I':
// javaType = "int";
// break;
// case 'J':
// javaType = "long";
// break;
// case 'F':
// javaType = "float";
// break;
// case 'D':
// javaType = "double";
// break;
// default:
// javaType = null;
// break;
// }
// }
//
// for (int i = 0; i < dimensions; i++) {
// javaType += "[]";
// }
//
// return javaType;
// }
//
// /**
// * 数组类型的基础类型。
// *
// * @param type
// * @return
// */
// public static String toArrayTypeSimple(String type) {
// int index = 0;
// for (char c : type.toCharArray()) {
// if ('[' == c) {
// index++;
// } else {
// break;
// }
// }
//
// String arrayType;
// char ch = type.charAt(index);
// if ('L' == ch) {
// arrayType = type.substring(index + 1, type.lastIndexOf(';')).replace('/', '.');
// } else {
// switch (ch) {
// case 'Z':
// arrayType = "boolean";
// break;
// case 'B':
// arrayType = "byte";
// break;
// case 'S':
// arrayType = "short";
// break;
// case 'C':
// arrayType = "char";
// break;
// case 'I':
// arrayType = "int";
// break;
// case 'J':
// arrayType = "long";
// break;
// case 'F':
// arrayType = "float";
// break;
// case 'D':
// arrayType = "double";
// break;
// default:
// arrayType = null;
// break;
// }
// }
// return arrayType;
// }
//
// /**
// * 生成方法参数列表。
// *
// * @param params
// * @return 返回方法参数列表。
// */
// public static List<String> getTypeList(String params) {
// List<String> types = new ArrayList<String>();
// int length = params.length();
//
// for (int i = 0; i < length; ) {
// String type;
// char ch = params.charAt(i);
// if ('L' == ch) {
// int end = params.indexOf(';', i) + 1;
// type = params.substring(i, end);
// i = end;
// } else if ('[' == ch) {
// int end;
// for (end = i + 1; end < length; end++) {
// char c = params.charAt(end);
// if ('[' == c) {
// continue;
// }
// if ('L' == c) {
// end = params.indexOf(';', end) + 1;
// break;
// }
// end += 1;
// break;
// }
// type = params.substring(i, end);
// i = end;
// } else {
// type = "" + ch;
// i++;
// }
// types.add(getJavaType(type));
// }
// return types;
// }
//
// }
// Path: src/main/java/buwai/android/smaliinstruction/SmaliInstruction24.java
import buwai.android.smali2java.Utils;
package buwai.android.smaliinstruction;
/**
*
60: sget
61: sget-wide
62: sget-object
63: sget-boolean
64: sget-byte
65: sget-char
66: sget-short
* @author buwai
*
*/
public class SmaliInstruction24 {
public static String toJava(int id, String smaliInst) {
int beginIndex, endIndex;
beginIndex = smaliInst.indexOf(' ');
endIndex = smaliInst.indexOf(',', beginIndex + 1);
String vA = smaliInst.substring(beginIndex, endIndex).trim();
beginIndex = endIndex + 1;
endIndex = smaliInst.indexOf("->", beginIndex); | String className = Utils.getJavaType(smaliInst.substring(beginIndex, endIndex).trim()); |
zylc369/smali2java | src/main/java/buwai/android/smaliinstruction/SmaliInstruction11.java | // Path: src/main/java/buwai/android/smali2java/Utils.java
// public class Utils {
//
// /**
// * 将smali类型转换为Java的表示形式。
// *
// * @param type
// * @return
// */
// public static String getJavaType(String smaliType) {
// char ch;
// ch = smaliType.charAt(0);
// String javaType;
//
// int index = 0;
// int dimensions = 0;
//
// if ('L' == ch) {
// return smaliType.substring(1, smaliType.lastIndexOf(';')).replace('/', '.');
// } else if ('[' == ch) { // 处理数组的情况。
// for (char c : smaliType.toCharArray()) {
// if ('[' == c) {
// dimensions++;
// index++;
// } else {
// break;
// }
// }
// }
//
// ch = smaliType.charAt(index);
// if ('L' == ch) {
// javaType = smaliType.substring(index + 1, smaliType.lastIndexOf(';')).replace('/', '.');
// } else {
// switch (ch) {
// case 'V':
// javaType = "void";
// break;
// case 'Z':
// javaType = "boolean";
// break;
// case 'B':
// javaType = "byte";
// break;
// case 'S':
// javaType = "short";
// break;
// case 'C':
// javaType = "char";
// break;
// case 'I':
// javaType = "int";
// break;
// case 'J':
// javaType = "long";
// break;
// case 'F':
// javaType = "float";
// break;
// case 'D':
// javaType = "double";
// break;
// default:
// javaType = null;
// break;
// }
// }
//
// for (int i = 0; i < dimensions; i++) {
// javaType += "[]";
// }
//
// return javaType;
// }
//
// /**
// * 数组类型的基础类型。
// *
// * @param type
// * @return
// */
// public static String toArrayTypeSimple(String type) {
// int index = 0;
// for (char c : type.toCharArray()) {
// if ('[' == c) {
// index++;
// } else {
// break;
// }
// }
//
// String arrayType;
// char ch = type.charAt(index);
// if ('L' == ch) {
// arrayType = type.substring(index + 1, type.lastIndexOf(';')).replace('/', '.');
// } else {
// switch (ch) {
// case 'Z':
// arrayType = "boolean";
// break;
// case 'B':
// arrayType = "byte";
// break;
// case 'S':
// arrayType = "short";
// break;
// case 'C':
// arrayType = "char";
// break;
// case 'I':
// arrayType = "int";
// break;
// case 'J':
// arrayType = "long";
// break;
// case 'F':
// arrayType = "float";
// break;
// case 'D':
// arrayType = "double";
// break;
// default:
// arrayType = null;
// break;
// }
// }
// return arrayType;
// }
//
// /**
// * 生成方法参数列表。
// *
// * @param params
// * @return 返回方法参数列表。
// */
// public static List<String> getTypeList(String params) {
// List<String> types = new ArrayList<String>();
// int length = params.length();
//
// for (int i = 0; i < length; ) {
// String type;
// char ch = params.charAt(i);
// if ('L' == ch) {
// int end = params.indexOf(';', i) + 1;
// type = params.substring(i, end);
// i = end;
// } else if ('[' == ch) {
// int end;
// for (end = i + 1; end < length; end++) {
// char c = params.charAt(end);
// if ('[' == c) {
// continue;
// }
// if ('L' == c) {
// end = params.indexOf(';', end) + 1;
// break;
// }
// end += 1;
// break;
// }
// type = params.substring(i, end);
// i = end;
// } else {
// type = "" + ch;
// i++;
// }
// types.add(getJavaType(type));
// }
// return types;
// }
//
// }
| import buwai.android.smali2java.Utils; | package buwai.android.smaliinstruction;
/**
*
23. new-array vA, vB, type@CCCC
* @author buwai
*
*/
public class SmaliInstruction11 {
public static String toJava(int id, String smaliInst) {
int beginIndex, endIndex;
beginIndex = smaliInst.indexOf(' ');
endIndex = smaliInst.indexOf(',', beginIndex + 1);
String vA = smaliInst.substring(beginIndex, endIndex).trim();
// endIndex + 1表示跳过逗号。
beginIndex = endIndex + 1;
String vB = smaliInst.substring(beginIndex, smaliInst.indexOf(',', beginIndex)).trim();
String className = smaliInst.substring(smaliInst.lastIndexOf(',') + 1).trim();
if ('[' == className.charAt(0)) { | // Path: src/main/java/buwai/android/smali2java/Utils.java
// public class Utils {
//
// /**
// * 将smali类型转换为Java的表示形式。
// *
// * @param type
// * @return
// */
// public static String getJavaType(String smaliType) {
// char ch;
// ch = smaliType.charAt(0);
// String javaType;
//
// int index = 0;
// int dimensions = 0;
//
// if ('L' == ch) {
// return smaliType.substring(1, smaliType.lastIndexOf(';')).replace('/', '.');
// } else if ('[' == ch) { // 处理数组的情况。
// for (char c : smaliType.toCharArray()) {
// if ('[' == c) {
// dimensions++;
// index++;
// } else {
// break;
// }
// }
// }
//
// ch = smaliType.charAt(index);
// if ('L' == ch) {
// javaType = smaliType.substring(index + 1, smaliType.lastIndexOf(';')).replace('/', '.');
// } else {
// switch (ch) {
// case 'V':
// javaType = "void";
// break;
// case 'Z':
// javaType = "boolean";
// break;
// case 'B':
// javaType = "byte";
// break;
// case 'S':
// javaType = "short";
// break;
// case 'C':
// javaType = "char";
// break;
// case 'I':
// javaType = "int";
// break;
// case 'J':
// javaType = "long";
// break;
// case 'F':
// javaType = "float";
// break;
// case 'D':
// javaType = "double";
// break;
// default:
// javaType = null;
// break;
// }
// }
//
// for (int i = 0; i < dimensions; i++) {
// javaType += "[]";
// }
//
// return javaType;
// }
//
// /**
// * 数组类型的基础类型。
// *
// * @param type
// * @return
// */
// public static String toArrayTypeSimple(String type) {
// int index = 0;
// for (char c : type.toCharArray()) {
// if ('[' == c) {
// index++;
// } else {
// break;
// }
// }
//
// String arrayType;
// char ch = type.charAt(index);
// if ('L' == ch) {
// arrayType = type.substring(index + 1, type.lastIndexOf(';')).replace('/', '.');
// } else {
// switch (ch) {
// case 'Z':
// arrayType = "boolean";
// break;
// case 'B':
// arrayType = "byte";
// break;
// case 'S':
// arrayType = "short";
// break;
// case 'C':
// arrayType = "char";
// break;
// case 'I':
// arrayType = "int";
// break;
// case 'J':
// arrayType = "long";
// break;
// case 'F':
// arrayType = "float";
// break;
// case 'D':
// arrayType = "double";
// break;
// default:
// arrayType = null;
// break;
// }
// }
// return arrayType;
// }
//
// /**
// * 生成方法参数列表。
// *
// * @param params
// * @return 返回方法参数列表。
// */
// public static List<String> getTypeList(String params) {
// List<String> types = new ArrayList<String>();
// int length = params.length();
//
// for (int i = 0; i < length; ) {
// String type;
// char ch = params.charAt(i);
// if ('L' == ch) {
// int end = params.indexOf(';', i) + 1;
// type = params.substring(i, end);
// i = end;
// } else if ('[' == ch) {
// int end;
// for (end = i + 1; end < length; end++) {
// char c = params.charAt(end);
// if ('[' == c) {
// continue;
// }
// if ('L' == c) {
// end = params.indexOf(';', end) + 1;
// break;
// }
// end += 1;
// break;
// }
// type = params.substring(i, end);
// i = end;
// } else {
// type = "" + ch;
// i++;
// }
// types.add(getJavaType(type));
// }
// return types;
// }
//
// }
// Path: src/main/java/buwai/android/smaliinstruction/SmaliInstruction11.java
import buwai.android.smali2java.Utils;
package buwai.android.smaliinstruction;
/**
*
23. new-array vA, vB, type@CCCC
* @author buwai
*
*/
public class SmaliInstruction11 {
public static String toJava(int id, String smaliInst) {
int beginIndex, endIndex;
beginIndex = smaliInst.indexOf(' ');
endIndex = smaliInst.indexOf(',', beginIndex + 1);
String vA = smaliInst.substring(beginIndex, endIndex).trim();
// endIndex + 1表示跳过逗号。
beginIndex = endIndex + 1;
String vB = smaliInst.substring(beginIndex, smaliInst.indexOf(',', beginIndex)).trim();
String className = smaliInst.substring(smaliInst.lastIndexOf(',') + 1).trim();
if ('[' == className.charAt(0)) { | className = Utils.toArrayTypeSimple(className); |
zylc369/smali2java | src/main/java/buwai/android/smaliinstruction/SmaliInstruction08.java | // Path: src/main/java/buwai/android/smali2java/Utils.java
// public class Utils {
//
// /**
// * 将smali类型转换为Java的表示形式。
// *
// * @param type
// * @return
// */
// public static String getJavaType(String smaliType) {
// char ch;
// ch = smaliType.charAt(0);
// String javaType;
//
// int index = 0;
// int dimensions = 0;
//
// if ('L' == ch) {
// return smaliType.substring(1, smaliType.lastIndexOf(';')).replace('/', '.');
// } else if ('[' == ch) { // 处理数组的情况。
// for (char c : smaliType.toCharArray()) {
// if ('[' == c) {
// dimensions++;
// index++;
// } else {
// break;
// }
// }
// }
//
// ch = smaliType.charAt(index);
// if ('L' == ch) {
// javaType = smaliType.substring(index + 1, smaliType.lastIndexOf(';')).replace('/', '.');
// } else {
// switch (ch) {
// case 'V':
// javaType = "void";
// break;
// case 'Z':
// javaType = "boolean";
// break;
// case 'B':
// javaType = "byte";
// break;
// case 'S':
// javaType = "short";
// break;
// case 'C':
// javaType = "char";
// break;
// case 'I':
// javaType = "int";
// break;
// case 'J':
// javaType = "long";
// break;
// case 'F':
// javaType = "float";
// break;
// case 'D':
// javaType = "double";
// break;
// default:
// javaType = null;
// break;
// }
// }
//
// for (int i = 0; i < dimensions; i++) {
// javaType += "[]";
// }
//
// return javaType;
// }
//
// /**
// * 数组类型的基础类型。
// *
// * @param type
// * @return
// */
// public static String toArrayTypeSimple(String type) {
// int index = 0;
// for (char c : type.toCharArray()) {
// if ('[' == c) {
// index++;
// } else {
// break;
// }
// }
//
// String arrayType;
// char ch = type.charAt(index);
// if ('L' == ch) {
// arrayType = type.substring(index + 1, type.lastIndexOf(';')).replace('/', '.');
// } else {
// switch (ch) {
// case 'Z':
// arrayType = "boolean";
// break;
// case 'B':
// arrayType = "byte";
// break;
// case 'S':
// arrayType = "short";
// break;
// case 'C':
// arrayType = "char";
// break;
// case 'I':
// arrayType = "int";
// break;
// case 'J':
// arrayType = "long";
// break;
// case 'F':
// arrayType = "float";
// break;
// case 'D':
// arrayType = "double";
// break;
// default:
// arrayType = null;
// break;
// }
// }
// return arrayType;
// }
//
// /**
// * 生成方法参数列表。
// *
// * @param params
// * @return 返回方法参数列表。
// */
// public static List<String> getTypeList(String params) {
// List<String> types = new ArrayList<String>();
// int length = params.length();
//
// for (int i = 0; i < length; ) {
// String type;
// char ch = params.charAt(i);
// if ('L' == ch) {
// int end = params.indexOf(';', i) + 1;
// type = params.substring(i, end);
// i = end;
// } else if ('[' == ch) {
// int end;
// for (end = i + 1; end < length; end++) {
// char c = params.charAt(end);
// if ('[' == c) {
// continue;
// }
// if ('L' == c) {
// end = params.indexOf(';', end) + 1;
// break;
// }
// end += 1;
// break;
// }
// type = params.substring(i, end);
// i = end;
// } else {
// type = "" + ch;
// i++;
// }
// types.add(getJavaType(type));
// }
// return types;
// }
//
// }
| import buwai.android.smali2java.Utils; | package buwai.android.smaliinstruction;
/**
*
20. instance-of vA, vB, type@CCCC
*
* @author buwai
*
*/
public class SmaliInstruction08 {
public static String toJava(int id, String smaliInst) {
int beginIndex, endIndex;
beginIndex = smaliInst.indexOf(' ');
endIndex = smaliInst.indexOf(',', beginIndex + 1);
String vA = smaliInst.substring(beginIndex, endIndex).trim();
// endIndex + 1表示跳过逗号。
String vB = smaliInst.substring(endIndex + 1, smaliInst.indexOf(',', endIndex + 1)).trim();
| // Path: src/main/java/buwai/android/smali2java/Utils.java
// public class Utils {
//
// /**
// * 将smali类型转换为Java的表示形式。
// *
// * @param type
// * @return
// */
// public static String getJavaType(String smaliType) {
// char ch;
// ch = smaliType.charAt(0);
// String javaType;
//
// int index = 0;
// int dimensions = 0;
//
// if ('L' == ch) {
// return smaliType.substring(1, smaliType.lastIndexOf(';')).replace('/', '.');
// } else if ('[' == ch) { // 处理数组的情况。
// for (char c : smaliType.toCharArray()) {
// if ('[' == c) {
// dimensions++;
// index++;
// } else {
// break;
// }
// }
// }
//
// ch = smaliType.charAt(index);
// if ('L' == ch) {
// javaType = smaliType.substring(index + 1, smaliType.lastIndexOf(';')).replace('/', '.');
// } else {
// switch (ch) {
// case 'V':
// javaType = "void";
// break;
// case 'Z':
// javaType = "boolean";
// break;
// case 'B':
// javaType = "byte";
// break;
// case 'S':
// javaType = "short";
// break;
// case 'C':
// javaType = "char";
// break;
// case 'I':
// javaType = "int";
// break;
// case 'J':
// javaType = "long";
// break;
// case 'F':
// javaType = "float";
// break;
// case 'D':
// javaType = "double";
// break;
// default:
// javaType = null;
// break;
// }
// }
//
// for (int i = 0; i < dimensions; i++) {
// javaType += "[]";
// }
//
// return javaType;
// }
//
// /**
// * 数组类型的基础类型。
// *
// * @param type
// * @return
// */
// public static String toArrayTypeSimple(String type) {
// int index = 0;
// for (char c : type.toCharArray()) {
// if ('[' == c) {
// index++;
// } else {
// break;
// }
// }
//
// String arrayType;
// char ch = type.charAt(index);
// if ('L' == ch) {
// arrayType = type.substring(index + 1, type.lastIndexOf(';')).replace('/', '.');
// } else {
// switch (ch) {
// case 'Z':
// arrayType = "boolean";
// break;
// case 'B':
// arrayType = "byte";
// break;
// case 'S':
// arrayType = "short";
// break;
// case 'C':
// arrayType = "char";
// break;
// case 'I':
// arrayType = "int";
// break;
// case 'J':
// arrayType = "long";
// break;
// case 'F':
// arrayType = "float";
// break;
// case 'D':
// arrayType = "double";
// break;
// default:
// arrayType = null;
// break;
// }
// }
// return arrayType;
// }
//
// /**
// * 生成方法参数列表。
// *
// * @param params
// * @return 返回方法参数列表。
// */
// public static List<String> getTypeList(String params) {
// List<String> types = new ArrayList<String>();
// int length = params.length();
//
// for (int i = 0; i < length; ) {
// String type;
// char ch = params.charAt(i);
// if ('L' == ch) {
// int end = params.indexOf(';', i) + 1;
// type = params.substring(i, end);
// i = end;
// } else if ('[' == ch) {
// int end;
// for (end = i + 1; end < length; end++) {
// char c = params.charAt(end);
// if ('[' == c) {
// continue;
// }
// if ('L' == c) {
// end = params.indexOf(';', end) + 1;
// break;
// }
// end += 1;
// break;
// }
// type = params.substring(i, end);
// i = end;
// } else {
// type = "" + ch;
// i++;
// }
// types.add(getJavaType(type));
// }
// return types;
// }
//
// }
// Path: src/main/java/buwai/android/smaliinstruction/SmaliInstruction08.java
import buwai.android.smali2java.Utils;
package buwai.android.smaliinstruction;
/**
*
20. instance-of vA, vB, type@CCCC
*
* @author buwai
*
*/
public class SmaliInstruction08 {
public static String toJava(int id, String smaliInst) {
int beginIndex, endIndex;
beginIndex = smaliInst.indexOf(' ');
endIndex = smaliInst.indexOf(',', beginIndex + 1);
String vA = smaliInst.substring(beginIndex, endIndex).trim();
// endIndex + 1表示跳过逗号。
String vB = smaliInst.substring(endIndex + 1, smaliInst.indexOf(',', endIndex + 1)).trim();
| String className = Utils.getJavaType(smaliInst.substring(smaliInst.lastIndexOf(',') + 1).trim()); |
zylc369/smali2java | src/main/java/buwai/android/smaliinstruction/SmaliInstruction10.java | // Path: src/main/java/buwai/android/smali2java/Utils.java
// public class Utils {
//
// /**
// * 将smali类型转换为Java的表示形式。
// *
// * @param type
// * @return
// */
// public static String getJavaType(String smaliType) {
// char ch;
// ch = smaliType.charAt(0);
// String javaType;
//
// int index = 0;
// int dimensions = 0;
//
// if ('L' == ch) {
// return smaliType.substring(1, smaliType.lastIndexOf(';')).replace('/', '.');
// } else if ('[' == ch) { // 处理数组的情况。
// for (char c : smaliType.toCharArray()) {
// if ('[' == c) {
// dimensions++;
// index++;
// } else {
// break;
// }
// }
// }
//
// ch = smaliType.charAt(index);
// if ('L' == ch) {
// javaType = smaliType.substring(index + 1, smaliType.lastIndexOf(';')).replace('/', '.');
// } else {
// switch (ch) {
// case 'V':
// javaType = "void";
// break;
// case 'Z':
// javaType = "boolean";
// break;
// case 'B':
// javaType = "byte";
// break;
// case 'S':
// javaType = "short";
// break;
// case 'C':
// javaType = "char";
// break;
// case 'I':
// javaType = "int";
// break;
// case 'J':
// javaType = "long";
// break;
// case 'F':
// javaType = "float";
// break;
// case 'D':
// javaType = "double";
// break;
// default:
// javaType = null;
// break;
// }
// }
//
// for (int i = 0; i < dimensions; i++) {
// javaType += "[]";
// }
//
// return javaType;
// }
//
// /**
// * 数组类型的基础类型。
// *
// * @param type
// * @return
// */
// public static String toArrayTypeSimple(String type) {
// int index = 0;
// for (char c : type.toCharArray()) {
// if ('[' == c) {
// index++;
// } else {
// break;
// }
// }
//
// String arrayType;
// char ch = type.charAt(index);
// if ('L' == ch) {
// arrayType = type.substring(index + 1, type.lastIndexOf(';')).replace('/', '.');
// } else {
// switch (ch) {
// case 'Z':
// arrayType = "boolean";
// break;
// case 'B':
// arrayType = "byte";
// break;
// case 'S':
// arrayType = "short";
// break;
// case 'C':
// arrayType = "char";
// break;
// case 'I':
// arrayType = "int";
// break;
// case 'J':
// arrayType = "long";
// break;
// case 'F':
// arrayType = "float";
// break;
// case 'D':
// arrayType = "double";
// break;
// default:
// arrayType = null;
// break;
// }
// }
// return arrayType;
// }
//
// /**
// * 生成方法参数列表。
// *
// * @param params
// * @return 返回方法参数列表。
// */
// public static List<String> getTypeList(String params) {
// List<String> types = new ArrayList<String>();
// int length = params.length();
//
// for (int i = 0; i < length; ) {
// String type;
// char ch = params.charAt(i);
// if ('L' == ch) {
// int end = params.indexOf(';', i) + 1;
// type = params.substring(i, end);
// i = end;
// } else if ('[' == ch) {
// int end;
// for (end = i + 1; end < length; end++) {
// char c = params.charAt(end);
// if ('[' == c) {
// continue;
// }
// if ('L' == c) {
// end = params.indexOf(';', end) + 1;
// break;
// }
// end += 1;
// break;
// }
// type = params.substring(i, end);
// i = end;
// } else {
// type = "" + ch;
// i++;
// }
// types.add(getJavaType(type));
// }
// return types;
// }
//
// }
| import buwai.android.smali2java.Utils; | package buwai.android.smaliinstruction;
/**
*
22. new-instance vAA, type@BBBB
* @author buwai
*
*/
public class SmaliInstruction10 {
public static String toJava(int id, String smaliInst) {
int beginIndex, endIndex;
beginIndex = smaliInst.indexOf(' ');
endIndex = smaliInst.indexOf(',', beginIndex + 1);
String vA = smaliInst.substring(beginIndex, endIndex).trim();
| // Path: src/main/java/buwai/android/smali2java/Utils.java
// public class Utils {
//
// /**
// * 将smali类型转换为Java的表示形式。
// *
// * @param type
// * @return
// */
// public static String getJavaType(String smaliType) {
// char ch;
// ch = smaliType.charAt(0);
// String javaType;
//
// int index = 0;
// int dimensions = 0;
//
// if ('L' == ch) {
// return smaliType.substring(1, smaliType.lastIndexOf(';')).replace('/', '.');
// } else if ('[' == ch) { // 处理数组的情况。
// for (char c : smaliType.toCharArray()) {
// if ('[' == c) {
// dimensions++;
// index++;
// } else {
// break;
// }
// }
// }
//
// ch = smaliType.charAt(index);
// if ('L' == ch) {
// javaType = smaliType.substring(index + 1, smaliType.lastIndexOf(';')).replace('/', '.');
// } else {
// switch (ch) {
// case 'V':
// javaType = "void";
// break;
// case 'Z':
// javaType = "boolean";
// break;
// case 'B':
// javaType = "byte";
// break;
// case 'S':
// javaType = "short";
// break;
// case 'C':
// javaType = "char";
// break;
// case 'I':
// javaType = "int";
// break;
// case 'J':
// javaType = "long";
// break;
// case 'F':
// javaType = "float";
// break;
// case 'D':
// javaType = "double";
// break;
// default:
// javaType = null;
// break;
// }
// }
//
// for (int i = 0; i < dimensions; i++) {
// javaType += "[]";
// }
//
// return javaType;
// }
//
// /**
// * 数组类型的基础类型。
// *
// * @param type
// * @return
// */
// public static String toArrayTypeSimple(String type) {
// int index = 0;
// for (char c : type.toCharArray()) {
// if ('[' == c) {
// index++;
// } else {
// break;
// }
// }
//
// String arrayType;
// char ch = type.charAt(index);
// if ('L' == ch) {
// arrayType = type.substring(index + 1, type.lastIndexOf(';')).replace('/', '.');
// } else {
// switch (ch) {
// case 'Z':
// arrayType = "boolean";
// break;
// case 'B':
// arrayType = "byte";
// break;
// case 'S':
// arrayType = "short";
// break;
// case 'C':
// arrayType = "char";
// break;
// case 'I':
// arrayType = "int";
// break;
// case 'J':
// arrayType = "long";
// break;
// case 'F':
// arrayType = "float";
// break;
// case 'D':
// arrayType = "double";
// break;
// default:
// arrayType = null;
// break;
// }
// }
// return arrayType;
// }
//
// /**
// * 生成方法参数列表。
// *
// * @param params
// * @return 返回方法参数列表。
// */
// public static List<String> getTypeList(String params) {
// List<String> types = new ArrayList<String>();
// int length = params.length();
//
// for (int i = 0; i < length; ) {
// String type;
// char ch = params.charAt(i);
// if ('L' == ch) {
// int end = params.indexOf(';', i) + 1;
// type = params.substring(i, end);
// i = end;
// } else if ('[' == ch) {
// int end;
// for (end = i + 1; end < length; end++) {
// char c = params.charAt(end);
// if ('[' == c) {
// continue;
// }
// if ('L' == c) {
// end = params.indexOf(';', end) + 1;
// break;
// }
// end += 1;
// break;
// }
// type = params.substring(i, end);
// i = end;
// } else {
// type = "" + ch;
// i++;
// }
// types.add(getJavaType(type));
// }
// return types;
// }
//
// }
// Path: src/main/java/buwai/android/smaliinstruction/SmaliInstruction10.java
import buwai.android.smali2java.Utils;
package buwai.android.smaliinstruction;
/**
*
22. new-instance vAA, type@BBBB
* @author buwai
*
*/
public class SmaliInstruction10 {
public static String toJava(int id, String smaliInst) {
int beginIndex, endIndex;
beginIndex = smaliInst.indexOf(' ');
endIndex = smaliInst.indexOf(',', beginIndex + 1);
String vA = smaliInst.substring(beginIndex, endIndex).trim();
| String className = Utils.getJavaType(smaliInst.substring(smaliInst.lastIndexOf(',') + 1).trim()); |
zylc369/smali2java | src/main/java/buwai/android/smaliinstruction/SmaliInstruction22.java | // Path: src/main/java/buwai/android/smali2java/Utils.java
// public class Utils {
//
// /**
// * 将smali类型转换为Java的表示形式。
// *
// * @param type
// * @return
// */
// public static String getJavaType(String smaliType) {
// char ch;
// ch = smaliType.charAt(0);
// String javaType;
//
// int index = 0;
// int dimensions = 0;
//
// if ('L' == ch) {
// return smaliType.substring(1, smaliType.lastIndexOf(';')).replace('/', '.');
// } else if ('[' == ch) { // 处理数组的情况。
// for (char c : smaliType.toCharArray()) {
// if ('[' == c) {
// dimensions++;
// index++;
// } else {
// break;
// }
// }
// }
//
// ch = smaliType.charAt(index);
// if ('L' == ch) {
// javaType = smaliType.substring(index + 1, smaliType.lastIndexOf(';')).replace('/', '.');
// } else {
// switch (ch) {
// case 'V':
// javaType = "void";
// break;
// case 'Z':
// javaType = "boolean";
// break;
// case 'B':
// javaType = "byte";
// break;
// case 'S':
// javaType = "short";
// break;
// case 'C':
// javaType = "char";
// break;
// case 'I':
// javaType = "int";
// break;
// case 'J':
// javaType = "long";
// break;
// case 'F':
// javaType = "float";
// break;
// case 'D':
// javaType = "double";
// break;
// default:
// javaType = null;
// break;
// }
// }
//
// for (int i = 0; i < dimensions; i++) {
// javaType += "[]";
// }
//
// return javaType;
// }
//
// /**
// * 数组类型的基础类型。
// *
// * @param type
// * @return
// */
// public static String toArrayTypeSimple(String type) {
// int index = 0;
// for (char c : type.toCharArray()) {
// if ('[' == c) {
// index++;
// } else {
// break;
// }
// }
//
// String arrayType;
// char ch = type.charAt(index);
// if ('L' == ch) {
// arrayType = type.substring(index + 1, type.lastIndexOf(';')).replace('/', '.');
// } else {
// switch (ch) {
// case 'Z':
// arrayType = "boolean";
// break;
// case 'B':
// arrayType = "byte";
// break;
// case 'S':
// arrayType = "short";
// break;
// case 'C':
// arrayType = "char";
// break;
// case 'I':
// arrayType = "int";
// break;
// case 'J':
// arrayType = "long";
// break;
// case 'F':
// arrayType = "float";
// break;
// case 'D':
// arrayType = "double";
// break;
// default:
// arrayType = null;
// break;
// }
// }
// return arrayType;
// }
//
// /**
// * 生成方法参数列表。
// *
// * @param params
// * @return 返回方法参数列表。
// */
// public static List<String> getTypeList(String params) {
// List<String> types = new ArrayList<String>();
// int length = params.length();
//
// for (int i = 0; i < length; ) {
// String type;
// char ch = params.charAt(i);
// if ('L' == ch) {
// int end = params.indexOf(';', i) + 1;
// type = params.substring(i, end);
// i = end;
// } else if ('[' == ch) {
// int end;
// for (end = i + 1; end < length; end++) {
// char c = params.charAt(end);
// if ('[' == c) {
// continue;
// }
// if ('L' == c) {
// end = params.indexOf(';', end) + 1;
// break;
// }
// end += 1;
// break;
// }
// type = params.substring(i, end);
// i = end;
// } else {
// type = "" + ch;
// i++;
// }
// types.add(getJavaType(type));
// }
// return types;
// }
//
// }
| import buwai.android.smali2java.Utils; | package buwai.android.smaliinstruction;
/**
*
52: iget
53: iget-wide
54: iget-object
55: iget-boolean
56: iget-byte
57: iget-char
58: iget-short
* @author buwai
*
*/
public class SmaliInstruction22 {
public static String toJava(int id, String smaliInst) {
int beginIndex, endIndex;
beginIndex = smaliInst.indexOf(' ');
endIndex = smaliInst.indexOf(',', beginIndex + 1);
String vA = smaliInst.substring(beginIndex, endIndex).trim();
beginIndex = endIndex + 1;
endIndex = smaliInst.indexOf(',', beginIndex + 1);
String vB = smaliInst.substring(beginIndex, endIndex).trim();
beginIndex = smaliInst.lastIndexOf(',') + 1;
endIndex = smaliInst.lastIndexOf("->"); | // Path: src/main/java/buwai/android/smali2java/Utils.java
// public class Utils {
//
// /**
// * 将smali类型转换为Java的表示形式。
// *
// * @param type
// * @return
// */
// public static String getJavaType(String smaliType) {
// char ch;
// ch = smaliType.charAt(0);
// String javaType;
//
// int index = 0;
// int dimensions = 0;
//
// if ('L' == ch) {
// return smaliType.substring(1, smaliType.lastIndexOf(';')).replace('/', '.');
// } else if ('[' == ch) { // 处理数组的情况。
// for (char c : smaliType.toCharArray()) {
// if ('[' == c) {
// dimensions++;
// index++;
// } else {
// break;
// }
// }
// }
//
// ch = smaliType.charAt(index);
// if ('L' == ch) {
// javaType = smaliType.substring(index + 1, smaliType.lastIndexOf(';')).replace('/', '.');
// } else {
// switch (ch) {
// case 'V':
// javaType = "void";
// break;
// case 'Z':
// javaType = "boolean";
// break;
// case 'B':
// javaType = "byte";
// break;
// case 'S':
// javaType = "short";
// break;
// case 'C':
// javaType = "char";
// break;
// case 'I':
// javaType = "int";
// break;
// case 'J':
// javaType = "long";
// break;
// case 'F':
// javaType = "float";
// break;
// case 'D':
// javaType = "double";
// break;
// default:
// javaType = null;
// break;
// }
// }
//
// for (int i = 0; i < dimensions; i++) {
// javaType += "[]";
// }
//
// return javaType;
// }
//
// /**
// * 数组类型的基础类型。
// *
// * @param type
// * @return
// */
// public static String toArrayTypeSimple(String type) {
// int index = 0;
// for (char c : type.toCharArray()) {
// if ('[' == c) {
// index++;
// } else {
// break;
// }
// }
//
// String arrayType;
// char ch = type.charAt(index);
// if ('L' == ch) {
// arrayType = type.substring(index + 1, type.lastIndexOf(';')).replace('/', '.');
// } else {
// switch (ch) {
// case 'Z':
// arrayType = "boolean";
// break;
// case 'B':
// arrayType = "byte";
// break;
// case 'S':
// arrayType = "short";
// break;
// case 'C':
// arrayType = "char";
// break;
// case 'I':
// arrayType = "int";
// break;
// case 'J':
// arrayType = "long";
// break;
// case 'F':
// arrayType = "float";
// break;
// case 'D':
// arrayType = "double";
// break;
// default:
// arrayType = null;
// break;
// }
// }
// return arrayType;
// }
//
// /**
// * 生成方法参数列表。
// *
// * @param params
// * @return 返回方法参数列表。
// */
// public static List<String> getTypeList(String params) {
// List<String> types = new ArrayList<String>();
// int length = params.length();
//
// for (int i = 0; i < length; ) {
// String type;
// char ch = params.charAt(i);
// if ('L' == ch) {
// int end = params.indexOf(';', i) + 1;
// type = params.substring(i, end);
// i = end;
// } else if ('[' == ch) {
// int end;
// for (end = i + 1; end < length; end++) {
// char c = params.charAt(end);
// if ('[' == c) {
// continue;
// }
// if ('L' == c) {
// end = params.indexOf(';', end) + 1;
// break;
// }
// end += 1;
// break;
// }
// type = params.substring(i, end);
// i = end;
// } else {
// type = "" + ch;
// i++;
// }
// types.add(getJavaType(type));
// }
// return types;
// }
//
// }
// Path: src/main/java/buwai/android/smaliinstruction/SmaliInstruction22.java
import buwai.android.smali2java.Utils;
package buwai.android.smaliinstruction;
/**
*
52: iget
53: iget-wide
54: iget-object
55: iget-boolean
56: iget-byte
57: iget-char
58: iget-short
* @author buwai
*
*/
public class SmaliInstruction22 {
public static String toJava(int id, String smaliInst) {
int beginIndex, endIndex;
beginIndex = smaliInst.indexOf(' ');
endIndex = smaliInst.indexOf(',', beginIndex + 1);
String vA = smaliInst.substring(beginIndex, endIndex).trim();
beginIndex = endIndex + 1;
endIndex = smaliInst.indexOf(',', beginIndex + 1);
String vB = smaliInst.substring(beginIndex, endIndex).trim();
beginIndex = smaliInst.lastIndexOf(',') + 1;
endIndex = smaliInst.lastIndexOf("->"); | String instanceName = Utils.getJavaType(smaliInst.substring(beginIndex, endIndex).trim()); |
zylc369/smali2java | src/main/java/buwai/android/smaliinstruction/SmaliInstruction25.java | // Path: src/main/java/buwai/android/smali2java/Utils.java
// public class Utils {
//
// /**
// * 将smali类型转换为Java的表示形式。
// *
// * @param type
// * @return
// */
// public static String getJavaType(String smaliType) {
// char ch;
// ch = smaliType.charAt(0);
// String javaType;
//
// int index = 0;
// int dimensions = 0;
//
// if ('L' == ch) {
// return smaliType.substring(1, smaliType.lastIndexOf(';')).replace('/', '.');
// } else if ('[' == ch) { // 处理数组的情况。
// for (char c : smaliType.toCharArray()) {
// if ('[' == c) {
// dimensions++;
// index++;
// } else {
// break;
// }
// }
// }
//
// ch = smaliType.charAt(index);
// if ('L' == ch) {
// javaType = smaliType.substring(index + 1, smaliType.lastIndexOf(';')).replace('/', '.');
// } else {
// switch (ch) {
// case 'V':
// javaType = "void";
// break;
// case 'Z':
// javaType = "boolean";
// break;
// case 'B':
// javaType = "byte";
// break;
// case 'S':
// javaType = "short";
// break;
// case 'C':
// javaType = "char";
// break;
// case 'I':
// javaType = "int";
// break;
// case 'J':
// javaType = "long";
// break;
// case 'F':
// javaType = "float";
// break;
// case 'D':
// javaType = "double";
// break;
// default:
// javaType = null;
// break;
// }
// }
//
// for (int i = 0; i < dimensions; i++) {
// javaType += "[]";
// }
//
// return javaType;
// }
//
// /**
// * 数组类型的基础类型。
// *
// * @param type
// * @return
// */
// public static String toArrayTypeSimple(String type) {
// int index = 0;
// for (char c : type.toCharArray()) {
// if ('[' == c) {
// index++;
// } else {
// break;
// }
// }
//
// String arrayType;
// char ch = type.charAt(index);
// if ('L' == ch) {
// arrayType = type.substring(index + 1, type.lastIndexOf(';')).replace('/', '.');
// } else {
// switch (ch) {
// case 'Z':
// arrayType = "boolean";
// break;
// case 'B':
// arrayType = "byte";
// break;
// case 'S':
// arrayType = "short";
// break;
// case 'C':
// arrayType = "char";
// break;
// case 'I':
// arrayType = "int";
// break;
// case 'J':
// arrayType = "long";
// break;
// case 'F':
// arrayType = "float";
// break;
// case 'D':
// arrayType = "double";
// break;
// default:
// arrayType = null;
// break;
// }
// }
// return arrayType;
// }
//
// /**
// * 生成方法参数列表。
// *
// * @param params
// * @return 返回方法参数列表。
// */
// public static List<String> getTypeList(String params) {
// List<String> types = new ArrayList<String>();
// int length = params.length();
//
// for (int i = 0; i < length; ) {
// String type;
// char ch = params.charAt(i);
// if ('L' == ch) {
// int end = params.indexOf(';', i) + 1;
// type = params.substring(i, end);
// i = end;
// } else if ('[' == ch) {
// int end;
// for (end = i + 1; end < length; end++) {
// char c = params.charAt(end);
// if ('[' == c) {
// continue;
// }
// if ('L' == c) {
// end = params.indexOf(';', end) + 1;
// break;
// }
// end += 1;
// break;
// }
// type = params.substring(i, end);
// i = end;
// } else {
// type = "" + ch;
// i++;
// }
// types.add(getJavaType(type));
// }
// return types;
// }
//
// }
| import buwai.android.smali2java.Utils; | package buwai.android.smaliinstruction;
/**
*
67: sput
68: sput-wide
69: sput-object
6a: sput-boolean
6b: sput-byte
6c: sput-char
6d: sput-short
* @author buwai
*
*/
public class SmaliInstruction25 {
public static String toJava(int id, String smaliInst) {
int beginIndex, endIndex;
beginIndex = smaliInst.indexOf(' ');
endIndex = smaliInst.indexOf(',', beginIndex + 1);
String vA = smaliInst.substring(beginIndex, endIndex).trim();
beginIndex = endIndex + 1;
endIndex = smaliInst.indexOf("->", beginIndex); | // Path: src/main/java/buwai/android/smali2java/Utils.java
// public class Utils {
//
// /**
// * 将smali类型转换为Java的表示形式。
// *
// * @param type
// * @return
// */
// public static String getJavaType(String smaliType) {
// char ch;
// ch = smaliType.charAt(0);
// String javaType;
//
// int index = 0;
// int dimensions = 0;
//
// if ('L' == ch) {
// return smaliType.substring(1, smaliType.lastIndexOf(';')).replace('/', '.');
// } else if ('[' == ch) { // 处理数组的情况。
// for (char c : smaliType.toCharArray()) {
// if ('[' == c) {
// dimensions++;
// index++;
// } else {
// break;
// }
// }
// }
//
// ch = smaliType.charAt(index);
// if ('L' == ch) {
// javaType = smaliType.substring(index + 1, smaliType.lastIndexOf(';')).replace('/', '.');
// } else {
// switch (ch) {
// case 'V':
// javaType = "void";
// break;
// case 'Z':
// javaType = "boolean";
// break;
// case 'B':
// javaType = "byte";
// break;
// case 'S':
// javaType = "short";
// break;
// case 'C':
// javaType = "char";
// break;
// case 'I':
// javaType = "int";
// break;
// case 'J':
// javaType = "long";
// break;
// case 'F':
// javaType = "float";
// break;
// case 'D':
// javaType = "double";
// break;
// default:
// javaType = null;
// break;
// }
// }
//
// for (int i = 0; i < dimensions; i++) {
// javaType += "[]";
// }
//
// return javaType;
// }
//
// /**
// * 数组类型的基础类型。
// *
// * @param type
// * @return
// */
// public static String toArrayTypeSimple(String type) {
// int index = 0;
// for (char c : type.toCharArray()) {
// if ('[' == c) {
// index++;
// } else {
// break;
// }
// }
//
// String arrayType;
// char ch = type.charAt(index);
// if ('L' == ch) {
// arrayType = type.substring(index + 1, type.lastIndexOf(';')).replace('/', '.');
// } else {
// switch (ch) {
// case 'Z':
// arrayType = "boolean";
// break;
// case 'B':
// arrayType = "byte";
// break;
// case 'S':
// arrayType = "short";
// break;
// case 'C':
// arrayType = "char";
// break;
// case 'I':
// arrayType = "int";
// break;
// case 'J':
// arrayType = "long";
// break;
// case 'F':
// arrayType = "float";
// break;
// case 'D':
// arrayType = "double";
// break;
// default:
// arrayType = null;
// break;
// }
// }
// return arrayType;
// }
//
// /**
// * 生成方法参数列表。
// *
// * @param params
// * @return 返回方法参数列表。
// */
// public static List<String> getTypeList(String params) {
// List<String> types = new ArrayList<String>();
// int length = params.length();
//
// for (int i = 0; i < length; ) {
// String type;
// char ch = params.charAt(i);
// if ('L' == ch) {
// int end = params.indexOf(';', i) + 1;
// type = params.substring(i, end);
// i = end;
// } else if ('[' == ch) {
// int end;
// for (end = i + 1; end < length; end++) {
// char c = params.charAt(end);
// if ('[' == c) {
// continue;
// }
// if ('L' == c) {
// end = params.indexOf(';', end) + 1;
// break;
// }
// end += 1;
// break;
// }
// type = params.substring(i, end);
// i = end;
// } else {
// type = "" + ch;
// i++;
// }
// types.add(getJavaType(type));
// }
// return types;
// }
//
// }
// Path: src/main/java/buwai/android/smaliinstruction/SmaliInstruction25.java
import buwai.android.smali2java.Utils;
package buwai.android.smaliinstruction;
/**
*
67: sput
68: sput-wide
69: sput-object
6a: sput-boolean
6b: sput-byte
6c: sput-char
6d: sput-short
* @author buwai
*
*/
public class SmaliInstruction25 {
public static String toJava(int id, String smaliInst) {
int beginIndex, endIndex;
beginIndex = smaliInst.indexOf(' ');
endIndex = smaliInst.indexOf(',', beginIndex + 1);
String vA = smaliInst.substring(beginIndex, endIndex).trim();
beginIndex = endIndex + 1;
endIndex = smaliInst.indexOf("->", beginIndex); | String className = Utils.getJavaType(smaliInst.substring(beginIndex, endIndex).trim()); |
zylc369/smali2java | src/main/java/buwai/android/smaliinstruction/SmaliInstruction04.java | // Path: src/main/java/buwai/android/smali2java/Utils.java
// public class Utils {
//
// /**
// * 将smali类型转换为Java的表示形式。
// *
// * @param type
// * @return
// */
// public static String getJavaType(String smaliType) {
// char ch;
// ch = smaliType.charAt(0);
// String javaType;
//
// int index = 0;
// int dimensions = 0;
//
// if ('L' == ch) {
// return smaliType.substring(1, smaliType.lastIndexOf(';')).replace('/', '.');
// } else if ('[' == ch) { // 处理数组的情况。
// for (char c : smaliType.toCharArray()) {
// if ('[' == c) {
// dimensions++;
// index++;
// } else {
// break;
// }
// }
// }
//
// ch = smaliType.charAt(index);
// if ('L' == ch) {
// javaType = smaliType.substring(index + 1, smaliType.lastIndexOf(';')).replace('/', '.');
// } else {
// switch (ch) {
// case 'V':
// javaType = "void";
// break;
// case 'Z':
// javaType = "boolean";
// break;
// case 'B':
// javaType = "byte";
// break;
// case 'S':
// javaType = "short";
// break;
// case 'C':
// javaType = "char";
// break;
// case 'I':
// javaType = "int";
// break;
// case 'J':
// javaType = "long";
// break;
// case 'F':
// javaType = "float";
// break;
// case 'D':
// javaType = "double";
// break;
// default:
// javaType = null;
// break;
// }
// }
//
// for (int i = 0; i < dimensions; i++) {
// javaType += "[]";
// }
//
// return javaType;
// }
//
// /**
// * 数组类型的基础类型。
// *
// * @param type
// * @return
// */
// public static String toArrayTypeSimple(String type) {
// int index = 0;
// for (char c : type.toCharArray()) {
// if ('[' == c) {
// index++;
// } else {
// break;
// }
// }
//
// String arrayType;
// char ch = type.charAt(index);
// if ('L' == ch) {
// arrayType = type.substring(index + 1, type.lastIndexOf(';')).replace('/', '.');
// } else {
// switch (ch) {
// case 'Z':
// arrayType = "boolean";
// break;
// case 'B':
// arrayType = "byte";
// break;
// case 'S':
// arrayType = "short";
// break;
// case 'C':
// arrayType = "char";
// break;
// case 'I':
// arrayType = "int";
// break;
// case 'J':
// arrayType = "long";
// break;
// case 'F':
// arrayType = "float";
// break;
// case 'D':
// arrayType = "double";
// break;
// default:
// arrayType = null;
// break;
// }
// }
// return arrayType;
// }
//
// /**
// * 生成方法参数列表。
// *
// * @param params
// * @return 返回方法参数列表。
// */
// public static List<String> getTypeList(String params) {
// List<String> types = new ArrayList<String>();
// int length = params.length();
//
// for (int i = 0; i < length; ) {
// String type;
// char ch = params.charAt(i);
// if ('L' == ch) {
// int end = params.indexOf(';', i) + 1;
// type = params.substring(i, end);
// i = end;
// } else if ('[' == ch) {
// int end;
// for (end = i + 1; end < length; end++) {
// char c = params.charAt(end);
// if ('[' == c) {
// continue;
// }
// if ('L' == c) {
// end = params.indexOf(';', end) + 1;
// break;
// }
// end += 1;
// break;
// }
// type = params.substring(i, end);
// i = end;
// } else {
// type = "" + ch;
// i++;
// }
// types.add(getJavaType(type));
// }
// return types;
// }
//
// }
| import buwai.android.smali2java.Utils; | package buwai.android.smaliinstruction;
/**
*
1c. const-class vAA, type@BBBB -> <类>.class
*
* @author buwai
*
*/
public class SmaliInstruction04 {
public static String toJava(int id, String smaliInst) {
int beginIndex, endIndex;
beginIndex = smaliInst.indexOf(' ');
endIndex = smaliInst.indexOf(',', beginIndex + 1);
String vA = smaliInst.substring(beginIndex, endIndex).trim();
// endIndex + 1表示跳过逗号。 | // Path: src/main/java/buwai/android/smali2java/Utils.java
// public class Utils {
//
// /**
// * 将smali类型转换为Java的表示形式。
// *
// * @param type
// * @return
// */
// public static String getJavaType(String smaliType) {
// char ch;
// ch = smaliType.charAt(0);
// String javaType;
//
// int index = 0;
// int dimensions = 0;
//
// if ('L' == ch) {
// return smaliType.substring(1, smaliType.lastIndexOf(';')).replace('/', '.');
// } else if ('[' == ch) { // 处理数组的情况。
// for (char c : smaliType.toCharArray()) {
// if ('[' == c) {
// dimensions++;
// index++;
// } else {
// break;
// }
// }
// }
//
// ch = smaliType.charAt(index);
// if ('L' == ch) {
// javaType = smaliType.substring(index + 1, smaliType.lastIndexOf(';')).replace('/', '.');
// } else {
// switch (ch) {
// case 'V':
// javaType = "void";
// break;
// case 'Z':
// javaType = "boolean";
// break;
// case 'B':
// javaType = "byte";
// break;
// case 'S':
// javaType = "short";
// break;
// case 'C':
// javaType = "char";
// break;
// case 'I':
// javaType = "int";
// break;
// case 'J':
// javaType = "long";
// break;
// case 'F':
// javaType = "float";
// break;
// case 'D':
// javaType = "double";
// break;
// default:
// javaType = null;
// break;
// }
// }
//
// for (int i = 0; i < dimensions; i++) {
// javaType += "[]";
// }
//
// return javaType;
// }
//
// /**
// * 数组类型的基础类型。
// *
// * @param type
// * @return
// */
// public static String toArrayTypeSimple(String type) {
// int index = 0;
// for (char c : type.toCharArray()) {
// if ('[' == c) {
// index++;
// } else {
// break;
// }
// }
//
// String arrayType;
// char ch = type.charAt(index);
// if ('L' == ch) {
// arrayType = type.substring(index + 1, type.lastIndexOf(';')).replace('/', '.');
// } else {
// switch (ch) {
// case 'Z':
// arrayType = "boolean";
// break;
// case 'B':
// arrayType = "byte";
// break;
// case 'S':
// arrayType = "short";
// break;
// case 'C':
// arrayType = "char";
// break;
// case 'I':
// arrayType = "int";
// break;
// case 'J':
// arrayType = "long";
// break;
// case 'F':
// arrayType = "float";
// break;
// case 'D':
// arrayType = "double";
// break;
// default:
// arrayType = null;
// break;
// }
// }
// return arrayType;
// }
//
// /**
// * 生成方法参数列表。
// *
// * @param params
// * @return 返回方法参数列表。
// */
// public static List<String> getTypeList(String params) {
// List<String> types = new ArrayList<String>();
// int length = params.length();
//
// for (int i = 0; i < length; ) {
// String type;
// char ch = params.charAt(i);
// if ('L' == ch) {
// int end = params.indexOf(';', i) + 1;
// type = params.substring(i, end);
// i = end;
// } else if ('[' == ch) {
// int end;
// for (end = i + 1; end < length; end++) {
// char c = params.charAt(end);
// if ('[' == c) {
// continue;
// }
// if ('L' == c) {
// end = params.indexOf(';', end) + 1;
// break;
// }
// end += 1;
// break;
// }
// type = params.substring(i, end);
// i = end;
// } else {
// type = "" + ch;
// i++;
// }
// types.add(getJavaType(type));
// }
// return types;
// }
//
// }
// Path: src/main/java/buwai/android/smaliinstruction/SmaliInstruction04.java
import buwai.android.smali2java.Utils;
package buwai.android.smaliinstruction;
/**
*
1c. const-class vAA, type@BBBB -> <类>.class
*
* @author buwai
*
*/
public class SmaliInstruction04 {
public static String toJava(int id, String smaliInst) {
int beginIndex, endIndex;
beginIndex = smaliInst.indexOf(' ');
endIndex = smaliInst.indexOf(',', beginIndex + 1);
String vA = smaliInst.substring(beginIndex, endIndex).trim();
// endIndex + 1表示跳过逗号。 | String className = Utils.getJavaType(smaliInst.substring(endIndex + 1).trim()); |
zylc369/smali2java | src/main/java/buwai/android/smaliinstruction/SmaliInstruction07.java | // Path: src/main/java/buwai/android/smali2java/Utils.java
// public class Utils {
//
// /**
// * 将smali类型转换为Java的表示形式。
// *
// * @param type
// * @return
// */
// public static String getJavaType(String smaliType) {
// char ch;
// ch = smaliType.charAt(0);
// String javaType;
//
// int index = 0;
// int dimensions = 0;
//
// if ('L' == ch) {
// return smaliType.substring(1, smaliType.lastIndexOf(';')).replace('/', '.');
// } else if ('[' == ch) { // 处理数组的情况。
// for (char c : smaliType.toCharArray()) {
// if ('[' == c) {
// dimensions++;
// index++;
// } else {
// break;
// }
// }
// }
//
// ch = smaliType.charAt(index);
// if ('L' == ch) {
// javaType = smaliType.substring(index + 1, smaliType.lastIndexOf(';')).replace('/', '.');
// } else {
// switch (ch) {
// case 'V':
// javaType = "void";
// break;
// case 'Z':
// javaType = "boolean";
// break;
// case 'B':
// javaType = "byte";
// break;
// case 'S':
// javaType = "short";
// break;
// case 'C':
// javaType = "char";
// break;
// case 'I':
// javaType = "int";
// break;
// case 'J':
// javaType = "long";
// break;
// case 'F':
// javaType = "float";
// break;
// case 'D':
// javaType = "double";
// break;
// default:
// javaType = null;
// break;
// }
// }
//
// for (int i = 0; i < dimensions; i++) {
// javaType += "[]";
// }
//
// return javaType;
// }
//
// /**
// * 数组类型的基础类型。
// *
// * @param type
// * @return
// */
// public static String toArrayTypeSimple(String type) {
// int index = 0;
// for (char c : type.toCharArray()) {
// if ('[' == c) {
// index++;
// } else {
// break;
// }
// }
//
// String arrayType;
// char ch = type.charAt(index);
// if ('L' == ch) {
// arrayType = type.substring(index + 1, type.lastIndexOf(';')).replace('/', '.');
// } else {
// switch (ch) {
// case 'Z':
// arrayType = "boolean";
// break;
// case 'B':
// arrayType = "byte";
// break;
// case 'S':
// arrayType = "short";
// break;
// case 'C':
// arrayType = "char";
// break;
// case 'I':
// arrayType = "int";
// break;
// case 'J':
// arrayType = "long";
// break;
// case 'F':
// arrayType = "float";
// break;
// case 'D':
// arrayType = "double";
// break;
// default:
// arrayType = null;
// break;
// }
// }
// return arrayType;
// }
//
// /**
// * 生成方法参数列表。
// *
// * @param params
// * @return 返回方法参数列表。
// */
// public static List<String> getTypeList(String params) {
// List<String> types = new ArrayList<String>();
// int length = params.length();
//
// for (int i = 0; i < length; ) {
// String type;
// char ch = params.charAt(i);
// if ('L' == ch) {
// int end = params.indexOf(';', i) + 1;
// type = params.substring(i, end);
// i = end;
// } else if ('[' == ch) {
// int end;
// for (end = i + 1; end < length; end++) {
// char c = params.charAt(end);
// if ('[' == c) {
// continue;
// }
// if ('L' == c) {
// end = params.indexOf(';', end) + 1;
// break;
// }
// end += 1;
// break;
// }
// type = params.substring(i, end);
// i = end;
// } else {
// type = "" + ch;
// i++;
// }
// types.add(getJavaType(type));
// }
// return types;
// }
//
// }
| import buwai.android.smali2java.Utils; | package buwai.android.smaliinstruction;
/**
*
类型转换
1f. check-cast vAA, type@BBBB -> (类型)vA;
*
* @author buwai
*
*/
public class SmaliInstruction07 {
public static String toJava(int id, String smaliInst) {
int beginIndex, endIndex;
beginIndex = smaliInst.indexOf(' ');
endIndex = smaliInst.indexOf(',', beginIndex + 1);
String vA = smaliInst.substring(beginIndex, endIndex).trim();
// endIndex + 1表示跳过逗号。 | // Path: src/main/java/buwai/android/smali2java/Utils.java
// public class Utils {
//
// /**
// * 将smali类型转换为Java的表示形式。
// *
// * @param type
// * @return
// */
// public static String getJavaType(String smaliType) {
// char ch;
// ch = smaliType.charAt(0);
// String javaType;
//
// int index = 0;
// int dimensions = 0;
//
// if ('L' == ch) {
// return smaliType.substring(1, smaliType.lastIndexOf(';')).replace('/', '.');
// } else if ('[' == ch) { // 处理数组的情况。
// for (char c : smaliType.toCharArray()) {
// if ('[' == c) {
// dimensions++;
// index++;
// } else {
// break;
// }
// }
// }
//
// ch = smaliType.charAt(index);
// if ('L' == ch) {
// javaType = smaliType.substring(index + 1, smaliType.lastIndexOf(';')).replace('/', '.');
// } else {
// switch (ch) {
// case 'V':
// javaType = "void";
// break;
// case 'Z':
// javaType = "boolean";
// break;
// case 'B':
// javaType = "byte";
// break;
// case 'S':
// javaType = "short";
// break;
// case 'C':
// javaType = "char";
// break;
// case 'I':
// javaType = "int";
// break;
// case 'J':
// javaType = "long";
// break;
// case 'F':
// javaType = "float";
// break;
// case 'D':
// javaType = "double";
// break;
// default:
// javaType = null;
// break;
// }
// }
//
// for (int i = 0; i < dimensions; i++) {
// javaType += "[]";
// }
//
// return javaType;
// }
//
// /**
// * 数组类型的基础类型。
// *
// * @param type
// * @return
// */
// public static String toArrayTypeSimple(String type) {
// int index = 0;
// for (char c : type.toCharArray()) {
// if ('[' == c) {
// index++;
// } else {
// break;
// }
// }
//
// String arrayType;
// char ch = type.charAt(index);
// if ('L' == ch) {
// arrayType = type.substring(index + 1, type.lastIndexOf(';')).replace('/', '.');
// } else {
// switch (ch) {
// case 'Z':
// arrayType = "boolean";
// break;
// case 'B':
// arrayType = "byte";
// break;
// case 'S':
// arrayType = "short";
// break;
// case 'C':
// arrayType = "char";
// break;
// case 'I':
// arrayType = "int";
// break;
// case 'J':
// arrayType = "long";
// break;
// case 'F':
// arrayType = "float";
// break;
// case 'D':
// arrayType = "double";
// break;
// default:
// arrayType = null;
// break;
// }
// }
// return arrayType;
// }
//
// /**
// * 生成方法参数列表。
// *
// * @param params
// * @return 返回方法参数列表。
// */
// public static List<String> getTypeList(String params) {
// List<String> types = new ArrayList<String>();
// int length = params.length();
//
// for (int i = 0; i < length; ) {
// String type;
// char ch = params.charAt(i);
// if ('L' == ch) {
// int end = params.indexOf(';', i) + 1;
// type = params.substring(i, end);
// i = end;
// } else if ('[' == ch) {
// int end;
// for (end = i + 1; end < length; end++) {
// char c = params.charAt(end);
// if ('[' == c) {
// continue;
// }
// if ('L' == c) {
// end = params.indexOf(';', end) + 1;
// break;
// }
// end += 1;
// break;
// }
// type = params.substring(i, end);
// i = end;
// } else {
// type = "" + ch;
// i++;
// }
// types.add(getJavaType(type));
// }
// return types;
// }
//
// }
// Path: src/main/java/buwai/android/smaliinstruction/SmaliInstruction07.java
import buwai.android.smali2java.Utils;
package buwai.android.smaliinstruction;
/**
*
类型转换
1f. check-cast vAA, type@BBBB -> (类型)vA;
*
* @author buwai
*
*/
public class SmaliInstruction07 {
public static String toJava(int id, String smaliInst) {
int beginIndex, endIndex;
beginIndex = smaliInst.indexOf(' ');
endIndex = smaliInst.indexOf(',', beginIndex + 1);
String vA = smaliInst.substring(beginIndex, endIndex).trim();
// endIndex + 1表示跳过逗号。 | String className = Utils.getJavaType(smaliInst.substring(endIndex + 1).trim()); |
zylc369/smali2java | src/main/java/buwai/android/smaliinstruction/SmaliInstruction23.java | // Path: src/main/java/buwai/android/smali2java/Utils.java
// public class Utils {
//
// /**
// * 将smali类型转换为Java的表示形式。
// *
// * @param type
// * @return
// */
// public static String getJavaType(String smaliType) {
// char ch;
// ch = smaliType.charAt(0);
// String javaType;
//
// int index = 0;
// int dimensions = 0;
//
// if ('L' == ch) {
// return smaliType.substring(1, smaliType.lastIndexOf(';')).replace('/', '.');
// } else if ('[' == ch) { // 处理数组的情况。
// for (char c : smaliType.toCharArray()) {
// if ('[' == c) {
// dimensions++;
// index++;
// } else {
// break;
// }
// }
// }
//
// ch = smaliType.charAt(index);
// if ('L' == ch) {
// javaType = smaliType.substring(index + 1, smaliType.lastIndexOf(';')).replace('/', '.');
// } else {
// switch (ch) {
// case 'V':
// javaType = "void";
// break;
// case 'Z':
// javaType = "boolean";
// break;
// case 'B':
// javaType = "byte";
// break;
// case 'S':
// javaType = "short";
// break;
// case 'C':
// javaType = "char";
// break;
// case 'I':
// javaType = "int";
// break;
// case 'J':
// javaType = "long";
// break;
// case 'F':
// javaType = "float";
// break;
// case 'D':
// javaType = "double";
// break;
// default:
// javaType = null;
// break;
// }
// }
//
// for (int i = 0; i < dimensions; i++) {
// javaType += "[]";
// }
//
// return javaType;
// }
//
// /**
// * 数组类型的基础类型。
// *
// * @param type
// * @return
// */
// public static String toArrayTypeSimple(String type) {
// int index = 0;
// for (char c : type.toCharArray()) {
// if ('[' == c) {
// index++;
// } else {
// break;
// }
// }
//
// String arrayType;
// char ch = type.charAt(index);
// if ('L' == ch) {
// arrayType = type.substring(index + 1, type.lastIndexOf(';')).replace('/', '.');
// } else {
// switch (ch) {
// case 'Z':
// arrayType = "boolean";
// break;
// case 'B':
// arrayType = "byte";
// break;
// case 'S':
// arrayType = "short";
// break;
// case 'C':
// arrayType = "char";
// break;
// case 'I':
// arrayType = "int";
// break;
// case 'J':
// arrayType = "long";
// break;
// case 'F':
// arrayType = "float";
// break;
// case 'D':
// arrayType = "double";
// break;
// default:
// arrayType = null;
// break;
// }
// }
// return arrayType;
// }
//
// /**
// * 生成方法参数列表。
// *
// * @param params
// * @return 返回方法参数列表。
// */
// public static List<String> getTypeList(String params) {
// List<String> types = new ArrayList<String>();
// int length = params.length();
//
// for (int i = 0; i < length; ) {
// String type;
// char ch = params.charAt(i);
// if ('L' == ch) {
// int end = params.indexOf(';', i) + 1;
// type = params.substring(i, end);
// i = end;
// } else if ('[' == ch) {
// int end;
// for (end = i + 1; end < length; end++) {
// char c = params.charAt(end);
// if ('[' == c) {
// continue;
// }
// if ('L' == c) {
// end = params.indexOf(';', end) + 1;
// break;
// }
// end += 1;
// break;
// }
// type = params.substring(i, end);
// i = end;
// } else {
// type = "" + ch;
// i++;
// }
// types.add(getJavaType(type));
// }
// return types;
// }
//
// }
| import buwai.android.smali2java.Utils; | package buwai.android.smaliinstruction;
/**
*
59: iput
5a: iput-wide
5b: iput-object
5c: iput-boolean
5d: iput-byte
5e: iput-char
5f: iput-short
* @author buwai
*
*/
public class SmaliInstruction23 {
public static String toJava(int id, String smaliInst) {
int beginIndex, endIndex;
beginIndex = smaliInst.indexOf(' ');
endIndex = smaliInst.indexOf(',', beginIndex + 1);
String vA = smaliInst.substring(beginIndex, endIndex).trim();
beginIndex = endIndex + 1;
endIndex = smaliInst.indexOf(',', beginIndex + 1);
String vB = smaliInst.substring(beginIndex, endIndex).trim();
beginIndex = smaliInst.lastIndexOf(',') + 1;
endIndex = smaliInst.lastIndexOf("->"); | // Path: src/main/java/buwai/android/smali2java/Utils.java
// public class Utils {
//
// /**
// * 将smali类型转换为Java的表示形式。
// *
// * @param type
// * @return
// */
// public static String getJavaType(String smaliType) {
// char ch;
// ch = smaliType.charAt(0);
// String javaType;
//
// int index = 0;
// int dimensions = 0;
//
// if ('L' == ch) {
// return smaliType.substring(1, smaliType.lastIndexOf(';')).replace('/', '.');
// } else if ('[' == ch) { // 处理数组的情况。
// for (char c : smaliType.toCharArray()) {
// if ('[' == c) {
// dimensions++;
// index++;
// } else {
// break;
// }
// }
// }
//
// ch = smaliType.charAt(index);
// if ('L' == ch) {
// javaType = smaliType.substring(index + 1, smaliType.lastIndexOf(';')).replace('/', '.');
// } else {
// switch (ch) {
// case 'V':
// javaType = "void";
// break;
// case 'Z':
// javaType = "boolean";
// break;
// case 'B':
// javaType = "byte";
// break;
// case 'S':
// javaType = "short";
// break;
// case 'C':
// javaType = "char";
// break;
// case 'I':
// javaType = "int";
// break;
// case 'J':
// javaType = "long";
// break;
// case 'F':
// javaType = "float";
// break;
// case 'D':
// javaType = "double";
// break;
// default:
// javaType = null;
// break;
// }
// }
//
// for (int i = 0; i < dimensions; i++) {
// javaType += "[]";
// }
//
// return javaType;
// }
//
// /**
// * 数组类型的基础类型。
// *
// * @param type
// * @return
// */
// public static String toArrayTypeSimple(String type) {
// int index = 0;
// for (char c : type.toCharArray()) {
// if ('[' == c) {
// index++;
// } else {
// break;
// }
// }
//
// String arrayType;
// char ch = type.charAt(index);
// if ('L' == ch) {
// arrayType = type.substring(index + 1, type.lastIndexOf(';')).replace('/', '.');
// } else {
// switch (ch) {
// case 'Z':
// arrayType = "boolean";
// break;
// case 'B':
// arrayType = "byte";
// break;
// case 'S':
// arrayType = "short";
// break;
// case 'C':
// arrayType = "char";
// break;
// case 'I':
// arrayType = "int";
// break;
// case 'J':
// arrayType = "long";
// break;
// case 'F':
// arrayType = "float";
// break;
// case 'D':
// arrayType = "double";
// break;
// default:
// arrayType = null;
// break;
// }
// }
// return arrayType;
// }
//
// /**
// * 生成方法参数列表。
// *
// * @param params
// * @return 返回方法参数列表。
// */
// public static List<String> getTypeList(String params) {
// List<String> types = new ArrayList<String>();
// int length = params.length();
//
// for (int i = 0; i < length; ) {
// String type;
// char ch = params.charAt(i);
// if ('L' == ch) {
// int end = params.indexOf(';', i) + 1;
// type = params.substring(i, end);
// i = end;
// } else if ('[' == ch) {
// int end;
// for (end = i + 1; end < length; end++) {
// char c = params.charAt(end);
// if ('[' == c) {
// continue;
// }
// if ('L' == c) {
// end = params.indexOf(';', end) + 1;
// break;
// }
// end += 1;
// break;
// }
// type = params.substring(i, end);
// i = end;
// } else {
// type = "" + ch;
// i++;
// }
// types.add(getJavaType(type));
// }
// return types;
// }
//
// }
// Path: src/main/java/buwai/android/smaliinstruction/SmaliInstruction23.java
import buwai.android.smali2java.Utils;
package buwai.android.smaliinstruction;
/**
*
59: iput
5a: iput-wide
5b: iput-object
5c: iput-boolean
5d: iput-byte
5e: iput-char
5f: iput-short
* @author buwai
*
*/
public class SmaliInstruction23 {
public static String toJava(int id, String smaliInst) {
int beginIndex, endIndex;
beginIndex = smaliInst.indexOf(' ');
endIndex = smaliInst.indexOf(',', beginIndex + 1);
String vA = smaliInst.substring(beginIndex, endIndex).trim();
beginIndex = endIndex + 1;
endIndex = smaliInst.indexOf(',', beginIndex + 1);
String vB = smaliInst.substring(beginIndex, endIndex).trim();
beginIndex = smaliInst.lastIndexOf(',') + 1;
endIndex = smaliInst.lastIndexOf("->"); | String instanceName = Utils.getJavaType(smaliInst.substring(beginIndex, endIndex).trim()); |
blockchain/api-v1-client-java | src/main/java/info/blockchain/api/statistics/Statistics.java | // Path: src/main/java/info/blockchain/api/APIException.java
// public class APIException extends Exception {
// private static final long serialVersionUID = -7731961787745059713L;
//
// public APIException (String message) {
// super(message);
// }
// }
//
// Path: src/main/java/info/blockchain/api/HttpClient.java
// public class HttpClient implements HttpClientInterface {
// private static final String BASE_URL = "https://blockchain.info/";
//
// public volatile static int TIMEOUT_MS = 10000;
//
// private static HttpClientInterface instance;
//
// public synchronized static HttpClientInterface getInstance () {
// if (instance == null) {
// // Thread Safe. Might be costly operation in some case
// synchronized (HttpClient.class) {
// if (instance == null) {
// instance = new HttpClient();
// }
// }
// }
// return instance;
// }
//
// public static void setCustomHttpClient (HttpClientInterface httpClient) {
// instance = httpClient;
// }
//
// /**
// * Perform a GET request on a Blockchain.info API resource.
// *
// * @param resource Resource path after https://blockchain.info/api/
// * @param params Map containing request parameters
// * @return String response
// * @throws APIException If the server returns an error
// */
// public String get (String resource, Map<String, String> params) throws APIException, IOException {
// return openURL(BASE_URL, resource, params, "GET");
// }
//
// public String get (String baseURL, String resource, Map<String, String> params) throws APIException, IOException {
// return openURL(baseURL, resource, params, "GET");
// }
//
// /**
// * Perform a POST request on a Blockchain.info API resource.
// *
// * @param resource Resource path after https://blockchain.info/api/
// * @param params Map containing request parameters
// * @return String response
// * @throws APIException If the server returns an error
// * @throws IOException If the server is not reachable
// */
// public String post (String resource, Map<String, String> params) throws APIException, IOException {
// return openURL(BASE_URL, resource, params, "POST");
// }
//
// public String post (String baseURL, String resource, Map<String, String> params) throws APIException, IOException {
// return openURL(baseURL, resource, params, "POST");
// }
//
// private static String openURL (String baseURL, String resource, Map<String, String> params, String requestMethod) throws APIException, IOException {
// String encodedParams = urlEncodeParams(params);
// URL url = null;
// APIException apiException = null;
// IOException ioException = null;
//
// String responseStr = null;
//
// if (requestMethod.equals("GET")) {
// if (encodedParams.isEmpty()) {
// url = new URL(baseURL + resource);
// } else {
// url = new URL(baseURL + resource + '?' + encodedParams);
// }
// } else if (requestMethod.equals("POST")) {
// url = new URL(baseURL + resource);
// }
//
// HttpURLConnection conn = null;
//
// try {
// conn = (HttpURLConnection) url.openConnection();
// conn.setRequestMethod(requestMethod);
// conn.setConnectTimeout(TIMEOUT_MS);
//
// if (requestMethod.equals("POST")) {
// byte[] postBytes = encodedParams.getBytes("UTF-8");
// conn.setDoOutput(true);
// conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
// conn.setRequestProperty("Content-Length", String.valueOf(postBytes.length));
// conn.getOutputStream().write(postBytes);
// conn.getOutputStream().close();
// }
//
// if (conn.getResponseCode() != 200) {
// apiException = new APIException(inputStreamToString(conn.getErrorStream()));
// } else {
// responseStr = inputStreamToString(conn.getInputStream());
// }
// } catch (IOException e) {
// ioException = e;
// } finally {
// try {
// if (apiException != null) {
// conn.getErrorStream().close();
// }
// conn.getInputStream().close();
// } catch (Exception ex) {
// }
//
// if (ioException != null) {
// throw ioException;
// }
//
// if (apiException != null) {
// throw apiException;
// }
// }
//
// return responseStr;
// }
//
// private static String urlEncodeParams (Map<String, String> params) {
// String result = "";
//
// if (params != null && params.size() > 0) {
// try {
// StringBuilder data = new StringBuilder();
// for (Entry<String, String> kvp : params.entrySet()) {
// if (data.length() > 0) {
// data.append('&');
// }
//
// data.append(URLEncoder.encode(kvp.getKey(), "UTF-8"));
// data.append('=');
// data.append(URLEncoder.encode(kvp.getValue(), "UTF-8"));
// }
// result = data.toString();
// } catch (UnsupportedEncodingException e) {
// }
// }
//
// return result;
// }
//
// private static String inputStreamToString (InputStream is) throws IOException {
// BufferedReader reader = new BufferedReader(new InputStreamReader(is));
//
// StringBuilder responseStringBuilder = new StringBuilder();
// String line = "";
//
// while ((line = reader.readLine()) != null) {
// responseStringBuilder.append(line);
// }
//
// reader.close();
//
// return responseStringBuilder.toString();
// }
// }
| import com.google.gson.Gson;
import com.google.gson.JsonObject;
import com.google.gson.JsonParser;
import com.google.gson.reflect.TypeToken;
import info.blockchain.api.APIException;
import info.blockchain.api.HttpClient;
import java.io.IOException;
import java.lang.reflect.Type;
import java.util.HashMap;
import java.util.Map; | package info.blockchain.api.statistics;
/**
* This class reflects the functionality documented
* at https://blockchain.info/api/charts_api
*/
public class Statistics {
private final String apiCode;
public Statistics () {
this(null);
}
public Statistics (String apiCode) {
this.apiCode = apiCode;
}
/**
* Gets the network statistics.
*
* @return An instance of the StatisticsResponse class
* @throws APIException If the server returns an error
*/ | // Path: src/main/java/info/blockchain/api/APIException.java
// public class APIException extends Exception {
// private static final long serialVersionUID = -7731961787745059713L;
//
// public APIException (String message) {
// super(message);
// }
// }
//
// Path: src/main/java/info/blockchain/api/HttpClient.java
// public class HttpClient implements HttpClientInterface {
// private static final String BASE_URL = "https://blockchain.info/";
//
// public volatile static int TIMEOUT_MS = 10000;
//
// private static HttpClientInterface instance;
//
// public synchronized static HttpClientInterface getInstance () {
// if (instance == null) {
// // Thread Safe. Might be costly operation in some case
// synchronized (HttpClient.class) {
// if (instance == null) {
// instance = new HttpClient();
// }
// }
// }
// return instance;
// }
//
// public static void setCustomHttpClient (HttpClientInterface httpClient) {
// instance = httpClient;
// }
//
// /**
// * Perform a GET request on a Blockchain.info API resource.
// *
// * @param resource Resource path after https://blockchain.info/api/
// * @param params Map containing request parameters
// * @return String response
// * @throws APIException If the server returns an error
// */
// public String get (String resource, Map<String, String> params) throws APIException, IOException {
// return openURL(BASE_URL, resource, params, "GET");
// }
//
// public String get (String baseURL, String resource, Map<String, String> params) throws APIException, IOException {
// return openURL(baseURL, resource, params, "GET");
// }
//
// /**
// * Perform a POST request on a Blockchain.info API resource.
// *
// * @param resource Resource path after https://blockchain.info/api/
// * @param params Map containing request parameters
// * @return String response
// * @throws APIException If the server returns an error
// * @throws IOException If the server is not reachable
// */
// public String post (String resource, Map<String, String> params) throws APIException, IOException {
// return openURL(BASE_URL, resource, params, "POST");
// }
//
// public String post (String baseURL, String resource, Map<String, String> params) throws APIException, IOException {
// return openURL(baseURL, resource, params, "POST");
// }
//
// private static String openURL (String baseURL, String resource, Map<String, String> params, String requestMethod) throws APIException, IOException {
// String encodedParams = urlEncodeParams(params);
// URL url = null;
// APIException apiException = null;
// IOException ioException = null;
//
// String responseStr = null;
//
// if (requestMethod.equals("GET")) {
// if (encodedParams.isEmpty()) {
// url = new URL(baseURL + resource);
// } else {
// url = new URL(baseURL + resource + '?' + encodedParams);
// }
// } else if (requestMethod.equals("POST")) {
// url = new URL(baseURL + resource);
// }
//
// HttpURLConnection conn = null;
//
// try {
// conn = (HttpURLConnection) url.openConnection();
// conn.setRequestMethod(requestMethod);
// conn.setConnectTimeout(TIMEOUT_MS);
//
// if (requestMethod.equals("POST")) {
// byte[] postBytes = encodedParams.getBytes("UTF-8");
// conn.setDoOutput(true);
// conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
// conn.setRequestProperty("Content-Length", String.valueOf(postBytes.length));
// conn.getOutputStream().write(postBytes);
// conn.getOutputStream().close();
// }
//
// if (conn.getResponseCode() != 200) {
// apiException = new APIException(inputStreamToString(conn.getErrorStream()));
// } else {
// responseStr = inputStreamToString(conn.getInputStream());
// }
// } catch (IOException e) {
// ioException = e;
// } finally {
// try {
// if (apiException != null) {
// conn.getErrorStream().close();
// }
// conn.getInputStream().close();
// } catch (Exception ex) {
// }
//
// if (ioException != null) {
// throw ioException;
// }
//
// if (apiException != null) {
// throw apiException;
// }
// }
//
// return responseStr;
// }
//
// private static String urlEncodeParams (Map<String, String> params) {
// String result = "";
//
// if (params != null && params.size() > 0) {
// try {
// StringBuilder data = new StringBuilder();
// for (Entry<String, String> kvp : params.entrySet()) {
// if (data.length() > 0) {
// data.append('&');
// }
//
// data.append(URLEncoder.encode(kvp.getKey(), "UTF-8"));
// data.append('=');
// data.append(URLEncoder.encode(kvp.getValue(), "UTF-8"));
// }
// result = data.toString();
// } catch (UnsupportedEncodingException e) {
// }
// }
//
// return result;
// }
//
// private static String inputStreamToString (InputStream is) throws IOException {
// BufferedReader reader = new BufferedReader(new InputStreamReader(is));
//
// StringBuilder responseStringBuilder = new StringBuilder();
// String line = "";
//
// while ((line = reader.readLine()) != null) {
// responseStringBuilder.append(line);
// }
//
// reader.close();
//
// return responseStringBuilder.toString();
// }
// }
// Path: src/main/java/info/blockchain/api/statistics/Statistics.java
import com.google.gson.Gson;
import com.google.gson.JsonObject;
import com.google.gson.JsonParser;
import com.google.gson.reflect.TypeToken;
import info.blockchain.api.APIException;
import info.blockchain.api.HttpClient;
import java.io.IOException;
import java.lang.reflect.Type;
import java.util.HashMap;
import java.util.Map;
package info.blockchain.api.statistics;
/**
* This class reflects the functionality documented
* at https://blockchain.info/api/charts_api
*/
public class Statistics {
private final String apiCode;
public Statistics () {
this(null);
}
public Statistics (String apiCode) {
this.apiCode = apiCode;
}
/**
* Gets the network statistics.
*
* @return An instance of the StatisticsResponse class
* @throws APIException If the server returns an error
*/ | public StatisticsResponse getStats () throws APIException, IOException { |
litongbupt/iframework | src/main/java/com/bupt/core/security/filter/MyUsernamePasswordAuthenticationFilter.java | // Path: src/main/java/com/bupt/core/security/service/AuthService.java
// public interface AuthService {
// boolean validate(String username,String password);
// }
| 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 org.springframework.security.authentication.AuthenticationServiceException;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;
import com.bupt.core.security.service.AuthService; | package com.bupt.core.security.filter;
/*
*
* UsernamePasswordAuthenticationFilter源码
attemptAuthentication
this.getAuthenticationManager()
ProviderManager.java
authenticate(UsernamePasswordAuthenticationToken authRequest)
AbstractUserDetailsAuthenticationProvider.java
authenticate(Authentication authentication)
P155 user = retrieveUser(username, (UsernamePasswordAuthenticationToken) authentication);
DaoAuthenticationProvider.java
P86 loadUserByUsername
*/
public class MyUsernamePasswordAuthenticationFilter extends UsernamePasswordAuthenticationFilter{
public static final String VALIDATE_CODE = "validateCode";
public static final String USERNAME = "username";
public static final String PASSWORD = "password";
private final Log log = LogFactory.getLog(getClass());
private boolean debug = log.isDebugEnabled(); | // Path: src/main/java/com/bupt/core/security/service/AuthService.java
// public interface AuthService {
// boolean validate(String username,String password);
// }
// Path: src/main/java/com/bupt/core/security/filter/MyUsernamePasswordAuthenticationFilter.java
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 org.springframework.security.authentication.AuthenticationServiceException;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;
import com.bupt.core.security.service.AuthService;
package com.bupt.core.security.filter;
/*
*
* UsernamePasswordAuthenticationFilter源码
attemptAuthentication
this.getAuthenticationManager()
ProviderManager.java
authenticate(UsernamePasswordAuthenticationToken authRequest)
AbstractUserDetailsAuthenticationProvider.java
authenticate(Authentication authentication)
P155 user = retrieveUser(username, (UsernamePasswordAuthenticationToken) authentication);
DaoAuthenticationProvider.java
P86 loadUserByUsername
*/
public class MyUsernamePasswordAuthenticationFilter extends UsernamePasswordAuthenticationFilter{
public static final String VALIDATE_CODE = "validateCode";
public static final String USERNAME = "username";
public static final String PASSWORD = "password";
private final Log log = LogFactory.getLog(getClass());
private boolean debug = log.isDebugEnabled(); | private AuthService authService; |
litongbupt/iframework | src/main/java/com/bupt/core/security/action/AuthAction.java | // Path: src/main/java/com/bupt/core/security/dao/CourseMapper.java
// public interface CourseMapper {
// List<Course> getCourseList();
// }
//
// Path: src/main/java/com/bupt/core/security/model/Course.java
// public class Course {
// private String id;
// private String name;
// private String num;
// private String p_id;
// private String type;
// public String getId() {
// return id;
// }
// public void setId(String id) {
// this.id = id;
// }
// public String getName() {
// return name;
// }
// public void setName(String name) {
// this.name = name;
// }
// public String getNum() {
// return num;
// }
// public void setNum(String num) {
// this.num = num;
// }
// public String getP_id() {
// return p_id;
// }
// public void setP_id(String p_id) {
// this.p_id = p_id;
// }
// public String getType() {
// return type;
// }
// public void setType(String type) {
// this.type = type;
// }
//
// }
//
// Path: src/main/java/com/bupt/core/security/service/AuthService.java
// public interface AuthService {
// boolean validate(String username,String password);
// }
| import java.util.List;
import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import com.bupt.core.security.dao.CourseMapper;
import com.bupt.core.security.model.Course;
import com.bupt.core.security.service.AuthService; | package com.bupt.core.security.action;
@Controller
@RequestMapping("/auth")
public class AuthAction {
//将spring 配置文件中的bean 通过setter注入进来
@Resource(name="authService") | // Path: src/main/java/com/bupt/core/security/dao/CourseMapper.java
// public interface CourseMapper {
// List<Course> getCourseList();
// }
//
// Path: src/main/java/com/bupt/core/security/model/Course.java
// public class Course {
// private String id;
// private String name;
// private String num;
// private String p_id;
// private String type;
// public String getId() {
// return id;
// }
// public void setId(String id) {
// this.id = id;
// }
// public String getName() {
// return name;
// }
// public void setName(String name) {
// this.name = name;
// }
// public String getNum() {
// return num;
// }
// public void setNum(String num) {
// this.num = num;
// }
// public String getP_id() {
// return p_id;
// }
// public void setP_id(String p_id) {
// this.p_id = p_id;
// }
// public String getType() {
// return type;
// }
// public void setType(String type) {
// this.type = type;
// }
//
// }
//
// Path: src/main/java/com/bupt/core/security/service/AuthService.java
// public interface AuthService {
// boolean validate(String username,String password);
// }
// Path: src/main/java/com/bupt/core/security/action/AuthAction.java
import java.util.List;
import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import com.bupt.core.security.dao.CourseMapper;
import com.bupt.core.security.model.Course;
import com.bupt.core.security.service.AuthService;
package com.bupt.core.security.action;
@Controller
@RequestMapping("/auth")
public class AuthAction {
//将spring 配置文件中的bean 通过setter注入进来
@Resource(name="authService") | private AuthService authService=null; |
litongbupt/iframework | src/main/java/com/bupt/core/security/action/AuthAction.java | // Path: src/main/java/com/bupt/core/security/dao/CourseMapper.java
// public interface CourseMapper {
// List<Course> getCourseList();
// }
//
// Path: src/main/java/com/bupt/core/security/model/Course.java
// public class Course {
// private String id;
// private String name;
// private String num;
// private String p_id;
// private String type;
// public String getId() {
// return id;
// }
// public void setId(String id) {
// this.id = id;
// }
// public String getName() {
// return name;
// }
// public void setName(String name) {
// this.name = name;
// }
// public String getNum() {
// return num;
// }
// public void setNum(String num) {
// this.num = num;
// }
// public String getP_id() {
// return p_id;
// }
// public void setP_id(String p_id) {
// this.p_id = p_id;
// }
// public String getType() {
// return type;
// }
// public void setType(String type) {
// this.type = type;
// }
//
// }
//
// Path: src/main/java/com/bupt/core/security/service/AuthService.java
// public interface AuthService {
// boolean validate(String username,String password);
// }
| import java.util.List;
import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import com.bupt.core.security.dao.CourseMapper;
import com.bupt.core.security.model.Course;
import com.bupt.core.security.service.AuthService; | package com.bupt.core.security.action;
@Controller
@RequestMapping("/auth")
public class AuthAction {
//将spring 配置文件中的bean 通过setter注入进来
@Resource(name="authService")
private AuthService authService=null;
@Resource(name="courseMapper") | // Path: src/main/java/com/bupt/core/security/dao/CourseMapper.java
// public interface CourseMapper {
// List<Course> getCourseList();
// }
//
// Path: src/main/java/com/bupt/core/security/model/Course.java
// public class Course {
// private String id;
// private String name;
// private String num;
// private String p_id;
// private String type;
// public String getId() {
// return id;
// }
// public void setId(String id) {
// this.id = id;
// }
// public String getName() {
// return name;
// }
// public void setName(String name) {
// this.name = name;
// }
// public String getNum() {
// return num;
// }
// public void setNum(String num) {
// this.num = num;
// }
// public String getP_id() {
// return p_id;
// }
// public void setP_id(String p_id) {
// this.p_id = p_id;
// }
// public String getType() {
// return type;
// }
// public void setType(String type) {
// this.type = type;
// }
//
// }
//
// Path: src/main/java/com/bupt/core/security/service/AuthService.java
// public interface AuthService {
// boolean validate(String username,String password);
// }
// Path: src/main/java/com/bupt/core/security/action/AuthAction.java
import java.util.List;
import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import com.bupt.core.security.dao.CourseMapper;
import com.bupt.core.security.model.Course;
import com.bupt.core.security.service.AuthService;
package com.bupt.core.security.action;
@Controller
@RequestMapping("/auth")
public class AuthAction {
//将spring 配置文件中的bean 通过setter注入进来
@Resource(name="authService")
private AuthService authService=null;
@Resource(name="courseMapper") | private CourseMapper courseMapper; |
litongbupt/iframework | src/main/java/com/bupt/core/security/action/AuthAction.java | // Path: src/main/java/com/bupt/core/security/dao/CourseMapper.java
// public interface CourseMapper {
// List<Course> getCourseList();
// }
//
// Path: src/main/java/com/bupt/core/security/model/Course.java
// public class Course {
// private String id;
// private String name;
// private String num;
// private String p_id;
// private String type;
// public String getId() {
// return id;
// }
// public void setId(String id) {
// this.id = id;
// }
// public String getName() {
// return name;
// }
// public void setName(String name) {
// this.name = name;
// }
// public String getNum() {
// return num;
// }
// public void setNum(String num) {
// this.num = num;
// }
// public String getP_id() {
// return p_id;
// }
// public void setP_id(String p_id) {
// this.p_id = p_id;
// }
// public String getType() {
// return type;
// }
// public void setType(String type) {
// this.type = type;
// }
//
// }
//
// Path: src/main/java/com/bupt/core/security/service/AuthService.java
// public interface AuthService {
// boolean validate(String username,String password);
// }
| import java.util.List;
import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import com.bupt.core.security.dao.CourseMapper;
import com.bupt.core.security.model.Course;
import com.bupt.core.security.service.AuthService; | package com.bupt.core.security.action;
@Controller
@RequestMapping("/auth")
public class AuthAction {
//将spring 配置文件中的bean 通过setter注入进来
@Resource(name="authService")
private AuthService authService=null;
@Resource(name="courseMapper")
private CourseMapper courseMapper;
private final Log log = LogFactory.getLog(getClass());
private boolean debug = log.isDebugEnabled();
@RequestMapping("/login.do")
public String login(HttpServletRequest request, ModelMap modelMap)
throws Exception {
String username = request.getParameter("username");
String password = request.getParameter("password");
System.out.println(username+password);
boolean flag= authService.validate(username, password);
if(debug){
log.debug("$$$$$$$$$$$$$$$$$$$$$you want to check the result.jsp+++++++++++++");
log.debug("$$$$$$$$$$$$$$$$$$$$$ ready to insert +++++++++++++");
log.debug("$$$$$$$$$$$$$$$$$$$$$ insert completed +++++++++++++");
log.debug(flag);
}
return "result";
}
//获取当前用户的信息
//UserDetails userDetails = (UserDetails) SecurityContextHolder.getContext().getAuthentication().getPrincipal();
//返回json对象示例
@RequestMapping("/courseWare_courseTreeList.do")
@ResponseBody | // Path: src/main/java/com/bupt/core/security/dao/CourseMapper.java
// public interface CourseMapper {
// List<Course> getCourseList();
// }
//
// Path: src/main/java/com/bupt/core/security/model/Course.java
// public class Course {
// private String id;
// private String name;
// private String num;
// private String p_id;
// private String type;
// public String getId() {
// return id;
// }
// public void setId(String id) {
// this.id = id;
// }
// public String getName() {
// return name;
// }
// public void setName(String name) {
// this.name = name;
// }
// public String getNum() {
// return num;
// }
// public void setNum(String num) {
// this.num = num;
// }
// public String getP_id() {
// return p_id;
// }
// public void setP_id(String p_id) {
// this.p_id = p_id;
// }
// public String getType() {
// return type;
// }
// public void setType(String type) {
// this.type = type;
// }
//
// }
//
// Path: src/main/java/com/bupt/core/security/service/AuthService.java
// public interface AuthService {
// boolean validate(String username,String password);
// }
// Path: src/main/java/com/bupt/core/security/action/AuthAction.java
import java.util.List;
import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import com.bupt.core.security.dao.CourseMapper;
import com.bupt.core.security.model.Course;
import com.bupt.core.security.service.AuthService;
package com.bupt.core.security.action;
@Controller
@RequestMapping("/auth")
public class AuthAction {
//将spring 配置文件中的bean 通过setter注入进来
@Resource(name="authService")
private AuthService authService=null;
@Resource(name="courseMapper")
private CourseMapper courseMapper;
private final Log log = LogFactory.getLog(getClass());
private boolean debug = log.isDebugEnabled();
@RequestMapping("/login.do")
public String login(HttpServletRequest request, ModelMap modelMap)
throws Exception {
String username = request.getParameter("username");
String password = request.getParameter("password");
System.out.println(username+password);
boolean flag= authService.validate(username, password);
if(debug){
log.debug("$$$$$$$$$$$$$$$$$$$$$you want to check the result.jsp+++++++++++++");
log.debug("$$$$$$$$$$$$$$$$$$$$$ ready to insert +++++++++++++");
log.debug("$$$$$$$$$$$$$$$$$$$$$ insert completed +++++++++++++");
log.debug(flag);
}
return "result";
}
//获取当前用户的信息
//UserDetails userDetails = (UserDetails) SecurityContextHolder.getContext().getAuthentication().getPrincipal();
//返回json对象示例
@RequestMapping("/courseWare_courseTreeList.do")
@ResponseBody | public List<Course> getCourseTreeList() |
litongbupt/iframework | src/main/java/com/bupt/core/system/dao/UserRoleMapper.java | // Path: src/main/java/com/bupt/core/system/model/UserRole.java
// public class UserRole {
// private int userId;
// private int roleId;
// public int getUserId() {
// return userId;
// }
// public void setUserId(int userId) {
// this.userId = userId;
// }
// public int getRoleId() {
// return roleId;
// }
// public void setRoleId(int roleId) {
// this.roleId = roleId;
// }
// }
| import java.util.List;
import com.bupt.core.system.model.Role;
import com.bupt.core.system.model.UserRole; | package com.bupt.core.system.dao;
public interface UserRoleMapper {
List<Role> getRolesForUserById(int id); | // Path: src/main/java/com/bupt/core/system/model/UserRole.java
// public class UserRole {
// private int userId;
// private int roleId;
// public int getUserId() {
// return userId;
// }
// public void setUserId(int userId) {
// this.userId = userId;
// }
// public int getRoleId() {
// return roleId;
// }
// public void setRoleId(int roleId) {
// this.roleId = roleId;
// }
// }
// Path: src/main/java/com/bupt/core/system/dao/UserRoleMapper.java
import java.util.List;
import com.bupt.core.system.model.Role;
import com.bupt.core.system.model.UserRole;
package com.bupt.core.system.dao;
public interface UserRoleMapper {
List<Role> getRolesForUserById(int id); | void insert(UserRole userRole); |
vclub/A-Native-TesterHome | app/src/main/java/com/testerhome/nativeandroid/views/AccountNotificationActivity.java | // Path: app/src/main/java/com/testerhome/nativeandroid/fragments/AccountNotificationFragment.java
// public class AccountNotificationFragment extends BaseFragment {
//
// @Bind(R.id.rv_topic_list)
// RecyclerView recyclerViewTopicList;
//
// @Bind(R.id.srl_refresh)
// SwipeRefreshLayout swipeRefreshLayout;
//
// private int mNextCursor = 0;
//
// private NotificationAdapter mAdatper;
//
//
// public static AccountNotificationFragment newInstance() {
// AccountNotificationFragment fragment = new AccountNotificationFragment();
// return fragment;
// }
//
// @Override
// protected int getLayoutRes() {
// return R.layout.fragment_topics;
// }
//
// @Override
// public void onActivityCreated(Bundle savedInstanceState) {
// super.onActivityCreated(savedInstanceState);
// if (mTesterHomeAccount == null){
// getUserInfo();
// }
// setupView();
//
//
// }
//
// private void setupView() {
// mAdatper = new NotificationAdapter(getActivity());
// mAdatper.setListener(new NotificationAdapter.EndlessListener() {
// @Override
// public void onListEnded() {
// if (mNextCursor > 0) {
// loadNotification();
// }
// }
// });
// swipeRefreshLayout.setColorSchemeResources(android.R.color.holo_blue_light, android.R.color.holo_red_light, android.R.color.holo_orange_light, android.R.color.holo_green_light);
// recyclerViewTopicList.setLayoutManager(new LinearLayoutManager(getActivity()));
// recyclerViewTopicList.addItemDecoration(new DividerItemDecoration(getActivity(),
// DividerItemDecoration.VERTICAL_LIST));
// recyclerViewTopicList.setAdapter(mAdatper);
//
// swipeRefreshLayout.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
// @Override
// public void onRefresh() {
// mNextCursor = 0;
// loadNotification();
// }
// });
//
// loadNotification();
// }
//
// private TesterUser mTesterHomeAccount;
//
// private void getUserInfo(){
// mTesterHomeAccount = TesterHomeAccountService.getInstance(getContext()).getActiveAccountInfo();
// }
//
//
// private void loadNotification() {
//
// TesterHomeApi.getInstance().getTopicsService().getNotifications(mTesterHomeAccount.getAccess_token(),
// mNextCursor * 20,
// new Callback<NotificationResponse>() {
// @Override
// public void success(NotificationResponse notificationResponse, Response response) {
//
// if (swipeRefreshLayout.isRefreshing()) {
// swipeRefreshLayout.setRefreshing(false);
// }
// if (notificationResponse.getNotifications().size() > 0) {
// if (mNextCursor == 0) {
// mAdatper.setItems(notificationResponse.getNotifications());
// } else {
// mAdatper.addItems(notificationResponse.getNotifications());
// }
// if (notificationResponse.getNotifications().size() == 20) {
// mNextCursor += 1;
// } else {
// mNextCursor = 0;
// }
//
// } else {
// mNextCursor = 0;
// }
// }
//
// @Override
// public void failure(RetrofitError error) {
// if (swipeRefreshLayout != null && swipeRefreshLayout.isRefreshing()) {
// swipeRefreshLayout.setRefreshing(false);
// }
// Log.e("demo", "failure() called with: " + "error = [" + error + "]"
// + error.getUrl());
// }
// });
// }
//
//
// }
//
// Path: app/src/main/java/com/testerhome/nativeandroid/views/base/BackBaseActivity.java
// public abstract class BackBaseActivity extends BaseActivity {
//
// @Override
// protected void setupToolbar() {
// super.setupToolbar();
// if (toolbar != null)
// toolbar.setNavigationIcon(R.drawable.abc_ic_ab_back_mtrl_am_alpha);
// }
//
// @Override
// public boolean onOptionsItemSelected(MenuItem item) {
// if (item.getItemId() == android.R.id.home){
// this.onBackPressed();
// }
// return super.onOptionsItemSelected(item);
// }
// }
| import android.os.Bundle;
import com.testerhome.nativeandroid.R;
import com.testerhome.nativeandroid.fragments.AccountNotificationFragment;
import com.testerhome.nativeandroid.views.base.BackBaseActivity; | package com.testerhome.nativeandroid.views;
/**
* Created by cvtpc on 2015/10/18.
*/
public class AccountNotificationActivity extends BackBaseActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_back_base);
setCustomTitle("我的通知");
setupView();
}
private void setupView() {
getSupportFragmentManager().beginTransaction().replace(R.id.container, | // Path: app/src/main/java/com/testerhome/nativeandroid/fragments/AccountNotificationFragment.java
// public class AccountNotificationFragment extends BaseFragment {
//
// @Bind(R.id.rv_topic_list)
// RecyclerView recyclerViewTopicList;
//
// @Bind(R.id.srl_refresh)
// SwipeRefreshLayout swipeRefreshLayout;
//
// private int mNextCursor = 0;
//
// private NotificationAdapter mAdatper;
//
//
// public static AccountNotificationFragment newInstance() {
// AccountNotificationFragment fragment = new AccountNotificationFragment();
// return fragment;
// }
//
// @Override
// protected int getLayoutRes() {
// return R.layout.fragment_topics;
// }
//
// @Override
// public void onActivityCreated(Bundle savedInstanceState) {
// super.onActivityCreated(savedInstanceState);
// if (mTesterHomeAccount == null){
// getUserInfo();
// }
// setupView();
//
//
// }
//
// private void setupView() {
// mAdatper = new NotificationAdapter(getActivity());
// mAdatper.setListener(new NotificationAdapter.EndlessListener() {
// @Override
// public void onListEnded() {
// if (mNextCursor > 0) {
// loadNotification();
// }
// }
// });
// swipeRefreshLayout.setColorSchemeResources(android.R.color.holo_blue_light, android.R.color.holo_red_light, android.R.color.holo_orange_light, android.R.color.holo_green_light);
// recyclerViewTopicList.setLayoutManager(new LinearLayoutManager(getActivity()));
// recyclerViewTopicList.addItemDecoration(new DividerItemDecoration(getActivity(),
// DividerItemDecoration.VERTICAL_LIST));
// recyclerViewTopicList.setAdapter(mAdatper);
//
// swipeRefreshLayout.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
// @Override
// public void onRefresh() {
// mNextCursor = 0;
// loadNotification();
// }
// });
//
// loadNotification();
// }
//
// private TesterUser mTesterHomeAccount;
//
// private void getUserInfo(){
// mTesterHomeAccount = TesterHomeAccountService.getInstance(getContext()).getActiveAccountInfo();
// }
//
//
// private void loadNotification() {
//
// TesterHomeApi.getInstance().getTopicsService().getNotifications(mTesterHomeAccount.getAccess_token(),
// mNextCursor * 20,
// new Callback<NotificationResponse>() {
// @Override
// public void success(NotificationResponse notificationResponse, Response response) {
//
// if (swipeRefreshLayout.isRefreshing()) {
// swipeRefreshLayout.setRefreshing(false);
// }
// if (notificationResponse.getNotifications().size() > 0) {
// if (mNextCursor == 0) {
// mAdatper.setItems(notificationResponse.getNotifications());
// } else {
// mAdatper.addItems(notificationResponse.getNotifications());
// }
// if (notificationResponse.getNotifications().size() == 20) {
// mNextCursor += 1;
// } else {
// mNextCursor = 0;
// }
//
// } else {
// mNextCursor = 0;
// }
// }
//
// @Override
// public void failure(RetrofitError error) {
// if (swipeRefreshLayout != null && swipeRefreshLayout.isRefreshing()) {
// swipeRefreshLayout.setRefreshing(false);
// }
// Log.e("demo", "failure() called with: " + "error = [" + error + "]"
// + error.getUrl());
// }
// });
// }
//
//
// }
//
// Path: app/src/main/java/com/testerhome/nativeandroid/views/base/BackBaseActivity.java
// public abstract class BackBaseActivity extends BaseActivity {
//
// @Override
// protected void setupToolbar() {
// super.setupToolbar();
// if (toolbar != null)
// toolbar.setNavigationIcon(R.drawable.abc_ic_ab_back_mtrl_am_alpha);
// }
//
// @Override
// public boolean onOptionsItemSelected(MenuItem item) {
// if (item.getItemId() == android.R.id.home){
// this.onBackPressed();
// }
// return super.onOptionsItemSelected(item);
// }
// }
// Path: app/src/main/java/com/testerhome/nativeandroid/views/AccountNotificationActivity.java
import android.os.Bundle;
import com.testerhome.nativeandroid.R;
import com.testerhome.nativeandroid.fragments.AccountNotificationFragment;
import com.testerhome.nativeandroid.views.base.BackBaseActivity;
package com.testerhome.nativeandroid.views;
/**
* Created by cvtpc on 2015/10/18.
*/
public class AccountNotificationActivity extends BackBaseActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_back_base);
setCustomTitle("我的通知");
setupView();
}
private void setupView() {
getSupportFragmentManager().beginTransaction().replace(R.id.container, | AccountNotificationFragment.newInstance()) |
vclub/A-Native-TesterHome | app/src/main/java/com/testerhome/nativeandroid/auth/TesterHomeAccountService.java | // Path: app/src/main/java/com/testerhome/nativeandroid/models/TesterUser.java
// public class TesterUser {
//
// private String id;
// private String login;
// private String name;
// private String avatar_url;
// private String location;
// private String website;
// private String github;
// private String email;
// private String company;
// private String access_token;
// private String tagline;
//
// public String getTagline() {
// return tagline;
// }
//
// public void setTagline(String tagline) {
// this.tagline = tagline;
// }
//
// public String getCompany() {
// return company;
// }
//
// public void setCompany(String company) {
// this.company = company;
// }
//
// public String getId() {
// return id;
// }
//
// public void setId(String id) {
// this.id = id;
// }
//
// public String getLogin() {
// return login;
// }
//
// public void setLogin(String login) {
// this.login = login;
// }
//
// public String getName() {
// return name;
// }
//
// public void setName(String name) {
// this.name = name;
// }
//
// public String getAvatar_url() {
// return avatar_url;
// }
//
// public void setAvatar_url(String avatar_url) {
// this.avatar_url = avatar_url;
// }
//
// public String getLocation() {
// return location;
// }
//
// public void setLocation(String location) {
// this.location = location;
// }
//
// public String getWebsite() {
// return website;
// }
//
// public void setWebsite(String website) {
// this.website = website;
// }
//
// public String getGithub() {
// return github;
// }
//
// public void setGithub(String github) {
// this.github = github;
// }
//
// public String getEmail() {
// return email;
// }
//
// public void setEmail(String email) {
// this.email = email;
// }
//
// public String getAccess_token() {
// return access_token;
// }
//
// public void setAccess_token(String access_token) {
// this.access_token = access_token;
// }
// }
//
// Path: app/src/main/java/com/testerhome/nativeandroid/utils/SharedPreferencesHelper.java
// public class SharedPreferencesHelper {
//
// private static final String APP_NAME = "com.testerhome.nativeandroid";
// public static SharedPreferencesHelper instance;
// protected Context mContext;
// protected SharedPreferences sharedPreferences;
//
//
// public SharedPreferencesHelper(Context context) {
// mContext = context;
// sharedPreferences = mContext.getSharedPreferences(APP_NAME, 0);
// }
//
// public static synchronized SharedPreferencesHelper getInstance(Context context) {
// if (null == instance)
// instance = new SharedPreferencesHelper(context.getApplicationContext());
// return instance;
// }
//
// public String getValue(String key) {
// return sharedPreferences.getString(key, "");
// }
//
// public Boolean getBoolValue(String key) {
// return sharedPreferences.getBoolean(key, false);
// }
//
// public Boolean getBoolean(String key, boolean defaultValue) {
// return sharedPreferences.getBoolean(key, defaultValue);
// }
//
// public int getIntValue(String key) {
// return sharedPreferences.getInt(key, 0);
// }
//
// public void setValue(String key, Boolean value) {
// SharedPreferences.Editor editor = sharedPreferences.edit();
// editor.putBoolean(key, value);
// editor.apply();
// }
//
// public void setValue(String key, String value) {
// SharedPreferences.Editor editor = sharedPreferences.edit();
// editor.putString(key, value);
// editor.apply();
// }
//
// public void setValue(String key, int value) {
// SharedPreferences.Editor editor = sharedPreferences.edit();
// editor.putInt(key, value);
// editor.apply();
// }
//
// public void remove(String key) {
// SharedPreferences.Editor editor = sharedPreferences.edit();
// editor.remove(key);
// editor.apply();
// }
//
// public void clear() {
// SharedPreferences.Editor editor = sharedPreferences.edit();
// editor.clear();
// editor.apply();
// }
//
// public Set<String> getSaveKeys() {
// return sharedPreferences.getAll().keySet();
// }
// }
| import android.accounts.Account;
import android.accounts.AccountManager;
import android.content.Context;
import android.util.Log;
import com.testerhome.nativeandroid.R;
import com.testerhome.nativeandroid.models.TesterUser;
import com.testerhome.nativeandroid.utils.SharedPreferencesHelper; | package com.testerhome.nativeandroid.auth;
/**
* Created by vclub on 15/10/13.
*/
public class TesterHomeAccountService {
private static TesterHomeAccountService mInstance;
private final String KEY_DEFAULT_ACCOUNT = "defaultAccount";
private final String KEY_USER_DATA_USER_ID = "uer_id";
private final String KEY_USER_DATA_ACCOUNT_NAME = "username";
private final String KEY_USER_DATA_NICKNAME = "nickname";
private final String KEY_USER_DATA_AVATAR = "avatar_url";
private final String KEY_USER_DATA_LOCATION = "location";
private final String KEY_USER_DATA_WEBSITE = "website";
private final String KEY_USER_DATA_GITHUB = "github";
private final String KEY_USER_DATA_EMAIL = "email";
private final String KEY_USER_DATA_TOKEN = "access_token";
private final String KEY_USER_DATA_COMPANY = "company";
private final String KEY_USER_DATA_TAGLINE = "tagline";
private Account activeAccount; | // Path: app/src/main/java/com/testerhome/nativeandroid/models/TesterUser.java
// public class TesterUser {
//
// private String id;
// private String login;
// private String name;
// private String avatar_url;
// private String location;
// private String website;
// private String github;
// private String email;
// private String company;
// private String access_token;
// private String tagline;
//
// public String getTagline() {
// return tagline;
// }
//
// public void setTagline(String tagline) {
// this.tagline = tagline;
// }
//
// public String getCompany() {
// return company;
// }
//
// public void setCompany(String company) {
// this.company = company;
// }
//
// public String getId() {
// return id;
// }
//
// public void setId(String id) {
// this.id = id;
// }
//
// public String getLogin() {
// return login;
// }
//
// public void setLogin(String login) {
// this.login = login;
// }
//
// public String getName() {
// return name;
// }
//
// public void setName(String name) {
// this.name = name;
// }
//
// public String getAvatar_url() {
// return avatar_url;
// }
//
// public void setAvatar_url(String avatar_url) {
// this.avatar_url = avatar_url;
// }
//
// public String getLocation() {
// return location;
// }
//
// public void setLocation(String location) {
// this.location = location;
// }
//
// public String getWebsite() {
// return website;
// }
//
// public void setWebsite(String website) {
// this.website = website;
// }
//
// public String getGithub() {
// return github;
// }
//
// public void setGithub(String github) {
// this.github = github;
// }
//
// public String getEmail() {
// return email;
// }
//
// public void setEmail(String email) {
// this.email = email;
// }
//
// public String getAccess_token() {
// return access_token;
// }
//
// public void setAccess_token(String access_token) {
// this.access_token = access_token;
// }
// }
//
// Path: app/src/main/java/com/testerhome/nativeandroid/utils/SharedPreferencesHelper.java
// public class SharedPreferencesHelper {
//
// private static final String APP_NAME = "com.testerhome.nativeandroid";
// public static SharedPreferencesHelper instance;
// protected Context mContext;
// protected SharedPreferences sharedPreferences;
//
//
// public SharedPreferencesHelper(Context context) {
// mContext = context;
// sharedPreferences = mContext.getSharedPreferences(APP_NAME, 0);
// }
//
// public static synchronized SharedPreferencesHelper getInstance(Context context) {
// if (null == instance)
// instance = new SharedPreferencesHelper(context.getApplicationContext());
// return instance;
// }
//
// public String getValue(String key) {
// return sharedPreferences.getString(key, "");
// }
//
// public Boolean getBoolValue(String key) {
// return sharedPreferences.getBoolean(key, false);
// }
//
// public Boolean getBoolean(String key, boolean defaultValue) {
// return sharedPreferences.getBoolean(key, defaultValue);
// }
//
// public int getIntValue(String key) {
// return sharedPreferences.getInt(key, 0);
// }
//
// public void setValue(String key, Boolean value) {
// SharedPreferences.Editor editor = sharedPreferences.edit();
// editor.putBoolean(key, value);
// editor.apply();
// }
//
// public void setValue(String key, String value) {
// SharedPreferences.Editor editor = sharedPreferences.edit();
// editor.putString(key, value);
// editor.apply();
// }
//
// public void setValue(String key, int value) {
// SharedPreferences.Editor editor = sharedPreferences.edit();
// editor.putInt(key, value);
// editor.apply();
// }
//
// public void remove(String key) {
// SharedPreferences.Editor editor = sharedPreferences.edit();
// editor.remove(key);
// editor.apply();
// }
//
// public void clear() {
// SharedPreferences.Editor editor = sharedPreferences.edit();
// editor.clear();
// editor.apply();
// }
//
// public Set<String> getSaveKeys() {
// return sharedPreferences.getAll().keySet();
// }
// }
// Path: app/src/main/java/com/testerhome/nativeandroid/auth/TesterHomeAccountService.java
import android.accounts.Account;
import android.accounts.AccountManager;
import android.content.Context;
import android.util.Log;
import com.testerhome.nativeandroid.R;
import com.testerhome.nativeandroid.models.TesterUser;
import com.testerhome.nativeandroid.utils.SharedPreferencesHelper;
package com.testerhome.nativeandroid.auth;
/**
* Created by vclub on 15/10/13.
*/
public class TesterHomeAccountService {
private static TesterHomeAccountService mInstance;
private final String KEY_DEFAULT_ACCOUNT = "defaultAccount";
private final String KEY_USER_DATA_USER_ID = "uer_id";
private final String KEY_USER_DATA_ACCOUNT_NAME = "username";
private final String KEY_USER_DATA_NICKNAME = "nickname";
private final String KEY_USER_DATA_AVATAR = "avatar_url";
private final String KEY_USER_DATA_LOCATION = "location";
private final String KEY_USER_DATA_WEBSITE = "website";
private final String KEY_USER_DATA_GITHUB = "github";
private final String KEY_USER_DATA_EMAIL = "email";
private final String KEY_USER_DATA_TOKEN = "access_token";
private final String KEY_USER_DATA_COMPANY = "company";
private final String KEY_USER_DATA_TAGLINE = "tagline";
private Account activeAccount; | private SharedPreferencesHelper spfHelper; |
vclub/A-Native-TesterHome | app/src/main/java/com/testerhome/nativeandroid/auth/TesterHomeAccountService.java | // Path: app/src/main/java/com/testerhome/nativeandroid/models/TesterUser.java
// public class TesterUser {
//
// private String id;
// private String login;
// private String name;
// private String avatar_url;
// private String location;
// private String website;
// private String github;
// private String email;
// private String company;
// private String access_token;
// private String tagline;
//
// public String getTagline() {
// return tagline;
// }
//
// public void setTagline(String tagline) {
// this.tagline = tagline;
// }
//
// public String getCompany() {
// return company;
// }
//
// public void setCompany(String company) {
// this.company = company;
// }
//
// public String getId() {
// return id;
// }
//
// public void setId(String id) {
// this.id = id;
// }
//
// public String getLogin() {
// return login;
// }
//
// public void setLogin(String login) {
// this.login = login;
// }
//
// public String getName() {
// return name;
// }
//
// public void setName(String name) {
// this.name = name;
// }
//
// public String getAvatar_url() {
// return avatar_url;
// }
//
// public void setAvatar_url(String avatar_url) {
// this.avatar_url = avatar_url;
// }
//
// public String getLocation() {
// return location;
// }
//
// public void setLocation(String location) {
// this.location = location;
// }
//
// public String getWebsite() {
// return website;
// }
//
// public void setWebsite(String website) {
// this.website = website;
// }
//
// public String getGithub() {
// return github;
// }
//
// public void setGithub(String github) {
// this.github = github;
// }
//
// public String getEmail() {
// return email;
// }
//
// public void setEmail(String email) {
// this.email = email;
// }
//
// public String getAccess_token() {
// return access_token;
// }
//
// public void setAccess_token(String access_token) {
// this.access_token = access_token;
// }
// }
//
// Path: app/src/main/java/com/testerhome/nativeandroid/utils/SharedPreferencesHelper.java
// public class SharedPreferencesHelper {
//
// private static final String APP_NAME = "com.testerhome.nativeandroid";
// public static SharedPreferencesHelper instance;
// protected Context mContext;
// protected SharedPreferences sharedPreferences;
//
//
// public SharedPreferencesHelper(Context context) {
// mContext = context;
// sharedPreferences = mContext.getSharedPreferences(APP_NAME, 0);
// }
//
// public static synchronized SharedPreferencesHelper getInstance(Context context) {
// if (null == instance)
// instance = new SharedPreferencesHelper(context.getApplicationContext());
// return instance;
// }
//
// public String getValue(String key) {
// return sharedPreferences.getString(key, "");
// }
//
// public Boolean getBoolValue(String key) {
// return sharedPreferences.getBoolean(key, false);
// }
//
// public Boolean getBoolean(String key, boolean defaultValue) {
// return sharedPreferences.getBoolean(key, defaultValue);
// }
//
// public int getIntValue(String key) {
// return sharedPreferences.getInt(key, 0);
// }
//
// public void setValue(String key, Boolean value) {
// SharedPreferences.Editor editor = sharedPreferences.edit();
// editor.putBoolean(key, value);
// editor.apply();
// }
//
// public void setValue(String key, String value) {
// SharedPreferences.Editor editor = sharedPreferences.edit();
// editor.putString(key, value);
// editor.apply();
// }
//
// public void setValue(String key, int value) {
// SharedPreferences.Editor editor = sharedPreferences.edit();
// editor.putInt(key, value);
// editor.apply();
// }
//
// public void remove(String key) {
// SharedPreferences.Editor editor = sharedPreferences.edit();
// editor.remove(key);
// editor.apply();
// }
//
// public void clear() {
// SharedPreferences.Editor editor = sharedPreferences.edit();
// editor.clear();
// editor.apply();
// }
//
// public Set<String> getSaveKeys() {
// return sharedPreferences.getAll().keySet();
// }
// }
| import android.accounts.Account;
import android.accounts.AccountManager;
import android.content.Context;
import android.util.Log;
import com.testerhome.nativeandroid.R;
import com.testerhome.nativeandroid.models.TesterUser;
import com.testerhome.nativeandroid.utils.SharedPreferencesHelper; | private boolean hasDefaultAccount() {
return getDefaultAccount() != null;
}
private Account getDefaultAccount() {
String accountName = spfHelper.getValue(KEY_DEFAULT_ACCOUNT);
return findAccountByUsername(accountName);
}
private void setDefaultAccount(Account defaultAccount) {
spfHelper.setValue(KEY_DEFAULT_ACCOUNT, defaultAccount.name);
boolean foundAccount = false;
Account[] accounts = mAccountManager.getAccounts();
for (int i = 0; i < accounts.length && !foundAccount; i++) {
if (accounts[i].name.equals(defaultAccount.name)) {
foundAccount = true;
}
}
if (!foundAccount) {
// 默认账户被注销了?
}
}
public boolean hasActiveAccount() {
return this.activeAccount != null;
}
| // Path: app/src/main/java/com/testerhome/nativeandroid/models/TesterUser.java
// public class TesterUser {
//
// private String id;
// private String login;
// private String name;
// private String avatar_url;
// private String location;
// private String website;
// private String github;
// private String email;
// private String company;
// private String access_token;
// private String tagline;
//
// public String getTagline() {
// return tagline;
// }
//
// public void setTagline(String tagline) {
// this.tagline = tagline;
// }
//
// public String getCompany() {
// return company;
// }
//
// public void setCompany(String company) {
// this.company = company;
// }
//
// public String getId() {
// return id;
// }
//
// public void setId(String id) {
// this.id = id;
// }
//
// public String getLogin() {
// return login;
// }
//
// public void setLogin(String login) {
// this.login = login;
// }
//
// public String getName() {
// return name;
// }
//
// public void setName(String name) {
// this.name = name;
// }
//
// public String getAvatar_url() {
// return avatar_url;
// }
//
// public void setAvatar_url(String avatar_url) {
// this.avatar_url = avatar_url;
// }
//
// public String getLocation() {
// return location;
// }
//
// public void setLocation(String location) {
// this.location = location;
// }
//
// public String getWebsite() {
// return website;
// }
//
// public void setWebsite(String website) {
// this.website = website;
// }
//
// public String getGithub() {
// return github;
// }
//
// public void setGithub(String github) {
// this.github = github;
// }
//
// public String getEmail() {
// return email;
// }
//
// public void setEmail(String email) {
// this.email = email;
// }
//
// public String getAccess_token() {
// return access_token;
// }
//
// public void setAccess_token(String access_token) {
// this.access_token = access_token;
// }
// }
//
// Path: app/src/main/java/com/testerhome/nativeandroid/utils/SharedPreferencesHelper.java
// public class SharedPreferencesHelper {
//
// private static final String APP_NAME = "com.testerhome.nativeandroid";
// public static SharedPreferencesHelper instance;
// protected Context mContext;
// protected SharedPreferences sharedPreferences;
//
//
// public SharedPreferencesHelper(Context context) {
// mContext = context;
// sharedPreferences = mContext.getSharedPreferences(APP_NAME, 0);
// }
//
// public static synchronized SharedPreferencesHelper getInstance(Context context) {
// if (null == instance)
// instance = new SharedPreferencesHelper(context.getApplicationContext());
// return instance;
// }
//
// public String getValue(String key) {
// return sharedPreferences.getString(key, "");
// }
//
// public Boolean getBoolValue(String key) {
// return sharedPreferences.getBoolean(key, false);
// }
//
// public Boolean getBoolean(String key, boolean defaultValue) {
// return sharedPreferences.getBoolean(key, defaultValue);
// }
//
// public int getIntValue(String key) {
// return sharedPreferences.getInt(key, 0);
// }
//
// public void setValue(String key, Boolean value) {
// SharedPreferences.Editor editor = sharedPreferences.edit();
// editor.putBoolean(key, value);
// editor.apply();
// }
//
// public void setValue(String key, String value) {
// SharedPreferences.Editor editor = sharedPreferences.edit();
// editor.putString(key, value);
// editor.apply();
// }
//
// public void setValue(String key, int value) {
// SharedPreferences.Editor editor = sharedPreferences.edit();
// editor.putInt(key, value);
// editor.apply();
// }
//
// public void remove(String key) {
// SharedPreferences.Editor editor = sharedPreferences.edit();
// editor.remove(key);
// editor.apply();
// }
//
// public void clear() {
// SharedPreferences.Editor editor = sharedPreferences.edit();
// editor.clear();
// editor.apply();
// }
//
// public Set<String> getSaveKeys() {
// return sharedPreferences.getAll().keySet();
// }
// }
// Path: app/src/main/java/com/testerhome/nativeandroid/auth/TesterHomeAccountService.java
import android.accounts.Account;
import android.accounts.AccountManager;
import android.content.Context;
import android.util.Log;
import com.testerhome.nativeandroid.R;
import com.testerhome.nativeandroid.models.TesterUser;
import com.testerhome.nativeandroid.utils.SharedPreferencesHelper;
private boolean hasDefaultAccount() {
return getDefaultAccount() != null;
}
private Account getDefaultAccount() {
String accountName = spfHelper.getValue(KEY_DEFAULT_ACCOUNT);
return findAccountByUsername(accountName);
}
private void setDefaultAccount(Account defaultAccount) {
spfHelper.setValue(KEY_DEFAULT_ACCOUNT, defaultAccount.name);
boolean foundAccount = false;
Account[] accounts = mAccountManager.getAccounts();
for (int i = 0; i < accounts.length && !foundAccount; i++) {
if (accounts[i].name.equals(defaultAccount.name)) {
foundAccount = true;
}
}
if (!foundAccount) {
// 默认账户被注销了?
}
}
public boolean hasActiveAccount() {
return this.activeAccount != null;
}
| public TesterUser getActiveAccountInfo() { |
vclub/A-Native-TesterHome | app/src/main/java/com/testerhome/nativeandroid/fragments/HomeFragment.java | // Path: app/src/main/java/com/testerhome/nativeandroid/Config.java
// public class Config {
//
// // recent - 最新
// // popular - 热门的话题(回帖和喜欢超过一定的数量
// // no_reply - 还没有任何回帖的
// // excellent - 精华帖
// // last_actived - 最近活跃的
//
// public static final String TOPICS_TYPE_RECENT = "recent";
// public static final String TOPICS_TYPE_POPULAR = "popular";
// public static final String TOPICS_TYPE_NO_REPLY = "no_reply";
// public static final String TOPICS_TYPE_EXCELLENT = "excellent";
// public static final String TOPICS_TYPE_LAST_ACTIVED = "last_actived";
// public static final int TOPIC_JOB_NODEID = 19;
// public static final String BASE_URL = "https://testerhome.com/api/v3";
// public static final String TOPICREPLY = "TopicReply";
// public static final String FOLLOW = "Follow";
// public static final String TOPIC = "Topic";
//
// public static String getImageUrl(String imagePath){
// if(!imagePath.contains("https://testerhome.com")){
// return "https://testerhome.com".concat(imagePath);
// }else{
// return imagePath;
// }
//
// }
// }
| import android.os.Bundle;
import android.support.design.widget.TabLayout;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentPagerAdapter;
import android.support.v4.view.ViewPager;
import com.testerhome.nativeandroid.Config;
import com.testerhome.nativeandroid.R;
import butterknife.Bind; | package com.testerhome.nativeandroid.fragments;
/**
* Created by vclub on 15/9/15.
*/
public class HomeFragment extends BaseFragment {
@Bind(R.id.tl_topics)
TabLayout tabLayoutTopicsTab;
@Bind(R.id.vp_topics)
ViewPager viewPagerTopics;
private TopicViewPagerAdapter mAdapter;
@Override
protected int getLayoutRes() {
return R.layout.fragment_home;
}
@Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
setupView();
}
private void setupView(){
mAdapter = new TopicViewPagerAdapter(getActivity().getSupportFragmentManager());
viewPagerTopics.setAdapter(mAdapter);
tabLayoutTopicsTab.setupWithViewPager(viewPagerTopics);
tabLayoutTopicsTab.setTabsFromPagerAdapter(mAdapter);
}
public class TopicViewPagerAdapter extends FragmentPagerAdapter {
private String[] typeName = {"最新","最热","沙发","精华"}; | // Path: app/src/main/java/com/testerhome/nativeandroid/Config.java
// public class Config {
//
// // recent - 最新
// // popular - 热门的话题(回帖和喜欢超过一定的数量
// // no_reply - 还没有任何回帖的
// // excellent - 精华帖
// // last_actived - 最近活跃的
//
// public static final String TOPICS_TYPE_RECENT = "recent";
// public static final String TOPICS_TYPE_POPULAR = "popular";
// public static final String TOPICS_TYPE_NO_REPLY = "no_reply";
// public static final String TOPICS_TYPE_EXCELLENT = "excellent";
// public static final String TOPICS_TYPE_LAST_ACTIVED = "last_actived";
// public static final int TOPIC_JOB_NODEID = 19;
// public static final String BASE_URL = "https://testerhome.com/api/v3";
// public static final String TOPICREPLY = "TopicReply";
// public static final String FOLLOW = "Follow";
// public static final String TOPIC = "Topic";
//
// public static String getImageUrl(String imagePath){
// if(!imagePath.contains("https://testerhome.com")){
// return "https://testerhome.com".concat(imagePath);
// }else{
// return imagePath;
// }
//
// }
// }
// Path: app/src/main/java/com/testerhome/nativeandroid/fragments/HomeFragment.java
import android.os.Bundle;
import android.support.design.widget.TabLayout;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentPagerAdapter;
import android.support.v4.view.ViewPager;
import com.testerhome.nativeandroid.Config;
import com.testerhome.nativeandroid.R;
import butterknife.Bind;
package com.testerhome.nativeandroid.fragments;
/**
* Created by vclub on 15/9/15.
*/
public class HomeFragment extends BaseFragment {
@Bind(R.id.tl_topics)
TabLayout tabLayoutTopicsTab;
@Bind(R.id.vp_topics)
ViewPager viewPagerTopics;
private TopicViewPagerAdapter mAdapter;
@Override
protected int getLayoutRes() {
return R.layout.fragment_home;
}
@Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
setupView();
}
private void setupView(){
mAdapter = new TopicViewPagerAdapter(getActivity().getSupportFragmentManager());
viewPagerTopics.setAdapter(mAdapter);
tabLayoutTopicsTab.setupWithViewPager(viewPagerTopics);
tabLayoutTopicsTab.setTabsFromPagerAdapter(mAdapter);
}
public class TopicViewPagerAdapter extends FragmentPagerAdapter {
private String[] typeName = {"最新","最热","沙发","精华"}; | private String[] typeValue = {Config.TOPICS_TYPE_RECENT, |
vclub/A-Native-TesterHome | app/src/main/java/com/testerhome/nativeandroid/views/base/BaseActivity.java | // Path: app/src/main/java/com/testerhome/nativeandroid/application/NativeApp.java
// public class NativeApp extends Application {
//
// public static RefWatcher getRefWatcher(Context context) {
// NativeApp application = (NativeApp) context.getApplicationContext();
// return application.refWatcher;
// }
//
// private RefWatcher refWatcher;
//
// @Override public void onCreate() {
// super.onCreate();
// refWatcher = LeakCanary.install(this);
//
// // initialize fresco with OK HTTP
// ImagePipelineConfig config = OkHttpImagePipelineConfigFactory
// .newBuilder(this, new OkHttpClient())
// .build();
// Fresco.initialize(this, config);
// }
// }
| import android.support.annotation.Nullable;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.widget.TextView;
import com.squareup.leakcanary.RefWatcher;
import com.testerhome.nativeandroid.R;
import com.testerhome.nativeandroid.application.NativeApp;
import butterknife.Bind;
import butterknife.ButterKnife; | package com.testerhome.nativeandroid.views.base;
/**
* Created by vclub on 15/9/15.
*/
public class BaseActivity extends AppCompatActivity {
@Nullable
@Bind(R.id.toolbar)
protected
Toolbar toolbar;
@Nullable
@Bind(R.id.toolbar_title)
TextView customTitle;
@Override
public void setContentView(int layoutResID) {
super.setContentView(layoutResID);
ButterKnife.bind(this);
setupToolbar();
}
protected void setupToolbar(){
if (toolbar != null){
setSupportActionBar(toolbar);
}
}
public void setCustomTitle(String title){
if (customTitle != null){
customTitle.setText(title);
}
}
@Override
protected void onDestroy() {
super.onDestroy();
ButterKnife.unbind(this);
| // Path: app/src/main/java/com/testerhome/nativeandroid/application/NativeApp.java
// public class NativeApp extends Application {
//
// public static RefWatcher getRefWatcher(Context context) {
// NativeApp application = (NativeApp) context.getApplicationContext();
// return application.refWatcher;
// }
//
// private RefWatcher refWatcher;
//
// @Override public void onCreate() {
// super.onCreate();
// refWatcher = LeakCanary.install(this);
//
// // initialize fresco with OK HTTP
// ImagePipelineConfig config = OkHttpImagePipelineConfigFactory
// .newBuilder(this, new OkHttpClient())
// .build();
// Fresco.initialize(this, config);
// }
// }
// Path: app/src/main/java/com/testerhome/nativeandroid/views/base/BaseActivity.java
import android.support.annotation.Nullable;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.widget.TextView;
import com.squareup.leakcanary.RefWatcher;
import com.testerhome.nativeandroid.R;
import com.testerhome.nativeandroid.application.NativeApp;
import butterknife.Bind;
import butterknife.ButterKnife;
package com.testerhome.nativeandroid.views.base;
/**
* Created by vclub on 15/9/15.
*/
public class BaseActivity extends AppCompatActivity {
@Nullable
@Bind(R.id.toolbar)
protected
Toolbar toolbar;
@Nullable
@Bind(R.id.toolbar_title)
TextView customTitle;
@Override
public void setContentView(int layoutResID) {
super.setContentView(layoutResID);
ButterKnife.bind(this);
setupToolbar();
}
protected void setupToolbar(){
if (toolbar != null){
setSupportActionBar(toolbar);
}
}
public void setCustomTitle(String title){
if (customTitle != null){
customTitle.setText(title);
}
}
@Override
protected void onDestroy() {
super.onDestroy();
ButterKnife.unbind(this);
| RefWatcher refWatcher = NativeApp.getRefWatcher(this); |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.